_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q269400
register
test
def register(linter): """Register the reporter classes with the linter.""" linter.register_reporter(TextReporter) linter.register_reporter(ParseableTextReporter) linter.register_reporter(VSTextReporter) linter.register_reporter(ColorizedTextReporter)
python
{ "resource": "" }
q269401
TextReporter.handle_message
test
def handle_message(self, msg): """manage message of different type and in the context of path""" if msg.module not in self._modules: if msg.module: self.writeln("************* Module %s" % msg.module) self._modules.add(msg.module) else: ...
python
{ "resource": "" }
q269402
TextReporter._display
test
def _display(self, layout): """launch layouts display""" print(file=self.out) TextWriter().format(layout, self.out)
python
{ "resource": "" }
q269403
ColorizedTextReporter.handle_message
test
def handle_message(self, msg): """manage message of different types, and colorize output using ansi escape codes """ if msg.module not in self._modules: color, style = self._get_decoration("S") if msg.module: modsep = colorize_ansi( ...
python
{ "resource": "" }
q269404
VCGPrinter.open_graph
test
def open_graph(self, **args): """open a vcg graph """ self._stream.write("%sgraph:{\n" % self._indent) self._inc_indent() self._write_attributes(GRAPH_ATTRS, **args)
python
{ "resource": "" }
q269405
VCGPrinter.node
test
def node(self, title, **args): """draw a node """ self._stream.write('%snode: {title:"%s"' % (self._indent, title)) self._write_attributes(NODE_ATTRS, **args) self._stream.write("}\n")
python
{ "resource": "" }
q269406
VCGPrinter.edge
test
def edge(self, from_node, to_node, edge_type="", **args): """draw an edge from a node to another. """ self._stream.write( '%s%sedge: {sourcename:"%s" targetname:"%s"' % (self._indent, edge_type, from_node, to_node) ) self._write_attributes(EDGE_ATTRS, **ar...
python
{ "resource": "" }
q269407
StringFormatChecker._check_new_format
test
def _check_new_format(self, node, func): """ Check the new string formatting. """ # TODO: skip (for now) format nodes which don't have # an explicit string on the left side of the format operation. # We do this because our inference engine can't properly handle # ...
python
{ "resource": "" }
q269408
StringConstantChecker.process_non_raw_string_token
test
def process_non_raw_string_token(self, prefix, string_body, start_row): """check for bad escapes in a non-raw string. prefix: lowercase string of eg 'ur' string prefix markers. string_body: the un-parsed body of the string, not including the quote marks. start_row: integer line ...
python
{ "resource": "" }
q269409
TextWriter.visit_section
test
def visit_section(self, layout): """display a section as text """ self.section += 1 self.writeln() self.format_children(layout) self.section -= 1 self.writeln()
python
{ "resource": "" }
q269410
TextWriter.visit_evaluationsection
test
def visit_evaluationsection(self, layout): """Display an evaluation section as a text.""" self.section += 1 self.format_children(layout) self.section -= 1 self.writeln()
python
{ "resource": "" }
q269411
TextWriter.visit_table
test
def visit_table(self, layout): """display a table as text""" table_content = self.get_table_content(layout) # get columns width cols_width = [0] * len(table_content[0]) for row in table_content: for index, col in enumerate(row): cols_width[index] = max...
python
{ "resource": "" }
q269412
TextWriter.default_table
test
def default_table(self, layout, table_content, cols_width): """format a table""" cols_width = [size + 1 for size in cols_width] format_strings = " ".join(["%%-%ss"] * len(cols_width)) format_strings = format_strings % tuple(cols_width) format_strings = format_strings.split(" ") ...
python
{ "resource": "" }
q269413
MessagesStore.add_renamed_message
test
def add_renamed_message(self, old_id, old_symbol, new_symbol): """Register the old ID and symbol for a warning that was renamed. This allows users to keep using the old ID/symbol in suppressions. """ message_definition = self.get_message_definitions(new_symbol)[0] message_defini...
python
{ "resource": "" }
q269414
MessagesStore.register_messages_from_checker
test
def register_messages_from_checker(self, checker): """Register all messages from a checker. :param BaseChecker checker: """ checker.check_consistency() for message in checker.messages: self.register_message(message)
python
{ "resource": "" }
q269415
MessagesStore.register_message
test
def register_message(self, message): """Register a MessageDefinition with consistency in mind. :param MessageDefinition message: The message definition being added. """ self._check_id_and_symbol_consistency(message.msgid, message.symbol) self._check_symbol(message.msgid, message...
python
{ "resource": "" }
q269416
MessagesStore._check_symbol
test
def _check_symbol(self, msgid, symbol): """Check that a symbol is not already used. """ other_message = self._messages_definitions.get(symbol) if other_message: self._raise_duplicate_msg_id(symbol, msgid, other_message.msgid) else: alternative_msgid = None ...
python
{ "resource": "" }
q269417
MessagesStore._raise_duplicate_symbol
test
def _raise_duplicate_symbol(msgid, symbol, other_symbol): """Raise an error when a symbol is duplicated. :param str msgid: The msgid corresponding to the symbols :param str symbol: Offending symbol :param str other_symbol: Other offending symbol :raises InvalidMessageError: when...
python
{ "resource": "" }
q269418
MessagesStore._raise_duplicate_msg_id
test
def _raise_duplicate_msg_id(symbol, msgid, other_msgid): """Raise an error when a msgid is duplicated. :param str symbol: The symbol corresponding to the msgids :param str msgid: Offending msgid :param str other_msgid: Other offending msgid :raises InvalidMessageError: when a ms...
python
{ "resource": "" }
q269419
MessagesStore.get_message_definitions
test
def get_message_definitions(self, msgid_or_symbol: str) -> list: """Returns the Message object for this message. :param str msgid_or_symbol: msgid_or_symbol may be either a numeric or symbolic id. :raises UnknownMessageError: if the message id is not defined. :rtype: List of MessageDefi...
python
{ "resource": "" }
q269420
MessagesStore.get_msg_display_string
test
def get_msg_display_string(self, msgid): """Generates a user-consumable representation of a message. Can be just the message ID or the ID and the symbol. """ message_definitions = self.get_message_definitions(msgid) if len(message_definitions) == 1: return repr(messa...
python
{ "resource": "" }
q269421
MessagesStore.help_message
test
def help_message(self, msgids): """Display help messages for the given message identifiers""" for msgid in msgids: try: for message_definition in self.get_message_definitions(msgid): print(message_definition.format_help(checkerref=True)) ...
python
{ "resource": "" }
q269422
MessagesStore.list_messages
test
def list_messages(self): """Output full messages list documentation in ReST format. """ messages = sorted(self._messages_definitions.values(), key=lambda m: m.msgid) for message in messages: if not message.may_be_emitted(): continue print(message.format_he...
python
{ "resource": "" }
q269423
builder_inited
test
def builder_inited(app): """Output full documentation in ReST format for all extension modules""" # PACKAGE/docs/exts/pylint_extensions.py --> PACKAGE/ base_path = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ) # PACKAGE/ --> PACKAGE/pylint/extensions ext_...
python
{ "resource": "" }
q269424
_cpu_count
test
def _cpu_count() -> int: """Use sched_affinity if available for virtualized or containerized environments.""" sched_getaffinity = getattr(os, "sched_getaffinity", None) # pylint: disable=not-callable,using-constant-test if sched_getaffinity: return len(sched_getaffinity(0)) if multiprocessin...
python
{ "resource": "" }
q269425
report_messages_stats
test
def report_messages_stats(sect, stats, _): """make messages type report""" if not stats["by_msg"]: # don't print this report when we didn't detected any errors raise exceptions.EmptyReportError() in_order = sorted( [ (value, msg_id) for msg_id, value in stats[...
python
{ "resource": "" }
q269426
fix_import_path
test
def fix_import_path(args): """Prepare sys.path for running the linter checks. Within this context, each of the given arguments is importable. Paths are added to sys.path in corresponding order to the arguments. We avoid adding duplicate directories to sys.path. `sys.path` is reset to its original v...
python
{ "resource": "" }
q269427
PyLinter.load_plugin_modules
test
def load_plugin_modules(self, modnames): """take a list of module names which are pylint plugins and load and register them """ for modname in modnames: if modname in self._dynamic_plugins: continue self._dynamic_plugins.add(modname) mo...
python
{ "resource": "" }
q269428
PyLinter.load_plugin_configuration
test
def load_plugin_configuration(self): """Call the configuration hook for plugins This walks through the list of plugins, grabs the "load_configuration" hook, if exposed, and calls it to allow plugins to configure specific settings. """ for modname in self._dynamic_plugins...
python
{ "resource": "" }
q269429
PyLinter.set_option
test
def set_option(self, optname, value, action=None, optdict=None): """overridden from config.OptionsProviderMixin to handle some special options """ if optname in self._options_methods or optname in self._bw_options_methods: if value: try: me...
python
{ "resource": "" }
q269430
PyLinter.register_checker
test
def register_checker(self, checker): """register a new checker checker is an object implementing IRawChecker or / and IAstroidChecker """ assert checker.priority <= 0, "checker priority can't be >= 0" self._checkers[checker.name].append(checker) for r_id, r_title, r_cb i...
python
{ "resource": "" }
q269431
PyLinter.disable_reporters
test
def disable_reporters(self): """disable all reporters""" for _reporters in self._reports.values(): for report_id, _, _ in _reporters: self.disable_report(report_id)
python
{ "resource": "" }
q269432
PyLinter.python3_porting_mode
test
def python3_porting_mode(self): """Disable all other checkers and enable Python 3 warnings.""" self.disable("all") self.enable("python3") if self._error_mode: # The error mode was activated, using the -E flag. # So we'll need to enable only the errors from the ...
python
{ "resource": "" }
q269433
PyLinter.get_checkers
test
def get_checkers(self): """return all available checkers as a list""" return [self] + [ c for _checkers in self._checkers.values() for c in _checkers if c is not self ]
python
{ "resource": "" }
q269434
PyLinter.get_checker_names
test
def get_checker_names(self): """Get all the checker names that this linter knows about.""" current_checkers = self.get_checkers() return sorted( {check.name for check in current_checkers if check.name != "master"} )
python
{ "resource": "" }
q269435
PyLinter.prepare_checkers
test
def prepare_checkers(self): """return checkers needed for activated messages and reports""" if not self.config.reports: self.disable_reporters() # get needed checkers neededcheckers = [self] for checker in self.get_checkers()[1:]: messages = {msg for msg i...
python
{ "resource": "" }
q269436
PyLinter.expand_files
test
def expand_files(self, modules): """get modules and errors from a list of modules and handle errors """ result, errors = utils.expand_modules( modules, self.config.black_list, self.config.black_list_re ) for error in errors: message = modname = error["mod"...
python
{ "resource": "" }
q269437
PyLinter.set_current_module
test
def set_current_module(self, modname, filepath=None): """set the name of the currently analyzed module and init statistics for it """ if not modname and filepath is None: return self.reporter.on_set_current_module(modname, filepath) self.current_name = modname...
python
{ "resource": "" }
q269438
PyLinter.check_astroid_module
test
def check_astroid_module(self, ast_node, walker, rawcheckers, tokencheckers): """Check a module from its astroid representation.""" try: tokens = utils.tokenize_module(ast_node) except tokenize.TokenError as ex: self.add_message("syntax-error", line=ex.args[1][0], args=ex...
python
{ "resource": "" }
q269439
PyLinter._report_evaluation
test
def _report_evaluation(self): """make the global evaluation report""" # check with at least check 1 statements (usually 0 when there is a # syntax error preventing pylint from further processing) previous_stats = config.load_results(self.file_state.base_name) if self.stats["state...
python
{ "resource": "" }
q269440
Run.cb_help_message
test
def cb_help_message(self, option, optname, value, parser): """optik callback for printing some help about a particular message""" self.linter.msgs_store.help_message(utils._splitstrip(value)) sys.exit(0)
python
{ "resource": "" }
q269441
Run.cb_full_documentation
test
def cb_full_documentation(self, option, optname, value, parser): """optik callback for printing full documentation""" self.linter.print_full_documentation() sys.exit(0)
python
{ "resource": "" }
q269442
Run.cb_list_messages
test
def cb_list_messages(self, option, optname, value, parser): # FIXME """optik callback for printing available messages""" self.linter.msgs_store.list_messages() sys.exit(0)
python
{ "resource": "" }
q269443
Run.cb_list_groups
test
def cb_list_groups(self, *args, **kwargs): """List all the check groups that pylint knows about These should be useful to know what check groups someone can disable or enable. """ for check in self.linter.get_checker_names(): print(check) sys.exit(0)
python
{ "resource": "" }
q269444
normalize_text
test
def normalize_text(text, line_len=80, indent=""): """Wrap the text on the given line length.""" return "\n".join( textwrap.wrap( text, width=line_len, initial_indent=indent, subsequent_indent=indent ) )
python
{ "resource": "" }
q269445
get_module_and_frameid
test
def get_module_and_frameid(node): """return the module name and the frame id in the module""" frame = node.frame() module, obj = "", [] while frame: if isinstance(frame, Module): module = frame.name else: obj.append(getattr(frame, "name", "<lambda>")) try:...
python
{ "resource": "" }
q269446
safe_decode
test
def safe_decode(line, encoding, *args, **kwargs): """return decoded line from encoding or decode with default encoding""" try: return line.decode(encoding or sys.getdefaultencoding(), *args, **kwargs) except LookupError: return line.decode(sys.getdefaultencoding(), *args, **kwargs)
python
{ "resource": "" }
q269447
_basename_in_blacklist_re
test
def _basename_in_blacklist_re(base_name, black_list_re): """Determines if the basename is matched in a regex blacklist :param str base_name: The basename of the file :param list black_list_re: A collection of regex patterns to match against. Successful matches are blacklisted. :returns: `True`...
python
{ "resource": "" }
q269448
register_plugins
test
def register_plugins(linter, directory): """load all module and package in the given directory, looking for a 'register' function in each one, used to register pylint checkers """ imported = {} for filename in listdir(directory): base, extension = splitext(filename) if base in import...
python
{ "resource": "" }
q269449
_comment
test
def _comment(string): """return string as a comment""" lines = [line.strip() for line in string.splitlines()] return "# " + ("%s# " % linesep).join(lines)
python
{ "resource": "" }
q269450
_format_option_value
test
def _format_option_value(optdict, value): """return the user input's value from a 'compiled' value""" if isinstance(value, (list, tuple)): value = ",".join(_format_option_value(optdict, item) for item in value) elif isinstance(value, dict): value = ",".join("%s:%s" % (k, v) for k, v in value...
python
{ "resource": "" }
q269451
format_section
test
def format_section(stream, section, options, doc=None): """format an options section using the INI format""" if doc: print(_comment(doc), file=stream) print("[%s]" % section, file=stream) _ini_format(stream, options)
python
{ "resource": "" }
q269452
_ini_format
test
def _ini_format(stream, options): """format options using the INI format""" for optname, optdict, value in options: value = _format_option_value(optdict, value) help_opt = optdict.get("help") if help_opt: help_opt = normalize_text(help_opt, line_len=79, indent="# ") ...
python
{ "resource": "" }
q269453
VNode.insert
test
def insert(self, index, child): """insert a child node""" self.children.insert(index, child) child.parent = self
python
{ "resource": "" }
q269454
BaseLayout.append
test
def append(self, child): """overridden to detect problems easily""" assert child not in self.parents() VNode.append(self, child)
python
{ "resource": "" }
q269455
BaseLayout.parents
test
def parents(self): """return the ancestor nodes""" assert self.parent is not self if self.parent is None: return [] return [self.parent] + self.parent.parents()
python
{ "resource": "" }
q269456
BaseWriter.format
test
def format(self, layout, stream=None, encoding=None): """format and write the given layout into the stream object unicode policy: unicode strings may be found in the layout; try to call stream.write with it, but give it back encoded using the given encoding if it fails """ ...
python
{ "resource": "" }
q269457
BaseWriter.get_table_content
test
def get_table_content(self, table): """trick to get table content without actually writing it return an aligned list of lists containing table cells values as string """ result = [[]] cols = table.cols for cell in self.compute_content(table): if cols == 0: ...
python
{ "resource": "" }
q269458
BaseWriter.compute_content
test
def compute_content(self, layout): """trick to compute the formatting of children layout before actually writing it return an iterator on strings (one for each child element) """ # Patch the underlying output stream with a fresh-generated stream, # which is used to store...
python
{ "resource": "" }
q269459
FileState.collect_block_lines
test
def collect_block_lines(self, msgs_store, module_node): """Walk the AST to collect block level options line numbers.""" for msg, lines in self._module_msgs_state.items(): self._raw_module_msgs_state[msg] = lines.copy() orig_state = self._module_msgs_state.copy() self._module_...
python
{ "resource": "" }
q269460
FileState.handle_ignored_message
test
def handle_ignored_message( self, state_scope, msgid, line, node, args, confidence ): # pylint: disable=unused-argument """Report an ignored message. state_scope is either MSG_STATE_SCOPE_MODULE or MSG_STATE_SCOPE_CONFIG, depending on whether the message was disabled locally in the...
python
{ "resource": "" }
q269461
ReportsHandlerMixIn.register_report
test
def register_report(self, reportid, r_title, r_cb, checker): """register a report reportid is the unique identifier for the report r_title the report's title r_cb the method to call to make the report checker is the checker defining the report """ reportid = repo...
python
{ "resource": "" }
q269462
ReportsHandlerMixIn.make_reports
test
def make_reports(self, stats, old_stats): """render registered reports""" sect = Section("Report", "%s statements analysed." % (self.stats["statement"])) for checker in self.report_order(): for reportid, r_title, r_cb in self._reports[checker]: if not self.report_is_e...
python
{ "resource": "" }
q269463
ReportsHandlerMixIn.add_stats
test
def add_stats(self, **kwargs): """add some stats entries to the statistic dictionary raise an AssertionError if there is a key conflict """ for key, value in kwargs.items(): if key[-1] == "_": key = key[:-1] assert key not in self.stats ...
python
{ "resource": "" }
q269464
get_setters_property_name
test
def get_setters_property_name(node): """Get the name of the property that the given node is a setter for. :param node: The node to get the property name for. :type node: str :rtype: str or None :returns: The name of the property that the node is a setter for, or None if one could not be fo...
python
{ "resource": "" }
q269465
get_setters_property
test
def get_setters_property(node): """Get the property node for the given setter node. :param node: The node to get the property for. :type node: astroid.FunctionDef :rtype: astroid.FunctionDef or None :returns: The node relating to the property of the given setter node, or None if one could ...
python
{ "resource": "" }
q269466
returns_something
test
def returns_something(return_node): """Check if a return node returns a value other than None. :param return_node: The return node to check. :type return_node: astroid.Return :rtype: bool :return: True if the return node returns a value other than None, False otherwise. """ returns...
python
{ "resource": "" }
q269467
possible_exc_types
test
def possible_exc_types(node): """ Gets all of the possible raised exception types for the given raise node. .. note:: Caught exception types are ignored. :param node: The raise node to find exception types for. :type node: astroid.node_classes.NodeNG :returns: A list of exception ty...
python
{ "resource": "" }
q269468
ByIdManagedMessagesChecker.process_module
test
def process_module(self, module): """inspect the source file to find messages activated or deactivated by id.""" managed_msgs = MessagesHandlerMixIn.get_by_id_managed_msgs() for (mod_name, msg_id, msg_symbol, lineno, is_disabled) in managed_msgs: if mod_name == module.name: ...
python
{ "resource": "" }
q269469
EncodingChecker.process_module
test
def process_module(self, module): """inspect the source file to find encoding problem""" if module.file_encoding: encoding = module.file_encoding else: encoding = "ascii" with module.stream() as stream: for lineno, line in enumerate(stream): ...
python
{ "resource": "" }
q269470
EncodingChecker.process_tokens
test
def process_tokens(self, tokens): """inspect the source to find fixme problems""" if not self.config.notes: return comments = ( token_info for token_info in tokens if token_info.type == tokenize.COMMENT ) for comment in comments: comment_text =...
python
{ "resource": "" }
q269471
_is_from_future_import
test
def _is_from_future_import(stmt, name): """Check if the name is a future import from another module.""" try: module = stmt.do_import_module(stmt.modname) except astroid.AstroidBuildingException: return None for local_node in module.locals.get(name, []): if isinstance(local_node,...
python
{ "resource": "" }
q269472
in_for_else_branch
test
def in_for_else_branch(parent, stmt): """Returns True if stmt in inside the else branch for a parent For stmt.""" return isinstance(parent, astroid.For) and any( else_stmt.parent_of(stmt) or else_stmt == stmt for else_stmt in parent.orelse )
python
{ "resource": "" }
q269473
overridden_method
test
def overridden_method(klass, name): """get overridden method if any""" try: parent = next(klass.local_attr_ancestors(name)) except (StopIteration, KeyError): return None try: meth_node = parent[name] except KeyError: # We have found an ancestor defining <name> but it'...
python
{ "resource": "" }
q269474
_get_unpacking_extra_info
test
def _get_unpacking_extra_info(node, infered): """return extra information to add to the message for unpacking-non-sequence and unbalanced-tuple-unpacking errors """ more = "" infered_module = infered.root().name if node.root().name == infered_module: if node.lineno == infered.lineno: ...
python
{ "resource": "" }
q269475
_detect_global_scope
test
def _detect_global_scope(node, frame, defframe): """ Detect that the given frames shares a global scope. Two frames shares a global scope when neither of them are hidden under a function scope, as well as any of parent scope of them, until the root scope. In this case, depending from something ...
python
{ "resource": "" }
q269476
_assigned_locally
test
def _assigned_locally(name_node): """ Checks if name_node has corresponding assign statement in same scope """ assign_stmts = name_node.scope().nodes_of_class(astroid.AssignName) return any(a.name == name_node.name for a in assign_stmts)
python
{ "resource": "" }
q269477
NamesConsumer.mark_as_consumed
test
def mark_as_consumed(self, name, new_node): """ Mark the name as consumed and delete it from the to_consume dictionary """ self.consumed[name] = new_node del self.to_consume[name]
python
{ "resource": "" }
q269478
VariablesChecker.visit_global
test
def visit_global(self, node): """check names imported exists in the global scope""" frame = node.frame() if isinstance(frame, astroid.Module): self.add_message("global-at-module-level", node=node) return module = frame.root() default_message = True ...
python
{ "resource": "" }
q269479
VariablesChecker._ignore_class_scope
test
def _ignore_class_scope(self, node): """ Return True if the node is in a local class scope, as an assignment. :param node: Node considered :type node: astroid.Node :return: True if the node is in a local class scope, as an assignment. False otherwise. :rtype: bool ...
python
{ "resource": "" }
q269480
VariablesChecker._has_homonym_in_upper_function_scope
test
def _has_homonym_in_upper_function_scope(self, node, index): """ Return True if there is a node with the same name in the to_consume dict of an upper scope and if that scope is a function :param node: node to check for :type node: astroid.Node :param index: index of the ...
python
{ "resource": "" }
q269481
VariablesChecker._check_unpacking
test
def _check_unpacking(self, infered, node, targets): """ Check for unbalanced tuple unpacking and unpacking non sequences. """ if utils.is_inside_abstract_class(node): return if utils.is_comprehension(node): return if infered is astroid.Uninferable:...
python
{ "resource": "" }
q269482
VariablesChecker3k._check_metaclasses
test
def _check_metaclasses(self, node): """ Update consumption analysis for metaclasses. """ consumed = [] # [(scope_locals, consumed_key)] for child_node in node.get_children(): if isinstance(child_node, astroid.ClassDef): consumed.extend(self._check_classdef_metaclass...
python
{ "resource": "" }
q269483
get_packages
test
def get_packages(directory, prefix): """return a list of subpackages for the given directory""" result = [] for package in os.listdir(directory): absfile = join(directory, package) if isdir(absfile): if exists(join(absfile, "__init__.py")): if prefix: ...
python
{ "resource": "" }
q269484
install
test
def install(**kwargs): """setup entry point""" if USE_SETUPTOOLS: if "--force-manifest" in sys.argv: sys.argv.remove("--force-manifest") packages = [modname] + get_packages(join(base_dir, "pylint"), modname) if USE_SETUPTOOLS: if install_requires: kwargs["install_...
python
{ "resource": "" }
q269485
MyInstallLib.run
test
def run(self): """overridden from install_lib class""" install_lib.install_lib.run(self) # manually install included directories if any if include_dirs: for directory in include_dirs: dest = join(self.install_dir, directory) if sys.version_info...
python
{ "resource": "" }
q269486
report_similarities
test
def report_similarities(sect, stats, old_stats): """make a layout with some stats about duplication""" lines = ["", "now", "previous", "difference"] lines += table_lines_from_stats( stats, old_stats, ("nb_duplicated_lines", "percent_duplicated_lines") ) sect.append(Table(children=lines, cols...
python
{ "resource": "" }
q269487
Run
test
def Run(argv=None): """standalone command line access point""" if argv is None: argv = sys.argv[1:] from getopt import getopt s_opts = "hdi" l_opts = ( "help", "duplicates=", "ignore-comments", "ignore-imports", "ignore-docstrings", ) min_line...
python
{ "resource": "" }
q269488
Similar.append_stream
test
def append_stream(self, streamid, stream, encoding=None): """append a file to search for similarities""" if encoding is None: readlines = stream.readlines else: readlines = decoding_stream(stream, encoding).readlines try: self.linesets.append( ...
python
{ "resource": "" }
q269489
Similar._compute_sims
test
def _compute_sims(self): """compute similarities in appended files""" no_duplicates = defaultdict(list) for num, lineset1, idx1, lineset2, idx2 in self._iter_sims(): duplicate = no_duplicates[num] for couples in duplicate: if (lineset1, idx1) in couples or...
python
{ "resource": "" }
q269490
Similar._display_sims
test
def _display_sims(self, sims): """display computed similarities on stdout""" nb_lignes_dupliquees = 0 for num, couples in sims: print() print(num, "similar lines in", len(couples), "files") couples = sorted(couples) for lineset, idx in couples: ...
python
{ "resource": "" }
q269491
Similar._find_common
test
def _find_common(self, lineset1, lineset2): """find similarities in the two given linesets""" lines1 = lineset1.enumerate_stripped lines2 = lineset2.enumerate_stripped find = lineset2.find index1 = 0 min_lines = self.min_lines while index1 < len(lineset1): ...
python
{ "resource": "" }
q269492
Similar._iter_sims
test
def _iter_sims(self): """iterate on similarities among all files, by making a cartesian product """ for idx, lineset in enumerate(self.linesets[:-1]): for lineset2 in self.linesets[idx + 1 :]: for sim in self._find_common(lineset, lineset2): ...
python
{ "resource": "" }
q269493
LineSet.enumerate_stripped
test
def enumerate_stripped(self, start_at=0): """return an iterator on stripped lines, starting from a given index if specified, else 0 """ idx = start_at if start_at: lines = self._stripped_lines[start_at:] else: lines = self._stripped_lines f...
python
{ "resource": "" }
q269494
LineSet._mk_index
test
def _mk_index(self): """create the index for this set""" index = defaultdict(list) for line_no, line in enumerate(self._stripped_lines): if line: index[line].append(line_no) return index
python
{ "resource": "" }
q269495
_definition_equivalent_to_call
test
def _definition_equivalent_to_call(definition, call): """Check if a definition signature is equivalent to a call.""" if definition.kwargs: same_kw_variadics = definition.kwargs in call.starred_kws else: same_kw_variadics = not call.starred_kws if definition.varargs: same_args_var...
python
{ "resource": "" }
q269496
_check_arg_equality
test
def _check_arg_equality(node_a, node_b, attr_name): """ 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 attribut...
python
{ "resource": "" }
q269497
_has_different_parameters_default_value
test
def _has_different_parameters_default_value(original, overridden): """ 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 d...
python
{ "resource": "" }
q269498
_different_parameters
test
def _different_parameters(original, overridden, dummy_parameter_regex): """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,...
python
{ "resource": "" }
q269499
_safe_infer_call_result
test
def _safe_infer_call_result(node, caller, context=None): """ Safely infer the return value of a function. Returns None if inference failed or if there is some ambiguity (more than one node has been inferred). Otherwise returns infered value. """ try: inferit = node.infer_call_result(cal...
python
{ "resource": "" }