{"instance_id": "psf__requests-1724", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/requests/sessions.py b/requests/sessions.py\nindex cc72f65d..98c81bcf 100644\n--- a/requests/sessions.py\n+++ b/requests/sessions.py\n@@ -12,7 +12,7 @@ import os\n from collections import Mapping\n from datetime import datetime\n \n-from .compat import cookielib, OrderedDict, urljoin, urlparse, urlunparse\n+from .compat import cookielib, OrderedDict, urljoin, urlparse, urlunparse, builtin_str\n from .cookies import cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar\n from .models import Request, PreparedRequest\n from .hooks import default_hooks, dispatch_hook\n@@ -311,7 +311,7 @@ class Session(SessionRedirectMixin):\n         \"\"\"\n         # Create the Request.\n         req = Request(\n-            method = method.upper(),\n+            method = builtin_str(method).upper(),\n             url = url,\n             headers = headers,\n             files = files,\n", "model": "claude-sonnet-5-5", "steps": 7, "finished": true, "patch_lines": 22, "candidates": [{"compile_ok": 0, "loc_hits": 1, "files": 1, "diff_lines": 22, "steps": 7}], "ms": 13647}
{"instance_id": "psf__requests-1766", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/requests/auth.py b/requests/auth.py\nindex a3de123d..48416e5f 100644\n--- a/requests/auth.py\n+++ b/requests/auth.py\n@@ -144,7 +144,7 @@ class HTTPDigestAuth(AuthBase):\n         if entdig:\n             base += ', digest=\"%s\"' % entdig\n         if qop:\n-            base += ', qop=auth, nc=%s, cnonce=\"%s\"' % (ncvalue, cnonce)\n+            base += ', qop=\"auth\", nc=%s, cnonce=\"%s\"' % (ncvalue, cnonce)\n \n         return 'Digest %s' % (base)\n \n", "model": "claude-sonnet-5-5", "steps": 5, "finished": true, "patch_lines": 13, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 1, "diff_lines": 13, "steps": 5}], "ms": 8273}
{"instance_id": "psf__requests-1921", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/requests/sessions.py b/requests/sessions.py\nindex a023e4ec..30c1378f 100644\n--- a/requests/sessions.py\n+++ b/requests/sessions.py\n@@ -55,9 +55,9 @@ def merge_setting(request_setting, session_setting, dict_class=OrderedDict):\n     merged_setting.update(to_key_val_list(request_setting))\n \n     # Remove keys that are set to None.\n-    for (k, v) in request_setting.items():\n-        if v is None:\n-            del merged_setting[k]\n+    none_keys = [k for (k, v) in merged_setting.items() if v is None]\n+    for key in none_keys:\n+        del merged_setting[key]\n \n     return merged_setting\n \n", "model": "claude-sonnet-5-5", "steps": 5, "finished": true, "patch_lines": 17, "candidates": [{"compile_ok": 0, "loc_hits": 1, "files": 1, "diff_lines": 17, "steps": 5}], "ms": 11489}
{"instance_id": "psf__requests-2317", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/requests/sessions.py b/requests/sessions.py\nindex d701ff2e..adcfbac7 100644\n--- a/requests/sessions.py\n+++ b/requests/sessions.py\n@@ -425,7 +425,7 @@ class Session(SessionRedirectMixin):\n             If Tuple, ('cert', 'key') pair.\n         \"\"\"\n \n-        method = builtin_str(method)\n+        method = to_native_string(method)\n \n         # Create the Request.\n         req = Request(\n", "model": "claude-sonnet-5-5", "steps": 7, "finished": true, "patch_lines": 13, "candidates": [{"compile_ok": 0, "loc_hits": 1, "files": 1, "diff_lines": 13, "steps": 7}], "ms": 8856}
{"instance_id": "psf__requests-2931", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/requests/models.py b/requests/models.py\nindex 9c624d3c..681eddd5 100644\n--- a/requests/models.py\n+++ b/requests/models.py\n@@ -81,7 +81,7 @@ class RequestEncodingMixin(object):\n         \"\"\"\n \n         if isinstance(data, (str, bytes)):\n-            return to_native_string(data)\n+            return data\n         elif hasattr(data, 'read'):\n             return data\n         elif hasattr(data, '__iter__'):\n@@ -387,6 +387,8 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n \n         enc_params = self._encode_params(params)\n         if enc_params:\n+            if isinstance(enc_params, (str, bytes, basestring)):\n+                enc_params = to_native_string(enc_params)\n             if query:\n                 query = '%s&%s' % (query, enc_params)\n             else:\n", "model": "claude-sonnet-5-5", "steps": 8, "finished": true, "patch_lines": 22, "candidates": [{"compile_ok": 0, "loc_hits": 1, "files": 1, "diff_lines": 22, "steps": 8}], "ms": 18939}
{"instance_id": "psf__requests-6028", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/requests/utils.py b/requests/utils.py\nindex 1c2ae4e0..153776c7 100644\n--- a/requests/utils.py\n+++ b/requests/utils.py\n@@ -974,6 +974,10 @@ def prepend_scheme_if_needed(url, new_scheme):\n     if not netloc:\n         netloc, path = path, netloc\n \n+    if auth:\n+        # parse_url doesn't provide the netloc with auth\n+        # so we'll add it ourselves.\n+        netloc = '@'.join([auth, netloc])\n     if scheme is None:\n         scheme = new_scheme\n     if path is None:\n", "model": "claude-sonnet-5-5", "steps": 6, "finished": true, "patch_lines": 15, "candidates": [{"compile_ok": 0, "loc_hits": 1, "files": 1, "diff_lines": 15, "steps": 6}], "ms": 12239}
{"instance_id": "mwaskom__seaborn-3069", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/seaborn/_core/plot.py b/seaborn/_core/plot.py\nindex 4f0290a4..e69de29b 100644\n--- a/seaborn/_core/plot.py\n+++ b/seaborn/_core/plot.py\n@@ -1,1649 +0,0 @@\n-\"\"\"The classes for specifying and compiling a declarative visualization.\"\"\"\n-from __future__ import annotations\n-\n-import io\n-import os\n-import re\n-import sys\n-import inspect\n-import itertools\n-import textwrap\n-from contextlib import contextmanager\n-from collections import abc\n-from collections.abc import Callable, Generator\n-from typing import Any, List, Optional, cast\n-\n-from cycler import cycler\n-import pandas as pd\n-from pandas import DataFrame, Series, Index\n-import matplotlib as mpl\n-from matplotlib.axes import Axes\n-from matplotlib.artist import Artist\n-from matplotlib.figure import Figure\n-\n-from seaborn._marks.base import Mark\n-from seaborn._stats.base import Stat\n-from seaborn._core.data import PlotData\n-from seaborn._core.moves import Move\n-from seaborn._core.scales import Scale\n-from seaborn._core.subplots import Subplots\n-from seaborn._core.groupby import GroupBy\n-from seaborn._core.properties import PROPERTIES, Property\n-from seaborn._core.typing import (\n-    DataSource,\n-    VariableSpec,\n-    VariableSpecList,\n-    OrderSpec,\n-    Default,\n-)\n-from seaborn._core.rules import categorical_order\n-from seaborn._compat import set_scale_obj, set_layout_engine\n-from seaborn.rcmod import axes_style, plotting_context\n-from seaborn.palettes import color_palette\n-from seaborn.external.version import Version\n-\n-from typing import TYPE_CHECKING\n-if TYPE_CHECKING:\n-    from matplotlib.figure import SubFigure\n-\n-\n-if sys.version_info >= (3, 8):\n-    from typing import TypedDict\n-else:\n-    from typing_extensions import TypedDict\n-\n-\n-default = Default()\n-\n-\n-# ---- Definitions for internal specs --------------------------------- #\n-\n-\n-class Layer(TypedDict, total=False):\n-\n-    mark: Mark  # TODO allow list?\n-    stat: Stat | None  # TODO allow list?\n-    move: Move | list[Move] | None\n-    data: PlotData\n-    source: DataSource\n-    vars: dict[str, VariableSpec]\n-    orient: str\n-    legend: bool\n-\n-\n-class FacetSpec(TypedDict, total=False):\n-\n-    variables: dict[str, VariableSpec]\n-    structure: dict[str, list[str]]\n-    wrap: int | None\n-\n-\n-class PairSpec(TypedDict, total=False):\n-\n-    variables: dict[str, VariableSpec]\n-    structure: dict[str, list[str]]\n-    cross: bool\n-    wrap: int | None\n-\n-\n-# --- Local helpers ----------------------------------------------------------------\n-\n-\n-@contextmanager\n-def theme_context(params: dict[str, Any]) -> Generator:\n-    \"\"\"Temporarily modify specifc matplotlib rcParams.\"\"\"\n-    orig_params = {k: mpl.rcParams[k] for k in params}\n-    color_codes = \"bgrmyck\"\n-    nice_colors = [*color_palette(\"deep6\"), (.15, .15, .15)]\n-    orig_colors = [mpl.colors.colorConverter.colors[x] for x in color_codes]\n-    # TODO how to allow this to reflect the color cycle when relevant?\n-    try:\n-        mpl.rcParams.update(params)\n-        for (code, color) in zip(color_codes, nice_colors):\n-            mpl.colors.colorConverter.colors[code] = color\n-            mpl.colors.colorConverter.cache[code] = color\n-        yield\n-    finally:\n-        mpl.rcParams.update(orig_params)\n-        for (code, color) in zip(color_codes, orig_colors):\n-            mpl.colors.colorConverter.colors[code] = color\n-            mpl.colors.colorConverter.cache[code] = color\n-\n-\n-def build_plot_signature(cls):\n-    \"\"\"\n-    Decorator function for giving Plot a useful signature.\n-\n-    Currently this mostly saves us some duplicated typing, but we would\n-    like eventually to have a way of registering new semantic properties,\n-    at which point dynamic signature generation would become more important.\n-\n-    \"\"\"\n-    sig = inspect.signature(cls)\n-    params = [\n-        inspect.Parameter(\"args\", inspect.Parameter.VAR_POSITIONAL),\n-        inspect.Parameter(\"data\", inspect.Parameter.KEYWORD_ONLY, default=None)\n-    ]\n-    params.extend([\n-        inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, default=None)\n-        for name in PROPERTIES\n-    ])\n-    new_sig = sig.replace(parameters=params)\n-    cls.__signature__ = new_sig\n-\n-    known_properties = textwrap.fill(\n-        \", \".join([f\"|{p}|\" for p in PROPERTIES]),\n-        width=78, subsequent_indent=\" \" * 8,\n-    )\n-\n-    if cls.__doc__ is not None:  # support python -OO mode\n-        cls.__doc__ = cls.__doc__.format(known_properties=known_properties)\n-\n-    return cls\n-\n-\n-# ---- The main interface for declarative plotting -------------------- #\n-\n-\n-@build_plot_signature\n-class Plot:\n-    \"\"\"\n-    An interface for declaratively specifying statistical graphics.\n-\n-    Plots are constructed by initializing this class and adding one or more\n-    layers, comprising a `Mark` and optional `Stat` or `Move`.  Additionally,\n-    faceting variables or variable pairings may be defined to divide the space\n-    into multiple subplots. The mappings from data values to visual properties\n-    can be parametrized using scales, although the plot will try to infer good\n-    defaults when scales are not explicitly defined.\n-\n-    The constructor accepts a data source (a :class:`pandas.DataFrame` or\n-    dictionary with columnar values) and variable assignments. Variables can be\n-    passed as keys to the data source or directly as data vectors.  If multiple\n-    data-containing objects are provided, they will be index-aligned.\n-\n-    The data source and variables defined in the constructor will be used for\n-    all layers in the plot, unless overridden or disabled when adding a layer.\n-\n-    The following variables can be defined in the constructor:\n-        {known_properties}\n-\n-    The `data`, `x`, and `y` variables can be passed as positional arguments or\n-    using keywords. Whether the first positional argument is interpreted as a\n-    data source or `x` variable depends on its type.\n-\n-    The methods of this class return a copy of the instance; use chaining to\n-    build up a plot through multiple calls. Methods can be called in any order.\n-\n-    Most methods only add information to the plot spec; no actual processing\n-    happens until the plot is shown or saved. It is also possible to compile\n-    the plot without rendering it to access the lower-level representation.\n-\n-    \"\"\"\n-    _data: PlotData\n-    _layers: list[Layer]\n-\n-    _scales: dict[str, Scale]\n-    _shares: dict[str, bool | str]\n-    _limits: dict[str, tuple[Any, Any]]\n-    _labels: dict[str, str | Callable[[str], str]]\n-    _theme: dict[str, Any]\n-\n-    _facet_spec: FacetSpec\n-    _pair_spec: PairSpec\n-\n-    _figure_spec: dict[str, Any]\n-    _subplot_spec: dict[str, Any]\n-    _layout_spec: dict[str, Any]\n-\n-    def __init__(\n-        self,\n-        *args: DataSource | VariableSpec,\n-        data: DataSource = None,\n-        **variables: VariableSpec,\n-    ):\n-\n-        if args:\n-            data, variables = self._resolve_positionals(args, data, variables)\n-\n-        unknown = [x for x in variables if x not in PROPERTIES]\n-        if unknown:\n-            err = f\"Plot() got unexpected keyword argument(s): {', '.join(unknown)}\"\n-            raise TypeError(err)\n-\n-        self._data = PlotData(data, variables)\n-\n-        self._layers = []\n-\n-        self._scales = {}\n-        self._shares = {}\n-        self._limits = {}\n-        self._labels = {}\n-        self._theme = {}\n-\n-        self._facet_spec = {}\n-        self._pair_spec = {}\n-\n-        self._figure_spec = {}\n-        self._subplot_spec = {}\n-        self._layout_spec = {}\n-\n-        self._target = None\n-\n-    def _resolve_positionals(\n-        self,\n-        args: tuple[DataSource | VariableSpec, ...],\n-        data: DataSource,\n-        variables: dict[str, VariableSpec],\n-    ) -> tuple[DataSource, dict[str, VariableSpec]]:\n-        \"\"\"Handle positional arguments, which may contain data / x / y.\"\"\"\n-        if len(args) > 3:\n-            err = \"Plot() accepts no more than 3 positional arguments (data, x, y).\"\n-            raise TypeError(err)\n-\n-        # TODO need some clearer way to differentiate data / vector here\n-        # (There might be an abstract DataFrame class to use here?)\n-        if isinstance(args[0], (abc.Mapping, pd.DataFrame)):\n-            if data is not None:\n-                raise TypeError(\"`data` given by both name and position.\")\n-            data, args = args[0], args[1:]\n-\n-        if len(args) == 2:\n-            x, y = args\n-        elif len(args) == 1:\n-            x, y = *args, None\n-        else:\n-            x = y = None\n-\n-        for name, var in zip(\"yx\", (y, x)):\n-            if var is not None:\n-                if name in variables:\n-                    raise TypeError(f\"`{name}` given by both name and position.\")\n-                # Keep coordinates at the front of the variables dict\n-                # Cast type because we know this isn't a DataSource at this point\n-                variables = {name: cast(VariableSpec, var), **variables}\n-\n-        return data, variables\n-\n-    def __add__(self, other):\n-\n-        if isinstance(other, Mark) or isinstance(other, Stat):\n-            raise TypeError(\"Sorry, this isn't ggplot! Perhaps try Plot.add?\")\n-\n-        other_type = other.__class__.__name__\n-        raise TypeError(f\"Unsupported operand type(s) for +: 'Plot' and '{other_type}\")\n-\n-    def _repr_png_(self) -> tuple[bytes, dict[str, float]]:\n-\n-        return self.plot()._repr_png_()\n-\n-    # TODO _repr_svg_?\n-\n-    def _clone(self) -> Plot:\n-        \"\"\"Generate a new object with the same information as the current spec.\"\"\"\n-        new = Plot()\n-\n-        # TODO any way to enforce that data does not get mutated?\n-        new._data = self._data\n-\n-        new._layers.extend(self._layers)\n-\n-        new._scales.update(self._scales)\n-        new._shares.update(self._shares)\n-        new._limits.update(self._limits)\n-        new._labels.update(self._labels)\n-        new._theme.update(self._theme)\n-\n-        new._facet_spec.update(self._facet_spec)\n-        new._pair_spec.update(self._pair_spec)\n-\n-        new._figure_spec.update(self._figure_spec)\n-        new._subplot_spec.update(self._subplot_spec)\n-        new._layout_spec.update(self._layout_spec)\n-\n-        new._target = self._target\n-\n-        return new\n-\n-    def _theme_with_defaults(self) -> dict[str, Any]:\n-\n-        style_groups = [\n-            \"axes\", \"figure\", \"font\", \"grid\", \"hatch\", \"legend\", \"lines\",\n-            \"mathtext\", \"markers\", \"patch\", \"savefig\", \"scatter\",\n-            \"xaxis\", \"xtick\", \"yaxis\", \"ytick\",\n-        ]\n-        base = {\n-            k: mpl.rcParamsDefault[k] for k in mpl.rcParams\n-            if any(k.startswith(p) for p in style_groups)\n-        }\n-        theme = {\n-            **base,\n-            **axes_style(\"darkgrid\"),\n-            **plotting_context(\"notebook\"),\n-            \"axes.prop_cycle\": cycler(\"color\", color_palette(\"deep\")),\n-        }\n-        theme.update(self._theme)\n-        return theme\n-\n-    @property\n-    def _variables(self) -> list[str]:\n-\n-        variables = (\n-            list(self._data.frame)\n-            + list(self._pair_spec.get(\"variables\", []))\n-            + list(self._facet_spec.get(\"variables\", []))\n-        )\n-        for layer in self._layers:\n-            variables.extend(v for v in layer[\"vars\"] if v not in variables)\n-\n-        # Coerce to str in return to appease mypy; we know these will only\n-        # ever be strings but I don't think we can type a DataFrame that way yet\n-        return [str(v) for v in variables]\n-\n-    def on(self, target: Axes | SubFigure | Figure) -> Plot:\n-        \"\"\"\n-        Provide existing Matplotlib figure or axes for drawing the plot.\n-\n-        When using this method, you will also need to explicitly call a method that\n-        triggers compilation, such as :meth:`Plot.show` or :meth:`Plot.save`. If you\n-        want to postprocess using matplotlib, you'd need to call :meth:`Plot.plot`\n-        first to compile the plot without rendering it.\n-\n-        Parameters\n-        ----------\n-        target : Axes, SubFigure, or Figure\n-            Matplotlib object to use. Passing :class:`matplotlib.axes.Axes` will add\n-            artists without otherwise modifying the figure. Otherwise, subplots will be\n-            created within the space of the given :class:`matplotlib.figure.Figure` or\n-            :class:`matplotlib.figure.SubFigure`.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.on.rst\n-\n-        \"\"\"\n-        accepted_types: tuple  # Allow tuple of various length\n-        if hasattr(mpl.figure, \"SubFigure\"):  # Added in mpl 3.4\n-            accepted_types = (\n-                mpl.axes.Axes, mpl.figure.SubFigure, mpl.figure.Figure\n-            )\n-            accepted_types_str = (\n-                f\"{mpl.axes.Axes}, {mpl.figure.SubFigure}, or {mpl.figure.Figure}\"\n-            )\n-        else:\n-            accepted_types = mpl.axes.Axes, mpl.figure.Figure\n-            accepted_types_str = f\"{mpl.axes.Axes} or {mpl.figure.Figure}\"\n-\n-        if not isinstance(target, accepted_types):\n-            err = (\n-                f\"The `Plot.on` target must be an instance of {accepted_types_str}. \"\n-                f\"You passed an instance of {target.__class__} instead.\"\n-            )\n-            raise TypeError(err)\n-\n-        new = self._clone()\n-        new._target = target\n-\n-        return new\n-\n-    def add(\n-        self,\n-        mark: Mark,\n-        *transforms: Stat | Mark,\n-        orient: str | None = None,\n-        legend: bool = True,\n-        data: DataSource = None,\n-        **variables: VariableSpec,\n-    ) -> Plot:\n-        \"\"\"\n-        Specify a layer of the visualization in terms of mark and data transform(s).\n-\n-        This is the main method for specifying how the data should be visualized.\n-        It can be called multiple times with different arguments to define\n-        a plot with multiple layers.\n-\n-        Parameters\n-        ----------\n-        mark : :class:`Mark`\n-            The visual representation of the data to use in this layer.\n-        transforms : :class:`Stat` or :class:`Move`\n-            Objects representing transforms to be applied before plotting the data.\n-            Currently, at most one :class:`Stat` can be used, and it\n-            must be passed first. This constraint will be relaxed in the future.\n-        orient : \"x\", \"y\", \"v\", or \"h\"\n-            The orientation of the mark, which also affects how transforms are computed.\n-            Typically corresponds to the axis that defines groups for aggregation.\n-            The \"v\" (vertical) and \"h\" (horizontal) options are synonyms for \"x\" / \"y\",\n-            but may be more intuitive with some marks. When not provided, an\n-            orientation will be inferred from characteristics of the data and scales.\n-        legend : bool\n-            Option to suppress the mark/mappings for this layer from the legend.\n-        data : DataFrame or dict\n-            Data source to override the global source provided in the constructor.\n-        variables : data vectors or identifiers\n-            Additional layer-specific variables, including variables that will be\n-            passed directly to the transforms without scaling.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.add.rst\n-\n-        \"\"\"\n-        if not isinstance(mark, Mark):\n-            msg = f\"mark must be a Mark instance, not {type(mark)!r}.\"\n-            raise TypeError(msg)\n-\n-        # TODO This API for transforms was a late decision, and previously Plot.add\n-        # accepted 0 or 1 Stat instances and 0, 1, or a list of Move instances.\n-        # It will take some work to refactor the internals so that Stat and Move are\n-        # treated identically, and until then well need to \"unpack\" the transforms\n-        # here and enforce limitations on the order / types.\n-\n-        stat: Optional[Stat]\n-        move: Optional[List[Move]]\n-        error = False\n-        if not transforms:\n-            stat, move = None, None\n-        elif isinstance(transforms[0], Stat):\n-            stat = transforms[0]\n-            move = [m for m in transforms[1:] if isinstance(m, Move)]\n-            error = len(move) != len(transforms) - 1\n-        else:\n-            stat = None\n-            move = [m for m in transforms if isinstance(m, Move)]\n-            error = len(move) != len(transforms)\n-\n-        if error:\n-            msg = \" \".join([\n-                \"Transforms must have at most one Stat type (in the first position),\",\n-                \"and all others must be a Move type. Given transform type(s):\",\n-                \", \".join(str(type(t).__name__) for t in transforms) + \".\"\n-            ])\n-            raise TypeError(msg)\n-\n-        new = self._clone()\n-        new._layers.append({\n-            \"mark\": mark,\n-            \"stat\": stat,\n-            \"move\": move,\n-            # TODO it doesn't work to supply scalars to variables, but it should\n-            \"vars\": variables,\n-            \"source\": data,\n-            \"legend\": legend,\n-            \"orient\": {\"v\": \"x\", \"h\": \"y\"}.get(orient, orient),  # type: ignore\n-        })\n-\n-        return new\n-\n-    def pair(\n-        self,\n-        x: VariableSpecList = None,\n-        y: VariableSpecList = None,\n-        wrap: int | None = None,\n-        cross: bool = True,\n-    ) -> Plot:\n-        \"\"\"\n-        Produce subplots by pairing multiple `x` and/or `y` variables.\n-\n-        Parameters\n-        ----------\n-        x, y : sequence(s) of data vectors or identifiers\n-            Variables that will define the grid of subplots.\n-        wrap : int\n-            When using only `x` or `y`, \"wrap\" subplots across a two-dimensional grid\n-            with this many columns (when using `x`) or rows (when using `y`).\n-        cross : bool\n-            When False, zip the `x` and `y` lists such that the first subplot gets the\n-            first pair, the second gets the second pair, etc. Otherwise, create a\n-            two-dimensional grid from the cartesian product of the lists.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.pair.rst\n-\n-        \"\"\"\n-        # TODO Add transpose= arg, which would then draw pair(y=[...]) across rows\n-        # This may also be possible by setting `wrap=1`, but is that too unobvious?\n-        # TODO PairGrid features not currently implemented: diagonals, corner\n-\n-        pair_spec: PairSpec = {}\n-\n-        axes = {\"x\": [] if x is None else x, \"y\": [] if y is None else y}\n-        for axis, arg in axes.items():\n-            if isinstance(arg, (str, int)):\n-                err = f\"You must pass a sequence of variable keys to `{axis}`\"\n-                raise TypeError(err)\n-\n-        pair_spec[\"variables\"] = {}\n-        pair_spec[\"structure\"] = {}\n-\n-        for axis in \"xy\":\n-            keys = []\n-            for i, col in enumerate(axes[axis]):\n-                key = f\"{axis}{i}\"\n-                keys.append(key)\n-                pair_spec[\"variables\"][key] = col\n-\n-            if keys:\n-                pair_spec[\"structure\"][axis] = keys\n-\n-        if not cross and len(axes[\"x\"]) != len(axes[\"y\"]):\n-            err = \"Lengths of the `x` and `y` lists must match with cross=False\"\n-            raise ValueError(err)\n-\n-        pair_spec[\"cross\"] = cross\n-        pair_spec[\"wrap\"] = wrap\n-\n-        new = self._clone()\n-        new._pair_spec.update(pair_spec)\n-        return new\n-\n-    def facet(\n-        self,\n-        col: VariableSpec = None,\n-        row: VariableSpec = None,\n-        order: OrderSpec | dict[str, OrderSpec] = None,\n-        wrap: int | None = None,\n-    ) -> Plot:\n-        \"\"\"\n-        Produce subplots with conditional subsets of the data.\n-\n-        Parameters\n-        ----------\n-        col, row : data vectors or identifiers\n-            Variables used to define subsets along the columns and/or rows of the grid.\n-            Can be references to the global data source passed in the constructor.\n-        order : list of strings, or dict with dimensional keys\n-            Define the order of the faceting variables.\n-        wrap : int\n-            When using only `col` or `row`, wrap subplots across a two-dimensional\n-            grid with this many subplots on the faceting dimension.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.facet.rst\n-\n-        \"\"\"\n-        variables: dict[str, VariableSpec] = {}\n-        if col is not None:\n-            variables[\"col\"] = col\n-        if row is not None:\n-            variables[\"row\"] = row\n-\n-        structure = {}\n-        if isinstance(order, dict):\n-            for dim in [\"col\", \"row\"]:\n-                dim_order = order.get(dim)\n-                if dim_order is not None:\n-                    structure[dim] = list(dim_order)\n-        elif order is not None:\n-            if col is not None and row is not None:\n-                err = \" \".join([\n-                    \"When faceting on both col= and row=, passing `order` as a list\"\n-                    \"is ambiguous. Use a dict with 'col' and/or 'row' keys instead.\"\n-                ])\n-                raise RuntimeError(err)\n-            elif col is not None:\n-                structure[\"col\"] = list(order)\n-            elif row is not None:\n-                structure[\"row\"] = list(order)\n-\n-        spec: FacetSpec = {\n-            \"variables\": variables,\n-            \"structure\": structure,\n-            \"wrap\": wrap,\n-        }\n-\n-        new = self._clone()\n-        new._facet_spec.update(spec)\n-\n-        return new\n-\n-    # TODO def twin()?\n-\n-    def scale(self, **scales: Scale) -> Plot:\n-        \"\"\"\n-        Specify mappings from data units to visual properties.\n-\n-        Keywords correspond to variables defined in the plot, including coordinate\n-        variables (`x`, `y`) and semantic variables (`color`, `pointsize`, etc.).\n-\n-        A number of \"magic\" arguments are accepted, including:\n-            - The name of a transform (e.g., `\"log\"`, `\"sqrt\"`)\n-            - The name of a palette (e.g., `\"viridis\"`, `\"muted\"`)\n-            - A tuple of values, defining the output range (e.g. `(1, 5)`)\n-            - A dict, implying a :class:`Nominal` scale (e.g. `{\"a\": .2, \"b\": .5}`)\n-            - A list of values, implying a :class:`Nominal` scale (e.g. `[\"b\", \"r\"]`)\n-\n-        For more explicit control, pass a scale spec object such as :class:`Continuous`\n-        or :class:`Nominal`. Or use `None` to use an \"identity\" scale, which treats data\n-        values as literally encoding visual properties.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.scale.rst\n-\n-        \"\"\"\n-        new = self._clone()\n-        new._scales.update(scales)\n-        return new\n-\n-    def share(self, **shares: bool | str) -> Plot:\n-        \"\"\"\n-        Control sharing of axis limits and ticks across subplots.\n-\n-        Keywords correspond to variables defined in the plot, and values can be\n-        boolean (to share across all subplots), or one of \"row\" or \"col\" (to share\n-        more selectively across one dimension of a grid).\n-\n-        Behavior for non-coordinate variables is currently undefined.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.share.rst\n-\n-        \"\"\"\n-        new = self._clone()\n-        new._shares.update(shares)\n-        return new\n-\n-    def limit(self, **limits: tuple[Any, Any]) -> Plot:\n-        \"\"\"\n-        Control the range of visible data.\n-\n-        Keywords correspond to variables defined in the plot, and values are a\n-        `(min, max)` tuple (where either can be `None` to leave unset).\n-\n-        Limits apply only to the axis; data outside the visible range are\n-        still used for any stat transforms and added to the plot.\n-\n-        Behavior for non-coordinate variables is currently undefined.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.limit.rst\n-\n-        \"\"\"\n-        new = self._clone()\n-        new._limits.update(limits)\n-        return new\n-\n-    def label(self, *, title=None, **variables: str | Callable[[str], str]) -> Plot:\n-        \"\"\"\n-        Control the labels and titles for axes, legends, and subplots.\n-\n-        Additional keywords correspond to variables defined in the plot.\n-        Values can be one of the following types:\n-\n-        - string (used literally; pass \"\" to clear the default label)\n-        - function (called on the default label)\n-\n-        For coordinate variables, the value sets the axis label.\n-        For semantic variables, the value sets the legend title.\n-        For faceting variables, `title=` modifies the subplot-specific label,\n-        while `col=` and/or `row=` add a label for the faceting variable.\n-        When using a single subplot, `title=` sets its title.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.label.rst\n-\n-\n-        \"\"\"\n-        new = self._clone()\n-        if title is not None:\n-            new._labels[\"title\"] = title\n-        new._labels.update(variables)\n-        return new\n-\n-    def layout(\n-        self,\n-        *,\n-        size: tuple[float, float] | Default = default,\n-        engine: str | None | Default = default,\n-    ) -> Plot:\n-        \"\"\"\n-        Control the figure size and layout.\n-\n-        .. note::\n-\n-            Default figure sizes and the API for specifying the figure size are subject\n-            to change in future \"experimental\" releases of the objects API. The default\n-            layout engine may also change.\n-\n-        Parameters\n-        ----------\n-        size : (width, height)\n-            Size of the resulting figure, in inches. Size is inclusive of legend when\n-            using pyplot, but not otherwise.\n-        engine : {{\"tight\", \"constrained\", None}}\n-            Name of method for automatically adjusting the layout to remove overlap.\n-            The default depends on whether :meth:`Plot.on` is used.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.layout.rst\n-\n-        \"\"\"\n-        # TODO add an \"auto\" mode for figsize that roughly scales with the rcParams\n-        # figsize (so that works), but expands to prevent subplots from being squished\n-        # Also should we have height=, aspect=, exclusive with figsize? Or working\n-        # with figsize when only one is defined?\n-\n-        new = self._clone()\n-\n-        if size is not default:\n-            new._figure_spec[\"figsize\"] = size\n-        if engine is not default:\n-            new._layout_spec[\"engine\"] = engine\n-\n-        return new\n-\n-    # TODO def legend (ugh)\n-\n-    def theme(self, *args: dict[str, Any]) -> Plot:\n-        \"\"\"\n-        Control the default appearance of elements in the plot.\n-\n-        .. note::\n-\n-            The API for customizing plot appearance is not yet finalized.\n-            Currently, the only valid argument is a dict of matplotlib rc parameters.\n-            (This dict must be passed as a positional argument.)\n-\n-            It is likely that this method will be enhanced in future releases.\n-\n-        Matplotlib rc parameters are documented on the following page:\n-        https://matplotlib.org/stable/tutorials/introductory/customizing.html\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.theme.rst\n-\n-        \"\"\"\n-        new = self._clone()\n-\n-        # We can skip this whole block on Python 3.8+ with positional-only syntax\n-        nargs = len(args)\n-        if nargs != 1:\n-            err = f\"theme() takes 1 positional argument, but {nargs} were given\"\n-            raise TypeError(err)\n-\n-        rc = args[0]\n-        new._theme.update(rc)\n-\n-        return new\n-\n-    def save(self, loc, **kwargs) -> Plot:\n-        \"\"\"\n-        Compile the plot and write it to a buffer or file on disk.\n-\n-        Parameters\n-        ----------\n-        loc : str, path, or buffer\n-            Location on disk to save the figure, or a buffer to write into.\n-        kwargs\n-            Other keyword arguments are passed through to\n-            :meth:`matplotlib.figure.Figure.savefig`.\n-\n-        \"\"\"\n-        # TODO expose important keyword arguments in our signature?\n-        with theme_context(self._theme_with_defaults()):\n-            self._plot().save(loc, **kwargs)\n-        return self\n-\n-    def show(self, **kwargs) -> None:\n-        \"\"\"\n-        Compile the plot and display it by hooking into pyplot.\n-\n-        Calling this method is not necessary to render a plot in notebook context,\n-        but it may be in other environments (e.g., in a terminal). After compiling the\n-        plot, it calls :func:`matplotlib.pyplot.show` (passing any keyword parameters).\n-\n-        Unlike other :class:`Plot` methods, there is no return value. This should be\n-        the last method you call when specifying a plot.\n-\n-        \"\"\"\n-        # TODO make pyplot configurable at the class level, and when not using,\n-        # import IPython.display and call on self to populate cell output?\n-\n-        # Keep an eye on whether matplotlib implements \"attaching\" an existing\n-        # figure to pyplot: https://github.com/matplotlib/matplotlib/pull/14024\n-\n-        self.plot(pyplot=True).show(**kwargs)\n-\n-    def plot(self, pyplot: bool = False) -> Plotter:\n-        \"\"\"\n-        Compile the plot spec and return the Plotter object.\n-        \"\"\"\n-        with theme_context(self._theme_with_defaults()):\n-            return self._plot(pyplot)\n-\n-    def _plot(self, pyplot: bool = False) -> Plotter:\n-\n-        # TODO if we have _target object, pyplot should be determined by whether it\n-        # is hooked into the pyplot state machine (how do we check?)\n-\n-        plotter = Plotter(pyplot=pyplot, theme=self._theme_with_defaults())\n-\n-        # Process the variable assignments and initialize the figure\n-        common, layers = plotter._extract_data(self)\n-        plotter._setup_figure(self, common, layers)\n-\n-        # Process the scale spec for coordinate variables and transform their data\n-        coord_vars = [v for v in self._variables if re.match(r\"^x|y\", v)]\n-        plotter._setup_scales(self, common, layers, coord_vars)\n-\n-        # Apply statistical transform(s)\n-        plotter._compute_stats(self, layers)\n-\n-        # Process scale spec for semantic variables and coordinates computed by stat\n-        plotter._setup_scales(self, common, layers)\n-\n-        # TODO Remove these after updating other methods\n-        # ---- Maybe have debug= param that attaches these when True?\n-        plotter._data = common\n-        plotter._layers = layers\n-\n-        # Process the data for each layer and add matplotlib artists\n-        for layer in layers:\n-            plotter._plot_layer(self, layer)\n-\n-        # Add various figure decorations\n-        plotter._make_legend(self)\n-        plotter._finalize_figure(self)\n-\n-        return plotter\n-\n-\n-# ---- The plot compilation engine ---------------------------------------------- #\n-\n-\n-class Plotter:\n-    \"\"\"\n-    Engine for compiling a :class:`Plot` spec into a Matplotlib figure.\n-\n-    This class is not intended to be instantiated directly by users.\n-\n-    \"\"\"\n-    # TODO decide if we ever want these (Plot.plot(debug=True))?\n-    _data: PlotData\n-    _layers: list[Layer]\n-    _figure: Figure\n-\n-    def __init__(self, pyplot: bool, theme: dict[str, Any]):\n-\n-        self._pyplot = pyplot\n-        self._theme = theme\n-        self._legend_contents: list[tuple[\n-            tuple[str, str | int], list[Artist], list[str],\n-        ]] = []\n-        self._scales: dict[str, Scale] = {}\n-\n-    def save(self, loc, **kwargs) -> Plotter:  # TODO type args\n-        kwargs.setdefault(\"dpi\", 96)\n-        try:\n-            loc = os.path.expanduser(loc)\n-        except TypeError:\n-            # loc may be a buffer in which case that would not work\n-            pass\n-        self._figure.savefig(loc, **kwargs)\n-        return self\n-\n-    def show(self, **kwargs) -> None:\n-        \"\"\"\n-        Display the plot by hooking into pyplot.\n-\n-        This method calls :func:`matplotlib.pyplot.show` with any keyword parameters.\n-\n-        \"\"\"\n-        # TODO if we did not create the Plotter with pyplot, is it possible to do this?\n-        # If not we should clearly raise.\n-        import matplotlib.pyplot as plt\n-        with theme_context(self._theme):\n-            plt.show(**kwargs)\n-\n-    # TODO API for accessing the underlying matplotlib objects\n-    # TODO what else is useful in the public API for this class?\n-\n-    def _repr_png_(self) -> tuple[bytes, dict[str, float]]:\n-\n-        # TODO better to do this through a Jupyter hook? e.g.\n-        # ipy = IPython.core.formatters.get_ipython()\n-        # fmt = ipy.display_formatter.formatters[\"text/html\"]\n-        # fmt.for_type(Plot, ...)\n-        # Would like to have a svg option too, not sure how to make that flexible\n-\n-        # TODO use matplotlib backend directly instead of going through savefig?\n-\n-        # TODO perhaps have self.show() flip a switch to disable this, so that\n-        # user does not end up with two versions of the figure in the output\n-\n-        # TODO use bbox_inches=\"tight\" like the inline backend?\n-        # pro: better results,  con: (sometimes) confusing results\n-        # Better solution would be to default (with option to change)\n-        # to using constrained/tight layout.\n-\n-        # TODO need to decide what the right default behavior here is:\n-        # - Use dpi=72 to match default InlineBackend figure size?\n-        # - Accept a generic \"scaling\" somewhere and scale DPI from that,\n-        #   either with 1x -> 72 or 1x -> 96 and the default scaling be .75?\n-        # - Listen to rcParams? InlineBackend behavior makes that so complicated :(\n-        # - Do we ever want to *not* use retina mode at this point?\n-\n-        from PIL import Image\n-\n-        dpi = 96\n-        buffer = io.BytesIO()\n-\n-        with theme_context(self._theme):\n-            self._figure.savefig(buffer, dpi=dpi * 2, format=\"png\", bbox_inches=\"tight\")\n-        data = buffer.getvalue()\n-\n-        scaling = .85 / 2\n-        w, h = Image.open(buffer).size\n-        metadata = {\"width\": w * scaling, \"height\": h * scaling}\n-        return data, metadata\n-\n-    def _extract_data(self, p: Plot) -> tuple[PlotData, list[Layer]]:\n-\n-        common_data = (\n-            p._data\n-            .join(None, p._facet_spec.get(\"variables\"))\n-            .join(None, p._pair_spec.get(\"variables\"))\n-        )\n-\n-        layers: list[Layer] = []\n-        for layer in p._layers:\n-            spec = layer.copy()\n-            spec[\"data\"] = common_data.join(layer.get(\"source\"), layer.get(\"vars\"))\n-            layers.append(spec)\n-\n-        return common_data, layers\n-\n-    def _resolve_label(self, p: Plot, var: str, auto_label: str | None) -> str:\n-\n-        label: str\n-        if var in p._labels:\n-            manual_label = p._labels[var]\n-            if callable(manual_label) and auto_label is not None:\n-                label = manual_label(auto_label)\n-            else:\n-                label = cast(str, manual_label)\n-        elif auto_label is None:\n-            label = \"\"\n-        else:\n-            label = auto_label\n-        return label\n-\n-    def _setup_figure(self, p: Plot, common: PlotData, layers: list[Layer]) -> None:\n-\n-        # --- Parsing the faceting/pairing parameterization to specify figure grid\n-\n-        subplot_spec = p._subplot_spec.copy()\n-        facet_spec = p._facet_spec.copy()\n-        pair_spec = p._pair_spec.copy()\n-\n-        for axis in \"xy\":\n-            if axis in p._shares:\n-                subplot_spec[f\"share{axis}\"] = p._shares[axis]\n-\n-        for dim in [\"col\", \"row\"]:\n-            if dim in common.frame and dim not in facet_spec[\"structure\"]:\n-                order = categorical_order(common.frame[dim])\n-                facet_spec[\"structure\"][dim] = order\n-\n-        self._subplots = subplots = Subplots(subplot_spec, facet_spec, pair_spec)\n-\n-        # --- Figure initialization\n-        self._figure = subplots.init_figure(\n-            pair_spec, self._pyplot, p._figure_spec, p._target,\n-        )\n-\n-        # --- Figure annotation\n-        for sub in subplots:\n-            ax = sub[\"ax\"]\n-            for axis in \"xy\":\n-                axis_key = sub[axis]\n-\n-                # ~~ Axis labels\n-\n-                # TODO Should we make it possible to use only one x/y label for\n-                # all rows/columns in a faceted plot? Maybe using sub{axis}label,\n-                # although the alignments of the labels from that method leaves\n-                # something to be desired (in terms of how it defines 'centered').\n-                names = [\n-                    common.names.get(axis_key),\n-                    *(layer[\"data\"].names.get(axis_key) for layer in layers)\n-                ]\n-                auto_label = next((name for name in names if name is not None), None)\n-                label = self._resolve_label(p, axis_key, auto_label)\n-                ax.set(**{f\"{axis}label\": label})\n-\n-                # ~~ Decoration visibility\n-\n-                # TODO there should be some override (in Plot.layout?) so that\n-                # axis / tick labels can be shown on interior shared axes if desired\n-\n-                axis_obj = getattr(ax, f\"{axis}axis\")\n-                visible_side = {\"x\": \"bottom\", \"y\": \"left\"}.get(axis)\n-                show_axis_label = (\n-                    sub[visible_side]\n-                    or not p._pair_spec.get(\"cross\", True)\n-                    or (\n-                        axis in p._pair_spec.get(\"structure\", {})\n-                        and bool(p._pair_spec.get(\"wrap\"))\n-                    )\n-                )\n-                axis_obj.get_label().set_visible(show_axis_label)\n-\n-                show_tick_labels = (\n-                    show_axis_label\n-                    or subplot_spec.get(f\"share{axis}\") not in (\n-                        True, \"all\", {\"x\": \"col\", \"y\": \"row\"}[axis]\n-                    )\n-                )\n-                for group in (\"major\", \"minor\"):\n-                    for t in getattr(axis_obj, f\"get_{group}ticklabels\")():\n-                        t.set_visible(show_tick_labels)\n-\n-            # TODO we want right-side titles for row facets in most cases?\n-            # Let's have what we currently call \"margin titles\" but properly using the\n-            # ax.set_title interface (see my gist)\n-            title_parts = []\n-            for dim in [\"col\", \"row\"]:\n-                if sub[dim] is not None:\n-                    val = self._resolve_label(p, \"title\", f\"{sub[dim]}\")\n-                    if dim in p._labels:\n-                        key = self._resolve_label(p, dim, common.names.get(dim))\n-                        val = f\"{key} {val}\"\n-                    title_parts.append(val)\n-\n-            has_col = sub[\"col\"] is not None\n-            has_row = sub[\"row\"] is not None\n-            show_title = (\n-                has_col and has_row\n-                or (has_col or has_row) and p._facet_spec.get(\"wrap\")\n-                or (has_col and sub[\"top\"])\n-                # TODO or has_row and sub[\"right\"] and <right titles>\n-                or has_row  # TODO and not <right titles>\n-            )\n-            if title_parts:\n-                title = \" | \".join(title_parts)\n-                title_text = ax.set_title(title)\n-                title_text.set_visible(show_title)\n-            elif not (has_col or has_row):\n-                title = self._resolve_label(p, \"title\", None)\n-                title_text = ax.set_title(title)\n-\n-    def _compute_stats(self, spec: Plot, layers: list[Layer]) -> None:\n-\n-        grouping_vars = [v for v in PROPERTIES if v not in \"xy\"]\n-        grouping_vars += [\"col\", \"row\", \"group\"]\n-\n-        pair_vars = spec._pair_spec.get(\"structure\", {})\n-\n-        for layer in layers:\n-\n-            data = layer[\"data\"]\n-            mark = layer[\"mark\"]\n-            stat = layer[\"stat\"]\n-\n-            if stat is None:\n-                continue\n-\n-            iter_axes = itertools.product(*[\n-                pair_vars.get(axis, [axis]) for axis in \"xy\"\n-            ])\n-\n-            old = data.frame\n-\n-            if pair_vars:\n-                data.frames = {}\n-                data.frame = data.frame.iloc[:0]  # TODO to simplify typing\n-\n-            for coord_vars in iter_axes:\n-\n-                pairings = \"xy\", coord_vars\n-\n-                df = old.copy()\n-                scales = self._scales.copy()\n-\n-                for axis, var in zip(*pairings):\n-                    if axis != var:\n-                        df = df.rename(columns={var: axis})\n-                        drop_cols = [x for x in df if re.match(rf\"{axis}\\d+\", str(x))]\n-                        df = df.drop(drop_cols, axis=1)\n-                        scales[axis] = scales[var]\n-\n-                orient = layer[\"orient\"] or mark._infer_orient(scales)\n-\n-                if stat.group_by_orient:\n-                    grouper = [orient, *grouping_vars]\n-                else:\n-                    grouper = grouping_vars\n-                groupby = GroupBy(grouper)\n-                res = stat(df, groupby, orient, scales)\n-\n-                if pair_vars:\n-                    data.frames[coord_vars] = res\n-                else:\n-                    data.frame = res\n-\n-    def _get_scale(\n-        self, spec: Plot, var: str, prop: Property, values: Series\n-    ) -> Scale:\n-\n-        if var in spec._scales:\n-            arg = spec._scales[var]\n-            if arg is None or isinstance(arg, Scale):\n-                scale = arg\n-            else:\n-                scale = prop.infer_scale(arg, values)\n-        else:\n-            scale = prop.default_scale(values)\n-\n-        return scale\n-\n-    def _get_subplot_data(self, df, var, view, share_state):\n-\n-        if share_state in [True, \"all\"]:\n-            # The all-shared case is easiest, every subplot sees all the data\n-            seed_values = df[var]\n-        else:\n-            # Otherwise, we need to setup separate scales for different subplots\n-            if share_state in [False, \"none\"]:\n-                # Fully independent axes are also easy: use each subplot's data\n-                idx = self._get_subplot_index(df, view)\n-            elif share_state in df:\n-                # Sharing within row/col is more complicated\n-                use_rows = df[share_state] == view[share_state]\n-                idx = df.index[use_rows]\n-            else:\n-                # This configuration doesn't make much sense, but it's fine\n-                idx = df.index\n-\n-            seed_values = df.loc[idx, var]\n-\n-        return seed_values\n-\n-    def _setup_scales(\n-        self, p: Plot,\n-        common: PlotData,\n-        layers: list[Layer],\n-        variables: list[str] | None = None,\n-    ) -> None:\n-\n-        if variables is None:\n-            # Add variables that have data but not a scale, which happens\n-            # because this method can be called multiple time, to handle\n-            # variables added during the Stat transform.\n-            variables = []\n-            for layer in layers:\n-                variables.extend(layer[\"data\"].frame.columns)\n-                for df in layer[\"data\"].frames.values():\n-                    variables.extend(str(v) for v in df if v not in variables)\n-            variables = [v for v in variables if v not in self._scales]\n-\n-        for var in variables:\n-\n-            # Determine whether this is a coordinate variable\n-            # (i.e., x/y, paired x/y, or derivative such as xmax)\n-            m = re.match(r\"^(?P<coord>(?P<axis>x|y)\\d*).*\", var)\n-            if m is None:\n-                coord = axis = None\n-            else:\n-                coord = m[\"coord\"]\n-                axis = m[\"axis\"]\n-\n-            # Get keys that handle things like x0, xmax, properly where relevant\n-            prop_key = var if axis is None else axis\n-            scale_key = var if coord is None else coord\n-\n-            if prop_key not in PROPERTIES:\n-                continue\n-\n-            # Concatenate layers, using only the relevant coordinate and faceting vars,\n-            # This is unnecessarily wasteful, as layer data will often be redundant.\n-            # But figuring out the minimal amount we need is more complicated.\n-            cols = [var, \"col\", \"row\"]\n-            parts = [common.frame.filter(cols)]\n-            for layer in layers:\n-                parts.append(layer[\"data\"].frame.filter(cols))\n-                for df in layer[\"data\"].frames.values():\n-                    parts.append(df.filter(cols))\n-            var_df = pd.concat(parts, ignore_index=True)\n-\n-            prop = PROPERTIES[prop_key]\n-            scale = self._get_scale(p, scale_key, prop, var_df[var])\n-\n-            if scale_key not in p._variables:\n-                # TODO this implies that the variable was added by the stat\n-                # It allows downstream orientation inference to work properly.\n-                # But it feels rather hacky, so ideally revisit.\n-                scale._priority = 0  # type: ignore\n-\n-            if axis is None:\n-                # We could think about having a broader concept of (un)shared properties\n-                # In general, not something you want to do (different scales in facets)\n-                # But could make sense e.g. with paired plots. Build later.\n-                share_state = None\n-                subplots = []\n-            else:\n-                share_state = self._subplots.subplot_spec[f\"share{axis}\"]\n-                subplots = [view for view in self._subplots if view[axis] == coord]\n-\n-            # Shared categorical axes are broken on matplotlib<3.4.0.\n-            # https://github.com/matplotlib/matplotlib/pull/18308\n-            # This only affects us when sharing *paired* axes. This is a novel/niche\n-            # behavior, so we will raise rather than hack together a workaround.\n-            if axis is not None and Version(mpl.__version__) < Version(\"3.4.0\"):\n-                from seaborn._core.scales import Nominal\n-                paired_axis = axis in p._pair_spec.get(\"structure\", {})\n-                cat_scale = isinstance(scale, Nominal)\n-                ok_dim = {\"x\": \"col\", \"y\": \"row\"}[axis]\n-                shared_axes = share_state not in [False, \"none\", ok_dim]\n-                if paired_axis and cat_scale and shared_axes:\n-                    err = \"Sharing paired categorical axes requires matplotlib>=3.4.0\"\n-                    raise RuntimeError(err)\n-\n-            if scale is None:\n-                self._scales[var] = Scale._identity()\n-            else:\n-                self._scales[var] = scale._setup(var_df[var], prop)\n-\n-            # Everything below here applies only to coordinate variables\n-            # We additionally skip it when we're working with a value\n-            # that is derived from a coordinate we've already processed.\n-            # e.g., the Stat consumed y and added ymin/ymax. In that case,\n-            # we've already setup the y scale and ymin/max are in scale space.\n-            if axis is None or (var != coord and coord in p._variables):\n-                continue\n-\n-            # Set up an empty series to receive the transformed values.\n-            # We need this to handle piecemeal transforms of categories -> floats.\n-            transformed_data = []\n-            for layer in layers:\n-                index = layer[\"data\"].frame.index\n-                empty_series = pd.Series(dtype=float, index=index, name=var)\n-                transformed_data.append(empty_series)\n-\n-            for view in subplots:\n-\n-                axis_obj = getattr(view[\"ax\"], f\"{axis}axis\")\n-                seed_values = self._get_subplot_data(var_df, var, view, share_state)\n-                view_scale = scale._setup(seed_values, prop, axis=axis_obj)\n-                set_scale_obj(view[\"ax\"], axis, view_scale._matplotlib_scale)\n-\n-                for layer, new_series in zip(layers, transformed_data):\n-                    layer_df = layer[\"data\"].frame\n-                    if var in layer_df:\n-                        idx = self._get_subplot_index(layer_df, view)\n-                        new_series.loc[idx] = view_scale(layer_df.loc[idx, var])\n-\n-            # Now the transformed data series are complete, set update the layer data\n-            for layer, new_series in zip(layers, transformed_data):\n-                layer_df = layer[\"data\"].frame\n-                if var in layer_df:\n-                    layer_df[var] = new_series\n-\n-    def _plot_layer(self, p: Plot, layer: Layer) -> None:\n-\n-        data = layer[\"data\"]\n-        mark = layer[\"mark\"]\n-        move = layer[\"move\"]\n-\n-        default_grouping_vars = [\"col\", \"row\", \"group\"]  # TODO where best to define?\n-        grouping_properties = [v for v in PROPERTIES if v[0] not in \"xy\"]\n-\n-        pair_variables = p._pair_spec.get(\"structure\", {})\n-\n-        for subplots, df, scales in self._generate_pairings(data, pair_variables):\n-\n-            orient = layer[\"orient\"] or mark._infer_orient(scales)\n-\n-            def get_order(var):\n-                # Ignore order for x/y: they have been scaled to numeric indices,\n-                # so any original order is no longer valid. Default ordering rules\n-                # sorted unique numbers will correctly reconstruct intended order\n-                # TODO This is tricky, make sure we add some tests for this\n-                if var not in \"xy\" and var in scales:\n-                    return getattr(scales[var], \"order\", None)\n-\n-            if \"width\" in mark._mappable_props:\n-                width = mark._resolve(df, \"width\", None)\n-            else:\n-                width = 0.8 if \"width\" not in df else df[\"width\"]  # TODO what default?\n-            if orient in df:\n-                df[\"width\"] = width * scales[orient]._spacing(df[orient])\n-\n-            if \"baseline\" in mark._mappable_props:\n-                # TODO what marks should have this?\n-                # If we can set baseline with, e.g., Bar(), then the\n-                # \"other\" (e.g. y for x oriented bars) parameterization\n-                # is somewhat ambiguous.\n-                baseline = mark._resolve(df, \"baseline\", None)\n-            else:\n-                # TODO unlike width, we might not want to add baseline to data\n-                # if the mark doesn't use it. Practically, there is a concern about\n-                # Mark abstraction like Area / Ribbon\n-                baseline = 0 if \"baseline\" not in df else df[\"baseline\"]\n-            df[\"baseline\"] = baseline\n-\n-            if move is not None:\n-                moves = move if isinstance(move, list) else [move]\n-                for move_step in moves:\n-                    move_by = getattr(move_step, \"by\", None)\n-                    if move_by is None:\n-                        move_by = grouping_properties\n-                    move_groupers = [*move_by, *default_grouping_vars]\n-                    if move_step.group_by_orient:\n-                        move_groupers.insert(0, orient)\n-                    order = {var: get_order(var) for var in move_groupers}\n-                    groupby = GroupBy(order)\n-                    df = move_step(df, groupby, orient, scales)\n-\n-            df = self._unscale_coords(subplots, df, orient)\n-\n-            grouping_vars = mark._grouping_props + default_grouping_vars\n-            split_generator = self._setup_split_generator(grouping_vars, df, subplots)\n-\n-            mark._plot(split_generator, scales, orient)\n-\n-        # TODO is this the right place for this?\n-        for view in self._subplots:\n-            view[\"ax\"].autoscale_view()\n-\n-        if layer[\"legend\"]:\n-            self._update_legend_contents(p, mark, data, scales)\n-\n-    def _unscale_coords(\n-        self, subplots: list[dict], df: DataFrame, orient: str,\n-    ) -> DataFrame:\n-        # TODO do we still have numbers in the variable name at this point?\n-        coord_cols = [c for c in df if re.match(r\"^[xy]\\D*$\", str(c))]\n-        drop_cols = [*coord_cols, \"width\"] if \"width\" in df else coord_cols\n-        out_df = (\n-            df\n-            .drop(drop_cols, axis=1)\n-            .reindex(df.columns, axis=1)  # So unscaled columns retain their place\n-            .copy(deep=False)\n-        )\n-\n-        for view in subplots:\n-            view_df = self._filter_subplot_data(df, view)\n-            axes_df = view_df[coord_cols]\n-            for var, values in axes_df.items():\n-\n-                axis = getattr(view[\"ax\"], f\"{str(var)[0]}axis\")\n-                # TODO see https://github.com/matplotlib/matplotlib/issues/22713\n-                transform = axis.get_transform().inverted().transform\n-                inverted = transform(values)\n-                out_df.loc[values.index, str(var)] = inverted\n-\n-                if var == orient and \"width\" in view_df:\n-                    width = view_df[\"width\"]\n-                    out_df.loc[values.index, \"width\"] = (\n-                        transform(values + width / 2) - transform(values - width / 2)\n-                    )\n-\n-        return out_df\n-\n-    def _generate_pairings(\n-        self, data: PlotData, pair_variables: dict,\n-    ) -> Generator[\n-        tuple[list[dict], DataFrame, dict[str, Scale]], None, None\n-    ]:\n-        # TODO retype return with subplot_spec or similar\n-\n-        iter_axes = itertools.product(*[\n-            pair_variables.get(axis, [axis]) for axis in \"xy\"\n-        ])\n-\n-        for x, y in iter_axes:\n-\n-            subplots = []\n-            for view in self._subplots:\n-                if (view[\"x\"] == x) and (view[\"y\"] == y):\n-                    subplots.append(view)\n-\n-            if data.frame.empty and data.frames:\n-                out_df = data.frames[(x, y)].copy()\n-            elif not pair_variables:\n-                out_df = data.frame.copy()\n-            else:\n-                if data.frame.empty and data.frames:\n-                    out_df = data.frames[(x, y)].copy()\n-                else:\n-                    out_df = data.frame.copy()\n-\n-            scales = self._scales.copy()\n-            if x in out_df:\n-                scales[\"x\"] = self._scales[x]\n-            if y in out_df:\n-                scales[\"y\"] = self._scales[y]\n-\n-            for axis, var in zip(\"xy\", (x, y)):\n-                if axis != var:\n-                    out_df = out_df.rename(columns={var: axis})\n-                    cols = [col for col in out_df if re.match(rf\"{axis}\\d+\", str(col))]\n-                    out_df = out_df.drop(cols, axis=1)\n-\n-            yield subplots, out_df, scales\n-\n-    def _get_subplot_index(self, df: DataFrame, subplot: dict) -> Index:\n-\n-        dims = df.columns.intersection([\"col\", \"row\"])\n-        if dims.empty:\n-            return df.index\n-\n-        keep_rows = pd.Series(True, df.index, dtype=bool)\n-        for dim in dims:\n-            keep_rows &= df[dim] == subplot[dim]\n-        return df.index[keep_rows]\n-\n-    def _filter_subplot_data(self, df: DataFrame, subplot: dict) -> DataFrame:\n-        # TODO note redundancies with preceding function ... needs refactoring\n-        dims = df.columns.intersection([\"col\", \"row\"])\n-        if dims.empty:\n-            return df\n-\n-        keep_rows = pd.Series(True, df.index, dtype=bool)\n-        for dim in dims:\n-            keep_rows &= df[dim] == subplot[dim]\n-        return df[keep_rows]\n-\n-    def _setup_split_generator(\n-        self, grouping_vars: list[str], df: DataFrame, subplots: list[dict[str, Any]],\n-    ) -> Callable[[], Generator]:\n-\n-        allow_empty = False  # TODO will need to recreate previous categorical plots\n-\n-        grouping_keys = []\n-        grouping_vars = [\n-            v for v in grouping_vars if v in df and v not in [\"col\", \"row\"]\n-        ]\n-        for var in grouping_vars:\n-            order = getattr(self._scales[var], \"order\", None)\n-            if order is None:\n-                order = categorical_order(df[var])\n-            grouping_keys.append(order)\n-\n-        def split_generator(keep_na=False) -> Generator:\n-\n-            for view in subplots:\n-\n-                axes_df = self._filter_subplot_data(df, view)\n-\n-                with pd.option_context(\"mode.use_inf_as_null\", True):\n-                    if keep_na:\n-                        # The simpler thing to do would be x.dropna().reindex(x.index).\n-                        # But that doesn't work with the way that the subset iteration\n-                        # is written below, which assumes data for grouping vars.\n-                        # Matplotlib (usually?) masks nan data, so this should \"work\".\n-                        # Downstream code can also drop these rows, at some speed cost.\n-                        present = axes_df.notna().all(axis=1)\n-                        nulled = {}\n-                        for axis in \"xy\":\n-                            if axis in axes_df:\n-                                nulled[axis] = axes_df[axis].where(present)\n-                        axes_df = axes_df.assign(**nulled)\n-                    else:\n-                        axes_df = axes_df.dropna()\n-\n-                subplot_keys = {}\n-                for dim in [\"col\", \"row\"]:\n-                    if view[dim] is not None:\n-                        subplot_keys[dim] = view[dim]\n-\n-                if not grouping_vars or not any(grouping_keys):\n-                    yield subplot_keys, axes_df.copy(), view[\"ax\"]\n-                    continue\n-\n-                grouped_df = axes_df.groupby(grouping_vars, sort=False, as_index=False)\n-\n-                for key in itertools.product(*grouping_keys):\n-\n-                    # Pandas fails with singleton tuple inputs\n-                    pd_key = key[0] if len(key) == 1 else key\n-\n-                    try:\n-                        df_subset = grouped_df.get_group(pd_key)\n-                    except KeyError:\n-                        # TODO (from initial work on categorical plots refactor)\n-                        # We are adding this to allow backwards compatability\n-                        # with the empty artists that old categorical plots would\n-                        # add (before 0.12), which we may decide to break, in which\n-                        # case this option could be removed\n-                        df_subset = axes_df.loc[[]]\n-\n-                    if df_subset.empty and not allow_empty:\n-                        continue\n-\n-                    sub_vars = dict(zip(grouping_vars, key))\n-                    sub_vars.update(subplot_keys)\n-\n-                    # TODO need copy(deep=...) policy (here, above, anywhere else?)\n-                    yield sub_vars, df_subset.copy(), view[\"ax\"]\n-\n-        return split_generator\n-\n-    def _update_legend_contents(\n-        self,\n-        p: Plot,\n-        mark: Mark,\n-        data: PlotData,\n-        scales: dict[str, Scale],\n-    ) -> None:\n-        \"\"\"Add legend artists / labels for one layer in the plot.\"\"\"\n-        if data.frame.empty and data.frames:\n-            legend_vars: list[str] = []\n-            for frame in data.frames.values():\n-                frame_vars = frame.columns.intersection(list(scales))\n-                legend_vars.extend(v for v in frame_vars if v not in legend_vars)\n-        else:\n-            legend_vars = list(data.frame.columns.intersection(list(scales)))\n-\n-        # First pass: Identify the values that will be shown for each variable\n-        schema: list[tuple[\n-            tuple[str, str | int], list[str], tuple[list, list[str]]\n-        ]] = []\n-        schema = []\n-        for var in legend_vars:\n-            var_legend = scales[var]._legend\n-            if var_legend is not None:\n-                values, labels = var_legend\n-                for (_, part_id), part_vars, _ in schema:\n-                    if data.ids[var] == part_id:\n-                        # Allow multiple plot semantics to represent same data variable\n-                        part_vars.append(var)\n-                        break\n-                else:\n-                    title = self._resolve_label(p, var, data.names[var])\n-                    entry = (title, data.ids[var]), [var], (values, labels)\n-                    schema.append(entry)\n-\n-        # Second pass, generate an artist corresponding to each value\n-        contents: list[tuple[tuple[str, str | int], Any, list[str]]] = []\n-        for key, variables, (values, labels) in schema:\n-            artists = []\n-            for val in values:\n-                artist = mark._legend_artist(variables, val, scales)\n-                if artist is not None:\n-                    artists.append(artist)\n-            if artists:\n-                contents.append((key, artists, labels))\n-\n-        self._legend_contents.extend(contents)\n-\n-    def _make_legend(self, p: Plot) -> None:\n-        \"\"\"Create the legend artist(s) and add onto the figure.\"\"\"\n-        # Combine artists representing same information across layers\n-        # Input list has an entry for each distinct variable in each layer\n-        # Output dict has an entry for each distinct variable\n-        merged_contents: dict[\n-            tuple[str, str | int], tuple[list[Artist], list[str]],\n-        ] = {}\n-        for key, new_artists, labels in self._legend_contents:\n-            # Key is (name, id); we need the id to resolve variable uniqueness,\n-            # but will need the name in the next step to title the legend\n-            if key in merged_contents:\n-                # Copy so inplace updates don't propagate back to legend_contents\n-                existing_artists = merged_contents[key][0]\n-                for i, artist in enumerate(existing_artists):\n-                    # Matplotlib accepts a tuple of artists and will overlay them\n-                    if isinstance(artist, tuple):\n-                        artist += new_artists[i],\n-                    else:\n-                        existing_artists[i] = artist, new_artists[i]\n-            else:\n-                merged_contents[key] = new_artists.copy(), labels\n-\n-        # TODO explain\n-        loc = \"center right\" if self._pyplot else \"center left\"\n-\n-        base_legend = None\n-        for (name, _), (handles, labels) in merged_contents.items():\n-\n-            legend = mpl.legend.Legend(\n-                self._figure,\n-                handles,\n-                labels,\n-                title=name,\n-                loc=loc,\n-                bbox_to_anchor=(.98, .55),\n-            )\n-\n-            if base_legend:\n-                # Matplotlib has no public API for this so it is a bit of a hack.\n-                # Ideally we'd define our own legend class with more flexibility,\n-                # but that is a lot of work!\n-                base_legend_box = base_legend.get_children()[0]\n-                this_legend_box = legend.get_children()[0]\n-                base_legend_box.get_children().extend(this_legend_box.get_children())\n-            else:\n-                base_legend = legend\n-                self._figure.legends.append(legend)\n-\n-    def _finalize_figure(self, p: Plot) -> None:\n-\n-        for sub in self._subplots:\n-            ax = sub[\"ax\"]\n-            for axis in \"xy\":\n-                axis_key = sub[axis]\n-\n-                # Axis limits\n-                if axis_key in p._limits:\n-                    convert_units = getattr(ax, f\"{axis}axis\").convert_units\n-                    a, b = p._limits[axis_key]\n-                    lo = a if a is None else convert_units(a)\n-                    hi = b if b is None else convert_units(b)\n-                    if isinstance(a, str):\n-                        lo = cast(float, lo) - 0.5\n-                    if isinstance(b, str):\n-                        hi = cast(float, hi) + 0.5\n-                    ax.set(**{f\"{axis}lim\": (lo, hi)})\n-\n-        engine_default = None if p._target is not None else \"tight\"\n-        layout_engine = p._layout_spec.get(\"engine\", engine_default)\n-        set_layout_engine(self._figure, layout_engine)\n", "model": "claude-sonnet-5-5", "steps": 26, "finished": false, "patch_lines": 1654, "candidates": [{"compile_ok": 0, "loc_hits": 1, "files": 1, "diff_lines": 1654, "steps": 26}], "ms": 171027}
{"instance_id": "mwaskom__seaborn-3187", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/seaborn/_core/scales.py b/seaborn/_core/scales.py\nindex 55874bf2..80bff39b 100644\n--- a/seaborn/_core/scales.py\n+++ b/seaborn/_core/scales.py\n@@ -378,6 +378,12 @@ class ContinuousBase(Scale):\n             axis.set_view_interval(vmin, vmax)\n             locs = axis.major.locator()\n             locs = locs[(vmin <= locs) & (locs <= vmax)]\n+            # Avoid an offset / scientific notation in the legend, since\n+            # it is not represented anywhere and the labels would be wrong.\n+            if hasattr(axis.major.formatter, \"set_useOffset\"):\n+                axis.major.formatter.set_useOffset(False)\n+            if hasattr(axis.major.formatter, \"set_scientific\"):\n+                axis.major.formatter.set_scientific(False)\n             labels = axis.major.formatter.format_ticks(locs)\n             new._legend = list(locs), list(labels)\n \ndiff --git a/seaborn/utils.py b/seaborn/utils.py\nindex 2407853c..d23eab49 100644\n--- a/seaborn/utils.py\n+++ b/seaborn/utils.py\n@@ -699,6 +699,8 @@ def locator_to_legend_entries(locator, limits, dtype):\n         formatter = mpl.ticker.LogFormatter()\n     else:\n         formatter = mpl.ticker.ScalarFormatter()\n+        formatter.set_useOffset(False)\n+        formatter.set_scientific(False)\n     formatter.axis = dummy_axis()\n \n     # TODO: The following two lines should be replaced\n", "model": "claude-sonnet-5-5", "steps": 7, "finished": true, "patch_lines": 30, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 2, "diff_lines": 30, "steps": 7}], "ms": 14813}
{"instance_id": "pallets__flask-5014", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/src/flask/blueprints.py b/src/flask/blueprints.py\nindex eb50585d..1aa82562 100644\n--- a/src/flask/blueprints.py\n+++ b/src/flask/blueprints.py\n@@ -190,6 +190,9 @@ class Blueprint(Scaffold):\n             root_path=root_path,\n         )\n \n+        if not name:\n+            raise ValueError(\"'name' may not be empty.\")\n+\n         if \".\" in name:\n             raise ValueError(\"'name' may not contain a dot '.' character.\")\n \n", "model": "claude-sonnet-5-5", "steps": 6, "finished": true, "patch_lines": 14, "candidates": [{"compile_ok": 0, "loc_hits": 1, "files": 1, "diff_lines": 14, "steps": 6}], "ms": 11598}
