internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: inducer/relate

Issue:
Datetime shown not localized.
As one of my student complaints, his browser is using en_US locale, however, the datetime shown in RELATE is in zh_CN format. Although he can understand Chinese, however, that will cause problem in other circumstances. 

The reason of problem lies in [this PR](https://github.com/inducer/relate/pull/39) I provided. It uses setting.LANGUAGE_CODE to determine the locale show in browser. 

I found I've made it too complicated in that PR, and it quite simple to modify that method using built-in method `django.utils.formats`, and the result is itself locale aware.

I'll create a PR later to fix it.



Discussion:

Resolving patch:
diff --git a/relate/utils.py b/relate/utils.py
--- a/relate/utils.py
+++ b/relate/utils.py
@@ -102,21 +102,29 @@ def local_now():
     return tz.localize(datetime.now())
 
 
-def format_datetime_local(datetime, format='medium'):
-    """Format the output of a datetime object to a localized string"""
-    from babel.dates import format_datetime
-    from django.conf import settings
-    from django.utils.translation.trans_real import to_locale
-    # See http://babel.pocoo.org/docs/api/dates/#date-and-time-formatting
-    # for customizing the output format.
-    try:
-        locale = to_locale(settings.LANGUAGE_CODE)
-    except ValueError:
-        locale = "en_US"
+def format_datetime_local(datetime, format='DATETIME_FORMAT'):
+    """
+    Format a datetime object to a localized string via python.
+
+    Note: The datetime rendered in template is itself locale aware.
+    A custom format must be defined in settings.py. 
+    When a custom format uses a same name with an existing built-in
+    format, it will be overrided by built-in format if l10n
+    is enabled.
+    """
+
+    fmt = format
 
-    result = format_datetime(datetime, format, locale=locale)
+    from django.utils import formats
+    from django.utils.dateformat import format
 
-    return result
+    try:
+        return formats.date_format(datetime, fmt)
+    except AttributeError:
+        try:
+            return format(datetime, fmt)
+        except AttributeError:
+            return formats.date_format(datetime, "DATETIME_FORMAT")
 
 
 # {{{ dict_to_struct


Test patch:
Repository: inducer/relate

Issue:
Automatically redirect back to previously visited page after login
In cases when users are required to login/register.



Discussion:
Yep, that would be nice. This should happen for all supported login routes. Step 1 in this would be for the login choice page to propagate the `?next=` GET parameter.


Resolving patch:
diff --git a/course/auth.py b/course/auth.py
--- a/course/auth.py
+++ b/course/auth.py
@@ -269,8 +269,14 @@ def get_user(self, user_id):
 
 # {{{ choice
 
-def sign_in_choice(request):
-    return render(request, "sign-in-choice.html")
+def sign_in_choice(request, redirect_field_name=REDIRECT_FIELD_NAME):
+    redirect_to = request.POST.get(redirect_field_name,
+                                   request.GET.get(redirect_field_name, ''))
+    next_uri=""
+    if redirect_to:
+        next_uri = "?%s=%s" % (redirect_field_name, redirect_to)
+
+    return render(request, "sign-in-choice.html", {"next_uri": next_uri})
 
 # }}}
 
@@ -318,11 +324,16 @@ def sign_in_by_user_pw(request, redirect_field_name=REDIRECT_FIELD_NAME):
 
     current_site = get_current_site(request)
 
+    next_uri = ""
+    if redirect_to:
+        next_uri = "?%s=%s" % (redirect_field_name, redirect_to)
+
     context = {
         'form': form,
         redirect_field_name: redirect_to,
         'site': current_site,
         'site_name': current_site.name,
+        'next_uri': next_uri,
     }
 
     return TemplateResponse(request, "course/login.html", context)
diff --git a/relate/settings.py b/relate/settings.py
--- a/relate/settings.py
+++ b/relate/settings.py
@@ -157,6 +157,7 @@
                 "django.template.context_processors.media",
                 "django.template.context_processors.static",
                 "django.template.context_processors.tz",
+                "django.template.context_processors.request",
                 "django.contrib.messages.context_processors.messages",
                 ) + RELATE_EXTRA_CONTEXT_PROCESSORS,
             }


Test patch:
Repository: inducer/relate

Issue:
csrf_token missing for grading form
The rendered form does not have csrf_token.

```
<form  class="form-horizontal relate-grading-form" method="post" > <div id="div_id_grade_percent" class="form-group"> <label for="id_grade_percent" class="control-label col-lg-2">
                Grade percent ...
</form>
```

The server starts with warning:

```
C:\Python27\lib\site-packages\django\template\defaulttags.py:65: UserWarning: A
{% csrf_token %} was used in a template, but the context did not provide the val
ue.  This is usually caused by not using RequestContext.
  "A {% csrf_token %} was used in a template, but the context "
```

and as a result, the post of the grading form result in failure.

```
Reason given for failure:
    CSRF token missing or incorrect.
```

I'm using Django 1.10 and the repo is up-to-date, and I just can not figure out what is the cause.



Discussion:

Resolving patch:
diff --git a/course/page/base.py b/course/page/base.py
--- a/course/page/base.py
+++ b/course/page/base.py
@@ -829,11 +829,9 @@ def grading_form_to_html(self, request, page_context, grading_form, grade_data):
                 "rubric": markup_to_html(page_context, self.page_desc.rubric)
                 }
 
-        from django.template import RequestContext
         from django.template.loader import render_to_string
         return render_to_string(
-                "course/human-feedback-form.html",
-                RequestContext(request, ctx))
+                "course/human-feedback-form.html", ctx, request)
 
     def grade(self, page_context, page_data, answer_data, grade_data):
         """This method is appropriate if the grade consists *only* of the
diff --git a/course/page/upload.py b/course/page/upload.py
--- a/course/page/upload.py
+++ b/course/page/upload.py
@@ -234,7 +234,6 @@ def form_to_html(self, request, page_context, form, answer_data):
                 answer_data["base64_data"],
                 )
 
-        from django.template import RequestContext
         from django.template.loader import render_to_string
         return render_to_string(
                 "course/file-upload-form.html", ctx, request)


Test patch:
Repository: inducer/relate

Issue:
FlowPageVisit bug?
After the instructor/TAs visited an attendant's flow pages, `FlowPageVisit` instances will be saved as if it is that attendant who had made those visits. I don't know if it is actually a bug or it is intended to be designed in this way. 

If it's a bug, then I think it's better that when impersonating, there should be no new instance saved or save the user who is impersonating as the `participant`.

_Update_:
I am wrong in that actually `FlowPageVisit` doesn't have a property recording the visitor, the `participant` property displayed in Admin is from the related `flow_session.participation.user`. I think it's better not to save those instances when the visit is make by course staff.

For impersonating, however, if the course staff submit answer for the attendants, is it possible to distinguish those visits from the actual visits made by the participants themselves?



Discussion:
I think we simply should add `user` and `impersonated_by` columns to the flow page visit. That way, we keep a record of the whole truth and can defer the decision of what to do with the facts to pieces of code actually using the information.


Resolving patch:
diff --git a/course/flow.py b/course/flow.py
--- a/course/flow.py
+++ b/course/flow.py
@@ -2032,6 +2032,9 @@ def post_flow_page(
                 page_context, fpctx.page_data.data,
                 form, request.FILES)
         answer_visit.is_submitted_answer = pressed_button == "submit"
+        if hasattr(request, "relate_impersonate_original_user"):
+            answer_visit.impersonated_by = \
+                request.relate_impersonate_original_user
         answer_visit.save()
 
         prev_answer_visits.insert(0, answer_visit)


Test patch:
Repository: inducer/relate

Issue:
Feature: Hide Institutional ID and/or Editor forms in profile
We are setting up RELATE (awesome btw!) and have no need for the institutional ID or editor parts of the profile. As a quick fix to reduce confusion with users, we are simply hiding the layouts by creating two settings:

    RELATE_SHOW_INST_ID_FORM = False
    RELATE_SHOW_EDITOR_FORM = False 

We appended the `adjust_layout` function by adding to display/hide based on these settings:

    if not settings.RELATE_SHOW_INST_ID_FORM:
        self.helper.layout[1].css_class = 'well hidden'
    if not settings.RELATE_SHOW_EDITOR_FORM:
        self.helper.layout[2].css_class = 'well hidden'

This seemed like the most straightforward approach to ensure that no form validation breaks along the way. If you think this is worthwhile, I can create a pull requestor modify it per your needs and then create the request.


Discussion:

Resolving patch:
diff --git a/course/auth.py b/course/auth.py
--- a/course/auth.py
+++ b/course/auth.py
@@ -859,6 +859,10 @@ def adjust_layout(is_inst_id_locked):
             else:
                 self.fields["institutional_id"].widget.\
                         attrs['disabled'] = True
+            if not settings.RELATE_SHOW_INST_ID_FORM:
+                self.helper.layout[1].css_class = 'well hidden'
+            if not settings.RELATE_SHOW_EDITOR_FORM:
+                self.helper.layout[2].css_class = 'well hidden'
 
         if self.instance.name_verified:
             self.fields["first_name"].widget.attrs['disabled'] = True
diff --git a/local_settings.example.py b/local_settings.example.py
--- a/local_settings.example.py
+++ b/local_settings.example.py
@@ -85,7 +85,7 @@
     )
 
 # If your email service do not allow nonauthorized sender, uncomment the following
-# statement and change the configurations above accordingly, noticing that all 
+# statement and change the configurations above accordingly, noticing that all
 # emails will be sent using the EMAIL_ settings above.
 #RELATE_EMAIL_SMTP_ALLOW_NONAUTHORIZED_SENDER = False
 
@@ -184,6 +184,10 @@
 # or you don't want to verfiy insitutional ID they submit.
 RELATE_EDITABLE_INST_ID_BEFORE_VERIFICATION = True
 
+# If set to False, these fields will be hidden in the user profile form.
+RELATE_SHOW_INST_ID_FORM = True
+RELATE_SHOW_EDITOR_FORM = True
+
 # }}}
 
 


Test patch:
Repository: inducer/relate

Issue:
DEFAULT_FROM_EMAIL is undocumented
@dzhuang It looks like `Course.get_from_email` uses `settings.DEFAULT_FROM_EMAIL`, but that setting doesn't occur in either `relate/settings.py` or `local_settings.example.py`, so it's not very discoverable and likely to lead to errors when users need to set up From-restricted email.

Could you take a look?
DEFAULT_FROM_EMAIL is undocumented
@dzhuang It looks like `Course.get_from_email` uses `settings.DEFAULT_FROM_EMAIL`, but that setting doesn't occur in either `relate/settings.py` or `local_settings.example.py`, so it's not very discoverable and likely to lead to errors when users need to set up From-restricted email.

Could you take a look?


Discussion:
Sorry, it's my fault. I'll submit a PR/MR along with tests to fix it. 
Sorry, it's my fault. I'll submit a PR/MR along with tests to fix it. 

Resolving patch:
diff --git a/course/models.py b/course/models.py
--- a/course/models.py
+++ b/course/models.py
@@ -235,7 +235,9 @@ def get_from_email(self):
         if settings.RELATE_EMAIL_SMTP_ALLOW_NONAUTHORIZED_SENDER:
             return self.from_email
         else:
-            return settings.DEFAULT_FROM_EMAIL
+            return getattr(
+                settings, "NOTIFICATION_EMAIL_FROM",
+                settings.ROBOT_EMAIL_FROM)
 
     def get_reply_to_email(self):
         # this functionality need more fields in Course model,


Test patch:
Repository: inducer/relate

Issue:
Login/logout redirects to root, not home route
Code like [this](https://github.com/inducer/relate/blob/4b405525b9d9b5859f671ab3ece897e1555952a5/course/auth.py#L414-L431) assumes that the application is mounted at domain root, while in my case it isn't.

Before redirecting, we should check if it's empty and in the case, set it to the route `relate-home`.


Discussion:
Could you put together a pull request?

Resolving patch:
diff --git a/course/auth.py b/course/auth.py
--- a/course/auth.py
+++ b/course/auth.py
@@ -421,7 +421,7 @@ def sign_in_by_user_pw(request, redirect_field_name=REDIRECT_FIELD_NAME):
             # Ensure the user-originating redirection url is safe.
             if not is_safe_url(url=redirect_to, host=request.get_host(),
                                require_https=request.is_secure()):
-                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
+                redirect_to = resolve_url("relate-home")
 
             user = form.get_user()
 
diff --git a/relate/settings.py b/relate/settings.py
--- a/relate/settings.py
+++ b/relate/settings.py
@@ -215,7 +215,6 @@
 # }}}
 
 LOGIN_URL = "relate-sign_in_choice"
-LOGIN_REDIRECT_URL = "/"
 
 # Static files (CSS, JavaScript, Images)
 # https://docs.djangoproject.com/en/dev/howto/static-files/


Test patch:
diff --git a/tests/test_auth.py b/tests/test_auth.py
--- a/tests/test_auth.py
+++ b/tests/test_auth.py
@@ -712,7 +712,7 @@ def test_user_pw_enabled_sign_in_view_anonymous(self):
             resp = self.post_sign_in_by_user_pw(data=self.get_sign_in_data())
             self.assertSessionHasUserLoggedIn()
             self.assertEqual(resp.status_code, 302)
-            self.assertRedirects(resp, settings.LOGIN_REDIRECT_URL,
+            self.assertRedirects(resp, reverse("relate-home"),
                                  fetch_redirect_response=False)
 
     @override_settings(RELATE_SIGN_IN_BY_USERNAME_ENABLED=False)
Repository: inducer/relate

Issue:
Create recurring event: cannot leave ordinal unspecified twice
For example:

* Create 20 weekly events `office_andreas`, leaving the ordinal unspecified, from (say) a Wednesday at 3:30pm
* Create 20 weekly events `office_andreas`, again leaving the ordinal unspecified, from (say) a Friday at 3:30pm
* "An event with this kind, ordinal, and course already exists." (Paraphrasing from German.)

@dzhuang I distinctly recall that this worked at some point...


Discussion:
I remember I added the constraint that event without ordinal should be unique (at course level). So did you mean I was wrong? If so, (sorry) I'll revert those changes.
P.S., you seemed to agree [ordinal-less events should be unique](https://github.com/inducer/relate/blob/master/course/models.py#L346-L353) in 32b4578236bbd820a04a39594bb80ec0c23dff67.

Resolving patch:
diff --git a/course/calendar.py b/course/calendar.py
--- a/course/calendar.py
+++ b/course/calendar.py
@@ -128,6 +128,7 @@ class EventAlreadyExists(Exception):
 def _create_recurring_events_backend(course, time, kind, starting_ordinal, interval,
         count, duration_in_minutes, all_day, shown_in_calendar):
     ordinal = starting_ordinal
+    assert ordinal is not None
 
     import datetime
 
@@ -143,14 +144,13 @@ def _create_recurring_events_backend(course, time, kind, starting_ordinal, inter
         if duration_in_minutes:
             evt.end_time = evt.time + datetime.timedelta(
                     minutes=duration_in_minutes)
-        try:
-            evt.save()
-        except Exception as e:
-            if isinstance(e, ValidationError) and "already exists" in str(e):
-                raise EventAlreadyExists(
-                    _("'%(exist_event)s' already exists")
-                    % {'exist_event': evt})
-            raise e
+
+        if Event.objects.filter(course=course, kind=kind, ordinal=ordinal).count():
+            raise EventAlreadyExists(
+                _("'%(exist_event)s' already exists")
+                % {'exist_event': evt})
+
+        evt.save()
 
         date = time.date()
         if interval == "weekly":


Test patch:
Repository: inducer/relate

Issue:
Update pysaml2 to 4.6.0 (or higher) to fix CVE-2017-1000246
* https://nvd.nist.gov/vuln/detail/CVE-2017-1000246
* https://github.com/IdentityPython/pysaml2/issues/417

Currently blocked on https://github.com/knaperek/djangosaml2/issues/129.




Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -4,10 +4,11 @@
 from setuptools import setup, find_packages
 
 # This script (for now) is only intended to install the 'relate' content helper
-# script.  relate-validate. Its use is not needed for (and unrelated to)
-# deploying RELATE as a web service.
+# script. Its use is not needed for (and unrelated to) deploying RELATE as a
+# web service.
 
-# Use 'pip install -r requirements.txt' first to install prerequisites.
+# Use 'pip install -r requirements.txt' to install prerequisites for RELATE as
+# a web service.
 
 setup(name="relate-courseware",
       version="2016.1",


Test patch:
Repository: inducer/relate

Issue:
Assertion failure in InlineMultiQuestion
Just got this traceback:

```
Traceback:

File "/home/andreas/my-relate-env3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/home/andreas/my-relate-env3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/home/andreas/my-relate-env3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "./course/utils.py" in wrapper
  792.             response = f(pctx, *args, **kwargs)

File "./course/flow.py" in view_flow_page
  1983.                 answer_data, grade_data)

File "./course/page/inline.py" in correct_answer
  862.                     .get_correct_answer_text(page_context)

File "./course/page/inline.py" in get_correct_answer_text
  358.         assert unspec_correct_answer_text

Exception Type: AssertionError at /course/cs101-fa18/flow-session/427261/6/
```

Looking at the code:

https://github.com/inducer/relate/blob/b0e64c93799cb8b603880f13d5d2c07f4117d06a/course/page/inline.py#L352-L358

it is not clear to me how that can happen, especially given the check immediately above that:

https://github.com/inducer/relate/blob/b0e64c93799cb8b603880f13d5d2c07f4117d06a/course/page/inline.py#L338-L345

@dzhuang, any idea?

FWIW, I've asked the TA in question to supply details if he has them.


Discussion:
`unspec_correct_answer_text` is not `None` but `0` ? Will `assert unspec_correct_answer_text is not None` be a workround?

Resolving patch:
diff --git a/course/page/inline.py b/course/page/inline.py
--- a/course/page/inline.py
+++ b/course/page/inline.py
@@ -355,7 +355,7 @@ def get_correct_answer_text(self, page_context):
             if unspec_correct_answer_text is not None:
                 break
 
-        assert unspec_correct_answer_text
+        assert unspec_correct_answer_text is not None
         return ("%s%s%s"
                 % (getattr(self.answers_desc, "prepended_text", "").strip(),
                    unspec_correct_answer_text,


Test patch:
Repository: mozilla/pontoon

Issue:
Added pontoon hook for Django.
This implements Pontoon hook for Django.



Discussion:
@mathjazz This is not yet ready for merge. I have created this pull request so that we could discuss on this and improve it before it is merged.


Resolving patch:
diff --git a/pontoon/base/views.py b/pontoon/base/views.py
--- a/pontoon/base/views.py
+++ b/pontoon/base/views.py
@@ -385,6 +385,7 @@ def get_translation_history(request):
             "user": "Imported" if u is None else u.name_or_email,
             "uid": "" if u is None else u.id,
             "username": "" if u is None else u.username,
+            "user_gravatar_url_small": "" if u is None else u.gravatar_url(44),
             "date": t.date.strftime('%b %d, %Y %H:%M'),
             "date_iso": t.date.isoformat(),
             "approved_user": User.display_name_or_blank(t.approved_user),


Test patch:
diff --git a/frontend/src/modules/history/components/Translation.test.js b/frontend/src/modules/history/components/Translation.test.js
--- a/frontend/src/modules/history/components/Translation.test.js
+++ b/frontend/src/modules/history/components/Translation.test.js
@@ -141,9 +141,9 @@ describe('<TranslationBase>', () => {
             />);
 
             const link = wrapper.find('a');
-            expect(link).toHaveLength(1);
-            expect(link.props().children).toEqual('Sarevok');
-            expect(link.props().href).toEqual('/contributors/id_Sarevok');
+            expect(link).toHaveLength(2);
+            expect(link.at(1).props().children).toEqual('Sarevok');
+            expect(link.at(1).props().href).toEqual('/contributors/id_Sarevok');
         });
 
         it('returns no link when the author is not known', () => {
Repository: mozilla/pontoon

Issue:
Redirected to a non-existing page while tring to translate to en-US
## Description

When I try to translate an application to `en-US`, I am redirected (`301`) to a non-existing page:

![image](https://user-images.githubusercontent.com/971438/144014809-d5545965-1c2f-4c55-86f6-dd2160627e02.png)

→ `/en-US/my-project/` is redirected to `/my-project/`

## Steps to reproduce

* Add the `en-US` locale to a project
* Browse project's language
* Click on English (en-US)
* → 404

## More...

This seems to be caused by some legacy code in `pontoon/urls.py:26`:

```python
urlpatterns = [
    # Legacy: Locale redirect for compatibility with i18n ready URL scheme
    path("en-US<path:url>", RedirectView.as_view(url="%(url)s", permanent=True)),
```

Removing this line fixes the problem and does not seem to cause additional issues (I am still testing on a production instance).

* This issue may be related to → #2192 
* Another issue to look at about `en-US` locale → #2260



Discussion:

Resolving patch:
diff --git a/pontoon/urls.py b/pontoon/urls.py
--- a/pontoon/urls.py
+++ b/pontoon/urls.py
@@ -22,8 +22,6 @@ class LocaleConverter(StringConverter):
 server_error_view = TemplateView.as_view(template_name="500.html")
 
 urlpatterns = [
-    # Legacy: Locale redirect for compatibility with i18n ready URL scheme
-    path("en-US<path:url>", RedirectView.as_view(url="%(url)s", permanent=True)),
     # Redirect legacy Aurora projects
     path(
         "projects/firefox-aurora/<path:url>",


Test patch: