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

Issue:
Make app config configurable from an environment var, fix broken configs
Currently the project runs by default on ProductionConfig which has DEBUG disabled. This is not convenient for development purposes as every change in code requires re-running the server.

Solution - Make app config configurable from an environment variable. If no env var is set, the default (ProductionConfig ?) will be used. 

Also there are some configs like DevelopmentConfig, StagingConfig which don't work at all as no SQLALCHEMY_DATABASE_URI is defined. Fix them.



Discussion:

Resolving patch:
diff --git a/config.py b/config.py
--- a/config.py
+++ b/config.py
@@ -10,14 +10,17 @@ class Config(object):
     CSRF_ENABLED = True
     CORS_HEADERS = 'Content-Type'
     SQLALCHEMY_TRACK_MODIFICATIONS = True
+    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'sqlite:///../app.db')
 
 
 class ProductionConfig(Config):
     DEBUG = False
-    try:
+    DEBUG_TB_ENABLED = False  # debug toolbar
+    try:  # you don't want production on default db
         SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
-    except:
-        print "did not find DATABASE_URL exported"
+    except KeyError:
+        SQLALCHEMY_DATABASE_URI = ''
+        print "ERROR: Did not find DATABASE_URL exported"
 
 
 class StagingConfig(Config):
diff --git a/open_event/__init__.py b/open_event/__init__.py
--- a/open_event/__init__.py
+++ b/open_event/__init__.py
@@ -1,6 +1,7 @@
 """Copyright 2015 Rafal Kowalski"""
 import logging
 import os.path
+from os import environ
 import sys
 import json
 
@@ -32,14 +33,13 @@ def create_app():
     app.register_blueprint(routes)
     migrate = Migrate(app, db)
 
-    app.config.from_object('config.ProductionConfig')
+    app.config.from_object(environ.get('APP_CONFIG', 'config.ProductionConfig'))
     db.init_app(app)
     manager = Manager(app)
     manager.add_command('db', MigrateCommand)
 
     cors = CORS(app)
     app.secret_key = 'super secret key'
-    # app.config.from_object('config.LocalSQLITEConfig')
     app.config['UPLOADS_FOLDER'] = os.path.realpath('.') + '/static/'
     app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static'
     app.config['STATIC_URL'] = '/static/'
@@ -55,7 +55,6 @@ def create_app():
     admin_view.init_login(app)
 
     # Flask-DebugToolbar Configuration
-    # Set DEBUG_TB_ENABLED as False in Production
     app.config['DEBUG_TB_ENABLED'] = True
     app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
     DebugToolbarExtension(app)


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

Issue:
Improve Heroku deploy docs
The heroku deploy docs (https://github.com/fossasia/open-event-orga-server/blob/master/docs/HowtoDeploytoHeroku.md) don't mention anything about creating a database and setting DATABASE_URL to it. Without that step, the deployed app won't function. 
Also nothing is mentioned about database migrations on server.



Discussion:

Resolving patch:
diff --git a/open_event/__init__.py b/open_event/__init__.py
--- a/open_event/__init__.py
+++ b/open_event/__init__.py
@@ -79,3 +79,7 @@ def request_wants_json():
         request.accept_mimetypes['text/html']
 
 current_app, manager, database = create_app()
+
+
+if __name__ == '__main__':
+    current_app.run()


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

Issue:
HTML Template rendered when page doesn't exist in API
If a paginated API endpoint is called with a non-existant page number, a template is rendered which should never happen in case of REST APIs.

```
http http://localhost:5000/api/v1/event/page/2
HTTP/1.0 404 NOT FOUND
Content-Length: 1062
Content-Type: text/html; charset=utf-8
Date: Sat, 21 May 2016 07:51:38 GMT
Server: Werkzeug/0.11.7 Python/2.7.10

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>You got 404'd</title>
    <link href="/admin/static/bootstrap/bootstrap3/css/bootstrap.min.css" rel="stylesheet">
    <link href="/static/admin/css/roboto.css" rel="stylesheet">
    <link href="/static/admin/css/material-custom.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-push-3 col-md-6" style="margin-top: 20px;">
            <div class="jumbotron">
                <h2 style="font-weight: 100; ">Page Not Found</h2>
                <p class="lead">Oops, the page you're looking for does not exist.</p>
                <p style="font-size: 14px;">
                    You may want to head back to the homepage and restart your journey.
                </p>
                <a href="/" class="btn btn-large btn-info" style="background-color: #3f51b5;">
                    <i class="glyphicon glyphicon-home"></i> Take Me Home
                </a>
            </div>
        </div>
    </div>
</div>
</body>
</html>
```



Discussion:

Resolving patch:
diff --git a/open_event/helpers/object_formatter.py b/open_event/helpers/object_formatter.py
--- a/open_event/helpers/object_formatter.py
+++ b/open_event/helpers/object_formatter.py
@@ -21,6 +21,8 @@ def get_json(name, query, request, page=None):
                     for table_object in
                     objects]})
         else:
+            if count <= ((page-1) * PER_PAGE):  # no results possible
+                return jsonify({})
             pagination = objects.paginate(page, PER_PAGE)
             return jsonify({
                 name: [


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

Issue:
Add social View 
#310

Input: name
Input Link

View should be similar to Session types View #343



Discussion:

Resolving patch:
diff --git a/migrations/versions/dbb79ff12e45_.py b/migrations/versions/dbb79ff12e45_.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/dbb79ff12e45_.py
@@ -0,0 +1,34 @@
+"""empty message
+
+Revision ID: dbb79ff12e45
+Revises: c3676a5f81de
+Create Date: 2016-05-23 15:36:42.015391
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = 'dbb79ff12e45'
+down_revision = 'c3676a5f81de'
+
+from alembic import op
+import sqlalchemy as sa
+import sqlalchemy_utils
+
+
+def upgrade():
+    ### commands auto generated by Alembic - please adjust! ###
+    op.create_table('social_link',
+    sa.Column('id', sa.INTEGER(), nullable=False),
+    sa.Column('name', sa.VARCHAR(), autoincrement=False, nullable=False),
+    sa.Column('link', sa.VARCHAR(), autoincrement=False, nullable=False),
+    sa.Column('event_id', sa.INTEGER(), autoincrement=False, nullable=True),
+    sa.ForeignKeyConstraint(['event_id'], [u'events.id'], name=u'social_link_event_id_fkey'),
+    sa.PrimaryKeyConstraint('id', name=u'social_link_pkey')
+    )
+    ### end Alembic commands ###
+
+
+def downgrade():
+    ### commands auto generated by Alembic - please adjust! ###
+    op.drop_table('social_link')
+    ### end Alembic commands ###
diff --git a/open_event/helpers/data.py b/open_event/helpers/data.py
--- a/open_event/helpers/data.py
+++ b/open_event/helpers/data.py
@@ -24,6 +24,7 @@
 from ..models.role import Role
 from ..models.users_events_roles import UsersEventsRoles
 from ..models.session_type import SessionType
+from ..models.social_link import SocialLink
 
 
 class DataManager(object):
@@ -456,10 +457,17 @@ def create_event(form):
         session_type_names = form.getlist('session_type[name]')
         session_type_length = form.getlist('session_type[length]')
 
+        social_link_name = form.getlist('social[name]')
+        social_link_link = form.getlist('social[link]')
+
         for index, name in enumerate(session_type_names):
             session_type = SessionType(name=name, length=session_type_length[index], event_id=event.id)
             db.session.add(session_type)
 
+        for index, name in enumerate(social_link_name):
+            social_link = SocialLink(name=name, link=social_link_link[index], event_id=event.id)
+            db.session.add(social_link)
+
         uer = UsersEventsRoles(event_id=event.id, user_id=login.current_user.id, role_id=role.id)
         save_to_db(uer, "Event saved")
         return event


Test patch:
diff --git a/tests/test_social_link.py b/tests/test_social_link.py
--- a/tests/test_social_link.py
+++ b/tests/test_social_link.py
@@ -7,8 +7,8 @@
 from tests.object_mother import ObjectMother
 
 
-class TestSessionType(OpenEventTestCase):
-    def test_add_session_type_to_db(self):
+class TestSocialLink(OpenEventTestCase):
+    def test_add_social_link_to_db(self):
         """Checks the one to many relationship between event and social_links """
         self.app = Setup.create_app()
         with app.test_request_context():
Repository: fossasia/open-event-server

Issue:
list_events url is inconsistent in API v2
The url is `/events/` whereas it should be `/events` to be consistent with other urls. 



Discussion:

Resolving patch:
diff --git a/open_event/api/events.py b/open_event/api/events.py
--- a/open_event/api/events.py
+++ b/open_event/api/events.py
@@ -32,7 +32,7 @@ def get(self, event_id):
         return get_object_or_404(EventModel, event_id)
 
 
-@api.route('/')
+@api.route('')
 class EventList(Resource):
     @api.doc('list_events')
     @api.marshal_list_with(EVENT)


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

Issue:
Add Track button in Schedule UI
Add Track button that opens up a modal to add a track to the Schedule UI and make necessary changes in the database.



Discussion:
Adding the view is remaining..


Resolving patch:
diff --git a/open_event/helpers/data.py b/open_event/helpers/data.py
--- a/open_event/helpers/data.py
+++ b/open_event/helpers/data.py
@@ -54,6 +54,19 @@ def create_track(form, event_id):
         if sessions:
             update_version(event_id, False, "session_ver")
 
+    @staticmethod
+    def create_new_track(form, event_id):
+        """
+        Track will be saved to database with proper Event id
+        :param form: view data form
+        :param event_id: Track belongs to Event by event id
+        """
+        new_track = Track(name=form['name'],
+                          description=form['description'],
+                          event_id=event_id,
+                          track_image_url=form['track_image_url'])
+        save_to_db(new_track, "Track saved")
+
     @staticmethod
     def update_track(form, track):
         """
diff --git a/open_event/views/admin/admin.py b/open_event/views/admin/admin.py
--- a/open_event/views/admin/admin.py
+++ b/open_event/views/admin/admin.py
@@ -6,9 +6,11 @@
 from open_event.models.event import Event
 from open_event.models.role import Role
 from open_event.models.user import User
+from open_event.models.track import Track
 from open_event.views.admin.models_views.events import EventsView
 from open_event.views.admin.models_views.roles import RoleView
 from open_event.views.admin.models_views.profile import ProfileView
+from open_event.views.admin.models_views.tracks import TracksView
 from open_event.views.admin.home import MyHomeView
 
 
@@ -27,12 +29,13 @@ def _add_views(self):
         events = EventsView(Event, db.session, name='Events', url='events')
         self.admin.add_view(events)
         self.admin.add_view(RoleView(Role, db.session, name='Role', url='events/<event_id>/roles'))
-
         profile = ProfileView(User, db.session, name='Profile', url='profile')
-
+        self.admin.add_view(profile)
+        track = TracksView(Track, db.session, name='Track', url='events/<event_id>/tracks')
+        self.admin.add_view(track)
         # self.admin.add_view(ev)
         # self.admin.add_view(events)
-        self.admin.add_view(profile)
+
 
     @staticmethod
     def init_login(app):
diff --git a/open_event/views/admin/models_views/tracks.py b/open_event/views/admin/models_views/tracks.py
new file mode 100644
--- /dev/null
+++ b/open_event/views/admin/models_views/tracks.py
@@ -0,0 +1,14 @@
+from flask_admin import expose
+from flask_admin.contrib.sqla import ModelView
+from flask import request, url_for, redirect
+from ....helpers.data import DataManager
+
+class TracksView(ModelView):
+
+    @expose('/new/', methods=('GET', 'POST'))
+    def create_view(self, event_id):
+        if request.method == 'POST':
+            print request.form
+            DataManager.create_new_track(request.form, event_id)
+        return redirect(url_for('event.details_view', event_id=event_id))
+


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

Issue:
Format missing in Session model



Discussion:

Resolving patch:
diff --git a/open_event/api/sessions.py b/open_event/api/sessions.py
--- a/open_event/api/sessions.py
+++ b/open_event/api/sessions.py
@@ -29,6 +29,11 @@
     'label_de': fields.String,
 })
 
+SESSION_FORMAT = api.model('SessionFormat', {
+    'id': fields.Integer(required=True),
+    'name': fields.String
+})
+
 SESSION_MICROLOCATION = api.model('SessionMicrolocation', {
     'id': fields.Integer(required=True),
     'name': fields.String,
@@ -46,6 +51,7 @@
     'speakers': fields.List(fields.Nested(SESSION_SPEAKER)),
     'level': fields.Nested(SESSION_LEVEL),
     'language': fields.Nested(SESSION_LANGUAGE),
+    'format': fields.Nested(SESSION_FORMAT),
     'microlocation': fields.Nested(SESSION_MICROLOCATION),
 })
 


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

Issue:
Slogan field no longer in Event model
The following error comes when trying to POST an event. Travis CI was not able to catch it because the event model was not tested for creating events. (due to issue with SQLite date time)

```
    new_event = EventModel(**self.api.payload)
TypeError: __init__() got an unexpected keyword argument 'slogan'
127.0.0.1 - - [04/Jun/2016 16:20:46] "POST /api/v2/events HTTP/1.1" 500 -
```



Discussion:
Also url is event_url 

@rafalkowalski @juslee I had the same issue while testing the APIs for iCal export. Should we have the slogan field? And what about the event_url? We need to make the changes accordingly.


Resolving patch:
diff --git a/open_event/api/events.py b/open_event/api/events.py
--- a/open_event/api/events.py
+++ b/open_event/api/events.py
@@ -19,8 +19,9 @@
     'end_time': fields.DateTime,
     'latitude': fields.Float,
     'longitude': fields.Float,
-    'slogan': fields.String,
-    'url': fields.String,
+    'event_url': fields.String,
+    'background_url': fields.String,
+    'description': fields.String,
     'location_name': fields.String,
 })
 


Test patch:
diff --git a/tests/api/utils_post_data.py b/tests/api/utils_post_data.py
--- a/tests/api/utils_post_data.py
+++ b/tests/api/utils_post_data.py
@@ -11,9 +11,10 @@
     "logo": "http://imgur.com/image.png",
     "longitude": 0,
     "name": "TestEvent",
-    "slogan": "TestEvent",
+    'event_url': "http://site.com",
+    'background_url': "http://imgur.com/image.png",
+    'description': "blah blah",
     "start_time": "2016-05-25T12:12:43.891Z",
-    "url": "http://website.com"
 }
 
 POST_FORMAT_DATA = {
Repository: fossasia/open-event-server

Issue:
Post API to create event failing
In gsoc branch, a new column (role) has been introduced in eventsusers model which is not fulfilled by the current POST method.

```
e 450, in do_execute
    cursor.execute(statement, parameters)
IntegrityError: (psycopg2.IntegrityError) null value in column "role" violates not-null constraint
DETAIL:  Failing row contains (1, 1, 1, t, t, null).
 [SQL: 'INSERT INTO eventsusers (event_id, user_id, editor, admin, role) VALUES (%(event_id)s, %(user_id)s, %(editor)s, %(admin)s, %(role)s) RETURNING eventsusers.id'] [parameters: {'admin': True, 'event_id': 1, 'role': None, 'editor': True, 'user_id': 1}]
127.0.0.1 - - [04/Jun/2016 18:22:49] "POST /api/v2/events HTTP/1.1" 404 -
```

Post API to create event failing
In gsoc branch, a new column (role) has been introduced in eventsusers model which is not fulfilled by the current POST method.

```
e 450, in do_execute
    cursor.execute(statement, parameters)
IntegrityError: (psycopg2.IntegrityError) null value in column "role" violates not-null constraint
DETAIL:  Failing row contains (1, 1, 1, t, t, null).
 [SQL: 'INSERT INTO eventsusers (event_id, user_id, editor, admin, role) VALUES (%(event_id)s, %(user_id)s, %(editor)s, %(admin)s, %(role)s) RETURNING eventsusers.id'] [parameters: {'admin': True, 'event_id': 1, 'role': None, 'editor': True, 'user_id': 1}]
127.0.0.1 - - [04/Jun/2016 18:22:49] "POST /api/v2/events HTTP/1.1" 404 -
```



Discussion:

Resolving patch:
diff --git a/open_event/api/events.py b/open_event/api/events.py
--- a/open_event/api/events.py
+++ b/open_event/api/events.py
@@ -3,6 +3,7 @@
 
 from custom_fields import EmailField, ColorField, UriField, ImageUriField
 from open_event.models.event import Event as EventModel, EventsUsers
+from open_event.models.user import ADMIN, SUPERADMIN
 from .helpers import get_object_list, get_object_or_404, get_paginated_list,\
     requires_auth
 from utils import PAGINATED_MODEL, PaginatedResourceBase, PAGE_PARAMS
@@ -64,6 +65,7 @@ def post(self):
         a.user = g.user
         a.editor = True
         a.admin = True
+        a.role = SUPERADMIN if a.user.role == SUPERADMIN else ADMIN
         new_event.users.append(a)
         save_to_db(new_event, "Event saved")
         update_version(
diff --git a/open_event/views/admin/models_views/tracks.py b/open_event/views/admin/models_views/tracks.py
--- a/open_event/views/admin/models_views/tracks.py
+++ b/open_event/views/admin/models_views/tracks.py
@@ -12,4 +12,3 @@ def create_view(self, event_id):
             print request.form
             DataManager.create_new_track(request.form, event_id)
         return redirect(url_for('event.details_view', event_id=event_id))
-


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

Issue:
Create .ics file to store iCal for exporting



Discussion:

Resolving patch:
diff --git a/open_event/views/views.py b/open_event/views/views.py
--- a/open_event/views/views.py
+++ b/open_event/views/views.py
@@ -1,5 +1,6 @@
 """Copyright 2015 Rafal Kowalski"""
 import os
+import uuid
 from flask import jsonify, url_for, redirect, request, send_from_directory
 from flask.ext.cors import cross_origin
 from flask.ext import login
@@ -399,10 +400,21 @@ def generate_icalendar_event(event_id):
     event.add('dtend', matching_event.end_time)
     event.add('logo', matching_event.logo)
     event.add('email', matching_event.email)
-    event.add('description', matching_event.slogan)
-    event.add('url', matching_event.url)
+    event.add('description', matching_event.description)
+    event.add('url', matching_event.event_url)
     cal.add_component(event)
-    return cal.to_ical()
+
+    #Saving ical in file
+    filename = "event_calendar/" + str(uuid.uuid4().hex[:15]) + ".ics"
+    f = open(os.path.join(os.path.realpath('.') + '/static/', filename), 'wb')
+    f.write(cal.to_ical())
+    f.close()
+
+    return api_response(
+        data=jsonify(calendar=str(cal.to_ical), filename=filename),
+        status_code=event_status_code(event_id),
+        error='Event'
+    )
 
 
 @app.route('/api/v1/event/<int:event_id>/tracks/<int:track_id>/export/ical', methods=['GET'])
@@ -498,6 +510,13 @@ def send_pic(filename):
     return send_from_directory(os.path.realpath('.') + '/static/', filename)
 
 
+@app.route('/calendar/<path:filename>')
+@auto.doc()
+def send_cal(filename):
+    """Returns calendar"""
+    return send_from_directory(os.path.realpath('.') + '/static/', filename)
+
+
 @app.route('/documentation')
 def documentation():
     return auto.html()


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

Issue:
Tests on development branch failing
This is due to change in track model in #560



Discussion:

Resolving patch:
diff --git a/open_event/api/tracks.py b/open_event/api/tracks.py
--- a/open_event/api/tracks.py
+++ b/open_event/api/tracks.py
@@ -1,9 +1,10 @@
 from flask.ext.restplus import Resource, Namespace, fields
 
 from open_event.models.track import Track as TrackModel
-from custom_fields import ImageUriField
+from custom_fields import ImageUriField, ColorField
 from .helpers import get_paginated_list, requires_auth
-from utils import PAGINATED_MODEL, PaginatedResourceBase, ServiceDAO, PAGE_PARAMS
+from utils import PAGINATED_MODEL, PaginatedResourceBase, ServiceDAO, \
+    PAGE_PARAMS
 
 api = Namespace('tracks', description='Tracks', path='/')
 
@@ -16,6 +17,7 @@
     'id': fields.Integer(required=True),
     'name': fields.String,
     'description': fields.String,
+    'color': ColorField(),
     'track_image_url': ImageUriField(),
     'sessions': fields.List(fields.Nested(TRACK_SESSION)),
 })


Test patch:
diff --git a/tests/api/utils.py b/tests/api/utils.py
--- a/tests/api/utils.py
+++ b/tests/api/utils.py
@@ -36,7 +36,12 @@ def create_services(event_id, serial_no=''):
     test_sponsor = 'TestSponsor{}_{}'.format(serial_no, event_id)
 
     microlocation = Microlocation(name=test_micro, event_id=event_id)
-    track = Track(name=test_track, description='descp', event_id=event_id)
+    track = Track(
+        name=test_track,
+        description='descp',
+        event_id=event_id,
+        color='red'
+    )
     level = Level(name=test_level, event_id=event_id)
     format_ = Format(name=test_format, label_en='label', event_id=event_id)
     language = Language(name=test_lang, event_id=event_id)
diff --git a/tests/api/utils_post_data.py b/tests/api/utils_post_data.py
--- a/tests/api/utils_post_data.py
+++ b/tests/api/utils_post_data.py
@@ -80,5 +80,6 @@
 POST_TRACK_DATA = {
     "description": "TestTrack",
     "name": "TestTrack",
+    "color": "red",
     "track_image_url": "http://imgur.com/image.png"
 }
Repository: fossasia/open-event-server

Issue:
Set email in super_admin created by create_db.py
The user created by create_db.py has no email set.
So we can now not login into the server as it requires email to login . 



Discussion:
This happened because of https://github.com/fossasia/open-event-orga-server/commit/241ad33372f04bcbeb6deddcdbf6533ce6a9997d


Resolving patch:
diff --git a/create_db.py b/create_db.py
--- a/create_db.py
+++ b/create_db.py
@@ -4,7 +4,7 @@
 
 
 def create_default_user():
-    print "Your login is 'super_admin'"
+    print "Your login is 'super_admin@gmail.com' (super_admin)"
     password = raw_input("Please enter password of Super Admin user")
     DataManager.create_super_admin(password)
 
@@ -13,4 +13,3 @@ def create_default_user():
     with current_app.app_context():
         db.create_all()
         create_default_user()
-
diff --git a/open_event/helpers/data.py b/open_event/helpers/data.py
--- a/open_event/helpers/data.py
+++ b/open_event/helpers/data.py
@@ -456,6 +456,7 @@ def create_user(form):
     def create_super_admin(password):
         user = User()
         user.login = 'super_admin'
+        user.email = 'super_admin@gmail.com'
         user.nickname = 'super_admin'
         salt = generate_random_salt()
         password = password


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

Issue:
Basic authentication in POST API broken
Basic auth in POST API is broken due to removal of login field in user model



Discussion:

Resolving patch:
diff --git a/open_event/api/helpers.py b/open_event/api/helpers.py
--- a/open_event/api/helpers.py
+++ b/open_event/api/helpers.py
@@ -186,7 +186,7 @@ def decorated(*args, **kwargs):
             else:
                 _error_abort(401, 'Authentication credentials not found')
         # validate credentials
-        user = UserModel.query.filter_by(login=auth.username).first()
+        user = UserModel.query.filter_by(email=auth.username).first()
         auth_ok = False
         if user is not None:
             auth_ok = check_password_hash(


Test patch: