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

Issue:
Internal server error in promotion link
https://open-event-dev.herokuapp.com/events/110/tickets/promotion/



Discussion:

Resolving patch:
diff --git a/app/views/admin/models_views/ticket_sales.py b/app/views/admin/models_views/ticket_sales.py
--- a/app/views/admin/models_views/ticket_sales.py
+++ b/app/views/admin/models_views/ticket_sales.py
@@ -1,6 +1,6 @@
 import flask_login
 import pycountry
-from flask import redirect
+from flask import redirect, flash
 from flask import request
 from flask import url_for
 from flask_admin import BaseView, expose
@@ -111,10 +111,17 @@ def add_order(self, event_id):
     @expose('/<order_identifier>/', methods=('GET',))
     def proceed_order(self, event_id, order_identifier):
         order = TicketingManager.get_order_by_identifier(order_identifier)
-        if order.status == 'completed':
-            return redirect(url_for('ticketing.view_order_after_payment', order_identifier=order_identifier))
-        return self.render('/gentelella/guest/ticketing/order_pre_payment.html', order=order, event=order.event,
-                           countries=list(pycountry.countries),
-                           from_organizer=True,
-                           pay_via=order.paid_via,
-                           stripe_publishable_key=get_settings()['stripe_publishable_key'])
+        if order:
+            if self.is_order_completed(order):
+                return redirect(url_for('ticketing.view_order_after_payment', order_identifier=order_identifier))
+            return self.render('/gentelella/guest/ticketing/order_pre_payment.html', order=order, event=order.event,
+                               countries=list(pycountry.countries),
+                               from_organizer=True,
+                               pay_via=order.paid_via,
+                               stripe_publishable_key=get_settings()['stripe_publishable_key'])
+        flash("Can't find order", 'warning')
+        return redirect(url_for('.display_ticket_stats', event_id=event_id))
+
+    @staticmethod
+    def is_order_completed(order):
+        return order.status == 'completed'


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

Issue:
Event image or sample image not showing up in sessions photo
Currently there is still a placeholder on the MySessions page.

![screenshot from 2016-08-02 20 23 57](https://cloud.githubusercontent.com/assets/1583873/17340124/344cd542-58ef-11e6-8849-d53e923e82f3.png)



Discussion:

Resolving patch:
diff --git a/app/views/admin/models_views/my_sessions.py b/app/views/admin/models_views/my_sessions.py
--- a/app/views/admin/models_views/my_sessions.py
+++ b/app/views/admin/models_views/my_sessions.py
@@ -9,11 +9,13 @@
 from app.views.admin.models_views.events import is_verified_user
 from ....helpers.data_getter import DataGetter
 
+
 class MySessionView(BaseView):
 
     @expose('/')
     @flask_login.login_required
     def display_my_sessions_view(self):
+        placeholder_images = DataGetter.get_event_default_images()
         upcoming_events_sessions = DataGetter.get_sessions_of_user(upcoming_events=True)
         past_events_sessions = DataGetter.get_sessions_of_user(upcoming_events=False)
         page_content = {"tab_upcoming_events": "Upcoming Sessions",
@@ -24,7 +26,7 @@ def display_my_sessions_view(self):
                   "Please verify by clicking on the confirmation link that has been emailed to you.")
         return self.render('/gentelella/admin/mysessions/mysessions_list.html',
                            upcoming_events_sessions=upcoming_events_sessions, past_events_sessions=past_events_sessions,
-                           page_content=page_content)
+                           page_content=page_content, placeholder_images=placeholder_images)
 
     @expose('/<int:session_id>/', methods=('GET',))
     @flask_login.login_required


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

Issue:
Event image or sample image not showing up in my ticket photo
Currently there is still a placeholder on the MyTicket page.



Discussion:

Resolving patch:
diff --git a/app/views/admin/models_views/my_tickets.py b/app/views/admin/models_views/my_tickets.py
--- a/app/views/admin/models_views/my_tickets.py
+++ b/app/views/admin/models_views/my_tickets.py
@@ -1,6 +1,7 @@
 import flask_login
 from flask_admin import BaseView, expose
 from app.helpers.ticketing import TicketingManager
+from app.helpers.data_getter import DataGetter
 
 
 class MyTicketsView(BaseView):
@@ -14,8 +15,10 @@ def display_my_tickets(self):
 
         upcoming_events_orders = TicketingManager.get_orders_of_user(upcoming_events=True)
         past_events_orders = TicketingManager.get_orders_of_user(upcoming_events=False)
+        placeholder_images = DataGetter.get_event_default_images()
 
         return self.render('/gentelella/admin/mytickets/mytickets_list.html',
                            page_content=page_content,
                            upcoming_events_orders=upcoming_events_orders,
-                           past_events_orders=past_events_orders)
+                           past_events_orders=past_events_orders,
+                           placeholder_images=placeholder_images)


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

Issue:
Submit session does not change label from draft to submitted state
See screenshot below:

![screenshot from 2016-08-02 20 17 54](https://cloud.githubusercontent.com/assets/1583873/17339913/4d5786d2-58ee-11e6-8404-c085aaee2c00.png)



Discussion:

Resolving patch:
diff --git a/app/helpers/data.py b/app/helpers/data.py
--- a/app/helpers/data.py
+++ b/app/helpers/data.py
@@ -551,6 +551,7 @@ def edit_session(request, session):
             session.subtitle = form.get('subtitle', '')
             session.long_abstract = form.get('long_abstract', '')
             session.short_abstract = form.get('short_abstract', '')
+            session.state = form_state
 
             if form.get('track', None) != "":
                 session.track_id = form.get('track', None)


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

Issue:
Import social_links from event json, don't create social_links json
Social links can easily be imported from event json without any data loss or other issues so we don't need social_links json. 



Discussion:

Resolving patch:
diff --git a/app/api/helpers/export_helpers.py b/app/api/helpers/export_helpers.py
--- a/app/api/helpers/export_helpers.py
+++ b/app/api/helpers/export_helpers.py
@@ -12,8 +12,7 @@
 from app.helpers.data_getter import DataGetter
 from app.helpers.helpers import send_email_after_export
 
-from ..events import DAO as EventDAO, EVENT, \
-    LinkDAO as SocialLinkDAO, SOCIAL_LINK
+from ..events import DAO as EventDAO, EVENT
 from ..microlocations import DAO as MicrolocationDAO, MICROLOCATION
 from ..sessions import DAO as SessionDAO, SESSION, \
     TypeDAO as SessionTypeDAO, SESSION_TYPE
@@ -32,7 +31,6 @@
     ('sponsors', SponsorDAO, SPONSOR),
     ('tracks', TrackDAO, TRACK),
     ('session_types', SessionTypeDAO, SESSION_TYPE),
-    ('social_links', SocialLinkDAO, SOCIAL_LINK),
     ('forms', CustomFormDAO, CUSTOM_FORM)
 ]
 
diff --git a/app/api/helpers/import_helpers.py b/app/api/helpers/import_helpers.py
--- a/app/api/helpers/import_helpers.py
+++ b/app/api/helpers/import_helpers.py
@@ -38,7 +38,7 @@
 ]
 
 DELETE_FIELDS = {
-    'event': ['creator', 'social_links'],
+    'event': ['creator'],
     'tracks': ['sessions'],
     'speakers': ['sessions']
 }
@@ -302,6 +302,10 @@ def import_event_json(task_handle, zip_path):
         data = _delete_fields(srv, data)
         new_event = EventDAO.create(data, 'dont')[0]
         version_data = data.get('version', {})
+        write_file(
+            path + '/social_links',
+            json.dumps(data.get('social_links', []))
+        )  # save social_links
         _upload_media_queue(srv, new_event)
     except BaseError as e:
         raise make_error('event', er=e)
@@ -369,3 +373,10 @@ def get_filename_from_cd(cd):
         return '', ''
     fn = fname[0].rsplit('.', 1)
     return fn[0], '' if len(fn) == 1 else ('.' + fn[1])
+
+
+def write_file(file, data):
+    """simple write to file"""
+    fp = open(file, 'w')
+    fp.write(data)
+    fp.close()


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

Issue:
Issues with old export tasks, they stay forever PENDING
Old celery export tasks may be flushed from Redis database and so their task_id's will be unavailable. 
In such a case, opening the 'Export' page of that event will show export status as 'Pending' forever. (This is an issue with Celery). Thus user will not be able to start a new export. 

Luckily there is a question on stack-overflow which addresses and solves this issue. 
http://stackoverflow.com/questions/9824172/find-out-whether-celery-task-exists

We should implement the same to prevent any inconvenience for the user. 



Discussion:

Resolving patch:
diff --git a/app/__init__.py b/app/__init__.py
--- a/app/__init__.py
+++ b/app/__init__.py
@@ -11,6 +11,7 @@
 # Keep it before flask extensions are imported
 import arrow
 from celery import Celery
+from celery.signals import after_task_publish
 from flask.ext.htmlmin import HTMLMIN
 import logging
 import os.path
@@ -305,6 +306,19 @@ def __call__(self, *args, **kwargs):
 
 
 celery = make_celery(current_app)
+
+
+# http://stackoverflow.com/questions/9824172/find-out-whether-celery-task-exists
+@after_task_publish.connect
+def update_sent_state(sender=None, body=None, **kwargs):
+    # the task may not exist if sent using `send_task` which
+    # sends tasks by name, so fall back to the default result backend
+    # if that is the case.
+    task = celery.tasks.get(sender)
+    backend = task.backend if task else celery.backend
+    backend.store_result(body['id'], None, 'WAITING')
+
+
 import api.helpers.tasks
 import helpers.tasks
 


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

Issue:
Event locations are not visible in footer



Discussion:

Resolving patch:
diff --git a/app/helpers/data_getter.py b/app/helpers/data_getter.py
--- a/app/helpers/data_getter.py
+++ b/app/helpers/data_getter.py
@@ -664,8 +664,8 @@ def get_message_setting_by_action(action):
     def get_locations_of_events():
         names = []
         try:
-            raise Exception()
             for event in DataGetter.get_live_and_public_events():
+                print event
                 if not string_empty(event.location_name) and not string_empty(event.latitude) and not string_empty(
                    event.longitude):
                     response = requests.get(


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

Issue:
Internal server error when publish event 
>  UnicodeEncodeError: 'ascii' codec can't encode character u'\u0142' in position 4: ordinal not in range(128)
> 2016-08-10T23:01:53.574341+00:00 app[web.1]:     print event.searchable_location_name
> 2016-08-10T23:01:53.648680+00:00 app[web.1]: [2016-08-10 23:01:53 +0000] [17] [ERROR] Error handling request /socket.io/?EIO=3&transport=websocket&sid=24d65baebe424c7ebf16e40c19ac741d
> 2016-08-10T23:01:53.648683+00:00 app[web.1]: Traceback (most recent call last):
> 2016-08-10T23:01:53.648684+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/async.py", line 52, in handle
> 2016-08-10T23:01:53.648685+00:00 app[web.1]:     self.handle_request(listener_name, req, client, addr)
> 2016-08-10T23:01:53.648686+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/async.py", line 112, in handle_request
> 2016-08-10T23:01:53.648686+00:00 app[web.1]:     resp.close()
> 2016-08-10T23:01:53.648687+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/http/wsgi.py", line 418, in close
> 2016-08-10T23:01:53.648688+00:00 app[web.1]:     self.send_headers()
> 2016-08-10T23:01:53.648688+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/http/wsgi.py", line 334, in send_headers
> 2016-08-10T23:01:53.648689+00:00 app[web.1]:     tosend = self.default_headers()
> 2016-08-10T23:01:53.648690+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/http/wsgi.py", line 315, in default_headers
> 2016-08-10T23:01:53.648690+00:00 app[web.1]:     elif self.should_close():
> 2016-08-10T23:01:53.648692+00:00 app[web.1]:     if self.status_code < 200 or self.status_code in (204, 304):
> 2016-08-10T23:01:53.648691+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/http/wsgi.py", line 238, in should_close
> 2016-08-10T23:01:53.648693+00:00 app[web.1]: AttributeError: 'Response' object has no attribute 'status_code'



Discussion:

Resolving patch:
diff --git a/app/views/admin/models_views/events.py b/app/views/admin/models_views/events.py
--- a/app/views/admin/models_views/events.py
+++ b/app/views/admin/models_views/events.py
@@ -115,7 +115,6 @@ def create_view(self,):
     @can_access
     def details_view(self, event_id):
         event = DataGetter.get_event(event_id)
-        print event.searchable_location_name
         checklist = {"": ""}
 
         if fields_not_empty(event,


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

Issue:
SERVER_NAME in app.config should be generic
Right now the `SERVER_NAME` in app.config is set to "open-event-dev.hrokuapp.com" because of which if the code is hosted in any other domain, it is unable to recognize the URL and gives 404.

I think we can set the value using environment variable.

SERVER_NAME in app.config should be generic
Right now the `SERVER_NAME` in app.config is set to "open-event-dev.hrokuapp.com" because of which if the code is hosted in any other domain, it is unable to recognize the URL and gives 404.

I think we can set the value using environment variable.



Discussion:
We can use `request.url_root` in a `before_first_request` function to set this value dynamically. 

We can use `request.url_root` in a `before_first_request` function to set this value dynamically. 


Resolving patch:
diff --git a/app/__init__.py b/app/__init__.py
--- a/app/__init__.py
+++ b/app/__init__.py
@@ -332,6 +332,7 @@ def update_sent_state(sender=None, body=None, **kwargs):
 def set_secret():
     current_app.secret_key = get_settings()['secret']
 
+
 @app.context_processor
 def integrate_socketio():
     integrate = current_app.config.get('INTEGRATE_SOCKETIO', False)
diff --git a/app/helpers/helpers.py b/app/helpers/helpers.py
--- a/app/helpers/helpers.py
+++ b/app/helpers/helpers.py
@@ -468,7 +468,10 @@ def get_latest_heroku_release():
         "Authorization": "Bearer " + token,
         "Range": "version ..; max=1, order=desc"
     }
-    response = requests.get("https://api.heroku.com/apps/open-event/releases", headers=headers)
+    response = requests.get(
+        "https://api.heroku.com/apps/%s/releases" % os.environ.get('HEROKU_APP_NAME', 'open-event'),
+        headers=headers
+    )
     try:
         return json.loads(response.text)[0]
     except:


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

Issue:
Celery based tasks not working
This is because someone commented the code where task was being registered. So sending email, import and export are all non-functional. 

```
import api.helpers.tasks
import helpers.tasks
```

I will send a PR with the fix and write some comments so that this doesn't happen again.



Discussion:

Resolving patch:
diff --git a/app/__init__.py b/app/__init__.py
--- a/app/__init__.py
+++ b/app/__init__.py
@@ -324,14 +324,17 @@ def update_sent_state(sender=None, body=None, **kwargs):
     backend.store_result(body['id'], None, 'WAITING')
 
 
-# import api.helpers.tasks
-# import helpers.tasks
+# register celery tasks. removing them will cause the tasks to not function. so don't remove them
+# it is important to register them after celery is defined to resolve circular imports
+import api.helpers.tasks
+import helpers.tasks
 
 
 @app.before_first_request
 def set_secret():
     current_app.secret_key = get_settings()['secret']
 
+
 @app.context_processor
 def integrate_socketio():
     integrate = current_app.config.get('INTEGRATE_SOCKETIO', False)


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

Issue:
Move Payment Gateways to own subtab
On `admin/settings/` add a subtab "Payment Gateways" and move the Paypal and Stripe here.

![screenshot from 2016-08-12 01 48 01](https://cloud.githubusercontent.com/assets/1583873/17608754/ed81ed04-602e-11e6-9e1a-444a1369aba2.png)

![screenshot from 2016-08-12 01 47 33](https://cloud.githubusercontent.com/assets/1583873/17608757/f19fce4c-602e-11e6-9bd0-e42e1d9b36b8.png)



Discussion:

Resolving patch:
diff --git a/app/settings/__init__.py b/app/settings/__init__.py
--- a/app/settings/__init__.py
+++ b/app/settings/__init__.py
@@ -30,7 +30,7 @@ def set_settings(**kwargs):
         from app.helpers.data_getter import DataGetter
         from app.helpers.data import save_to_db
         currencies = DataGetter.get_payment_currencies()
-        for i, currency in enumerate(currencies):
+        for i, (currency, has_paypal, has_stripe) in enumerate(currencies):
             currency = currency.split(' ')[0]
             ticket_fee = TicketFees(currency=currency,
                                     service_fee=ticket_service_fees[i],


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

Issue:
Sales tab in super admin doesn't work. Internal server error



Discussion:

Resolving patch:
diff --git a/app/settings/__init__.py b/app/settings/__init__.py
--- a/app/settings/__init__.py
+++ b/app/settings/__init__.py
@@ -37,7 +37,12 @@ def set_settings(**kwargs):
                                     maximum_fee=ticket_maximum_fees[i])
             save_to_db(ticket_fee, "Ticket Fees settings saved")
     else:
-        setting = Setting(**kwargs)
+        setting = Setting.query.first()
+        if not setting:
+            setting = Setting(**kwargs)
+        else:
+            for key, value in kwargs.iteritems():
+                setattr(setting, key, value)
         from app.helpers.data import save_to_db
         save_to_db(setting, 'Setting saved')
         current_app.secret_key = setting.secret
diff --git a/app/views/admin/super_admin/sales.py b/app/views/admin/super_admin/sales.py
--- a/app/views/admin/super_admin/sales.py
+++ b/app/views/admin/super_admin/sales.py
@@ -77,11 +77,12 @@ def sales_by_events_view(self, path):
             }
             tickets_summary_organizer_wise[str(event.creator_id)] = \
                 copy.deepcopy(tickets_summary_event_wise[str(event.id)])
-            tickets_summary_organizer_wise[str(event.creator_id)]['name'] = event.creator.email
+            if event.creator:
+                tickets_summary_organizer_wise[str(event.creator_id)]['name'] = event.creator.email
 
-            tickets_summary_location_wise[str(event.searchable_location_name)] = \
+            tickets_summary_location_wise[unicode(event.searchable_location_name)] = \
                 copy.deepcopy(tickets_summary_event_wise[str(event.id)])
-            tickets_summary_location_wise[str(event.searchable_location_name)]['name'] = event.searchable_location_name
+            tickets_summary_location_wise[unicode(event.searchable_location_name)]['name'] = event.searchable_location_name
 
         for order in orders:
             if order.status == 'initialized':


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

Issue:
Import/Export doesn't work on server
https://github.com/fossasia/open-event-orga-server/issues/2192#issuecomment-239621924

The status stays on WAITING forever. The process works locally but not on server. The logs show nothing useful. 



Discussion:

Resolving patch:
diff --git a/app/api/helpers/tasks.py b/app/api/helpers/tasks.py
--- a/app/api/helpers/tasks.py
+++ b/app/api/helpers/tasks.py
@@ -3,6 +3,7 @@
 This is done to resolve circular imports
 """
 import traceback
+import logging
 from flask import url_for
 
 from app import celery
@@ -31,6 +32,7 @@ def import_event_task(self, file):
 @celery.task(base=RequestContextTask, name='export.event', bind=True)
 def export_event_task(self, event_id, settings):
     try:
+        logging.info('Exporting started')
         path = event_export_task_base(event_id, settings)
         # task_id = self.request.id.__str__()  # str(async result)
         result = {
@@ -43,6 +45,7 @@ def export_event_task(self, event_id, settings):
     except Exception:
         print traceback.format_exc()
         result = {'__error': True, 'result': ServerError().to_dict()}
+    logging.info('Exporting done.. sending email')
     # send email
     send_export_mail(event_id, result)
     # return result
diff --git a/config.py b/config.py
--- a/config.py
+++ b/config.py
@@ -21,6 +21,10 @@ class ProductionConfig(Config):
     MINIFY_PAGE = True
     PRODUCTION = True
     INTEGRATE_SOCKETIO = True
+    # if force off
+    socketio_integration = os.environ.get('INTEGRATE_SOCKETIO')
+    if socketio_integration == 'false':
+        INTEGRATE_SOCKETIO = False
     # you don't want production on default db
     SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', '')
     if not SQLALCHEMY_DATABASE_URI:


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

Issue:
When editing speaker, adding photo doesn't work
http://localhost:5000/events/6/speakers/1/edit/

Setting photo from a url like above (Manage event -> Speakers -> Edit a speaker) doesn't work. 
The code is not set to update speaker photo. 



Discussion:

Resolving patch:
diff --git a/app/views/admin/models_views/speakers.py b/app/views/admin/models_views/speakers.py
--- a/app/views/admin/models_views/speakers.py
+++ b/app/views/admin/models_views/speakers.py
@@ -7,6 +7,8 @@
 from flask import request, url_for, redirect, flash
 from ....helpers.data import delete_from_db, save_to_db
 from ....helpers.data_getter import DataGetter
+from ....helpers.storage import upload, UPLOAD_PATHS
+
 
 def get_speaker_or_throw(speaker_id):
     session = DataGetter.get_speaker(speaker_id)
@@ -14,6 +16,7 @@ def get_speaker_or_throw(speaker_id):
         abort(404)
     return session
 
+
 class SpeakersView(BaseView):
 
     def is_accessible(self):
@@ -47,6 +50,16 @@ def edit_view(self, event_id, speaker_id):
                                speaker=speaker, event_id=event_id,
                                event=event, speaker_form=speaker_form)
         if request.method == 'POST':
+            # set photo
+            if 'photo' in request.files and request.files['photo'].filename != '':
+                speaker_img_file = request.files['photo']
+                speaker_img = upload(
+                    speaker_img_file,
+                    UPLOAD_PATHS['speakers']['photo'].format(
+                        event_id=int(event_id), id=int(speaker.id)
+                    ))
+                speaker.photo = speaker_img
+            # set other fields
             speaker.name = request.form.get('name', None)
             speaker.short_biography = request.form.get('short_biography', None)
             speaker.long_biography = request.form.get('long_biography', None)


Test patch: