def statistics_sets(request, planid):
    result = { 'success': False }

    plan = Plan.objects.filter(id=planid)
    if plan.count() == 0:
        result['message'] = _('No plan with that ID exists.')
        return HttpResponse(json.dumps(result),mimetype='application/json')
    else:
        plan = plan[0]

    if request.method == 'GET':
        sets = []
        scorefunctions = []
            
        # Get the functions available for the users
        user_functions = ScoreFunction.objects.filter(selectable_bodies=plan.legislative_body).order_by('name')
        for f in user_functions:
            if 'report' not in f.name.lower() and 'comments' not in f.name.lower():
                scorefunctions.append({ 'id': f.id, 'name': force_escape(f.get_label()) })
        result['functions'] = scorefunctions

        
        admin_display_names = [
            plan.legislative_body.name % "%s_sidebar_demo",
        ]

        if plan.legislative_body.is_community:
            admin_display_names.append("%s_sidebar_comments" %
                    plan.legislative_body.name)
        else:
            admin_display_names.append("%s_sidebar_basic" %
                    plan.legislative_body.name)
        # Get the admin displays
        admin_displays = ScoreDisplay.objects.filter(
            owner__is_superuser=True,
            legislative_body=plan.legislative_body,
            name__in=admin_display_names
        )

        for admin_display in admin_displays:
            sets.append({ 
                'id': admin_display.id,
                'name': force_escape(admin_display.get_label()),
                'functions': [],
                'mine':False
            })

        try:
            user_displays = ScoreDisplay.objects.filter(
                owner=request.user, 
                legislative_body=plan.legislative_body,
                is_page=False).order_by('title')
            result['displays_count'] = len(user_displays)
            for display in user_displays:
                functions = []
                for panel in display.scorepanel_set.all():
                    if panel.type == 'district':
                        functions = map(lambda x: x.id, panel.score_functions.all())
                        if len(functions) == 0:
                            result['message'] = _("No functions for %(panel)s") % \
                                                {'panel_name': panel}
                sets.append({ 'id': display.id, 'name': force_escape(display.__unicode__()), 'functions': functions, 'mine': display.owner==request.user })
        except Exception, ex:
            result['message'] = _('No user displays for %(user)s') % \
                 {'user': request.user}
            logger.warn('Error fetching ScoreDisplays for user')
            logger.debug('Reason: %s', ex)

        result['sets'] = sets
        result['success'] = True
    # Delete the requested ScoreDisplay to make some room
    elif request.method == 'POST' and 'delete' in request.POST:
        try:
            display = ScoreDisplay.objects.get(pk=request.REQUEST.get('id', -1))
            result['set'] = {'name':force_escape(display.__unicode__()), 'id':display.id}
            qset = display.scorepanel_set.all()
            for panel in qset:
                if panel.displays.count() == 1:
                    panel.delete()
            display.delete()
            result['success'] = True
        except Exception, ex:
            result['message'] = _("Couldn't delete personalized scoredisplay")
            result['exception'] = traceback.format_exc()
            logger.warn("Couldn't delete personalized ScoreDisplay")
            logger.debug('Reason: %s', ex)
            
    # If it's a post, edit or create the ScoreDisplay and return 
    # the id and name as usual
    elif request.method == 'POST':
        # If we're adding a new display, we should make sure they only have 3
        def validate_num(user, limit=3):
            return ScoreDisplay.objects.filter(owner=user, legislative_body=plan.legislative_body, is_page=False).count() < limit

        if 'functions[]' in request.POST:
            functions = request.POST.getlist('functions[]')
            functions = map(lambda x: int(x), functions)
            try:
                display = ScoreDisplay.objects.get(title=request.POST.get('name'), owner=request.user)
                display = display.copy_from(display=display, functions=functions)
            except:
                limit = 3
                if validate_num(request.user, limit):
                    demo = ScoreDisplay.objects.filter(
                        owner__is_superuser=True,
                        legislative_body=plan.legislative_body,
                        is_page=False,
			title="Demographics"
                    )
                    # DO NOT select the ScoreDisplay that contains
                    # the comment calculator
                    for disp in demo:
                        has_comments = False
                        for pnl in disp.scorepanel_set.all():
                            for fn in pnl.score_functions.all():
                                has_comments = has_comments or fn.calculator.endswith('.Comments')
                        if not has_comments:
                            demo = disp
                            break

                    display = ScoreDisplay()
                    display = display.copy_from(display=demo, title=request.POST.get('name'), owner=request.user, functions=functions)
                    result['newRecord'] = True
                else:
                    result['message'] = _('Each user is limited to %(limit)d '
                        'statistics sets. Please delete one or edit '
                        'an existing set.') % { 'limit': limit }
                    result['error'] = 'limit'
                    return HttpResponse(json.dumps(result),mimetype='application/json')

            result['set'] = {'name':force_escape(display.__unicode__()), 'id':display.id, 'functions':functions, 'mine': display.owner==request.user}
            result['success'] = True

        else:
            result['message'] = _("Didn't get functions in POST parameter")

    return HttpResponse(json.dumps(result),mimetype='application/json')

#
# Comment views
#
dataset/ETHPy150Open PublicMapping/DistrictBuilder/django/publicmapping/redistricting/views.py/statistics_sets/swapped operands of `%`