internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: fossasia/open-event-server

Issue:
Add exception handling if user provides wrong timezone 
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server

**Current behavior:**
<!-- Describe how the bug manifests. -->
Error with status code 500 is thrown

**Expected behavior:**
<!-- Describe what the behavior would be without the bug. -->
Throw proper validation error




Discussion:

Resolving patch:
diff --git a/app/api/events.py b/app/api/events.py
--- a/app/api/events.py
+++ b/app/api/events.py
@@ -1,4 +1,5 @@
 from datetime import datetime
+import pytz
 
 from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
 from marshmallow_jsonapi.flask import Schema, Relationship
@@ -61,6 +62,13 @@ def validate_date(self, data, original_data):
 
     @validates_schema
     def validate_timezone(self, data):
+        try:
+            timezone(data['timezone'])
+        except pytz.exceptions.UnknownTimeZoneError:
+            raise UnprocessableEntity({'pointer': '/data/attributes/timezone'},
+                                      "Unknown timezone: '{}'".
+                                      format(data['timezone']))
+
         if 'timezone' in data:
             offset = timezone(data['timezone']).utcoffset(
                 datetime.strptime('2014-12-01', '%Y-%m-%d')).seconds


Test patch:
Repository: fossasia/open-event-server

Issue:
Bug: sentry cannot catch internal server errors
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server

**Current behavior:**
<!-- Describe how the bug manifests. -->
sentry cannot catch internal server errors, because api frameworks catches each and every exception

**Expected behavior:**
<!-- Describe what the behavior would be without the bug. -->
Based on config variable, framework should not catch exceptions and instead app should handle them and return proper error response




Discussion:

Resolving patch:
diff --git a/app/__init__.py b/app/__init__.py
--- a/app/__init__.py
+++ b/app/__init__.py
@@ -17,7 +17,7 @@
 from os import environ
 from envparse import env
 import sys
-from flask import Flask
+from flask import Flask, json, make_response
 from app.settings import get_settings, get_setts
 from flask_migrate import Migrate, MigrateCommand
 from flask_script import Manager
@@ -26,6 +26,8 @@
 from datetime import timedelta
 from flask_cors import CORS
 from raven.contrib.flask import Sentry
+from flask_rest_jsonapi.errors import jsonapi_errors
+from flask_rest_jsonapi.exceptions import JsonApiException
 
 import sqlalchemy as sa
 
@@ -202,5 +204,16 @@ def update_sent_state(sender=None, body=None, **kwargs):
 scheduler.add_job(send_event_fee_notification_followup, 'cron', day=15)
 scheduler.start()
 
+
+@app.errorhandler(500)
+def internal_server_error(error):
+    if current_app.config['PROPOGATE_ERROR'] is True:
+        exc = JsonApiException({'pointer': ''}, str(error))
+    else:
+        exc = JsonApiException({'pointer': ''}, 'Unknown error')
+    return make_response(json.dumps(jsonapi_errors([exc.to_dict()])), exc.status,
+                         {'Content-Type': 'application/vnd.api+json'})
+
+
 if __name__ == '__main__':
     current_app.run()
diff --git a/config.py b/config.py
--- a/config.py
+++ b/config.py
@@ -54,11 +54,14 @@ class Config(object):
     SQLALCHEMY_DATABASE_URI = env('DATABASE_URL', default=None)
     SERVE_STATIC = env.bool('SERVE_STATIC', default=False)
     DATABASE_QUERY_TIMEOUT = 0.1
+    SENTRY_DSN = env('SENTRY_DSN', default=None)
+
+    # API configs
     SOFT_DELETE = True
     PROPOGATE_ERROR = env.bool('PROPOGATE_ERROR', default=False)
     DASHERIZE_API = True
+    API_PROPOGATE_UNCAUGHT_EXCEPTIONS = env.bool('API_PROPOGATE_UNCAUGHT_EXCEPTIONS', default=True)
     ETAG = True
-    SENTRY_DSN = env('SENTRY_DSN', default=None)
 
     if not SQLALCHEMY_DATABASE_URI:
         print('`DATABASE_URL` either not exported or empty')


Test patch:
Repository: fossasia/open-event-server

Issue:
IntegrityError: (psycopg2.IntegrityError) null value in column "name" violates not-null constraint
https://sentry.eventyay.com/eventyay/api/issues/14/

```
IntegrityError: (psycopg2.IntegrityError) null value in column "name" violates not-null constraint
DETAIL:  Failing row contains (392, null, null, null, null, null, 176).
CONTEXT:  SQL statement "update microlocations set name = NULL where name = '';update microlocations set room = NULL where room = '';"
PL/pgSQL function replace_in_table(text,text,text,boolean) line 23 at EXECUTE
 [SQL: "SELECT replace_in_table('microlocations', '''''', 'NULL', true)"]
(25 additional frame(s) were not displayed)
...
  File "sqlalchemy/engine/base.py", line 1189, in _execute_context
    context)
  File "sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception
    exc_info
  File "sqlalchemy/util/compat.py", line 203, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "sqlalchemy/engine/base.py", line 1182, in _execute_context
    context)
  File "sqlalchemy/engine/default.py", line 470, in do_execute
    cursor.execute(statement, parameters)

IntegrityError: (psycopg2.IntegrityError) null value in column "name" violates not-null constraint
DETAIL:  Failing row contains (392, null, null, null, null, null, 176).
CONTEXT:  SQL statement "update microlocations set name = NULL where name = '';update microlocations set room = NULL where room = '';"
PL/pgSQL function replace_in_table(text,text,text,boolean) line 23 at EXECUTE
 [SQL: "SELECT replace_in_table('microlocations', '''''', 'NULL', true)"]
```

> This error occurred when running the migrations against a clone of the production database


Discussion:

Resolving patch:
diff --git a/migrations/versions/1b9c8698c632_.py b/migrations/versions/1b9c8698c632_.py
--- a/migrations/versions/1b9c8698c632_.py
+++ b/migrations/versions/1b9c8698c632_.py
@@ -23,6 +23,7 @@ def __init__(self, name, sqltext):
 # function to find a and replace a string(the whole string should match, not substring)
 # across all the columns of a table.
 # If run is true then the function executes the query.
+# This will work only for nullable columns
 replace_in_table = ReplaceableObject(
     "replace_in_table(table_name text, original text, replacement text, run boolean)",
     """
@@ -42,6 +43,7 @@ def __init__(self, name, sqltext):
                 and (atttypid = 25
                 or atttypid = 1042
                 or atttypid = 1043)
+                and not attnotnull
             order by attnum
         loop
             q = format($fmt$%supdate %s set %s = %s where %s = %s;$fmt$,


Test patch:
Repository: fossasia/open-event-server

Issue:
Error in sizes in create_save_image_sizes() function in files helper
**I'm submitting a ...**  (check one with "x")
- [X] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server

**Current behavior:**
<!-- Describe how the bug manifests. -->
Thumbnail and icon sizes interchanged

**Expected behavior:**
<!-- Describe what the behavior would be without the bug. -->
Fix thumbnail and icon sizes


Discussion:

Resolving patch:
diff --git a/app/api/helpers/files.py b/app/api/helpers/files.py
--- a/app/api/helpers/files.py
+++ b/app/api/helpers/files.py
@@ -117,7 +117,7 @@ def create_save_image_sizes(image_file, image_sizes_type, unique_identifier=None
     try:
         image_sizes = ImageSizes.query.filter_by(type=image_sizes_type).one()
     except NoResultFound:
-        image_sizes = ImageSizes(image_sizes_type, 1300, 500, True, 100, 500, 200, True, 100, 75, 30, True, 100)
+        image_sizes = ImageSizes(image_sizes_type, 1300, 500, True, 100, 75, 30, True, 100, 500, 200, True, 100)
 
     # Get an unique identifier from uuid if not provided
     if unique_identifier is None:


Test patch:
Repository: fossasia/open-event-server

Issue:
ProgrammingError: (psycopg2.ProgrammingError) more than one row returned by a subquery used as an expression
https://sentry.eventyay.com/eventyay/api/issues/19/

```
ProgrammingError: (psycopg2.ProgrammingError) more than one row returned by a subquery used as an expression
 [SQL: 'UPDATE events SET event_sub_topic_id = (SELECT id FROM event_sub_topics WHERE event_sub_topics.name=events.event_sub_topic_id)']
(25 additional frame(s) were not displayed)
...
  File "sqlalchemy/engine/base.py", line 1189, in _execute_context
    context)
  File "sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception
    exc_info
  File "sqlalchemy/util/compat.py", line 203, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "sqlalchemy/engine/base.py", line 1182, in _execute_context
    context)
  File "sqlalchemy/engine/default.py", line 470, in do_execute
    cursor.execute(statement, parameters)

ProgrammingError: (psycopg2.ProgrammingError) more than one row returned by a subquery used as an expression
 [SQL: 'UPDATE events SET event_sub_topic_id = (SELECT id FROM event_sub_topics WHERE event_sub_topics.name=events.event_sub_topic_id)']
```

> This error occurred when running the migrations against a copy of the current production database


Discussion:

Resolving patch:
diff --git a/migrations/versions/52d175c3da98_.py b/migrations/versions/52d175c3da98_.py
--- a/migrations/versions/52d175c3da98_.py
+++ b/migrations/versions/52d175c3da98_.py
@@ -32,11 +32,11 @@ def upgrade():
     op.execute('INSERT INTO event_sub_topics(name, slug, event_topic_id) SELECT DISTINCT event_sub_topic_id, lower(replace(regexp_replace(event_sub_topic_id, \'& |,\', \'\', \'g\'), \' \', \'-\')), event_topic_id\
                FROM events where not exists (SELECT 1 FROM event_sub_topics where event_sub_topics.name=events.event_sub_topic_id) and event_sub_topic_id is not null')
     op.execute(
-        'UPDATE events SET event_sub_topic_id = (SELECT id FROM event_sub_topics WHERE event_sub_topics.name=events.event_sub_topic_id)')
+        'UPDATE events SET event_sub_topic_id = (SELECT id FROM event_sub_topics WHERE event_sub_topics.name=events.event_sub_topic_id ORDER BY id DESC LIMIT 1)')
     op.execute('ALTER TABLE events ALTER COLUMN event_sub_topic_id TYPE integer USING event_sub_topic_id::integer')
     op.create_foreign_key(None, 'events', 'event_sub_topics', ['event_sub_topic_id'], ['id'], ondelete='CASCADE')
     op.execute(
-        'UPDATE events_version SET event_sub_topic_id = (SELECT id FROM event_sub_topics WHERE event_sub_topics.name=events_version.event_sub_topic_id)')
+        'UPDATE events_version SET event_sub_topic_id = (SELECT id FROM event_sub_topics WHERE event_sub_topics.name=events_version.event_sub_topic_id ORDER BY id DESC LIMIT 1)')
     op.execute(
         'ALTER TABLE events_version ALTER COLUMN event_sub_topic_id TYPE integer USING event_sub_topic_id::integer')
     op.execute('UPDATE event_types set slug=replace(slug, \'/\', \'-\') where slug like \'%/%\'')


Test patch:
Repository: fossasia/open-event-server

Issue:
Fix event-sub-topic query in event-topic api
**I'm submitting a ...**  (check one with "x")
- [X] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server


Discussion:

Resolving patch:
diff --git a/app/api/event_topics.py b/app/api/event_topics.py
--- a/app/api/event_topics.py
+++ b/app/api/event_topics.py
@@ -74,8 +74,8 @@ def before_get_object(self, view_kwargs):
                 view_kwargs['id'] = None
 
         if view_kwargs.get('event_sub_topic_id'):
-            event_sub_topic = safe_query(self, EventSubTopic, 'id', view_kwargs['event_subtopic_id'],
-                                         'event_subtopic_id')
+            event_sub_topic = safe_query(self, EventSubTopic, 'id', view_kwargs['event_sub_topic_id'],
+                                         'event_sub_topic_id')
             if event_sub_topic.event_topic_id:
                 view_kwargs['id'] = event_sub_topic.event_topic_id
             else:


Test patch:
Repository: fossasia/open-event-server

Issue:
Enhance Permission Manager, Add Support for fetching multiple keys from view_kwargs
**I'm submitting a ...**  (check one with "x")
- [ ] bug report
- [x] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server





Discussion:

Resolving patch:
diff --git a/app/api/helpers/permission_manager.py b/app/api/helpers/permission_manager.py
--- a/app/api/helpers/permission_manager.py
+++ b/app/api/helpers/permission_manager.py
@@ -183,6 +183,15 @@ def create_event(view, view_args, view_kwargs, *args, **kwargs):
 }
 
 
+def is_multiple(data):
+    if type(data) is list:
+        return True
+    if type(data) is str:
+        if data.find(",") > 0:
+            return True
+    return False
+
+
 def permission_manager(view, view_args, view_kwargs, *args, **kwargs):
     """The function use to check permissions
 
@@ -232,12 +241,30 @@ def permission_manager(view, view_args, view_kwargs, *args, **kwargs):
             fetch_key_model = 'id'
             if 'fetch_key_url' in kwargs:
                 fetch_key_url = kwargs['fetch_key_url']
+
             if 'fetch_key_model' in kwargs:
                 fetch_key_model = kwargs['fetch_key_model']
-            try:
-                data = model.query.filter(getattr(model, fetch_key_model)
-                                          == view_kwargs[fetch_key_url]).one()
-            except NoResultFound, e:
+
+            if not is_multiple(model):
+                model = [model]
+
+            if is_multiple(fetch_key_url):
+                fetch_key_url = fetch_key_url.split(",")
+
+            found = False
+            for index, mod in enumerate(model):
+                if is_multiple(fetch_key_url):
+                    f_url = fetch_key_url[index]
+                else:
+                    f_url = fetch_key_url
+                try:
+                    data = mod.query.filter(getattr(mod, fetch_key_model) == view_kwargs[f_url]).one()
+                except NoResultFound, e:
+                    pass
+                else:
+                    found = True
+
+            if not found:
                 return NotFoundError({'source': ''}, 'Object not found.').respond()
 
             kwargs[fetch_as] = getattr(data, fetch)


Test patch:
Repository: fossasia/open-event-server

Issue:
Add option to access events organised by authenticated user
**I'm submitting a ...**  (check one with "x")
- [ ] bug report
- [x] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server

**Current behavior:**
Currently, there is no way to access events organized by an authenticated user.

**Expected behavior:**
There should be a relationship with user to the events he manages




Discussion:
@iamareebjamal This is already there with a get parameter, please try sending the same request `?withRole=1` 

Might be left to document. I will document to api docs.

**Edited**
This get parameter ensures that you get the event in events list if the user is associated with the event is any way like, track_organizer, organizers, registrar, etc.

Resolving patch:
diff --git a/app/api/__init__.py b/app/api/__init__.py
--- a/app/api/__init__.py
+++ b/app/api/__init__.py
@@ -115,7 +115,8 @@
 # events
 api.route(EventList, 'event_list', '/events', '/event-types/<int:event_type_id>/events',
           '/event-topics/<int:event_topic_id>/events',
-          '/event-sub-topics/<int:event_sub_topic_id>/events', '/discount-codes/<int:discount_code_id>/events')
+          '/event-sub-topics/<int:event_sub_topic_id>/events', '/discount-codes/<int:discount_code_id>/events',
+          '/users/<int:user_id>/events')
 api.route(EventDetail, 'event_detail', '/events/<int:id>', '/events/<identifier>',
           '/tickets/<int:ticket_id>/event', '/microlocations/<int:microlocation_id>/event',
           '/social-links/<int:social_link_id>/event',
diff --git a/app/api/events.py b/app/api/events.py
--- a/app/api/events.py
+++ b/app/api/events.py
@@ -1,4 +1,3 @@
-from datetime import datetime
 import pytz
 
 from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
diff --git a/create_db.py b/create_db.py
--- a/create_db.py
+++ b/create_db.py
@@ -4,9 +4,9 @@
 
 from app import current_app
 from flask_migrate import stamp
-from app.helpers.data import DataManager
 from app.models import db
 from populate_db import populate
+from tests.unittests.auth_helper import create_super_admin
 
 
 def _validate_email(email):
@@ -27,7 +27,7 @@ def create_default_user():
     _validate_email(email)
     password = getpass.getpass("Enter password for super_admin : ")
     _validate_password(password)
-    DataManager.create_super_admin(email, password)
+    create_super_admin(email, password)
 
 
 if __name__ == "__main__":


Test patch:
Repository: fossasia/open-event-server

Issue:
ProgrammingError: (psycopg2.ProgrammingError) column "is_featured" of relation "speaker" already exists
https://sentry.eventyay.com/eventyay/api/issues/22/

```
ProgrammingError: (psycopg2.ProgrammingError) column "is_featured" of relation "speaker" already exists
 [SQL: 'ALTER TABLE speaker ADD COLUMN is_featured BOOLEAN']
(25 additional frame(s) were not displayed)
...
  File "sqlalchemy/engine/base.py", line 1189, in _execute_context
    context)
  File "sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception
    exc_info
  File "sqlalchemy/util/compat.py", line 203, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "sqlalchemy/engine/base.py", line 1182, in _execute_context
    context)
  File "sqlalchemy/engine/default.py", line 470, in do_execute
    cursor.execute(statement, parameters)

ProgrammingError: (psycopg2.ProgrammingError) column "is_featured" of relation "speaker" already exists
 [SQL: 'ALTER TABLE speaker ADD COLUMN is_featured BOOLEAN']
```


Discussion:

Resolving patch:
diff --git a/migrations/versions/526dec6f4aff_.py b/migrations/versions/526dec6f4aff_.py
--- a/migrations/versions/526dec6f4aff_.py
+++ b/migrations/versions/526dec6f4aff_.py
@@ -15,16 +15,12 @@
 
 def upgrade():
     # commands auto generated by Alembic - please adjust! #
-    op.add_column('speaker', sa.Column('is_featured', sa.Boolean(), nullable=True))
-    op.drop_column('speaker', 'featured')
     op.drop_table('image_config')
     # end Alembic commands #
 
 
 def downgrade():
     # commands auto generated by Alembic - please adjust! #
-    op.add_column('speaker', sa.Column('featured', sa.BOOLEAN(), autoincrement=False, nullable=True))
-    op.drop_column('speaker', 'is_featured')
     op.create_table('image_config',
     sa.Column('id', sa.INTEGER(), nullable=False),
     sa.Column('page', sa.VARCHAR(), autoincrement=False, nullable=True),


Test patch:
Repository: fossasia/open-event-server

Issue:
GET request to  speakers with sessions results in 500 internal server error
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server

**Current behavior:**
<!-- Describe how the bug manifests. -->
`GET v1/events/<event_identifier>/speakers?include=sessions`
Results in 500 internal server error



Discussion:

Resolving patch:
diff --git a/app/api/speakers.py b/app/api/speakers.py
--- a/app/api/speakers.py
+++ b/app/api/speakers.py
@@ -71,6 +71,7 @@ class Meta:
                             related_view='v1.session_list',
                             related_view_kwargs={'speaker_id': '<id>'},
                             schema='SessionSchema',
+                            many=True,
                             type_='session')
 
 


Test patch:
Repository: fossasia/open-event-server

Issue:
PATCH request for event requires timezone attribute
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server

**Current behavior:**
PATCH request for event does not complete successfully if timezone attribute is skipped

**Expected behavior:**
PATCH request should not have any required attributes

**Steps to reproduce:**
Request : PATCH http://open-event-api.herokuapp.com/v1/events/106

Body:
````json
{
  "data": {
    "attributes": {
      "payment-currency": "INR"
    },
    "id": "106",
    "type": "event"
  }
}
````

Response:
````json
{
    "errors": [
        {
            "detail": "Unknown error",
            "source": {
                "pointer": ""
            },
            "status": 500,
            "title": "Unknown error"
        }
    ],
    "jsonapi": {
        "version": "1.0"
    }
}
````

But, if we include timezone:
````json
{
  "data": {
    "attributes": {
      "timezone": "Asia/Kolkata",
      "payment-currency": "INR"
    },
    "id": "106",
    "type": "event"
  }
}
````
It is completed successfuly


Discussion:

Resolving patch:
diff --git a/app/api/events.py b/app/api/events.py
--- a/app/api/events.py
+++ b/app/api/events.py
@@ -58,12 +58,21 @@ def validate_date(self, data, original_data):
             if 'ends_at' not in data:
                 data['ends_at'] = event.ends_at
 
+        if 'starts_at' not in data or 'ends_at' not in data:
+            raise UnprocessableEntity({'pointer': '/data/attributes/date'},
+                                      "enter required fields starts-at/ends-at")
+
         if data['starts_at'] >= data['ends_at']:
             raise UnprocessableEntity({'pointer': '/data/attributes/ends-at'},
                                       "ends-at should be after starts-at")
 
-    @validates_schema
-    def validate_timezone(self, data):
+    @validates_schema(pass_original=True)
+    def validate_timezone(self, data, original_data):
+        if 'id' in original_data['data']:
+            event = Event.query.filter_by(id=original_data['data']['id']).one()
+
+            if 'timezone' not in data:
+                data['timezone'] = event.timezone
         try:
             timezone(data['timezone'])
         except pytz.exceptions.UnknownTimeZoneError:
@@ -461,6 +470,7 @@ def before_get_object(self, view_kwargs):
                 view_kwargs['id'] = None
 
     def before_update_object(self, event, data, view_kwargs):
+
         if data.get('original_image_url') and data['original_image_url'] != event.original_image_url:
             uploaded_images = create_save_image_sizes(data['original_image_url'], 'event', event.id)
             data['original_image_url'] = uploaded_images['original_image_url']


Test patch: