internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: koxudaxi/datamodel-code-generator

Issue:
Bug with oneOf and const
**Describe the bug**
Bug reproduce with datamodel-code-generator 0.25+ 

**To Reproduce**

Example schema:
```json
{
    "$schema": "https://json-schema.org/draft/2019-09/schema",
    "$id": "transcoder-meta.schema.json",
    "title": "Title",
    "description": "Description",
    "type": "object",
    "oneOf": [
        {
            "type": "object",
            "title" : "videoTranscodingMeta",
            "additionalProperties": false,
            "properties": {
                "streamType": {
                    "const": "video"
                }
            }
        },
        {
            "type": "object",
            "title" : "audioTranscodingMeta",
            "additionalProperties": false,
            "properties": {
                "streamType": {
                    "const": "audio"
                }
            }
        }
    ]
}
```

Used commandline:
```
$ datamodel-codegen --input transcoding_meta.json --input-file-type jsonschema --output-model-type dataclasses.dataclass
```
**Actual behavior**
```python
# generated by datamodel-codegen:
#   filename:  transcoding_meta.json
#   timestamp: 2023-12-23T19:26:19+00:00

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Optional


@dataclass
class Title1:
    streamType: Optional[Any] = None


Title = Title1
```

**Expected behavior**
```python
# generated by datamodel-codegen:
#   filename:  transcoding_meta.json
#   timestamp: 2023-12-23T19:22:04+00:00

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Union


@dataclass
class TitleItem:
    streamType: str = 'video'


@dataclass
class TitleItem1:
    streamType: str = 'audio'


Title = Union[TitleItem, TitleItem1]
```

**Version:**
 - OS: Linux
 - Python version: 3.11.7
 - datamodel-code-generator version: 0.25.2 and master



Discussion:
I have the same issue. 

Resolving patch:
diff --git a/datamodel_code_generator/parser/jsonschema.py b/datamodel_code_generator/parser/jsonschema.py
--- a/datamodel_code_generator/parser/jsonschema.py
+++ b/datamodel_code_generator/parser/jsonschema.py
@@ -270,6 +270,8 @@ class Config:
         def __init__(self, **data: Any) -> None:
             super().__init__(**data)
             self.extras = {k: v for k, v in data.items() if k not in EXCLUDE_FIELD_KEYS}
+            if 'const' in data.get(self.__extra_key__, {}):
+                self.extras['const'] = data[self.__extra_key__]['const']
 
     @cached_property
     def is_object(self) -> bool:


Test patch:
Repository: koxudaxi/datamodel-code-generator

Issue:
Importing code generator changes behavior of pyyaml
When importing ``datamodel_code_generator``, the behaviour of ``pyyaml`` is changed after the import, datetime objects suddenly are deserialized from yaml as `str` whereas before they were deserialized as `datetime` objects.

## Steps to reproduce:
### create clean venv
```bash
python3 -m venv blub
blub/bin/pip install datamodel-code-generator pyyaml
```

### Run this reproducer with the interpreter from the venv
```python
import yaml
import tempfile
import datetime

tmp=tempfile.NamedTemporaryFile(mode='w')

def write_read():
    tmp=tempfile.NamedTemporaryFile(mode='w')
    yaml.safe_dump({"datetime": datetime.datetime.now()}, tmp)
    dumped_reloaded = yaml.safe_load(open(tmp.name,"r"))
    print(dumped_reloaded)

print("before importing datamodel-code-generator:")
write_read()

import datamodel_code_generator
print("\nafter importing datamodel-code-generator:")
write_read()
```

**Actual output:** (time string + object may change depending on run time)
```
before importing datamodel-code-generator:
{'datetime': datetime.datetime(2024, 1, 30, 9, 51, 19, 612368)}

after importing datamodel-code-generator:
{'datetime': '2024-01-30 09:51:20.019991'}
```

**Expected output:**  (time string + object may change depending on run time):
```
before importing datamodel-code-generator:
{'datetime': datetime.datetime(2024, 1, 30, 9, 51, 19, 612368)}

after importing datamodel-code-generator:
{'datetime': datetime.datetime(2024, 1, 30, 9, 51, 20, 019991)}
```

The reason seems to be that the SafeLoader of ``yaml`` is modified globally by ``datamodel-code-generator``
https://github.com/koxudaxi/datamodel-code-generator/blob/acc6bf604b13626f22fc123d72ae08ff0a114155/datamodel_code_generator/util.py#L72




Discussion:

Resolving patch:
diff --git a/datamodel_code_generator/util.py b/datamodel_code_generator/util.py
--- a/datamodel_code_generator/util.py
+++ b/datamodel_code_generator/util.py
@@ -1,5 +1,6 @@
 from __future__ import annotations
 
+import copy
 from pathlib import Path
 from typing import TYPE_CHECKING, Any, Callable, Dict, TypeVar
 
@@ -69,9 +70,13 @@ def load_toml(path: Path) -> Dict[str, Any]:
             return toml.load(path)
 
 
-SafeLoader.yaml_constructors[
-    'tag:yaml.org,2002:timestamp'
-] = SafeLoader.yaml_constructors['tag:yaml.org,2002:str']
+SafeLoaderTemp = copy.deepcopy(SafeLoader)
+SafeLoaderTemp.yaml_constructors = copy.deepcopy(SafeLoader.yaml_constructors)
+SafeLoaderTemp.add_constructor(
+    'tag:yaml.org,2002:timestamp',
+    SafeLoaderTemp.yaml_constructors['tag:yaml.org,2002:str'],
+)
+SafeLoader = SafeLoaderTemp
 
 Model = TypeVar('Model', bound=_BaseModel)
 


Test patch:
Repository: ansible/ansible-modules-core

Issue:
Pull SSL certificate IDs from existing ELBs
Fixes ansible/ansible#9073 and fixes #22
The root cause of that issue is that boto's "get_complex_tuple()" doesn't include the ssl_certificate_id for some unknown reason. I'm following up on this upstream, but a workaround for now would be nice :)



Discussion:

Resolving patch:
diff --git a/cloud/amazon/ec2_elb_lb.py b/cloud/amazon/ec2_elb_lb.py
--- a/cloud/amazon/ec2_elb_lb.py
+++ b/cloud/amazon/ec2_elb_lb.py
@@ -341,7 +341,7 @@ def get_info(self):
                 }
 
             if check_elb.listeners:
-                info['listeners'] = [l.get_complex_tuple()
+                info['listeners'] = [self._api_listener_as_tuple(l)
                                      for l in check_elb.listeners]
             elif self.status == 'created':
                 # When creating a new ELB, listeners don't show in the
@@ -431,7 +431,7 @@ def _set_elb_listeners(self):
                 # Since ELB allows only one listener on each incoming port, a
                 # single match on the incomping port is all we're looking for
                 if existing_listener[0] == listener['load_balancer_port']:
-                    existing_listener_found = existing_listener.get_complex_tuple()
+                    existing_listener_found = self._api_listener_as_tuple(existing_listener)
                     break
 
             if existing_listener_found:
@@ -451,7 +451,7 @@ def _set_elb_listeners(self):
         # Check for any extraneous listeners we need to remove, if desired
         if self.purge_listeners:
             for existing_listener in self.elb.listeners:
-                existing_listener_tuple = existing_listener.get_complex_tuple()
+                existing_listener_tuple = self._api_listener_as_tuple(existing_listener)
                 if existing_listener_tuple in listeners_to_remove:
                     # Already queued for removal
                     continue
@@ -468,6 +468,13 @@ def _set_elb_listeners(self):
         if listeners_to_add:
             self._create_elb_listeners(listeners_to_add)
 
+    def _api_listener_as_tuple(self, listener):
+        """Adds ssl_certificate_id to ELB API tuple if present"""
+        base_tuple = listener.get_complex_tuple()
+        if listener.ssl_certificate_id and len(base_tuple) < 5:
+            return base_tuple + (listener.ssl_certificate_id,)
+        return base_tuple
+
     def _listener_as_tuple(self, listener):
         """Formats listener as a 4- or 5-tuples, in the order specified by the
         ELB API"""


Test patch:
Repository: ansible/ansible-modules-core

Issue:
git module key_file= option doesn't interpret the ~/ as $HOME
[This is a clone of ansible/ansible#7533 of which I am **not** the author]
##### Issue Type:

Bug Report
##### Ansible Version:

ansible 1.6.2
##### Environment:

Ubuntu 12.04
##### Summary:

git module key_file= option doesn't interpret the ~/ as $HOME
##### Steps To Reproduce:

```
git: repo=ssh://git@bitbucket.org/xxx/yyyy.git dest=~/compile key_file=~/.ssh/bitbucket_app -vvvv
```
##### Expected Results:

read the keyfile and checkout from git :)
##### Actual Results:

```
<localhost> REMOTE_MODULE git repo=ssh:********@bitbucket.org/xxx/yyy.git dest=~/compile key_file=~/.ssh/bitbucket_app
failed: [localhost] => {"cmd": "/usr/bin/git ls-remote origin -h refs/heads/master", "failed": true, "item": "", "rc": 128}
stderr: Warning: Identity file ~/.ssh/bitbucket_app not accessible: No such file or directory.
```

git module key_file= option doesn't interpret the ~/ as $HOME
[This is a clone of ansible/ansible#7533 of which I am **not** the author]
##### Issue Type:

Bug Report
##### Ansible Version:

ansible 1.6.2
##### Environment:

Ubuntu 12.04
##### Summary:

git module key_file= option doesn't interpret the ~/ as $HOME
##### Steps To Reproduce:

```
git: repo=ssh://git@bitbucket.org/xxx/yyyy.git dest=~/compile key_file=~/.ssh/bitbucket_app -vvvv
```
##### Expected Results:

read the keyfile and checkout from git :)
##### Actual Results:

```
<localhost> REMOTE_MODULE git repo=ssh:********@bitbucket.org/xxx/yyy.git dest=~/compile key_file=~/.ssh/bitbucket_app
failed: [localhost] => {"cmd": "/usr/bin/git ls-remote origin -h refs/heads/master", "failed": true, "item": "", "rc": 128}
stderr: Warning: Identity file ~/.ssh/bitbucket_app not accessible: No such file or directory.
```



Discussion:

Resolving patch:
diff --git a/source_control/git.py b/source_control/git.py
--- a/source_control/git.py
+++ b/source_control/git.py
@@ -518,6 +518,10 @@ def main():
         else:
             gitconfig = os.path.join(dest, '.git', 'config')
 
+    # make sure the key_file path is expanded for ~ and $HOME
+    if key_file is not None:
+        key_file = os.path.abspath(os.path.expanduser(key_file))
+
     # create a wrapper script and export
     # GIT_SSH=<path> as an environment variable
     # for git to use the wrapper script


Test patch:
Repository: ansible/ansible-modules-core

Issue:
The nova-compute module can not associate floatng ip address to instance of VM
##### Issue Type:

Bug Report
##### Ansible Version:
- ansible 1.8(devel)
- nova-compute(master)
##### Environment:

OpenStack 2014.2 Juno with RDO,DevStack
(exclude hpcloud)
##### Summary:

The nova-compute module with floating_ip_pools option retrieve the floating ip address from unused floating ip list that is created by response of nova-api.
If a floating ip address is already assigned, instance_id field contains uuid of virtual machine instance.
But  in the current Juno release of OpenStack, a value of instance_id in response of nova-api is always null, so it should be adopted the fixed_ip instead.
Using the fixed_ip is safer than instance_id in almost version.
##### Steps To Reproduce:
- floating-ip: 172.16.0.6 (in-use)
- fliaging-ip: 172.16.0.7 (unassigned)

```
$ nova --debug floating-ip-list
...
REQ: curl -i 'http://172.16.0.100:8774/v2/832e34a525d948b7b5d5a40e8df792ef/os-floating-ips'
 -X GET -H "Accept: application/json" -H "User-Agent: python-novaclient"
 -H "X-Auth-Project-Id: demo"
 -H "X-Auth-Token: {SHA1}515e73dc756b13c2f4209ff75c75f12ff0477a8d"

RESP: [200] {'date': 'Thu, 30 Oct 2014 14:39:45 GMT',
 'connection': 'keep-alive', 'content-type': 'application/json',
 'content-length': '274',
 'x-compute-request-id': 'req-1253acd4-88f5-4ef1-813a-d080eabc65c7'}
RESP BODY: {
 "floating_ips": [
 {"instance_id": null,
  "ip": "172.16.1.7",
  "fixed_ip": null,
  "id": "082d3444-60eb-4fb0-9791-b9e88b45e7ee",
  "pool": "public"},
 {"instance_id": null,    <- it is already assigned but instance_id is null.
  "ip": "172.16.1.6",
  "fixed_ip": "10.0.0.3",
  "id": "51f86251-d7ed-4ef7-8de9-24698beb555c",
  "pool": "public"}
 ]}
+------------+-----------+----------+--------+
| Ip         | Server Id | Fixed Ip | Pool   |
+------------+-----------+----------+--------+
| 172.16.1.7 | -         | -        | public |
| 172.16.1.6 | -         | 10.0.0.3 | public |
+------------+-----------+----------+--------+
```
##### Expected Results:

The nova-compute module will use from top of unused floating ip list.
If unused list is empty then it allocate new floating ip from pool.
##### Actual Results:

The nova-compute module creates list of all floating ip because instanceid is always null.
At this time, it will use from top of all floating ip list that contains in-use and un-use address.



Discussion:

Resolving patch:
diff --git a/cloud/openstack/_nova_compute.py b/cloud/openstack/_nova_compute.py
--- a/cloud/openstack/_nova_compute.py
+++ b/cloud/openstack/_nova_compute.py
@@ -324,7 +324,7 @@ def _add_floating_ip_from_pool(module, nova, server):
         # loop through all floating IPs
         for f_ip in all_floating_ips:
             # if not reserved and the correct pool, add
-            if f_ip.instance_id is None and (f_ip.pool == pool):
+            if f_ip.fixed_ip is None and (f_ip.pool == pool):
                 pool_ips.append(f_ip.ip)
                 # only need one
                 break


Test patch:
Repository: ansible/ansible-modules-core

Issue:
gce_net fails when using src_range
##### Issue Type:

Bug Report
##### Ansible Version:

1.7.2
##### Environment:

Mac OS X 10.10
##### Summary:

gce_net fails when using src_range
##### Steps To Reproduce:

YAML at https://gist.github.com/bangmedia-seanmcavoy/ebe6a3b9654fe397db7e
basically gce_net fails is src_range is specified.
I have specified '10.0.0.1/32' and ['10.0.0.1/32'] same error
##### Expected Results:

The module should set the value of the resource.sourceRange field to src_range value
##### Actual Results:

```
failed: [localhost -> 127.0.0.1] => {"changed": false, "failed": true}
msg: Unexpected response: {'code': None,
'driver': None,
'http_code': 400,
 'value': {'domain': 'global',
           'message': "Invalid value for field 'resource.sourceRange': ''.  Must specify either sourceRange or   sourceTag.",
           'reason': 'invalid'}}

FATAL: all hosts have already failed -- aborting
```



Discussion:
cc @erjohnso 

For anyone interested, this simple workaround worked for me:

``` diff
--- a/cloud/google/gce_net.py
+++ b/cloud/google/gce_net.py
@@ -156,7 +156,7 @@ def main():
             ipv4_range = dict(),
             fwname = dict(),
             name = dict(),
-            src_range = dict(),
+            src_range = dict(type='list'),
             src_tags = dict(type='list'),
             state = dict(default='present'),
             service_account_email = dict(),
```

With the above modification, below task is working just fine:

``` yaml
- name: Provision staging tier firewall rules (internal)
  local_action: gce_net name=staging-net
                        fwname=internal-allow
                        allowed={{ item }}
                        src_range=10.241.0.0/16
  with_items:
    - "tcp:1-65535"
    - "udp:1-65535"
    - "icmp"
```


Resolving patch:
diff --git a/cloud/google/gce_net.py b/cloud/google/gce_net.py
--- a/cloud/google/gce_net.py
+++ b/cloud/google/gce_net.py
@@ -156,7 +156,7 @@ def main():
             ipv4_range = dict(),
             fwname = dict(),
             name = dict(),
-            src_range = dict(),
+            src_range = dict(type='list'),
             src_tags = dict(type='list'),
             state = dict(default='present'),
             service_account_email = dict(),


Test patch:
Repository: ansible/ansible-modules-core

Issue:
Mount module throws KeyError exception when "opts" parameter is not provided
##### Issue Type:

Bug Report
##### Ansible Version:

1.8.3
##### Environment:

Amazon Linux AMI release 2014.09
##### Summary:

Not specifying a the "opts" parameter in the "mount" module causes a KeyError to be thrown.
This looks like it was introduced as part of PR: https://github.com/ansible/ansible-modules-core/pull/49
The following line should probably check for the presence of the "opts" key in the args dictionary before trying to access it: https://github.com/ansible/ansible-modules-core/blob/a75bef5bc6ae3ca23e312f9aec9c56b31811f4d0/system/mount.py#L323
##### Steps To Reproduce:

The following mount task throws the exception (note the absence of the optional opts parameter)
- name: Mount NFS volume
  mount: name=/media/storage fstype=nfs4 src={{storage_instance_ip.stdout}}:/ state=mounted
##### Expected Results:

Mount module should mount the drive.
##### Actual Results:

Python KeyError exception is thrown



Discussion:

Resolving patch:
diff --git a/system/mount.py b/system/mount.py
--- a/system/mount.py
+++ b/system/mount.py
@@ -320,7 +320,7 @@ def main():
             if os.path.ismount(name):
                 if changed:
                     res,msg = mount(module, **args)
-            elif "bind" in args['opts']:
+            elif 'bind' in args.get('opts', []):
                 changed = True
                 cmd = 'mount -l'
                 rc, out, err = module.run_command(cmd)


Test patch:
Repository: ansible/ansible-modules-core

Issue:
Backups not enabled when creating DigitalOcean droplets
##### Issue Type:

Bug Report
##### Ansible Version:

```
ansible 1.8.3
  configured module search path = None
```
##### Environment:

Debian 7
##### Summary:

When creating a droplet with `backups_enabled=yes` the Digital Ocean droplet is created without backups being enabled.
##### Steps To Reproduce:

```
- name: Create Digital Ocean droplet
  digital_ocean:
    state=present
    command=droplet
    name="{{ hostname }}"
    client_id="{{ client_id }}"
    api_key="{{ api_key }}"
    backups_enabled=yes
    size_id=63
    region_id=8
    image_id={{ image_id }}
    wait_timeout=500
    unique_name=yes
  register: do_droplet
```
##### Expected Results:

New droplet should have backups enabled.
##### Actual Results:

Backups are not enabled.



Discussion:

Resolving patch:
diff --git a/cloud/digital_ocean/digital_ocean.py b/cloud/digital_ocean/digital_ocean.py
--- a/cloud/digital_ocean/digital_ocean.py
+++ b/cloud/digital_ocean/digital_ocean.py
@@ -237,7 +237,8 @@ def setup(cls, client_id, api_key):
     @classmethod
     def add(cls, name, size_id, image_id, region_id, ssh_key_ids=None, virtio=True, private_networking=False, backups_enabled=False):
         private_networking_lower = str(private_networking).lower()
-        json = cls.manager.new_droplet(name, size_id, image_id, region_id, ssh_key_ids, virtio, private_networking_lower, backups_enabled)
+        backups_enabled_lower = str(backups_enabled).lower()
+        json = cls.manager.new_droplet(name, size_id, image_id, region_id, ssh_key_ids, virtio, private_networking_lower, backups_enabled_lower)
         droplet = cls(json)
         return droplet
 


Test patch:
Repository: ansible/ansible-modules-core

Issue:
route53 module: list the associated name servers of zone
##### Issue Type:

Feature Idea
##### Ansible Version:

1.8.2
##### Environment:

OS running: "Ubuntu 14.04", OS managing: “N/A”
##### Summary:

List the name servers which amazon associated to the zone when using the `get` command.



Discussion:

Resolving patch:
diff --git a/cloud/amazon/route53.py b/cloud/amazon/route53.py
--- a/cloud/amazon/route53.py
+++ b/cloud/amazon/route53.py
@@ -248,7 +248,13 @@ def main():
                 module.exit_json(changed=False)
 
     if command_in == 'get':
-        module.exit_json(changed=False, set=record)
+        if type_in == 'NS':
+            ns = record['values']
+        else:
+            # Retrieve name servers associated to the zone.
+            ns = conn.get_zone(zone_in).get_nameservers()
+
+        module.exit_json(changed=False, set=record, nameservers=ns)
 
     if command_in == 'delete' and not found_record:
         module.exit_json(changed=False)


Test patch:
Repository: ansible/ansible-modules-core

Issue:
Deprecated Openstack modules need a drepecated: documentation field
@emonty Looks like we just merged the deprecation of old openstack modules: https://github.com/ansible/ansible-modules-core/pull/244  When we did this the documentation build job noticed that we did not add a deprecation field to the module's documentation at the same time.  Each of the deprecated modules need something like:

```
 module: glance_image
 version_added: "1.2"
 deprecated: Deprecated in 1.9.  Use os_image instead
 short_description: Add/Delete images from glance
```

I could just add deprecated in 1.9 to all those modules but that's not very friendly to users.  Better if you do it so that you can mention the replacement module to use.  Would that be okay?



Discussion:
@abadger absolutely - on it

@emonty Cool, thanks!  There's one module that was missed in the pull request: _quantum_router.py


Resolving patch:
diff --git a/cloud/openstack/_quantum_router.py b/cloud/openstack/_quantum_router.py
--- a/cloud/openstack/_quantum_router.py
+++ b/cloud/openstack/_quantum_router.py
@@ -30,6 +30,7 @@
 module: quantum_router
 version_added: "1.2"
 short_description: Create or Remove router from openstack
+deprecated: Deprecated in 1.9. Use os_router instead
 description:
    - Create or Delete routers from OpenStack
 options:


Test patch:
Repository: ansible/ansible-modules-core

Issue:
Instance deregistration should try all associated ELBs
It is currently possible for ELB deregistration to short circuit if an instance is not found in the associated load balancer. This can be problematic when an instance is associated with multiple load balancers and happens to be deregistered with one at the beginning of the list. As a result, the instance will not be deregistered from the remaining load balancers.

see: https://github.com/ansible/ansible-modules-core/blob/0ab5682b8740f0075bd74e6345a81aea6b4be6cd/cloud/amazon/ec2_elb.py#L132



Discussion:

Resolving patch:
diff --git a/cloud/amazon/ec2_elb.py b/cloud/amazon/ec2_elb.py
--- a/cloud/amazon/ec2_elb.py
+++ b/cloud/amazon/ec2_elb.py
@@ -130,9 +130,9 @@ def deregister(self, wait, timeout):
         for lb in self.lbs:
             initial_state = self._get_instance_health(lb) 
             if initial_state is None:
-                # The instance isn't registered with this ELB so just 
-                # return unchanged
-                return
+                # Instance isn't registered with this load
+                # balancer. Ignore it and try the next one.
+                continue
 
             lb.deregister_instances([self.instance_id])
 


Test patch:
Repository: ansible/ansible-modules-core

Issue:
rds_subnet_group never reports 'changed' on a new or modified group
When running the 'rds_subnet_group' module, the module will correctly create or modify a group but always reports task as 'ok' instead of 'changed'.



Discussion:

Resolving patch:
diff --git a/cloud/amazon/rds_subnet_group.py b/cloud/amazon/rds_subnet_group.py
--- a/cloud/amazon/rds_subnet_group.py
+++ b/cloud/amazon/rds_subnet_group.py
@@ -149,10 +149,14 @@ def main():
         else:
             if not exists:
                 new_group = conn.create_db_subnet_group(group_name, desc=group_description, subnet_ids=group_subnets)
-
+                changed = True
             else:
-                changed_group = conn.modify_db_subnet_group(group_name, description=group_description, subnet_ids=group_subnets)
-
+                # Sort the subnet groups before we compare them
+                matching_groups[0].subnet_ids.sort()
+                group_subnets.sort()
+                if ( (matching_groups[0].name != group_name) or (matching_groups[0].description != group_description) or (matching_groups[0].subnet_ids != group_subnets) ):
+                    changed_group = conn.modify_db_subnet_group(group_name, description=group_description, subnet_ids=group_subnets)
+                    changed = True
     except BotoServerError, e:
         module.fail_json(msg = e.error_message)
 


Test patch: