def _check_new_format(self, node, func):

<EOL>if isinstance(node.func, astroid.Attribute) and not isinstance(<EOL>node.func.expr, astroid.Const<EOL>):<EOL><INDENT>return<EOL><DEDENT>if node.starargs or node.kwargs:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>strnode = next(func.bound.infer())<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>return<EOL><DEDENT>if not (isinstance(strnode, astroid.Const) and isinstance(strnode.value, str)):<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>call_site = CallSite.from_call(node)<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>fields, num_args, manual_pos = utils.parse_format_method_string(<EOL>strnode.value<EOL>)<EOL><DEDENT>except utils.IncompleteFormatString:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL>return<EOL><DEDENT>positional_arguments = call_site.positional_arguments<EOL>named_arguments = call_site.keyword_arguments<EOL>named_fields = {field[<NUM_LIT:0>] for field in fields if isinstance(field[<NUM_LIT:0>], str)}<EOL>if num_args and manual_pos:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL>return<EOL><DEDENT>check_args = False<EOL>num_args += sum(<NUM_LIT:1> for field in named_fields if field == "<STR_LIT>")<EOL>if named_fields:<EOL><INDENT>for field in named_fields:<EOL><INDENT>if field and field not in named_arguments:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", node=node, args=(field,)<EOL>)<EOL><DEDENT><DEDENT>for field in named_arguments:<EOL><INDENT>if field not in named_fields:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", node=node, args=(field,)<EOL>)<EOL><DEDENT><DEDENT>num_args = num_args or manual_pos<EOL>if positional_arguments or num_args:<EOL><INDENT>empty = any(True for field in named_fields if field == "<STR_LIT>")<EOL>if named_arguments or empty:<EOL><INDENT>check_args = True<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>check_args = True<EOL><DEDENT>if check_args:<EOL><INDENT>num_args = num_args or manual_pos<EOL>if len(positional_arguments) > num_args:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>elif len(positional_arguments) < num_args:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT><DEDENT>self._detect_vacuous_formatting(node, positional_arguments)<EOL>self._check_new_format_specifiers(node, fields, named_arguments)<EOL>


check if the node has a right sibling (if so, that's some unreachable
        code)


def _check_in_loop(self, node, node_name):

_node = node.parent<EOL>while _node:<EOL><INDENT>if isinstance(_node, (astroid.For, astroid.While)):<EOL><INDENT>if node not in _node.orelse:<EOL><INDENT>return<EOL><DEDENT><DEDENT>if isinstance(_node, (astroid.ClassDef, astroid.FunctionDef)):<EOL><INDENT>break<EOL><DEDENT>if (<EOL>isinstance(_node, astroid.TryFinally)<EOL>and node in _node.finalbody<EOL>and isinstance(node, astroid.Continue)<EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>_node = _node.parent<EOL><DEDENT>self.add_message("<STR_LIT>", node=node, args=node_name)<EOL>

check that a node is inside a for or while loop


<EOL>if node.args.defaults:<EOL><INDENT>return<EOL><DEDENT>call = node.body<EOL>if not isinstance(call, astroid.Call):<EOL><INDENT>return<EOL><DEDENT>if isinstance(node.body.func, astroid.Attribute) and isinstance(<EOL>node.body.func.expr, astroid.Call<EOL>):<EOL><INDENT>return<EOL><DEDENT>call_site = CallSite.from_call(call)<EOL>ordinary_args = list(node.args.args)<EOL>new_call_args = list(self._filter_vararg(node, call.args))<EOL>if node.args.kwarg:<EOL><INDENT>if self._has_variadic_argument(call.kwargs, node.args.kwarg):<EOL><INDENT>return<EOL><DEDENT><DEDENT>if node.args.vararg:<EOL><INDENT>if self._has_variadic_argument(call.starargs, node.args.vararg):<EOL><INDENT>return<EOL><DEDENT><DEDENT>elif call.starargs:<EOL><INDENT>return<EOL><DEDENT>if call.keywords:<EOL><INDENT>lambda_kwargs = {keyword.name for keyword in node.args.defaults}<EOL>if len(lambda_kwargs) != len(call_site.keyword_arguments):<EOL><INDENT>return<EOL><DEDENT>if set(call_site.keyword_arguments).difference(lambda_kwargs):<EOL><INDENT>return<EOL><DEDENT><DEDENT>if len(ordinary_args) != len(new_call_args):<EOL><INDENT>return<EOL><DEDENT>for arg, passed_arg in zip(ordinary_args, new_call_args):<EOL><INDENT>if not isinstance(passed_arg, astroid.Name):<EOL><INDENT>return<EOL><DEDENT>if arg.name != passed_arg.name:<EOL><INDENT>return<EOL><DEDENT><DEDENT>self.add_message("<STR_LIT>", line=node.fromlineno, node=node)<EOL>

check whether or not the lambda is suspicious


keys = set()<EOL>for k, _ in node.items:<EOL><INDENT>if isinstance(k, astroid.Const):<EOL><INDENT>key = k.value<EOL>if key in keys:<EOL><INDENT>self.add_message("<STR_LIT>", node=node, args=key)<EOL><DEDENT>keys.add(key)<EOL><DEDENT><DEDENT>


required method to auto register this checker


loop_nodes = (astroid.For, astroid.While)<EOL>parent = break_node.parent<EOL>while not isinstance(parent, loop_nodes) or break_node in getattr(<EOL>parent, "<STR_LIT>", []<EOL>):<EOL><INDENT>break_node = parent<EOL>parent = parent.parent<EOL>if parent is None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return parent<EOL>

Returns the loop node that holds the break node in arguments.

Args:
    break_node (astroid.Break): the break node of interest.

Returns:
    astroid.For or astroid.While: the loop node holding the break node.


self.stats["<STR_LIT>"] += <NUM_LIT:1><EOL>

check module name, docstring and required arguments


@utils.check_messages("<STR_LIT>", "<STR_LIT>")<EOL><INDENT>def visit_return(self, node):<DEDENT>

self._check_unreachable(node)<EOL>self._check_not_in_finally(node, "<STR_LIT>", (astroid.FunctionDef,))<EOL>

1 - check is the node has a right sibling (if so, that's some
        unreachable code)
        2 - check is the node is inside the finally clause of a try...finally
        block


property_classes, property_names = _get_properties(config)<EOL>if not node.is_method():<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>if node.decorators:<EOL><INDENT>decorators = node.decorators.nodes<EOL><DEDENT>else:<EOL><INDENT>decorators = []<EOL><DEDENT>for decorator in decorators:<EOL><INDENT>if isinstance(decorator, astroid.Name) or (<EOL>isinstance(decorator, astroid.Attribute)<EOL>and decorator.attrname in property_names<EOL>):<EOL><INDENT>infered = utils.safe_infer(decorator)<EOL>if infered and infered.qname() in property_classes:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT><DEDENT>elif isinstance(decorator, astroid.Attribute) and decorator.attrname in (<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>):<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT><DEDENT>return "<STR_LIT>"<EOL>

Determine the name type whose regex the a function's name should match.

    :param node: A function node.
    :type node: astroid.node_classes.NodeNG
    :param config: Configuration from which to pull additional property classes.
    :type config: :class:`optparse.Values`

    :returns: One of ('function', 'method', 'attr')
    :rtype: str


def same_scope(current):<EOL><INDENT>return current.scope() is node<EOL><DEDENT>from_iter = itertools.chain.from_iterable<EOL>nonlocals = set(<EOL>from_iter(<EOL>child.names<EOL>for child in node.nodes_of_class(astroid.Nonlocal)<EOL>if same_scope(child)<EOL>)<EOL>)<EOL>if not nonlocals:<EOL><INDENT>return<EOL><DEDENT>global_vars = set(<EOL>from_iter(<EOL>child.names<EOL>for child in node.nodes_of_class(astroid.Global)<EOL>if same_scope(child)<EOL>)<EOL>)<EOL>for name in nonlocals.intersection(global_vars):<EOL><INDENT>self.add_message("<STR_LIT>", args=(name,), node=node)<EOL><DEDENT>

Check that a name is both nonlocal and global.


try:<EOL><INDENT>argument = utils.safe_infer(utils.get_argument_from_call(node, position=<NUM_LIT:0>))<EOL><DEDENT>except utils.NoSuchArgumentError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if argument is astroid.Uninferable:<EOL><INDENT>return<EOL><DEDENT>if argument is None:<EOL><INDENT>if isinstance(node.args[<NUM_LIT:0>], astroid.Call):<EOL><INDENT>try:<EOL><INDENT>func = next(node.args[<NUM_LIT:0>].func.infer())<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>return<EOL><DEDENT>if getattr(<EOL>func, "<STR_LIT:name>", None<EOL>) == "<STR_LIT>" and utils.is_builtin_object(func):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT><DEDENT>return<EOL><DEDENT>if isinstance(argument, (astroid.List, astroid.Tuple)):<EOL><INDENT>return<EOL><DEDENT>if isinstance(argument, astroid.Instance):<EOL><INDENT>if argument._proxied.name == "<STR_LIT>" and utils.is_builtin_object(<EOL>argument._proxied<EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL>return<EOL><DEDENT>if any(<EOL>ancestor.name == "<STR_LIT>" and utils.is_builtin_object(ancestor)<EOL>for ancestor in argument._proxied.ancestors()<EOL>):<EOL><INDENT>try:<EOL><INDENT>argument.locals[REVERSED_PROTOCOL_METHOD]<EOL><DEDENT>except KeyError:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>return<EOL><DEDENT><DEDENT>if hasattr(argument, "<STR_LIT>"):<EOL><INDENT>for methods in REVERSED_METHODS:<EOL><INDENT>for meth in methods:<EOL><INDENT>try:<EOL><INDENT>argument.getattr(meth)<EOL><DEDENT>except astroid.NotFoundError:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT><DEDENT>

check that the argument to `reversed` is a sequence


if (<EOL>node.fail is None<EOL>and isinstance(node.test, astroid.Tuple)<EOL>and len(node.test.elts) == <NUM_LIT:2><EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>

check the use of an assert statement on a tuple.


def _check_type_x_is_y(self, node, left, operator, right):

left_func = utils.safe_infer(left.func)<EOL>if not (<EOL>isinstance(left_func, astroid.ClassDef) and left_func.qname() == TYPE_QNAME<EOL>):<EOL><INDENT>return<EOL><DEDENT>if operator in ("<STR_LIT>", "<STR_LIT>") and _is_one_arg_pos_call(right):<EOL><INDENT>right_func = utils.safe_infer(right.func)<EOL>if (<EOL>isinstance(right_func, astroid.ClassDef)<EOL>and right_func.qname() == TYPE_QNAME<EOL>):<EOL><INDENT>right_arg = utils.safe_infer(right.args[<NUM_LIT:0>])<EOL>if not isinstance(right_arg, LITERAL_NODE_TYPES):<EOL><INDENT>return<EOL><DEDENT><DEDENT><DEDENT>self.add_message("<STR_LIT>", node=node)<EOL>

Check for expressions like type(x) == Y.


try:<EOL><INDENT>for inferred in node.func.infer():<EOL><INDENT>self._check_inferred_class_is_abstract(inferred, node)<EOL><DEDENT><DEDENT>except astroid.InferenceError:<EOL><INDENT>return<EOL><DEDENT>

Check instantiating abstract class with
        abc.ABCMeta as metaclass.


unreach_stmt = node.next_sibling()<EOL>if unreach_stmt is not None:<EOL><INDENT>self.add_message("<STR_LIT>", node=unreach_stmt)<EOL><DEDENT>


def _check_name(self, node_type, name, node, confidence=interfaces.HIGH):

def _should_exempt_from_invalid_name(node):<EOL><INDENT>if node_type == "<STR_LIT>":<EOL><INDENT>inferred = utils.safe_infer(node)<EOL>if isinstance(inferred, astroid.ClassDef):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL><DEDENT>if utils.is_inside_except(node):<EOL><INDENT>clobbering, _ = utils.clobber_in_except(node)<EOL>if clobbering:<EOL><INDENT>return<EOL><DEDENT><DEDENT>if name in self.config.good_names:<EOL><INDENT>return<EOL><DEDENT>if name in self.config.bad_names:<EOL><INDENT>self.stats["<STR_LIT>" + node_type] += <NUM_LIT:1><EOL>self.add_message("<STR_LIT>", node=node, args=name)<EOL>return<EOL><DEDENT>regexp = self._name_regexps[node_type]<EOL>match = regexp.match(name)<EOL>if _is_multi_naming_match(match, node_type, confidence):<EOL><INDENT>name_group = self._find_name_group(node_type)<EOL>bad_name_group = self._bad_names.setdefault(name_group, {})<EOL>warnings = bad_name_group.setdefault(match.lastgroup, [])<EOL>warnings.append((node, node_type, name, confidence))<EOL><DEDENT>if match is None and not _should_exempt_from_invalid_name(node):<EOL><INDENT>self._raise_name_warning(node, node_type, name, confidence)<EOL><DEDENT>

check for a name using the type's regexp


if original.args is None or overridden.args is None:<EOL><INDENT>return False<EOL><DEDENT>all_args = chain(original.args, original.kwonlyargs)<EOL>original_param_names = [param.name for param in all_args]<EOL>default_missing = object()<EOL>for param_name in original_param_names:<EOL><INDENT>try:<EOL><INDENT>original_default = original.default_value(param_name)<EOL><DEDENT>except astroid.exceptions.NoDefault:<EOL><INDENT>original_default = default_missing<EOL><DEDENT>try:<EOL><INDENT>overridden_default = overridden.default_value(param_name)<EOL><DEDENT>except astroid.exceptions.NoDefault:<EOL><INDENT>overridden_default = default_missing<EOL><DEDENT>default_list = [<EOL>arg == default_missing for arg in (original_default, overridden_default)<EOL>]<EOL>if any(default_list) and not all(default_list):<EOL><INDENT>return True<EOL><DEDENT>astroid_type_compared_attr = {<EOL>astroid.Const: "<STR_LIT:value>",<EOL>astroid.ClassDef: "<STR_LIT:name>",<EOL>astroid.Tuple: "<STR_LIT>",<EOL>astroid.List: "<STR_LIT>",<EOL>}<EOL>handled_types = tuple(<EOL>astroid_type for astroid_type in astroid_type_compared_attr<EOL>)<EOL>original_type = _get_node_type(original_default, handled_types)<EOL>if original_type:<EOL><INDENT>if not isinstance(overridden_default, original_type):<EOL><INDENT>return True<EOL><DEDENT>if not _check_arg_equality(<EOL>original_default,<EOL>overridden_default,<EOL>astroid_type_compared_attr[original_type],<EOL>):<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return False<EOL>

Check if original and overridden methods arguments have different default values

Return True if one of the overridden arguments has a default
value different from the default value of the original argument
If one of the method doesn't have argument (.args is None)
return False


def _different_parameters(original, overridden, dummy_parameter_regex):

original_parameters = _positional_parameters(original)<EOL>overridden_parameters = _positional_parameters(overridden)<EOL>different_positional = _has_different_parameters(<EOL>original_parameters, overridden_parameters, dummy_parameter_regex<EOL>)<EOL>different_kwonly = _has_different_parameters(<EOL>original.args.kwonlyargs, overridden.args.kwonlyargs, dummy_parameter_regex<EOL>)<EOL>if original.name in PYMETHODS:<EOL><INDENT>different_positional = different_kwonly = False<EOL><DEDENT>different_kwarg = (<EOL>sum(<NUM_LIT:1> for param in (original.args.kwarg, overridden.args.kwarg) if not param)<EOL>== <NUM_LIT:1><EOL>)<EOL>different_vararg = (<EOL>sum(<NUM_LIT:1> for param in (original.args.vararg, overridden.args.vararg) if not param)<EOL>== <NUM_LIT:1><EOL>)<EOL>return any(<EOL>(different_positional, different_kwarg, different_vararg, different_kwonly)<EOL>)<EOL>

Determine if the two methods have different parameters

    They are considered to have different parameters if:

       * they have different positional parameters, including different names

       * one of the methods is having variadics, while the other is not

       * they have different keyword only parameters.


for potential_type in potential_types:<EOL><INDENT>if isinstance(node, potential_type):<EOL><INDENT>return potential_type<EOL><DEDENT><DEDENT>return None<EOL>

Return the type of the node if it exists in potential_types.

Args:
    node (astroid.node): node to get the type of.
    potential_types (tuple): potential types of the node.

Returns:
    type: type of the node or None.


try:<EOL><INDENT>node.mro()<EOL><DEDENT>except InconsistentMroError:<EOL><INDENT>self.add_message("<STR_LIT>", args=node.name, node=node)<EOL><DEDENT>except DuplicateBasesError:<EOL><INDENT>self.add_message("<STR_LIT>", args=node.name, node=node)<EOL><DEDENT>except NotImplementedError:<EOL><INDENT>pass<EOL><DEDENT>

Detect that a class has a consistent mro or duplicate bases.


frame = node_frame_class(node)<EOL>if frame is None:<EOL><INDENT>return<EOL><DEDENT>self._scopes[frame][node.attrname].append(node)<EOL>


for base in node.bases:<EOL><INDENT>ancestor = safe_infer(base)<EOL>if ancestor in (astroid.Uninferable, None):<EOL><INDENT>continue<EOL><DEDENT>if isinstance(ancestor, astroid.Instance) and ancestor.is_subtype_of(<EOL>"<STR_LIT>" % (BUILTINS,)<EOL>):<EOL><INDENT>continue<EOL><DEDENT>if not isinstance(ancestor, astroid.ClassDef) or _is_invalid_base_class(<EOL>ancestor<EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", args=base.as_string(), node=node)<EOL><DEDENT>if ancestor.name == object.__name__:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", args=node.name, node=node<EOL>)<EOL><DEDENT><DEDENT>

Detect that a class inherits something which is not
a class or a type.


if node.is_method():<EOL><INDENT>if node.args.args is not None:<EOL><INDENT>self._first_attrs.pop()<EOL><DEDENT>if not self.linter.is_message_enabled("<STR_LIT>"):<EOL><INDENT>return<EOL><DEDENT>class_node = node.parent.frame()<EOL>if (<EOL>self._meth_could_be_func<EOL>and node.type == "<STR_LIT>"<EOL>and node.name not in PYMETHODS<EOL>and not (<EOL>node.is_abstract()<EOL>or overrides_a_method(class_node, node.name)<EOL>or decorated_with_property(node)<EOL>or _has_bare_super_call(node)<EOL>)<EOL>):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT><DEDENT>

on method node, check if this method couldn't be a function

        ignore class, static and abstract methods, initializer,
        methods overridden from a parent class.


return self._scopes.get(scope, {})<EOL>

Get the accessed variables for the given scope.


attrname = node.attrname<EOL>if (<EOL>is_attr_protected(attrname)<EOL>and attrname not in self.config.exclude_protected<EOL>):<EOL><INDENT>klass = node_frame_class(node)<EOL>callee = node.expr.as_string()<EOL>if klass is None:<EOL><INDENT>self.add_message("<STR_LIT>", node=node, args=attrname)<EOL>return<EOL><DEDENT>if (<EOL>isinstance(node.expr, astroid.Call)<EOL>and isinstance(node.expr.func, astroid.Name)<EOL>and node.expr.func.name == "<STR_LIT>"<EOL>):<EOL><INDENT>return<EOL><DEDENT>if self._is_type_self_call(node.expr):<EOL><INDENT>return<EOL><DEDENT>if not (callee == klass.name or callee in klass.basenames):<EOL><INDENT>stmt = node.parent.statement()<EOL>if (<EOL>isinstance(stmt, astroid.Assign)<EOL>and len(stmt.targets) == <NUM_LIT:1><EOL>and isinstance(stmt.targets[<NUM_LIT:0>], astroid.AssignName)<EOL>):<EOL><INDENT>name = stmt.targets[<NUM_LIT:0>].name<EOL>if _is_attribute_property(name, klass):<EOL><INDENT>return<EOL><DEDENT><DEDENT>self.add_message("<STR_LIT>", node=node, args=attrname)<EOL><DEDENT><DEDENT>

Given an attribute access node (set or get), check if attribute
        access is legitimate. Call _check_first_attr with node before calling
        this method. Valid cases are:
        * self._attr in a method or cls._attr in a classmethod. Checked by
        _check_first_attr.
        * Klass._attr inside "Klass" class.
        * Klass2._attr inside "Klass" class when Klass2 is a base class of
            Klass.


def _check_arg_equality(node_a, node_b, attr_name):

return getattr(node_a, attr_name) == getattr(node_b, attr_name)<EOL>

Check equality of nodes based on the comparison of their attributes named attr_name.

Args:
    node_a (astroid.node): first node to compare.
    node_b (astroid.node): second node to compare.
    attr_name (str): name of the nodes attribute to use for comparison.

Returns:
    bool: True if node_a.attr_name == node_b.attr_name, False otherwise.


to_call = {}<EOL>for base_node in klass_node.ancestors(recurs=False):<EOL><INDENT>try:<EOL><INDENT>to_call[base_node] = next(base_node.igetattr(method))<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>return to_call<EOL>

return a dictionary where keys are the list of base classes providing
    the queried method, and so that should/may be called from the method node


if self._first_attrs and (<EOL>node.name == self._first_attrs[-<NUM_LIT:1>] or not self._first_attrs[-<NUM_LIT:1>]<EOL>):<EOL><INDENT>self._meth_could_be_func = False<EOL><DEDENT>

check if the name handle an access to a class member
        if so, register it


if definition.kwargs:<EOL><INDENT>same_kw_variadics = definition.kwargs in call.starred_kws<EOL><DEDENT>else:<EOL><INDENT>same_kw_variadics = not call.starred_kws<EOL><DEDENT>if definition.varargs:<EOL><INDENT>same_args_variadics = definition.varargs in call.starred_args<EOL><DEDENT>else:<EOL><INDENT>same_args_variadics = not call.starred_args<EOL><DEDENT>same_kwonlyargs = all(kw in call.kws for kw in definition.kwonlyargs)<EOL>same_args = definition.args == call.args<EOL>no_additional_kwarg_arguments = True<EOL>if call.kws:<EOL><INDENT>for keyword in call.kws:<EOL><INDENT>is_arg = keyword in call.args<EOL>is_kwonly = keyword in definition.kwonlyargs<EOL>if not is_arg and not is_kwonly:<EOL><INDENT>no_additional_kwarg_arguments = False<EOL>break<EOL><DEDENT><DEDENT><DEDENT>return all(<EOL>(<EOL>same_args,<EOL>same_kwonlyargs,<EOL>same_args_variadics,<EOL>same_kw_variadics,<EOL>no_additional_kwarg_arguments,<EOL>)<EOL>)<EOL>

Check if a definition signature is equivalent to a call.


def _called_in_methods(func, klass, methods):

if not isinstance(func, astroid.FunctionDef):<EOL><INDENT>return False<EOL><DEDENT>for method in methods:<EOL><INDENT>try:<EOL><INDENT>infered = klass.getattr(method)<EOL><DEDENT>except astroid.NotFoundError:<EOL><INDENT>continue<EOL><DEDENT>for infer_method in infered:<EOL><INDENT>for call in infer_method.nodes_of_class(astroid.Call):<EOL><INDENT>try:<EOL><INDENT>bound = next(call.func.infer())<EOL><DEDENT>except (astroid.InferenceError, StopIteration):<EOL><INDENT>continue<EOL><DEDENT>if not isinstance(bound, astroid.BoundMethod):<EOL><INDENT>continue<EOL><DEDENT>func_obj = bound._proxied<EOL>if isinstance(func_obj, astroid.UnboundMethod):<EOL><INDENT>func_obj = func_obj._proxied<EOL><DEDENT>if func_obj.name == func.name:<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return False<EOL>

Check if the func was called in any of the given methods,
    belonging to the *klass*. Returns True if so, False otherwise.


def _continuation_inside_bracket(self, bracket, position):

indentation = self._tokens.line_indent(position)<EOL>token_indent = self._tokens.token_indent(position)<EOL>next_token_indent = self._tokens.token_indent(position + <NUM_LIT:1>)<EOL>if (<EOL>self._is_block_opener<EOL>and next_token_indent == indentation + self._block_indent_string<EOL>):<EOL><INDENT>return _ContinuedIndent(<EOL>CONTINUED_BLOCK,<EOL>bracket,<EOL>position,<EOL>_Indentations(token_indent),<EOL>_BeforeBlockIndentations(<EOL>next_token_indent, next_token_indent + self._continuation_string<EOL>),<EOL>)<EOL><DEDENT>return _ContinuedIndent(<EOL>CONTINUED,<EOL>bracket,<EOL>position,<EOL>_Indentations(token_indent, next_token_indent),<EOL>_Indentations(next_token_indent),<EOL>)<EOL>

Extracts indentation information for a continued indent.


result = "<STR_LIT>"<EOL>for char in line:<EOL><INDENT>if char in "<STR_LIT>":<EOL><INDENT>result += char<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return result<EOL>

Return the indention string of the given line.


self.next_physical_line()<EOL>self.retained_warnings = []<EOL>self._cont_stack = []<EOL>

Prepares the tracker for a new logical line (NEWLINE).

        A new logical line only starts with block indentation.


return _get_indent_string(self.line(idx))<EOL>

Get the string of TABs and Spaces used for indentation of the line of this token


def _has_valid_type_annotation(self, tokens, i):

if not self._inside_brackets("<STR_LIT:(>"):<EOL><INDENT>return False<EOL><DEDENT>bracket_level = <NUM_LIT:0><EOL>for token in tokens[i - <NUM_LIT:1> :: -<NUM_LIT:1>]:<EOL><INDENT>if token[<NUM_LIT:1>] == "<STR_LIT::>":<EOL><INDENT>return True<EOL><DEDENT>if token[<NUM_LIT:1>] == "<STR_LIT:(>":<EOL><INDENT>return False<EOL><DEDENT>if token[<NUM_LIT:1>] == "<STR_LIT:]>":<EOL><INDENT>bracket_level += <NUM_LIT:1><EOL><DEDENT>elif token[<NUM_LIT:1>] == "<STR_LIT:[>":<EOL><INDENT>bracket_level -= <NUM_LIT:1><EOL><DEDENT>elif token[<NUM_LIT:1>] == "<STR_LIT:U+002C>":<EOL><INDENT>if not bracket_level:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>elif token[<NUM_LIT:1>] in ("<STR_LIT:.>", "<STR_LIT>"):<EOL><INDENT>continue<EOL><DEDENT>elif token[<NUM_LIT:0>] not in (tokenize.NAME, tokenize.STRING, tokenize.NL):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return False<EOL>

Extended check of PEP-484 type hint presence


def _check_equals_spacing(self, tokens, i):

if self._has_valid_type_annotation(tokens, i):<EOL><INDENT>self._check_space(tokens, i, (_MUST, _MUST))<EOL><DEDENT>elif self._inside_brackets("<STR_LIT:(>") or self._inside_brackets("<STR_LIT>"):<EOL><INDENT>self._check_space(tokens, i, (_MUST_NOT, _MUST_NOT))<EOL><DEDENT>else:<EOL><INDENT>self._check_space(tokens, i, (_MUST, _MUST))<EOL><DEDENT>

Check the spacing of a single equals sign.


<EOL>stack_top = -<NUM_LIT:1><EOL>if (<EOL>self._tokens.token(idx) in ("<STR_LIT:}>", "<STR_LIT>")<EOL>and self._cont_stack[-<NUM_LIT:1>].token == "<STR_LIT::>"<EOL>):<EOL><INDENT>stack_top = -<NUM_LIT:2><EOL><DEDENT>indent = self._cont_stack[stack_top]<EOL>if self._tokens.token(idx) in _CLOSING_BRACKETS:<EOL><INDENT>valid_indentations = indent.valid_outdent_strings<EOL><DEDENT>else:<EOL><INDENT>valid_indentations = indent.valid_continuation_strings<EOL><DEDENT>return indent, valid_indentations.copy()<EOL>

Returns the valid offsets for the token at the given position.


def set_option(self, optname, value, action=None, optdict=None):

BaseChecker.set_option(self, optname, value, action, optdict)<EOL>if optname == "<STR_LIT>":<EOL><INDENT>self.min_lines = self.config.min_similarity_lines<EOL><DEDENT>elif optname == "<STR_LIT>":<EOL><INDENT>self.ignore_comments = self.config.ignore_comments<EOL><DEDENT>elif optname == "<STR_LIT>":<EOL><INDENT>self.ignore_docstrings = self.config.ignore_docstrings<EOL><DEDENT>elif optname == "<STR_LIT>":<EOL><INDENT>self.ignore_imports = self.config.ignore_imports<EOL><DEDENT>

method called to set an option (registered in the options list)

        overridden to report options setting to Similar


with node.stream() as stream:<EOL><INDENT>self.append_stream(self.linter.current_name, stream, node.file_encoding)<EOL><DEDENT>

process a module

        the module's content is accessible via the stream object

        stream must implement the readlines method


total = sum(len(lineset) for lineset in self.linesets)<EOL>duplicated = <NUM_LIT:0><EOL>stats = self.stats<EOL>for num, couples in self._compute_sims():<EOL><INDENT>msg = []<EOL>for lineset, idx in couples:<EOL><INDENT>msg.append("<STR_LIT>" % (lineset.name, idx))<EOL><DEDENT>msg.sort()<EOL>for line in lineset._real_lines[idx : idx + num]:<EOL><INDENT>msg.append(line.rstrip())<EOL><DEDENT>self.add_message("<STR_LIT>", args=(len(couples), "<STR_LIT:\n>".join(msg)))<EOL>duplicated += num * (len(couples) - <NUM_LIT:1>)<EOL><DEDENT>stats["<STR_LIT>"] = duplicated<EOL>stats["<STR_LIT>"] = total and duplicated * <NUM_LIT> / total<EOL>

compute and display similarities on closing (i.e. end of parsing)


nb_lignes_dupliquees = <NUM_LIT:0><EOL>for num, couples in sims:<EOL><INDENT>print()<EOL>print(num, "<STR_LIT>", len(couples), "<STR_LIT>")<EOL>couples = sorted(couples)<EOL>for lineset, idx in couples:<EOL><INDENT>print("<STR_LIT>" % (lineset.name, idx))<EOL><DEDENT>for line in lineset._real_lines[idx : idx + num]:<EOL><INDENT>print("<STR_LIT:U+0020>", line.rstrip())<EOL><DEDENT>nb_lignes_dupliquees += num * (len(couples) - <NUM_LIT:1>)<EOL><DEDENT>nb_total_lignes = sum([len(lineset) for lineset in self.linesets])<EOL>print(<EOL>"<STR_LIT>"<EOL>% (<EOL>nb_total_lignes,<EOL>nb_lignes_dupliquees,<EOL>nb_lignes_dupliquees * <NUM_LIT> / nb_total_lignes,<EOL>)<EOL>)<EOL>


def report_similarities(sect, stats, old_stats):

lines = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL>lines += table_lines_from_stats(<EOL>stats, old_stats, ("<STR_LIT>", "<STR_LIT>")<EOL>)<EOL>sect.append(Table(children=lines, cols=<NUM_LIT:4>, rheaders=<NUM_LIT:1>, cheaders=<NUM_LIT:1>))<EOL>

make a layout with some stats about duplication


linter.register_checker(SimilarChecker(linter))<EOL>

required method to auto register this checker


def stripped_lines(lines, ignore_comments, ignore_docstrings, ignore_imports):

if ignore_imports:<EOL><INDENT>tree = astroid.parse("<STR_LIT>".join(lines))<EOL>node_is_import_by_lineno = (<EOL>(node.lineno, isinstance(node, (astroid.Import, astroid.ImportFrom)))<EOL>for node in tree.body<EOL>)<EOL>line_begins_import = {<EOL>lineno: all(is_import for _, is_import in node_is_import_group)<EOL>for lineno, node_is_import_group in groupby(<EOL>node_is_import_by_lineno, key=lambda x: x[<NUM_LIT:0>]<EOL>)<EOL>}<EOL>current_line_is_import = False<EOL><DEDENT>strippedlines = []<EOL>docstring = None<EOL>for lineno, line in enumerate(lines, start=<NUM_LIT:1>):<EOL><INDENT>line = line.strip()<EOL>if ignore_docstrings:<EOL><INDENT>if not docstring and any(<EOL>line.startswith(i) for i in ['<STR_LIT>', "<STR_LIT>", '<STR_LIT>', "<STR_LIT>"]<EOL>):<EOL><INDENT>docstring = line[:<NUM_LIT:3>]<EOL>line = line[<NUM_LIT:3>:]<EOL><DEDENT>if docstring:<EOL><INDENT>if line.endswith(docstring):<EOL><INDENT>docstring = None<EOL><DEDENT>line = "<STR_LIT>"<EOL><DEDENT><DEDENT>if ignore_imports:<EOL><INDENT>current_line_is_import = line_begins_import.get(<EOL>lineno, current_line_is_import<EOL>)<EOL>if current_line_is_import:<EOL><INDENT>line = "<STR_LIT>"<EOL><DEDENT><DEDENT>if ignore_comments:<EOL><INDENT>line = line.split("<STR_LIT:#>", <NUM_LIT:1>)[<NUM_LIT:0>].strip()<EOL><DEDENT>strippedlines.append(line)<EOL><DEDENT>return strippedlines<EOL>

return lines with leading/trailing whitespace and any ignored code
    features removed


def _no_context_variadic(node, variadic_name, variadic_type, variadics):

statement = node.statement()<EOL>for name in statement.nodes_of_class(astroid.Name):<EOL><INDENT>if name.name != variadic_name:<EOL><INDENT>continue<EOL><DEDENT>inferred = safe_infer(name)<EOL>if isinstance(inferred, (astroid.List, astroid.Tuple)):<EOL><INDENT>length = len(inferred.elts)<EOL><DEDENT>elif isinstance(inferred, astroid.Dict):<EOL><INDENT>length = len(inferred.items)<EOL><DEDENT>else:<EOL><INDENT>continue<EOL><DEDENT>inferred_statement = inferred.statement()<EOL>if not length and isinstance(inferred_statement, astroid.FunctionDef):<EOL><INDENT>is_in_starred_context = _has_parent_of_type(node, variadic_type, statement)<EOL>used_as_starred_argument = _is_name_used_as_variadic(name, variadics)<EOL>if is_in_starred_context or used_as_starred_argument:<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return False<EOL>

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.


def _is_owner_ignored(owner, name, ignored_classes, ignored_modules):

ignored_modules = set(ignored_modules)<EOL>module_name = owner.root().name<EOL>module_qname = owner.root().qname()<EOL>if any(<EOL>module_name in ignored_modules<EOL>or module_qname in ignored_modules<EOL>or fnmatch.fnmatch(module_qname, ignore)<EOL>for ignore in ignored_modules<EOL>):<EOL><INDENT>return True<EOL><DEDENT>ignored_classes = set(ignored_classes)<EOL>if hasattr(owner, "<STR_LIT>"):<EOL><INDENT>qname = owner.qname()<EOL><DEDENT>else:<EOL><INDENT>qname = "<STR_LIT>"<EOL><DEDENT>return any(ignore in (name, qname) for ignore in ignored_classes)<EOL>

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*.


called = safe_infer(node.func)<EOL>if called and not called.callable():<EOL><INDENT>if isinstance(called, astroid.Instance) and (<EOL>not has_known_bases(called)<EOL>or (<EOL>isinstance(called.scope(), astroid.ClassDef)<EOL>and "<STR_LIT>" in called.locals<EOL>)<EOL>):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self.add_message("<STR_LIT>", node=node, args=node.func.as_string())<EOL><DEDENT><DEDENT>self._check_uninferable_call(node)<EOL>try:<EOL><INDENT>called, implicit_args, callable_name = _determine_callable(called)<EOL><DEDENT>except ValueError:<EOL><INDENT>return<EOL><DEDENT>if called.args.args is None:<EOL><INDENT>return<EOL><DEDENT>if len(called.argnames()) != len(set(called.argnames())):<EOL><INDENT>return<EOL><DEDENT>call_site = astroid.arguments.CallSite.from_call(node)<EOL>for keyword in call_site.duplicated_keywords:<EOL><INDENT>self.add_message("<STR_LIT>", node=node, args=(keyword,))<EOL><DEDENT>if call_site.has_invalid_arguments() or call_site.has_invalid_keywords():<EOL><INDENT>return<EOL><DEDENT>num_positional_args = len(call_site.positional_arguments)<EOL>keyword_args = list(call_site.keyword_arguments.keys())<EOL>if isinstance(node.scope(), astroid.FunctionDef):<EOL><INDENT>has_no_context_positional_variadic = _no_context_variadic_positional(node)<EOL>has_no_context_keywords_variadic = _no_context_variadic_keywords(node)<EOL><DEDENT>else:<EOL><INDENT>has_no_context_positional_variadic = (<EOL>has_no_context_keywords_variadic<EOL>) = False<EOL><DEDENT>already_filled_positionals = getattr(called, "<STR_LIT>", <NUM_LIT:0>)<EOL>already_filled_keywords = getattr(called, "<STR_LIT>", {})<EOL>keyword_args += list(already_filled_keywords)<EOL>num_positional_args += implicit_args + already_filled_positionals<EOL>num_mandatory_parameters = len(called.args.args) - len(called.args.defaults)<EOL>parameters = []<EOL>parameter_name_to_index = {}<EOL>for i, arg in enumerate(called.args.args):<EOL><INDENT>if isinstance(arg, astroid.Tuple):<EOL><INDENT>name = None<EOL><DEDENT>else:<EOL><INDENT>assert isinstance(arg, astroid.AssignName)<EOL>name = arg.name<EOL>parameter_name_to_index[name] = i<EOL><DEDENT>if i >= num_mandatory_parameters:<EOL><INDENT>defval = called.args.defaults[i - num_mandatory_parameters]<EOL><DEDENT>else:<EOL><INDENT>defval = None<EOL><DEDENT>parameters.append([(name, defval), False])<EOL><DEDENT>kwparams = {}<EOL>for i, arg in enumerate(called.args.kwonlyargs):<EOL><INDENT>if isinstance(arg, astroid.Keyword):<EOL><INDENT>name = arg.arg<EOL><DEDENT>else:<EOL><INDENT>assert isinstance(arg, astroid.AssignName)<EOL>name = arg.name<EOL><DEDENT>kwparams[name] = [called.args.kw_defaults[i], False]<EOL><DEDENT>for i in range(num_positional_args):<EOL><INDENT>if i < len(parameters):<EOL><INDENT>parameters[i][<NUM_LIT:1>] = True<EOL><DEDENT>elif called.args.vararg is not None:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", node=node, args=(callable_name,)<EOL>)<EOL>break<EOL><DEDENT><DEDENT>for keyword in keyword_args:<EOL><INDENT>if keyword in parameter_name_to_index:<EOL><INDENT>i = parameter_name_to_index[keyword]<EOL>if parameters[i][<NUM_LIT:1>]:<EOL><INDENT>if not (keyword == "<STR_LIT>" and called.qname() in STR_FORMAT):<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(keyword, callable_name),<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>parameters[i][<NUM_LIT:1>] = True<EOL><DEDENT><DEDENT>elif keyword in kwparams:<EOL><INDENT>if kwparams[keyword][<NUM_LIT:1>]:  <EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(keyword, callable_name),<EOL>)<EOL><DEDENT>else:<EOL><INDENT>kwparams[keyword][<NUM_LIT:1>] = True<EOL><DEDENT><DEDENT>elif called.args.kwarg is not None:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>", node=node, args=(keyword, callable_name)<EOL>)<EOL><DEDENT><DEDENT>if node.kwargs:<EOL><INDENT>for i, [(name, defval), assigned] in enumerate(parameters):<EOL><INDENT>if name is not None:<EOL><INDENT>parameters[i][<NUM_LIT:1>] = True<EOL><DEDENT>else:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>for [(name, defval), assigned] in parameters:<EOL><INDENT>if (defval is None) and not assigned:<EOL><INDENT>if name is None:<EOL><INDENT>display_name = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>display_name = repr(name)<EOL><DEDENT>if not has_no_context_positional_variadic:<EOL><INDENT>self.add_message(<EOL>"<STR_LIT>",<EOL>node=node,<EOL>args=(display_name, callable_name),<EOL>)<EOL><DEDENT><DEDENT><DEDENT>for name in kwparams:<EOL><INDENT>defval, assigned = kwparams[name]<EOL>if defval is None and not assigned and not has_no_context_keywords_variadic:<EOL><INDENT>self.add_message("<STR_LIT>", node=node, args=(name, callable_name))<EOL><DEDENT><DEDENT>

check that called functions/methods are inferred to callable objects,
        and that the arguments passed to the function match the parameters in
        the inferred function's definition


linter.register_checker(TypeChecker(linter))<EOL>linter.register_checker(IterableChecker(linter))<EOL>


raise NotImplementedError()<EOL>


if self.name is not None:<EOL><INDENT>self.name = self.name.lower()<EOL><DEDENT>OptionsProviderMixIn.__init__(self)<EOL>self.linter = linter<EOL>

checker instances should have the linter as argument

        :param ILinter linter: is an object implementing ILinter.


def collect_string_fields(format_string) -> Iterable[Optional[str]]:

formatter = string.Formatter()<EOL>try:<EOL><INDENT>parseiterator = formatter.parse(format_string)<EOL>for result in parseiterator:<EOL><INDENT>if all(item is None for item in result[<NUM_LIT:1>:]):<EOL><INDENT>continue<EOL><DEDENT>name = result[<NUM_LIT:1>]<EOL>nested = result[<NUM_LIT:2>]<EOL>yield name<EOL>if nested:<EOL><INDENT>for field in collect_string_fields(nested):<EOL><INDENT>yield field<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except ValueError as exc:<EOL><INDENT>if exc.args[<NUM_LIT:0>].startswith("<STR_LIT>"):<EOL><INDENT>yield "<STR_LIT>"<EOL>yield "<STR_LIT:1>"<EOL>return<EOL><DEDENT>raise IncompleteFormatString(format_string)<EOL><DEDENT>

Given a format string, return an iterator
    of all the valid format fields. It handles nested fields
    as well.


def node_frame_class(<EOL>node: astroid.node_classes.NodeNG<EOL>) -> Optional[astroid.node_classes.NodeNG]:

klass = node.frame()<EOL>while klass is not None and not isinstance(klass, astroid.ClassDef):<EOL><INDENT>if klass.parent is None:<EOL><INDENT>klass = None<EOL><DEDENT>else:<EOL><INDENT>klass = klass.parent.frame()<EOL><DEDENT><DEDENT>return klass<EOL>

return klass node for a method node (or a staticmethod or a
    classmethod), return null otherwise


def is_node_inside_try_except(node: astroid.Raise) -> bool:

context = find_try_except_wrapper_node(node)<EOL>return isinstance(context, astroid.TryExcept)<EOL>

Check if the node is directly under a Try/Except statement.
    (but not under an ExceptHandler!)

    Args:
        node (astroid.Raise): the node raising the exception.

    Returns:
        bool: True if the node is inside a try/except statement, False otherwise.


def error_of_type(handler: astroid.ExceptHandler, error_type) -> bool:

def stringify_error(error):<EOL><INDENT>if not isinstance(error, str):<EOL><INDENT>return error.__name__<EOL><DEDENT>return error<EOL><DEDENT>if not isinstance(error_type, tuple):<EOL><INDENT>error_type = (error_type,)  <EOL><DEDENT>expected_errors = {stringify_error(error) for error in error_type}  <EOL>if not handler.type:<EOL><INDENT>return True<EOL><DEDENT>return handler.catch(expected_errors)<EOL>

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 is_from_fallback_block(node: astroid.node_classes.NodeNG) -> bool:

context = find_try_except_wrapper_node(node)<EOL>if not context:<EOL><INDENT>return False<EOL><DEDENT>if isinstance(context, astroid.ExceptHandler):<EOL><INDENT>other_body = context.parent.body<EOL>handlers = context.parent.handlers<EOL><DEDENT>else:<EOL><INDENT>other_body = itertools.chain.from_iterable(<EOL>handler.body for handler in context.handlers<EOL>)<EOL>handlers = context.handlers<EOL><DEDENT>has_fallback_imports = any(<EOL>isinstance(import_node, (astroid.ImportFrom, astroid.Import))<EOL>for import_node in other_body<EOL>)<EOL>ignores_import_error = _except_handlers_ignores_exception(handlers, ImportError)<EOL>return ignores_import_error or has_fallback_imports<EOL>

Check if the given node is from a fallback import block.


def is_default_argument(node: astroid.node_classes.NodeNG) -> bool:

parent = node.scope()<EOL>if isinstance(parent, (astroid.FunctionDef, astroid.Lambda)):<EOL><INDENT>for default_node in parent.args.defaults:<EOL><INDENT>for default_name_node in default_node.nodes_of_class(astroid.Name):<EOL><INDENT>if default_name_node is node:<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return False<EOL>

return true if the given Name node is used in function or lambda
    default argument's value


def has_known_bases(klass: astroid.ClassDef, context=None) -> bool:

try:<EOL><INDENT>return klass._all_bases_known<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>for base in klass.bases:<EOL><INDENT>result = safe_infer(base, context=context)<EOL>if (<EOL>not isinstance(result, astroid.ClassDef)<EOL>or result is klass<EOL>or not has_known_bases(result, context=context)<EOL>):<EOL><INDENT>klass._all_bases_known = False<EOL>return False<EOL><DEDENT><DEDENT>klass._all_bases_known = True<EOL>return True<EOL>

Return true if all base classes of a class could be inferred.


def decorated_with(func: astroid.FunctionDef, qnames: Iterable[str]) -> bool:

decorators = func.decorators.nodes if func.decorators else []<EOL>for decorator_node in decorators:<EOL><INDENT>try:<EOL><INDENT>if any(<EOL>i is not None and i.qname() in qnames for i in decorator_node.infer()<EOL>):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>except astroid.InferenceError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>return False<EOL>

Determine if the `func` node has a decorator with the qualified name `qname`.


def node_ignores_exception(<EOL>node: astroid.node_classes.NodeNG, exception=Exception<EOL>) -> bool:

managing_handlers = get_exception_handlers(node, exception)<EOL>if not managing_handlers:<EOL><INDENT>return False<EOL><DEDENT>return any(managing_handlers)<EOL>

Check if the node is in a TryExcept which handles the given exception.

    If the exception is not given, the function is going to look for bare
    excepts.


@lru_cache(maxsize=<NUM_LIT>)<EOL>def safe_infer(<EOL>node: astroid.node_classes.NodeNG, context=None<EOL>) -> Optional[astroid.node_classes.NodeNG]:

try:<EOL><INDENT>inferit = node.infer(context=context)<EOL>value = next(inferit)<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>next(inferit)<EOL>return None  <EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>return None  <EOL><DEDENT>except StopIteration:<EOL><INDENT>return value<EOL><DEDENT>

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).


def get_node_last_lineno(node: astroid.node_classes.NodeNG) -> int:

<EOL>if getattr(node, "<STR_LIT>", False):<EOL><INDENT>return get_node_last_lineno(node.finalbody[-<NUM_LIT:1>])<EOL><DEDENT>if getattr(node, "<STR_LIT>", False):<EOL><INDENT>return get_node_last_lineno(node.orelse[-<NUM_LIT:1>])<EOL><DEDENT>if getattr(node, "<STR_LIT>", False):<EOL><INDENT>return get_node_last_lineno(node.handlers[-<NUM_LIT:1>])<EOL><DEDENT>if getattr(node, "<STR_LIT:body>", False):<EOL><INDENT>return get_node_last_lineno(node.body[-<NUM_LIT:1>])<EOL><DEDENT>return node.lineno<EOL>

Get the last lineno of the given node. For a simple statement this will just be node.lineno,
but for a node that has child statements (e.g. a method) this will be the lineno of the last
child statement recursively.


@utils.check_messages("<STR_LIT>", "<STR_LIT>")<EOL><INDENT>def visit_raise(self, node):<DEDENT>

<EOL>if node.exc is None:<EOL><INDENT>return<EOL><DEDENT>expr = node.exc<EOL>if self._check_raise_value(node, expr):<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>value = next(astroid.unpack_infer(expr))<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>return<EOL><DEDENT>self._check_raise_value(node, value)<EOL>

Visit a raise statement and check for raising
        strings or old-raise-syntax.


@utils.check_messages("<STR_LIT>", "<STR_LIT>")<EOL><INDENT>def visit_excepthandler(self, node):<DEDENT>

def _is_used_in_except_block(node):<EOL><INDENT>scope = node.scope()<EOL>current = node<EOL>while (<EOL>current<EOL>and current != scope<EOL>and not isinstance(current, astroid.ExceptHandler)<EOL>):<EOL><INDENT>current = current.parent<EOL><DEDENT>return isinstance(current, astroid.ExceptHandler) and current.type != node<EOL><DEDENT>if isinstance(node.name, (astroid.Tuple, astroid.List)):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL>return<EOL><DEDENT>if not node.name:<EOL><INDENT>return<EOL><DEDENT>scope = node.parent.scope()<EOL>scope_names = scope.nodes_of_class(astroid.Name, skip_klass=astroid.FunctionDef)<EOL>scope_names = list(scope_names)<EOL>potential_leaked_names = [<EOL>scope_name<EOL>for scope_name in scope_names<EOL>if scope_name.name == node.name.name<EOL>and scope_name.lineno > node.lineno<EOL>and not _is_used_in_except_block(scope_name)<EOL>]<EOL>reassignments_for_same_name = {<EOL>assign_name.lineno<EOL>for assign_name in scope.nodes_of_class(<EOL>astroid.AssignName, skip_klass=astroid.FunctionDef<EOL>)<EOL>if assign_name.name == node.name.name<EOL>}<EOL>for leaked_name in potential_leaked_names:<EOL><INDENT>if any(<EOL>node.lineno < elem < leaked_name.lineno<EOL>for elem in reassignments_for_same_name<EOL>):<EOL><INDENT>continue<EOL><DEDENT>self.add_message("<STR_LIT>", node=leaked_name)<EOL><DEDENT>

Visit an except handler block and check for exception unpacking.


@utils.check_messages("<STR_LIT>", "<STR_LIT>")<EOL><INDENT>def visit_attribute(self, node):<DEDENT>

if node.attrname == "<STR_LIT>":<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL>return<EOL><DEDENT>exception_message = "<STR_LIT:message>"<EOL>try:<EOL><INDENT>for inferred in node.expr.infer():<EOL><INDENT>if isinstance(inferred, astroid.Instance) and utils.inherit_from_std_ex(<EOL>inferred<EOL>):<EOL><INDENT>if node.attrname == exception_message:<EOL><INDENT>if exception_message in inferred.instance_attrs:<EOL><INDENT>continue<EOL><DEDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT><DEDENT>if isinstance(inferred, astroid.Module):<EOL><INDENT>self._warn_if_deprecated(<EOL>node, inferred.name, {node.attrname}, report_on_modules=False<EOL>)<EOL><DEDENT><DEDENT><DEDENT>except astroid.InferenceError:<EOL><INDENT>return<EOL><DEDENT>


branches = <NUM_LIT:1><EOL>if node.orelse:<EOL><INDENT>branches += <NUM_LIT:1><EOL><DEDENT>self._inc_branch(node, branches)<EOL>


nb_bool_expr = <NUM_LIT:0><EOL>for bool_expr in bool_op.get_children():<EOL><INDENT>if isinstance(bool_expr, BoolOp):<EOL><INDENT>nb_bool_expr += _count_boolean_expressions(bool_expr)<EOL><DEDENT>else:<EOL><INDENT>nb_bool_expr += <NUM_LIT:1><EOL><DEDENT><DEDENT>return nb_bool_expr<EOL>

Counts the number of boolean expressions in BoolOp `bool_op` (recursive)

    example: a and (b or c or (d and e)) ==> 5 boolean expressions


if node.is_statement:<EOL><INDENT>self._inc_all_stmts(<NUM_LIT:1>)<EOL><DEDENT>

default visit method -> increments the statements counter if
        necessary


self.stats = self.linter.add_stats()<EOL>self._returns = []<EOL>self._branches = defaultdict(int)<EOL>self._stmts = []<EOL>


Default implementation for all the nodes.


try:<EOL><INDENT>infered = next(node.infer())<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>return<EOL><DEDENT>if isinstance(infered, Instance) and infered.qname() == "<STR_LIT>":<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>

Check that a datetime was infered.
        If so, emit boolean-datetime warning.


linter.register_checker(StdlibChecker(linter))<EOL>

required method to auto register this checker


if self._is_actual_elif(node):<EOL><INDENT>return<EOL><DEDENT>if len(node.orelse) != <NUM_LIT:1> or len(node.body) != <NUM_LIT:1>:<EOL><INDENT>return<EOL><DEDENT>first_branch = node.body[<NUM_LIT:0>]<EOL>else_branch = node.orelse[<NUM_LIT:0>]<EOL>if isinstance(first_branch, astroid.Return):<EOL><INDENT>if not isinstance(else_branch, astroid.Return):<EOL><INDENT>return<EOL><DEDENT>first_branch_is_bool = self._is_bool_const(first_branch)<EOL>else_branch_is_bool = self._is_bool_const(else_branch)<EOL>reduced_to = "<STR_LIT>"<EOL><DEDENT>elif isinstance(first_branch, astroid.Assign):<EOL><INDENT>if not isinstance(else_branch, astroid.Assign):<EOL><INDENT>return<EOL><DEDENT>first_branch_targets = [<EOL>target.name<EOL>for target in first_branch.targets<EOL>if isinstance(target, astroid.AssignName)<EOL>]<EOL>else_branch_targets = [<EOL>target.name<EOL>for target in else_branch.targets<EOL>if isinstance(target, astroid.AssignName)<EOL>]<EOL>if not first_branch_targets or not else_branch_targets:<EOL><INDENT>return<EOL><DEDENT>if sorted(first_branch_targets) != sorted(else_branch_targets):<EOL><INDENT>return<EOL><DEDENT>first_branch_is_bool = self._is_bool_const(first_branch)<EOL>else_branch_is_bool = self._is_bool_const(else_branch)<EOL>reduced_to = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT>if not first_branch_is_bool or not else_branch_is_bool:<EOL><INDENT>return<EOL><DEDENT>if not first_branch.value.value:<EOL><INDENT>return<EOL><DEDENT>self.add_message("<STR_LIT>", node=node, args=(reduced_to,))<EOL>

Check if the given if node can be simplified.

        The if statement can be reduced to a boolean expression
        in some cases. For instance, if there are two branches
        and both of them return a boolean value that depends on
        the result of the statement's test, then this can be reduced
        to `bool(test)` without losing any functionality.


stopiteration_qname = "<STR_LIT>".format(utils.EXCEPTIONS_MODULE)<EOL>return any(_class.qname() == stopiteration_qname for _class in exc.mro())<EOL>

Return True if the exception node in argument inherit from StopIteration


<EOL>if isinstance(node, astroid.Return):<EOL><INDENT>return True<EOL><DEDENT>if isinstance(node, astroid.Call):<EOL><INDENT>try:<EOL><INDENT>funcdef_node = node.func.inferred()[<NUM_LIT:0>]<EOL>if self._is_function_def_never_returning(funcdef_node):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>except astroid.InferenceError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if isinstance(node, astroid.While):<EOL><INDENT>return True<EOL><DEDENT>if isinstance(node, astroid.Raise):<EOL><INDENT>if not node.exc:<EOL><INDENT>return True<EOL><DEDENT>if not utils.is_node_inside_try_except(node):<EOL><INDENT>return True<EOL><DEDENT>exc = utils.safe_infer(node.exc)<EOL>if exc is None or exc is astroid.Uninferable:<EOL><INDENT>return False<EOL><DEDENT>exc_name = exc.pytype().split("<STR_LIT:.>")[-<NUM_LIT:1>]<EOL>handlers = utils.get_exception_handlers(node, exc_name)<EOL>handlers = list(handlers) if handlers is not None else []<EOL>if handlers:<EOL><INDENT>return any(<EOL>self._is_node_return_ended(_handler) for _handler in handlers<EOL>)<EOL><DEDENT>return True<EOL><DEDENT>if isinstance(node, astroid.If):<EOL><INDENT>is_orelse_returning = any(<EOL>self._is_node_return_ended(_ore)<EOL>for _ore in node.orelse<EOL>if not isinstance(_ore, astroid.FunctionDef)<EOL>)<EOL>is_if_returning = any(<EOL>self._is_node_return_ended(_ifn)<EOL>for _ifn in node.body<EOL>if not isinstance(_ifn, astroid.FunctionDef)<EOL>)<EOL>return is_if_returning and is_orelse_returning<EOL><DEDENT>return any(<EOL>self._is_node_return_ended(_child)<EOL>for _child in node.get_children()<EOL>if not isinstance(_child, astroid.ExceptHandler)<EOL>)<EOL>

Check if the node ends with an explicit return statement.

        Args:
            node (astroid.NodeNG): node to be checked.

        Returns:
            bool: True if the node ends with an explicit statement, False otherwise.


if node.op != "<STR_LIT>" or len(node.values) < <NUM_LIT:2>:<EOL><INDENT>return<EOL><DEDENT>def _find_lower_upper_bounds(comparison_node, uses):<EOL><INDENT>left_operand = comparison_node.left<EOL>for operator, right_operand in comparison_node.ops:<EOL><INDENT>for operand in (left_operand, right_operand):<EOL><INDENT>value = None<EOL>if isinstance(operand, astroid.Name):<EOL><INDENT>value = operand.name<EOL><DEDENT>elif isinstance(operand, astroid.Const):<EOL><INDENT>value = operand.value<EOL><DEDENT>if value is None:<EOL><INDENT>continue<EOL><DEDENT>if operator in ("<STR_LIT:<>", "<STR_LIT>"):<EOL><INDENT>if operand is left_operand:<EOL><INDENT>uses[value]["<STR_LIT>"].add(comparison_node)<EOL><DEDENT>elif operand is right_operand:<EOL><INDENT>uses[value]["<STR_LIT>"].add(comparison_node)<EOL><DEDENT><DEDENT>elif operator in ("<STR_LIT:>>", "<STR_LIT>"):<EOL><INDENT>if operand is left_operand:<EOL><INDENT>uses[value]["<STR_LIT>"].add(comparison_node)<EOL><DEDENT>elif operand is right_operand:<EOL><INDENT>uses[value]["<STR_LIT>"].add(comparison_node)<EOL><DEDENT><DEDENT><DEDENT>left_operand = right_operand<EOL><DEDENT><DEDENT>uses = collections.defaultdict(<EOL>lambda: {"<STR_LIT>": set(), "<STR_LIT>": set()}<EOL>)<EOL>for comparison_node in node.values:<EOL><INDENT>if isinstance(comparison_node, astroid.Compare):<EOL><INDENT>_find_lower_upper_bounds(comparison_node, uses)<EOL><DEDENT><DEDENT>for _, bounds in uses.items():<EOL><INDENT>num_shared = len(bounds["<STR_LIT>"].intersection(bounds["<STR_LIT>"]))<EOL>num_lower_bounds = len(bounds["<STR_LIT>"])<EOL>num_upper_bounds = len(bounds["<STR_LIT>"])<EOL>if num_shared < num_lower_bounds and num_shared < num_upper_bounds:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL>break<EOL><DEDENT><DEDENT>

Check if there is any chained comparison in the expression.

        Add a refactoring message if a boolOp contains comparison like a < b and b < c,
        which can be chained as a < b < c.

        Care is taken to avoid simplifying a < b < c and b < d.


duplicated_objects = set()<EOL>all_types = collections.defaultdict(set)<EOL>for call in node.values:<EOL><INDENT>if not isinstance(call, astroid.Call) or len(call.args) != <NUM_LIT:2>:<EOL><INDENT>continue<EOL><DEDENT>inferred = utils.safe_infer(call.func)<EOL>if not inferred or not utils.is_builtin_object(inferred):<EOL><INDENT>continue<EOL><DEDENT>if inferred.name != "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>isinstance_object = call.args[<NUM_LIT:0>].as_string()<EOL>isinstance_types = call.args[<NUM_LIT:1>]<EOL>if isinstance_object in all_types:<EOL><INDENT>duplicated_objects.add(isinstance_object)<EOL><DEDENT>if isinstance(isinstance_types, astroid.Tuple):<EOL><INDENT>elems = [<EOL>class_type.as_string() for class_type in isinstance_types.itered()<EOL>]<EOL><DEDENT>else:<EOL><INDENT>elems = [isinstance_types.as_string()]<EOL><DEDENT>all_types[isinstance_object].update(elems)<EOL><DEDENT>return {<EOL>key: value for key, value in all_types.items() if key in duplicated_objects<EOL>}<EOL>

Get the duplicated types from the underlying isinstance calls.

        :param astroid.BoolOp node: Node which should contain a bunch of isinstance calls.
        :returns: Dictionary of the comparison objects from the isinstance calls,
                  to duplicate values from consecutive calls.
        :rtype: dict


<EOL>if not isinstance(node.iter, astroid.Call):<EOL><INDENT>return<EOL><DEDENT>if not self._is_builtin(node.iter.func, "<STR_LIT>"):<EOL><INDENT>return<EOL><DEDENT>if len(node.iter.args) == <NUM_LIT:2> and not _is_constant_zero(node.iter.args[<NUM_LIT:0>]):<EOL><INDENT>return<EOL><DEDENT>if len(node.iter.args) > <NUM_LIT:2>:<EOL><INDENT>return<EOL><DEDENT>if not isinstance(node.iter.args[-<NUM_LIT:1>], astroid.Call):<EOL><INDENT>return<EOL><DEDENT>second_func = node.iter.args[-<NUM_LIT:1>].func<EOL>if not self._is_builtin(second_func, "<STR_LIT>"):<EOL><INDENT>return<EOL><DEDENT>len_args = node.iter.args[-<NUM_LIT:1>].args<EOL>if not len_args or len(len_args) != <NUM_LIT:1>:<EOL><INDENT>return<EOL><DEDENT>iterating_object = len_args[<NUM_LIT:0>]<EOL>if not isinstance(iterating_object, astroid.Name):<EOL><INDENT>return<EOL><DEDENT>scope = node.scope()<EOL>if iterating_object.name == "<STR_LIT>" and scope.name == "<STR_LIT>":<EOL><INDENT>return<EOL><DEDENT>for child in node.body:<EOL><INDENT>for subscript in child.nodes_of_class(astroid.Subscript):<EOL><INDENT>if not isinstance(subscript.value, astroid.Name):<EOL><INDENT>continue<EOL><DEDENT>if not isinstance(subscript.slice, astroid.Index):<EOL><INDENT>continue<EOL><DEDENT>if not isinstance(subscript.slice.value, astroid.Name):<EOL><INDENT>continue<EOL><DEDENT>if subscript.slice.value.name != node.target.name:<EOL><INDENT>continue<EOL><DEDENT>if iterating_object.name != subscript.value.name:<EOL><INDENT>continue<EOL><DEDENT>if subscript.value.scope() != node.scope():<EOL><INDENT>continue<EOL><DEDENT>self.add_message("<STR_LIT>", node=node)<EOL>return<EOL><DEDENT><DEDENT>

Emit a convention whenever range and len are used for indexing.


if len(self._return_nodes[node.name]) > <NUM_LIT:1>:<EOL><INDENT>return<EOL><DEDENT>if len(node.body) <= <NUM_LIT:1>:<EOL><INDENT>return<EOL><DEDENT>last = node.body[-<NUM_LIT:1>]<EOL>if isinstance(last, astroid.Return):<EOL><INDENT>if last.value is None:<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT>elif isinstance(last.value, astroid.Const) and (last.value.value is None):<EOL><INDENT>self.add_message("<STR_LIT>", node=node)<EOL><DEDENT><DEDENT>

Check for presence of a *single* return statement at the end of a
        function. "return" or "return None" are useless because None is the
        default return type if they are missing.

        NOTE: produces a message only if there is a single return statement
        in the function body. Otherwise _check_consistent_returns() is called!
        Per its implementation and PEP8 we can have a "return None" at the end
        of the function body if there are other return statements before that!


walker = ASTWalker(linter)<EOL>walker.add_checker(self.checker)<EOL>walker.walk(node)<EOL>


<EOL>file_handle, tmp = tempfile.mkstemp()<EOL>if content:<EOL><INDENT>if sys.version_info >= (<NUM_LIT:3>, <NUM_LIT:0>):<EOL><INDENT>write(file_handle, bytes(content, "<STR_LIT:ascii>"))<EOL><DEDENT>else:<EOL><INDENT>write(file_handle, content)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>yield tmp<EOL><DEDENT>finally:<EOL><INDENT>close(file_handle)<EOL>remove(tmp)<EOL><DEDENT>

Create a new temporary file.

    If *content* parameter is given, then it will be written
    in the temporary file, before passing it back.
    This is a context manager and should be used with a *with* statement.


self._dec_indent()<EOL>self._stream.write("<STR_LIT>" % self._indent)<EOL>


self._indent = "<STR_LIT>" % self._indent<EOL>


self.module_names = self._set_option(self.config.module_names)<EOL>all_ancestors = self._set_option(self.config.all_ancestors)<EOL>all_associated = self._set_option(self.config.all_associated)<EOL>anc_level, association_level = (<NUM_LIT:0>, <NUM_LIT:0>)<EOL>if all_ancestors:<EOL><INDENT>anc_level = -<NUM_LIT:1><EOL><DEDENT>if all_associated:<EOL><INDENT>association_level = -<NUM_LIT:1><EOL><DEDENT>if self.config.show_ancestors is not None:<EOL><INDENT>anc_level = self.config.show_ancestors<EOL><DEDENT>if self.config.show_associated is not None:<EOL><INDENT>association_level = self.config.show_associated<EOL><DEDENT>self.anc_level, self.association_level = anc_level, association_level<EOL>

set different default options with _default dictionary


<EOL>if option is None:<EOL><INDENT>return bool(self.config.classes)<EOL><DEDENT>return option<EOL>

activate some options if not explicitly deactivated


anc_level, association_level = self._get_levels()<EOL>self.extract_classes(node, anc_level, association_level)<EOL>

visit an astroid.Class node

        add this class to the class diagram definition


def set_printer(self, file_name, basename):

self.graph_file = open(file_name, "<STR_LIT>")<EOL>self.printer = VCGPrinter(self.graph_file)<EOL>self.printer.open_graph(<EOL>title=basename,<EOL>layoutalgorithm="<STR_LIT>",<EOL>late_edge_labels="<STR_LIT:yes>",<EOL>port_sharing="<STR_LIT>",<EOL>manhattan_edges="<STR_LIT:yes>",<EOL>)<EOL>self.printer.emit_node = self.printer.node<EOL>self.printer.emit_edge = self.printer.edge<EOL>


<EOL>for i, obj in enumerate(sorted(diagram.objects, key=lambda x: x.title)):<EOL><INDENT>self.printer.emit_node(i, **self.get_values(obj))<EOL>obj.fig_id = i<EOL><DEDENT>for rel in diagram.get_relationships("<STR_LIT>"):<EOL><INDENT>self.printer.emit_edge(<EOL>rel.from_object.fig_id, rel.to_object.fig_id, **self.inh_edges<EOL>)<EOL><DEDENT>for rel in diagram.get_relationships("<STR_LIT>"):<EOL><INDENT>self.printer.emit_edge(<EOL>rel.from_object.fig_id, rel.to_object.fig_id, **self.imp_edges<EOL>)<EOL><DEDENT>for rel in diagram.get_relationships("<STR_LIT>"):<EOL><INDENT>self.printer.emit_edge(<EOL>rel.from_object.fig_id,<EOL>rel.to_object.fig_id,<EOL>label=rel.name,<EOL>**self.association_edges<EOL>)<EOL><DEDENT>


raise NotImplementedError<EOL>


__mode = <NUM_LIT:0><EOL>for nummod in mode.split("<STR_LIT:+>"):<EOL><INDENT>try:<EOL><INDENT>__mode += MODES[nummod]<EOL><DEDENT>except KeyError as ex:<EOL><INDENT>print("<STR_LIT>" % ex, file=sys.stderr)<EOL><DEDENT><DEDENT>self.__mode = __mode<EOL>


if hasattr(node, "<STR_LIT>"):<EOL><INDENT>return<EOL><DEDENT>node.locals_type = collections.defaultdict(list)<EOL>if self.tag:<EOL><INDENT>node.uid = self.generate_id()<EOL><DEDENT>for baseobj in node.ancestors(recurs=False):<EOL><INDENT>specializations = getattr(baseobj, "<STR_LIT>", [])<EOL>specializations.append(node)<EOL>baseobj.specializations = specializations<EOL><DEDENT>node.instance_attrs_type = collections.defaultdict(list)<EOL>for assignattrs in node.instance_attrs.values():<EOL><INDENT>for assignattr in assignattrs:<EOL><INDENT>self.handle_assignattr_type(assignattr, node)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>node.implements = list(interfaces(node, self.inherited_interfaces))<EOL><DEDENT>except astroid.InferenceError:<EOL><INDENT>node.implements = ()<EOL><DEDENT>

visit an astroid.Class node

         * set the locals_type and instance_attrs_type mappings
         * set the implements list and build it
         * optionally tag the node with a unique id


def interfaces(node, herited=True, handler_func=_iface_hdlr):

<EOL>try:<EOL><INDENT>implements = bases.Instance(node).getattr("<STR_LIT>")[<NUM_LIT:0>]<EOL><DEDENT>except exceptions.NotFoundError:<EOL><INDENT>return<EOL><DEDENT>if not herited and implements.frame() is not node:<EOL><INDENT>return<EOL><DEDENT>found = set()<EOL>missing = False<EOL>for iface in node_classes.unpack_infer(implements):<EOL><INDENT>if iface is astroid.Uninferable:<EOL><INDENT>missing = True<EOL>continue<EOL><DEDENT>if iface not in found and handler_func(iface):<EOL><INDENT>found.add(iface)<EOL>yield iface<EOL><DEDENT><DEDENT>if missing:<EOL><INDENT>raise exceptions.InferenceError()<EOL><DEDENT>

Return an iterator on interfaces implemented by the given class node.


context_file = node.root().file<EOL>for name in node.names:<EOL><INDENT>relative = modutils.is_relative(name[<NUM_LIT:0>], context_file)<EOL>self._imported_module(node, name[<NUM_LIT:0>], relative)<EOL><DEDENT>

visit an astroid.Import node

        resolve module dependencies


return True<EOL>

Handler used by interfaces to handle suspicious interface nodes.


self.id_count += <NUM_LIT:1><EOL>return self.id_count<EOL>


for obj in self.classes():<EOL><INDENT>node = obj.node<EOL>obj.attrs = self.get_attrs(node)<EOL>obj.methods = self.get_methods(node)<EOL>if is_interface(node):<EOL><INDENT>obj.shape = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>obj.shape = "<STR_LIT:class>"<EOL><DEDENT>for par_node in node.ancestors(recurs=False):<EOL><INDENT>try:<EOL><INDENT>par_obj = self.object_from_node(par_node)<EOL>self.add_relationship(obj, par_obj, "<STR_LIT>")<EOL><DEDENT>except KeyError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>for impl_node in node.implements:<EOL><INDENT>try:<EOL><INDENT>impl_obj = self.object_from_node(impl_node)<EOL>self.add_relationship(obj, impl_obj, "<STR_LIT>")<EOL><DEDENT>except KeyError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>for name, values in list(node.instance_attrs_type.items()) + list(<EOL>node.locals_type.items()<EOL>):<EOL><INDENT>for value in values:<EOL><INDENT>if value is astroid.Uninferable:<EOL><INDENT>continue<EOL><DEDENT>if isinstance(value, astroid.Instance):<EOL><INDENT>value = value._proxied<EOL><DEDENT>try:<EOL><INDENT>associated_obj = self.object_from_node(value)<EOL>self.add_relationship(associated_obj, obj, "<STR_LIT>", name)<EOL><DEDENT>except KeyError:<EOL><INDENT>continue<EOL><DEDENT><DEDENT><DEDENT><DEDENT>

extract relation ships between nodes in the diagram


names = []<EOL>for node in nodes:<EOL><INDENT>if isinstance(node, astroid.Instance):<EOL><INDENT>node = node._proxied<EOL><DEDENT>if (<EOL>isinstance(node, astroid.ClassDef)<EOL>and hasattr(node, "<STR_LIT:name>")<EOL>and not self.has_node(node)<EOL>):<EOL><INDENT>if node.name not in names:<EOL><INDENT>node_name = node.name<EOL>names.append(node_name)<EOL><DEDENT><DEDENT><DEDENT>return names<EOL>


for mod in self.modules():<EOL><INDENT>mod_name = mod.node.name<EOL>if mod_name == name:<EOL><INDENT>return mod<EOL><DEDENT>package = node.root().name<EOL>if mod_name == "<STR_LIT>" % (package, name):<EOL><INDENT>return mod<EOL><DEDENT>if mod_name == "<STR_LIT>" % (package.rsplit("<STR_LIT:.>", <NUM_LIT:1>)[<NUM_LIT:0>], name):<EOL><INDENT>return mod<EOL><DEDENT><DEDENT>raise KeyError(name)<EOL>

return a module by its name, looking also for relative imports;
        raise KeyError if not found


return '<STR_LIT>' % nid<EOL>

Returns a suitable DOT node id for `nid`.


self.lines.append(line)<EOL>


basename = osp.basename(filename)<EOL>storedir = osp.dirname(osp.abspath(filename))<EOL>target = filename.split("<STR_LIT:.>")[-<NUM_LIT:1>]<EOL>return storedir, basename, target<EOL>

Transforms /some/path/foo.png into ('/some/path', 'foo.png', 'png').


linter.register_checker(MyAstroidChecker(linter))<EOL>

This required method auto registers the checker.

    :param linter: The linter to register the checker to.
    :type linter: pylint.lint.PyLinter


install_lib.install_lib.run(self)<EOL>if include_dirs:<EOL><INDENT>for directory in include_dirs:<EOL><INDENT>dest = join(self.install_dir, directory)<EOL>if sys.version_info >= (<NUM_LIT:3>, <NUM_LIT:0>):<EOL><INDENT>exclude = {"<STR_LIT>", "<STR_LIT>"}<EOL><DEDENT>else:<EOL><INDENT>exclude = set()<EOL><DEDENT>shutil.rmtree(dest, ignore_errors=True)<EOL>shutil.copytree(<EOL>directory, dest, ignore=shutil.ignore_patterns(*exclude)<EOL>)<EOL><DEDENT><DEDENT>


if USE_SETUPTOOLS:<EOL><INDENT>if "<STR_LIT>" in sys.argv:<EOL><INDENT>sys.argv.remove("<STR_LIT>")<EOL><DEDENT><DEDENT>packages = [modname] + get_packages(join(base_dir, "<STR_LIT>"), modname)<EOL>if USE_SETUPTOOLS:<EOL><INDENT>if install_requires:<EOL><INDENT>kwargs["<STR_LIT>"] = install_requires<EOL>kwargs["<STR_LIT>"] = dependency_links<EOL><DEDENT>kwargs["<STR_LIT>"] = {<EOL>"<STR_LIT>": [<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>]<EOL>}<EOL><DEDENT>kwargs["<STR_LIT>"] = packages<EOL>cmdclass = {"<STR_LIT>": MyInstallLib, "<STR_LIT>": build_py}<EOL>if easy_install_lib:<EOL><INDENT>cmdclass["<STR_LIT>"] = easy_install<EOL><DEDENT>return setup(<EOL>name=distname,<EOL>version=__pkginfo__["<STR_LIT:version>"],<EOL>license=__pkginfo__["<STR_LIT>"],<EOL>description=__pkginfo__["<STR_LIT:description>"],<EOL>long_description=long_description,<EOL>author=__pkginfo__["<STR_LIT>"],<EOL>author_email=__pkginfo__["<STR_LIT>"],<EOL>url=__pkginfo__["<STR_LIT>"],<EOL>scripts=ensure_scripts(scripts),<EOL>classifiers=__pkginfo__["<STR_LIT>"],<EOL>data_files=data_files,<EOL>ext_modules=ext_modules,<EOL>cmdclass=cmdclass,<EOL>extras_require=extras_require,<EOL>test_suite="<STR_LIT:test>",<EOL>python_requires="<STR_LIT>",<EOL>setup_requires=["<STR_LIT>"],<EOL>tests_require=["<STR_LIT>"],<EOL>**kwargs<EOL>)<EOL>


from distutils import util<EOL>if util.get_platform()[:<NUM_LIT:3>] == "<STR_LIT>":<EOL><INDENT>return linux_scripts + [script + "<STR_LIT>" for script in linux_scripts]<EOL><DEDENT>return linux_scripts<EOL>

Creates the proper script names required for each platform
    (taken from 4Suite)


return pd.concat([record.series for record in collection], axis=<NUM_LIT:1>).T<EOL>

Converts a collection back into a pandas DataFrame

parameters
----------
collection : list
    list of Record objects where each Record represents one row from a dataframe

Returns
-------
df : pandas.DataFrame
    DataFrame of length=len(collection) where each row represents one Record


try:<EOL><INDENT>spit = kwargs.pop('<STR_LIT>')<EOL><DEDENT>except:<EOL><INDENT>spit = None<EOL><DEDENT>try:<EOL><INDENT>results = fcn(*args, **kwargs)<EOL>if results:<EOL><INDENT>return results<EOL><DEDENT><DEDENT>except:<EOL><INDENT>print(traceback.format_exc())<EOL>if spit:<EOL><INDENT>return spit<EOL><DEDENT><DEDENT>

try:
          retrun fcn(*args, **kwargs)
       except:
          print traceback
            if 'spit' in kwargs.keys():
                return kwargs['spit']

    Parameters
    ----------
    fcn : function
    *args : unnamed parameters of fcn
    **kwargs : named parameters of fcn
        spit : returns the parameter named return in the exception

    Returns
    -------
    The expected output of fcn or prints the exception traceback


def to_pickle(obj, filename, clean_memory=False):

path, filename = path_to_filename(filename)<EOL>create_dir(path)<EOL>with open(path + filename, "<STR_LIT:wb>") as output:<EOL><INDENT>pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)<EOL><DEDENT>if clean_memory:<EOL><INDENT>obj = None<EOL><DEDENT>return obj<EOL>


def Walk(root='<STR_LIT:.>', recurse=True, pattern='<STR_LIT:*>'):

for path, subdirs, files in os.walk(root):<EOL><INDENT>for name in files:<EOL><INDENT>if fnmatch.fnmatch(name, pattern):<EOL><INDENT>yield os.path.join(path, name)<EOL><DEDENT><DEDENT>if not recurse:<EOL><INDENT>break<EOL><DEDENT><DEDENT>

Generator for walking a directory tree.
Starts at specified root folder, returning files that match our pattern.
Optionally will also recurse through sub-folders.

Parameters
----------
root : string (default is *'.'*)
    Path for the root folder to look in.
recurse : bool (default is *True*)
    If *True*, will also look in the subfolders.
pattern : string (default is :emphasis:`'*'`, which means all the files are concerned)
    The pattern to look for in the files' name.

Returns
-------
generator
    **Walk** yields a generator from the matching files paths.


def scan_path(root='<STR_LIT:.>', recurse=False, pattern='<STR_LIT:*>'):

path_list = []<EOL>for path in Walk(root=root, recurse=recurse, pattern=pattern):<EOL><INDENT>path_list.append(path)<EOL><DEDENT>return path_list<EOL>

Runs a loop over the :doc:`Walk<relpy.utils.Walk>` Generator
to find all file paths in the root directory with the given
pattern. If recurse is *True*: matching paths are identified
for all sub directories.

Parameters
----------
root : string (default is *'.'*)
    Path for the root folder to look in.
recurse : bool (default is *True*)
    If *True*, will also look in the subfolders.
pattern : string (default is :emphasis:`'*'`, which means all the files are concerned)
    The pattern to look for in the files' name.

Returns
-------
path_list : list
    list of all the matching files paths.


depend_dict = {}<EOL>for name, info_module in self.info_modules.items():<EOL><INDENT>depend_dict[name] = getattr(info_module, '<STR_LIT>', [])<EOL><DEDENT>package_names = []<EOL>for name in list(depend_dict.keys()):<EOL><INDENT>if not depend_dict[name]:<EOL><INDENT>package_names.append(name)<EOL>del depend_dict[name]<EOL><DEDENT><DEDENT>while depend_dict:<EOL><INDENT>for name, lst in list(depend_dict.items()):<EOL><INDENT>new_lst = [n for n in lst if n in depend_dict]<EOL>if not new_lst:<EOL><INDENT>package_names.append(name)<EOL>del depend_dict[name]<EOL><DEDENT>else:<EOL><INDENT>depend_dict[name] = new_lst<EOL><DEDENT><DEDENT><DEDENT>return package_names<EOL>

Return package names sorted in the order as they should be
        imported due to dependence relations between packages.


import sys<EOL>self.info_modules = {}<EOL>self._init_info_modules(None)<EOL>titles = []<EOL>symbols = []<EOL>for package_name, info_module in self.info_modules.items():<EOL><INDENT>global_symbols = getattr(info_module, '<STR_LIT>', [])<EOL>fullname = self.parent_name +'<STR_LIT:.>'+ package_name<EOL>note = '<STR_LIT>'<EOL>if fullname not in sys.modules:<EOL><INDENT>note = '<STR_LIT>'<EOL><DEDENT>titles.append((fullname, self._get_doc_title(info_module) + note))<EOL>if global_symbols:<EOL><INDENT>symbols.append((package_name, '<STR_LIT:U+002CU+0020>'.join(global_symbols)))<EOL><DEDENT><DEDENT>retstr = self._format_titles(titles) +'<STR_LIT>'<EOL>if symbols:<EOL><INDENT>retstr += """<STR_LIT>""""""<STR_LIT>""" +self._format_titles(symbols, '<STR_LIT>')<EOL><DEDENT>return retstr<EOL>

Return documentation summary of subpackages.


def _get_info_files(self, package_dir, parent_path, parent_package=None):

from glob import glob<EOL>files = glob(os.path.join(parent_path, package_dir, '<STR_LIT>'))<EOL>for info_file in glob(os.path.join(parent_path, package_dir, '<STR_LIT>')):<EOL><INDENT>if info_file[:-<NUM_LIT:1>] not in files:<EOL><INDENT>files.append(info_file)<EOL><DEDENT><DEDENT>info_files = []<EOL>for info_file in files:<EOL><INDENT>package_name = os.path.dirname(info_file[len(parent_path)+<NUM_LIT:1>:]).replace(os.sep, '<STR_LIT:.>')<EOL>if parent_package:<EOL><INDENT>package_name = parent_package + '<STR_LIT:.>' + package_name<EOL><DEDENT>info_files.append((package_name, info_file))<EOL>info_files.extend(self._get_info_files('<STR_LIT:*>',<EOL>os.path.dirname(info_file),<EOL>package_name))<EOL><DEDENT>return info_files<EOL>

Return list of (package name,info.py file) from parent_path subdirectories.


frame = self.parent_frame<EOL>self.info_modules = {}<EOL>if options.get('<STR_LIT>', False):<EOL><INDENT>self.imported_packages = []<EOL><DEDENT>self.verbose = verbose = options.get('<STR_LIT>', -<NUM_LIT:1>)<EOL>postpone = options.get('<STR_LIT>', None)<EOL>self._init_info_modules(packages or None)<EOL>self.log('<STR_LIT>'% self.parent_name)<EOL>for package_name in self._get_sorted_names():<EOL><INDENT>if package_name in self.imported_packages:<EOL><INDENT>continue<EOL><DEDENT>info_module = self.info_modules[package_name]<EOL>global_symbols = getattr(info_module, '<STR_LIT>', [])<EOL>postpone_import = getattr(info_module, '<STR_LIT>', False)<EOL>if (postpone and not global_symbols)or (postpone_import and postpone is not None):<EOL><INDENT>continue<EOL><DEDENT>old_object = frame.f_locals.get(package_name, None)<EOL>cmdstr = '<STR_LIT>'+package_name<EOL>if self._execcmd(cmdstr):<EOL><INDENT>continue<EOL><DEDENT>self.imported_packages.append(package_name)<EOL>if verbose!=-<NUM_LIT:1>:<EOL><INDENT>new_object = frame.f_locals.get(package_name)<EOL>if old_object is not None and old_object is not new_object:<EOL><INDENT>self.warn('<STR_LIT>'% (package_name, self._obj2repr(new_object),<EOL>self._obj2repr(old_object)))<EOL><DEDENT><DEDENT>if '<STR_LIT:.>' not in package_name:<EOL><INDENT>self.parent_export_names.append(package_name)<EOL><DEDENT>for symbol in global_symbols:<EOL><INDENT>if symbol=='<STR_LIT:*>':<EOL><INDENT>symbols = eval('<STR_LIT>'% (package_name),<EOL>frame.f_globals, frame.f_locals)<EOL>if symbols is None:<EOL><INDENT>symbols = eval('<STR_LIT>' % (package_name),<EOL>frame.f_globals, frame.f_locals)<EOL>symbols = [s for s in symbols if not s.startswith('<STR_LIT:_>')]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>symbols = [symbol]<EOL><DEDENT>if verbose!=-<NUM_LIT:1>:<EOL><INDENT>old_objects = {}<EOL>for s in symbols:<EOL><INDENT>if s in frame.f_locals:<EOL><INDENT>old_objects[s] = frame.f_locals[s]<EOL><DEDENT><DEDENT><DEDENT>cmdstr = '<STR_LIT>'+package_name+'<STR_LIT>'+symbol<EOL>if self._execcmd(cmdstr):<EOL><INDENT>continue<EOL><DEDENT>if verbose!=-<NUM_LIT:1>:<EOL><INDENT>for s, old_object in old_objects.items():<EOL><INDENT>new_object = frame.f_locals[s]<EOL>if new_object is not old_object:<EOL><INDENT>self.warn('<STR_LIT>'% (s, self._obj2repr(new_object),<EOL>self._obj2repr(old_object)))<EOL><DEDENT><DEDENT><DEDENT>if symbol=='<STR_LIT:*>':<EOL><INDENT>self.parent_export_names.extend(symbols)<EOL><DEDENT>else:<EOL><INDENT>self.parent_export_names.append(symbol)<EOL><DEDENT><DEDENT><DEDENT>return<EOL>

Load one or more packages into parent package top-level namespace.

       This function is intended to shorten the need to import many
       subpackages, say of scipy, constantly with statements such as

         import scipy.linalg, scipy.fftpack, scipy.etc...

       Instead, you can say:

         import scipy
         scipy.pkgload('linalg','fftpack',...)

       or

         scipy.pkgload()

       to load all of them in one call.

       If a name which doesn't exist in scipy's namespace is
       given, a warning is shown.

       Parameters
       ----------
        *packages : arg-tuple
             the names (one or more strings) of all the modules one
             wishes to load into the top-level namespace.
        verbose= : integer
             verbosity level [default: -1].
             verbose=-1 will suspend also warnings.
        force= : bool
             when True, force reloading loaded packages [default: False].
        postpone= : bool
             when True, don't load packages [default: False]


return RandomState(seed=<NUM_LIT:0>)<EOL>

Return a RandomState instance.

    This function exists solely to assist (un)pickling.

    Note that the state of the RandomState returned here is irrelevant, as this function's
    entire purpose is to return a newly allocated RandomState whose state pickle can set.
    Consequently the RandomState returned by this function is a freshly allocated copy
    with a seed=0.

    See https://github.com/numpy/numpy/issues/4763 for a detailed discussion


<EOL>[c] = pu.as_series([c])<EOL>if len(c) == <NUM_LIT:1> and c[<NUM_LIT:0>] == <NUM_LIT:0>:<EOL><INDENT>return c<EOL><DEDENT>prd = np.empty(len(c) + <NUM_LIT:1>, dtype=c.dtype)<EOL>prd[<NUM_LIT:0>] = c[<NUM_LIT:0>]*<NUM_LIT:0><EOL>prd[<NUM_LIT:1>] = c[<NUM_LIT:0>]<EOL>if len(c) > <NUM_LIT:1>:<EOL><INDENT>tmp = c[<NUM_LIT:1>:]/<NUM_LIT:2><EOL>prd[<NUM_LIT:2>:] = tmp<EOL>prd[<NUM_LIT:0>:-<NUM_LIT:2>] += tmp<EOL><DEDENT>return prd<EOL>

Multiply a Chebyshev series by x.

    Multiply the polynomial `c` by x, where x is the independent
    variable.

    Parameters
    ----------
    c : array_like
        1-D array of Chebyshev series coefficients ordered from low to
        high.

    Returns
    -------
    out : ndarray
        Array representing the result of the multiplication.

    Notes
    -----

    .. versionadded:: 1.5.0


n = c.size<EOL>zs = np.zeros(<NUM_LIT:2>*n-<NUM_LIT:1>, dtype=c.dtype)<EOL>zs[n-<NUM_LIT:1>:] = c/<NUM_LIT:2><EOL>return zs + zs[::-<NUM_LIT:1>]<EOL>

Covert Chebyshev series to z-series.

    Covert a Chebyshev series to the equivalent z-series. The result is
    never an empty array. The dtype of the return is the same as that of
    the input. No checks are run on the arguments as this routine is for
    internal use.

    Parameters
    ----------
    c : 1-D ndarray
        Chebyshev coefficients, ordered from low to high

    Returns
    -------
    zs : 1-D ndarray
        Odd length symmetric z-series, ordered from  low to high.


try:<EOL><INDENT>x, y = np.array((x, y), copy=<NUM_LIT:0>)<EOL><DEDENT>except:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>c = chebval(x, c)<EOL>c = chebval(y, c, tensor=False)<EOL>return c<EOL>

Evaluate a 2-D Chebyshev series at points (x, y).

This function returns the values:

.. math:: p(x,y) = \\sum_{i,j} c_{i,j} * T_i(x) * T_j(y)

The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars and they
must have the same shape after conversion. In either case, either `x`
and `y` or their elements must support multiplication and addition both
with themselves and with the elements of `c`.

If `c` is a 1-D array a one is implicitly appended to its shape to make
it 2-D. The shape of the result will be c.shape[2:] + x.shape.

Parameters
----------
x, y : array_like, compatible objects
    The two dimensional series is evaluated at the points `(x, y)`,
    where `x` and `y` must have the same shape. If `x` or `y` is a list
    or tuple, it is first converted to an ndarray, otherwise it is left
    unchanged and if it isn't an ndarray it is treated as a scalar.
c : array_like
    Array of coefficients ordered so that the coefficient of the term
    of multi-degree i,j is contained in ``c[i,j]``. If `c` has
    dimension greater than 2 the remaining indices enumerate multiple
    sets of coefficients.

Returns
-------
values : ndarray, compatible object
    The values of the two dimensional Chebyshev series at points formed
    from pairs of corresponding values from `x` and `y`.

See Also
--------
chebval, chebgrid2d, chebval3d, chebgrid3d

Notes
-----

.. versionadded::1.7.0


c = chebval(x, c)<EOL>c = chebval(y, c)<EOL>c = chebval(z, c)<EOL>return c<EOL>

Evaluate a 3-D Chebyshev series on the Cartesian product of x, y, and z.

This function returns the values:

.. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * T_i(a) * T_j(b) * T_k(c)

where the points `(a, b, c)` consist of all triples formed by taking
`a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
a grid with `x` in the first dimension, `y` in the second, and `z` in
the third.

The parameters `x`, `y`, and `z` are converted to arrays only if they
are tuples or a lists, otherwise they are treated as a scalars. In
either case, either `x`, `y`, and `z` or their elements must support
multiplication and addition both with themselves and with the elements
of `c`.

If `c` has fewer than three dimensions, ones are implicitly appended to
its shape to make it 3-D. The shape of the result will be c.shape[3:] +
x.shape + y.shape + z.shape.

Parameters
----------
x, y, z : array_like, compatible objects
    The three dimensional series is evaluated at the points in the
    Cartesian product of `x`, `y`, and `z`.  If `x`,`y`, or `z` is a
    list or tuple, it is first converted to an ndarray, otherwise it is
    left unchanged and, if it isn't an ndarray, it is treated as a
    scalar.
c : array_like
    Array of coefficients ordered so that the coefficients for terms of
    degree i,j are contained in ``c[i,j]``. If `c` has dimension
    greater than two the remaining indices enumerate multiple sets of
    coefficients.

Returns
-------
values : ndarray, compatible object
    The values of the two dimensional polynomial at points in the Cartesian
    product of `x` and `y`.

See Also
--------
chebval, chebval2d, chebgrid2d, chebval3d

Notes
-----

.. versionadded::1.7.0


n = (zs.size + <NUM_LIT:1>)//<NUM_LIT:2><EOL>c = zs[n-<NUM_LIT:1>:].copy()<EOL>c[<NUM_LIT:1>:n] *= <NUM_LIT:2><EOL>return c<EOL>

Covert z-series to a Chebyshev series.

    Covert a z series to the equivalent Chebyshev series. The result is
    never an empty array. The dtype of the return is the same as that of
    the input. No checks are run on the arguments as this routine is for
    internal use.

    Parameters
    ----------
    zs : 1-D ndarray
        Odd length symmetric z-series, ordered from  low to high.

    Returns
    -------
    c : 1-D ndarray
        Chebyshev coefficients, ordered from  low to high.


<EOL>[c1, c2] = pu.as_series([c1, c2])<EOL>z1 = _cseries_to_zseries(c1)<EOL>z2 = _cseries_to_zseries(c2)<EOL>prd = _zseries_mul(z1, z2)<EOL>ret = _zseries_to_cseries(prd)<EOL>return pu.trimseq(ret)<EOL>

Multiply one Chebyshev series by another.

Returns the product of two Chebyshev series `c1` * `c2`.  The arguments
are sequences of coefficients, from lowest order "term" to highest,
e.g., [1,2,3] represents the series ``T_0 + 2*T_1 + 3*T_2``.

Parameters
----------
c1, c2 : array_like
    1-D arrays of Chebyshev series coefficients ordered from low to
    high.

Returns
-------
out : ndarray
    Of Chebyshev series coefficients representing their product.

See Also
--------
chebadd, chebsub, chebdiv, chebpow

Notes
-----
In general, the (polynomial) product of two C-series results in terms
that are not in the Chebyshev polynomial basis set.  Thus, to express
the product as a C-series, it is typically necessary to "reproject"
the product onto said basis set, which typically produces
"unintuitive live" (but correct) results; see Examples section below.

Examples
--------
>>> from numpy.polynomial import chebyshev as C
>>> c1 = (1,2,3)
>>> c2 = (3,2,1)
>>> C.chebmul(c1,c2) # multiplication requires "reprojection"
array([  6.5,  12. ,  12. ,   4. ,   1.5])


if len(roots) == <NUM_LIT:0>:<EOL><INDENT>return np.ones(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>[roots] = pu.as_series([roots], trim=False)<EOL>roots.sort()<EOL>p = [chebline(-r, <NUM_LIT:1>) for r in roots]<EOL>n = len(p)<EOL>while n > <NUM_LIT:1>:<EOL><INDENT>m, r = divmod(n, <NUM_LIT:2>)<EOL>tmp = [chebmul(p[i], p[i+m]) for i in range(m)]<EOL>if r:<EOL><INDENT>tmp[<NUM_LIT:0>] = chebmul(tmp[<NUM_LIT:0>], p[-<NUM_LIT:1>])<EOL><DEDENT>p = tmp<EOL>n = m<EOL><DEDENT>return p[<NUM_LIT:0>]<EOL><DEDENT>

Generate a Chebyshev series with given roots.

The function returns the coefficients of the polynomial

.. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),

in Chebyshev form, where the `r_n` are the roots specified in `roots`.
If a zero has multiplicity n, then it must appear in `roots` n times.
For instance, if 2 is a root of multiplicity three and 3 is a root of
multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The
roots can appear in any order.

If the returned coefficients are `c`, then

.. math:: p(x) = c_0 + c_1 * T_1(x) + ... +  c_n * T_n(x)

The coefficient of the last term is not generally 1 for monic
polynomials in Chebyshev form.

Parameters
----------
roots : array_like
    Sequence containing the roots.

Returns
-------
out : ndarray
    1-D array of coefficients.  If all roots are real then `out` is a
    real array, if some of the roots are complex, then `out` is complex
    even if all the coefficients in the result are real (see Examples
    below).

See Also
--------
polyfromroots, legfromroots, lagfromroots, hermfromroots,
hermefromroots.

Examples
--------
>>> import numpy.polynomial.chebyshev as C
>>> C.chebfromroots((-1,0,1)) # x^3 - x relative to the standard basis
array([ 0.  , -0.25,  0.  ,  0.25])
>>> j = complex(0,1)
>>> C.chebfromroots((-j,j)) # x^2 + 1 relative to the standard basis
array([ 1.5+0.j,  0.0+0.j,  0.5+0.j])


return np.convolve(z1, z2)<EOL>

Multiply two z-series.

    Multiply two z-series to produce a z-series.

    Parameters
    ----------
    z1, z2 : 1-D ndarray
        The arrays must be 1-D but this is not checked.

    Returns
    -------
    product : 1-D ndarray
        The product z-series.

    Notes
    -----
    This is simply convolution. If symmetric/anti-symmetric z-series are
    denoted by S/A then the following rules apply:

    S*S, A*A -> S
    S*A, A*S -> A


if scl != <NUM_LIT:0>:<EOL><INDENT>return np.array([off, scl])<EOL><DEDENT>else:<EOL><INDENT>return np.array([off])<EOL><DEDENT>

Chebyshev series whose graph is a straight line.

Parameters
----------
off, scl : scalars
    The specified line is given by ``off + scl*x``.

Returns
-------
y : ndarray
    This module's representation of the Chebyshev series for
    ``off + scl*x``.

See Also
--------
polyline

Examples
--------
>>> import numpy.polynomial.chebyshev as C
>>> C.chebline(3,2)
array([3, 2])
>>> C.chebval(-3, C.chebline(3,2)) # should be -3
-3.0


_npts = int(npts)<EOL>if _npts != npts:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if _npts < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>x = np.linspace(-np.pi, <NUM_LIT:0>, _npts, endpoint=False) + np.pi/(<NUM_LIT:2>*_npts)<EOL>return np.cos(x)<EOL>

Chebyshev points of the first kind.

The Chebyshev points of the first kind are the points ``cos(x)``,
where ``x = [pi*(k + .5)/npts for k in range(npts)]``.

Parameters
----------
npts : int
    Number of sample points desired.

Returns
-------
pts : ndarray
    The Chebyshev points of the first kind.

See Also
--------
chebpts2

Notes
-----

.. versionadded:: 1.5.0


<EOL>[c] = pu.as_series([c])<EOL>if len(c) < <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if len(c) == <NUM_LIT:2>:<EOL><INDENT>return np.array([[-c[<NUM_LIT:0>]/c[<NUM_LIT:1>]]])<EOL><DEDENT>n = len(c) - <NUM_LIT:1><EOL>mat = np.zeros((n, n), dtype=c.dtype)<EOL>scl = np.array([<NUM_LIT:1.>] + [np.sqrt(<NUM_LIT>)]*(n-<NUM_LIT:1>))<EOL>top = mat.reshape(-<NUM_LIT:1>)[<NUM_LIT:1>::n+<NUM_LIT:1>]<EOL>bot = mat.reshape(-<NUM_LIT:1>)[n::n+<NUM_LIT:1>]<EOL>top[<NUM_LIT:0>] = np.sqrt(<NUM_LIT>)<EOL>top[<NUM_LIT:1>:] = <NUM_LIT:1>/<NUM_LIT:2><EOL>bot[...] = top<EOL>mat[:, -<NUM_LIT:1>] -= (c[:-<NUM_LIT:1>]/c[-<NUM_LIT:1>])*(scl/scl[-<NUM_LIT:1>])*<NUM_LIT><EOL>return mat<EOL>

Return the scaled companion matrix of c.

    The basis polynomials are scaled so that the companion matrix is
    symmetric when `c` is aa Chebyshev basis polynomial. This provides
    better eigenvalue estimates than the unscaled case and for basis
    polynomials the eigenvalues are guaranteed to be real if
    `numpy.linalg.eigvalsh` is used to obtain them.

    Parameters
    ----------
    c : array_like
        1-D array of Chebyshev series coefficients ordered from low to high
        degree.

    Returns
    -------
    mat : ndarray
        Scaled companion matrix of dimensions (deg, deg).

    Notes
    -----

    .. versionadded::1.7.0


[pol] = pu.as_series([pol])<EOL>deg = len(pol) - <NUM_LIT:1><EOL>res = <NUM_LIT:0><EOL>for i in range(deg, -<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>res = legadd(legmulx(res), pol[i])<EOL><DEDENT>return res<EOL>

Convert a polynomial to a Legendre series.

Convert an array representing the coefficients of a polynomial (relative
to the "standard" basis) ordered from lowest degree to highest, to an
array of the coefficients of the equivalent Legendre series, ordered
from lowest to highest degree.

Parameters
----------
pol : array_like
    1-D array containing the polynomial coefficients

Returns
-------
c : ndarray
    1-D array containing the coefficients of the equivalent Legendre
    series.

See Also
--------
leg2poly

Notes
-----
The easy way to do conversions between polynomial basis sets
is to use the convert method of a class instance.

Examples
--------
>>> from numpy import polynomial as P
>>> p = P.Polynomial(np.arange(4))
>>> p
Polynomial([ 0.,  1.,  2.,  3.], [-1.,  1.])
>>> c = P.Legendre(P.poly2leg(p.coef))
>>> c
Legendre([ 1.  ,  3.25,  1.  ,  0.75], [-1.,  1.])


<EOL>[c] = pu.as_series([c])<EOL>if len(c) == <NUM_LIT:1> and c[<NUM_LIT:0>] == <NUM_LIT:0>:<EOL><INDENT>return c<EOL><DEDENT>prd = np.empty(len(c) + <NUM_LIT:1>, dtype=c.dtype)<EOL>prd[<NUM_LIT:0>] = c[<NUM_LIT:0>]*<NUM_LIT:0><EOL>prd[<NUM_LIT:1>] = c[<NUM_LIT:0>]<EOL>for i in range(<NUM_LIT:1>, len(c)):<EOL><INDENT>j = i + <NUM_LIT:1><EOL>k = i - <NUM_LIT:1><EOL>s = i + j<EOL>prd[j] = (c[i]*j)/s<EOL>prd[k] += (c[i]*i)/s<EOL><DEDENT>return prd<EOL>

Multiply a Legendre series by x.

    Multiply the Legendre series `c` by x, where x is the independent
    variable.

    Parameters
    ----------
    c : array_like
        1-D array of Legendre series coefficients ordered from low to
        high.

    Returns
    -------
    out : ndarray
        Array representing the result of the multiplication.

    Notes
    -----
    The multiplication uses the recursion relationship for Legendre
    polynomials in the form

    .. math::

      xP_i(x) = ((i + 1)*P_{i + 1}(x) + i*P_{i - 1}(x))/(2i + 1)


<EOL>[c] = pu.as_series([c])<EOL>if len(c) < <NUM_LIT:2>:<EOL><INDENT>return np.array([], dtype=c.dtype)<EOL><DEDENT>if len(c) == <NUM_LIT:2>:<EOL><INDENT>return np.array([-c[<NUM_LIT:0>]/c[<NUM_LIT:1>]])<EOL><DEDENT>m = legcompanion(c)<EOL>r = la.eigvals(m)<EOL>r.sort()<EOL>return r<EOL>

Compute the roots of a Legendre series.

Return the roots (a.k.a. "zeros") of the polynomial

.. math:: p(x) = \\sum_i c[i] * L_i(x).

Parameters
----------
c : 1-D array_like
    1-D array of coefficients.

Returns
-------
out : ndarray
    Array of the roots of the series. If all the roots are real,
    then `out` is also real, otherwise it is complex.

See Also
--------
polyroots, chebroots, lagroots, hermroots, hermeroots

Notes
-----
The root estimates are obtained as the eigenvalues of the companion
matrix, Roots far from the origin of the complex plane may have large
errors due to the numerical instability of the series for such values.
Roots with multiplicity greater than 1 will also show larger errors as
the value of the series near such points is relatively insensitive to
errors in the roots. Isolated roots near the origin can be improved by
a few iterations of Newton's method.

The Legendre series basis polynomials aren't powers of ``x`` so the
results of this function may seem unintuitive.

Examples
--------
>>> import numpy.polynomial.legendre as leg
>>> leg.legroots((1, 2, 3, 4)) # 4L_3 + 3L_2 + 2L_1 + 1L_0, all real roots
array([-0.85099543, -0.11407192,  0.51506735])


try:<EOL><INDENT>x, y, z = np.array((x, y, z), copy=<NUM_LIT:0>)<EOL><DEDENT>except:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>c = legval(x, c)<EOL>c = legval(y, c, tensor=False)<EOL>c = legval(z, c, tensor=False)<EOL>return c<EOL>

Evaluate a 3-D Legendre series at points (x, y, z).

This function returns the values:

.. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * L_i(x) * L_j(y) * L_k(z)

The parameters `x`, `y`, and `z` are converted to arrays only if
they are tuples or a lists, otherwise they are treated as a scalars and
they must have the same shape after conversion. In either case, either
`x`, `y`, and `z` or their elements must support multiplication and
addition both with themselves and with the elements of `c`.

If `c` has fewer than 3 dimensions, ones are implicitly appended to its
shape to make it 3-D. The shape of the result will be c.shape[3:] +
x.shape.

Parameters
----------
x, y, z : array_like, compatible object
    The three dimensional series is evaluated at the points
    `(x, y, z)`, where `x`, `y`, and `z` must have the same shape.  If
    any of `x`, `y`, or `z` is a list or tuple, it is first converted
    to an ndarray, otherwise it is left unchanged and if it isn't an
    ndarray it is  treated as a scalar.
c : array_like
    Array of coefficients ordered so that the coefficient of the term of
    multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension
    greater than 3 the remaining indices enumerate multiple sets of
    coefficients.

Returns
-------
values : ndarray, compatible object
    The values of the multidimensional polynomial on points formed with
    triples of corresponding values from `x`, `y`, and `z`.

See Also
--------
legval, legval2d, leggrid2d, leggrid3d

Notes
-----

.. versionadded::1.7.0


c = np.array(c, ndmin=<NUM_LIT:1>, copy=<NUM_LIT:0>)<EOL>if c.dtype.char in '<STR_LIT>':<EOL><INDENT>c = c.astype(np.double)<EOL><DEDENT>if isinstance(x, (tuple, list)):<EOL><INDENT>x = np.asarray(x)<EOL><DEDENT>if isinstance(x, np.ndarray) and tensor:<EOL><INDENT>c = c.reshape(c.shape + (<NUM_LIT:1>,)*x.ndim)<EOL><DEDENT>if len(c) == <NUM_LIT:1>:<EOL><INDENT>c0 = c[<NUM_LIT:0>]<EOL>c1 = <NUM_LIT:0><EOL><DEDENT>elif len(c) == <NUM_LIT:2>:<EOL><INDENT>c0 = c[<NUM_LIT:0>]<EOL>c1 = c[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>nd = len(c)<EOL>c0 = c[-<NUM_LIT:2>]<EOL>c1 = c[-<NUM_LIT:1>]<EOL>for i in range(<NUM_LIT:3>, len(c) + <NUM_LIT:1>):<EOL><INDENT>tmp = c0<EOL>nd = nd - <NUM_LIT:1><EOL>c0 = c[-i] - (c1*(nd - <NUM_LIT:1>))/nd<EOL>c1 = tmp + (c1*x*(<NUM_LIT:2>*nd - <NUM_LIT:1>))/nd<EOL><DEDENT><DEDENT>return c0 + c1*x<EOL>

Evaluate a Legendre series at points x.

If `c` is of length `n + 1`, this function returns the value:

.. math:: p(x) = c_0 * L_0(x) + c_1 * L_1(x) + ... + c_n * L_n(x)

The parameter `x` is converted to an array only if it is a tuple or a
list, otherwise it is treated as a scalar. In either case, either `x`
or its elements must support multiplication and addition both with
themselves and with the elements of `c`.

If `c` is a 1-D array, then `p(x)` will have the same shape as `x`.  If
`c` is multidimensional, then the shape of the result depends on the
value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
scalars have shape (,).

Trailing zeros in the coefficients will be used in the evaluation, so
they should be avoided if efficiency is a concern.

Parameters
----------
x : array_like, compatible object
    If `x` is a list or tuple, it is converted to an ndarray, otherwise
    it is left unchanged and treated as a scalar. In either case, `x`
    or its elements must support addition and multiplication with
    with themselves and with the elements of `c`.
c : array_like
    Array of coefficients ordered so that the coefficients for terms of
    degree n are contained in c[n]. If `c` is multidimensional the
    remaining indices enumerate multiple polynomials. In the two
    dimensional case the coefficients may be thought of as stored in
    the columns of `c`.
tensor : boolean, optional
    If True, the shape of the coefficient array is extended with ones
    on the right, one for each dimension of `x`. Scalars have dimension 0
    for this action. The result is that every column of coefficients in
    `c` is evaluated for every element of `x`. If False, `x` is broadcast
    over the columns of `c` for the evaluation.  This keyword is useful
    when `c` is multidimensional. The default value is True.

    .. versionadded:: 1.7.0

Returns
-------
values : ndarray, algebra_like
    The shape of the return value is described above.

See Also
--------
legval2d, leggrid2d, legval3d, leggrid3d

Notes
-----
The evaluation uses Clenshaw recursion, aka synthetic division.

Examples
--------