internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: pytorch/vision

Issue:
to_grayscale gives non-actionable deprecation warning
_Originally reported in the [user forum](https://discuss.pytorch.org/t/cannot-find-convert-color-space/182591) by `@function2`._

> When I use to_grayscale, there’s a deprecation warning:
> ```
> UserWarning: The function `to_grayscale(...)` is deprecated in will be removed in a future release. Instead, please use `convert_color_space(..., color_space=datapoints.ColorSpace.GRAY)`.
> ```
> However, I can’t find this function in the current code base

---

Note that this only applies to `torchvision.transforms.v2.function`

https://github.com/pytorch/vision/blob/52eb5039bed1a23eee14014ff4cd6fd9cc9b2b08/torchvision/transforms/v2/functional/_deprecated.py#L12-L22

since the v1 version, i.e. `torchvision.transforms.functional` does not emit the warning

https://github.com/pytorch/vision/blob/52eb5039bed1a23eee14014ff4cd6fd9cc9b2b08/torchvision/transforms/functional.py#L1249-L1253

Fixing the v2 warning was forgotten in #7120.


cc @vfdev-5


Discussion:

Resolving patch:
diff --git a/torchvision/transforms/v2/functional/_deprecated.py b/torchvision/transforms/v2/functional/_deprecated.py
--- a/torchvision/transforms/v2/functional/_deprecated.py
+++ b/torchvision/transforms/v2/functional/_deprecated.py
@@ -10,15 +10,10 @@
 
 @torch.jit.unused
 def to_grayscale(inpt: PIL.Image.Image, num_output_channels: int = 1) -> PIL.Image.Image:
-    call = ", num_output_channels=3" if num_output_channels == 3 else ""
-    replacement = "convert_color_space(..., color_space=datapoints.ColorSpace.GRAY)"
-    if num_output_channels == 3:
-        replacement = f"convert_color_space({replacement}, color_space=datapoints.ColorSpace.RGB)"
     warnings.warn(
-        f"The function `to_grayscale(...{call})` is deprecated in will be removed in a future release. "
-        f"Instead, please use `{replacement}`.",
+        "The function `to_grayscale` is deprecated in will be removed in a future release. "
+        "Instead, please use `rgb_to_grayscale`.",
     )
-
     return _F.to_grayscale(inpt, num_output_channels=num_output_channels)
 
 


Test patch:
Repository: pytorch/vision

Issue:
transforms v2 rotate can create different sizes between tensors and PIL with expand=True
```python
import torch
from torchvision.transforms.v2 import functional as F

input_tensor = torch.rand(3, 17, 11)
input_pil = F.to_pil_image(input_tensor)

kwargs = dict(angle=-10.9, center=(1.2, 4.9), expand=True)

output_tensor = F.rotate(input_tensor, **kwargs)
output_pil = F.rotate(input_pil, **kwargs)

shape_tensor = F.get_image_size(output_tensor)
shape_pil = F.get_image_size(output_pil)

assert shape_tensor == shape_pil, f"{shape_tensor} != {shape_pil}"
```

```
AssertionError: [15, 20] != [15, 19]
```

Replacing the import with `from torchvision.transforms import functional as F`, i.e. using transforms v1, does not have this problem.


Discussion:
We had some subtle issues here before, which supposedly should have been fixed by #7271.
PIL kernel is the culprit:

```python
import torch
from torchvision.transforms.v2 import functional as F

input_tensor = torch.rand(3, 17, 11)
input_pil = F.to_pil_image(input_tensor)

kwargs = dict(angle=-10.9, expand=True)

output_w_center = F.rotate(input_tensor, **kwargs, center=(1.2, 4.9))
output_wo_center = F.rotate(input_pil, **kwargs, center=None)

shape_w_center = F.get_image_size(output_w_center)
shape_wo_center = F.get_image_size(output_wo_center)

assert shape_w_center == shape_wo_center, f"{shape_w_center} != {shape_wo_center}"
```

```
AssertionError: [15, 20] != [15, 19]
```

Meaning, #7271 did its job, but we need to expand it to the PIL kernel as well.

The issue is that `center` theoretically should have no effect on the output size if `expand=True` is given. Practically, rounding effects take place which lead the off-by-one errors. The difference between v1 and v2 is that we not only warn users about setting both parameters

https://github.com/pytorch/vision/blob/71968bc4afb8892284844a7c4cbd772696f42a88/torchvision/transforms/v2/functional/_geometry.py#L922-L923

we also explicitly unset `center` in this case

https://github.com/pytorch/vision/blob/71968bc4afb8892284844a7c4cbd772696f42a88/torchvision/transforms/v2/functional/_geometry.py#L924

Resolving patch:
diff --git a/torchvision/transforms/v2/functional/_geometry.py b/torchvision/transforms/v2/functional/_geometry.py
--- a/torchvision/transforms/v2/functional/_geometry.py
+++ b/torchvision/transforms/v2/functional/_geometry.py
@@ -921,7 +921,6 @@ def rotate_image_pil(
 
     if center is not None and expand:
         warnings.warn("The provided center argument has no effect on the result if expand is True")
-        center = None
 
     return _FP.rotate(
         image, angle, interpolation=pil_modes_mapping[interpolation], expand=expand, fill=fill, center=center
@@ -938,7 +937,6 @@ def rotate_bounding_box(
 ) -> Tuple[torch.Tensor, Tuple[int, int]]:
     if center is not None and expand:
         warnings.warn("The provided center argument has no effect on the result if expand is True")
-        center = None
 
     return _affine_bounding_box_with_expand(
         bounding_box,


Test patch:
Repository: pytorch/vision

Issue:
yet another ssdlite link fix
<!-- Before submitting a PR, please make sure to check our contributing guidelines regarding code formatting, tests, and documentation: https://github.com/pytorch/vision/blob/main/CONTRIBUTING.md -->



Discussion:

Resolving patch:
diff --git a/torchvision/models/detection/ssdlite.py b/torchvision/models/detection/ssdlite.py
--- a/torchvision/models/detection/ssdlite.py
+++ b/torchvision/models/detection/ssdlite.py
@@ -255,7 +255,7 @@ def ssdlite320_mobilenet_v3_large(
         norm_layer (callable, optional): Module specifying the normalization layer to use.
         **kwargs: parameters passed to the ``torchvision.models.detection.ssd.SSD``
             base class. Please refer to the `source code
-            <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/ssd.py>`_
+            <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/ssdlite.py>`_
             for more details about this class.
 
     .. autoclass:: torchvision.models.detection.SSDLite320_MobileNet_V3_Large_Weights


Test patch:
Repository: napalm-automation/napalm

Issue:
Unknown device model
Using the IOS driver on 3 different switches always returns 'model': u'Unknown'

> > > from netmiko import ConnectHandler
> > > from napalm import get_network_driver
> > > get_network_driver('ios')
> > > <class napalm.ios.IOSDriver at 0x7fc3a1763a78>
> > > driver = get_network_driver('ios')
> > > device = driver('IP', 'xionox', 'pass')
> > > device.open()
> > > device.get_facts()
> 
> {'os_version': u'IOS-XE Software, Catalyst L3 Switch Software (CAT3K_CAA-UNIVERSALK9-M), Version 03.03.05SE RELEASE SOFTWARE (fc1)', 'uptime': 6721260, 'interface_list': [u'Vlan1', u'Vlan206', u'GigabitEthernet0/0', u'GigabitEthernet1/0/1', u'GigabitEthernet1/0/2', u'GigabitEthernet1/0/3', u'GigabitEthernet1/0/4', u'GigabitEthernet1/0/5', u'GigabitEthernet1/0/6', u'GigabitEthernet1/0/7', u'GigabitEthernet1/0/8', u'GigabitEthernet1/0/9', u'GigabitEthernet1/0/10', u'GigabitEthernet1/0/11', u'GigabitEthernet1/0/12', u'GigabitEthernet1/0/13', u'GigabitEthernet1/0/14', u'GigabitEthernet1/0/15',......], 'vendor': u'Cisco', 'serial_number': u'ABCD', 'model': u'Unknown', 'hostname': u'switch1.df101-1', 'fqdn': u'switch1.df101-1.xxxxxxx'}

Show version returns:
cisco WS-C3850-48T (MIPS) processor with 4194304K bytes of physical memory.
And more down the page (as stacked switches)
Model Number                       : WS-C3850-48T

Same with:

> {'os_version': u'IOS-XE Software, Catalyst 4500 L3 Switch Software (cat4500e-UNIVERSALK9-M), Version 03.04.05.SG RELEASE SOFTWARE (fc1)',[...]

cisco WS-C4500X-32 (MPC8572) processor (revision 9) with 4194304K/20480K bytes of memory.

And

> {'os_version': u'CBS31X0 Software (CBS31X0-UNIVERSALK9-M), Version 12.2(58)SE1, RELEASE SOFTWARE (fc1)',[...]

show version:
cisco WS-CBS3120X-S (PowerPC405) processor (revision E0) with 262144K bytes of memory.
and more down the page (stacked as well):
Model number                    : WS-CBS3120X-S

Thanks



Discussion:
I can take a look at this issue. The big difference offhand is the switches start with lowercase 'cisco'.


Resolving patch:
diff --git a/napalm/ios.py b/napalm/ios.py
--- a/napalm/ios.py
+++ b/napalm/ios.py
@@ -379,8 +379,6 @@ def parse_uptime(uptime_str):
 
     def get_facts(self):
         """This function returns a set of facts from the devices."""
-        # creating the parsing regex.
-        model_regex = r".*Cisco\s(?P<model>\d+).*"
 
         # default values.
         vendor = u'Cisco'
@@ -421,9 +419,8 @@ def get_facts(self):
 
         # model filter
         try:
-            match_model = re.match(model_regex, show_ver, re.DOTALL)
-            group_model = match_model.groupdict()
-            model = group_model["model"]
+            match_model = re.search(r"Cisco (.+?) .+bytes of", show_ver, re.IGNORECASE)
+            model = match_model.group(1)
         except AttributeError:
             model = u'Unknown'
 


Test patch:
Repository: napalm-automation/napalm

Issue:
get_facts on iosxr fails
```
    def get_facts(self):
    
        facts = {
            'vendor': u'Cisco',
            'os_version': u'',
            'hostname': u'',
            'uptime': -1,
            'serial_number': u'',
            'fqdn': u'',
            'model': u'',
            'interface_list': []
        }
    
        facts_rpc_request = '<Get><Operational><SystemTime/><PlatformInventory/>\
            </Operational></Get>'
    
        facts_rpc_reply = ETREE.fromstring(self.device.make_rpc_call(facts_rpc_request))
        system_time_xpath = './/SystemTime/Uptime'
        platform_attr_xpath = './/RackTable/Rack/Attributes/BasicInfo'
        system_time_tree = facts_rpc_reply.xpath(system_time_xpath)[0]
>       platform_attr_tree = facts_rpc_reply.xpath(platform_attr_xpath)[0]
E       IndexError: list index out of range

../napalm/napalm/iosxr/iosxr.py:186: IndexError
```

Using the develop branch as of today.

Running IOS-XRv.

```
Sat Nov 18 00:40:17.546 UTC
Cisco IOS XR Software, Version 5.3.1[Default]
Copyright (c) 2015 by Cisco Systems, Inc.
ROM: GRUB, Version 1.99(0), DEV RELEASE
pynet-iosxr1 uptime is 39 weeks, 56 minutes
System image file is "bootflash:disk0/xrvr-os-mbi-5.3.1/mbixrvr-rp.vm"
cisco IOS XRv Series (Intel 686 F6M13S3) processor with 4193904K bytes of memory.
Intel 686 F6M13S3 processor at 2673MHz, Revision 2.174
IOS XRv Chassis
3 GigabitEthernet
1 Management Ethernet
```


Discussion:

Resolving patch:
diff --git a/napalm/iosxr/iosxr.py b/napalm/iosxr/iosxr.py
--- a/napalm/iosxr/iosxr.py
+++ b/napalm/iosxr/iosxr.py
@@ -183,7 +183,10 @@ def get_facts(self):
         system_time_xpath = './/SystemTime/Uptime'
         platform_attr_xpath = './/RackTable/Rack/Attributes/BasicInfo'
         system_time_tree = facts_rpc_reply.xpath(system_time_xpath)[0]
-        platform_attr_tree = facts_rpc_reply.xpath(platform_attr_xpath)[0]
+        try:
+            platform_attr_tree = facts_rpc_reply.xpath(platform_attr_xpath)[0]
+        except IndexError:
+            platform_attr_tree = facts_rpc_reply.xpath(platform_attr_xpath)
 
         hostname = napalm.base.helpers.convert(
             text_type, napalm.base.helpers.find_txt(system_time_tree, 'Hostname'))


Test patch:
Repository: napalm-automation/napalm

Issue:
junos ConnectionException
`  File "/Users/paperbacon/Documents/PycharmProjects/napalm-test/venv/lib/python3.6/site-packages/napalm/junos/junos.py", line 109, in open
    raise ConnectionException(cte.message)
AttributeError: 'ConnectTimeoutError' object has no attribute 'message'`

I think line 109 of napalm/napalm/junos/junos.py should be:
`raise ConnectionException(cte.msg)`
as per http://junos-pyez.readthedocs.io/en/2.1.4/jnpr.junos.html#jnpr.junos.exception.ConnectTimeoutError ?


Discussion:

Resolving patch:
diff --git a/napalm/junos/junos.py b/napalm/junos/junos.py
--- a/napalm/junos/junos.py
+++ b/napalm/junos/junos.py
@@ -102,11 +102,11 @@ def __init__(self, hostname, username, password, timeout=60, optional_args=None)
         self.profile = ["junos"]
 
     def open(self):
-        """Open the connection wit the device."""
+        """Open the connection with the device."""
         try:
             self.device.open()
         except ConnectTimeoutError as cte:
-            raise ConnectionException(cte.message)
+            raise ConnectionException(cte.msg)
         self.device.timeout = self.timeout
         self.device._conn._session.transport.set_keepalive(self.keepalive)
         if hasattr(self.device, "cu"):


Test patch:
Repository: napalm-automation/napalm

Issue:
IOS : Uncaught error response during replace
Caught this when trying to commit replace an altered post-grab get_config 'startup' which adds an unsupported line on line 1 

```
 head config.txt 
  
Using 1316 out of 196600 bytes
!
! Last configuration change at 15:49:05 BUC Wed Feb 14 2018 by root
version 15.1
service timestamps debug datetime msec
service timestamps log datetime msec
service password-encryption
!
hostname NAPALM-TARGET
!
```


Cisco 1841 Version 12.4(13r)t issues the following when doing 

> replace flash:candidate_config.txt force revert trigger error

The response is 

> %The input file is not a valid config file.

Napalm goes forward with the code, even if changes are not applied on the router. I may not be that good at Python, but i assume this code bit does not have this answer in order to raise exception

```
            if self.auto_rollback_on_error:
                cmd = 'configure replace {} force revert trigger error'.format(cfg_file)
            else:
                cmd = 'configure replace {} force'.format(cfg_file)
            output = self._commit_hostname_handler⌘
            if ('original configuration has been successfully restored' in output) or \
               ('error' in output.lower()) or \
               ('failed' in output.lower()):
                msg = "Candidate config could not be applied\n{}".format(output)
                raise ReplaceConfigException(msg)
```

Could we add this text to the code? 




Discussion:

Resolving patch:
diff --git a/napalm/ios/ios.py b/napalm/ios/ios.py
--- a/napalm/ios/ios.py
+++ b/napalm/ios/ios.py
@@ -442,6 +442,7 @@ def commit_config(self):
             output = self._commit_hostname_handler(cmd)
             if ('original configuration has been successfully restored' in output) or \
                ('error' in output.lower()) or \
+               ('not a valid config file' in output.lower()) or \
                ('failed' in output.lower()):
                 msg = "Candidate config could not be applied\n{}".format(output)
                 raise ReplaceConfigException(msg)


Test patch:
Repository: napalm-automation/napalm

Issue:
`base.clitools.cl_napalm:main` entrypoint still uses PIP internals
https://github.com/napalm-automation/napalm/blob/f45fc4f8e9108cacd76ce8f5cd9182df45129480/napalm/base/clitools/cl_napalm.py#L146

Should switch to `pkg_resources.find_distributions()` or similar.


Discussion:

Resolving patch:
diff --git a/napalm/base/clitools/cl_napalm.py b/napalm/base/clitools/cl_napalm.py
--- a/napalm/base/clitools/cl_napalm.py
+++ b/napalm/base/clitools/cl_napalm.py
@@ -7,11 +7,11 @@
 from napalm.base.clitools import helpers
 
 # stdlib
-import pip
 import json
 import logging
 import argparse
 import getpass
+import pkg_resources
 from functools import wraps
 
 
@@ -143,9 +143,8 @@ def build_help():
 
 def check_installed_packages():
     logger.debug("Gathering napalm packages")
-    installed_packages = pip.get_installed_distributions()
     napalm_packages = sorted(["{}=={}".format(i.key, i.version)
-                              for i in installed_packages if i.key.startswith("napalm")])
+                              for i in pkg_resources.working_set if i.key.startswith("napalm")])
     for n in napalm_packages:
         logger.debug(n)
 


Test patch:
Repository: napalm-automation/napalm

Issue:
Implement get_ntp_peers on Cisco IOS



Discussion:

Resolving patch:
diff --git a/napalm/ios/ios.py b/napalm/ios/ios.py
--- a/napalm/ios/ios.py
+++ b/napalm/ios/ios.py
@@ -1856,6 +1856,12 @@ def cli(self, commands):
 
         return cli_output
 
+    def get_ntp_peers(self):
+        """Implementation of get_ntp_peers for IOS."""
+        ntp_stats = self.get_ntp_stats()
+
+        return {ntp_peer.get('remote'): {} for ntp_peer in ntp_stats if ntp_peer.get('remote')}
+
     def get_ntp_servers(self):
         """Implementation of get_ntp_servers for IOS.
 


Test patch:
diff --git a/test/ios/mocked_data/test_get_ntp_peers/normal/expected_result.json b/test/ios/mocked_data/test_get_ntp_peers/normal/expected_result.json
new file mode 100644
--- /dev/null
+++ b/test/ios/mocked_data/test_get_ntp_peers/normal/expected_result.json
@@ -0,0 +1,3 @@
+{
+    "172.29.50.34" : {}
+}
diff --git a/test/ios/mocked_data/test_get_ntp_peers/normal/show_ntp_associations.txt b/test/ios/mocked_data/test_get_ntp_peers/normal/show_ntp_associations.txt
new file mode 100644
--- /dev/null
+++ b/test/ios/mocked_data/test_get_ntp_peers/normal/show_ntp_associations.txt
@@ -0,0 +1,4 @@
+
+  address         ref clock       st   when   poll reach  delay  offset   disp
+*~172.29.50.34    83.168.200.199   3     54   1024   377  1.186   0.122 18.659
+ * sys.peer, # selected, + candidate, - outlyer, x falseticker, ~ configured
Repository: napalm-automation/napalm

Issue:
napalm validate is modifying the source dictionary with pop operations
```python
def napalm_validate(napalm, file=None, source=None):
    complies = napalm.compliance_report(validation_file=file, validation_source=source)[
        "complies"
    ]
    return complies
```

and i'm using it like this:

```python
def whatever(task):
    napalm = task.host.get_connection("napalm")

    ping_gw = [
        {
            "ping": {
                "_name": "ping_gw",
                "_kwargs": {"destination": "10.0.0.1", "source": "Vlan1000"},
                "success": {"packet_loss": 0},
                "_mode": "strict",
            }
        }
    ]

    print("1", task.host, ping_gw)
    ping = napalm_validate(napalm, source=ping_gw)

    print("2", task.host, ping_gw)
    ping = napalm_validate(napalm, source=ping_gw)
```

which results in
```
1 host02 [{'ping': {'_name': 'ping_gw', '_kwargs': 
     {'destination': '10.0.0.1', 'source': 'Vlan1000'}, 
     'success': {'packet_loss': 0}, '_mode': 'strict'}}]
2 host02 [{'ping': {'success': {'packet_loss': 0}}}]
```

is it because of `kwargs = expected_results.pop('_kwargs', {})` in `compliance_report`?


Discussion:

Resolving patch:
diff --git a/napalm/base/validate.py b/napalm/base/validate.py
--- a/napalm/base/validate.py
+++ b/napalm/base/validate.py
@@ -180,6 +180,9 @@ def compliance_report(cls, validation_file=None, validation_source=None):
     if validation_file:
         validation_source = _get_validation_file(validation_file)
 
+    # Otherwise we are going to modify a "live" object
+    validation_source = copy.deepcopy(validation_source)
+
     for validation_check in validation_source:
         for getter, expected_results in validation_check.items():
             if getter == "get_config":


Test patch:
diff --git a/test/base/validate/test_validate.py b/test/base/validate/test_validate.py
--- a/test/base/validate/test_validate.py
+++ b/test/base/validate/test_validate.py
@@ -143,6 +143,17 @@ def test_strict_pass_skip_from_source(self):
 
         assert expected_report == actual_report, yaml.safe_dump(actual_report)
 
+    def test_immutable_validation_source(self):
+        """Test validation_source is not modified."""
+        mocked_data = os.path.join(BASEPATH, "mocked_data", "strict_pass_skip")
+
+        device = FakeDriver(mocked_data)
+        source = _read_yaml(os.path.join(mocked_data, "validate.yml"))
+        witness = _read_yaml(os.path.join(mocked_data, "validate.yml"))
+        device.compliance_report(validation_source=source)
+
+        assert source == witness, yaml.safe_dump(source)
+
 
 class FakeDriver(NetworkDriver):
     """This is a fake NetworkDriver."""
Repository: napalm-automation/napalm

Issue:
IOS get_bgp_neighbors() fails on None neighbor_entry
For IOS getter get_bgp_neighbors(), if a neighbor shows up with a supported AFI, but no info under that AFI, a ValueError is raised, which causes a TypeError since the neighbor_entry is None.  Skipping the neighbor/afi seems like an acceptable solution.

Example CLI Output:
```
router1#show bgp all neighbors 10.0.0.1
For address family: IPv4 Unicast

For address family: IPv6 Unicast

For address family: IPv4 MDT
BGP neighbor is 10.0.0.1,  remote AS 65001, internal link
 Description: router2
 Member of peer-group VRR for session parameters
```


Tries to raise a ValueError on None:
```
>>> dev.get_bgp_neighbors() 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/ENV/lib/python3.6/site-packages/napalm/ios/ios.py", line 1284, in get_bgp_neighbors
    (remote_addr, afi))
TypeError: ValueError does not take keyword arguments
```

Check for None before doing the isinstance check.?
```
1282+    # check for proper session data for the afi
1283+    if neighbor_entry is None:
1284+        continue
1285+    elif not isinstance(neighbor_entry, dict):
1286         raise ValueError(msg="Couldn't find neighbor data for %s in afi %s" %
1287                              (remote_addr, afi))
```


Discussion:

Resolving patch:
diff --git a/napalm/ios/ios.py b/napalm/ios/ios.py
--- a/napalm/ios/ios.py
+++ b/napalm/ios/ios.py
@@ -1279,7 +1279,10 @@ def get_bgp_neighbors(self):
                         napalm.base.helpers.ip(neighbor['remote_addr']) == remote_addr):
                     neighbor_entry = neighbor
                     break
-            if not isinstance(neighbor_entry, dict):
+            # check for proper session data for the afi
+            if neighbor_entry is None:
+                continue
+            elif not isinstance(neighbor_entry, dict):
                 raise ValueError(msg="Couldn't find neighbor data for %s in afi %s" %
                                      (remote_addr, afi))
 


Test patch:
Repository: napalm-automation/napalm

Issue:
Timeout parameter for IOS driver not used
The timeout parameter for IOS driver is not used, causing unreachable devices to time out after ~100 seconds instead of whatever was specified.


Discussion:

Resolving patch:
diff --git a/napalm/base/base.py b/napalm/base/base.py
--- a/napalm/base/base.py
+++ b/napalm/base/base.py
@@ -79,6 +79,7 @@ def _netmiko_open(self, device_type, netmiko_optional_args=None):
                                                   host=self.hostname,
                                                   username=self.username,
                                                   password=self.password,
+                                                  timeout=self.timeout,
                                                   **netmiko_optional_args)
         except NetMikoTimeoutException:
             raise ConnectionException('Cannot connect to {}'.format(self.hostname))


Test patch: