**Bug Report**

 When connected to a PostgreSQL database and running a CREATE OR REPLACE FUNCTION statement that uses dollar-quoting ($$), sqlit throws a parsing error before sending the query to Postgres:

  _unterminated dollar-quoted string at or near "$$
  DECLARE
      ..."
  LINE 2: RETURNS api.transactions AS $$_
                                      ^

  **Steps to Reproduce**

  1. Connect sqlit to a PostgreSQL database
  2. Run any function/procedure using dollar-quote syntax, e.g.:

  CREATE OR REPLACE FUNCTION example()
  RETURNS void AS $$
  BEGIN
    -- body
  END;
  $$ LANGUAGE plpgsql;

  **Expected Behavior**

  The full statement should be sent to PostgreSQL as-is. PostgreSQL natively supports dollar-quoting and executes it without
  error.

  **Actual Behavior**

  sqlit appears to parse/split the statement client-side and does not correctly handle $$ dollar-quote delimiters, resulting in
  the error above.

  **Workaround**

  Running the same SQL via psql directly works fine.

  - Tool: sqlit
  - Database: PostgreSQL

<img width="649" height="199" alt="Image" src="https://github.com/user-attachments/assets/d4456a32-3bcb-4c04-a2a4-65fc157a1c26" />

PostgreSQL dollar-quoted strings ($$) cause "unterminated dollar-quoted string" error

uv sync --frozen --group test --no-dev --extra duckdb --no-install-project


If I write this query

```sql
ALTER SESSION SET EDITION = V0;
```
I get
```
Query error: ORA-00922: missing or invalid option
Help: https://docs.oracle.com/error-help/db/ora-00922/
```

but if I remove the trailing `;` it works

oracledb: if query has `;` it fails with `ORA-00922: missing or invalid option`


Hi, this is sort of a collection of issues/questions but I'm reporting them together to share to full picture.

I'm currently trying to figure out how to best handle pandas indices in the context of `nw.concat` for certain cases. Consider the situation where I have some function `process` that transforms a given dataframe into another but *not* using index-preserving dataframe operations (the specifics don't matter, but in my case this happens because I'm transitioning to `torch` for the computation).

The problem I run into is that the resulting pandas execution will differ from other backends if I feed the resulting dataframe together with the original one into `nw.concat`:

```python
import narwhals as nw
import pandas as pd

def process(df: nw.DataFrame) -> nw.DataFrame:
    return nw.from_dict(
        {"B": list(range(len(df)))}, backend=nw.get_native_namespace(df)
    )

df1 = pd.DataFrame({"A": [1, 2, 3]}, index=[10, 20, 30])
df1_nw = nw.from_native(df1)
df2_nw = process(df1_nw)

print("\n-- concat without index alignment --")
print(nw.to_native(nw.concat([df1_nw, df2_nw], how="horizontal")))
```

That is, for polars I'll get the "expected" compact 3-row dataframe while for pandas I get:
```
-- concat without index alignment --
      A    B
10  1.0  NaN
20  2.0  NaN
30  3.0  NaN
0   NaN  0.0
1   NaN  1.0
2   NaN  2.0
```

### Questions
1. Do you see a better way how to handle this situation, i.e. how would you approach it?
2. One easy way to avoid losing the index would be if there existed some function that would let me "swap out" the dataframe content of the original one, instead of creating a new one. In particular, that would allow to both a) keep the index and b) keep the backend information. But I guess that functionality does not exist? The closest I could find is `replace_strict`, but that only works for `Series`.
3. The other alternative I see is manually handle the index by calling `maybe_get_index`/`maybe_set_index`, like outlined in the method below. However, when I tried this, I was very surprised that the two functions are not symmetric in terms of types! That is, I would have expected that `maybe_set_index` also accepts an interable like `Series.from_iterable` does and I can easily nest them like `nw.maybe_set_index(..., index=nw.maybe_get_index(...))`, but that does not seem to be the case.

Any thoughts here?

```python
def process_preserving_index(df: nw.DataFrame) -> nw.DataFrame:
    idx = nw.maybe_get_index(df)
    result = process(df)
    if idx is not None:
        idx_series = nw.from_native(pd.Series(idx), series_only=True)
        result = nw.maybe_set_index(result, index=idx_series)
    return result
```

python -m pytest -q --randomly-seed=0 --hypothesis-seed=0 -o cache_dir=/tmp/pytest-cache --runslow --constructors=pandas,pandas[nullable] tests

uv pip install --python /opt/venv/bin/python --only-binary :all: uv_build==0.11.0

uv sync --frozen --no-default-groups --group tests --extra pandas --no-install-project

mkdir -p "$HOME" "$XDG_CACHE_HOME" "$UV_CACHE_DIR" && uv pip install --offline --python /opt/venv/bin/python --no-deps --no-build-isolation --editable .


### Contributing guidelines

- [x] I understand the contributing guidelines

### Documentation

- [x] My proposal is not addressed by the documentation or examples

### Existing issues

- [x] Nothing similar appears in an existing issue

### Describe the bug

In trying to reproduce the GTFS to Graphs example (https://city2graph.net/latest/examples/gtfs.html#the-power-of-graph-representation) , I found an error when plotting:
```
c2g.plot_graph(
    nodes=travel_nodes,
    edges=travel_edges,
    markersize=8,
    node_color='centrality_quantile',
    node_alpha=0.9,
    edge_color='#bbbbbb',
    edge_linewidth=travel_edges['frequency'] / 200,
    edge_alpha=0.7,
    figsize=(16, 16),
    title="Central London Transit Network\nBetweenness Centrality of Stops",
    legend=True,
    legend_kwargs={'label': 'Betweenness Centrality', 'orientation': 'horizontal'},
    title = 'Central London Transit Network\nBetweenness Centrality of Stops',
    ax=ax
)
```
> `IndexError: index 1 is out of bounds for axis 0 with size 1`

Removing `legend=True`, `legend_kwargs`, and `title`  makes the same call work.

### To Reproduce

```python
### Fails

import geopandas as gpd
from shapely.geometry import Point, LineString
import matplotlib.pyplot as plt
import city2graph as c2g

nodes = gpd.GeoDataFrame(
    {"centrality_quantile": [1, 2]},
    geometry=[Point(0, 0), Point(1, 1)],
    crs="EPSG:4326",
)

edges = gpd.GeoDataFrame(
    {"frequency": [100, 200]},
    geometry=[LineString([(0, 0), (1, 1)]), LineString([(1, 1), (2, 2)])],
    crs="EPSG:4326",
)

fig, ax = plt.subplots(figsize=(5, 5))

c2g.plot_graph(
    nodes=nodes,
    edges=edges,
    node_color="centrality_quantile",
    edge_color="#bbbbbb",
    edge_linewidth=edges["frequency"] / 200,
    legend=True,
    legend_kwargs={"label": "Betweenness Centrality", "orientation": "horizontal"},
    title = "Central London Transit Network Betweenness Centrality of Stops",
    ax=ax,
)

plt.show()
```
This produces:
 > `IndexError: index 1 is out of bounds for axis 0 with size 1`
I would expect that this creates plots the graph

### Expected behavior

```python
### Works
# Removing `legend=True`, `legend_kwargs`, and `title`  a makes the same call succeed.

import geopandas as gpd
from shapely.geometry import Point, LineString
import matplotlib.pyplot as plt
import city2graph as c2g

nodes = gpd.GeoDataFrame(
    {"centrality_quantile": [1, 2]},
    geometry=[Point(0, 0), Point(1, 1)],
    crs="EPSG:4326",
)

edges = gpd.GeoDataFrame(
    {"frequency": [100, 200]},
    geometry=[LineString([(0, 0), (1, 1)]), LineString([(1, 1), (2, 2)])],
    crs="EPSG:4326",
)

fig, ax = plt.subplots(figsize=(5, 5))

c2g.plot_graph(
    nodes=nodes,
    edges=edges,
    node_color="centrality_quantile",
    edge_color="#bbbbbb",
    edge_linewidth=edges["frequency"] / 200,
    # legend=True,
    # legend_kwargs={"label": "Betweenness Centrality", "orientation": "horizontal"},
    # title = "Central London Transit Network Betweenness Centrality of Stops"
    ax=ax,
)

plt.show()
```

### Environment (please complete the following information):

OS: macOS 15.7.2

CPU: Apple M4 Max (arm64)

GPU: Apple M4 Max (integrated GPU)

Python version: 3.13

city2graph version: 0.2.4

torch version: 2.10.0

torch_geometric version: 2.7.0

### How did you install city2graph?

via PyPI (e.g., pip)

### Additional context

_No response_

[BUG] plot_graph fails when `legend=True` , `legend_kwargs` and `title` is provided

uv sync --frozen --extra cpu --group dev --no-install-project


### Version of the library

https://mangiucugna.github.io/json_repair/#jr=v1.d.eJw9isEKglAUBX9FDoKL3kZr9aAv6bR42i2sfMZVQbjcf4_ImsUwizHcEWHEMolORDwZkdMgRCTKtGuPHXnV1Fnt1nhJBELH53cgW7n12V5DmrVfvai50fxi_9GhICVf_h8R_ByI8UHEWRepmOFvF04wEQ

### Describe the bug

LaTex uses double backslashes `\\` to break new liens, and in JSON we have to write 4 backslashes `\\\\`. This is important in writing matrices.
json_repair would convert `\\\\` (4 backslashes) to `\\` (2 backslahes), making the matrix expression incorrect.

### How to reproduce
For input
`{ "content": [ { "topic_text": " $$\\begin{pmatrix} a\\\\b\\\\c \\end{pmatrix}$$" } ] } `

output is
`
{
    "content": [
        {
            "topic_text": " $$\\begin{pmatrix} a\\b\\c \\end{pmatrix}$$"
        }
    ]
}
`

### Expected behavior
`
{
    "content": [
        {
            "topic_text": " $$\\begin{pmatrix} a\\\\b\\\\c \\end{pmatrix}$$"
        }
    ]
}
`

uv pip install --python /opt/venv/bin/python setuptools==80.9.0

uv sync --frozen --all-groups --no-install-project

uv pip install --offline --python /opt/venv/bin/python --no-deps --no-build-isolation --editable .


### Version of the library

0.59.0

### Describe the bug

If input contains () characters outside of json block, the result gets weird.

With 0.58.7 it works as expected: `{"key": "value"}` is returned.
With 0.59.0 result is: `["some clarification):\n        \n        ```json\n        {", "key\": \"value"]`

### How to reproduce

```
    async def test_json_and_parenthesis(self):
        import json_repair
        data_str = """
         **Decision**: bla, bla (some clarification):

        ```json
        {
          "key": "value"
        }
        ```
        """

        repaired = json_repair.repair_json(data_str)

        self.assertEqual('{"key": "value"}', repaired)
```

### Expected behavior

`{"key": "value"}` is returned.

[Bug]: 0.59.0 regression: () characters in input break json output


### Version of the library

0.61.4

### Describe the bug

When malformed JSON activates the schema-aware repair parser, validation of an `anyOf` branch containing a root-relative $ref fails with `PointerToNowhere`:

```
jsonschema.exceptions._WrappedReferencingError: PointerToNowhere: '/$defs/Item' does not exist within {'type': 'array', 'items': {'$ref': '#/$defs/Item'}}
```

json_repair appears to validate the individual anyOf branch as a standalone schema document which fails because that isolated branch does not contain $defs.

### How to reproduce

```python
import json_repair

schema = {
    "$defs": {
        "Item": {
            "type": "object",
            "properties": {
                "name": {"type": "string"},
            },
            "required": ["name"],
        }
    },
    "type": "object",
    "properties": {
        "value": {
            "anyOf": [
                {
                    "type": "array",
                    "items": {"$ref": "#/$defs/Item"},
                },
                {"type": "null"},
            ]
        }
    },
    "required": ["value"],
}

# The trailing comma forces json_repair to use its repair parser.
broken_json = '{"value": [{"name": "example"}],}'

print(json_repair.loads(broken_json, schema=schema))
```

### Expected behavior

The reference should resolve against the original root schema.

[Bug]: Schema aware repair loses root $defs scope when validating an anyOf branch


<!--
This issue tracker is a tool to address bugs in Click itself. Please use
GitHub Discussions or the Pallets Discord for questions about your own code.

Replace this comment with a clear outline of what the bug is.
-->
I had failing unit tests after upgrading to click 8.4.1. I was able to address some
by using `runner.invoke(cmd, color=False)`, but that didn't help for commands
that use `click.confirm()`

<!--
Describe how to replicate the bug.

Include a minimal reproducible example that demonstrates the bug.
Include the full traceback if there was an exception.
-->

This test script `test_repro.py` replicates the issue.
```
import click
from click.testing import CliRunner

@click.command()
def cmd():
    click.echo(click.style('Hello World!', fg='green'))

@click.command()
def cmd_confirm():
    click.confirm(click.style('Hello World!', fg='green'), abort=True)

def test_echo_strips_ansi_with_color_false():
    runner = CliRunner()
    result = runner.invoke(cmd, color=False)
    assert result.output == "Hello World!\n"

def test_confirm_strips_ansi_with_color_false():
    runner = CliRunner()
    result = runner.invoke(cmd_confirm, input="Y", color=False)
    assert result.output == "Hello World! [y/N]: Y\n"  # FAILS: ANSI codes present
```

With click 8.3.3 both tests pass. With click 8.4.0 and 8.4.1, the `test_confirm_strips_ansi_with_color_false` test fails:

```
uvx --with click==8.4 pytest test_repro.py
...
================================================ FAILURES ================================================
_______________________________ test_confirm_strips_ansi_with_color_false ________________________________

    def test_confirm_strips_ansi_with_color_false():
        runner = CliRunner()
        result = runner.invoke(cmd_confirm, input="Y", color=False)
>       assert result.output == "Hello World! [y/N]: Y\n"  # FAILS: ANSI codes present
```

<!--
Describe the expected behavior that should have happened but didn't.
-->
The ansi codes should be stripped when running click.confirm, as they are for click.echo.

Environment:

- Python version: 3.13
- Click version: 8.4.1
- MacOS

ANSI codes not stripped from click.confirm after upgrading to click 8.4

apt-get update && apt-get install -y --no-install-recommends less=590-2.1~deb12u2 && rm -rf /var/lib/apt/lists/*

SETUPTOOLS_SCM_PRETEND_VERSION_FOR_ATTRS=0.0.0 uv sync --frozen --no-default-groups --group tests --no-install-project


If no `args` are passed to `HelpFormatter.write_usage`, the Usage line is not printed.

### Reproduction

```python
import click

f = click.HelpFormatter()
f.write_usage("program")
print(f.getvalue())
```
<!--
Describe how to replicate the bug.

Include a minimal reproducible example that demonstrates the bug.
Include the full traceback if there was an exception.
-->

### Expected output
```
Usage: program
```

### Actual output
(an empty line)

### Environment

- Python version: 3.12.3
- Click version: 8.3.1

### Additional information

We use `click` for a CLI program with interactive mode. We are about to use `click.HelpFormatter` to print help for internal commands, some of which do not accept any arguments (`exit`, for example).

Empty output from `HelpFormatter.write_usage` for a program without arguments


tests/test_formatting.py::test_formatting_usage_error_help_hint[help_names1-extra_options1-Try 'cli foo --help' for help.]

<!--
This issue tracker is a tool to address bugs in Click itself. Please use
GitHub Discussions or the Pallets Discord for questions about your own code.

Replace this comment with a clear outline of what the bug is.
-->

Click prints an incorrect suggestion when using a combination of nested command and required argument. This happens when the nested command shadows the `-h` option shortcut of the main command which Click apparently tolerates.

<!--
Describe how to replicate the bug.

Include a minimal reproducible example that demonstrates the bug.
Include the full traceback if there was an exception.
-->

## Replication

See https://github.com/tumidi/click-subcommand-help-message.

```shell-session
$ click-test-cli foo
Usage: click-test-cli foo [OPTIONS] REQUIRED_ARG
Try 'click-test-cli foo -h' for help.

Error: Missing argument 'REQUIRED_ARG'.
```

But, actually running the suggested `click-test-cli foo -h` prints

```shell-session
$ click-test-cli foo -h
Error: Option '-h' requires an argument.
```

Interestingly, Click correctly detects the shadowing of the option when printing the foo command help and prints a consistent help page.

```shell-session
$ click-test-cli foo --help
Usage: click-test-cli foo [OPTIONS] REQUIRED_ARG

Options:
  -h, --host TEXT
  --help           Show this message and exit.
```

### Python code

```py
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
def cli():
    pass

@click.command()
@click.argument("required_arg")
@click.option("--host", "-h", "host", default="localhost")
def foo(required_arg, host):
    click.echo(f"Foo command required_arg={required_arg} host={host}")

cli.add_command(foo)
```

<!--
Describe the expected behavior that should have happened but didn't.
-->

## Possible solutions

Fix the generated message, so it prints `Try 'click-test-cli foo --help' for help.` in this case.

Environment:

- Python version: 3.12.6
- Click version: 8.2.0.dev0 d73083e

Nested command option shadowing `-h` prints wrong suggestion


I am using `visitor_text` to get text positions so I can draw highlight boxes over
a rendered page.

The attached PDF sets a text leading of 14 (`14 TL`) and uses `T*` to move to the
next line. Each `T*` should move down 14pt. `visitor_text` reports the lines
168pt apart instead.

This looks distinct from #3247 / #3250, which corrected the *direction* of the
`T*` translation (the missing horizontal component for rotated text). Here the
direction is fine and the *distance* is wrong.

Content stream, in full:

```
BT
/F1 12 Tf
1 0 0 1 72 700 Tm
14 TL
(Line one) Tj
T*
(Line two) Tj
T*
(Line three) Tj
ET
```

## Environment

```bash
$ python -m platform
Windows-10-10.0.26200-SP0

$ python -c "import pypdf;print(pypdf._debug_versions)"
pypdf==6.16.1, crypt_provider=('local_crypt_fallback', '0.0.0'), PIL=12.3.0
```

## Code + PDF

`tl_repro.pdf` attached (633 bytes). Happy for it to go in your tests.

```python
import pypdf

page = pypdf.PdfReader("tl_repro.pdf").pages[0]

ys = []
page.extract_text(
    visitor_text=lambda text, cm, tm, fd, fs:
        ys.append(round(tm[5], 2)) if text.strip() else None)
print(ys)
```

Expected `[700.0, 686.0, 672.0]` (14pt apart).
Actual `[700.0, 532.0, 364.0]` (168pt apart).

For reference, MuPDF 1.28.2 puts the three lines 14pt apart on this file
(top-y `79.10 / 93.10 / 107.10`).

The extracted text itself is correct (`'Line one\nLine two\nLine three'`) — only
the reported text matrix is wrong.

## Traceback

Not applicable, no exception — the returned coordinates are just wrong.

## Bisect

Same file, same script:

```
pypdf 5.0.1 : [700.0, 686.0, 672.0]   correct
pypdf 5.1.0 : [700.0, 532.0, 364.0]   wrong
pypdf 6.16.1: [700.0, 532.0, 364.0]   wrong
```

[tl_repro.pdf](https://github.com/user-attachments/files/31226124/tl_repro.pdf)

T* moves by the wrong amount — regression in 5.1.0

python
-m
pytest
-q
-p
pytest_socket
-p
pytest_timeout
--timeout=60
-o
cache_dir=/tmp/pytest-cache
-m
not enable_socket and not samples
tests

uv pip install --python /opt/venv/bin/python --no-deps --only-binary :all: flit_core==3.11.0 pygments==2.19.2

python -m venv /opt/venv && uv pip install --python /opt/venv/bin/python --no-deps --only-binary :all: -r requirements/ci-3.11.txt


[Issue description, minimal reproducible example, and link to test document](https://stackoverflow.com/questions/79962929/calling-remove-from-tree-on-outline-item-causes-removed-child-does-not-appear-t?noredirect=1#comment141089279_79962929)

## Environment

Which environment were you using when you encountered the problem?

```bash
$ python -m platform
Windows-11-10.0.26200-SP0

$ python -c "import pypdf;print(pypdf._debug_versions)"
pypdf==6.13.0, crypt_provider=('cryptography', '48.0.0'), PIL=12.2.0
```

## Code + PDF

This is a minimal, complete example that shows the issue:

```python
# Source - https://stackoverflow.com/q/79962929
# Posted by Les Harris, modified by community. See post 'Timeline' for change history
# Retrieved 2026-06-19, License - CC BY-SA 4.0

from typing import List, Union

from pypdf import PdfReader, PdfWriter
from pypdf.generic import Destination, Fit, NameObject, ArrayObject, NumberObject, FloatObject

def remove_outline_item(output_path: str) -> None:
    try:
        # Remove a specific outline item by its color
        for outline in writer.outline:
            if isinstance(outline, list):
                remove_outline_item(outline)
            else:
                if outline.color == [0.0, 0.0, 0.0]:
                    print(outline.title, outline.color, outline.get("/Parent"))
                    outline.remove_from_tree() # error happens here

    except FileNotFoundError:
        print(f"Error: File '{output_path}' not found.")
    except Exception as e:
        print(f"An error occurred: {e}")

reader = PdfReader("input.pdf")
writer = PdfWriter(clone_from=reader)

remove_outline_item(writer)

# Save to a new file
with open("output.pdf", "wb") as f:
    writer.write(f)

```

For testing:
[input.pdf](https://github.com/user-attachments/files/29153170/input.pdf)

## Traceback

This is the complete traceback I see:

```
# Source - https://stackoverflow.com/q/79962929
# Posted by Les Harris, modified by community. See post 'Timeline' for change history
# Retrieved 2026-06-19, License - CC BY-SA 4.0

PS C:\temp> python change-bookmark-text-color.py
Cover [0.0, 0.0, 0.0] None
An error occurred: Removed child does not appear to be a tree item

```

Calling remove_from_tree on outline item causes "Removed child does not appear to be a tree item" error


I get an AssertionError when merging a PDF that contains both latin and Chinese characters. This happens with a real PDF I work with, but for this issue I've created a small PDF that triggers the error. Perhaps the fact that the PDF contains both latin and Chinese characters has nothing to do with the issue, but I suspect it does.

## Environment

```bash
$ python3 -c "import pypdf;print(pypdf._debug_versions)"
pypdf==6.5.0, crypt_provider=('cryptography', '43.0.0'), PIL=11.1.0
```

## Code + PDF

```python
import pypdf

reader = pypdf.PdfReader("minimal.pdf")
writer = pypdf.PdfWriter()
for page in reader.pages:
    writerPage = writer.add_blank_page(reader.pages[0].mediabox.width, reader.pages[0].mediabox.height)
    writerPage.merge_page(page)
```

[minimal.pdf](https://github.com/user-attachments/files/24400020/minimal.pdf)

I do not know why this particular set of characters triggers the error, but it's the minimal set I could find that triggers it. Feel free to add the PDF to your tests.

## Traceback

```
Traceback (most recent call last):
  File "/home/user/tmp/minimal.py", line 7, in <module>
    writerPage.merge_page(page)
    ~~~~~~~~~~~~~~~~~~~~~^^^^^^
  File "/home/user/tmp/pypdf/_page.py", line 1068, in merge_page
    self._merge_page(page2, over=over, expand=expand)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/tmp/pypdf/_page.py", line 1147, in _merge_page
    page2content.operations.insert(
    ^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/tmp/pypdf/generic/_data_structures.py", line 1410, in operations
    self._parse_content_stream(BytesIO(self._data))
    ~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/tmp/pypdf/generic/_data_structures.py", line 1303, in _parse_content_stream
    operands.append(read_object(stream, None, self.forced_encoding))
                    ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/tmp/pypdf/generic/_data_structures.py", line 1452, in read_object
    return ArrayObject.read_from_stream(stream, pdf, forced_encoding)
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/tmp/pypdf/generic/_data_structures.py", line 261, in read_from_stream
    arr.append(read_object(stream, pdf, forced_encoding))
               ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/tmp/pypdf/generic/_data_structures.py", line 1450, in read_object
    return read_hex_string_from_stream(stream, forced_encoding)
  File "/home/user/tmp/pypdf/generic/_utils.py", line 35, in read_hex_string_from_stream
    return create_string_object(bytes(arr), forced_encoding)
  File "/home/user/tmp/pypdf/generic/_utils.py", line 168, in create_string_object
    retval = TextStringObject(string.decode("utf-16be"))
  File "/home/user/tmp/pypdf/generic/_base.py", line 673, in __new__
    assert org is not None, "mypy"
           ^^^^^^^^^^^^^^^
AssertionError: mypy
```

## Typst code

The PDF I share above was created with the [Typst](https://typst.app) typesetting system, version 0.14.2, from the following code:

```typ
#set document(date: none)
#set text(font: ("Noto Sans CJK SC"))

接司智对UQfiffI:'!'bSMEftN;Tpghlxo?Ldcrm,quva sine.取器效论证反结件以量说明讨用公高认带的起最准都你单和愿计兰它由，亲台本及集游术行具马扩充要读好您才蜂无击步方并急标是多哪该度去朋被小整任译形始成中之应种么识社织调放弃己基理次倒人预况有灵从经个康能建、手现同作慧队

划时但AA轮更力战付者关互AA文型强导工密们各关已（意络共关采利一体张关开关通确信关测关提关关模到立关语关关备这养入关压关第味程关）团群如另言动情；来规培关果没枪关过治自网。就参主地系德着解构做旦政重目感出切大协受令关想翻友关内诸比为把在相先可看机领
```

I don't think this bug comes from Typst creating a malformed PDF, but if you find that it does I'll be happy to create an issue on their side.

Wrong BOM detection for strings starting with \x00\xfe\x00\xff


The following code

```python
from typing import TYPE_CHECKING

import attrs

if TYPE_CHECKING:
    from typing import ClassVar

@attrs.define
class T:
    t: ClassVar[str]

T()
```

results in:
```python
Traceback (most recent call last):
  File "/tmp/test.py", line 12, in <module>
    T()
    ~^^
TypeError: T.__init__() missing 1 required positional argument: 't'
```

Since the `if TYPE_CHECKING` block doesn't run, `ClassVar` isn't defined and attrs can't evaluate the ForwardRef or doesn't recognize `ClassVar`:

```python
>>> attrs.fields_dict(T)["t"]
Attribute(name='t', default=NOTHING, validator=None, repr=True, eq=True, eq_key=None, order=True, order_key=None, hash=None, init=True, metadata=mappingproxy({}), type=ForwardRef('ClassVar[str]', is_class=True, owner=<class '__main__.T'>), converter=None, kw_only=False, inherited=False, on_setattr=None, alias='t')
```

Before Python 3.14, `T`'s definition would only run if you used a string annotation or `from __future__ import annotations` (which if used with 3.14, the above code runs fine), but with the new annotations behavior the class definition runs fine and this error appears. This is actually issue for dataclasses too, as I get the same error with them.

I'm not sure if this is fixable, but decided to report it, because it catches you by surprise

attrs doesn't recognize ClassVar if not imported in Python 3.14

python -m pytest -q --hypothesis-seed=0 tests

uv sync --frozen --no-default-groups --group tests --no-install-project


### Things to check first

- [X] I have searched the existing issues and didn't find my bug already reported there

- [X] I have checked that my bug is still present in the latest release

### Typeguard version

4.4.1

### Python version

3.13.0

### What happened?

I think https://github.com/agronholm/typeguard/issues/498 is not fully fixed yet.

### How can we reproduce the bug?

`bug.py`
```python
from typeguard import install_import_hook

install_import_hook()

from code import Class, function_of_instance, function_of_type

# This works:
function_of_instance(Class())

# This does not:
function_of_type(Class)
```

`code.py`
```python
from typing import Protocol

class Proto(Protocol):
    foo: str

class Class(Proto):
    def __init__(self):
        self.foo = "bar"

def function_of_instance(instance: Proto): ...

def function_of_type(type_: type[Proto]): ...
```

Class is not compatible with protocol because it has no attribute named ...

SETUPTOOLS_SCM_PRETEND_VERSION_FOR_TYPEGUARD=0.0.0 uv sync --no-default-groups --group test --no-install-project


This is based on @PrieJos's helpful analysis in https://github.com/hynek/structlog/issues/693#issuecomment-2629117069

In async log methods, callsite collection happens in the async logger thread which makes its thread-related information worthless:

```python
# /// script
# dependencies = [
#   "structlog",
# ]
# ///

import asyncio
import logging
import sys

import structlog

sl = structlog.get_logger()
logger = logging.getLogger()

logging.basicConfig(
    stream=sys.stdout,
    format=(
        "%(process)d %(processName)s %(module)s"
        " %(funcName)s:%(lineno)d %(threadName)s %(taskName)s"
        " %(message)s"
    ),
    datefmt=r"%Y-%m-%dT%H:%M:%S",
    level=logging.INFO,
    encoding="utf-8",
)

structlog.configure(
    processors=[
        structlog.processors.CallsiteParameterAdder(
            [
                structlog.processors.CallsiteParameter.PROCESS,
                structlog.processors.CallsiteParameter.PROCESS_NAME,
                structlog.processors.CallsiteParameter.MODULE,
                structlog.processors.CallsiteParameter.FILENAME,
                structlog.processors.CallsiteParameter.FUNC_NAME,
                structlog.processors.CallsiteParameter.LINENO,
                structlog.processors.CallsiteParameter.THREAD_NAME,
            ]
        ),
        structlog.processors.LogfmtRenderer(),
    ],
)

async def afunc():
    await sl.ainfo("async")
    logger.info("stdlib async")

def func():
    sl.info("sync")
    logger.info("stdlib sync")

asyncio.run(afunc())
func()
```

Notably, thread name is wrong and so would be a task name as shown in #698:

```
event=async process=55347 process_name=n/a module=t filename=t.py func_name=afunc lineno=47 thread_name=asyncio_0
55347 MainProcess t afunc:48 MainThread Task-1 stdlib async
event=sync process=55347 process_name=n/a module=t filename=t.py func_name=func lineno=51 thread_name=MainThread
55347 MainProcess t func:52 MainThread None stdlib sync
```

Not sure how to deal with this most elegantly – I feel like we'll have to pass thread/task objects into the event_dict or something?

I _think_ the `process_name` is in fact correct, since `logging` just [sets it unconditionally](https://github.com/python/cpython/blob/72e5b25efb580fb1f0fdfade516be90d90822164/Lib/logging/__init__.py#L359-L371) and we get `n/a` in sync code too. Happy to be corrected, though.

Thread name CallsiteParameterAdder parameter doesn't work in async methods

python -m pytest -q -p no:randomly tests

SETUPTOOLS_SCM_PRETEND_VERSION_FOR_STRUCTLOG=0.0.0 uv sync --no-default-groups --group tests --no-install-project


When I attempt to highlight the following code snippet using `jsx` as the lexer in Sphinx and MyST, Sphinx returns a warning:

`WARNING: Lexing literal_block (JSX code omitted) as "jsx" resulted in an error at token: "'". Retrying in relaxed mode.`

````
```jsx
import React from 'react';

const View = props => {
  return
I'm the Block view component!
;
};

export default View;
```
````

[Try it on the Pygments demo](https://pygments.org/demo/?lexer=jsx&style=bw&formatter=html&code=import+React+from+%27react%27%3B%0A%0Aconst+View+%3D+props+%3D%3E+%7B%0A++return+%3Cdiv%3EI%27m+the+Block+view+component%21%3C%2Fdiv%3E%3B%0A%7D%3B%0A%0Aexport+default+View%3B%0A).

FWIW, if I try `js` as the lexer, it also does not lex.

See:
- https://github.com/plone/volto/issues/3038
- https://github.com/plone/training/issues/347
- https://github.com/fcurella/jsx-lexer/issues/15

WARNING: Lexing literal_block ... as "jsx" resulted in an error at token: "'". Retrying in relaxed mode.

python -m pytest -q -W error --cache-clear --randomly-seed=0 -o cache_dir=/tmp/pytest-cache tests

uv pip install --python /opt/venv/bin/python --only-binary=:all: 'hatchling==1.27.0' 'editables==0.5' && uv pip install --python /opt/venv/bin/python --no-deps --only-binary=:all: 'pytest==8.4.2' 'pytest-randomly==4.0.1' 'iniconfig==2.1.0' && uv pip install --python /opt/venv/bin/python --no-deps 'wcag-contrast-ratio==0.9' && uv pip freeze --python /opt/venv/bin/python > /opt/patcheval-requirements.txt

mkdir -p "$HOME" "$XDG_CACHE_HOME" "$UV_CACHE_DIR" && uv pip install --offline --python /opt/venv/bin/python --no-deps --no-build-isolation --editable . && uv pip check --python /opt/venv/bin/python


The `::` in this snippet is highlighted as an error but it shouldn't be, it's array slice notation, just like in Python

```jsonnet
{
  local numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  even_numbers: numbers[1::2],
}
```

https://pygments.org/demo/?lexer=jsonnet&style=bw&formatter=html&code=local+obj2+%3D+%7B%0A++local+numbers+%3D+%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%2C+9%2C+10%5D%2C%0A++even_numbers%3A+numbers%5B1%3A%3A2%5D%2C%0A%7D%3B%0A

You can try it on https://jsonnet.org/learning/tutorial.html


Hello,
Sorry to be opening another issue so early after the last one, but I found something else:

```python
v = tomlkit.loads("""[x]\na.b = {}""")
v["x"]["c"] = 3
print(tomlkit.dumps(v))
```

output:
```toml
[x]
a.b = {}c = 3
```

As you can see, there should be a new line before `c = 3`

Note that this doesn't happens with either:
- `"""[x]\na.b = {}\n"""`
- `"""[x]\na = {}"""`

python -m pytest -q -o cache_dir=/tmp/pytest-cache tests --ignore=tests/test_toml_tests.py

python -m venv /opt/venv && uv pip install --python /opt/venv/bin/python --no-deps --only-binary=:all: pytest==7.4.4 iniconfig==2.0.0 packaging==24.0 pluggy==1.2.0


```python
#!/usr/bin/env python3

import tomlkit

doc = tomlkit.parse("a.b = 1\nc.d = 2\n")
aot = tomlkit.aot()
t = tomlkit.table()
t["x"] = 9
aot.append(t)
doc["a"] = aot
print(tomlkit.dumps(doc))
```
result
```
[[a]]
x = 9
c.d = 2
```
in which `c.d` has wrongly been captured by the array of tables.

Similar in flavour to other recent bug reports and fixes, I expect the fix will be nearby too.