{"django__django-13810__dbd7d915": {"H": [[345, "set_urlconf(None)"], [118, "elif method_is_async:"], [296, "if not(response is None or asyncio.iscoroutine(response)):"], [272, "raise RuntimeError('Response is still a coroutine.')"], [169, "response = middleware_method(request, callback, callback_args, callback_kwargs)"]], "WRONG": [[329, "return view"], [118, "elif method_is_async:"], [101, "Adapt a method to be in the correct \"mode\":"], [261, "response = await sync_to_async(response.render, thread_sensitive=True)()"], [296, "if not(response is None or asyncio.iscoroutine(response)):"]], "BM25": [[227, "# If it is a synchronous view, run it in a subthread"], [175, "# If it is an asynchronous view, run it in a subthread."], [93, "# We only assign to this when initialization is complete as it is used"], [101, "Adapt a method to be in the correct \"mode\":"], [313, "\"%s didn't return an HttpResponse object. It returned an \""]], "GOLD": [[264, "self.process_exception_by_middleware,"], [54, "handler = self.adapt_method_mode("], [58, "mw_instance = middleware(handler)"], [65, "continue"], [67, "if mw_instance is None:"]]}, "django__django-10097__62a68852": {"H": [[95, "regex = _lazy_re_compile("], [107, "if schemes is not None:"], [296, "regexp = _lazy_re_compile(r'^%(neg)s\\d+(?:%(sep)s%(neg)s\\d+)*\\Z' % {"], [97, "r'(?:\\S+(?::\\S*)?@)?' # user:pass authentication"], [96, "r'^(?:[a-z0-9\\.\\-\\+]*)://' # scheme is validated separately"]], "WRONG": [[116, "# Then check full URL"], [57, "regex_matches = self.regex.search(str(value))"], [296, "regexp = _lazy_re_compile(r'^%(neg)s\\d+(?:%(sep)s%(neg)s\\d+)*\\Z' % {"], [127, "netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE"], [259, "if not is_valid_ipv6_address(value):"]], "BM25": [[390, "Validate that the input does not exceed the maximum number of digits"], [425, "# If the absolute value of the negative exponent is larger than the"], [426, "# number of digits, then it's the same as the number of digits,"], [74, "class URLValidator(RegexValidator):"], [519, "\"\"\"Validate that the string doesn't contain the null character.\"\"\""]], "GOLD": [[269, "except ValidationError:"], [97, "r'(?:\\S+(?::\\S*)?@)?' # user:pass authentication"], [98, "r'(?:' + ipv4_re + '|' + ipv6_re + '|' + host_re + ')'"], [172, "# max length for domain name labels is 63 characters per RFC 1034"], [42, "self.code = code"]]}, "pytest-dev__pytest-7982__75b21bfc": {"H": [[281, "return False"], [284, "if not lock.is_file():"], [561, "if entry.is_dir(follow_symlinks=False) and recurse(entry):"], [280, "if path.is_symlink():"], [457, ":raises ImportPathMismatchError:"]], "WRONG": [[48, "rm_rf(path)"], [610, ")"], [208, "return new_path"], [433, "\"\"\""], [509, "importlib.import_module(module_name)"]], "BM25": [[561, "if entry.is_dir(follow_symlinks=False) and recurse(entry):"], [412, "\"\"\"Make a symlink, or skip the test in case symlinks are not supported.\"\"\""], [197, "for i in range(10):"], [339, "for i in range(10):"], [251, "\"\"\"Remove a numbered directory if its lock can be obtained and it does"]], "GOLD": [[468, "if mode is ImportMode.importlib:"], [503, "elif mode is ImportMode.prepend:"], [469, "module_name = path.stem"], [561, "if entry.is_dir(follow_symlinks=False) and recurse(entry):"], [576, "no common part."]]}, "django__django-13195__5ac1dc15": {"H": [[95, "response.delete_cookie(self.cookie_name, domain=settings.SESSION_COOKIE_DOMAIN)"], [175, "return None"], [92, "samesite=settings.SESSION_COOKIE_SAMESITE,"], [87, "response.set_cookie("], [149, "return self.signer.sign(value)"]], "WRONG": [[36, "if obj[1]:"], [102, "If the encoded data is larger than ``max_cookie_size``, remove"], [163, "# RemovedInDjango40Warning: when the deprecation ends, replace"], [114, "return len(cookie.value_encode(val)[1])"], [37, "obj[3] = mark_safe(obj[3])"]], "BM25": [[92, "samesite=settings.SESSION_COOKIE_SAMESITE,"], [90, "secure=settings.SESSION_COOKIE_SECURE or None,"], [95, "response.delete_cookie(self.cookie_name, domain=settings.SESSION_COOKIE_DOMAIN)"], [84, "store, or delete the cookie."], [91, "httponly=settings.SESSION_COOKIE_HTTPONLY or None,"]], "GOLD": [[184, "return None"], [89, "domain=settings.SESSION_COOKIE_DOMAIN,"], [84, "store, or delete the cookie."], [82, "\"\"\""], [95, "response.delete_cookie(self.cookie_name, domain=settings.SESSION_COOKIE_DOMAIN)"]]}, "django__django-13195__7e0a8bc9": {"H": [[45, ")"], [46, "patch_vary_headers(response, ('Cookie',))"], [78, "return response"], [76, "samesite=settings.SESSION_COOKIE_SAMESITE,"], [41, "response.delete_cookie("]], "WRONG": [[19, "engine = import_module(settings.SESSION_ENGINE)"], [24, "request.session = self.SessionStore(session_key)"], [16, "self._get_response_none_deprecation(get_response)"], [20, "self.SessionStore = engine.SessionStore"], [64, "raise SuspiciousOperation("]], "BM25": [[76, "samesite=settings.SESSION_COOKIE_SAMESITE,"], [74, "secure=settings.SESSION_COOKIE_SECURE or None,"], [41, "response.delete_cookie("], [38, "# First check if we need to delete this cookie."], [29, "session every time, save the changes and set a session cookie or delete"]], "GOLD": [[1, "import time"], [33, "accessed = request.session.accessed"], [36, "except AttributeError:"], [44, "domain=settings.SESSION_COOKIE_DOMAIN,"], [45, ")"]]}, "django__django-13195__eeebc8cb": {"H": [[220, ")"], [222, "# Common methods used by subclasses"], [217, "self.set_cookie("], [213, "def delete_cookie(self, key, path='/', domain=None):"], [214, "# Most browsers ignore the Set-Cookie header if the cookie name starts"]], "WRONG": [[362, "self.streaming_content = streaming_content"], [185, "self.cookies[key]['expires'] = ''"], [373, "return map(self.make_bytes, self._iterator)"], [377, "self._set_streaming_content(value)"], [554, "if safe and not isinstance(data, dict):"]], "BM25": [[213, "def delete_cookie(self, key, path='/', domain=None):"], [215, "# with __Host- or __Secure- and the cookie doesn't use the secure flag."], [214, "# Most browsers ignore the Set-Cookie header if the cookie name starts"], [217, "self.set_cookie("], [161, "Set a cookie."]], "GOLD": [[213, "def delete_cookie(self, key, path='/', domain=None):"], [214, "# Most browsers ignore the Set-Cookie header if the cookie name starts"], [216, "secure = key.startswith(('__Secure-', '__Host-'))"], [215, "# with __Host- or __Secure- and the cookie doesn't use the secure flag."], [219, "expires='Thu, 01 Jan 1970 00:00:00 GMT',"]]}, "sympy__sympy-14531__aa081ba2": {"H": [[478, "if terms[0] in ['-', '+']:"], [823, "p = StrPrinter(settings)"], [821, "\"\"\""], [824, "s = p.doprint(expr)"], [218, "if str(dir) == \"+\":"]], "WRONG": [[478, "if terms[0] in ['-', '+']:"], [575, "if self._settings.get(\"sympy_integers\", False):"], [632, "if expr.rel_op in charmap:"], [577, "return \"%s/%s\" % (expr.p, expr.q)"], [234, "_print_ImmutableMatrix = \\"]], "BM25": [[244, "x = list(x)"], [247, "if x[1] == x[0] + 1:"], [250, "x[0] = ''"], [23, "\"sympy_integers\": False,"], [246, "del x[2]"]], "GOLD": [[207, "return \"Lambda(%s, %s)\" % (args.args[0], expr)"], [210, "return \"Lambda((%s), %s)\" % (arg_string, expr)"], [89, "return '%s(%s)' % (expr.func, expr.arg)"], [725, "return \"Uniform(%s, %s)\" % (expr.a, expr.b)"], [240, "+ '[%s, %s]' % (expr.i, expr.j)"]]}, "django__django-15957__e0e6b7bb": {"H": [[562, "self.field = rel.field"], [40, "3. Related instance on the reverse side of a one-to-one relation:"], [266, "# since we've not yet cleared out the related field."], [29, "Uniqueness of foreign key values is irrelevant to accessing the related"], [1191, "obj, created = super(ManyRelatedManager, self.db_manager(db)).get_or_create("]], "WRONG": [[731, "return queryset, rel_obj_attr, instance_attr, False, cache_name, False"], [713, "queryset = super().get_queryset()"], [869, "self.add(*new_objs, bulk=bulk)"], [727, "if not self.field.is_cached(rel_obj):"], [20, "``child.parent`` is a forward many-to-one relation. ``parent.children`` is a"]], "BM25": [[546, "Accessor to the related objects manager on the reverse side of a"], [52, "of objects. It returns a manager rather than an instance."], [1378, "# Check that all the objects are of the right type"], [486, "# Following the example above, this would be the cached"], [880, "Accessor to the related objects manager on the forward and reverse sides of"]], "GOLD": [[81, "instance.__dict__[self.field.attname] = value"], [67, "from django.db import connections, router, transaction"], [68, "from django.db.models import Q, signals"], [721, "query = {\"%s__in\" % self.field.name: instances}"], [84, "class ForwardManyToOneDescriptor:"]]}, "pylint-dev__pylint-4661__66a059a6": {"H": [[64, "PYLINT_HOME = \".pylint.d\""], [113, "not found, it defaults to ~/.pylint.d/ or .pylint.d (in the current working"], [66, "PYLINT_HOME = os.path.join(USER_HOME, \".pylint.d\")"], [58, "USER_HOME = os.path.expanduser(\"~\")"], [86, "os.mkdir(PYLINT_HOME)"]], "WRONG": [[37, "import sys"], [39, "from pylint.config.configuration_mixin import ConfigurationMixIn"], [62, "USER_HOME = os.path.dirname(PYLINT_HOME)"], [58, "USER_HOME = os.path.expanduser(\"~\")"], [47, "__all__ = ["]], "BM25": [[112, "Path to the directory where persistent data for the run will be stored. If"], [70, "base_name = base_name.replace(os.sep, \"_\")"], [71, "return os.path.join(PYLINT_HOME, f\"{base_name}{recurs}.stats\")"], [116, "Path to the configuration file. See the documentation for the method used"], [113, "not found, it defaults to ~/.pylint.d/ or .pylint.d (in the current working"]], "GOLD": [[37, "import sys"], [39, "from pylint.config.configuration_mixin import ConfigurationMixIn"], [103, "return None"], [40, "from pylint.config.find_default_config_files import find_default_config_files"], [66, "PYLINT_HOME = os.path.join(USER_HOME, \".pylint.d\")"]]}, "sphinx-doc__sphinx-9367__b1cc0199": {"H": [[217, "return \"(\" + \", \".join(self.visit(e) for e in node.elts) + \")\""], [236, "return repr(node.s)"], [218, "else:"], [216, "if node.elts:"], [219, "return \"()\""]], "WRONG": [[190, "return node.id"], [236, "return repr(node.s)"], [172, "return repr(node.value)"], [186, "def visit_List(self, node: ast.List) -> str:"], [239, "raise NotImplementedError('Unable to parse %s object' % type(node).__name__)"]], "BM25": [[101, "\"\"\"Unparse a single argument to a string.\"\"\""], [2, "sphinx.pycode.ast"], [203, "if is_simple_tuple(node.slice):"], [196, "def is_simple_tuple(value: ast.AST) -> bool:"], [57, "# type_comments parameter (refs: https://github.com/sphinx-doc/sphinx/issues/8652)."]], "GOLD": [[221, "if sys.version_info < (3, 8):"], [219, "return \"()\""], [217, "return \"(\" + \", \".join(self.visit(e) for e in node.elts) + \")\""], [218, "else:"], [216, "if node.elts:"]]}, "django__django-16819__52410aea": {"H": [[905, "return \"remove_%s_%s\" % (self.model_name_lower, self.name.lower())"], [33, "return super().reduce(operation, app_label) or self.can_reduce_through("], [38, "return not operation.references_model(self.name, app_label)"], [101, "schema_editor.delete_model(model)"], [250, "option = set("]], "WRONG": [[137, "if ("], [905, "return \"remove_%s_%s\" % (self.model_name_lower, self.name.lower())"], [101, "schema_editor.delete_model(model)"], [129, "for _name, field in self.fields:"], [912, "if not old_name and not old_fields:"]], "BM25": [[865, "class RemoveIndex(IndexOperation):"], [818, "\"Indexes passed to AddIndex operations require a name \""], [811, "class AddIndex(IndexOperation):"], [947, "state.add_index("], [887, "schema_editor.add_index(model, index)"]], "GOLD": [[83, "ModelState("], [865, "class RemoveIndex(IndexOperation):"], [862, "return \"%s_%s\" % (self.model_name_lower, self.index.name.lower())"], [361, "kwargs = {"], [575, "def deconstruct(self):"]]}, "sympy__sympy-24661__c3f3cb40": {"H": [[599, "# the tokens"], [125, "return result2"], [1147, "args=[ast.UnaryOp(op=ast.USub(), operand=ast.Num(1)), right],"], [46, "def _token_callable(token: TOKEN, local_dict: DICT, global_dict: DICT, nextToken=None):"], [108, "return [self.function, *self.args]"]], "WRONG": [[125, "return result2"], [1015, ">>> parse_expr(\"2x\", transformations=T[:5])"], [368, "``predicate`` should return True if the symbol name is to be split."], [1147, "args=[ast.UnaryOp(op=ast.USub(), operand=ast.Num(1)), right],"], [650, "\"\"\"Treats XOR, ``^``, as exponentiation, ``**``.\"\"\""]], "BM25": [[961, ">>> parse_expr(\"2**3\"), parse_expr(\"2**3\", evaluate=False)"], [967, ">>> a = parse_expr('1 + x', evaluate=False)"], [968, ">>> b = parse_expr('x + 1', evaluate=0)"], [861, ">>> parse_expr(\"(1*2=x)=False\", transformations=("], [948, ">>> parse_expr(\"1/2\")"]], "GOLD": [[1122, "def flatten(self, args, func):"], [104, "self.items = ['function', 'args', 'exponent']"], [1120, ")"], [680, "if (not num and '.' in tokval and 'e' not in tokval.lower() and"], [446, "#: Splits symbol names for implicit multiplication."]]}, "django__django-14765__c8a3e1d2": {"H": [[95, "self.real_apps = real_apps if isinstance(real_apps, set) else set(real_apps)"], [94, "if real_apps:"], [287, "if field.remote_field.model == RECURSIVE_RELATIONSHIP_CONSTANT:"], [106, "self.reload_model(app_label, model_name)"], [559, "\"\"\""]], "WRONG": [[744, "def construct_managers(self):"], [287, "if field.remote_field.model == RECURSIVE_RELATIONSHIP_CONSTANT:"], [807, "return \"<%s: '%s.%s'>\" % (self.__class__.__name__, self.app_label, self.name)"], [4, "from functools import partial"], [355, "self.relations = defaultdict(partial(defaultdict, list))"]], "BM25": [[429, "\"\"\"Take an Apps and return a ProjectState matching it.\"\"\""], [91, "def __init__(self, models=None, real_apps=None):"], [84, "class ProjectState:"], [409, "\"\"\"Return an exact copy of this ProjectState.\"\"\""], [410, "new_state = ProjectState("]], "GOLD": [[95, "self.real_apps = real_apps if isinstance(real_apps, set) else set(real_apps)"], [296, "rel_model = self.apps.get_model(rel_app_label, rel_model_name)"], [94, "if real_apps:"], [404, "# Concrete model found, stop looking at bases."], [97, "self.real_apps = set()"]]}, "sphinx-doc__sphinx-7985__bb67587a": {"H": [[216, "return 'local', '', 0"], [215, "elif not uri.startswith(('http:', 'https:')):"], [19, "from urllib.parse import unquote, urlparse"], [330, "n += 1"], [227, "# need to actually check the URI"]], "WRONG": [[33, "from sphinx.util.requests import is_ssl_error"], [19, "from urllib.parse import unquote, urlparse"], [94, "self.redirected = {} # type: Dict[str, Tuple[str, int]]"], [18, "from typing import Any, Dict, List, Set, Tuple"], [185, "if err.response.status_code == 401:"]], "BM25": [[80, "Checks for broken external links."], [2, "sphinx.builders.linkcheck"], [216, "return 'local', '', 0"], [279, "logger.warning(__('broken link: %s (%s)'), uri, info,"], [270, "elif status == 'local':"]], "GOLD": [[216, "return 'local', '', 0"], [39, "DEFAULT_REQUEST_HEADERS = {"], [213, "if len(uri) == 0 or uri.startswith(('#', 'mailto:', 'ftp:')):"], [295, "text, color = ('with unknown code', purple)"], [36, "logger = logging.getLogger(__name__)"]]}, "scikit-learn__scikit-learn-25973__956fcce2": {"H": [[321, "return self.support_"], [308, "scores[feature_idx] = cross_val_score("], [276, "for _ in range(n_iterations):"], [304, "candidate_mask[feature_idx] = True"], [247, "# With auto feature selection, `n_features_to_select_` will be updated"]], "WRONG": [[257, "self.n_features_to_select_ = int(n_features * self.n_features_to_select)"], [247, "# With auto feature selection, `n_features_to_select_` will be updated"], [159, "Interval(Integral, 0, None, closed=\"neither\"),"], [245, "elif self.n_features_to_select == \"auto\":"], [242, "if self.tol is not None:"]], "BM25": [[139, ">>> from sklearn.feature_selection import SequentialFeatureSelector"], [146, "SequentialFeatureSelector(estimator=KNeighborsClassifier(n_neighbors=3),"], [140, ">>> from sklearn.neighbors import KNeighborsClassifier"], [144, ">>> sfs = SequentialFeatureSelector(knn, n_features_to_select=3)"], [16, "from ..model_selection import cross_val_score"]], "GOLD": [[312, "cv=self.cv,"], [278, "cloned_estimator, X, y, current_mask"], [294, "def _get_best_new_feature_score(self, estimator, X, y, current_mask):"], [262, "cloned_estimator = clone(self.estimator)"], [16, "from ..model_selection import cross_val_score"]]}, "sympy__sympy-15017__15ee009d": {"H": [[152, "self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 0"], [72, "list_length = functools.reduce(lambda x, y: x*y, shape)"], [73, "return cls._new(([0]*list_length,), shape)"], [153, "return self"], [100, "return self._array.__iter__()"]], "WRONG": [[126, "raise ValueError(\"Invalid reshape parameters \" + newshape)"], [56, "return [start + i*step for i in range((stop-start)//step)]"], [105, "must be suitable to new shape. The only argument of method sets"], [60, "array = [self._array[self._parse_index(i)] for i in eindices]"], [61, "nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)]"]], "BM25": [[151, "self._rank = len(shape)"], [176, "self._rank = len(shape)"], [105, "must be suitable to new shape. The only argument of method sets"], [10, "from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray"], [83, ">>> a = MutableDenseNDimArray([1 for i in range(9)], (3, 3))"]], "GOLD": [[140, "@classmethod"], [65, "return self._array[index]"], [62, "return type(self)(array, nshape)"], [73, "return cls._new(([0]*list_length,), shape)"], [152, "self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 0"]]}, "django__django-13363__fe1badf6": {"H": [[239, "value = value.replace(tzinfo=None)"], [296, "sql = connection.ops.datetime_cast_date_sql(lhs, tzname)"], [295, "tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None"], [293, "# Cast to date rather than truncate to date."], [27, "tzname = timezone._get_timezone_name(self.tzinfo)"]], "WRONG": [[76, "if ("], [263, ")"], [260, "super().__init__("], [71, "# Passing dates to functions expecting datetimes is most likely a mistake."], [216, "# Passing dates or times to functions expecting datetimes is most"]], "BM25": [[287, "class TruncDate(TruncBase):"], [177, "# PostgreSQL's CURRENT_TIMESTAMP means \"the time at the start of the"], [325, "DateTimeField.register_lookup(TruncDate)"], [18, "# Timezone conversions must happen to the input datetime *before*"], [11, "from django.utils import timezone"]], "GOLD": [[37, "self.lookup_name = lookup_name"], [39, "raise ValueError('lookup_name must be provided')"], [295, "tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None"], [256, "class Trunc(TruncBase):"], [308, "tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None"]]}, "django__django-14053__c7242ded": {"H": [[212, "refer to the cache-busting filenames."], [399, "yield from super().post_process(*args, **kwargs)"], [231, "for name, hashed_name, processed, _ in self._post_process(paths, adjustable_paths, hashed_files):"], [238, "for name, hashed_name, processed, subst in self._post_process(paths, adjustable_paths, hashed_files):"], [332, "# path."]], "WRONG": [[109, "unparsed_name[2] += '?'"], [187, "hashed_url = self._url("], [321, "yield name, hashed_name, processed, substitutions"], [212, "refer to the cache-busting filenames."], [319, "hashed_files[hash_key] = hashed_name"]], "BM25": [[48, "(\"*.css\", ("], [331, "# ../foo/bar.css and ../foo/../foo/bar.css which normalize to the same"], [170, "# CSS / JS?). Note that STATIC_URL cannot be empty."], [205, "Post process the given dictionary of files (called from collectstatic)."], [20, "The defaults for ``location`` and ``base_url`` are"]], "GOLD": [[249, "self.hashed_files.update(hashed_files)"], [232, "yield name, hashed_name, processed"], [239, "yield name, hashed_name, processed"], [229, "# Do a single pass first. Post-process all files once, then repeat for"], [230, "# adjustable files."]]}, "sphinx-doc__sphinx-7590__6c311922": {"H": [[392, "if not self.skip_string_and_ws(']'):"], [388, "# TODO: actually implement the correct grammar"], [389, "arg = self._parse_balanced_token_seq(end=[']'])"], [394, "return ASTCPPAttribute(arg)"], [393, "self.fail(\"Expected ']' in end of attribute after [[...]\")"]], "WRONG": [[408, "self.fail('Parameterized GNU style attribute not yet supported.')"], [407, "if self.skip_string_and_ws('('):"], [435, "return ASTParenAttribute(id, arg)"], [15, "Any, Callable, List, Match, Pattern, Tuple, Union"], [392, "if not self.skip_string_and_ws(']'):"]], "BM25": [[273, "'Invalid %s declaration: %s [error at %d]\\n %s\\n %s' %"], [267, "print(\"%s\\n%s\\n%s\" % (msg, self.definition, indicator))"], [5, "Utility functions common to the C and C++ domains."], [2, "sphinx.util.cfamily"], [7, ":copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS."]], "GOLD": [[44, "float_literal_re = re.compile(r'''(?x)"], [43, "binary_literal_re = re.compile(r'0[bB][01][01]*')"], [55, "''')"], [56, "char_literal_re = re.compile(r'''(?x)"], [72, "if mode not in ('lastIsName', 'noneIsName', 'markType', 'markName', 'param'):"]]}, "django__django-11119__2ec90d8b": {"H": [[163, "return t.render(Context(context))"], [143, "template, origin = self.find_template(template_name)"], [165, "def select_template(self, template_name_list):"], [157, "t = self.get_template(template_name)"], [146, "template = Template(template, origin, template_name, engine=self)"]], "WRONG": [[143, "template, origin = self.find_template(template_name)"], [180, "raise TemplateDoesNotExist(', '.join(not_found))"], [141, "handling template inheritance recursively."], [55, "@staticmethod"], [22, "file_charset='utf-8', libraries=None, builtins=None, autoescape=True):"]], "BM25": [[149, "def render_to_string(self, template_name, context=None):"], [145, "# template needs to be compiled"], [48, "self.string_if_invalid = string_if_invalid"], [68, ">>> template.render(context)"], [151, "Render the template specified by template_name with the given context."]], "GOLD": [[90, "def get_template_libraries(self, libraries):"], [163, "return t.render(Context(context))"], [50, "self.libraries = libraries"], [112, "args = []"], [155, "t = self.select_template(template_name)"]]}, "sphinx-doc__sphinx-11510__e32fc687": {"H": [[372, "if self.arguments[0].startswith('<') and \\"], [379, "return super().run()"], [376, "rel_filename, filename = self.env.relfn2path(self.arguments[0])"], [378, "self.env.note_included(filename)"], [315, "option_spec: OptionSpec = {}"]], "WRONG": [[256, "option_spec: OptionSpec = {}"], [278, "option_spec: OptionSpec = {"], [84, "generated_docnames = frozenset(StandardDomain._virtual_doc_names)"], [138, "if docname not in frozen_all_docnames:"], [397, "directives.register_directive('cssclass', Class)"]], "BM25": [[403, "'parallel_read_safe': True,"], [41, "and to include a table-of-contents like tree in the current document."], [404, "'parallel_write_safe': True,"], [40, "Directive to notify Sphinx about the hierarchical structure of the docs,"], [368, "\"correctly\", i.e. relative to source directory."]], "GOLD": [[21, "if TYPE_CHECKING:"], [12, "from sphinx import addnodes"], [372, "if self.arguments[0].startswith('<') and \\"], [19, "from sphinx.util.nodes import explicit_title_re"], [371, "def run(self) -> list[Node]:"]]}, "django__django-15569__1e7fc0d7": {"H": [[219, "del cls.class_lookups[lookup_name]"], [142, "loaded in the instance. This can be done if the to-be fetched"], [199, "subclass.get_lookups.cache_clear()"], [33, "\"\"\""], [218, "lookup_name = lookup.lookup_name"]], "WRONG": [[122, "Retrieve and caches the value from the datastore on the first lookup."], [334, "raise NotImplementedError(\"FilteredRelation.resolve_expression() is unused.\")"], [47, "children=[*args, *sorted(kwargs.items())],"], [339, "where = query.build_filtered_relation_q(self.condition, reuse=set(self.path))"], [86, "# We must promote any new joins to left outer joins so that when Q is"]], "BM25": [[101, "path = path.replace(\"django.db.models.query_utils\", \"django.db.models\")"], [100, "if path.startswith(\"django.db.models.query_utils\"):"], [166, "from django.db.models.lookups import Lookup"], [212, "def _unregister_lookup(cls, lookup, lookup_name=None):"], [4, "Factored out from django.db.models.query to avoid making the main module very"]], "GOLD": [[236, "\"\"\""], [302, "\"\"\"Specify custom filtering in the ON clause of SQL joins.\"\"\""], [219, "del cls.class_lookups[lookup_name]"], [222, "def select_related_descend(field, restricted, requested, load_fields, reverse=False):"], [274, "Check that self.model is compatible with target_opts. Compatibility"]]}, "sphinx-doc__sphinx-9320__1b82e76d": {"H": [[226, "'', is_path)"], [149, "if default and not x:"], [150, "x = default"], [225, "d['path'] = do_prompt(__('Please enter a new root path (or just Enter to exit)'),"], [228, "sys.exit(1)"]], "WRONG": [[375, "write_file(path.join(srcdir, 'conf.py'), template.render_string(conf_text, d))"], [178, "if self._has_custom_template(template_name):"], [388, "batchfile_template = 'quickstart/make.bat.new_t'"], [201, "* makefile: make Makefile"], [328, "if 'mastertoctree' not in d:"]], "BM25": [[225, "d['path'] = do_prompt(__('Please enter a new root path (or just Enter to exit)'),"], [253, "print(__('Sphinx has the notion of a \"version\" and a \"release\" for the\\n'"], [207, "print(__('Please enter values for the following settings (just press Enter to\\n'"], [94, "raise ValidationError(__(\"Please enter a valid path name.\"))"], [2, "sphinx.cmd.quickstart"]], "GOLD": [[436, "if not path.exists(dir):"], [98, "def allow_empty(x: str) -> str:"], [226, "'', is_path)"], [417, "print(__('Use the sphinx-build command to build the docs, like so:\\n'"], [95, "return x"]]}, "pytest-dev__pytest-7571__a36360ed": {"H": [[471, "* caplog.clear() -> clear captured records and formatted log output string"], [150, "return int(auto_indent_option)"], [358, "logger.setLevel(level)"], [294, "self.level = level"], [303, "root_logger.setLevel(min(self.orig_level, self.level))"]], "WRONG": [[471, "* caplog.clear() -> clear captured records and formatted log output string"], [583, "formatter._style._fmt, auto_indent=auto_indent"], [150, "return int(auto_indent_option)"], [325, "self.records.append(record)"], [194, "return ret"]], "BM25": [[431, "end of the test."], [424, "the test."], [677, "self.caplog_handler, level=self.log_level,"], [423, "\"\"\"Sets the level for capturing of logs. The level will be restored to its previous value at the end of"], [369, "Get the logging records for one of the possible test phases."]], "GOLD": [[347, "# dict of log name -> log level"], [437, "self.handler.setLevel(level)"], [436, "logger_obj.setLevel(level)"], [355, "# restore log levels"], [356, "for logger_name, level in self._initial_logger_levels.items():"]]}, "django__django-16527__f0d80708": {"H": [[105, "and save_as,"], [103, "and has_change_permission"], [87, ")"], [82, "has_add_permission"], [106, "\"show_save_and_add_another\": can_save_and_add_another,"]], "WRONG": [[27, "prepopulated_fields_json.append("], [6, "from .base import InclusionAdminNode"], [4, "from django.template.context import Context"], [18, "prepopulated_fields.extend(context[\"adminform\"].prepopulated_fields)"], [142, "is_hidden = field.field.is_hidden"]], "BM25": [[102, "\"show_save_as_new\": not is_popup"], [84, "and (not save_as or add)"], [72, "has_add_permission = context[\"has_add_permission\"]"], [78, "or (has_add_permission and add)"], [105, "and save_as,"]], "GOLD": [[97, "not is_popup"], [42, "context.update("], [57, "template_name=\"prepopulated_fields_js.html\","], [103, "and has_change_permission"], [8, "register = template.Library()"]]}, "sympy__sympy-13798__7ef9e433": {"H": [[59, "'Tau': 'T',"], [1757, "def _print_FractionField(self, expr):"], [160, "mul_symbol_table[self._settings['mul_symbol']]"], [1589, "if exp:"], [718, "# If we are dealing with a power-style inverse trig function"]], "WRONG": [[1757, "def _print_FractionField(self, expr):"], [1589, "if exp:"], [613, "tex += r\"%s %s\" % (diff_symbol, self._print(x))"], [1568, "if exp:"], [261, "return False"]], "BM25": [[2157, "mul_symbol: The symbol to use for multiplication. Can be one of None,"], [131, "\"mul_symbol\": None,"], [1808, "mul_symbol = self._settings['mul_symbol_latex']"], [226, "specifies that this expr is the last to appear in a Mul."], [160, "mul_symbol_table[self._settings['mul_symbol']]"]], "GOLD": [[160, "mul_symbol_table[self._settings['mul_symbol']]"], [163, "mul_symbol_table[self._settings['mul_symbol'] or 'dot']"], [1183, "return r\"\\operatorname{Li}_{%s}%s\" % (s, tex)"], [162, "self._settings['mul_symbol_latex_numbers'] = \\"], [159, "self._settings['mul_symbol_latex'] = \\"]]}, "sympy__sympy-16886__a6e3f1ef": {"H": [[2002, "`\\frac{1}{r^{ad}} m e^a \\equiv \\frac{1}{r^{ad}} m {r^{d a}} \\equiv m \\pmod p`"], [2343, "List[int]: the randomized encrpyted message."], [103, "Joins characters of `phrase` and if ``symbols`` is given, raises"], [773, "map = {c: i for i, c in enumerate(A)}"], [158, "Returns the elements of the list ``range(n)`` shifted to the"]], "WRONG": [[2002, "`\\frac{1}{r^{ad}} m e^a \\equiv \\frac{1}{r^{ad}} m {r^{d a}} \\equiv m \\pmod p`"], [2358, "return m"], [1165, "return decipher_bifid(msg, '', key)"], [2332, "return [ encode(b) for b in rev ]"], [1731, "``P``: the period of ``L``"]], "BM25": [[1607, "mapping = mapping or morse_char"], [1559, "mapping = mapping or char_morse"], [1560, "assert sep not in mapping"], [1539, "def encode_morse(msg, sep='|', mapping=None):"], [1586, "def decode_morse(msg, sep='|', mapping=None):"]], "GOLD": [[1523, "\"-----\": \"0\", \"----\": \"1\","], [410, "reverse / counterpart (i.e. a would map to z, b to y etc.)"], [1280, "[Y, Z, 0, 1, 2, 3],"], [2026, "################ Diffie-Hellman Key Exchange #########################"], [132, "missing = ''.join(list(sorted(set(rv) - set(symbols))))"]]}, "django__django-15277__bf776a3b": {"H": [[769, "self.name = self.name or name"], [1013, "self.validators.append(validators.MaxLengthValidator(self.max_length))"], [143, "self.max_length, self._unique = max_length, unique"], [933, "form_class = forms.TypedChoiceField"], [2113, "'form_class': forms.SlugField,"]], "WRONG": [[1443, "class DecimalField(Field):"], [1357, "# local time. This won't work during DST change, but we can't"], [2172, "**({} if self.choices is not None else {'widget': forms.Textarea}),"], [1802, "internal_type = self.get_internal_type()"], [2377, "return memoryview(b64decode(value.encode('ascii')))"]], "BM25": [[398, "(output_field is None or output_field == self)"], [1083, "# Passing max_length to forms.CharField means that the value's length"], [2167, "# Passing max_length to forms.CharField means that the value's length"], [1013, "self.validators.append(validators.MaxLengthValidator(self.max_length))"], [2325, "self.validators.append(validators.MaxLengthValidator(self.max_length))"]], "GOLD": [[1604, "if isinstance(value, datetime.timedelta):"], [2526, "def get_internal_type(self):"], [1013, "self.validators.append(validators.MaxLengthValidator(self.max_length))"], [291, "\"'max_length' is too small to fit the longest value \""], [1150, "]"]]}, "sympy__sympy-13878__25305d2d": {"H": [[99, "]"], [1112, "return random.gammavariate(self.k, self.theta)"], [1568, "(S.Half + S.Half*erf((log(x) - mean)/sqrt(2)/std), x>0),"], [156, "def Arcsin(name, a=0, b=1):"], [1124, "with :math:`x \\in [0,1]`."]], "WRONG": [[90, "'StudentT',"], [52, "from sympy import cos, exp, besseli"], [905, "Create a continuous random variable with a F distribution."], [2723, "k : Real number, `k > 0` a shape"], [2392, "0 & \\mathrm{for\\ } b < x."]], "BM25": [[603, "def _cdf(self, x):"], [1892, "def _cdf(self, x):"], [1795, "def _cdf(self, x):"], [1565, "def _cdf(self, x):"], [810, "def _cdf(self, x):"]], "GOLD": [[1540, "References"], [1482, "exp(-Abs(mu - z)/b)/(2*b)"], [50, "Lambda, Basic, lowergamma, erf, erfc, I)"], [2300, "def Trapezoidal(name, a, b, c, d):"], [1741, ">>> from sympy.stats import Nakagami, density, E, variance"]]}, "django__django-13417__5b0dda5e": {"H": [[1384, ")"], [1907, "between the objects."], [1955, "self.related_populators = get_related_populators(klass_info, select, self.db)"], [1895, "return all_related_objects, additional_lookups"], [1898, "class RelatedPopulator:"]], "WRONG": [[1722, "# (e.g. via select_related), or hopefully some other property"], [1907, "between the objects."], [1895, "return all_related_objects, additional_lookups"], [1793, "else:"], [1898, "class RelatedPopulator:"]], "BM25": [[1636, "done_queries = {} # dictionary of things like 'foo__bar': [results]"], [1220, "Return True if the QuerySet is ordered -- i.e. has an order_by()"], [1227, "elif self.query.default_ordering and self.query.get_meta().ordering:"], [1221, "clause or a default ordering on the model (or is empty)."], [1162, "\"\"\"Reverse the ordering of the QuerySet.\"\"\""]], "GOLD": [[39, "self.queryset = queryset"], [468, "# are two workarounds:"], [28, "from django.utils.functional import cached_property, partition"], [1227, "elif self.query.default_ordering and self.query.get_meta().ordering:"], [1350, "return query"]]}, "django__django-13023__bf776a3b": {"H": [[587, "return value"], [1503, "return decimal.Decimal(value)"], [1505, "raise exceptions.ValidationError("], [1502, "try:"], [1500, "if isinstance(value, float):"]], "WRONG": [[38, "'SmallIntegerField', 'TextField', 'TimeField', 'URLField', 'UUIDField',"], [1745, "internal_type = self.get_internal_type()"], [2414, "to be implemented on Field to be used instead."], [422, "been run."], [1725, "*self._check_max_length_warning(),"]], "BM25": [[1446, "except TypeError:"], [1422, "except TypeError:"], [59, "# A guide to Field parameters:"], [698, "Return the data type that a related field pointing to this field should"], [1962, "Return the data type that a related field pointing to this field should"]], "GOLD": [[1504, "except decimal.InvalidOperation:"], [1976, "description = _('Positive big integer')"], [1608, "})"], [342, "errors = []"], [801, "def pre_save(self, model_instance, add):"]]}, "django__django-11095__3c42de3e": {"H": [[706, "def get_changelist(self, request, **kwargs):"], [1727, "formset = cl.formset = FormSet(request.POST, request.FILES, queryset=modified_objects)"], [398, "model = field.get_path_info()[-1].to_opts.model"], [584, "inline_instances = []"], [1915, "\"Helper function to generate formsets for add/change_view.\""]], "WRONG": [[1831, "if obj is None:"], [398, "model = field.get_path_info()[-1].to_opts.model"], [2013, "\"\"\"Hook for customizing the max number of extra inline forms.\"\"\""], [706, "def get_changelist(self, request, **kwargs):"], [825, "def log_deletion(self, request, object, object_repr):"]], "BM25": [[783, "def get_formsets_with_inlines(self, request, obj=None):"], [555, "inlines = []"], [1922, "for FormSet, inline in self.get_formsets_with_inlines(*get_formsets_args):"], [446, "for inline in admin.inlines:"], [903, "or the name of a method on the ModelAdmin. Return is a tuple of"]], "GOLD": [[1491, "# We have to special-case M2Ms as a list of comma-separated PKs."], [330, "def get_ordering(self, request):"], [1998, "if self.filter_vertical or self.filter_horizontal:"], [585, "for inline_class in self.inlines:"], [328, "return [(None, {'fields': self.get_fields(request, obj)})]"]]}, "django__django-11265__0edd8535": {"H": [[1234, "clause = self.where_class()"], [1395, "'names' is the path of names to travel, 'opts' is the model Options we"], [1261, "# Update used_joins before trimming since they are reused to determine"], [1276, "col = MultiColSource(alias, targets, join_info.targets, join_info.final_field)"], [1259, "return self.split_exclude(filter_expr, can_reuse, e.names_with_path)"]], "WRONG": [[601, "# will be unused in the new query, too. We have to add and"], [647, "model. Models that have all their fields included aren't mentioned in"], [2154, "# TODO: It might be possible to trim more joins from the start of the"], [1315, "# (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if"], [1963, "field names replace any existing immediate loading field names. If"]], "BM25": [[1305, "self.add_q(Q(**{filter_clause[0]: filter_clause[1]}))"], [1645, "def split_exclude(self, filter_expr, can_reuse, names_with_path):"], [1259, "return self.split_exclude(filter_expr, can_reuse, e.names_with_path)"], [1188, "to this Query. Query.add_q() will then add this filter to the where"], [1669, "query.add_filter(filter_expr)"]], "GOLD": [[1668, "query = Query(self.model)"], [2144, "# miss those rows that have nothing on the outer side."], [2145, "if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type != LOUTER:"], [2143, "# (that is, self). We can't do this for LEFT JOINs because we would"], [1669, "query.add_filter(filter_expr)"]]}, "django__django-16100__3c42de3e": {"H": [[470, "model = field.path_infos[-1].to_opts.model"], [1797, "self.save_model(request, new_object, form, not add)"], [68, "from django.views.generic import RedirectView"], [1745, "with transaction.atomic(using=router.db_for_write(self.model)):"], [2016, "obj = self.save_form(request, form, change=True)"]], "WRONG": [[2120, "if obj is None:"], [1677, "def get_inline_formsets(self, request, formsets, inline_instances, obj=None):"], [2338, "\"\"\"Hook for customizing the max number of extra inline forms.\"\"\""], [435, "model = self.model"], [470, "model = field.path_infos[-1].to_opts.model"]], "BM25": [[415, "admin site. This is used by changelist_view."], [623, "list_editable = ()"], [605, "Can be overridden by the user in subclasses. In such case it should"], [568, "Can be overridden by the user in subclasses. In such case it should"], [553, "Can be overridden by the user in subclasses. In such case it should"]], "GOLD": [[2021, "changecount += 1"], [2020, "self.log_change(request, obj, change_msg)"], [2019, "change_msg = self.construct_change_message(request, form, None)"], [2015, "if form.has_changed():"], [2017, "self.save_model(request, obj, form, change=True)"]]}, "sympy__sympy-12489__a6c43802": {"H": [[211, "return b"], [167, "return inv_form"], [1129, ">>> from sympy.combinatorics import Permutation"], [522, ">>> [p(q(i)) for i in range(p.size)]"], [2263, "The index of a permutation is the sum of all subscripts j such"]], "WRONG": [[2263, "The index of a permutation is the sum of all subscripts j such"], [522, ">>> [p(q(i)) for i in range(p.size)]"], [521, "[2, 0, 1]"], [503, ">>> [i^p for i in range(p.size)]"], [791, "\"\"\""]], "BM25": [[2831, "_af_new = Perm._af_new"], [933, "in a method, so p = Perm._af_new(a) is the only object"], [942, ">>> p = Perm._af_new(a)"], [1439, "return _af_new(a)"], [2426, "return _af_new(perm)"]], "GOLD": [[1227, "\"\"\""], [1166, "def __sub__(self, other):"], [2741, "\"\"\""], [2484, "Gets the precedence matrix. This is used for computing the"], [929, "\"\"\"A method to produce a Permutation object from a list;"]]}, "sympy__sympy-21930__49b5e398": {"H": [[2580, "the dummy order. However, a consistent substitution guided by the ordered"], [2014, "split = ("], [2662, "masked_facs = dict(list(zip(dumstruct, masked_facs)))"], [2042, "{Fd(p)*F(q)} = {Fd(a)*F(b)} + {Fd(a)*F(i)} + {Fd(j)*F(b)} -{F(i)*Fd(j)}"], [2402, "dummy variables, where the order is determined by the index range, what"]], "WRONG": [[1290, "return FockStateBosonKet(*self.args)"], [492, "Is this FermionicOperator restricted with respect to fermi level?"], [2662, "masked_facs = dict(list(zip(dumstruct, masked_facs)))"], [2580, "the dummy order. However, a consistent substitution guided by the ordered"], [1972, ">>> from textwrap import fill"]], "BM25": [[89, ">>> from sympy.physics.secondquant import Dagger, B, Bd"], [116, ">>> from sympy.physics.secondquant import Dagger, B, Bd"], [481, "return \"b^\\\\dagger_{%s}\" % self.state.name"], [119, ">>> Dagger(B(0))"], [92, ">>> Dagger(B(0))"]], "GOLD": [[942, "return \"a^\\\\dagger_{%s}\" % self.state.name"], [221, "return \"%s^{%s}_{%s}\" % ("], [685, "return Mul(self, state)"], [581, "The same applies to creation operators Fd"], [481, "return \"b^\\\\dagger_{%s}\" % self.state.name"]]}, "matplotlib__matplotlib-24970__1417350f": {"H": [[1586, "def make_norm_from_scale(scale_cls, base_norm_cls=None, *, init=None):"], [1525, "self.halfrange = max(self._vcenter-A.min(),"], [2607, "return np.where(rgb <= 0.5, low, high)"], [1880, "raise ValueError(\"minvalue must be less than or equal to maxvalue\")"], [2008, "# index computed above to full range of the color bins. This"]], "WRONG": [[2464, "Additional kwargs are passed on to the *blend_mode* function."], [1972, "self._scale = None # don't use the default scale."], [1603, "parameters will be forwarded to the base class (``Normalize.__init__``),"], [2453, "the *blend_mode* function."], [1777, "set to 1. If ``False`` masked values remain masked."]], "BM25": [[55, "import numpy as np"], [732, "xa[mask_bad] = self._i_bad"], [731, "xa[xa < 0] = self._i_under"], [730, "xa[xa > self.N - 1] = self._i_over"], [743, "alpha *= 255 # Will be cast to uint8 upon assignment."]], "GOLD": [[721, "# truncate them towards zero."], [722, "xa[xa < 0] = -1"], [718, "with np.errstate(invalid=\"ignore\"):"], [726, "np.clip(xa, -1, self.N, out=xa)"], [725, "# Avoid converting large positive values to negative integers."]]}, "sphinx-doc__sphinx-8269__bb67587a": {"H": [[172, "raise Exception(__(\"Anchor '%s' not found\") % anchor)"], [194, "return 'broken', str(err), 0"], [180, "except HTTPError:"], [295, "logger.info(red('broken ') + uri + red(' - ' + info))"], [291, "if self.app.quiet or self.app.warningiserror:"]], "WRONG": [[296, "self.write_entry('broken', docname, filename, lineno, uri + ': ' + info)"], [71, "chunk = chunk.decode() # manually try to decode it"], [18, "from typing import Any, Dict, List, Set, Tuple"], [186, "except HTTPError as err:"], [242, "status, info, code = check_uri()"]], "BM25": [[176, "# the server and the network"], [165, "if anchor and self.app.config.linkcheck_anchors:"], [217, "elif not uri.startswith(('http:', 'https:')):"], [68, "# the loop early in hopes not to have to download the whole thing."], [2, "sphinx.builders.linkcheck"]], "GOLD": [[249, "self.broken[uri] = info"], [277, "if status == 'ignored':"], [168, "auth=auth_info, **kwargs)"], [281, "logger.info(darkgray('-ignored- ') + uri)"], [169, "found = check_anchor(response, unquote(anchor))"]]}, "django__django-14771__46e69f28": {"H": [[562, "self.client.receive()"], [476, "expression = ['name', filenames, 'wholename']"], [136, "continue"], [176, "path_parts = sorted([x.parts for x in paths], key=len, reverse=True)"], [441, "logger.debug('Watchman watch-project result: %s', result)"]], "WRONG": [[476, "expression = ['name', filenames, 'wholename']"], [356, "results = file_changed.send(sender=self, file_path=path)"], [610, "return StatReloader()"], [176, "path_parts = sorted([x.parts for x in paths], key=len, reverse=True)"], [630, "logger.info('Watching for file changes with %s', reloader.__class__.__name__)"]], "BM25": [[297, "def wait_for_apps_ready(self, app_reg, django_main_thread):"], [309, "if app_reg.ready_event.wait(timeout=0.1):"], [224, "# see https://docs.python.org/3/reference/import.html#main-spec"], [132, "# See https://docs.python.org/reference/import.html#main-spec"], [18, "from django.apps import apps"]], "GOLD": [[121, "\"\"\"Iterate through all modules needed to be watched.\"\"\""], [343, "This generator is called in a loop from run_loop. It's important that"], [222, "args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions]"], [306, "event."], [223, "# __spec__ is set when the server was started with the `-m` option,"]]}, "django__django-12143__3c42de3e": {"H": [[1634, "pk_pattern = re.compile(r'{}-\\d+-{}$'.format(prefix, self.model._meta.pk.name))"], [1834, "if obj is None:"], [1635, "return [value for key, value in request.POST.items() if pk_pattern.match(key)]"], [1499, "def _get_obj_does_not_exist_redirect(self, request, opts, object_id):"], [6, "from urllib.parse import quote as urlquote"]], "WRONG": [[402, "model = field.get_path_info()[-1].to_opts.model"], [1834, "if obj is None:"], [2016, "\"\"\"Hook for customizing the max number of extra inline forms.\"\"\""], [1918, "\"Helper function to generate formsets for add/change_view.\""], [1496, "initial[k] = initial[k].split(\",\")"]], "BM25": [[1634, "pk_pattern = re.compile(r'{}-\\d+-{}$'.format(prefix, self.model._meta.pk.name))"], [1635, "return [value for key, value in request.POST.items() if pk_pattern.match(key)]"], [1049, "posts a message using the django.contrib.messages backend."], [906, "or the name of a method on the ModelAdmin. Return is a tuple of"], [1644, "validate = queryset.model._meta.pk.to_python"]], "GOLD": [[138, "# If the field specifies choices, we don't need to look for special"], [621, "path('/', wrap(RedirectView.as_view("], [2041, "'exclude': exclude,"], [1139, "'save_as': self.save_as,"], [1634, "pk_pattern = re.compile(r'{}-\\d+-{}$'.format(prefix, self.model._meta.pk.name))"]]}, "django__django-13512__31911315": {"H": [[428, "return str(value)"], [403, "return field.get_prep_value(value)"], [426, "return ', '.join(str(v) for v in value)"], [402, "try:"], [60, "elif key.endswith('__isnull'):"]], "WRONG": [[136, "None, (quote(obj.pk),))"], [400, "return format_html('{}', value.url, value)"], [60, "elif key.endswith('__isnull'):"], [549, "changed_field_labels.append(str(verbose_field_name))"], [546, "verbose_field_name = form.fields[field_name].label or field_name"]], "BM25": [[401, "elif isinstance(field, models.JSONField) and value:"], [495, "Construct a JSON structure describing changes from a changed object."], [70, "different so that it doesn't get automatically unquoted by the Web browser."], [147, "# Don't display link to edit, because it either has no"], [85, "for field in fields:"]], "GOLD": [[2, "import decimal"], [3, "from collections import defaultdict"], [23, "\"\"\"A field is a foreign key attname, i.e. _id.\"\"\""], [130, "perms_needed.add(opts.verbose_name)"], [403, "return field.get_prep_value(value)"]]}, "django__django-13512__d7e069df": {"H": [[963, "cleaned by the first field, the second value is cleaned by the second"], [1238, "converted = json.loads(value, cls=self.decoder)"], [1041, "clean_data.append(field.clean(field_value))"], [1261, "return json.dumps(value, cls=self.encoder)"], [69, "# version of the form field name, if the Field is part of a"]], "WRONG": [[963, "cleaned by the first field, the second value is cleaned by the second"], [1041, "clean_data.append(field.clean(field_value))"], [225, "if value not in self.empty_values:"], [80, "# disabled -- Boolean that specifies whether the field is disabled, that"], [42, "'JSONField', 'SlugField', 'TypedChoiceField', 'TypedMultipleChoiceField',"]], "BM25": [[68, "# field in a form. By default, Django will use a \"pretty\""], [1219, "class JSONField(CharField):"], [7, "import json"], [1261, "return json.dumps(value, cls=self.encoder)"], [1255, "except json.JSONDecodeError:"]], "GOLD": [[983, "self.error_messages['incomplete'])"], [874, "for val in value:"], [460, "if isinstance(value, datetime.date):"], [1261, "return json.dumps(value, cls=self.encoder)"], [1192, "}"]]}, "django__django-16938__9e02fad0": {"H": [[88, "self._current[field.name] = [m2m_value(related) for related in m2m_iter]"], [82, "return getattr(obj, field.name).only(\"pk\").iterator()"], [84, "m2m_iter = getattr(obj, \"_prefetched_objects_cache\", {}).get("], [90, "def getvalue(self):"], [76, "else:"]], "WRONG": [[31, "self.objects.append(self.get_dump_object(obj))"], [35, "data = {\"model\": str(obj._meta)}"], [169, "data[field.attname] = value"], [173, "data[field.name] = field.to_python(field_value)"], [180, "yield base.DeserializedObject(obj, m2m_data, deferred_fields)"]], "BM25": [[88, "self._current[field.name] = [m2m_value(related) for related in m2m_iter]"], [9, "from django.db import DEFAULT_DB_ALIAS, models"], [55, "related = getattr(obj, field.name)"], [56, "if related:"], [8, "from django.core.serializers import base"]], "GOLD": [[53, "field.remote_field.model, \"natural_key\""], [2, "A Python \"serializer\". Doesn't do much serializing per se -- just converts to"], [74, "return getattr(obj, field.name).iterator()"], [106, "for d in object_list:"], [82, "return getattr(obj, field.name).only(\"pk\").iterator()"]]}, "django__django-16938__d588ffdd": {"H": [[133, "if field.remote_field.through._meta.auto_created:"], [152, "else:"], [324, "return model._meta.get_field(field.remote_field.field_name).to_python("], [150, "return getattr(obj, field.name).iterator()"], [138, "# If the objects in the m2m have a natural key, use it"]], "WRONG": [[324, "return model._meta.get_field(field.remote_field.field_name).to_python("], [311, "# If this is a natural foreign key to an object that"], [75, "self.xml.startElement("], [133, "if field.remote_field.through._meta.auto_created:"], [152, "else:"]], "BM25": [[13, "from django.db import DEFAULT_DB_ALIAS, models"], [224, "# {m2m_accessor_attribute : [list_of_related_objects]})"], [113, "related = getattr(obj, field.name)"], [117, "for key_value in related:"], [109, "if related_att is not None:"]], "GOLD": [[158, "return getattr(obj, field.name).only(\"pk\").iterator()"], [356, "values = []"], [368, "def _get_model_from_node(self, node, attr):"], [271, "data[field.attname] = value"], [280, "data[field.name] = value"]]}, "pydata__xarray-4356__bd916ff7": {"H": [[115, "return _maybe_null_out(result, axis, mask, min_count)"], [30, "raise ValueError("], [42, "null_mask = mask.size - mask.sum()"], [85, "def nanmax(a, axis=None, out=None):"], [96, "return _nan_argminmax_object(\"argmin\", fill_value, a, axis=axis)"]], "WRONG": [[96, "return _nan_argminmax_object(\"argmin\", fill_value, a, axis=axis)"], [54, "value = fillna(value, fill_value)"], [112, "a, mask = _replace_nan(a, 0)"], [55, "data = _dask_or_eager_func(func)(value, axis=axis, **kwargs)"], [44, "result = np.nan"]], "BM25": [[31, "\"min_count is not available for reduction with more than one dimensions.\""], [184, "if min_count is not None:"], [114, "if min_count is not None:"], [35, "null_mask = (mask.shape[axis] - mask.sum(axis) - min_count) < 0"], [43, "if null_mask < min_count:"]], "GOLD": [[35, "null_mask = (mask.shape[axis] - mask.sum(axis) - min_count) < 0"], [29, "if hasattr(axis, \"__len__\"): # if tuple or list"], [31, "\"min_count is not available for reduction with more than one dimensions.\""], [30, "raise ValueError("], [32, ")"]]}, "sympy__sympy-13480__fe6e1f3f": {"H": [[142, "if arg.func == acoth:"], [975, "(sqrt(3) - 1)/sqrt(2**3): 5*S.Pi/12,"], [906, "return (-1)**k * R / F * x**n / n"], [54, "for a in Add.make_args(arg):"], [1306, "return sech"]], "WRONG": [[1114, "* acoth(x) -> Returns the inverse hyperbolic cotangent of x"], [366, "tanh_half = tanh(S.Half*arg)**2"], [142, "if arg.func == acoth:"], [1205, "3*I*pi/4"], [369, "def _eval_rewrite_as_coth(self, arg):"]], "BM25": [[743, "The hyperbolic cosecant function, `\\frac{2}{e^x - e^{-x}}`"], [241, "The hyperbolic cosine function, `\\frac{e^x + e^{-x}}{2}`."], [794, "The hyperbolic secant function, `\\frac{2}{e^x + e^{-x}}`"], [72, "The hyperbolic sine function, `\\frac{e^x - e^{-x}}{2}`."], [590, "if cotm is S.ComplexInfinity:"]], "GOLD": [[592, "else: # cothm == 0"], [59, "K, p = a.as_two_terms()"], [936, "asinh, atanh, cosh"], [590, "if cotm is S.ComplexInfinity:"], [236, "return True"]]}, "psf__requests-1142__afd5aad8": {"H": [[389, "self.headers['Content-Length'] = '0'"], [395, "self.headers['Content-Length'] = str(len(body))"], [394, "elif body is not None:"], [27, "cookielib, urlparse, urlunparse, urlsplit, urlencode, str, bytes, StringIO,"], [32, "ITER_CHUNK_SIZE = 512"]], "WRONG": [[560, "if self.status_code is 0:"], [452, "#: Requires that ``stream=True` on the request."], [566, "self._content = None"], [292, "netloc = netloc.encode('idna').decode('utf-8')"], [626, "header = self.headers['link']"]], "BM25": [[243, ">>> req = requests.Request('GET', 'http://httpbin.org/get')"], [175, ">>> req = requests.Request('GET', 'http://httpbin.org/get')"], [256, "#: HTTP URL to send the request to."], [422, "cookie_header = get_cookie_header(cookies, self)"], [260, "#: request body to send to the server."]], "GOLD": [[389, "self.headers['Content-Length'] = '0'"], [397, "def prepare_auth(self, auth):"], [395, "self.headers['Content-Length'] = str(len(body))"], [210, "self.cookies = cookies"], [283, "pass"]]}, "django__django-16429__5459584c": {"H": [[9, "\"month\": ngettext_lazy(\"%(num)d month\", \"%(num)d months\", \"num\"),"], [70, "delta = now - d"], [72, "# Ignore microseconds."], [69, "d, now = now, d"], [66, "now = now or datetime.datetime.now(datetime.timezone.utc if is_aware(d) else None)"]], "WRONG": [[106, "count = remaining_time // chunk"], [73, "since = delta.days * 24 * 60 * 60 + delta.seconds"], [18, "TIME_CHUNKS = ["], [113, "for i, value in enumerate(partials):"], [121, "while i < len(TIME_STRINGS_KEYS) and current_depth < depth:"]], "BM25": [[85, "# Create a \"pivot\" datetime shifted from d by years and months, then use"], [30, "Take two datetime objects and return the time between d and now as a nicely"], [75, "# d is in the future compared to now, stop processing."], [40, "in the former case and 397 in the latter."], [66, "now = now or datetime.datetime.now(datetime.timezone.utc if is_aware(d) else None)"]], "GOLD": [[72, "# Ignore microseconds."], [99, "d.second,"], [101, "else:"], [81, "total_months -= 1"], [100, ")"]]}, "pytest-dev__pytest-5809__57b4a9a8": {"H": [[82, "\"lexer\": \"python3\" if sys.version_info[0] >= 3 else \"python\","], [86, "response = urlopen(url, data=urlencode(params).encode(\"ascii\")).read()"], [83, "\"expiry\": \"1week\","], [85, "url = \"https://bpaste.net\""], [113, "pastebinurl = create_new_paste(s)"]], "WRONG": [[58, "del tr._tw.__dict__[\"write\"]"], [86, "response = urlopen(url, data=urlencode(params).encode(\"ascii\")).read()"], [43, "s = s.encode(\"utf-8\")"], [104, "msg = rep.longrepr.reprtraceback.reprentries[-1].reprfileloc"], [37, "config._pastebinfile = tempfile.TemporaryFile(\"w+b\")"]], "BM25": [[70, ":returns: url to the pasted contents"], [56, "# undo our patching in the terminal reporter"], [85, "url = \"https://bpaste.net\""], [95, "import _pytest.config"], [33, "# this can happen when this function executes in a slave node"]], "GOLD": [[84, "}"], [83, "\"expiry\": \"1week\","], [80, "params = {"], [81, "\"code\": contents,"], [82, "\"lexer\": \"python3\" if sys.version_info[0] >= 3 else \"python\","]]}, "django__django-13279__04481db4": {"H": [[126, "encoded_data = base64.b64decode(session_data.encode('ascii'))"], [119, "# RemovedInDjango40Warning: when the deprecation ends, handle here"], [122, "return self._legacy_decode(session_data)"], [129, "hash, serialized = encoded_data.split(b':', 1)"], [51, "self.modified = False"]], "WRONG": [[366, "raise NotImplementedError('subclasses of SessionBase must provide a load() method')"], [269, "if isinstance(expiry, datetime):"], [298, "self['_session_expiry'] = value"], [128, "# could produce ValueError if there is no ':'"], [129, "hash, serialized = encoded_data.split(b':', 1)"]], "BM25": [[302, "Return ``True`` if the session is set to expire when the browser"], [160, "# To avoid unnecessary persistent storage accesses, we set up the"], [84, "args = () if default is self.__not_given else (default,)"], [357, "Delete the session data under this key. If the key is None, use the"], [161, "# internals directly (loading data wastes time, since we are going to"]], "GOLD": [[124, "def _legacy_decode(self, session_data):"], [233, "\"\"\""], [110, "\"Return the given session dictionary serialized and encoded as a string.\""], [122, "return self._legacy_decode(session_data)"], [111, "return signing.dumps("]]}, "django__django-15161__fe637a3e": {"H": [[857, "alias, target = self.alias, self.target"], [381, "yield expr"], [393, "@deconstructible"], [636, "return self"], [932, "# Casting to numeric is unnecessary."]], "WRONG": [[636, "return self"], [1162, "clone.query = clone.query.clone()"], [298, "sources_iter = (source for source in self.get_source_fields() if source is not None)"], [1094, "c.cases[pos] = case.resolve_expression(query, allow_joins, reuse, summarize, for_save)"], [857, "alias, target = self.alias, self.target"]], "BM25": [[581, "@deconstructible(path='django.db.models.F')"], [10, "from django.db.models import fields"], [12, "from django.db.models.query_utils import Q"], [11, "from django.db.models.constants import LOOKUP_SEP"], [13, "from django.utils.deconstruct import deconstructible"]], "GOLD": [[985, "return \"{}({})\".format(self.__class__.__name__, self.expression)"], [953, "return super().as_sql(*args, **kwargs)"], [1228, "class OrderBy(Expression):"], [988, "class When(Expression):"], [1055, "class Case(SQLiteNumericMixin, Expression):"]]}, "django__django-15930__fe637a3e": {"H": [[328, "source for source in self.get_source_fields() if source is not None"], [852, "return self"], [1364, "c.cases[pos] = case.resolve_expression("], [31, "sql = \"CAST(%s AS NUMERIC)\" % sql"], [1332, "template = \"CASE %(cases)s ELSE %(default)s END\""]], "WRONG": [[852, "return self"], [328, "source for source in self.get_source_fields() if source is not None"], [198, "assert not exprs"], [920, "c.source_expressions[pos] = arg.resolve_expression("], [449, "yield expr"]], "BM25": [[1579, "# in a CASE WHEN."], [1653, "\"Window.order_by must be either a string reference to a \""], [1632, "self.order_by = order_by"], [1510, "sql = \"CASE WHEN {} THEN 1 ELSE 0 END\".format(sql)"], [1585, "When(self.expression, then=True),"]], "GOLD": [[738, "def as_sql(self, compiler, connection):"], [1301, "condition_sql, condition_params = compiler.compile(self.condition)"], [1302, "template_params[\"condition\"] = condition_sql"], [1440, "clone.query = clone.query.clone()"], [1551, "def as_sql(self, compiler, connection, template=None, **extra_context):"]]}, "django__django-11276__89d6614a": {"H": [[46, "return mark_safe(str(text).translate(_html_escapes))"], [8, ")"], [268, "return text.replace('&', '&').replace('<', '<').replace("], [32, "ord(\"'\"): ''',"], [10, "from django.utils.functional import Promise, keep_lazy, keep_lazy_text"]], "WRONG": [[61, "ord('\\u2029'): '\\\\u2029'"], [56, "ord('='): '\\\\u003D',"], [107, "return escape(text)"], [105, "return text.__html__()"], [350, "middle = '%s' % (escape(url), nofollow_attr, trimmed)"]], "BM25": [[99, "This function relies on the __html__ convention used both by Django's"], [209, "# See also https://bugs.python.org/issue16285"], [374, "A decorator that defines the __html__ method. This helps non-Django"], [83, "Escape all the HTML/XML special characters with their unicode escapes, so"], [5, "from html.parser import HTMLParser"]], "GOLD": [[3, "import json"], [31, "ord('\"'): '"',"], [28, "ord('&'): '&',"], [268, "return text.replace('&', '&').replace('<', '<').replace("], [27, "_html_escapes = {"]]}, "sphinx-doc__sphinx-10323__bd7aecb3": {"H": [[346, "lines.insert(0, prepend + '\\n')"], [60, "new_line = line[dedent:]"], [55, "if any(s[:dedent].strip() for s in lines):"], [417, "retnode: Element = nodes.literal_block(text, text, source=filename)"], [415, "text, lines = reader.read(location=location)"]], "WRONG": [[257, "self.lineno_start = start"], [217, "(self.encoding, filename)) from exc"], [275, "raise ValueError(__('Cannot use \"lineno-match\" with a disjoint '"], [448, "return [document.reporter.warning(exc, line=self.lineno)]"], [221, "lines = self.show_diff()"]], "BM25": [[166, "# when options['name'] is provided, it should be primary ID."], [443, "# when options['name'] is provided, it should be primary ID."], [458, "'version': 'builtin',"], [148, "# configuration."], [27, "Directive to set the highlighting language for code blocks, as well"]], "GOLD": [[228, "self.append_filter,"], [227, "self.prepend_filter,"], [229, "self.dedent_filter]"], [226, "self.lines_filter,"], [248, "tags = analyzer.find_tags()"]]}, "django__django-15098__5682903b": {"H": [[105, "result = cat.get(key, missing)"], [551, "return get_supported_language_variant(accept_lang)"], [538, "return get_supported_language_variant(lang_code)"], [513, "return get_supported_language_variant(lang_code, strict=strict)"], [556, "return get_supported_language_variant(settings.LANGUAGE_CODE)"]], "WRONG": [[358, "result = translation_object.gettext(eol_message)"], [105, "result = cat.get(key, missing)"], [355, "_default = _default or translation(settings.LANGUAGE_CODE)"], [547, "if not language_code_re.search(accept_lang):"], [569, "result = []"]], "BM25": [[542, "accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')"], [564, "Parse the lang_string, which is the body of an HTTP Accept-Language"], [473, "as the provided language codes are taken from the HTTP request. See also"], [443, "as the provided language codes are taken from the HTTP request. See also"], [36, "([A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*|\\*) # \"en\", \"en-au\", \"x-y-z\", \"es-419\", \"*\""]], "GOLD": [[46, "language_code_prefix_re = _lazy_re_compile(r'^/(\\w+([@-]\\w+)?)(/|$)')"], [57, "get_languages.cache_clear()"], [258, "tmsg = msgid2"], [58, "get_supported_language_variant.cache_clear()"], [557, "except LookupError:"]]}, "pylint-dev__pylint-6386__11613171": {"H": [[175, "This is based on the parameters passed to argparse.ArgumentsParser.add_message."], [140, "\"\"\"Class representing an argument to be parsed by an argparse.ArgumentsParser."], [326, "\"\"\"Class for extend arguments to be parsed by an argparse.ArgumentsParser."], [251, "This is based on the parameters passed to argparse.ArgumentsParser.add_message."], [267, "super().__init__("]], "WRONG": [[202, "\"\"\"Class representing a store argument to be parsed by an argparse.ArgumentsParser."], [204, "This is based on the parameters passed to argparse.ArgumentsParser.add_message."], [17, "from typing import Any, Pattern, Sequence, Tuple, Union"], [173, "\"\"\"Base class for store arguments to be parsed by an argparse.ArgumentsParser."], [129, "}"]], "BM25": [[7, "An Argument instance represents a pylint option to be handled by an argparse.ArgumentParser"], [163, "\"\"\"The description of the argument.\"\"\""], [198, "\"\"\"The default value of the argument.\"\"\""], [306, "\"\"\"The default value of the argument.\"\"\""], [156, "\"\"\"The name of the argument.\"\"\""]], "GOLD": [[57, "return pylint_utils._check_csv(value)"], [302, "self.action = action"], [460, ") -> None:"], [459, "section: str | None,"], [469, "\"\"\"Any additional arguments passed to the action.\"\"\""]]}, "pylint-dev__pylint-6386__74424d91": {"H": [[750, "self.config = self._arg_parser.parse_known_args("], [373, "option = optikcontainer.add_option(*args, **optdict)"], [209, "section_group.add_argument("], [408, "del optdict[\"short\"]"], [609, "(options, args) = self.cmdline_parser.parse_args(args=args)"]], "WRONG": [[700, "# Create a comment if the option has no value"], [402, "optdict[\"help\"] += \" [current: %default]\" # type: ignore[operator]"], [33, "_StoreTrueArgument,"], [750, "self.config = self._arg_parser.parse_known_args("], [238, "self.config = self._arg_parser.parse_args([], self.config)"]], "BM25": [[497, "if verbose:"], [522, "if verbose:"], [667, "# Skip the options section with the --help option"], [40, "from pylint.config.option import Option"], [145, "\"\"\"Add an argument to the correct argument section/group.\"\"\""]], "GOLD": [[723, "# Make sure the string we produce is valid toml and can be parsed"], [221, ")"], [747, "DeprecationWarning,"], [220, "help=argument.help,"], [243, "arguments, self.config"]]}, "pylint-dev__pylint-6386__6368f3fc": {"H": [[124, "return _StoreOldNamesArgument("], [188, "assert value is None"], [241, "raise ArgumentPreprocessingError(f\"Option {option} expects a value\")"], [244, "raise ArgumentPreprocessingError(f\"Option {option} doesn't expects a value\")"], [96, "dest=optdict.get(\"dest\", None),"]], "WRONG": [[17, "_CallableArgument,"], [13, "from typing import TYPE_CHECKING, Any"], [15, "from pylint import extensions, utils"], [156, "return str(value)"], [246, "cb(run, value)"]], "BM25": [[80, "\"the option's default value. This key will be required in pylint \""], [244, "raise ArgumentPreprocessingError(f\"Option {option} doesn't expects a value\")"], [45, "\"Use 'hide' with a boolean to hide an option from the help message.\","], [241, "raise ArgumentPreprocessingError(f\"Option {option} expects a value\")"], [209, "\"--verbose\": (False, _set_verbose_mode),"]], "GOLD": [[210, "\"--enable-all-extensions\": (False, _enable_all_extensions),"], [74, ")"], [73, "section=optdict.get(\"group\", None),"], [221, "if not argument.startswith(\"--\"):"], [209, "\"--verbose\": (False, _set_verbose_mode),"]]}, "pylint-dev__pylint-6386__c448acd7": {"H": [[275, "},"], [478, "},"], [392, ")"], [317, "},"], [531, "\"short\": \"E\","]], "WRONG": [[524, "},"], [11, "from typing import TYPE_CHECKING"], [275, "},"], [31, "from pylint.typing import Options"], [217, "'\"--disable=all --enable=similarities\". '"]], "BM25": [[539, "\"verbose\","], [196, "'See also the \"--disable\" option for examples.',"], [361, "\"Will default to the version used to run pylint.\""], [564, "\"help\": \"Show more verbose help.\","], [31, "from pylint.typing import Options"]], "GOLD": [[556, "\"hide_from_config_file\": True,"], [557, "},"], [547, "},"], [546, "\"hide_from_config_file\": True,"], [451, "{"]]}, "pydata__xarray-4687__293280a1": {"H": [[917, "support dask arrays (e.g. converts them to numpy arrays)."], [1037, "Most of NumPy's builtin functions already broadcast their inputs"], [766, "for dim, new_size in var.sizes.items():"], [895, "- 'inner': take only overlapped variables"], [1820, ")"]], "WRONG": [[1259, "return _cov_corr(da_a, da_b, dim=dim, ddof=ddof, method=\"cov\")"], [1225, "* time (time) datetime64[ns] 2000-01-01 2000-01-02 2000-01-03"], [1794, "* lat (lat) int64 0 1 2"], [958, "You can now apply ``magnitude()`` to :py:class:`DataArray` and :py:class:`Dataset`"], [933, "``dask_gufunc_kwargs`` parameter . It will be removed as direct parameter"]], "BM25": [[554, "SLICE_NONE = slice(None)"], [472, "dummy = None"], [196, "name = None"], [1071, "if kwargs is None:"], [1116, "if keep_attrs is None:"]], "GOLD": [[1747, "Returns"], [1745, "values to choose from where `cond` is False"], [1730, "def where(cond, x, y):"], [1810, "\"\"\""], [1819, "dask=\"allowed\","]]}, "sympy__sympy-12481__a6c43802": {"H": [[1133, ">>> from sympy.combinatorics import Permutation"], [518, ">>> [(p*q)(i) for i in range(p.size)]"], [1895, ">>> from sympy.combinatorics import Permutation"], [100, "a, b = a"], [735, "The product of two permutations p and q is defined as their composition as"]], "WRONG": [[2267, "The index of a permutation is the sum of all subscripts j such"], [522, ">>> [p(q(i)) for i in range(p.size)]"], [1133, ">>> from sympy.combinatorics import Permutation"], [503, ">>> [i^p for i in range(p.size)]"], [2252, ">>> Permutation([0, 1, 2]).full_cyclic_form"]], "BM25": [[1564, "# gets called a lot and should be fast"], [840, "in the cycles:"], [892, "# if there are n elements present, 0, 1, ..., n-1 should be present"], [2664, "raise ValueError(\"The permutations must be of the same size.\")"], [2627, "raise ValueError(\"The permutations must be of the same size.\")"]], "GOLD": [[899, "if is_cycle:"], [901, "'cycles use Cycle%s.' % ''.join([str(tuple(c)) for c in args]))"], [903, "raise ValueError('there were repeated elements.')"], [902, "else:"], [898, "if has_dups(temp):"]]}, "django__django-12713__3c42de3e": {"H": [[401, "model = field.get_path_info()[-1].to_opts.model"], [1849, "if obj is None:"], [760, "Return a Form class for use in the Formset on the changelist page."], [658, "return self.get_form(request, obj, fields=None)"], [1745, "formset = cl.formset = FormSet(request.POST, request.FILES, queryset=modified_objects)"]], "WRONG": [[1849, "if obj is None:"], [401, "model = field.get_path_info()[-1].to_opts.model"], [2031, "\"\"\"Hook for customizing the max number of extra inline forms.\"\"\""], [708, "def get_changelist(self, request, **kwargs):"], [1745, "formset = cl.formset = FormSet(request.POST, request.FILES, queryset=modified_objects)"]], "BM25": [[155, "formfield = self.formfield_for_manytomany(db_field, request, **kwargs)"], [242, "def formfield_for_manytomany(self, db_field, request, **kwargs):"], [153, "formfield = self.formfield_for_foreignkey(db_field, request, **kwargs)"], [218, "def formfield_for_foreignkey(self, db_field, request, **kwargs):"], [77, "FORMFIELD_FOR_DBFIELD_DEFAULTS = {"]], "GOLD": [[257, "elif db_field.name in [*self.filter_vertical, *self.filter_horizontal]:"], [258, "kwargs['widget'] = widgets.FilteredSelectMultiple("], [261, ")"], [252, "autocomplete_fields = self.get_autocomplete_fields(request)"], [255, "elif db_field.name in self.raw_id_fields:"]]}, "django__django-10999__4db1d116": {"H": [[32, "r'((?:(?P-?\\d+):)(?=\\d+:\\d+))?'"], [63, "r'(?:\\.(?P\\d{1,6}))?'"], [29, "standard_duration_re = re.compile("], [44, "r'(?:(?P\\d+(.\\d+)?)D)?'"], [39, "# Support the sections of ISO 8601 date representation that are accepted by"]], "WRONG": [[39, "# Support the sections of ISO 8601 date representation that are accepted by"], [13, "date_re = re.compile("], [63, "r'(?:\\.(?P\\d{1,6}))?'"], [114, "offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0"], [11, "from django.utils.timezone import get_fixed_timezone, utc"]], "BM25": [[32, "r'((?:(?P-?\\d+):)(?=\\d+:\\d+))?'"], [60, "r'(?P\\d+):'"], [46, "r'(?:(?P\\d+(.\\d+)?)H)?'"], [44, "r'(?:(?P\\d+(.\\d+)?)D)?'"], [61, "r'(?P\\d\\d):'"]], "GOLD": [[34, "r'(?P-?\\d+)'"], [72, "Return None if the input isn't well formatted."], [32, "r'((?:(?P-?\\d+):)(?=\\d+:\\d+))?'"], [33, "r'(?:(?P-?\\d+):)?'"], [88, "\"\"\""]]}, "django__django-14500__191c6b80": {"H": [[279, "self.recorder.record_applied(*key)"], [196, "self.unapply_migration(states[migration], migration, fake=fake)"], [206, "for migration, _ in full_plan[index:]:"], [197, "applied_migrations.remove(migration)"], [195, "for migration, _ in plan:"]], "WRONG": [[174, "# We remove every migration that we applied from this set so"], [79, "migration.mutate_state(state, preserve=False)"], [208, "migration.mutate_state(state, preserve=False)"], [2, "from django.db import migrations, router"], [370, "return False, project_state"]], "BM25": [[10, "class MigrationExecutor:"], [200, "# the last migration is unapplied and mutating it to include all the"], [272, "be applied, but the applied state of the squashed migration must be"], [205, "if migration == last_unapplied_migration:"], [202, "last_unapplied_migration = plan[-1][0]"]], "GOLD": [[252, "state = migration.unapply(state, schema_editor)"], [257, "else:"], [253, "# For replacement migrations, record individual statuses"], [298, ")"], [258, "self.recorder.record_unapplied(migration.app_label, migration.name)"]]}, "django__django-13794__31c53995": {"H": [[149, "if self._delegate_bytes:"], [336, "__ne__ = new_method_proxy(operator.ne)"], [140, "return func(*self.__args, **self.__kw)"], [176, "return str(self) % rhs"], [175, "if self._delegate_text:"]], "WRONG": [[148, "def __cast(self):"], [149, "if self._delegate_bytes:"], [154, "return func(*self.__args, **self.__kw)"], [143, "return bytes(func(*self.__args, **self.__kw))"], [140, "return func(*self.__args, **self.__kw)"]], "BM25": [[213, "raise TypeError(\"You must pass at least one argument to keep_lazy().\")"], [209, "immediately, otherwise a __proxy__ is returned that will evaluate the"], [21, "raise TypeError("], [35, "raise TypeError("], [207, "A decorator that allows a function to be called with one or more lazy"]], "GOLD": [[104, ")"], [177, "return self.__cast() % rhs"], [221, "return lazy_func(*args, **kwargs)"], [179, "def __deepcopy__(self, memo):"], [308, "# self.__class__, because the latter is proxied."]]}, "django__django-14170__f592eccb": {"H": [[693, "return ''"], [118, "'subclasses of BaseDatabaseOperations may require a '"], [547, "lookup."], [134, "raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method')"], [552, "second = datetime.datetime(value, 12, 31, 23, 59, 59, 999999)"]], "WRONG": [[617, "return params"], [118, "'subclasses of BaseDatabaseOperations may require a '"], [104, "Given a lookup_type of 'year', 'month', or 'day', return the SQL that"], [693, "return ''"], [126, "raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_cast_time_sql() method')"]], "BM25": [[82, "This is used by the 'db' cache backend to determine where to start"], [566, "format, this is the hook for converter functions."], [9, "from django.db.backends import utils"], [529, "def year_lookup_bounds_for_date_field(self, value):"], [561, "def get_db_converters(self, expression):"]], "GOLD": [[529, "def year_lookup_bounds_for_date_field(self, value):"], [549, "`value` is an int, containing the looked-up year."], [537, "first = datetime.date(value, 1, 1)"], [551, "first = datetime.datetime(value, 1, 1)"], [538, "second = datetime.date(value, 12, 31)"]]}, "django__django-14170__b6b218ec": {"H": [[557, "rhs_sql = self.get_direct_rhs_sql(connection, rhs_sql)"], [561, "return super().as_sql(compiler, connection)"], [564, "return connection.operators[self.lookup_name] % rhs"], [559, "params.extend(self.get_bound_params(start, finish))"], [567, "raise NotImplementedError("]], "WRONG": [[43, "def batch_process_rhs(self, compiler, connection, rhs=None):"], [457, "if self.rhs_is_direct_value() and params and not self.bilateral_transforms:"], [287, "def process_rhs(self, compiler, connection):"], [316, "@Field.register_lookup"], [61, "if self.rhs_is_direct_value():"]], "BM25": [[607, "from django.db.models.functions import Replace"], [546, "bounds = connection.ops.year_lookup_bounds_for_date_field(year)"], [553, "# Skip the extract part by directly using the originating field,"], [558, "start, finish = self.year_lookup_bounds(connection, self.rhs)"], [288, "from django.db.models.sql.query import Query"]], "GOLD": [[276, "def as_postgresql(self, compiler, connection):"], [542, "output_field = self.lhs.lhs.output_field"], [541, "def year_lookup_bounds(self, connection, year):"], [546, "bounds = connection.ops.year_lookup_bounds_for_date_field(year)"], [544, "bounds = connection.ops.year_lookup_bounds_for_datetime_field(year)"]]}, "django__django-15103__0d09e983": {"H": [[86, "def json_script(value, element_id):"], [91, "return _json_script(value, element_id)"], [140, "if isinstance(arg, str):"], [89, "tag."], [96, "\"\"\""]], "WRONG": [[313, "\"\"\""], [42, "args[0] = str(args[0])"], [40, "def _dec(*args, **kwargs):"], [41, "args = list(args)"], [138, "force_grouping = False"]], "BM25": [[86, "def json_script(value, element_id):"], [91, "return _json_script(value, element_id)"], [16, "json_script as _json_script, linebreaks, strip_tags, urlize as _urlize,"], [88, "Output value JSON-encoded, wrapped in a ',"], [74, "element_id, mark_safe(json_str)"], [57, "_json_script_escapes = {"], [68, "the escaped JSON in a script tag."]], "GOLD": [[73, "'',"], [72, "return format_html("], [75, ")"], [64, "def json_script(value, element_id):"], [74, "element_id, mark_safe(json_str)"]]}, "sympy__sympy-13974__f7b19756": {"H": [[385, "return tensor_product_simp(e.base) ** e.exp"], [393, "return e"], [387, "return tensor_product_simp_Mul(e)"], [383, "return Add(*[tensor_product_simp(arg) for arg in e.args])"], [379, "(A*C)x(B*D)**2"]], "WRONG": [[120, "if isinstance(args[0], (Matrix, numpy_ndarray, scipy_sparse_matrix)):"], [187, "pform = prettyForm(*pform.right(',' + ' '))"], [125, "return c_part"], [393, "return e"], [383, "return Add(*[tensor_product_simp(arg) for arg in e.args])"]], "BM25": [[114, ">>> tp.expand(tensorproduct=True)"], [97, ">>> tp = TensorProduct(A, B)"], [60, "are pulled out in front of the ``TensorProduct``. Non-commutative arguments"], [111, ">>> tp = TensorProduct(A+B,C)"], [75, ">>> from sympy.physics.quantum import TensorProduct"]], "GOLD": [[344, "else:"], [324, "raise TypeError('TensorProduct expected, got: %r' % current)"], [345, "return e"], [340, "for i in range(len(new_args)):"], [19, ")"]]}, "django__django-14493__c7242ded": {"H": [[233, "refer to the cache-busting filenames."], [127, "unparsed_name[2] += '?'"], [382, "cache_name = self.clean_name("], [353, "yield name, hashed_name, processed, substitutions"], [256, "for name, hashed_name, processed, _ in self._post_process(paths, adjustable_paths, hashed_files):"]], "WRONG": [[351, "hashed_files[hash_key] = hashed_name"], [207, "hashed_url = self._url("], [127, "unparsed_name[2] += '?'"], [235, "If either of these are performed on a file, then that file is considered"], [233, "refer to the cache-busting filenames."]], "BM25": [[46, "max_post_process_passes = 5"], [381, "for i in range(self.max_post_process_passes + 1):"], [264, "for i in range(self.max_post_process_passes):"], [431, "yield from super().post_process(*args, **kwargs)"], [429, "def post_process(self, *args, **kwargs):"]], "GOLD": [[262, "paths = {path: paths[path] for path in adjustable_paths}"], [121, "(root, file_hash, ext))"], [264, "for i in range(self.max_post_process_passes):"], [29, "super().__init__(location, base_url, *args, **kwargs)"], [382, "cache_name = self.clean_name("]]}, "django__django-16612__57866af2": {"H": [[456, "return HttpResponsePermanentRedirect(\"%s/\" % request.path)"], [451, "match = resolve(\"%s/\" % request.path_info, urlconf)"], [457, "raise Http404"], [449, "urlconf = getattr(request, \"urlconf\", None)"], [448, "if settings.APPEND_SLASH and not url.endswith(\"/\"):"]], "WRONG": [[41, "functions that present a full admin interface for the collection of registered"], [303, "# labels for which we need to allow access to the app_index view,"], [600, "AdminSiteClass = import_string(apps.get_app_config(\"admin\").default_site)"], [95, "if modeladmin.model._meta.app_config in app_configs:"], [143, "admin_class = type("]], "BM25": [[447, "def catch_all_view(self, request, url):"], [11, "from django.http import Http404, HttpResponsePermanentRedirect, HttpResponseRedirect"], [456, "return HttpResponsePermanentRedirect(\"%s/\" % request.path)"], [69, "final_catch_all_view = True"], [311, "urlpatterns.append(re_path(r\"(?P.*)$\", wrap(self.catch_all_view)))"]], "GOLD": [[73, "self.name = name"], [38, "An AdminSite object encapsulates an instance of the Django admin application, ready"], [456, "return HttpResponsePermanentRedirect(\"%s/\" % request.path)"], [91, "modeladmins = ("], [57, "enable_nav_sidebar = True"]]}, "sphinx-doc__sphinx-8595__48ca4d65": {"H": [[298, "*directivetype*."], [2579, "from sphinx.ext.autodoc.deprecated import SlotsAttributeDocumenter # NOQA"], [127, "\"\"\"Used to convert the :members: option to auto directives.\"\"\""], [1736, "class DataDocumenterMixinBase:"], [1594, "return []"]], "WRONG": [[717, "# if the member __doc__ is the same as self's __doc__, it's just"], [2501, "class PropertyDocumenter(DocstringStripSignatureMixin, ClassLevelDocumenter): # type: ignore"], [1736, "class DataDocumenterMixinBase:"], [1784, "return (inspect.isNewType(self.object) or"], [1557, "sig = super().format_signature()"]], "BM25": [[1106, "# Sort by __all__"], [1026, "# invalid __all__ found."], [1110, "return self.__all__.index(name)"], [1022, "# __all__ raises an error."], [1112, "return len(self.__all__)"]], "GOLD": [[774, "keep = False"], [1077, "if not self.__all__:"], [1213, "if not match:"], [1134, "# ... or in the scope of a module directive"], [60, "(?: \\((.*)\\) # optional: arguments"]]}, "pydata__xarray-3305__3fbfbfa6": {"H": [[1914, "return type(self)(self.dims, numeric_array, self._attrs)"], [2192, "List of integer arrays which specifies the integer positions to which"], [1661, "return Variable(new_dims, qs)"], [103, "elif isinstance(obj, (set, dict)):"], [538, "elif not isinstance(k, integer_types):"]], "WRONG": [[800, "Data to use in the new object. Must have same shape as original."], [2210, "return Variable.concat(variables, dim, positions, shortcut)"], [103, "elif isinstance(obj, (set, dict)):"], [1091, "pad_width: Mapping of the form {dim: (before, after)}"], [398, "return self._data.__dask_scheduler__"]], "BM25": [[1404, "keep_attrs=None,"], [1476, "if keep_attrs is None:"], [1880, "attrs = self._attrs if keep_attrs else None"], [1478, "attrs = self._attrs if keep_attrs else None"], [1020, "keep = slice(None)"]], "GOLD": [[1617, "* midpoint: ``(i + j) / 2``."], [1619, "Returns"], [1654, "# only add the quantile dimension if q is array like"], [1626, "dimensions that remain after the reduction of the array."], [1595, "def quantile(self, q, dim=None, interpolation=\"linear\"):"]]}, "django__django-12754__a71b173d": {"H": [[128, "self.old_apps = self.from_state.concrete_apps"], [628, "),"], [989, "def create_altered_indexes(self):"], [511, "def generate_created_models(self):"], [1287, "required_apps = set(app_labels)"]], "WRONG": [[909, "isn's possible."], [109, "The resulting migrations aren't specially named, but the names"], [128, "self.old_apps = self.from_state.concrete_apps"], [996, "old_indexes = old_model_state.options[option_name]"], [822, "old_field = old_model_state.fields[rem_field_name]"]], "BM25": [[678, "Make CreateModel statements for proxy models. Use the same statements"], [6, "from django.db import models"], [773, "# a through model the field that references it."], [204, "deletion to the field that uses it."], [831, "# Was the field renamed and db_column equal to the"]], "GOLD": [[27, "depends on first). A user interface may offer single-app usage"], [1155, "self.kept_proxy_keys,"], [565, "dependencies.append((base_app_label, base_name, None, True))"], [487, "for field in model_opts.get_fields():"], [566, "# Depend on the other end of the primary key if it's a relation"]]}, "scikit-learn__scikit-learn-13496__522aed87": {"H": [[176, "verbose=0):"], [170, "contamination=\"legacy\","], [171, "max_features=1.,"], [121, "Controls the verbosity of the tree building process."], [177, "super().__init__("]], "WRONG": [[150, "Notes"], [292, "return self"], [299, "return self"], [306, "return self"], [410, "def _compute_chunked_score_samples(self, X):"]], "BM25": [[29, "class IsolationForest(BaseBagging, OutlierMixin):"], [24, "__all__ = [\"IsolationForest\"]"], [34, "The IsolationForest 'isolates' observations by randomly selecting a feature"], [32, "Return the anomaly score of each sample using the IsolationForest algorithm"], [346, "The input samples. Internally, it will be converted to"]], "GOLD": [[124, "Attributes"], [188, "n_jobs=n_jobs,"], [187, "max_features=max_features,"], [176, "verbose=0):"], [121, "Controls the verbosity of the tree building process."]]}, "sphinx-doc__sphinx-9698__6af9db04": {"H": [[1087, "class PythonModuleIndex(Index):"], [531, "def get_index_text(self, modname: str, name: Tuple[str, str]) -> str:"], [370, "class PyField(PyXrefMixin, Field):"], [1205, "}"], [1272, "if name[-2:] == '()':"]], "WRONG": [[531, "def get_index_text(self, modname: str, name: Tuple[str, str]) -> str:"], [1206, "indices = ["], [1205, "}"], [557, "if 'noindexentry' not in self.options:"], [1159, "class PythonDomain(Domain):"]], "BM25": [[1338, "# entry that defined by ``property`` directive."], [1185, "'property': PyProperty,"], [1331, "# fallback to meth (for property; Sphinx-2.4.x)"], [532, "\"\"\"Return the text for the index entry of the object.\"\"\""], [1336, "# fallback to attr (for property)"]], "GOLD": [[799, "return _('%s() (%s property)') % (methname, clsname)"], [273, "ends_open = ends_close = 0"], [821, "option_spec: OptionSpec = PyObject.option_spec.copy()"], [97, "# Note: It would be better to use qualname to describe the object to support support"], [393, "# None is not a type, so use obj role instead."]]}, "sympy__sympy-24066__b0b3e4d2": {"H": [[135, "return self.get_dimensional_expr(expr.base) ** expr.exp"], [132, "if isinstance(expr, Mul):"], [171, "exp_dim = 1"], [172, "return factor ** exp_factor, dim ** (exp_factor * exp_dim)"], [170, "if self.get_dimension_system().is_dimensionless(exp_dim):"]], "WRONG": [[183, "factor += addend_factor"], [137, "return self.get_dimensional_expr(expr.args[0])"], [200, "return expr, Dimension(1)"], [195, "return (expr.func(*(f[0] for f in fds)),"], [172, "return factor ** exp_factor, dim ** (exp_factor * exp_dim)"]], "BM25": [[152, "def _collect_factor_and_dimension(self, expr):"], [174, "factor, dim = self._collect_factor_and_dimension(expr.args[0])"], [186, "factor, dim = self._collect_factor_and_dimension(expr.args[0])"], [168, "factor, dim = self._collect_factor_and_dimension(expr.base)"], [169, "exp_factor, exp_dim = self._collect_factor_and_dimension(expr.exp)"]], "GOLD": [[195, "return (expr.func(*(f[0] for f in fds)),"], [76, "return self._dimension_system"], [194, "arg) for arg in expr.args]"], [196, "*(d[1] for d in fds))"], [193, "fds = [self._collect_factor_and_dimension("]]}, "astropy__astropy-13579__dac61873": {"H": [[185, "dropped_info[\"serialized_classes\"] = self.serialized_classes"], [44, "ind = e_ind + i"], [261, "pixel_arrays[ipixel] -= self._slices_pixel[ipixel].start"], [102, "return slice(start, stop)"], [17, "Given a slice as input sanitise it to an easier to parse format.format"]], "WRONG": [[134, "slices_original[ipixel_orig] = combine_slices(slices_original[ipixel_orig],"], [222, "pixel_arrays_new.append(pixel_arrays[ipix_curr] + self._slices_pixel[ipix].start)"], [221, "if self._slices_pixel[ipix].start is not None:"], [68, "if isinstance(slice1, slice) and slice1.step is not None:"], [241, "world_arrays = world_arrays[0]"]], "BM25": [[119, "A valid array slice to apply to the WCS."], [117, "The WCS to slice."], [107, "A Low Level WCS wrapper which applies an array slice to a WCS."], [227, "return self._wcs.pixel_to_world_values(*pixel_arrays_new)"], [257, "pixel_arrays = list(self._wcs.world_to_pixel_values(*world_arrays_new))"]], "GOLD": [[246, "world_arrays = tuple(map(np.asanyarray, world_arrays))"], [245, "def world_to_pixel_values(self, *world_arrays):"], [254, "world_arrays_new.append(1.)"], [229, "def pixel_to_world_values(self, *pixel_arrays):"], [181, "filter("]]}, "astropy__astropy-13398__eb5bbd9a": {"H": [[60, "# we define an __all__ because otherwise the transformation modules"], [71, "'HeliocentricEclipticIAU76', 'CustomBarycentricEcliptic']"], [21, "``__init__.py`` to ensure the transformations are hooked up when this package is"], [51, "from . import intermediate_rotation_transforms"], [69, "'SkyOffsetFrame', 'GalacticLSR', 'LSR', 'LSRK', 'LSRD',"]], "WRONG": [[128, "\u279d"], [21, "``__init__.py`` to ensure the transformations are hooked up when this package is"], [127, "{cls.__name__}:"], [60, "# we define an __all__ because otherwise the transformation modules"], [58, "from astropy.coordinates.baseframe import frame_transform_graph"]], "BM25": [[64, "'Supergalactic', 'AltAz', 'HADec', 'GCRS', 'CIRS', 'ITRS', 'HCRS',"], [37, "from .itrs import ITRS"], [58, "from astropy.coordinates.baseframe import frame_transform_graph"], [33, "from .altaz import AltAz"], [16, "To implement a new frame in Astropy, a developer should add the frame as a new"]], "GOLD": [[88, "transform graph."], [51, "from . import intermediate_rotation_transforms"], [95, "# then in the transform graph."], [50, "from . import icrs_observed_transforms"], [65, "'TEME', 'TETE', 'PrecessedGeocentric', 'GeocentricMeanEcliptic',"]]}, "astropy__astropy-13398__303601b1": {"H": [[22, "# # first define helper functions"], [275, "# Create loopback transformations"], [272, "return teme_frame.realize_frame(newrepr)"], [13, "from astropy.coordinates.matrix_utilities import matrix_transpose"], [25, "def teme_to_itrs_mat(time):"]], "WRONG": [[270, "pmat = teme_to_itrs_mat(teme_frame.obstime)"], [256, "pmat = teme_to_itrs_mat(teme_coo.obstime)"], [137, "# We now have a GCRS vector for the input location and obstime."], [272, "return teme_frame.realize_frame(newrepr)"], [20, "from .utils import get_polar_motion, get_jd12, EARTH_CENTER"]], "BM25": [[261, "return itrs.transform_to(itrs_frame)"], [159, "@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ITRS, TETE)"], [197, "@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, CIRS, ITRS)"], [264, "@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ITRS, TEME)"], [209, "@frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ITRS, CIRS)"]], "GOLD": [[74, "# now determine the greenwich apparent siderial time for the input obstime"], [149, "# first get us to TETE at the target obstime, and geocentric position"], [199, "# first get us to geocentric CIRS at the target obstime"], [164, "tete = TETE(newrepr, obstime=itrs_coo.obstime)"], [151, "location=EARTH_CENTER))"]]}, "astropy__astropy-13398__40c52f52": {"H": [[37, "# Self-transform is in intermediate_rotation_transforms.py with all the other"], [7, "from .utils import DEFAULT_OBSTIME"], [19, ":ref:`astropy:astropy-coordinates-seealso` section of the documentation."], [9, "__all__ = ['ITRS']"], [20, "\"\"\""]], "WRONG": [[7, "from .utils import DEFAULT_OBSTIME"], [9, "__all__ = ['ITRS']"], [22, "default_representation = CartesianRepresentation"], [38, "# ITRS transforms"], [34, "cart = self.represent_as(CartesianRepresentation)"]], "BM25": [[18, "For more background on the ITRS, see the references provided in the"], [13, "class ITRS(BaseCoordinateFrame):"], [16, "(ITRS). This is approximately a geocentric system, although strictly it is"], [38, "# ITRS transforms"], [37, "# Self-transform is in intermediate_rotation_transforms.py with all the other"]], "GOLD": [[25, "obstime = TimeAttribute(default=DEFAULT_OBSTIME)"], [17, "defined by a series of reference locations near the surface of the Earth."], [27, "@property"], [7, "from .utils import DEFAULT_OBSTIME"], [6, "from astropy.coordinates.attributes import TimeAttribute"]]}, "psf__requests-5414__afd5aad8": {"H": [[509, "else:"], [357, "raise UnicodeError"], [355, "host = idna.encode(host, uts46=True).decode('utf-8')"], [405, "raise InvalidURL('URL has an invalid label.')"], [356, "except idna.IDNAError:"]], "WRONG": [[620, "#: Use of ``raw`` requires that ``stream=True`` be set on the request."], [104, "result.append("], [736, "\"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\""], [348, "self.method = to_native_string(self.method.upper())"], [109, "return data"]], "BM25": [[357, "raise UnicodeError"], [404, "except UnicodeError:"], [405, "raise InvalidURL('URL has an invalid label.')"], [407, "raise InvalidURL('URL has an invalid label.')"], [366, "#: https://github.com/psf/requests/pull/2238"]], "GOLD": [[877, "#"], [944, "# isn't utf-8, we fall back to iso-8859-1 for all other"], [967, "\"\"\""], [469, "# provides this natively, but Python 3 gives a Unicode string."], [406, "elif host.startswith(u'*'):"]]}, "django__django-13344__7e0a8bc9": {"H": [[32, "try:"], [41, "response.delete_cookie("], [37, "return response"], [79, "return response"], [38, "# First check if we need to delete this cookie."]], "WRONG": [[37, "return response"], [63, "request.session.save()"], [48, "else:"], [52, "if request.session.get_expire_at_browser_close():"], [70, "response.set_cookie("]], "BM25": [[12, "class SessionMiddleware(MiddlewareMixin):"], [26, "def process_response(self, request, response):"], [8, "from django.utils.deprecation import MiddlewareMixin"], [28, "If request.session was modified, or if the configuration is to save the"], [66, "\"The request's session was deleted before the \""]], "GOLD": [[16, "self._get_response_none_deprecation(get_response)"], [38, "# First check if we need to delete this cookie."], [17, "self.get_response = get_response"], [18, "self._async_check()"], [44, "domain=settings.SESSION_COOKIE_DOMAIN,"]]}, "django__django-13344__f6643247": {"H": [[15, "``FetchFromCacheMiddleware`` needs to run last during the request phase, which"], [75, "def _should_update_cache(self, request, response):"], [159, "return None # No cache information available, need to rebuild."], [84, "if response.streaming or response.status_code not in (200, 304):"], [116, "self.cache.set(cache_key, response, timeout)"]], "WRONG": [[158, "request._cache_update_cache = True"], [150, "return None # No cache information available, need to rebuild."], [197, "self.cache_alias = cache_alias"], [203, "self.cache = caches[self.cache_alias]"], [68, "self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS"]], "BM25": [[78, "def process_response(self, request, response):"], [32, "* This middleware expects that a HEAD request is answered with the same response"], [55, "class UpdateCacheMiddleware(MiddlewareMixin):"], [88, "# sensitive) cookie in response to a cookie-less request."], [61, "UpdateCacheMiddleware must be the first piece of middleware in MIDDLEWARE"]], "GOLD": [[199, "if cache_timeout is None:"], [188, "key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX"], [73, "self.get_response = get_response"], [135, "self.get_response = get_response"], [194, "cache_alias = DEFAULT_CACHE_ALIAS"]]}, "django__django-13344__07433d3a": {"H": [[35, "if (self.sts_seconds and request.is_secure() and"], [58, "return response"], [56, "))"], [5, "from django.utils.deprecation import MiddlewareMixin"], [42, "response['Strict-Transport-Security'] = sts_header"]], "WRONG": [[53, "response.setdefault('Referrer-Policy', ','.join("], [13, "self.sts_seconds = settings.SECURE_HSTS_SECONDS"], [55, "if isinstance(self.referrer_policy, str) else self.referrer_policy"], [35, "if (self.sts_seconds and request.is_secure() and"], [12, "self._get_response_none_deprecation(get_response)"]], "BM25": [[8, "class SecurityMiddleware(MiddlewareMixin):"], [34, "def process_response(self, request, response):"], [5, "from django.utils.deprecation import MiddlewareMixin"], [4, "from django.http import HttpResponsePermanentRedirect"], [9, "# RemovedInDjango40Warning: when the deprecation ends, replace with:"]], "GOLD": [[29, "host = self.redirect_host or request.get_host()"], [12, "self._get_response_none_deprecation(get_response)"], [58, "return response"], [22, "self.get_response = get_response"], [5, "from django.utils.deprecation import MiddlewareMixin"]]}, "sympy__sympy-18199__d43e7fc1": {"H": [[1302, "return _discrete_log_pohlig_hellman(n, a, b, order)"], [817, ">>> from sympy.ntheory.residue_ntheory import quadratic_residues"], [481, "Find solution to ``x**2 == a mod p**n`` when ``a % p == 0``"], [806, "res = _nthroot_mod1(a, pa, p, all_roots)"], [800, "res = [a]"]], "WRONG": [[774, "if not is_nthpow_residue(a, n, p):"], [481, "Find solution to ``x**2 == a mod p**n`` when ``a % p == 0``"], [696, "s = _nthroot_mod1(s, qx, p, False)"], [1023, "``a`` to the base ``b`` modulo ``n``."], [459, "# with f(x) = x**2 - a; one has f'(a) != 0 (mod p) for p != 2"]], "BM25": [[766, ">>> nthroot_mod(68, 3, 109)"], [762, ">>> nthroot_mod(11, 4, 19)"], [764, ">>> nthroot_mod(11, 4, 19, True)"], [746, "def nthroot_mod(a, n, p, all_roots=False):"], [761, ">>> from sympy.ntheory.residue_ntheory import nthroot_mod"]], "GOLD": [[776, "if not isprime(p):"], [743, "return min(res)"], [746, "def nthroot_mod(a, n, p, all_roots=False):"], [5, "from sympy.core.numbers import igcd, igcdex, mod_inverse"], [774, "if not is_nthpow_residue(a, n, p):"]]}, "sphinx-doc__sphinx-9230__9710f42b": {"H": [[120, "super().__init__(name, names, label, True, rolename)"], [305, "types.setdefault(typename, {})[argname] = \\"], [313, "translatable_content.line = field_body.parent.line"], [186, "par.extend(self.make_xrefs(self.typerolename, domain, typename,"], [301, "argtype, argname = fieldarg.split(None, 1)"]], "WRONG": [[120, "super().__init__(name, names, label, True, rolename)"], [19, "from sphinx.util.typing import TextlikeNode"], [12, "from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Type, Union, cast"], [33, "if isinstance(node[0], nodes.paragraph):"], [148, "*rolename*, the type using the given *typerolename*."]], "BM25": [[232, "types: Dict[str, Dict] = {}"], [231, "groupindices: Dict[str, int] = {}"], [8, ":copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS."], [2, "sphinx.util.docfields"], [17, "from sphinx import addnodes"]], "GOLD": [[44, "just a single inline or text node."], [313, "translatable_content.line = field_body.parent.line"], [332, "new_list = nodes.field_list()"], [286, "typename = typedesc.name"], [301, "argtype, argname = fieldarg.split(None, 1)"]]}, "sphinx-doc__sphinx-9461__6af9db04": {"H": [[1106, "class PythonDomain(Domain):"], [506, "def get_index_text(self, modname: str, name: Tuple[str, str]) -> str:"], [282, "signode += paramlist"], [347, "class PyField(PyXrefMixin, Field):"], [1152, "}"]], "WRONG": [[506, "def get_index_text(self, modname: str, name: Tuple[str, str]) -> str:"], [1152, "}"], [1153, "indices = ["], [1034, "class PythonModuleIndex(Index):"], [517, "# Assign old styled node_id(fullname) not to break old hyperlinks (if possible)"]], "BM25": [[1182, "@property"], [1157, "@property"], [1132, "'property': PyProperty,"], [1278, "# fallback to meth (for property; Sphinx-2.4.x)"], [868, "prefix = ['property']"]], "GOLD": [[872, "return ' '.join(prefix) + ' '"], [855, "'type': directives.unchanged,"], [870, "prefix.insert(0, 'abstract')"], [854, "'abstractmethod': directives.flag,"], [868, "prefix = ['property']"]]}, "sphinx-doc__sphinx-9461__48ca4d65": {"H": [[1123, "class ModuleLevelDocumenter(Documenter):"], [994, "'imported-members': bool_option, 'ignore-module-all': bool_option"], [722, "if not isinstance(doc, str):"], [305, "*directivetype*."], [2651, "class PropertyDocumenter(DocstringStripSignatureMixin, ClassLevelDocumenter): # type: ignore"]], "WRONG": [[1619, "if __qualname__ and '' in __qualname__:"], [2741, "from sphinx.ext.autodoc.deprecated import SlotsAttributeDocumenter # NOQA"], [1123, "class ModuleLevelDocumenter(Documenter):"], [2039, "super().add_content(more_content, no_docstring=no_docstring)"], [1738, "return list(self.analyzer.attr_docs.get(key, []))"]], "BM25": [[362, "@property"], [2655, "objtype = 'property'"], [2651, "class PropertyDocumenter(DocstringStripSignatureMixin, ClassLevelDocumenter): # type: ignore"], [2062, "Specialized Documenter subclass for methods (normal, static and class)."], [290, "self.class_ = class_"]], "GOLD": [[721, "self.parent, self.object_name)"], [2664, "return inspect.isproperty(member) and isinstance(parent, ClassDocumenter)"], [2677, "self.add_line(' :abstractmethod:', sourcename)"], [1984, "else:"], [2679, "if safe_getattr(self.object, 'fget', None) and self.config.autodoc_typehints != 'none':"]]}, "sphinx-doc__sphinx-9461__84bfd2ad": {"H": [[351, "return inspect.isfunction(unwrap_all(obj))"], [840, "doc = attrgetter(obj, '__doc__', None)"], [320, "elif type(unwrapped).__name__ == \"instancemethod\":"], [253, "return True"], [465, "except Exception as exc:"]], "WRONG": [[788, "if hasattr(args, \"posonlyargs\"):"], [512, "This avoids the error on evaluating the type inside `get_type_hints()`."], [597, ":param follow_wrapped: Same as ``inspect.signature()``."], [679, "ref = ForwardRef(annotation, True)"], [721, "if param.kind != param.POSITIONAL_ONLY and last_kind == param.POSITIONAL_ONLY:"]], "BM25": [[389, "from functools import cached_property # cached_property is available since py3.8"], [390, "if isinstance(obj, cached_property):"], [387, "\"\"\"Check if the object is property.\"\"\""], [393, "return isinstance(obj, property)"], [551, "# return the real class"]], "GOLD": [[255, "return False"], [253, "return True"], [839, "\"\"\""], [248, "def isclassmethod(obj: Any) -> bool:"], [840, "doc = attrgetter(obj, '__doc__', None)"]]}, "django__django-11951__5b0dda5e": {"H": [[1663, "# (e.g. via select_related), or hopefully some other property"], [523, "batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size"], [1212, "batch_size = (batch_size or max(ops.bulk_batch_size(fields, objs), 1))"], [1734, "else:"], [446, "# When you bulk insert you don't get the primary keys back (if it's an"]], "WRONG": [[1663, "# (e.g. via select_related), or hopefully some other property"], [1839, "class RelatedPopulator:"], [1836, "return all_related_objects, additional_lookups"], [1734, "else:"], [1848, "between the objects."]], "BM25": [[523, "batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size"], [1212, "batch_size = (batch_size or max(ops.bulk_batch_size(fields, objs), 1))"], [458, "assert batch_size is None or batch_size > 0"], [506, "if batch_size is not None and batch_size < 0:"], [522, "max_batch_size = connections[self.db].ops.bulk_batch_size(['pk', 'pk'] + fields, objs)"]], "GOLD": [[988, "def select_related(self, *fields):"], [1710, "attr_found = hasattr(instance, through_attr)"], [1212, "batch_size = (batch_size or max(ops.bulk_batch_size(fields, objs), 1))"], [138, "rowfactory = operator.itemgetter(*[index_map[f] for f in fields])"], [1922, "return iterators"]]}, "astropy__astropy-14182__a1959e8c": {"H": [[64, "lines = super().write(lines)"], [60, "def __init__(self):"], [65, "lines = [lines[1]] + lines + [lines[1]]"], [63, "def write(self, lines):"], [22, "def get_fixedwidth_params(self, line):"]], "WRONG": [[64, "lines = super().write(lines)"], [16, "class SimpleRSTHeader(FixedWidthHeader):"], [13, ")"], [65, "lines = [lines[1]] + lines + [lines[1]]"], [53, "\"\"\""]], "BM25": [[51, "line of dashes in the header."], [36, "\"\"\"reStructuredText simple format table."], [22, "def get_fixedwidth_params(self, line):"], [63, "def write(self, lines):"], [23, "vals, starts, ends = super().get_fixedwidth_params(line)"]], "GOLD": [[47, "==== ===== ======"], [61, "super().__init__(delimiter_pad=None, bookend=False)"], [60, "def __init__(self):"], [46, "2 4.5 Worlds"], [43, "Col1 Col2 Col3"]]}, "scikit-learn__scikit-learn-15100__904f5f84": {"H": [[136, "return ''.join([c for c in normalized if not unicodedata.combining(c)])"], [486, "\" since 'analyzer' is callable'\")"], [133, "if normalized == s:"], [1164, "self._validate_vocabulary()"], [481, "\" since 'analyzer' is callable'\")"]], "WRONG": [[535, "The hash function employed is the signed 32-bit version of Murmurhash3."], [1760, "an iterable which yields either str, unicode or file objects"], [1506, "analyzer : string, {'word', 'char', 'char_wb'} or callable"], [1176, "X = self._sort_features(X, vocabulary)"], [749, "if self.norm is not None:"]], "BM25": [[44, "'strip_accents_unicode',"], [152, "strip_accents_unicode"], [310, "strip_accents = strip_accents_unicode"], [114, "def strip_accents_unicode(s):"], [563, "strip_accents : {'ascii', 'unicode', None}"]], "GOLD": [[135, "else:"], [1208, "Returns"], [133, "if normalized == s:"], [132, "normalized = unicodedata.normalize('NFKD', s)"], [167, "s : string"]]}, "astropy__astropy-8872__e5e9598f": {"H": [[788, "# This flag controls whether convenience conversion members, such"], [299, "if not (np.can_cast(np.float32, value.dtype) or"], [817, "\"'{0}' object has no '{1}' member\".format("], [591, "obj = np.array(obj, copy=False)"], [296, "if not copy:"]], "WRONG": [[317, "r'([iI][nN][fF]([iI][nN][iI][tT][yY]){0,1}))'"], [788, "# This flag controls whether convenience conversion members, such"], [1409, "# returned as numbers."], [1294, "A new object equal to this quantity with units decomposed."], [33, "\"QuantityInfoBase\", \"QuantityInfo\", \"allclose\", \"isclose\"]"]], "BM25": [[182, "data = np.zeros(shape=shape, dtype=dtype)"], [301, "dtype = float"], [380, "if dtype is None and (not (np.can_cast(np.float32, value.dtype)"], [303, "return np.array(value, dtype=dtype, copy=copy, order=order,"], [368, "value = np.array(value, dtype=dtype, copy=copy, order=order,"]], "GOLD": [[219, "is converted to float."], [382, "or value.dtype.kind == 'O'):"], [300, "value.dtype.fields):"], [381, "or value.dtype.fields)"], [218, "except that any input that cannot represent float (integer and bool)"]]}, "pytest-dev__pytest-7236__1d1f5a07": {"H": [[225, "setattr(self._testcase, \"tearDown\", lambda *args: None)"], [224, "self._explicit_tearDown = self._testcase.tearDown"], [233, "delattr(self._testcase, self.name)"], [100, "yield"], [69, "\"\"\"Injects a hidden auto-use fixture to invoke setUpClass/setup_method and corresponding"]], "WRONG": [[151, "fail(\"\".join(values), pytrace=False)"], [116, "# a bound method to be called during teardown() if set (see 'runtest()')"], [68, "def _inject_setup_teardown_fixtures(self, cls):"], [100, "yield"], [144, "try:"]], "BM25": [[54, "if not getattr(x, \"__test__\", True):"], [41, "if not getattr(cls, \"__test__\", True):"], [64, "if ut is None or runtest != ut.TestCase.runTest:"], [203, "test_method, \"__unittest_expecting_failure__\", False"], [130, "def startTest(self, testcase):"]], "GOLD": [[44, "skipped = getattr(cls, \"__unittest_skip__\", False)"], [223, "if self.config.getoption(\"usepdb\"):"], [92, "if getattr(self, \"__unittest_skip__\", None):"], [303, "done.append(1)"], [54, "if not getattr(x, \"__test__\", True):"]]}, "django__django-16485__0d09e983": {"H": [[18, "from django.utils.html import json_script as _json_script"], [956, "except ValueError: # Invalid string that's not a number."], [139, "force_grouping = False"], [154, "input_val = str(text)"], [96, "def floatformat(text, arg=-1):"]], "WRONG": [[318, "\"\"\""], [18, "from django.utils.html import json_script as _json_script"], [755, "return int(str(value)[-arg])"], [48, "result = func(first, *args, **kwargs)"], [956, "except ValueError: # Invalid string that's not a number."]], "BM25": [[133, "* {{ 66666.6666|floatformat:\"2\" }} displays \"66666,67\""], [127, "* {{ 6666.6666|floatformat:\"2g\" }} displays \"6,666.67\""], [112, "* {{ num1|floatformat:3 }} displays \"34.232\""], [107, "* {{ num2|floatformat }} displays \"34\""], [119, "* {{ num1|floatformat:\"-3\" }} displays \"34.232\""]], "GOLD": [[382, "\"\"\""], [919, "if negative:"], [43, "\"\"\""], [702, "pass"], [171, "if not m and p < 0:"]]}, "django__django-15380__a71b173d": {"H": [[1135, "def _get_altered_foo_together_operations(self, option_name):"], [1031, "old_indexes = old_model_state.options[option_name]"], [1024, "def create_altered_indexes(self):"], [43, "changes = self._detect_changes(convert_apps, graph)"], [653, "dependencies=related_dependencies,"]], "WRONG": [[109, "The resulting migrations aren't specially named, but the names"], [1135, "def _get_altered_foo_together_operations(self, option_name):"], [234, "through_key = resolve_relation(field.remote_field.through, app_label, model_name)"], [513, "model_state.app_label,"], [1031, "old_indexes = old_model_state.options[option_name]"]], "BM25": [[8, "from django.db.migrations.migration import Migration"], [6, "from django.db import models"], [7, "from django.db.migrations import operations"], [12, "from django.db.migrations.utils import ("], [5, "from django.conf import settings"]], "GOLD": [[827, "new_model_state = self.to_state.models[app_label, old_model_name]"], [1033, "add_idx = [idx for idx in new_indexes if idx not in old_indexes]"], [348, "if dep[0] == app_label:"], [441, "self.generated_operations.setdefault(app_label, []).append(operation)"], [1289, "name=model_name,"]]}}