internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: akvo/akvo-rsr

Issue:
Bugs with budget item totals and labels
### Totals

Unknown format code 'f' for object of type 'str'

In:

```
/var/akvo/rsr/code/akvo/rsr/models/project.py in budget_currency_totals_string
        totals = self.budget_currency_totals()
        total_string = ''
        for t in totals:
            print type(totals[t])
            total_string += '%s %s, ' % ("{:,.0f}".format(totals[t]), t) ...
        return total_string[:-2]
```
### Labels

AttributeError: 'NoneType' object has no attribute 'label'

```
File "akvo/rsr/models/budget_item.py", line 116, in get_label
    if self.label.label in self.OTHER_LABELS:

```



Discussion:

Resolving patch:
diff --git a/akvo/rsr/models/budget_item.py b/akvo/rsr/models/budget_item.py
--- a/akvo/rsr/models/budget_item.py
+++ b/akvo/rsr/models/budget_item.py
@@ -113,7 +113,7 @@ def clean(self):
 
     def get_label(self):
         "Needed since we have to have a vanilla __unicode__() method for the admin"
-        if self.label.label in self.OTHER_LABELS:
+        if self.label and self.label.label in self.OTHER_LABELS:
             # display "other" if other_extra is empty.
             # Translating here without translating the other labels seems corny
             return u"other" if self.other_extra is None else self.other_extra.strip()
diff --git a/akvo/rsr/models/project.py b/akvo/rsr/models/project.py
--- a/akvo/rsr/models/project.py
+++ b/akvo/rsr/models/project.py
@@ -20,6 +20,7 @@
 from django.dispatch import receiver
 from django.utils.safestring import mark_safe
 from django.utils.translation import ugettext, ugettext_lazy as _
+from django.db.models import Q
 
 from django_counter.models import ViewCounter
 
@@ -1008,7 +1009,7 @@ def budget_currency_totals(self):
         totals = {}
         for c in unique_currencies:
             if c == self.currency:
-                totals[c] = budget_items.filter(currency__exact='').aggregate(Sum('amount')).values()[0]
+                totals[c] = budget_items.filter(Q(currency='') | Q(currency=c)).aggregate(Sum('amount')).values()[0]
             else:
                 totals[c] = budget_items.filter(currency=c).aggregate(Sum('amount')).values()[0]
 
@@ -1021,7 +1022,6 @@ def budget_currency_totals_string(self):
         total_string = ''
 
         for t in totals:
-            print type(totals[t])
             total_string += '%s %s, ' % ("{:,.0f}".format(totals[t]), t)
 
         return total_string[:-2]


Test patch:
Repository: akvo/akvo-rsr

Issue:
Updates list not loading
```
FieldError: Cannot resolve keyword 'country' into field. Choices are: address_1, address_2, city, id, latitude, location_target, location_target_id, longitude, postcode, projectupdate, state

    locations_qs = location_model.objects.filter(
         location_target__in=qs).order_by('country__id').distinct('country__id')
     locations = []
     for location in locations_qs:
         if location.country:
             country = get_id_for_iso(location.country.iso_code.upper())
             locations.append(country)
             locations.extend(get_locations(country, []))
```

See http://sentry.support.akvo-ops.org/rsr/live/group/930/.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/views/project_update.py b/akvo/rsr/views/project_update.py
--- a/akvo/rsr/views/project_update.py
+++ b/akvo/rsr/views/project_update.py
@@ -66,9 +66,6 @@ def directory(request):
 
     # Swap to choice filter for RSR pages
     if request.rsr_page:
-        # Filter location filter list to only populated locations
-        f.filters['location'].extra['choices'] = location_choices(all_updates)
-
         # Filter partner filter list to only populated partners
         f.filters['partner'] = django_filters.ChoiceFilter(
             choices=build_choices(_page_organisations(request.rsr_page)),


Test patch:
Repository: akvo/akvo-rsr

Issue:
Create a 500 page
Create a (working) 500 page with a message like:

> Oops something went wrong. We have been notified and will take action asap. Please check in later or contact us at xyz. RSR team



Discussion:

Resolving patch:
diff --git a/akvo/rsr/views/error.py b/akvo/rsr/views/error.py
--- a/akvo/rsr/views/error.py
+++ b/akvo/rsr/views/error.py
@@ -6,8 +6,12 @@
     see < http://www.gnu.org/licenses/agpl.html >.
 """
 
-from django.http import HttpResponse
+from django.shortcuts import render_to_response
+from django.template import RequestContext
 
 
 def server_error(request, template_name='500.html'):
-    HttpResponse("Server Error - 500")
+    response = render_to_response('500.html', {}, context_instance=RequestContext(request))
+    response.status_code = 500
+    return response
+


Test patch:
Repository: akvo/akvo-rsr

Issue:
Buggy behavior when adding documents in project editor
### Adding documents changes URL/upload switch

To reproduce:
1. Go to editor and in section 9 upload a new document.
2. Click the 'Add another document' link
3. _Result:_ The first document switches back to show the URL instead of upload field
### Trying to save an invalid URL will populate blank documents with the incorrect URL

To reproduce:
1. Go to editor and in section 9 add a new document
2. Enter an invalid url (ex. 'http://test.c') in one document url field and try to save
3. Correct the url (ex. 'http://test.com') and save again
4. Upon reloading the page, there will be an additional 'Untitled Document' with the incorrect url  ('http://test.c')



Discussion:

Resolving patch:
diff --git a/akvo/rest/views/project_editor.py b/akvo/rest/views/project_editor.py
--- a/akvo/rest/views/project_editor.py
+++ b/akvo/rest/views/project_editor.py
@@ -380,6 +380,7 @@ def create_object(Model, kwargs, field, field_name, orig_data, changes, errors,
             # Somewhere else in the model a validation error occurred (or a combination of fields).
             # We display this nonetheless and do not save the field.
             errors = add_error(errors, str(e), field_name)
+        obj.delete()
     except MultipleObjectsReturned:
         # Multiple reporting organisations are not allowed and will raise a MultipleObjectsReturned
         # exception. In this case, display a nice error message and delete the created partnership.


Test patch:
Repository: akvo/akvo-rsr

Issue:
Remove check on completed or cancelled projects
The change in last release should be reverted; projects with the 'Completion' or 'Cancelled' status should still be editable and it should be possible to place updates on these projects.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/models/project.py b/akvo/rsr/models/project.py
--- a/akvo/rsr/models/project.py
+++ b/akvo/rsr/models/project.py
@@ -124,7 +124,7 @@ class Project(TimestampsMixin, models.Model):
     }
 
     # Status combinations used in conditionals
-    EDIT_DISABLED = ['3', '5']
+    EDIT_DISABLED = []
     DONATE_DISABLED = ['', '3', '4', '5', '6']
     NOT_SUSPENDED = ['', '1', '2', '3', '4', '5']
 


Test patch:
Repository: akvo/akvo-rsr

Issue:
Old project update admin crashes
Trying to save anything in the old project update admin will make it crash.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/admin.py b/akvo/rsr/admin.py
--- a/akvo/rsr/admin.py
+++ b/akvo/rsr/admin.py
@@ -1172,8 +1172,7 @@ class ProjectCommentAdmin(admin.ModelAdmin):
 class ProjectUpdateLocationInline(admin.StackedInline):
     model = get_model('rsr', 'projectupdatelocation')
     extra = 0
-    fields = ('latitude', 'longitude', 'city', 'state', 'address_1', 'address_2', 'postcode',
-              'country')
+    fields = ('latitude', 'longitude', 'city', 'state', 'address_1', 'address_2', 'postcode')
 
 
 class ProjectUpdateAdmin(TimestampsAdminDisplayMixin, AdminVideoMixin, admin.ModelAdmin):


Test patch:
Repository: akvo/akvo-rsr

Issue:
Non unicode location data
Filling in this data for locations will give an UnicodeDecodeError: `28.2118Â°` or `81.7131Â°`.



Discussion:

Resolving patch:
diff --git a/akvo/rest/views/project_editor.py b/akvo/rest/views/project_editor.py
--- a/akvo/rest/views/project_editor.py
+++ b/akvo/rest/views/project_editor.py
@@ -562,6 +562,13 @@ def project_editor(request, pk=None):
     updated_project = Project.objects.get(pk=pk)
     updated_project.update_iati_checks()
 
+    # Ensure errors are properly encoded
+    for error in errors:
+        if 'location' in error['name'] and 'Invalid literal' in error['error']:
+            error['error'] = 'Only decimal values are accepted.'
+        else:
+            error['error'] = unicode(error['error'], errors='ignore')
+
     return Response(
         {
             'changes': log_changes(changes, user, project),


Test patch:
Repository: akvo/akvo-rsr

Issue:
Remove unpublished projects from the hierarchy
On the hierarchy page in RSR, we now show any project and thus also unpublished projects. Only published and public (non-private) projects should be shown.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/models/project.py b/akvo/rsr/models/project.py
--- a/akvo/rsr/models/project.py
+++ b/akvo/rsr/models/project.py
@@ -1180,7 +1180,7 @@ def parents(self):
                 related_to_projects__project=self,
                 related_to_projects__relation=1
             )
-        ).distinct()
+        ).distinct().published().public()
 
     def children(self):
         return (
@@ -1191,7 +1191,7 @@ def children(self):
                 related_to_projects__project=self,
                 related_to_projects__relation=2
             )
-        ).distinct()
+        ).distinct().published().public()
 
     def siblings(self):
         return (
@@ -1202,7 +1202,7 @@ def siblings(self):
                 related_to_projects__project=self,
                 related_to_projects__relation=3
             )
-        ).distinct()
+        ).distinct().published().public()
 
     def check_mandatory_fields(self):
         iati_checks = IatiChecks(self)


Test patch:
Repository: akvo/akvo-rsr

Issue:
Warn the user when they lose editing rights of project
When removing an organisation from a project, it is possible that the user loses the right to edit the project altogether. In this case, we should warn the user that they will lose the editing rights.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/models/user.py b/akvo/rsr/models/user.py
--- a/akvo/rsr/models/user.py
+++ b/akvo/rsr/models/user.py
@@ -472,5 +472,5 @@ def project_editor_of(self, org):
 
         :param org; an Organisation instance
         """
-        editor_group = Group.objects.get(name='Project editors')
+        editor_group = Group.objects.get(name='Project Editors')
         return self.has_role_in_org(org, editor_group)
diff --git a/akvo/rsr/views/my_rsr.py b/akvo/rsr/views/my_rsr.py
--- a/akvo/rsr/views/my_rsr.py
+++ b/akvo/rsr/views/my_rsr.py
@@ -292,11 +292,22 @@ def project_editor(request, project_id):
     dac5_codes = codelist_choices(SECTOR)
     dac3_codes = codelist_choices(SECTOR_CATEGORY)
 
+    # Permissions
+    org_permissions = []
+    for approved_org in request.user.approved_organisations():
+        if request.user.admin_of(approved_org) or request.user.me_manager_of(approved_org) or \
+                request.user.project_editor_of(approved_org):
+            org_permissions.append(approved_org.pk)
+
     context = {
         'id': project_id,
         'project': project,
         'projectmodel': Project,
 
+        # Permissions
+        'is_admin': request.user.is_admin or request.user.is_superuser,
+        'org_permissions': list(set(org_permissions)),
+
         # Validation
         'validations': validations,
         'validation_sets': validation_sets,


Test patch:
Repository: akvo/akvo-rsr

Issue:
Allow 0 as value for funding amount in partnerships
It should be possible to fill in 0 as a funding amount in the project editor, and then publish a project. This is based on Plan Finland feedback:

"Are you able to give us an estimate on when the suggestions we made to Geert could be published (the changes to the results section and possibility for 0€ budget project)."



Discussion:

Resolving patch:
diff --git a/akvo/rsr/models/publishing_status.py b/akvo/rsr/models/publishing_status.py
--- a/akvo/rsr/models/publishing_status.py
+++ b/akvo/rsr/models/publishing_status.py
@@ -90,7 +90,7 @@ def clean(self):
             else:
                 for funding_partner in self.project.partnerships.filter(
                         iati_organisation_role=Partnership.IATI_FUNDING_PARTNER):
-                    if not funding_partner.funding_amount:
+                    if not funding_partner.funding_amount and not funding_partner.funding_amount == 0:
                         validation_errors.append(
                             ValidationError(_('All funding partners should have a funding amount.'),
                                             code='partners'
@@ -130,7 +130,7 @@ def clean(self):
                     ValidationError(_('Project needs to have at least one budget item.'),
                                     code='budget_item')
                 )
-            elif not self.project.budget_items.filter(amount__gt=0).exists():
+            elif not self.project.budget_items.filter(amount__gte=0).exists():
                 validation_errors.append(
                     ValidationError(
                         _('Project needs to have at least one budget item with an amount.'),


Test patch:
Repository: akvo/akvo-rsr

Issue:
Internal server error for API call
This URL currently gives an internal server error: http://rsr.akvo.org/rest/v1/project_extra/787/.json

Part of the stacktrace:

```
IOError Root Cause
image file is truncated (48 bytes not processed)

...
akvo/rest/fields.py ? in to_native
    default_thumb = get_thumbnail(value, default_width, quality=99)
sorl/thumbnail/shortcuts.py ? in get_thumbnail
    return default.backend.get_thumbnail(file_, geometry_string, **options)
sorl/thumbnail/base.py ? in get_thumbnail
    thumbnail)
sorl/thumbnail/base.py ? in _create_thumbnail
    image = default.engine.create(source_image, geometry, options)
sorl/thumbnail/engines/base.py ? in create
    image = self.colorspace(image, geometry, options)
sorl/thumbnail/engines/base.py ? in colorspace
    return self._colorspace(image, colorspace)
sorl/thumbnail/engines/pil_engine.py ? in _colorspace
    return image.convert('RGB')
PIL/Image.py ? in convert
    self.load()
PIL/ImageFile.py ? in load
    "(%d bytes not processed)" % len(b))
```



Discussion:

Resolving patch:
diff --git a/akvo/rest/fields.py b/akvo/rest/fields.py
--- a/akvo/rest/fields.py
+++ b/akvo/rest/fields.py
@@ -124,18 +124,20 @@ def get_thumb(request, name):
                     max_size = request.GET.get('image_thumb_{}_max_size'.format(name))
                     if max_size:
                         return get_thumbnail(value, '{}'.format(max_size), quality=99)
-                except ThumbnailParseError:
+                except (ThumbnailParseError, IOError):
                     return None
+
             # no size specification matching the name found; give up
             return None
 
         if value:
             default_width = '191' # width of update images on akvo.org/seeithappen
-            default_thumb = get_thumbnail(value, default_width, quality=99)
             try:
+                default_thumb = get_thumbnail(value, default_width, quality=99)
                 request = self.context['request']
-            except KeyError:
+            except (ThumbnailParseError, IOError, KeyError):
                 return None
+
             # look for name(s) of thumb(s)
             image_thumb_name = request.GET.get('image_thumb_name')
             if image_thumb_name:


Test patch:
Repository: akvo/akvo-rsr

Issue:
Invite existing users gives an IntegrityError
See http://sentry.support.akvo-ops.org/rsr/live/group/797/.



Discussion:

Resolving patch:
diff --git a/akvo/rest/views/employment.py b/akvo/rest/views/employment.py
--- a/akvo/rest/views/employment.py
+++ b/akvo/rest/views/employment.py
@@ -6,10 +6,12 @@
 """
 
 from django.contrib.auth.models import Group
+from django.db import IntegrityError
 from rest_framework.decorators import api_view, permission_classes
 from rest_framework.exceptions import PermissionDenied
 from rest_framework.permissions import IsAuthenticated
 from rest_framework.response import Response
+from rest_framework import status
 from akvo.rsr.models import Employment
 from ..serializers import EmploymentSerializer
 from ..viewsets import BaseRSRViewSet
@@ -48,6 +50,10 @@ def set_group(request, pk=None, group_id=None):
         raise PermissionDenied
 
     employment.group = group
-    employment.save()
+    try:
+        employment.save()
+    except IntegrityError:
+        return Response({'status': 'group not set', 'error': 'Employment already exists.'},
+                        status=status.HTTP_400_BAD_REQUEST)
 
     return Response({'status': 'group set'})


Test patch:
Repository: akvo/akvo-rsr

Issue:
Invalid query parameters cause internal server error
```
  File "akvo/rest/filters.py", line 61, in filter_queryset
    queryset = getattr(queryset, param)(**args_or_kwargs)
```

In the new API filtering, you get an internal server error when the query is not correct, e.g.: http://rsr.akvo.org/rest/v1/project/?filter={'incorrect':'code'}. 

We should catch this and return the error message in a dict with detail as key. E.g. `{detail: 'Related Field got invalid lookup: incorrect'}`



Discussion:

Resolving patch:
diff --git a/akvo/rest/filters.py b/akvo/rest/filters.py
--- a/akvo/rest/filters.py
+++ b/akvo/rest/filters.py
@@ -7,8 +7,10 @@
 import ast
 
 from django.db.models import Q
+from django.core.exceptions import FieldError
 
-from rest_framework import filters
+from rest_framework import filters, status
+from rest_framework.exceptions import APIException
 
 
 class RSRGenericFilterBackend(filters.BaseFilterBackend):
@@ -57,10 +59,14 @@ def eval_query_value(request, key):
             args_or_kwargs = eval_query_value(request, param)
             if args_or_kwargs:
                 # filter and exclude are called with a dict kwarg, the _related methods with a list
-                if param in ['filter', 'exclude',]:
-                    queryset = getattr(queryset, param)(**args_or_kwargs)
-                else:
-                    queryset = getattr(queryset, param)(*args_or_kwargs)
+                try:
+                    if param in ['filter', 'exclude',]:
+                        queryset = getattr(queryset, param)(**args_or_kwargs)
+                    else:
+                        queryset = getattr(queryset, param)(*args_or_kwargs)
+
+                except FieldError as e:
+                    raise APIException("Error in request: {message}".format(message=e.message))
 
         # support for Q expressions, limited to OR-concatenated filtering
         if request.QUERY_PARAMS.get('q_filter1', None):


Test patch:
Repository: akvo/akvo-rsr

Issue:
Place updates on private projects
It should be possible to place (narrative) updates on private projects as well.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/models/__init__.py b/akvo/rsr/models/__init__.py
--- a/akvo/rsr/models/__init__.py
+++ b/akvo/rsr/models/__init__.py
@@ -385,6 +385,8 @@
 
 rules.add_perm('rsr.add_project', is_rsr_admin | is_org_admin)
 rules.add_perm('rsr.change_project', is_rsr_admin | is_org_admin | is_org_project_editor)
+rules.add_perm('rsr.view_project', is_rsr_admin | is_org_admin | is_org_user_manager |
+               is_org_project_editor | is_org_user)
 
 rules.add_perm('rsr.change_publishingstatus', is_rsr_admin | is_org_admin)
 
diff --git a/akvo/rsr/views/project.py b/akvo/rsr/views/project.py
--- a/akvo/rsr/views/project.py
+++ b/akvo/rsr/views/project.py
@@ -161,7 +161,7 @@ def _check_project_viewing_permissions(user, project):
     should be logged in and able to make changes to the project (e.g. be an admin of the project).
     """
     if not ((project.is_public and project.is_published()) or
-            user.has_perm('rsr.change_project', project)):
+            user.has_perm('rsr.view_project', project)):
         raise PermissionDenied
 
 


Test patch:
Repository: akvo/akvo-rsr

Issue:
Update actual values of parent through project editor
Currently, the actual values only of a parent project only get updated when an indicator update is placed in the 'My results' section. However, adding or changing the value in the project editor should give the same result.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/models/indicator.py b/akvo/rsr/models/indicator.py
--- a/akvo/rsr/models/indicator.py
+++ b/akvo/rsr/models/indicator.py
@@ -318,7 +318,7 @@ def __unicode__(self):
 
         return period_unicode
 
-    def save(self, *args, **kwargs):
+    def save(self, update_parents=True, *args, **kwargs):
         """Update the values of child periods, if a parent period is updated."""
         # Update period when it's edited
         if self.pk:
@@ -345,6 +345,13 @@ def save(self, *args, **kwargs):
 
                 child_period.save()
 
+            # Update parent actual values
+            if self.indicator.is_child_indicator() and self.actual_value != orig_period.actual_value and update_parents:
+                if self.parent_period().indicator.result.project.aggregate_children and \
+                        self.indicator.result.project.aggregate_to_parent:
+                    # self.parent_period().update_parent_actual_values(self.actual_value, orig_period.actual_value)
+                    self.parent_period().update_actual_value(self.actual_value, True)
+
         # Create a new period when it's added
         else:
             for child_indicator in self.indicator.child_indicators():
@@ -560,7 +567,7 @@ def update_actual_value(self, data, relative_data, comment=''):
             new_parent_value = str(-old_actual) if old_is_decimal or new_is_decimal else ''
 
         # Save new actual value of period
-        self.save(update_fields=['actual_value'])
+        self.save(update_fields=['actual_value'], update_parents=False)
 
         # Update parent period
         if parent and aggregate_to_parent and (old_is_decimal or new_is_decimal):
diff --git a/akvo/rsr/models/project.py b/akvo/rsr/models/project.py
--- a/akvo/rsr/models/project.py
+++ b/akvo/rsr/models/project.py
@@ -1322,9 +1322,9 @@ def import_results(self):
         import_failed = 0
         import_success = 1
 
-        if self.parents().count() == 1:
-            parent_project = self.parents()[0]
-        elif self.parents().count() == 0:
+        if self.parents_all().count() == 1:
+            parent_project = self.parents_all()[0]
+        elif self.parents_all().count() == 0:
             return import_failed, 'Project does not have a parent project'
         else:
             return import_failed, 'Project has multiple parent projects'


Test patch: