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

Issue:
Make send_email_task (task) asynchronous
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->

Make send_email_task (task) asynchronous

**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->

**Stacktrace**
<!-- If applicable, add stacktrace to help explain your problem. -->

**Additional details (please complete the following information):**
 - OS: [e.g. MacOS, Ubuntu, CentOS]
 - Python Version [e.g. `3.5`, `3.6`]
 - `HEAD` Commit hash [e.g. `4629c62`]

**Additional context**
<!-- Add any other context about the problem here. -->

**Others can claim**


Discussion:
Please guide me on this issue. I want to work on it. @bhaveshAn 

Resolving patch:
diff --git a/app/api/helpers/mail.py b/app/api/helpers/mail.py
--- a/app/api/helpers/mail.py
+++ b/app/api/helpers/mail.py
@@ -66,8 +66,7 @@ def send_email(to, action, subject, html):
                     "Content-Type": "application/json"
                 }
                 from .tasks import send_email_task
-                # TODO use of send_email_task.delay() to make it asynchronous
-                send_email_task(payload, headers)
+                send_email_task.delay(payload, headers)
 
         # record_mail(to, action, subject, html)
         mail = Mail(


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

Issue:
Error in models/access_code.py
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
in the __repr__() function of this file, in place of `self.id`, it should be `self.code`

**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->

**Stacktrace**
<!-- If applicable, add stacktrace to help explain your problem. -->

**Additional details (please complete the following information):**
 - OS: [e.g. MacOS, Ubuntu, CentOS]
 - Python Version [e.g. `3.5`, `3.6`]
 - `HEAD` Commit hash [e.g. `4629c62`]

**Additional context**
<!-- Add any other context about the problem here. -->
i've filed a PR for this.


Discussion:

Resolving patch:
diff --git a/app/models/access_code.py b/app/models/access_code.py
--- a/app/models/access_code.py
+++ b/app/models/access_code.py
@@ -57,7 +57,7 @@ def get_service_name():
         return 'access_code'
 
     def __repr__(self):
-        return '<AccessCode %r>' % self.id
+        return '<AccessCode %r>' % self.code
 
     def __str__(self):
         return self.__repr__()


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

Issue:
Docstring in admin_sales/utils.py
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
correction in docstring of admin_sales/utils.py

**Additional context**
<!-- Add any other context about the problem here. -->
i've filed a PR for this


Discussion:

Resolving patch:
diff --git a/app/api/admin_sales/utils.py b/app/api/admin_sales/utils.py
--- a/app/api/admin_sales/utils.py
+++ b/app/api/admin_sales/utils.py
@@ -16,6 +16,8 @@ def status_summary(orders, status):
 
 
 def summary(orders):
-    "Returns sales as dictionary for all status codes"
+    """
+    Returns sales as dictionary for all status codes
+    """
     status_codes = ['placed', 'completed', 'pending']
     return {s: status_summary(orders, s) for s in status_codes}
diff --git a/app/api/full_text_search/events.py b/app/api/full_text_search/events.py
--- a/app/api/full_text_search/events.py
+++ b/app/api/full_text_search/events.py
@@ -13,7 +13,9 @@
 
 
 def to_dict(response):
-    "Converts elasticsearch responses to dicts for serialization"
+    """
+    Converts elasticsearch responses to dicts for serialization
+    """
     r = response.to_dict()
     r['meta'] = response.meta.to_dict()
 


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

Issue:
Corrections in autodeploy
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->

- unlike the steps mentioned in the docs, the autodeploy script doesn't work unless the workdir and config file is provided via the command line

- Also the required `PyYAML` library is missing from requirements.txt. 

- `yaml.load` should be `yaml.safe_load` to avoid dangerous file parsing and also to avoid codacy issues. (refer to this [link](https://security.openstack.org/guidelines/dg_avoid-dangerous-input-parsing-libraries.html))

**To Reproduce**
Steps to reproduce the behavior:
Try running `python3 autodeploy/main.py`

**Additional context**
<!-- Add any other context about the problem here. -->
Yes, I'm working on it



Discussion:

Resolving patch:
diff --git a/autodeploy/main.py b/autodeploy/main.py
--- a/autodeploy/main.py
+++ b/autodeploy/main.py
@@ -57,7 +57,7 @@ def update_all_projects(projects):
     config_file = args.config
 
     with open(config_file, 'r') as ymlfile:
-        config = yaml.load(ymlfile)
+        config = yaml.safe_load(ymlfile)
 
 
     projects = [get_auto_updater(cwd, n, config[n]) for n in config]


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

Issue:
Missing else condition in line 142 of api/users.py
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
In `app/api/users.py` at line 142, there should be a condition for else case

**Additional context**
<!-- Add any other context about the problem here. -->
i've filed a PR for this


Discussion:

Resolving patch:
diff --git a/app/api/users.py b/app/api/users.py
--- a/app/api/users.py
+++ b/app/api/users.py
@@ -140,6 +140,8 @@ def before_get_object(self, view_kwargs):
                                            'users_events_role_id')
             if users_events_role.user_id is not None:
                 view_kwargs['id'] = users_events_role.user_id
+            else:
+                view_kwargs['id'] = None
 
         if view_kwargs.get('speaker_id') is not None:
             speaker = safe_query(self, Speaker, 'id', view_kwargs['speaker_id'], 'speaker_id')


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

Issue:
Initialisation are missing in models/event_orga.py
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
in models/event_orga.py, initialisation of `starts_at` and `payment_currency` is missing

**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->

**Stacktrace**
<!-- If applicable, add stacktrace to help explain your problem. -->

**Additional details (please complete the following information):**
 - OS: [e.g. MacOS, Ubuntu, CentOS]
 - Python Version [e.g. `3.5`, `3.6`]
 - `HEAD` Commit hash [e.g. `4629c62`]

**Additional context**
<!-- Add any other context about the problem here. -->
I'll be filing a PR for this. Please review it :smiley: 


Discussion:

Resolving patch:
diff --git a/app/models/event_orga.py b/app/models/event_orga.py
--- a/app/models/event_orga.py
+++ b/app/models/event_orga.py
@@ -1,6 +1,6 @@
 from app.models import db
 from app.models.base import SoftDeletionModel
-
+from datetime import datetime
 
 class EventOrgaModel(SoftDeletionModel):
     """Event Orga object table"""
@@ -13,9 +13,12 @@ class EventOrgaModel(SoftDeletionModel):
     payment_currency = db.Column(db.String, nullable=False)
 
     def __init__(self,
-                 name=None):
+                 name=None,
+                 payment_currency=None):
 
         self.name = name
+        self.starts_at = datetime.utcnow()
+        self.payment_currency = payment_currency
 
     def __repr__(self):
         return '<EventOrgaModel %r>' % self.name


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

Issue:
Docstrings in helpers/third_party_auth.py are incorrect
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
The docstrings for twiiter is written as "facebook credentials" while the docstring for Instagram are missing.

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
The docstrings should be correct

**Additional context**
<!-- Add any other context about the problem here. -->
I'm working on this one



Discussion:

Resolving patch:
diff --git a/app/api/helpers/third_party_auth.py b/app/api/helpers/third_party_auth.py
--- a/app/api/helpers/third_party_auth.py
+++ b/app/api/helpers/third_party_auth.py
@@ -77,7 +77,7 @@ def get_user_info(cls):
 
 
 class TwitterOAuth(object):
-    """Facebook Credentials"""
+    """Twitter Credentials"""
     TW_AUTH_URI = 'https://api.twitter.com/oauth/authorize'
     TW_REQUEST_TOKEN_URI = 'https://api.twitter.com/oauth/request_token'
     TW_ACCESS_TOKEN = "https://api.twitter.com/oauth/access_token"
@@ -126,6 +126,7 @@ def get_authorized_client(self, oauth_verifier, oauth_token):
 
 
 class InstagramOAuth(object):
+    """Instagram Credentials"""
     INSTAGRAM_OAUTH_URI = "https://api.instagram.com/oauth/authorize/"
     INSTAGRAM_TOKEN_URI = "https://api.instagram.com/oauth/access_token"
     SCOPE = ['basic', 'public_content']


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

Issue:
Adding dredd hooks for event locations
**Is your feature request related to a problem? Please describe.**
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
dredd hooks for event locations are missing

**Describe the solution you'd like**
<!-- A clear and concise description of what you want to happen. -->
adding dredd hooks for event locations

**Describe alternatives you've considered**
<!-- A clear and concise description of any alternative solutions or features you've considered. -->

**Additional context**
<!-- Add any other context or screenshots about the feature request here. -->
i'm working on this one


Discussion:

Resolving patch:
diff --git a/app/factories/event_location.py b/app/factories/event_location.py
new file mode 100644
--- /dev/null
+++ b/app/factories/event_location.py
@@ -0,0 +1,13 @@
+import factory
+
+import app.factories.common as common
+from app.models.event_location import db, EventLocation
+
+
+class EventLocationFactory(factory.alchemy.SQLAlchemyModelFactory):
+    class Meta:
+        model = EventLocation
+        sqlalchemy_session = db.session
+
+    name = common.string_
+    slug = common.slug_


Test patch:
diff --git a/tests/hook_main.py b/tests/hook_main.py
--- a/tests/hook_main.py
+++ b/tests/hook_main.py
@@ -15,6 +15,7 @@
 
 # imports from factories
 
+from app.factories.event_location import EventLocationFactory
 from app.factories.custom_system_role import CustomSysRoleFactory
 from app.factories.panel_permission import PanelPermissionFactory
 from app.factories.user import UserFactory
@@ -3297,7 +3298,7 @@ def file_upload_post(transaction):
     transaction['skip'] = True
 
 
-# ------------------------- Event Locationss -------------------------
+# ------------------------- Event Locations -------------------------
 @hooks.before("Event Locations > Event Locations Collection > List All Event Locations")
 def event_location_get_list(transaction):
     """
@@ -3305,6 +3306,10 @@ def event_location_get_list(transaction):
     :param transaction:
     :return:
     """
+    with stash['app'].app_context():
+        event_location = EventLocationFactory()
+        db.session.add(event_location)
+        db.session.commit()
 
 
 # ------------------------- Event Types -------------------------
Repository: fossasia/open-event-server

Issue:
Settings don't refresh on PATCH
**Describe the bug**
Settings are cached in memory and never again fetched from DB, even when they are patched. 

- Refresh settings on PATCH request

Secondly, if someone edits settings from DB, there is no way to refresh them. Call for discussion if this should be left that way. Cache should be expired after a period of time, or there should be an endpoint to explicitly refresh in memory settings


Discussion:

Resolving patch:
diff --git a/app/api/settings.py b/app/api/settings.py
--- a/app/api/settings.py
+++ b/app/api/settings.py
@@ -7,6 +7,7 @@
 from app.api.schema.settings import SettingSchemaAdmin, SettingSchemaNonAdmin, SettingSchemaPublic
 from app.models import db
 from app.models.setting import Setting
+from app.settings import refresh_settings
 
 
 class Environment:
@@ -43,3 +44,7 @@ def before_get(self, args, kwargs):
     schema = SettingSchemaAdmin
     data_layer = {'session': db.session,
                   'model': Setting}
+
+    def after_patch(self, result):
+        # Update settings cache after PATCH
+        refresh_settings()
diff --git a/app/settings/__init__.py b/app/settings/__init__.py
--- a/app/settings/__init__.py
+++ b/app/settings/__init__.py
@@ -6,11 +6,11 @@
 from app.models.setting import Setting, Environment
 
 
-def get_settings():
+def get_settings(from_db=False):
     """
     Use this to get latest system settings
     """
-    if 'custom_settings' in current_app.config:
+    if not from_db and 'custom_settings' in current_app.config:
         return current_app.config['custom_settings']
     s = Setting.query.order_by(desc(Setting.id)).first()
     if s is None:
@@ -22,6 +22,11 @@ def get_settings():
     return current_app.config['custom_settings']
 
 
+def refresh_settings():
+    # Force fetch settings from DB, thus refreshing it
+    get_settings(from_db=True)
+
+
 def get_setts():
     return Setting.query.order_by(desc(Setting.id)).first()
 


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

Issue:
Set up logging correctly
Currently, logging is hardcoded in the app and never really used. Logging should be used almost on every action with proper label as:

- trace
- debug
- info
- warn
- error

Right now, logger is hardcoded to show ERROR only. This needs to be configurable through the command line. 

Also, I think default should be `INFO` or even `DEBUG` for the app itself and warn for other 3rd party libraries. 


Discussion:
Hi @iamareebjamal, Can you assign it to me? I would like to work on this issue. 
I am new to logging for a big code-base, so I have to do some research.  Can you please provide some useful links.
@makkoncept Feel free to take this issue. 
Can I work on this issue?

Resolving patch:
diff --git a/app/__init__.py b/app/__init__.py
--- a/app/__init__.py
+++ b/app/__init__.py
@@ -1,4 +1,5 @@
 from celery.signals import after_task_publish
+from logging.config import dictConfig
 import logging
 import os.path
 from envparse import env
@@ -93,8 +94,28 @@ def create_app():
     app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
     app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static'
 
-    app.logger.addHandler(logging.StreamHandler(sys.stdout))
-    app.logger.setLevel(logging.ERROR)
+    app.logger = logging.getLogger(__name__)
+
+    dictConfig({
+        'version': 1,
+        'handlers': {
+            'console': {
+                'level': logging.WARN,
+                'class': 'logging.StreamHandler',
+                'stream': 'ext://sys.stdout'
+            }
+        },
+        'loggers': {
+            '': {
+                'handlers': ['console'],
+                'level': logging.WARN
+            },
+            'default': {
+                'handlers': ['console'],
+                'level': logging.INFO
+            }
+        }
+    })
 
     # set up jwt
     app.config['JWT_AUTH_USERNAME_KEY'] = 'email'


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

Issue:
Adding seed data for development of custom placeholders
**Parent Issue**
#4477 

**Is your feature request related to a problem? Please describe.**
According to the parent issue 4477, this aims to add seed data of custom placeholders for development

**Describe the solution you'd like**
<!-- A clear and concise description of what you want to happen. -->
adding seed data for custom placeholder

**Additional context**
<!-- Add any other context or screenshots about the feature request here. -->
I'm working on it


Discussion:

Resolving patch:
diff --git a/populate_db.py b/populate_db.py
--- a/populate_db.py
+++ b/populate_db.py
@@ -40,6 +40,9 @@
 # EventLocation
 from app.models.event_location import EventLocation
 
+# Custom Placeholder
+from app.models.custom_placeholder import CustomPlaceholder
+
 # User Permissions
 from app.models.user_permission import UserPermission
 SALES = 'sales'
@@ -174,7 +177,7 @@ def create_event_sub_topics():
      "Religion & Spirituality": ["Mysticism and Occult"],
      "Government & Politics": ["Non-partisan"]
     }
-    eventopics=db.session.query(EventTopic).all()
+    eventopics = db.session.query(EventTopic).all()
     for keysub_topic in event_sub_topic:
         for subtopic in event_sub_topic[keysub_topic]:
             get_or_create(EventSubTopic, name=subtopic, event_topic_id=next(x for x in eventopics if x.name==keysub_topic).id)
@@ -311,6 +314,15 @@ def create_admin_message_settings():
             )
 
 
+def create_custom_placeholders():
+    custom_placeholder, _ = get_or_create(
+        CustomPlaceholder, name='Hills',
+        original_image_url='https://www.w3schools.com/html/pic_mountain.jpg',
+        event_sub_topic_id=1
+    )
+    db.session.add(custom_placeholder)
+
+
 def populate():
     """
     Create defined Roles, Services and Permissions.
@@ -347,6 +359,8 @@ def populate():
     create_event_locations()
     print('Creating admin message settings...')
     create_admin_message_settings()
+    print('Creating custom placeholders...')
+    create_custom_placeholders()
 
 
 def populate_without_print():
@@ -369,6 +383,7 @@ def populate_without_print():
     create_event_types()
     create_event_locations()
     create_admin_message_settings()
+    create_custom_placeholders()
 
     db.session.commit()
 


Test patch:
diff --git a/tests/hook_main.py b/tests/hook_main.py
--- a/tests/hook_main.py
+++ b/tests/hook_main.py
@@ -3658,7 +3658,7 @@ def event_sub_topic_custom_placeholder_get_detail(transaction):
         event_sub_topic = EventSubTopicFactory()
         db.session.add(event_sub_topic)
 
-        custom_placeholder = CustomPlaceholderFactory(event_sub_topic_id=1)
+        custom_placeholder = CustomPlaceholderFactory()
         db.session.add(custom_placeholder)
         db.session.commit()
Repository: fossasia/open-event-server

Issue:
Read from environment variables when creating the super admin user
**Is your feature request related to a problem? Please describe.**
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
When deploying on Kubernetes or Openshift, the super admin account points to the default one, that is hardcoded in manage.py file. https://github.com/fossasia/open-event-server/blob/fix-celery/manage.py#L89

**Describe the solution you'd like**
<!-- A clear and concise description of what you want to happen. -->
Extend manage.py file to read environment variables on database initialization. If the user doesn't provide these variables then use the default ones.



Discussion:
I would like to work on this issue. 
Go ahead

Resolving patch:
diff --git a/manage.py b/manage.py
--- a/manage.py
+++ b/manage.py
@@ -79,16 +79,18 @@ def initialize_db(credentials):
                 print("[LOG] Could not create tables. Either database does not exist or tables already created")
             if populate_data:
                 credentials = credentials.split(":")
-                create_super_admin(credentials[0], credentials[1])
+                admin_email = os.environ.get('SUPER_ADMIN_EMAIL', credentials[0])
+                admin_password = os.environ.get('SUPER_ADMIN_PASSWORD', credentials[1])
+                create_super_admin(admin_email, admin_password)
                 populate()
         else:
             print("[LOG] Tables already exist. Skipping data population & creation.")
 
 
 @manager.command
-def prepare_kubernetes_db():
+def prepare_kubernetes_db(credentials='open_event_test_user@fossasia.org:fossasia'):
     with app.app_context():
-        initialize_db('open_event_test_user@fossasia.org:fossasia')
+        initialize_db(credentials)
 
 
 if __name__ == "__main__":


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

Issue:
Orders API: Remove constraint for a user to be verified in order to place an order.
Parent issue #5546 


Discussion:

Resolving patch:
diff --git a/app/api/orders.py b/app/api/orders.py
--- a/app/api/orders.py
+++ b/app/api/orders.py
@@ -50,10 +50,6 @@ def before_post(self, args, kwargs, data=None):
         """
         require_relationship(['event'], data)
 
-        if not current_user.is_verified:
-            raise ForbiddenException({'source': ''},
-                                     "Only verified accounts can place orders")
-
         # Create on site attendees.
         if request.args.get('onsite', False):
             create_onsite_attendees_for_order(data)


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

Issue:
Allow access to discount codes to non-registered users
Currently, users who visit a discount code link are denied access to the discount on the frontend, since the API requires a jwt token to view them using GET endpoints.


Parent issue #5546 


Discussion:

Resolving patch:
diff --git a/app/api/discount_codes.py b/app/api/discount_codes.py
--- a/app/api/discount_codes.py
+++ b/app/api/discount_codes.py
@@ -222,10 +222,12 @@ def before_get(self, args, kwargs):
                 raise ObjectNotFound(
                     {'parameter': '{id}'}, "DiscountCode: not found")
 
-            if discount.used_for == 'ticket' and has_access('is_coorganizer', event_id=discount.event_id):
+#             if discount.used_for == 'ticket' and has_access('is_coorganizer', event_id=discount.event_id):
+            if discount.used_for == 'ticket':
                 self.schema = DiscountCodeSchemaTicket
 
-            elif discount.used_for == 'event' and has_access('is_admin'):
+#             elif discount.used_for == 'event' and has_access('is_admin'):
+            elif discount.used_for == 'event':
                 self.schema = DiscountCodeSchemaEvent
             else:
                 raise UnprocessableEntity({'source': ''},
@@ -267,10 +269,12 @@ def before_get_object(self, view_kwargs):
                 self.schema = DiscountCodeSchemaPublic
                 return
 
-            if discount.used_for == 'ticket' and has_access('is_coorganizer', event_id=discount.event_id):
+#             if discount.used_for == 'ticket' and has_access('is_coorganizer', event_id=discount.event_id):
+            if discount.used_for == 'ticket':
                 self.schema = DiscountCodeSchemaTicket
 
-            elif discount.used_for == 'event' and has_access('is_admin'):
+#             elif discount.used_for == 'event' and has_access('is_admin'):
+            elif discount.used_for == 'event':
                 self.schema = DiscountCodeSchemaEvent
             else:
                 raise UnprocessableEntity({'source': ''},
@@ -319,7 +323,7 @@ def before_delete_object(self, discount, view_kwargs):
         else:
             raise UnprocessableEntity({'source': ''}, "Please verify your permission")
 
-    decorators = (jwt_required,)
+#     decorators = (jwt_required,)
     schema = DiscountCodeSchemaTicket
     data_layer = {'session': db.session,
                   'model': DiscountCode,


Test patch: