prompt: You will be provided with a partial code base and an issue statement explaining a problem to resolve.
  <issue>
  Bulk import workflow encounters IntegrityError when saving an organization
  Currently, we allow organizations with the domain that contains the `www` subdomain. For eg: Google can exist as `www.google.com` as well as `google.com`, leading to `IntegrityError` while saving the first while the second exists.
  
  Shouldn't we enforce one URL pattern and trim/add `www` to the `domain` field when saving an organization?
  
  Testcase:
  
  ``` py
  In [5]: Organization.objects.create(fullname='Google', domain='google.com')
  Out[5]: <Organization: google.com>
  
  In [6]: Organization.objects.create(fullname='Google', domain='www.google.com')
  ---------------------------------------------------------------------------
  IntegrityError                            Traceback (most recent call last)
  ```
  
  
  </issue>
  <code>
  [start of pydata/api.py]
  1 from functools import lru_cache
  2 from json import JSONDecodeError
  3 from urllib.parse import urljoin, urlparse
  4 
  5 import requests
  6 from django.conf import settings
  7 
  8 from workshops.models import (
  9     Person,
  10     Role,
  11     Organization,
  12     Sponsorship,
  13     Task,
  14 )
  15 from workshops.util import create_username
  16 
  17 
  18 class BaseAPIClient(requests.Session):
  19     """
  20     An API client that abstracts away the work of dealing with URLs.
  21     Usage:
  22     > client = APIClient(event)
  23     > list(client) -> returns a list of all objects returned by the API.
  24     > client[23] -> returns the object with pk=23
  25     """
  26     ROOT_ENDPOINT = 'api/'
  27 
  28     @lru_cache(maxsize=None)
  29     def __new__(cls, event):
  30         """
  31         Returns an instance of APIClient.
  32         Throws NotImplementedError if an API does not exist at the root URL.
  33         """
  34         try:
  35             r = requests.get(urljoin(event.url, cls.ROOT_ENDPOINT))
  36             r.raise_for_status()
  37             r.json()
  38         except (requests.exceptions.HTTPError, JSONDecodeError):
  39             raise NotImplementedError('Conference site does not support an API')
  40         return super().__new__(cls)
  41 
  42     def __init__(self, event):
  43         '''Populate API endpoint and set up basic authentication'''
  44         super().__init__()
  45         self.event = event
  46         self.endpoint = urljoin(event.url, self.ENDPOINT)
  47         self.auth = (
  48             settings.PYDATA_USERNAME_SECRET, settings.PYDATA_PASSWORD_SECRET)
  49 
  50     def __iter__(self):
  51         try:
  52             r = self.get(self.endpoint)
  53             r.raise_for_status()
  54             pydata_objs = r.json()
  55         except (requests.exceptions.HTTPError, JSONDecodeError) as e:
  56             raise IOError('Cannot fetch instances from API: {}'.format(str(e)))
  57         for obj in pydata_objs:
  58             yield self.parse(obj)
  59 
  60     def __contains__(self, pk):
  61         try:
  62             self.get(self.endpoint + str(pk)).raise_for_status()
  63         except requests.exceptions.HTTPError:
  64             return False
  65         else:
  66             return True
  67 
  68     def __getitem__(self, pk):
  69         if pk not in self:
  70             raise KeyError(
  71                 '{} does not exist'.format(self.model._meta.verbose_name)
  72             )
  73         obj = self.get(self.endpoint + str(pk)).json()
  74         return self.parse(obj)
  75 
  76 
  77 class PersonAPIClient(BaseAPIClient):
  78     ENDPOINT = 'api/speaker/'
  79     model = Person
  80 
  81     def parse(self, speaker):
  82         speaker['name'] = speaker['name'].strip()
  83         personal = speaker['name'].rsplit(' ', 1)[0]
  84         family = speaker['name'].rsplit(' ', 1)[-1]
  85         return Person(
  86             username=speaker['username'],
  87             personal=personal,
  88             family=family,
  89             email=speaker['email'],
  90             url=speaker['absolute_url'],
  91         )
  92 
  93 
  94 class TaskAPIClient(BaseAPIClient):
  95     ENDPOINT = 'api/presentation/'
  96     model = Task
  97 
  98     def parse(self, presentation):
  99         return Task(
  100             event=self.event,
  101             person=Person.objects.get_or_create(
  102                 email=presentation['speaker']['email'],
  103                 defaults={
  104                     'username': create_username('', presentation['speaker']['username']),
  105                     'personal': presentation['speaker']['name'].rsplit(' ', 1)[0],
  106                     'family': presentation['speaker']['name'].rsplit(' ', 1)[-1],
  107                     'url': presentation['speaker']['absolute_url'],
  108                 }
  109             )[0],
  110             role=Role.objects.get(name='presenter'),
  111             title=presentation['title'],
  112             url=presentation['absolute_url'],
  113         )
  114 
  115 
  116 class SponsorshipAPIClient(BaseAPIClient):
  117     ENDPOINT = 'api/sponsor/'
  118     model = Sponsorship
  119 
  120     def parse(self, sponsor):
  121         return Sponsorship(
  122             organization=Organization.objects.get_or_create(
  123                 domain=urlparse(sponsor['external_url']).netloc,
  124                 defaults={
  125                     'fullname': sponsor['name'],
  126                     'notes': sponsor['annotation'],
  127                 },
  128             )[0],
  129             event=self.event,
  130             amount=sponsor['level']['cost'],
  131             contact=Person.objects.get_or_create(
  132                 email=sponsor['contact_email'],
  133                 defaults={
  134                     'username': create_username('', sponsor['contact_name']),
  135                     'personal': sponsor['contact_name'].rsplit(' ', 1)[0],
  136                     'family': sponsor['contact_name'].rsplit(' ', 1)[-1],
  137                 },
  138             )[0],
  139         )
  140
  [end of pydata/api.py]
  </code>
  
  I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format.
  <patch>
  diff --git a/file.py b/file.py
  --- a/file.py
  +++ b/file.py
  @@ -1,27 +1,35 @@
   def euclidean(a, b):
  -    while b:
  -        a, b = b, a % b
  -    return a
  +    if b == 0:
  +        return a
  +    return euclidean(b, a % b)
   
   
   def bresenham(x0, y0, x1, y1):
       points = []
       dx = abs(x1 - x0)
       dy = abs(y1 - y0)
  -    sx = 1 if x0 < x1 else -1
  -    sy = 1 if y0 < y1 else -1
  -    err = dx - dy
  +    x, y = x0, y0
  +    sx = -1 if x0 > x1 else 1
  +    sy = -1 if y0 > y1 else 1
   
  -    while True:
  -        points.append((x0, y0))
  -        if x0 == x1 and y0 == y1:
  -            break
  -        e2 = 2 * err
  -        if e2 > -dy:
  -            err -= dy
  -            x0 += sx
  -        if e2 < dx:
  -            err += dx
  -            y0 += sy
  +    if dx > dy:
  +        err = dx / 2.0
  +        while x != x1:
  +            points.append((x, y))
  +            err -= dy
  +            if err < 0:
  +                y += sy
  +                err += dx
  +            x += sx
  +    else:
  +        err = dy / 2.0
  +        while y != y1:
  +            points.append((x, y))
  +            err -= dx
  +            if err < 0:
  +                x += sx
  +                err += dy
  +            y += sy
  +
  +    points.append((x, y))
       return points
  
  </patch>
