<commit_before># -*- coding: utf-8 -*-
'''
    :codeauthor: :email:`Thomas Jackson <jacksontj.89@gmail.com>`
'''

# Import python libs
from __future__ import absolute_import
import os
import threading

import tornado.gen
import tornado.ioloop
from tornado.testing import AsyncTestCase

import salt.config
import salt.utils
import salt.transport.server
import salt.transport.client
import salt.exceptions

# Import Salt Testing libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../')
import integration

# Import Salt libs
from unit.transport.req_test import ReqChannelMixin
from unit.transport.pub_test import PubChannelMixin

# TODO: move to a library?
def get_config_file_path(filename):
    return os.path.join(integration.TMP, 'config', filename)

class BaseTCPReqCase(TestCase):
    '''
    Test the req server/client pair
    '''
    @classmethod
    def setUpClass(cls):
        cls.master_opts = salt.config.master_config(get_config_file_path('master'))
        cls.master_opts.update({
            'transport': 'tcp',
            'auto_accept': True,
        })

        cls.minion_opts = salt.config.minion_config(get_config_file_path('minion'))
        cls.minion_opts.update({
            'transport': 'tcp',
            'master_uri': 'tcp://127.0.0.1:{0}'.format(cls.minion_opts['master_port']),
        })

        cls.process_manager = salt.utils.process.ProcessManager(name='ReqServer_ProcessManager')

        cls.server_channel = salt.transport.server.ReqServerChannel.factory(cls.master_opts)
        cls.server_channel.pre_fork(cls.process_manager)

        cls.io_loop = tornado.ioloop.IOLoop()
        cls.io_loop.make_current()
        cls.server_channel.post_fork(cls._handle_payload, io_loop=cls.io_loop)

        cls.server_thread = threading.Thread(target=cls.io_loop.start)
        cls.server_thread.daemon = True
        cls.server_thread.start()

    @classmethod
    def tearDownClass(cls):
        cls.io_loop.stop()
        cls.server_thread.join()
        cls.process_manager.kill_children()
        cls.server_channel.close()
        del cls.server_channel

@skipIf(salt.utils.is_darwin(), 'hanging test suite on MacOS')
class ClearReqTestCases(BaseTCPReqCase, ReqChannelMixin):
    '''
    Test all of the clear msg stuff
    '''
    def setUp(self):
        self.channel = salt.transport.client.ReqChannel.factory(self.minion_opts, crypt='clear')

    @classmethod
    @tornado.gen.coroutine
    def _handle_payload(cls, payload):
        '''
        TODO: something besides echo
        '''
        raise tornado.gen.Return((payload, {'fun': 'send_clear'}))

@skipIf(salt.utils.is_darwin(), 'hanging test suite on MacOS')
class AESReqTestCases(BaseTCPReqCase, ReqChannelMixin):
    def setUp(self):
        self.channel = salt.transport.client.ReqChannel.factory(self.minion_opts)

    @classmethod
    @tornado.gen.coroutine
    def _handle_payload(cls, payload):
        '''
        TODO: something besides echo
        '''
        raise tornado.gen.Return((payload, {'fun': 'send'}))

    # TODO: make failed returns have a specific framing so we can raise the same exception
    # on encrypted channels
    def test_badload(self):
        '''
        Test a variety of bad requests, make sure that we get some sort of error
        '''
        msgs = ['', [], tuple()]
        for msg in msgs:
            with self.assertRaises(salt.exceptions.AuthenticationError):
                ret = self.channel.send(msg)

class BaseTCPPubCase(AsyncTestCase):
    '''
    Test the req server/client pair
    '''
    @classmethod
    def setUpClass(cls):
        cls.master_opts = salt.config.master_config(get_config_file_path('master'))
        cls.master_opts.update({
            'transport': 'tcp',
            'auto_accept': True,
        })

        cls.minion_opts = salt.config.minion_config(get_config_file_path('minion'))
        cls.minion_opts.update({
            'transport': 'tcp',
            'master_ip': '127.0.0.1',
            'auth_timeout': 1,
            'master_uri': 'tcp://127.0.0.1:{0}'.format(cls.minion_opts['master_port']),
        })

        cls.process_manager = salt.utils.process.ProcessManager(name='ReqServer_ProcessManager')

        cls.server_channel = salt.transport.server.PubServerChannel.factory(cls.master_opts)
        cls.server_channel.pre_fork(cls.process_manager)

        # we also require req server for auth
        cls.req_server_channel = salt.transport.server.ReqServerChannel.factory(cls.master_opts)
        cls.req_server_channel.pre_fork(cls.process_manager)

        cls._server_io_loop = tornado.ioloop.IOLoop()
        cls.req_server_channel.post_fork(cls._handle_payload, io_loop=cls._server_io_loop)

        cls.server_thread = threading.Thread(target=cls._server_io_loop.start)
        cls.server_thread.start()

    @classmethod
    def _handle_payload(cls, payload):
        '''
        TODO: something besides echo
        '''
        return payload, {'fun': 'send_clear'}

    @classmethod
    def tearDownClass(cls):
        cls._server_io_loop.stop()
        cls.server_thread.join()
        cls.process_manager.kill_children()
        cls.req_server_channel.close()
        del cls.req_server_channel

    def setUp(self):
        super(BaseTCPPubCase, self).setUp()
        self._start_handlers = dict(self.io_loop._handlers)

    def tearDown(self):
        super(BaseTCPPubCase, self).tearDown()
        failures = []
        for k, v in self.io_loop._handlers.iteritems():
            if self._start_handlers.get(k) != v:
                failures.append((k, v))
        if len(failures) > 0:
            raise Exception('FDs still attached to the IOLoop: {0}'.format(failures))

@skipIf(True, 'Skip until we can devote time to fix this test')
class AsyncPubChannelTest(BaseTCPPubCase, PubChannelMixin):
    '''
    Tests around the publish system
    '''

if __name__ == '__main__':
    from integration import run_tests
    run_tests(ClearReqTestCases, needs_daemon=False)
    run_tests(AESReqTestCases, needs_daemon=False)
<commit_msg>Fix TCP test<commit_after># -*- coding: utf-8 -*-
'''
    :codeauthor: :email:`Thomas Jackson <jacksontj.89@gmail.com>`
'''

# Import python libs
from __future__ import absolute_import
import os
import threading

import tornado.gen
import tornado.ioloop
from tornado.testing import AsyncTestCase

import salt.config
import salt.utils
import salt.transport.server
import salt.transport.client
import salt.exceptions

# Import Salt Testing libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../')
import integration

# Import Salt libs
from unit.transport.req_test import ReqChannelMixin
from unit.transport.pub_test import PubChannelMixin

# TODO: move to a library?
def get_config_file_path(filename):
    return os.path.join(integration.TMP, 'config', filename)

class BaseTCPReqCase(TestCase):
    '''
    Test the req server/client pair
    '''
    @classmethod
    def setUpClass(cls):
        cls.master_opts = salt.config.master_config(get_config_file_path('master'))
        cls.master_opts.update({
            'transport': 'tcp',
            'auto_accept': True,
        })

        cls.minion_opts = salt.config.minion_config(get_config_file_path('minion'))
        cls.minion_opts.update({
            'transport': 'tcp',
            'master_uri': 'tcp://127.0.0.1:{0}'.format(cls.minion_opts['master_port']),
        })

        cls.process_manager = salt.utils.process.ProcessManager(name='ReqServer_ProcessManager')

        cls.server_channel = salt.transport.server.ReqServerChannel.factory(cls.master_opts)
        cls.server_channel.pre_fork(cls.process_manager)

        cls.io_loop = tornado.ioloop.IOLoop()
        cls.io_loop.make_current()
        cls.server_channel.post_fork(cls._handle_payload, io_loop=cls.io_loop)

        cls.server_thread = threading.Thread(target=cls.io_loop.start)
        cls.server_thread.daemon = True
        cls.server_thread.start()

    @classmethod
    def tearDownClass(cls):
        cls.io_loop.stop()
        cls.server_thread.join()
        cls.process_manager.kill_children()
        cls.server_channel.close()
        del cls.server_channel

    @classmethod
    @tornado.gen.coroutine
    def _handle_payload(cls, payload):
        '''
        TODO: something besides echo
        '''
        raise tornado.gen.Return((payload, {'fun': 'send_clear'}))

@skipIf(salt.utils.is_darwin(), 'hanging test suite on MacOS')
class ClearReqTestCases(BaseTCPReqCase, ReqChannelMixin):
    '''
    Test all of the clear msg stuff
    '''
    def setUp(self):
        self.channel = salt.transport.client.ReqChannel.factory(self.minion_opts, crypt='clear')

    @classmethod
    @tornado.gen.coroutine
    def _handle_payload(cls, payload):
        '''
        TODO: something besides echo
        '''
        raise tornado.gen.Return((payload, {'fun': 'send_clear'}))

@skipIf(salt.utils.is_darwin(), 'hanging test suite on MacOS')
class AESReqTestCases(BaseTCPReqCase, ReqChannelMixin):
    def setUp(self):
        self.channel = salt.transport.client.ReqChannel.factory(self.minion_opts)

    @classmethod
    @tornado.gen.coroutine
    def _handle_payload(cls, payload):
        '''
        TODO: something besides echo
        '''
        raise tornado.gen.Return((payload, {'fun': 'send'}))

    # TODO: make failed returns have a specific framing so we can raise the same exception
    # on encrypted channels
    def test_badload(self):
        '''
        Test a variety of bad requests, make sure that we get some sort of error
        '''
        msgs = ['', [], tuple()]
        for msg in msgs:
            with self.assertRaises(salt.exceptions.AuthenticationError):
                ret = self.channel.send(msg)

class BaseTCPPubCase(AsyncTestCase):
    '''
    Test the req server/client pair
    '''
    @classmethod
    def setUpClass(cls):
        cls.master_opts = salt.config.master_config(get_config_file_path('master'))
        cls.master_opts.update({
            'transport': 'tcp',
            'auto_accept': True,
        })

        cls.minion_opts = salt.config.minion_config(get_config_file_path('minion'))
        cls.minion_opts.update({
            'transport': 'tcp',
            'master_ip': '127.0.0.1',
            'auth_timeout': 1,
            'master_uri': 'tcp://127.0.0.1:{0}'.format(cls.minion_opts['master_port']),
        })

        cls.process_manager = salt.utils.process.ProcessManager(name='ReqServer_ProcessManager')

        cls.server_channel = salt.transport.server.PubServerChannel.factory(cls.master_opts)
        cls.server_channel.pre_fork(cls.process_manager)

        # we also require req server for auth
        cls.req_server_channel = salt.transport.server.ReqServerChannel.factory(cls.master_opts)
        cls.req_server_channel.pre_fork(cls.process_manager)

        cls._server_io_loop = tornado.ioloop.IOLoop()
        cls.req_server_channel.post_fork(cls._handle_payload, io_loop=cls._server_io_loop)

        cls.server_thread = threading.Thread(target=cls._server_io_loop.start)
        cls.server_thread.start()

    @classmethod
    def _handle_payload(cls, payload):
        '''
        TODO: something besides echo
        '''
        return payload, {'fun': 'send_clear'}

    @classmethod
    def tearDownClass(cls):
        cls._server_io_loop.stop()
        cls.server_thread.join()
        cls.process_manager.kill_children()
        cls.req_server_channel.close()
        del cls.req_server_channel

    def setUp(self):
        super(BaseTCPPubCase, self).setUp()
        self._start_handlers = dict(self.io_loop._handlers)

    def tearDown(self):
        super(BaseTCPPubCase, self).tearDown()
        failures = []
        for k, v in self.io_loop._handlers.iteritems():
            if self._start_handlers.get(k) != v:
                failures.append((k, v))
        if len(failures) > 0:
            raise Exception('FDs still attached to the IOLoop: {0}'.format(failures))

@skipIf(True, 'Skip until we can devote time to fix this test')
class AsyncPubChannelTest(BaseTCPPubCase, PubChannelMixin):
    '''
    Tests around the publish system
    '''

if __name__ == '__main__':
    from integration import run_tests
    run_tests(ClearReqTestCases, needs_daemon=False)
    run_tests(AESReqTestCases, needs_daemon=False)
<|endoftext|>


<commit_before>from application import app
from flask import render_template, jsonify
from application.models import *
from flask import Flask, session, redirect, url_for, escape, request
from flask_oauthlib.client import OAuth, OAuthException
import random
import quality_control
from __init__ import facebook
import urllib2

@app.route('/')
def home():
    unfinRaps = Rap.query.filter(Rap.completed == False).limit(3).all()
    finRaps = Rap.query.filter(Rap.completed == True).limit(3).all()
    user = None
    if 'user_id' in session:
        user = User.query.filter_by(fb_id=session['user_id']).first()
    return render_template("info/home.html", title="Home", user = user, unfinRaps=unfinRaps, finRaps=finRaps)

@app.route('/raps/<int:rapID>')
def show_rap(rapID):
    rap = Rap.query.filter(Rap.id == rapID).first()
    pending_lines = Line.query.filter(Line.rapID == rapID) \
                               .filter(Line.isPending == True).all()
    pending_lines = quality_control.sort_lines_by_wilson_score(pending_lines)
    already_voted = []
    current_user = User.query.filter_by(fb_id=session['user_id']).first()
    line_users = []
    for i in pending_lines:
        if (current_user and i in current_user.lines):
            already_voted.append(True)
        else:
            already_voted.append(False)
        user = User.query.filter_by(fb_id=i.userID).first()
        line_users.append((user.full_name,user.id))
    accepted_line_users = []
    accepted_lines = Line.query.filter(Line.rapID == rapID) \
                               .filter(Line.isPending == False) \
                               .order_by(Line.lineIndex.asc()).all()
    for i in accepted_lines:
        user = User.query.filter_by(fb_id=i.userID).first()
        accepted_line_users.append((user.full_name,user.id, i.upvotes, i.downvotes))
    user = None
    if 'user_id' in session:
        user = User.query.filter_by(fb_id=session['user_id']).first()
    return render_template("info/rap.html", user=user, rap=rap,
                           already_voted=already_voted,
                           line_users=line_users, accepted_line_users=accepted_line_users,
                           pending_lines=pending_lines, accepted_lines=accepted_lines)

@app.route('/add_rap', methods=['POST'])
def add_rap():
    try:
        if session['user_id']:
            print request.form['rap_length']
            if (not request.form['rap']) or (not request.form['rap_length']):
                return jsonify(success=False)

            r = Rap(request.form['rap'], request.form['rap_length'])
            db.session.add(r)
            db.session.commit()
        return redirect(url_for('home'))
    except:
        return jsonify(success=False)

@app.route('/add_line', methods=['POST'])
def add_line():
    index = 1 + 2*len(Line.query.filter(Line.rapID == request.form['rapID'],
                                        Line.isPending == False).all())
    rapID = request.form['rapID']
    try:
        if (not request.form['line1']) or (not request.form['line2']):
            return jsonify(success=False)

        l = Line(request.form['line1'], request.form['line2'],
            index, request.form['rapID'], escape(session['user_id']))
        db.session.add(l)
        db.session.commit()
        return redirect(url_for('show_rap', rapID = rapID))
    except:
        return jsonify(success=False)

# THIS IS THE ROUTE I AM USING FOR THE UPVOTES

@app.route('/line/_upvote', methods=['POST', 'GET'])
def upvote_ajax():
    if request.method == 'POST':
        lineID = request.form['lineID']
        line = Line.query.get(lineID)
        current_user = User.query.filter_by(fb_id=session['user_id']).first()
        if (current_user and line not in current_user.lines):
            line.upvotes += 1
            current_user.lines.append(line)
            owner = User.query.filter_by(fb_id=line.userID).first()
            owner.rapGodPoints += 1
            db.session.add(current_user)
            db.session.commit()
            total_votes = line.upvotes + line.downvotes
            print total_votes
            if total_votes >= 1:
                select_best_line(line)
            return jsonify({"Success" : True, "Line" : lineID})
        else:
            return jsonify({"Success":False, "Line": lineID})

@app.route('/line/_downvote', methods=['POST', 'GET'])
def downvote_ajax():
    if request.method == 'POST':
        lineID = request.form['lineID']
        line = Line.query.get(lineID)
        line.downvotes += 1
        current_user = User.query.filter_by(fb_id=session['user_id']).first()
        if (current_user and line not in current_user.lines):
            line.downvotes += 1
            current_user.lines.append(line)
            db.session.add(current_user)
            db.session.commit()
            total_votes = line.upvotes + line.downvotes
            if total_votes >= 1:
                select_best_line(line)
            return jsonify({"Success":True, "Line": lineID})
        else:
            return jsonify({"Success":False, "Line": lineID})

def accepted_lines(rapID):
    return Line.query.filter(Line.rapID == rapID) \
                     .filter(Line.isPending == True).all()

def pending_lines(rapID):
    return Line.query.filter(Line.rapID == rapID) \
                     .filter(Line.isPending == True).all()

def select_best_line(line):
    rapID = line.rapID
    rap = Rap.query.get(rapID)
    all_pending_lines = pending_lines(rapID)
    best_line, other_lines = quality_control.best_line(all_pending_lines)
    best_line = best_line[1]
    if best_line:
        for line in other_lines:
            db.session.delete(line[1])
        best_line.isPending = False
        owner = User.query.filter_by(fb_id=best_line.userID).first()
        owner.rapGodPoints += 10
        rap.progress += 2
        db.session.add(best_line)
        db.session.commit()
        # finishes the rap if it reaches the max length
        if rap.progress >= rap.max_length:
            rap.completed = True
            db.session.add(rap)
            db.session.commit()

@app.route('/login')
def login():
    callback = url_for('facebook_authorized',
        next=request.args.get('next') or request.referrer or None,
        _external=True)
    print callback
    return facebook.authorize(callback=callback)

@app.route('/login/authorized')
def facebook_authorized():
    resp = facebook.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'],
            request.args['error_description']
        )
    if isinstance(resp, OAuthException):
        return 'Access denied: %s' % resp.message
    session['oauth_token'] = (resp['access_token'], '')
    me = facebook.get('/me')
    session['user_id'] = me.data["id"]
    u = User.query.filter_by(fb_id=str(me.data['id'])).first()
    print u
    if not User.query.filter_by(fb_id=str(me.data['id'])).first():
        email = me.data['email']
        u = User(me.data['name'], me.data['id'], email)
        db.session.add(u)
        db.session.commit()
    return redirect(url_for('home'))

@facebook.tokengetter
def get_facebook_oauth_token():
    return session.get('oauth_token')

@app.route('/logout')
def logout():
    session.pop('oauth_token', None)
    session.pop('user_id', None)
    return redirect(url_for('home'))

@app.route('/user/<int:userID>')
def profile(userID):
    user = User.query.filter_by(id=userID).first()
    lines = Line.query.filter_by(userID=user.fb_id, isPending=False)
    pending = Line.query.filter_by(userID=user.fb_id, isPending=True)
    return render_template("info/profile.html", pending=pending, user=user,
                           lines=lines)

@app.route('/unfinished')
def unfinished():
    raps = Rap.query.filter_by(completed=False).all()
    current_user = User.query.filter_by(fb_id=session['user_id']).first()
    return render_template("info/unfinished.html", raps=raps, user=current_user)

@app.route("/finished")
def finished():
    raps = Rap.query.filter_by(completed=True).all()
    current_user = User.query.filter_by(fb_id=session['user_id']).first()
    return render_template("info/finished.html", raps=raps, user=current_user)

@app.route("/about")
def about():
    current_user = User.query.filter_by(fb_id=session['user_id']).first()
    return render_template("info/about.html", user=current_user)
<commit_msg>update<commit_after>from application import app
from flask import render_template, jsonify
from application.models import *
from flask import Flask, session, redirect, url_for, escape, request
from flask_oauthlib.client import OAuth, OAuthException
import random
import quality_control
from __init__ import facebook
import urllib2

@app.route('/')
def home():
    unfinRaps = Rap.query.filter(Rap.completed == False).limit(3).all()
    finRaps = Rap.query.filter(Rap.completed == True).limit(3).all()
    user = None
    if 'user_id' in session:
        user = User.query.filter_by(fb_id=session['user_id']).first()
    return render_template("info/home.html", title="Home", user = user, unfinRaps=unfinRaps, finRaps=finRaps)

@app.route('/raps/<int:rapID>')
def show_rap(rapID):
    rap = Rap.query.filter(Rap.id == rapID).first()
    pending_lines = Line.query.filter(Line.rapID == rapID) \
                               .filter(Line.isPending == True).all()
    pending_lines = quality_control.sort_lines_by_wilson_score(pending_lines)
    already_voted = []
    current_user = User.query.filter_by(fb_id=session['user_id']).first()
    line_users = []
    for i in pending_lines:
        if (current_user and i in current_user.lines):
            already_voted.append(True)
        else:
            already_voted.append(False)
        user = User.query.filter_by(fb_id=i.userID).first()
        line_users.append((user.full_name,user.id))
    accepted_line_users = []
    accepted_lines = Line.query.filter(Line.rapID == rapID) \
                               .filter(Line.isPending == False) \
                               .order_by(Line.lineIndex.asc()).all()
    for i in accepted_lines:
        user = User.query.filter_by(fb_id=i.userID).first()
        accepted_line_users.append((user.full_name,user.id, i.upvotes, i.downvotes))
    user = None
    if 'user_id' in session:
        user = User.query.filter_by(fb_id=session['user_id']).first()
    return render_template("info/rap.html", user=user, rap=rap,
                           already_voted=already_voted,
                           line_users=line_users, accepted_line_users=accepted_line_users,
                           pending_lines=pending_lines, accepted_lines=accepted_lines)

@app.route('/add_rap', methods=['POST'])
def add_rap():
    try:
        if session['user_id']:
            print request.form['rap_length']
            if (not request.form['rap']) or (not request.form['rap_length']):
                return jsonify(success=False)

            r = Rap(request.form['rap'], request.form['rap_length'])
            db.session.add(r)
            db.session.commit()
        return redirect(url_for('home'))
    except:
        return jsonify(success=False)

@app.route('/add_line', methods=['POST'])
def add_line():
    index = 1 + 2*len(Line.query.filter(Line.rapID == request.form['rapID'],
                                        Line.isPending == False).all())
    rapID = request.form['rapID']
    try:
        if (not request.form['line1']) or (not request.form['line2']):
            return jsonify(success=False)

        l = Line(request.form['line1'], request.form['line2'],
            index, request.form['rapID'], escape(session['user_id']))
        db.session.add(l)
        db.session.commit()
        return redirect(url_for('show_rap', rapID = rapID))
    except:
        return jsonify(success=False)

# THIS IS THE ROUTE I AM USING FOR THE UPVOTES

@app.route('/line/_upvote', methods=['POST', 'GET'])
def upvote_ajax():
    if request.method == 'POST':
        lineID = request.form['lineID']
        line = Line.query.get(lineID)
        current_user = User.query.filter_by(fb_id=session['user_id']).first()
        if (current_user and line not in current_user.lines):
            line.upvotes += 1
            current_user.lines.append(line)
            owner = User.query.filter_by(fb_id=line.userID).first()
            owner.rapGodPoints += 1
            db.session.add(current_user)
            db.session.commit()
            total_votes = line.upvotes + line.downvotes
            print total_votes
            if total_votes >= 1:
                select_best_line(line)
            return jsonify({"Success" : True, "Line" : lineID})
        else:
            return jsonify({"Success":False, "Line": lineID})

@app.route('/line/_downvote', methods=['POST', 'GET'])
def downvote_ajax():
    if request.method == 'POST':
        lineID = request.form['lineID']
        line = Line.query.get(lineID)
        line.downvotes += 1
        current_user = User.query.filter_by(fb_id=session['user_id']).first()
        if (current_user and line not in current_user.lines):
            line.downvotes += 1
            current_user.lines.append(line)
            db.session.add(current_user)
            db.session.commit()
            total_votes = line.upvotes + line.downvotes
            if total_votes >= 1:
                select_best_line(line)
            return jsonify({"Success":True, "Line": lineID})
        else:
            return jsonify({"Success":False, "Line": lineID})

def accepted_lines(rapID):
    return Line.query.filter(Line.rapID == rapID) \
                     .filter(Line.isPending == True).all()

def pending_lines(rapID):
    return Line.query.filter(Line.rapID == rapID) \
                     .filter(Line.isPending == True).all()

def select_best_line(line):
    rapID = line.rapID
    rap = Rap.query.get(rapID)
    all_pending_lines = pending_lines(rapID)
    best_line, other_lines = quality_control.best_line(all_pending_lines)
    best_line = best_line[1]
    if best_line:
        for line in other_lines:
            db.session.delete(line[1])
        best_line.isPending = False
        owner = User.query.filter_by(fb_id=best_line.userID).first()
        owner.rapGodPoints += 10
        rap.progress += 2
        db.session.add(best_line)
        db.session.commit()
        # finishes the rap if it reaches the max length
        if rap.progress >= rap.max_length:
            rap.completed = True
            db.session.add(rap)
            db.session.commit()

@app.route('/login')
def login():
    callback = url_for('facebook_authorized',
        next=request.args.get('next') or request.referrer or None,
        _external=True)
    print callback
    return facebook.authorize(callback=callback)

@app.route('/login/authorized')
def facebook_authorized():
    resp = facebook.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'],
            request.args['error_description']
        )
    if isinstance(resp, OAuthException):
        return 'Access denied: %s' % resp.message
    session['oauth_token'] = (resp['access_token'], '')
    me = facebook.get('/me')
    session['user_id'] = me.data["id"]
    u = User.query.filter_by(fb_id=str(000)).first()
    print u
    if not User.query.filter_by(fb_id=str(me.data['id'])).first():
        email = me.data['email']
        u = User(me.data['name'], me.data['id'], email)
        db.session.add(u)
        db.session.commit()
    return redirect(url_for('home'))

@facebook.tokengetter
def get_facebook_oauth_token():
    return session.get('oauth_token')

@app.route('/logout')
def logout():
    session.pop('oauth_token', None)
    session.pop('user_id', None)
    return redirect(url_for('home'))

@app.route('/user/<int:userID>')
def profile(userID):
    user = User.query.filter_by(id=userID).first()
    lines = Line.query.filter_by(userID=user.fb_id, isPending=False)
    pending = Line.query.filter_by(userID=user.fb_id, isPending=True)
    return render_template("info/profile.html", pending=pending, user=user,
                           lines=lines)

@app.route('/unfinished')
def unfinished():
    raps = Rap.query.filter_by(completed=False).all()
    current_user = User.query.filter_by(fb_id=session['user_id']).first()
    return render_template("info/unfinished.html", raps=raps, user=current_user)

@app.route("/finished")
def finished():
    raps = Rap.query.filter_by(completed=True).all()
    current_user = User.query.filter_by(fb_id=session['user_id']).first()
    return render_template("info/finished.html", raps=raps, user=current_user)

@app.route("/about")
def about():
    current_user = User.query.filter_by(fb_id=session['user_id']).first()
    return render_template("info/about.html", user=current_user)
<|endoftext|>


<commit_before>from datetime import datetime

from django.conf import settings
from django.core.urlresolvers import reverse
from django.forms.widgets import DateTimeInput, CheckboxInput
from django.http import HttpResponseForbidden
from django.views.generic import DetailView
from django.views.generic import ListView
from django.views.generic import TemplateView
from django.views.generic.edit import FormView

from mongoengine.fields import EmbeddedDocumentField, ListField

from mongonaut.forms import DocumentListForm
from mongonaut.forms import DocumentDetailForm
from mongonaut.forms import document_detail_form_factory
from mongonaut.mixins import MongonautViewMixin

class IndexView(ListView, MongonautViewMixin):

    template_name = "mongonaut/index.html"
    queryset = []

    def get_queryset(self):
        return self.get_mongoadmins()

class AppListView(ListView, MongonautViewMixin):
    """ :args: <app_label> """

    template_name = "mongonaut/app_list.html"

class DocumentListView(FormView, MongonautViewMixin):
    """ :args: <app_label> <document_name>

        TODO - Make a generic document fetcher method
    """
    form_class = DocumentListForm
    success_url = '/'
    template_name = "mongonaut/document_list.html"

    def get_queryset(self):
        if hasattr(self, "queryset") and self.queryset:
            return self.queryset

        self.set_mongonaut_base()
        self.set_mongoadmin()
        self.document = getattr(self.models, self.document_name)
        queryset = self.document.objects.all()

        # search. move this to get_queryset
        # search. move this to get_queryset
        q = self.request.GET.get('q')
        if self.mongoadmin.search_fields and q:
            params = {}
            for field in self.mongoadmin.search_fields:
                search_key = "{field}__icontains".format(field=field)
                params[search_key] = q
            queryset = queryset.filter(**params)

        ### Start pagination
        ### Note:
        ###    Didn't use the Paginator in Django cause mongoengine querysets are
        ###    not the same as Django ORM querysets and it broke.
        # Make sure page request is an int. If not, deliver first page.
        try:
            page = int(self.request.GET.get('page', '1'))
        except ValueError:
            page = 1
        self.page = page

        self.documents_per_page = 25
        self.total_pages = max(queryset.count() / self.documents_per_page, 1)
        start = (self.page -1) * self.documents_per_page
        end = self.page * self.documents_per_page
        self.previous_page_number = page - 1
        self.next_page_number = page + 1
        try:
            queryset = queryset[start:end]
        except Exception as e:
            print e

        self.queryset = queryset
        return queryset

    def get_initial(self):
        self.query = self.get_queryset()
        mongo_ids = {'mongo_id':[unicode(x.id) for x in self.query]}
        return mongo_ids

    def get_context_data(self, **kwargs):
        context = super(DocumentListView, self).get_context_data(**kwargs)

        context['object_list'] = self.get_queryset()
        context['document'] = self.document
        context['app_label'] = self.app_label
        context['document_name'] = self.document_name

        # pagination bits
        context['page'] = self.page
        context['documents_per_page'] = self.documents_per_page
        context['previous_page_number'] = self.previous_page_number
        context['next_page_number'] = self.next_page_number
        context['total_pages'] = self.total_pages

        # Part of upcoming list view form functionality
        if self.queryset.count():
            context['keys'] = ['id',]
            for key in sorted([x for x in self.document._fields.keys() if x != 'id']):
                # TODO - Figure out why this EmbeddedDocumentField and ListField breaks this view
                # Note - This is the challenge part, right? :)
                if isinstance(self.document._fields[key], EmbeddedDocumentField):
                    continue
                if isinstance(self.document._fields[key], ListField):
                    continue
                context['keys'].append(key)

        if self.mongoadmin.search_fields:
            context['search_field'] = True

        context = self.get_permissions(context)
        return context

    def post(self, request, *args, **kwargs):
        # TODO - make sure to check the rights of the poster
        #self.get_queryset() # TODO - write something that grabs the document class better
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        mongo_ids = self.get_initial()['mongo_id']
        for form_mongo_id in form.data.getlist('mongo_id'):
            for mongo_id in mongo_ids:
                if form_mongo_id == mongo_id:
                    self.document.objects.get(id=mongo_id).delete()

        return self.form_invalid(form)

class DocumentDetailView(TemplateView, MongonautViewMixin):
    """ :args: <app_label> <document_name> <id> """
    template_name = "mongonaut/document_detail.html"

    def get_context_data(self, **kwargs):
        context = super(DocumentDetailView, self).get_context_data(**kwargs)
        self.set_mongonaut_base()
        self.document_type = getattr(self.models, self.document_name)
        self.ident = self.kwargs.get('id')
        self.document = self.document_type.objects.get(id=self.ident)

        context['document'] = self.document
        context['app_label'] = self.app_label
        context['document_name'] = self.document_name
        context['keys'] = ['id',]
        for key in sorted([x for x in self.document._fields.keys() if x != 'id']):
            # TODO - Figure out why this EmbeddedDocumentField and ListField breaks this view
            # Note - This is the challenge part, right? :)
            if isinstance(self.document._fields[key], EmbeddedDocumentField):
                continue
            if isinstance(self.document._fields[key], ListField):
                continue
            context['keys'].append(key)

        self.set_mongoadmin()
        context = self.get_permissions(context)

        return context

class DocumentDetailEditFormView(FormView, MongonautViewMixin):
    """ :args: <app_label> <document_name> <id> """#

    template_name = "mongonaut/document_detail_edit_form.html"
    form_class = DocumentDetailForm
    success_url = '/'

    def get_success_url(self):
        self.set_mongonaut_base()
        return reverse('document_detail_edit_form', kwargs={'app_label':self.app_label,'document_name':self.document_name,'id':self.kwargs.get('id')})

    def get_context_data(self, **kwargs):
        context = super(DocumentDetailEditFormView, self).get_context_data(**kwargs)
        self.set_mongonaut_base()
        self.document_type = getattr(self.models, self.document_name)
        self.ident = self.kwargs.get('id')
        self.document = self.document_type.objects.get(id=self.ident)

        context['document'] = self.document
        context['app_label'] = self.app_label
        context['document_name'] = self.document_name

        self.set_mongoadmin()
        context = self.get_permissions(context)

        return context

    def get_form(self, DocumentDetailForm):
        self.set_mongonaut_base()
        self.document_type = getattr(self.models, self.document_name)
        self.ident = self.kwargs.get('id')
        self.document = self.document_type.objects.get(id=self.ident)
        self.form = DocumentDetailForm()
        self.form = document_detail_form_factory(form=self.form, document_type=self.document_type, initial=self.document)
        if self.request.method == 'POST':
            self.form.data = self.request.POST
            self.form.is_bound = True
            if self.form.is_valid():
                for key, field in self.form.fields.items():
                    if 'readonly' in field.widget.attrs:
                        # For _id
                        # TODO - make the ones below work
                        # for ReferenceField - like <class 'articles.models.User'> on Blog
                        # For ListField - like 'field': <mongoengine.fields.StringField object at 0x101b51810>,
                        # For EmbeddedDocumentField
                        continue

                    if isinstance(field.widget, DateTimeInput):
                        format = field.widget.format
                        setattr(self.document, key, datetime.strptime(self.request.POST[key], format))
                        continue

                    if isinstance(field.widget, CheckboxInput):
                        if key in self.request.POST:
                            setattr(self.document, key, True)
                        else:
                            setattr(self.document, key, False)
                        continue

                    # for strings
                    setattr(self.document, key, self.request.POST[key])
                self.document.save()
                # TODO add message for save

        return self.form

class DocumentDetailAddFormView(FormView, MongonautViewMixin):
    """ :args: <app_label> <document_name> <id> """#

    template_name = "mongonaut/document_detail_add_form.html"
    form_class = DocumentDetailForm
    success_url = '/'

    def get_success_url(self):
        self.set_mongonaut_base()
        return reverse('document_detail_form', kwargs={'app_label':self.app_label,'document_name':self.document_name,'id':self.document.id})

    def get_context_data(self, **kwargs):
        """ TODO - possibly inherit this from DocumentDetailEditFormView. This is same thing minus:
            self.ident = self.kwargs.get('id')
            self.document = self.document_type.objects.get(id=self.ident)
        """
        context = super(DocumentDetailAddFormView, self).get_context_data(**kwargs)
        self.set_mongonaut_base()
        self.document_type = getattr(self.models, self.document_name)

        context['app_label'] = self.app_label
        context['document_name'] = self.document_name

        self.set_mongoadmin()
        context = self.get_permissions(context)

        return context

    def get_form(self, DocumentDetailForm):
        self.set_mongonaut_base()
        self.document_type = getattr(self.models, self.document_name)
        self.form = DocumentDetailForm()
        self.form = document_detail_form_factory(form=self.form, document_type=self.document_type)
        if self.request.method == 'POST':
            self.form.data = self.request.POST
            self.form.is_bound = True
            if self.form.is_valid():
                self.document = self.document_type()
                for key, field in self.form.fields.items():
                    if 'readonly' in field.widget.attrs:
                        # For _id
                        # TODO - make the ones below work
                        # for ReferenceField - like <class 'articles.models.User'> on Blog
                        # For ListField - like 'field': <mongoengine.fields.StringField object at 0x101b51810>,
                        # For EmbeddedDocumentField
                        continue

                    if isinstance(field.widget, DateTimeInput):
                        format = field.widget.format
                        setattr(self.document, key, datetime.strptime(self.request.POST[key], format))
                        continue

                    if isinstance(field.widget, CheckboxInput):
                        if key in self.request.POST:
                            setattr(self.document, key, True)
                        else:
                            setattr(self.document, key, False)
                        continue

                    # for strings
                    setattr(self.document, key, self.request.POST[key])
                self.document.save()
                # TODO add message for save

        return self.form

class EmbeddedDocumentDetailView(DetailView, MongonautViewMixin):
    """ :args: <app_label> <document_name> <id> <???> """
    template_name = "mongonaut/embedded_document_detail.html"<commit_msg>Add form fixes<commit_after>from datetime import datetime

from django.conf import settings
from django.core.urlresolvers import reverse
from django.forms.widgets import DateTimeInput, CheckboxInput
from django.http import HttpResponseForbidden
from django.views.generic import DetailView
from django.views.generic import ListView
from django.views.generic import TemplateView
from django.views.generic.edit import FormView

from mongoengine.fields import EmbeddedDocumentField, ListField

from mongonaut.forms import DocumentListForm
from mongonaut.forms import DocumentDetailForm
from mongonaut.forms import document_detail_form_factory
from mongonaut.mixins import MongonautViewMixin

class IndexView(ListView, MongonautViewMixin):

    template_name = "mongonaut/index.html"
    queryset = []

    def get_queryset(self):
        return self.get_mongoadmins()

class AppListView(ListView, MongonautViewMixin):
    """ :args: <app_label> """

    template_name = "mongonaut/app_list.html"

class DocumentListView(FormView, MongonautViewMixin):
    """ :args: <app_label> <document_name>

        TODO - Make a generic document fetcher method
    """
    form_class = DocumentListForm
    success_url = '/'
    template_name = "mongonaut/document_list.html"

    def get_queryset(self):
        if hasattr(self, "queryset") and self.queryset:
            return self.queryset

        self.set_mongonaut_base()
        self.set_mongoadmin()
        self.document = getattr(self.models, self.document_name)
        queryset = self.document.objects.all()

        # search. move this to get_queryset
        # search. move this to get_queryset
        q = self.request.GET.get('q')
        if self.mongoadmin.search_fields and q:
            params = {}
            for field in self.mongoadmin.search_fields:
                search_key = "{field}__icontains".format(field=field)
                params[search_key] = q
            queryset = queryset.filter(**params)

        ### Start pagination
        ### Note:
        ###    Didn't use the Paginator in Django cause mongoengine querysets are
        ###    not the same as Django ORM querysets and it broke.
        # Make sure page request is an int. If not, deliver first page.
        try:
            page = int(self.request.GET.get('page', '1'))
        except ValueError:
            page = 1
        self.page = page

        self.documents_per_page = 25
        self.total_pages = max(queryset.count() / self.documents_per_page, 1)
        start = (self.page -1) * self.documents_per_page
        end = self.page * self.documents_per_page
        self.previous_page_number = page - 1
        self.next_page_number = page + 1
        try:
            queryset = queryset[start:end]
        except Exception as e:
            print e

        self.queryset = queryset
        return queryset

    def get_initial(self):
        self.query = self.get_queryset()
        mongo_ids = {'mongo_id':[unicode(x.id) for x in self.query]}
        return mongo_ids

    def get_context_data(self, **kwargs):
        context = super(DocumentListView, self).get_context_data(**kwargs)

        context['object_list'] = self.get_queryset()
        context['document'] = self.document
        context['app_label'] = self.app_label
        context['document_name'] = self.document_name

        # pagination bits
        context['page'] = self.page
        context['documents_per_page'] = self.documents_per_page
        context['previous_page_number'] = self.previous_page_number
        context['next_page_number'] = self.next_page_number
        context['total_pages'] = self.total_pages

        # Part of upcoming list view form functionality
        if self.queryset.count():
            context['keys'] = ['id',]
            for key in sorted([x for x in self.document._fields.keys() if x != 'id']):
                # TODO - Figure out why this EmbeddedDocumentField and ListField breaks this view
                # Note - This is the challenge part, right? :)
                if isinstance(self.document._fields[key], EmbeddedDocumentField):
                    continue
                if isinstance(self.document._fields[key], ListField):
                    continue
                context['keys'].append(key)

        if self.mongoadmin.search_fields:
            context['search_field'] = True

        context = self.get_permissions(context)
        return context

    def post(self, request, *args, **kwargs):
        # TODO - make sure to check the rights of the poster
        #self.get_queryset() # TODO - write something that grabs the document class better
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        mongo_ids = self.get_initial()['mongo_id']
        for form_mongo_id in form.data.getlist('mongo_id'):
            for mongo_id in mongo_ids:
                if form_mongo_id == mongo_id:
                    self.document.objects.get(id=mongo_id).delete()

        return self.form_invalid(form)

class DocumentDetailView(TemplateView, MongonautViewMixin):
    """ :args: <app_label> <document_name> <id> """
    template_name = "mongonaut/document_detail.html"

    def get_context_data(self, **kwargs):
        context = super(DocumentDetailView, self).get_context_data(**kwargs)
        self.set_mongonaut_base()
        self.document_type = getattr(self.models, self.document_name)
        self.ident = self.kwargs.get('id')
        self.document = self.document_type.objects.get(id=self.ident)

        context['document'] = self.document
        context['app_label'] = self.app_label
        context['document_name'] = self.document_name
        context['keys'] = ['id',]
        for key in sorted([x for x in self.document._fields.keys() if x != 'id']):
            # TODO - Figure out why this EmbeddedDocumentField and ListField breaks this view
            # Note - This is the challenge part, right? :)
            if isinstance(self.document._fields[key], EmbeddedDocumentField):
                continue
            if isinstance(self.document._fields[key], ListField):
                continue
            context['keys'].append(key)

        self.set_mongoadmin()
        context = self.get_permissions(context)

        return context

class DocumentDetailEditFormView(FormView, MongonautViewMixin):
    """ :args: <app_label> <document_name> <id> """#

    template_name = "mongonaut/document_detail_edit_form.html"
    form_class = DocumentDetailForm
    success_url = '/'

    def get_success_url(self):
        self.set_mongonaut_base()
        return reverse('document_detail_edit_form', kwargs={'app_label':self.app_label,'document_name':self.document_name,'id':self.kwargs.get('id')})

    def get_context_data(self, **kwargs):
        context = super(DocumentDetailEditFormView, self).get_context_data(**kwargs)
        self.set_mongonaut_base()
        self.document_type = getattr(self.models, self.document_name)
        self.ident = self.kwargs.get('id')
        self.document = self.document_type.objects.get(id=self.ident)

        context['document'] = self.document
        context['app_label'] = self.app_label
        context['document_name'] = self.document_name

        self.set_mongoadmin()
        context = self.get_permissions(context)

        return context

    def get_form(self, DocumentDetailForm):
        self.set_mongonaut_base()
        self.document_type = getattr(self.models, self.document_name)
        self.ident = self.kwargs.get('id')
        self.document = self.document_type.objects.get(id=self.ident)
        self.form = DocumentDetailForm()
        self.form = document_detail_form_factory(form=self.form, document_type=self.document_type, initial=self.document)
        if self.request.method == 'POST':
            self.form.data = self.request.POST
            self.form.is_bound = True
            if self.form.is_valid():
                for key, field in self.form.fields.items():
                    if 'readonly' in field.widget.attrs:
                        # For _id
                        # TODO - make the ones below work
                        # for ReferenceField - like <class 'articles.models.User'> on Blog
                        # For ListField - like 'field': <mongoengine.fields.StringField object at 0x101b51810>,
                        # For EmbeddedDocumentField
                        continue

                    if isinstance(field.widget, DateTimeInput):
                        format = field.widget.format
                        setattr(self.document, key, datetime.strptime(self.request.POST[key], format))
                        continue

                    if isinstance(field.widget, CheckboxInput):
                        if key in self.request.POST:
                            setattr(self.document, key, True)
                        else:
                            setattr(self.document, key, False)
                        continue

                    # for strings
                    setattr(self.document, key, self.request.POST[key])
                self.document.save()
                # TODO add message for save

        return self.form

class DocumentDetailAddFormView(FormView, MongonautViewMixin):
    """ :args: <app_label> <document_name> <id> """#

    template_name = "mongonaut/document_detail_add_form.html"
    form_class = DocumentDetailForm
    success_url = '/'

    def get_success_url(self):
        self.set_mongonaut_base()
        return reverse('document_detail', kwargs={'app_label':self.app_label,'document_name':self.document_name,'id':str(self.document.id)})

    def get_context_data(self, **kwargs):
        """ TODO - possibly inherit this from DocumentDetailEditFormView. This is same thing minus:
            self.ident = self.kwargs.get('id')
            self.document = self.document_type.objects.get(id=self.ident)
        """
        context = super(DocumentDetailAddFormView, self).get_context_data(**kwargs)
        self.set_mongonaut_base()
        self.document_type = getattr(self.models, self.document_name)

        context['app_label'] = self.app_label
        context['document_name'] = self.document_name

        self.set_mongoadmin()
        context = self.get_permissions(context)

        return context

    def get_form(self, DocumentDetailForm):
        self.set_mongonaut_base()
        self.document_type = getattr(self.models, self.document_name)
        self.form = DocumentDetailForm()
        self.form = document_detail_form_factory(form=self.form, document_type=self.document_type)
        if self.request.method == 'POST':
            self.form.data = self.request.POST
            self.form.is_bound = True
            if self.form.is_valid():
                self.document = self.document_type()
                for key, field in self.form.fields.items():
                    if 'readonly' in field.widget.attrs:
                        # For _id
                        # TODO - make the ones below work
                        # for ReferenceField - like <class 'articles.models.User'> on Blog
                        # For ListField - like 'field': <mongoengine.fields.StringField object at 0x101b51810>,
                        # For EmbeddedDocumentField
                        continue

                    if isinstance(field.widget, DateTimeInput):
                        format = field.widget.format
                        setattr(self.document, key, datetime.strptime(self.request.POST[key], format))
                        continue

                    if isinstance(field.widget, CheckboxInput):
                        if key in self.request.POST:
                            setattr(self.document, key, True)
                        else:
                            setattr(self.document, key, False)
                        continue

                    # for strings
                    setattr(self.document, key, self.request.POST[key])
                self.document.save()
                # TODO add message for save

        return self.form

class EmbeddedDocumentDetailView(DetailView, MongonautViewMixin):
    """ :args: <app_label> <document_name> <id> <???> """
    template_name = "mongonaut/embedded_document_detail.html"<|endoftext|>


<commit_before>import logging
import ibmsecurity
from ibmsecurity.utilities import tools

logger = logging.getLogger(__name__)

uri = "/wga/redis_config/wrp"
requires_modules = ["wga"]
requires_version = "10.0.1"

def get(isamAppliance, name, check_mode=False, force=False):
    """
    Retrieve the Redis collections configured for a specific Web Reverse Proxy
    """
    return isamAppliance.invoke_get("Retrieve the Redis collections configured for a specific Web",
                                    "{0}/{1}".format(uri, name),
                                    requires_modules=requires_modules, requires_version=requires_version)

def update(isamAppliance, name, input_data=[], check_mode=False, force=False):
    """
    Update the Redis collections which are used by a Web Reverse Proxy
    """

    exist, warnings = _check_exist(isamAppliance, name)
    if exist is True:
        same_contents, warnings = _check_contents(isamAppliance=isamAppliance, name=name, input_data=input_data)
    else:
        return isamAppliance.create_return_object(warnings=warnings)

    if force is True or same_contents is False:
        if check_mode is True:
            return isamAppliance.create_return_object(changed=True)
        else:
            return isamAppliance.invoke_put(
                "Update the Redis collections which are used by a Web Reverse Proxy",
                "{0}/{1}".format(uri, name),
                input_data,
                requires_modules=requires_modules, requires_version=requires_version)

    return isamAppliance.create_return_object(warnings=warnings)

def _check_exist(isamAppliance, name):
    ret_obj = ibmsecurity.isam.web.reverse_proxy.instance.get(isamAppliance)

    for rp in ret_obj['data']:
        if rp['id'] == name:
            return True, ret_obj['warnings']

    return False, ret_obj['warnings']

def _check_contents(isamAppliance, name, input_data):
    ret_obj = get(isamAppliance, name)

    if ret_obj['data'] == input_data:
        return True, ret_obj['warnings']
    else:
        return False, ret_obj['warnings']

def compare(isamAppliance1, isamAppliance2, name1, name2=None):
    if name2 is None or name1 == '':
        name2 = name1
    ret_obj1 = get(isamAppliance1, name1)
    ret_obj2 = get(isamAppliance2, name2)

    return tools.json_compare(ret_obj1, ret_obj2)
<commit_msg> this import statement seems only necessary when calling update() from a role #349. Merge branch 'issue348_missing_import' of https://github.com/tombosmansibm/ibmsecurity into tombosmansibm-issue348_missing_import<commit_after>import logging
import ibmsecurity

import ibmsecurity.isam.web.reverse_proxy.instance

from ibmsecurity.utilities import tools

logger = logging.getLogger(__name__)

uri = "/wga/redis_config/wrp"
requires_modules = ["wga"]
requires_version = "10.0.1"

def get(isamAppliance, name, check_mode=False, force=False):
    """
    Retrieve the Redis collections configured for a specific Web Reverse Proxy
    """
    return isamAppliance.invoke_get("Retrieve the Redis collections configured for a specific Web",
                                    "{0}/{1}".format(uri, name),
                                    requires_modules=requires_modules, requires_version=requires_version)

def update(isamAppliance, name, input_data=[], check_mode=False, force=False):
    """
    Update the Redis collections which are used by a Web Reverse Proxy
    """

    exist, warnings = _check_exist(isamAppliance, name)
    if exist is True:
        same_contents, warnings = _check_contents(isamAppliance=isamAppliance, name=name, input_data=input_data)
    else:
        return isamAppliance.create_return_object(warnings=warnings)

    if force is True or same_contents is False:
        if check_mode is True:
            return isamAppliance.create_return_object(changed=True)
        else:
            return isamAppliance.invoke_put(
                "Update the Redis collections which are used by a Web Reverse Proxy",
                "{0}/{1}".format(uri, name),
                input_data,
                requires_modules=requires_modules, requires_version=requires_version)

    return isamAppliance.create_return_object(warnings=warnings)

def _check_exist(isamAppliance, name):
    ret_obj = ibmsecurity.isam.web.reverse_proxy.instance.get(isamAppliance)

    for rp in ret_obj['data']:
        if rp['id'] == name:
            return True, ret_obj['warnings']

    return False, ret_obj['warnings']

def _check_contents(isamAppliance, name, input_data):
    ret_obj = get(isamAppliance, name)

    if ret_obj['data'] == input_data:
        return True, ret_obj['warnings']
    else:
        return False, ret_obj['warnings']

def compare(isamAppliance1, isamAppliance2, name1, name2=None):
    if name2 is None or name1 == '':
        name2 = name1
    ret_obj1 = get(isamAppliance1, name1)
    ret_obj2 = get(isamAppliance2, name2)

    return tools.json_compare(ret_obj1, ret_obj2)
<|endoftext|>


<commit_before>import datetime

from django.db import models
from django.db.models import ForeignKey, CharField, DateField, OneToOneField
from django.db.models.signals import post_save
from django.utils.translation import ugettext
_ = lambda u: unicode(ugettext(u))

from django.contrib.auth.models import User

import userena.models
from userena.models import UserenaLanguageBaseProfile

from imagekit.models import ImageModel

from django_countries import CountryField
from timezones.fields import TimeZoneField

class UserProfile(UserenaLanguageBaseProfile):
    """
    A profile for a user
    """
    class Meta:
        permissions = userena.models.PROFILE_PERMISSIONS

    genre_choices = (('M', _('Male')),
                     ('F', _('Female')))

    birthdate = DateField(verbose_name=_('Birthdate'),
                          null=True, blank=True)

    genre = CharField(verbose_name=_('Genre'),
                      max_length=1, blank=True,
                      choices=genre_choices)

    country = CountryField(verbose_name=_('Country'))
    timezone = TimeZoneField(verbose_name=_('Timezone'))

    town = CharField(verbose_name=_('Town'),
                     max_length=50, blank=True)

    @property
    def age(self):
        """
        Calculate the age of a user
        """
        if self.birthdate:
            d = datetime.date.today()
            return (d.year - self.birthdate.year) - int((d.month, d.day) < (self.birthdate.month, self.birthdate.day))
        else:
            return None

    @models.permalink
    def get_absolute_url(self):
        return ("userena_profile_detail", (self.user,), {})

    def __unicode__(self):
        return "Profile for %s" % self.user

def get_useravatar_path(aUserAvatar, filename):
    dst = 'users/%d/avatar/%s' % (aUserAvatar.userprofile.id,
                                  filename)
    return dst

class UserAvatar(ImageModel):
    """
    An avatar of a user
    """
    class IKOptions:
        image_field = 'original_image'
        spec_module = 'account.imagespecs'

    original_image = models.ImageField(upload_to=get_useravatar_path)

    userprofile = OneToOneField(UserProfile,
                                related_name='avatar')

    def __unicode__(self):
        return "Avatar for %s" % self.userprofile.user

# Create a profile as soon as we create a user
def create_profile(sender, instance, created, **kwargs):
    if created:
        profile = UserProfile(user=instance)
        profile.save()

#post_save.connect(create_profile, sender=User)
<commit_msg>reversion for user profiles<commit_after>import datetime

from django.db import models
from django.db.models import ForeignKey, CharField, DateField, OneToOneField
from django.db.models.signals import post_save
from django.utils.translation import ugettext
_ = lambda u: unicode(ugettext(u))

from django.contrib.auth.models import User

import userena.models
from userena.models import UserenaLanguageBaseProfile

from imagekit.models import ImageModel

from django_countries import CountryField
from timezones.fields import TimeZoneField

class UserProfile(UserenaLanguageBaseProfile):
    """
    A profile for a user
    """
    class Meta:
        permissions = userena.models.PROFILE_PERMISSIONS

    genre_choices = (('M', _('Male')),
                     ('F', _('Female')))

    birthdate = DateField(verbose_name=_('Birthdate'),
                          null=True, blank=True)

    genre = CharField(verbose_name=_('Genre'),
                      max_length=1, blank=True,
                      choices=genre_choices)

    country = CountryField(verbose_name=_('Country'))
    timezone = TimeZoneField(verbose_name=_('Timezone'))

    town = CharField(verbose_name=_('Town'),
                     max_length=50, blank=True)

    @property
    def age(self):
        """
        Calculate the age of a user
        """
        if self.birthdate:
            d = datetime.date.today()
            return (d.year - self.birthdate.year) - int((d.month, d.day) < (self.birthdate.month, self.birthdate.day))
        else:
            return None

    @models.permalink
    def get_absolute_url(self):
        return ("userena_profile_detail", (self.user,), {})

    def __unicode__(self):
        return "Profile for %s" % self.user

def get_useravatar_path(aUserAvatar, filename):
    dst = 'users/%d/avatar/%s' % (aUserAvatar.userprofile.id,
                                  filename)
    return dst

class UserAvatar(ImageModel):
    """
    An avatar of a user
    """
    class IKOptions:
        image_field = 'original_image'
        spec_module = 'account.imagespecs'

    original_image = models.ImageField(upload_to=get_useravatar_path)

    userprofile = OneToOneField(UserProfile,
                                related_name='avatar')

    def __unicode__(self):
        return "Avatar for %s" % self.userprofile.user

# Create a profile as soon as we create a user
def create_profile(sender, instance, created, **kwargs):
    if created:
        profile = UserProfile(user=instance)
        profile.save()

#post_save.connect(create_profile, sender=User)

# Reversions
import reversion
reversion.register(UserProfile)
<|endoftext|>


<commit_before>#!/usr/bin/env python

'''
'''

__docformat__ = 'restructuredtext'
__version__ = '$Id$'

import time
from ctypes import *

clib = cdll.LoadLibrary('libc.so.6')
clib.usleep.argtypes = [c_ulong]

class Clock:
    last_ts = None
    calibration = 0

    @classmethod
    def calibrate(cls, time=time.time):
        test = cls().set_fps
        s = time()
        for i in xrange(100): test(100)
        d = time() - s - 1
        cls.calibration = d/100
        print 'CALIBRATION = %f'%cls.calibration

    def set_fps(self, fps, time=time.time, usleep=clib.usleep):
        delay = 1. / fps
        ts = time()
        if self.last_ts is None:
            self.last_ts = ts
            return 0
        self.last_ts = ts
        actual = ts - self.last_ts
        sleeptime = (delay - actual) - self.calibration
        if sleeptime > 0:
            usleep(int(sleeptime * 1000000))
            return delay
        else:
            return actual

if __name__ == '__main__':
    Clock.calibrate()
    s = time.time()
    c = Clock()
    for i in xrange(100):
        c.set_fps(50)
    print time.time() - s

<commit_msg>Clock implementation for OS X. Interestingly, the calibration factor is much smaller than for my Linux desktop. This might be due to any number of factors: Python 2.4 vs. 2.5 or ctypes versions or platform issues.<commit_after>#!/usr/bin/env python

'''
'''

__docformat__ = 'restructuredtext'
__version__ = '$Id$'

import time
import sys
import ctypes
import ctypes.util

if sys.platform == 'win32':
    raise NotImplementedError, 'Need usleep() on Windows'
elif sys.platform == 'darwin':
    path = ctypes.util.find_library('c')
    if not path:
        raise ImportError('libc not found')
    _c = ctypes.cdll.LoadLibrary(path)
    _c.usleep.argtypes = [ctypes.c_ulong]
else:
    _c = ctypes.cdll.LoadLibrary('libc.so.6')
    _c.usleep.argtypes = [ctypes.c_ulong]

class Clock:
    last_ts = None
    calibration = 0

    @classmethod
    def calibrate(cls, time=time.time):
        test = cls().set_fps
        s = time()
        for i in xrange(100): test(100)
        d = time() - s - 1
        cls.calibration = d/100
        print 'CALIBRATION = %f'%cls.calibration

    def set_fps(self, fps, time=time.time, usleep=_c.usleep):
        delay = 1. / fps
        ts = time()
        if self.last_ts is None:
            self.last_ts = ts
            return 0
        self.last_ts = ts
        actual = ts - self.last_ts
        sleeptime = (delay - actual) - self.calibration
        if sleeptime > 0:
            usleep(int(sleeptime * 1000000))
            return delay
        else:
            return actual

if __name__ == '__main__':
    Clock.calibrate()
    s = time.time()
    c = Clock()
    for i in xrange(100):
        c.set_fps(50)
    print time.time() - s

<|endoftext|>


<commit_before>import time
import sys
import logging
import math
import datetime

from croniter import croniter

from .main import db
from .service import Service
from .heartbeat import Heartbeat
from . import config

log = logging.getLogger(__name__)

def main():

    next_time = int(time.time()) / 60 * 60
    while True:
        now = time.time()
        to_wait = math.ceil(next_time - now)
        if to_wait > 0:
            print >> sys.stderr, 'worker sleeping for %ds' % to_wait
            time.sleep(to_wait)
            continue

        for service in db.session.query(Service):

            if service.cron_spec and service.can_active_check:
                cron = croniter(service.cron_spec, next_time - 1)
                cron_next = cron.get_next()
                if cron_next == next_time:
                    log.debug('checking "%s"...' % service.name)
                    service.active_check()
                else:
                    log.debug('next check of "%s" in %ds' % (service.name, math.ceil(cron_next - now)))

            # Clean up excess heartbeats.
            if len(service.heartbeats) > config.HEARTBEATS_PER_SERVICE:
                service.heartbeats.sort(key=lambda h: h.time, reverse=True)
                service.heartbeats[config.HEARTBEATS_PER_SERVICE:] = []

        db.session.commit()
        next_time += 60

if __name__ == '__main__':
    main()
<commit_msg>Worker will properly trigger sub-minute jobs<commit_after>import time
import sys
import logging
import math
import datetime

from croniter import croniter

from .main import db
from .service import Service
from .heartbeat import Heartbeat
from . import config

log = logging.getLogger(__name__)

def main():

    next_time = int(time.time() + 60) / 60 * 60
    last_time = next_time - 60

    while True:

        # Wait for the full minute to pass.
        now = time.time()
        to_wait = math.ceil(next_time - now)
        if to_wait > 0:
            print >> sys.stderr, 'worker sleeping for %ds' % to_wait
            time.sleep(to_wait)
            continue

        for service in db.session.query(Service):

            if service.cron_spec and service.can_active_check:

                # See if the next time to run is within the bracket that
                # just passed.
                cron = croniter(service.cron_spec, last_time)
                cron_next = cron.get_next()
                if cron_next <= next_time:
                    log.debug('checking "%s"...' % service.name)
                    service.active_check()

                else:
                    log.debug('next check of "%s" in %ds' % (service.name, math.ceil(cron_next - now)))

            # Clean up excess heartbeats.
            if len(service.heartbeats) > config.HEARTBEATS_PER_SERVICE:
                service.heartbeats.sort(key=lambda h: h.time, reverse=True)
                service.heartbeats[config.HEARTBEATS_PER_SERVICE:] = []

        db.session.commit()
        next_time += 60

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>import jingo
import jinja2
from l10n import ugettext as _, ugettext_lazy as _lazy

import amo
from amo.helpers import urlparams
from addons.models import Addon

@jinja2.contextfunction
def install_button(context, addon, version=None, show_eula=True,
                   show_contrib=True, show_warning=True):
    """If version isn't given, we use the latest version."""
    app, lang = context['APP'], context['LANG']
    show_eula = bool(context['request'].GET.get('eula', show_eula))
    button = install_button_factory(addon, app, lang, version,
                                    show_eula, show_contrib)
    c = {'button': button, 'addon': addon, 'version': button.version,
         'APP': app}
    t = jingo.env.get_template('addons/button.html').render(c)
    return jinja2.Markup(t)

def install_button_factory(*args, **kwargs):
    button = InstallButton(*args, **kwargs)
    # Order matters.  We want to highlight unreviewed before featured.  They
    # should be mutually exclusive, but you never know.
    classes = (('unreviewed', UnreviewedInstallButton),
               ('self_hosted', SelfHostedInstallButton),
               ('featured', FeaturedInstallButton))
    for pred, cls in classes:
        if getattr(button, pred, False):
            button.__class__ = cls
            break
    button.prepare()
    return button

class InstallButton(object):
    button_class = ['download']
    install_class = []
    install_text = ''

    def __init__(self, addon, app, lang, version=None, show_eula=True,
                 show_contrib=True, show_warning=True):
        self.addon, self.app, self.lang = addon, app, lang
        self.latest = version is None
        self.version = version or addon.current_version

        self.featured = addon.is_featured(app, lang)
        self.unreviewed = addon.is_unreviewed() or self.version.is_unreviewed
        self.self_hosted = addon.status == amo.STATUS_LISTED

        self.show_eula = show_eula and addon.has_eula
        self.show_contrib = (show_contrib and addon.takes_contributions
                             and addon.annoying == amo.CONTRIB_ROADBLOCK)
        self.show_warning = show_warning and (self.unreviewed or
                                              self.self_hosted)

    def prepare(self):
        """Called after the class is set to manage eulas, contributions."""
        # Get a copy for this instance.
        self.button_class = list(self.__class__.button_class)
        self.install_class = list(self.__class__.install_class)
        tests = (self.show_eula, 'eula'), (self.show_contrib, 'contrib')
        for pred, cls in tests:
            if bool(pred):
                try:
                    self.button_class.remove('download')
                except ValueError:
                    pass
                self.button_class.append(cls)
                self.install_class.append(cls)

    def attrs(self):
        rv = {}
        addon = self.addon
        if addon.takes_contributions and addon.annoying == amo.CONTRIB_AFTER:
            rv['data-after'] = 'contrib'
        if addon.type_id == amo.ADDON_SEARCH:
            rv['data-search'] = 'true'
        return rv

    def links(self):
        rv = []
        for file in self.version.files.all():
            platform = file.platform_id
            # TODO(jbalogh): this is wrong if we got a version argument.
            url = file.latest_xpi_url()
            if platform == amo.PLATFORM_ALL.id:
                text, os = _('Download Now'), None
            else:
                text, os = _('Download'), amo.PLATFORMS[platform]
            if self.show_eula:
                text, url = _('Continue to Download →'), file.eula_url()
            elif self.show_contrib:
                # The eula doesn't exist or has been hit already.
                text = _('Continue to Download →')
                roadblock = self.addon.meet_the_dev_url(extra='roadblock')
                url = urlparams(roadblock, eula='')
            rv.append(Link(text, url, os, file))
        return rv

class FeaturedInstallButton(InstallButton):
    install_class = ['featuredaddon']
    install_text = _lazy(u'Featured', 'install_button')

class UnreviewedInstallButton(InstallButton):
    install_class = ['unreviewed']
    install_text = _lazy(u'Not Reviewed', 'install_button')
    button_class = 'download caution'.split()

class SelfHostedInstallButton(InstallButton):
    install_class = ['selfhosted']
    install_text = _lazy(u'Self Hosted', 'install_button')
    button_class = ['go']

    def links(self):
        return [Link(_('Continue to Website →'), self.addon.homepage)]

class Link(object):

    def __init__(self, text, url, os=None, file=None):
        self.text, self.url, self.os, self.file = text, url, os, file

def js(request):
    return jingo.render(request, 'addons/popups.html',
                        content_type='text/javascript')

def smorgasbord(request):
    """
    Gather many different kinds of tasty add-ons together.

    Great for testing install buttons.
    """
    def _compat(min, max):
        # Helper for faking compatible_apps.
        return {'min': {'version': min}, 'max': {'version': max}}

    addons = []
    normal_version = _compat('1.0', '10.0')
    older_version = _compat('1.0', '2.0')
    newer_version = _compat('9.0', '10.0')

    # Featured.
    featured = Addon.objects.featured(request.APP)
    addons.append(featured[0])
    addons[-1].tag = 'featured'

    # Normal.
    normal = Addon.objects.listed(request.APP).exclude(id__in=featured)
    addon = normal[0]
    addon.tag = 'normal'
    addon.compatible_apps[request.APP] = normal_version
    addons.append(addon)

    # Older version.
    addon = normal[0]
    addon.tag = 'older version'
    addon.compatible_apps[request.APP] = older_version
    addons.append(addon)

    # Newer version.
    addon = normal[0]
    addon.tag = 'newer version'
    addon.compatible_apps[request.APP] = newer_version
    addons.append(addon)

    # Unreviewed.
    exp = Addon.objects.experimental()
    addons.append(exp[0])
    addons[-1].tag = 'unreviewed'

    # Multiple Platforms.
    addons.append(Addon.objects.get(id=2313))
    addons[-1].tag = 'platformer'

    # Incompatible Platform.
    def w(tag, version):
        a = Addon.objects.get(id=5308)
        a.tag = tag
        a.compatible_apps[request.APP] = version
        return a
    addons.append(w('windows/linux-only', normal_version))
    addons.append(w('windows/linux-only + older version', older_version))
    addons.append(w('windows/linux-only + newer version', newer_version))

    # Self-Hosted.
    addons.append(Addon.objects.filter(status=amo.STATUS_LISTED,
                                       inactive=False)[0])
    addons[-1].tag = 'self-hosted'

    # EULA.
    addons.append(normal.filter(eula__isnull=False)[0])
    addons[-1].tag = 'eula'
    addons.append(exp.filter(eula__isnull=False)
                  .exclude(eula__localized_string='')[0])
    addons[-1].tag = 'eula + unreviewed'

    # Contributions.
    addons.append(normal.filter(annoying=1)[0])
    addons[-1].tag = 'contrib: passive'
    addons.append(normal.filter(annoying=2)[0])
    addons[-1].tag = 'contrib: after'
    addons.append(normal.filter(annoying=3)[0])
    addons[-1].tag = 'contrib: roadblock'
    addons.append(Addon.objects.get(id=2608))
    addons[-1].tag = 'after + eula'
    addons.append(Addon.objects.get(id=8442))
    addons[-1].tag = 'roadblock + eula'

    # Other App.
    addons.append(Addon.objects.get(id=5326))
    addons[-1].tag = 'tbird'

    # Mobile.
    addons.append(Addon.objects.get(id=53476))
    addons[-1].tag = 'mobile'

    # Search Engine.
    addons.append(Addon.objects.filter(type=amo.ADDON_SEARCH)[0])
    addons[-1].tag = 'search engine'
    # Theme.
    # Persona.
    # Future Version.
    # No versions.

    return jingo.render(request, 'addons/smorgasbord.html',
                        {'addons': addons})
<commit_msg>propagate src and collection references<commit_after>import jingo
import jinja2
from l10n import ugettext as _, ugettext_lazy as _lazy

import amo
from amo.helpers import urlparams
from addons.models import Addon

@jinja2.contextfunction
def install_button(context, addon, version=None, show_eula=True,
                   show_contrib=True, show_warning=True, src='',
                   collection=None):
    """If version isn't given, we use the latest version."""
    request = context['request']
    app, lang = context['APP'], context['LANG']
    show_eula = bool(request.GET.get('eula', show_eula))
    src = src or context.get('src') or request.GET.get('src', '')
    collection = (collection or context.get('collection')
                  or request.GET.get('collection')
                  or request.GET.get('collection_id')
                  or request.GET.get('collection_uuid'))
    button = install_button_factory(addon, app, lang, version,
                                    show_eula, show_contrib, show_warning,
                                    src, collection)
    c = {'button': button, 'addon': addon, 'version': button.version,
         'APP': app}
    t = jingo.env.get_template('addons/button.html').render(c)
    return jinja2.Markup(t)

def install_button_factory(*args, **kwargs):
    button = InstallButton(*args, **kwargs)
    # Order matters.  We want to highlight unreviewed before featured.  They
    # should be mutually exclusive, but you never know.
    classes = (('unreviewed', UnreviewedInstallButton),
               ('self_hosted', SelfHostedInstallButton),
               ('featured', FeaturedInstallButton))
    for pred, cls in classes:
        if getattr(button, pred, False):
            button.__class__ = cls
            break
    button.prepare()
    return button

class InstallButton(object):
    button_class = ['download']
    install_class = []
    install_text = ''

    def __init__(self, addon, app, lang, version=None, show_eula=True,
                 show_contrib=True, show_warning=True, src='', collection=None):
        self.addon, self.app, self.lang = addon, app, lang
        self.latest = version is None
        self.version = version or addon.current_version
        self.src = src
        self.collection = collection

        self.featured = addon.is_featured(app, lang)
        self.unreviewed = addon.is_unreviewed() or self.version.is_unreviewed
        self.self_hosted = addon.status == amo.STATUS_LISTED

        self.show_eula = show_eula and addon.has_eula
        self.show_contrib = (show_contrib and addon.takes_contributions
                             and addon.annoying == amo.CONTRIB_ROADBLOCK)
        self.show_warning = show_warning and (self.unreviewed or
                                              self.self_hosted)

    def prepare(self):
        """Called after the class is set to manage eulas, contributions."""
        # Get a copy for this instance.
        self.button_class = list(self.__class__.button_class)
        self.install_class = list(self.__class__.install_class)
        tests = (self.show_eula, 'eula'), (self.show_contrib, 'contrib')
        for pred, cls in tests:
            if bool(pred):
                try:
                    self.button_class.remove('download')
                except ValueError:
                    pass
                self.button_class.append(cls)
                self.install_class.append(cls)

    def attrs(self):
        rv = {}
        addon = self.addon
        if addon.takes_contributions and addon.annoying == amo.CONTRIB_AFTER:
            rv['data-after'] = 'contrib'
        if addon.type_id == amo.ADDON_SEARCH:
            rv['data-search'] = 'true'
        return rv

    def links(self):
        rv = []
        for file in self.version.files.all():
            platform = file.platform_id
            # TODO(jbalogh): this is wrong if we got a version argument.
            url = file.latest_xpi_url()
            if platform == amo.PLATFORM_ALL.id:
                text, os = _('Download Now'), None
            else:
                text, os = _('Download'), amo.PLATFORMS[platform]
            if self.show_eula:
                text, url = _('Continue to Download →'), file.eula_url()
            elif self.show_contrib:
                # The eula doesn't exist or has been hit already.
                text = _('Continue to Download →')
                roadblock = self.addon.meet_the_dev_url(extra='roadblock')
                url = urlparams(roadblock, eula='')
            rv.append(Link(text, self.fix_link(url), os, file))
        return rv

    def fix_link(self, url):
        if self.src:
            url = urlparams(url, src=self.src)
        if self.collection:
            url = urlparams(url, collection=self.collection)
        return url

class FeaturedInstallButton(InstallButton):
    install_class = ['featuredaddon']
    install_text = _lazy(u'Featured', 'install_button')

class UnreviewedInstallButton(InstallButton):
    install_class = ['unreviewed']
    install_text = _lazy(u'Not Reviewed', 'install_button')
    button_class = 'download caution'.split()

class SelfHostedInstallButton(InstallButton):
    install_class = ['selfhosted']
    install_text = _lazy(u'Self Hosted', 'install_button')
    button_class = ['go']

    def links(self):
        return [Link(_('Continue to Website →'), self.addon.homepage)]

class Link(object):

    def __init__(self, text, url, os=None, file=None):
        self.text, self.url, self.os, self.file = text, url, os, file

def js(request):
    return jingo.render(request, 'addons/popups.html',
                        content_type='text/javascript')

def smorgasbord(request):
    """
    Gather many different kinds of tasty add-ons together.

    Great for testing install buttons.
    """
    def _compat(min, max):
        # Helper for faking compatible_apps.
        return {'min': {'version': min}, 'max': {'version': max}}

    addons = []
    normal_version = _compat('1.0', '10.0')
    older_version = _compat('1.0', '2.0')
    newer_version = _compat('9.0', '10.0')

    # Featured.
    featured = Addon.objects.featured(request.APP)
    addons.append(featured[0])
    addons[-1].tag = 'featured'

    # Normal.
    normal = Addon.objects.listed(request.APP).exclude(id__in=featured)
    addon = normal[0]
    addon.tag = 'normal'
    addon.compatible_apps[request.APP] = normal_version
    addons.append(addon)

    # Older version.
    addon = normal[0]
    addon.tag = 'older version'
    addon.compatible_apps[request.APP] = older_version
    addons.append(addon)

    # Newer version.
    addon = normal[0]
    addon.tag = 'newer version'
    addon.compatible_apps[request.APP] = newer_version
    addons.append(addon)

    # Unreviewed.
    exp = Addon.objects.experimental()
    addons.append(exp[0])
    addons[-1].tag = 'unreviewed'

    # Multiple Platforms.
    addons.append(Addon.objects.get(id=2313))
    addons[-1].tag = 'platformer'

    # Incompatible Platform.
    def w(tag, version):
        a = Addon.objects.get(id=5308)
        a.tag = tag
        a.compatible_apps[request.APP] = version
        return a
    addons.append(w('windows/linux-only', normal_version))
    addons.append(w('windows/linux-only + older version', older_version))
    addons.append(w('windows/linux-only + newer version', newer_version))

    # Self-Hosted.
    addons.append(Addon.objects.filter(status=amo.STATUS_LISTED,
                                       inactive=False)[0])
    addons[-1].tag = 'self-hosted'

    # EULA.
    addons.append(normal.filter(eula__isnull=False)[0])
    addons[-1].tag = 'eula'
    addons.append(exp.filter(eula__isnull=False)
                  .exclude(eula__localized_string='')[0])
    addons[-1].tag = 'eula + unreviewed'

    # Contributions.
    addons.append(normal.filter(annoying=1)[0])
    addons[-1].tag = 'contrib: passive'
    addons.append(normal.filter(annoying=2)[0])
    addons[-1].tag = 'contrib: after'
    addons.append(normal.filter(annoying=3)[0])
    addons[-1].tag = 'contrib: roadblock'
    addons.append(Addon.objects.get(id=2608))
    addons[-1].tag = 'after + eula'
    addons.append(Addon.objects.get(id=8442))
    addons[-1].tag = 'roadblock + eula'

    # Other App.
    addons.append(Addon.objects.get(id=5326))
    addons[-1].tag = 'tbird'

    # Mobile.
    addons.append(Addon.objects.get(id=53476))
    addons[-1].tag = 'mobile'

    # Search Engine.
    addons.append(Addon.objects.filter(type=amo.ADDON_SEARCH)[0])
    addons[-1].tag = 'search engine'
    # Theme.
    # Persona.
    # Future Version.
    # No versions.

    return jingo.render(request, 'addons/smorgasbord.html',
                        {'addons': addons})
<|endoftext|>


<commit_before>import random
import re

from exceptions import ValidationLengthException, ValidationContentException

class DefaultMessageBackend(object):
    def __init__(self):
        self.messages = {}
        self.index = 0

    def get_by_id(self, _id, none_msg=None):
        return self.messages.get(_id, none_msg)

    def get_all(self):
        return self.messages.values()

    def add_message(self, text):
        self.index += 1
        self.messages[self.index] = text

    def random(self):
        return self.messages[random.randint(1, self.index)]

class MessageStore(object):
    def __init__(self, backend=None):
        if backend is None:
            self.backend = DefaultMessageBackend()
        else:
            self.backend = backend

    def add_message(self, text):
        self.backend.add_message(text)

    def filter_id(self, _id):
        return self.backend.get_by_id(_id, "<No such message id>")

    def random(self):
        return self.backend.random()

    def all(self):
        return self.backend.get_all()

matcher = re.compile(ur'[a-zA-Z0-9-!\033\r\n$%^&*()_+\ |~=`{}\[\]:";\'<>?,.\/]', re.U|re.I|re.M)
def validate_message(text):
    if len(text) > 80:
        raise ValidationLengthException()

    mo = matcher.sub('', text)
    if len(mo):
        raise ValidationContentException()

    return text
<commit_msg>Updated matcher rx.<commit_after>import random
import re

from exceptions import ValidationLengthException, ValidationContentException

class DefaultMessageBackend(object):
    def __init__(self):
        self.messages = {}
        self.index = 0

    def get_by_id(self, _id, none_msg=None):
        return self.messages.get(_id, none_msg)

    def get_all(self):
        return self.messages.values()

    def add_message(self, text):
        self.index += 1
        self.messages[self.index] = text

    def random(self):
        return self.messages[random.randint(1, self.index)]

class MessageStore(object):
    def __init__(self, backend=None):
        if backend is None:
            self.backend = DefaultMessageBackend()
        else:
            self.backend = backend

    def add_message(self, text):
        self.backend.add_message(text)

    def filter_id(self, _id):
        return self.backend.get_by_id(_id, "<No such message id>")

    def random(self):
        return self.backend.random()

    def all(self):
        return self.backend.get_all()

matcher = re.compile(ur'[a-zA-Z0-9-!\\\033\r\n$%^&*()_+\ |~=`{}\[\]:";\'<>?,.\/]', re.U|re.I|re.M)
def validate_message(text):
    if len(text) > 80:
        raise ValidationLengthException()

    mo = matcher.sub('', text)
    if len(mo):
        raise ValidationContentException()

    return text
<|endoftext|>