golden_diff: diff --git a/pydata/api.py b/pydata/api.py
  --- a/pydata/api.py
  +++ b/pydata/api.py
  @@ -4,6 +4,7 @@
   
   import requests
   from django.conf import settings
  +from django.db.models import Q
   
   from workshops.models import (
       Person,
  @@ -118,14 +119,18 @@
       model = Sponsorship
   
       def parse(self, sponsor):
  +        domain = urlparse(sponsor['external_url']).netloc
  +        organization = Organization.objects.filter(
  +            Q(fullname=sponsor['name']) | Q(domain=domain)
  +        ).first()
  +        if not organization:
  +            organization = Organization.objects.create(
  +                fullname=sponsor['name'],
  +                domain=domain,
  +                notes=sponsor['annotation'],
  +            )
           return Sponsorship(
  -            organization=Organization.objects.get_or_create(
  -                domain=urlparse(sponsor['external_url']).netloc,
  -                defaults={
  -                    'fullname': sponsor['name'],
  -                    'notes': sponsor['annotation'],
  -                },
  -            )[0],
  +            organization=organization,
               event=self.event,
               amount=sponsor['level']['cost'],
               contact=Person.objects.get_or_create(
  
verification_info: {"golden_diff": "diff --git a/pydata/api.py b/pydata/api.py\n--- a/pydata/api.py\n+++ b/pydata/api.py\n@@ -4,6 +4,7 @@\n \n import requests\n from django.conf import settings\n+from django.db.models import Q\n \n from workshops.models import (\n     Person,\n@@ -118,14 +119,18 @@\n     model = Sponsorship\n \n     def parse(self, sponsor):\n+        domain = urlparse(sponsor['external_url']).netloc\n+        organization = Organization.objects.filter(\n+            Q(fullname=sponsor['name']) | Q(domain=domain)\n+        ).first()\n+        if not organization:\n+            organization = Organization.objects.create(\n+                fullname=sponsor['name'],\n+                domain=domain,\n+                notes=sponsor['annotation'],\n+            )\n         return Sponsorship(\n-            organization=Organization.objects.get_or_create(\n-                domain=urlparse(sponsor['external_url']).netloc,\n-                defaults={\n-                    'fullname': sponsor['name'],\n-                    'notes': sponsor['annotation'],\n-                },\n-            )[0],\n+            organization=organization,\n             event=self.event,\n             amount=sponsor['level']['cost'],\n             contact=Person.objects.get_or_create(\n", "issue": "Bulk import workflow encounters IntegrityError when saving an organization\nCurrently, we allow organizations with the domain that contains the `www` subdomain. For eg: Google can exist as `www.google.com` as well as `google.com`, leading to `IntegrityError` while saving the first while the second exists.\n\nShouldn't we enforce one URL pattern and trim/add `www` to the `domain` field when saving an organization?\n\nTestcase:\n\n``` py\nIn [5]: Organization.objects.create(fullname='Google', domain='google.com')\nOut[5]: <Organization: google.com>\n\nIn [6]: Organization.objects.create(fullname='Google', domain='www.google.com')\n---------------------------------------------------------------------------\nIntegrityError                            Traceback (most recent call last)\n```\n\n", "before_files": [{"content": "from functools import lru_cache\nfrom json import JSONDecodeError\nfrom urllib.parse import urljoin, urlparse\n\nimport requests\nfrom django.conf import settings\n\nfrom workshops.models import (\n    Person,\n    Role,\n    Organization,\n    Sponsorship,\n    Task,\n)\nfrom workshops.util import create_username\n\n\nclass BaseAPIClient(requests.Session):\n    \"\"\"\n    An API client that abstracts away the work of dealing with URLs.\n    Usage:\n    > client = APIClient(event)\n    > list(client) -> returns a list of all objects returned by the API.\n    > client[23] -> returns the object with pk=23\n    \"\"\"\n    ROOT_ENDPOINT = 'api/'\n\n    @lru_cache(maxsize=None)\n    def __new__(cls, event):\n        \"\"\"\n        Returns an instance of APIClient.\n        Throws NotImplementedError if an API does not exist at the root URL.\n        \"\"\"\n        try:\n            r = requests.get(urljoin(event.url, cls.ROOT_ENDPOINT))\n            r.raise_for_status()\n            r.json()\n        except (requests.exceptions.HTTPError, JSONDecodeError):\n            raise NotImplementedError('Conference site does not support an API')\n        return super().__new__(cls)\n\n    def __init__(self, event):\n        '''Populate API endpoint and set up basic authentication'''\n        super().__init__()\n        self.event = event\n        self.endpoint = urljoin(event.url, self.ENDPOINT)\n        self.auth = (\n            settings.PYDATA_USERNAME_SECRET, settings.PYDATA_PASSWORD_SECRET)\n\n    def __iter__(self):\n        try:\n            r = self.get(self.endpoint)\n            r.raise_for_status()\n            pydata_objs = r.json()\n        except (requests.exceptions.HTTPError, JSONDecodeError) as e:\n            raise IOError('Cannot fetch instances from API: {}'.format(str(e)))\n        for obj in pydata_objs:\n            yield self.parse(obj)\n\n    def __contains__(self, pk):\n        try:\n            self.get(self.endpoint + str(pk)).raise_for_status()\n        except requests.exceptions.HTTPError:\n            return False\n        else:\n            return True\n\n    def __getitem__(self, pk):\n        if pk not in self:\n            raise KeyError(\n                '{} does not exist'.format(self.model._meta.verbose_name)\n            )\n        obj = self.get(self.endpoint + str(pk)).json()\n        return self.parse(obj)\n\n\nclass PersonAPIClient(BaseAPIClient):\n    ENDPOINT = 'api/speaker/'\n    model = Person\n\n    def parse(self, speaker):\n        speaker['name'] = speaker['name'].strip()\n        personal = speaker['name'].rsplit(' ', 1)[0]\n        family = speaker['name'].rsplit(' ', 1)[-1]\n        return Person(\n            username=speaker['username'],\n            personal=personal,\n            family=family,\n            email=speaker['email'],\n            url=speaker['absolute_url'],\n        )\n\n\nclass TaskAPIClient(BaseAPIClient):\n    ENDPOINT = 'api/presentation/'\n    model = Task\n\n    def parse(self, presentation):\n        return Task(\n            event=self.event,\n            person=Person.objects.get_or_create(\n                email=presentation['speaker']['email'],\n                defaults={\n                    'username': create_username('', presentation['speaker']['username']),\n                    'personal': presentation['speaker']['name'].rsplit(' ', 1)[0],\n                    'family': presentation['speaker']['name'].rsplit(' ', 1)[-1],\n                    'url': presentation['speaker']['absolute_url'],\n                }\n            )[0],\n            role=Role.objects.get(name='presenter'),\n            title=presentation['title'],\n            url=presentation['absolute_url'],\n        )\n\n\nclass SponsorshipAPIClient(BaseAPIClient):\n    ENDPOINT = 'api/sponsor/'\n    model = Sponsorship\n\n    def parse(self, sponsor):\n        return Sponsorship(\n            organization=Organization.objects.get_or_create(\n                domain=urlparse(sponsor['external_url']).netloc,\n                defaults={\n                    'fullname': sponsor['name'],\n                    'notes': sponsor['annotation'],\n                },\n            )[0],\n            event=self.event,\n            amount=sponsor['level']['cost'],\n            contact=Person.objects.get_or_create(\n                email=sponsor['contact_email'],\n                defaults={\n                    'username': create_username('', sponsor['contact_name']),\n                    'personal': sponsor['contact_name'].rsplit(' ', 1)[0],\n                    'family': sponsor['contact_name'].rsplit(' ', 1)[-1],\n                },\n            )[0],\n        )\n", "path": "pydata/api.py"}]}