<commit_before># Create your views here.
# -*- coding: utf-8 -*-

import logging
import random
import json
import sys

from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.views.generic.base import View, TemplateView, RedirectView
from django.views.generic.edit import FormView

from .forms import (
    CountyPerformancePetitionForm, CountyPerformanceSenateForm,
    YouthEmploymentCommentForm, YouthEmploymentSupportForm,
    YouthEmploymentInputForm
)

from pombola.core.models import Person, Place
from pombola.core.views import PersonDetail, PersonDetailSub
from pombola.experiments.views import (
    ExperimentViewDataMixin, ExperimentFormSubmissionMixin,
    sanitize_parameter
)
from pombola.hansard.views import HansardPersonMixin
from pombola.kenya import shujaaz


logger = logging.getLogger('django.request')

EXPERIMENT_DATA = {
    'mit-county': {
        'session_key_prefix': 'MIT',
        'base_view_name': 'county-performance',
        'pageview_label': 'county-performance',
        'template_prefix': 'county',
        'experiment_key': None,
        'qualtrics_sid': 'SV_5hhE4mOfYG1eaOh',
        'variants': ('o', 't', 'n', 'os', 'ts', 'ns'),
        'default_variant': 'n',
        'demographic_keys': {
            'g': ('m', 'f'),
            'agroup': ('under', 'over'),
        },
        'major_partials': [
            '_county_share.html',
            '_county_petition.html',
            '_county_senate.html',
        ],
    },
    'mit-county-larger': {
        'session_key_prefix': 'MIT2',
        'base_view_name': 'county-performance-2',
        'pageview_label': 'county-performance-2',
        'template_prefix': 'county',
        'experiment_key': settings.COUNTY_PERFORMANCE_EXPERIMENT_KEY,
        'qualtrics_sid': 'SV_5hhE4mOfYG1eaOh',
        'variants': ('o', 't', 'n', 'os', 'ts', 'ns'),
        'default_variant': 'n',
        'demographic_keys': {
            'g': ('m', 'f'),
            'agroup': ('under', 'over'),
        },
        'major_partials': [
            '_county_share.html',
            '_county_petition.html',
            '_county_senate.html',
        ],
    },
    'youth-employment-bill': {
        'session_key_prefix': 'MIT3',
        'base_view_name': 'youth-employment',
        'pageview_label': 'youth-employment',
        'template_prefix': 'youth',
        'experiment_key': settings.YOUTH_EMPLOYMENT_BILL_EXPERIMENT_KEY,
        'qualtrics_sid': 'SV_ebVXgzAevcuo2sB',
        'variants': ('y', 'n'),
        'default_variant': 'n',
        'demographic_keys': {
            'g': ('m', 'f'),
            'agroup': ('under', 'over'),
            'pint': ('hi', 'lo'),
        },
        'major_partials': [
            '_youth_share.html',
            '_youth_comment.html',
            '_youth_support.html',
            '_youth_input.html'
        ],
    },
    'youth-employment-bill-generic-no-randomization': {
        'session_key_prefix': 'MIT4',
        'base_view_name': 'youth-employment-n',
        'pageview_label': 'youth-employment-n',
        'template_prefix': 'youth',
        'experiment_key': settings.YOUTH_EMPLOYMENT_BILL_EXPERIMENT_KEY,
        'qualtrics_sid': 'SV_ebVXgzAevcuo2sB',
        'variants': ('n',),
        'default_variant': 'n',
        'demographic_keys': {
            'g': ('m', 'f'),
            'agroup': ('under', 'over'),
            'pint': ('hi', 'lo'),
        },
        'major_partials': [
            '_youth_share.html',
            '_youth_comment.html',
            '_youth_support.html',
            '_youth_input.html'
        ],
    },
}


class KEPersonDetail(HansardPersonMixin, PersonDetail):

    def get_context_data(self, **kwargs):
        context = super(KEPersonDetail, self).get_context_data(**kwargs)
        context['hansard_entries_to_show'] = ":3"

        cdf_constituencies = self.object.constituencies().filter(
            budget_entries__organisation='Constituencies Development Fund'
        ).select_related()

        # We only retrieve one budget because we only really care about the
        # latest. budgets() are default sorted by date of the budget session.
        cdf_budget_constituencies = [
            {'constituency': c, 'budget': c.budgets()[0]}
            for c in cdf_constituencies
        ]

        context['cdf_budget_constituencies'] = cdf_budget_constituencies

        context['shujaaz_finalist_info'] = [
            (
                year,
                'shujaaz-finalists-' + year,
                shujaaz.FINALISTS_DICT[year].get(self.object.pk)
            )
            for year in ('2015', '2014')
            if shujaaz.FINALISTS_DICT[year].get(self.object.pk)
        ]

        political_positions = self.object.position_set.all().political().currently_active()

        na_memberships = political_positions.filter(title__slug='member-national-assembly')
        na_memberships_count = na_memberships.count()
        if na_memberships_count > 1:
            logger.error(
                '{} - Too many NA memberships ({})'.format(self.object.slug, na_memberships_count))

        senate_memberships = political_positions.filter(title__slug='senator')
        senate_memberships_count = senate_memberships.count()
        if senate_memberships_count > 1:
            logger.error(
                '{} - Too many Senate memberships ({})'.format(self.object.slug, senate_memberships_count))

        if na_memberships_count:
            constituencies = Place.objects.filter(position=na_memberships[0]).distinct()
        elif senate_memberships_count:
            constituencies = Place.objects.filter(position=senate_memberships[0]).distinct()
        else:
            constituencies = []

        context['constituencies'] = constituencies

        return context


class KEPersonDetailAppearances(HansardPersonMixin, PersonDetailSub):

    def get_context_data(self, **kwargs):
        context = super(KEPersonDetailAppearances, self).get_context_data(**kwargs)
        context['hansard_entries_to_show'] = ":5"
        context['lifetime_summary'] = context['hansard_entries'] \
            .monthly_appearance_counts()
        return context


class MITExperimentView(ExperimentViewDataMixin, TemplateView):

    def get_context_data(self, **kwargs):<commit_msg>[KE] Get constituency appearing on appearances sub page.<commit_after># Create your views here.
# -*- coding: utf-8 -*-

import logging
import random
import json
import sys

from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.views.generic.base import View, TemplateView, RedirectView
from django.views.generic.edit import FormView

from .forms import (
    CountyPerformancePetitionForm, CountyPerformanceSenateForm,
    YouthEmploymentCommentForm, YouthEmploymentSupportForm,
    YouthEmploymentInputForm
)

from pombola.core.models import Person, Place
from pombola.core.views import PersonDetail, PersonDetailSub
from pombola.experiments.views import (
    ExperimentViewDataMixin, ExperimentFormSubmissionMixin,
    sanitize_parameter
)
from pombola.hansard.views import HansardPersonMixin
from pombola.kenya import shujaaz


logger = logging.getLogger('django.request')

EXPERIMENT_DATA = {
    'mit-county': {
        'session_key_prefix': 'MIT',
        'base_view_name': 'county-performance',
        'pageview_label': 'county-performance',
        'template_prefix': 'county',
        'experiment_key': None,
        'qualtrics_sid': 'SV_5hhE4mOfYG1eaOh',
        'variants': ('o', 't', 'n', 'os', 'ts', 'ns'),
        'default_variant': 'n',
        'demographic_keys': {
            'g': ('m', 'f'),
            'agroup': ('under', 'over'),
        },
        'major_partials': [
            '_county_share.html',
            '_county_petition.html',
            '_county_senate.html',
        ],
    },
    'mit-county-larger': {
        'session_key_prefix': 'MIT2',
        'base_view_name': 'county-performance-2',
        'pageview_label': 'county-performance-2',
        'template_prefix': 'county',
        'experiment_key': settings.COUNTY_PERFORMANCE_EXPERIMENT_KEY,
        'qualtrics_sid': 'SV_5hhE4mOfYG1eaOh',
        'variants': ('o', 't', 'n', 'os', 'ts', 'ns'),
        'default_variant': 'n',
        'demographic_keys': {
            'g': ('m', 'f'),
            'agroup': ('under', 'over'),
        },
        'major_partials': [
            '_county_share.html',
            '_county_petition.html',
            '_county_senate.html',
        ],
    },
    'youth-employment-bill': {
        'session_key_prefix': 'MIT3',
        'base_view_name': 'youth-employment',
        'pageview_label': 'youth-employment',
        'template_prefix': 'youth',
        'experiment_key': settings.YOUTH_EMPLOYMENT_BILL_EXPERIMENT_KEY,
        'qualtrics_sid': 'SV_ebVXgzAevcuo2sB',
        'variants': ('y', 'n'),
        'default_variant': 'n',
        'demographic_keys': {
            'g': ('m', 'f'),
            'agroup': ('under', 'over'),
            'pint': ('hi', 'lo'),
        },
        'major_partials': [
            '_youth_share.html',
            '_youth_comment.html',
            '_youth_support.html',
            '_youth_input.html'
        ],
    },
    'youth-employment-bill-generic-no-randomization': {
        'session_key_prefix': 'MIT4',
        'base_view_name': 'youth-employment-n',
        'pageview_label': 'youth-employment-n',
        'template_prefix': 'youth',
        'experiment_key': settings.YOUTH_EMPLOYMENT_BILL_EXPERIMENT_KEY,
        'qualtrics_sid': 'SV_ebVXgzAevcuo2sB',
        'variants': ('n',),
        'default_variant': 'n',
        'demographic_keys': {
            'g': ('m', 'f'),
            'agroup': ('under', 'over'),
            'pint': ('hi', 'lo'),
        },
        'major_partials': [
            '_youth_share.html',
            '_youth_comment.html',
            '_youth_support.html',
            '_youth_input.html'
        ],
    },
}


class KEPersonDetailBase(PersonDetail):
    def get_context_data(self, **kwargs):
        context = super(KEPersonDetailBase, self).get_context_data(**kwargs)
        context['hansard_entries_to_show'] = ":3"

        cdf_constituencies = self.object.constituencies().filter(
            budget_entries__organisation='Constituencies Development Fund'
        ).select_related()

        # We only retrieve one budget because we only really care about the
        # latest. budgets() are default sorted by date of the budget session.
        cdf_budget_constituencies = [
            {'constituency': c, 'budget': c.budgets()[0]}
            for c in cdf_constituencies
        ]

        context['cdf_budget_constituencies'] = cdf_budget_constituencies

        context['shujaaz_finalist_info'] = [
            (
                year,
                'shujaaz-finalists-' + year,
                shujaaz.FINALISTS_DICT[year].get(self.object.pk)
            )
            for year in ('2015', '2014')
            if shujaaz.FINALISTS_DICT[year].get(self.object.pk)
        ]

        political_positions = self.object.position_set.all().political().currently_active()

        na_memberships = political_positions.filter(title__slug='member-national-assembly')
        na_memberships_count = na_memberships.count()
        if na_memberships_count > 1:
            logger.error(
                '{} - Too many NA memberships ({})'.format(self.object.slug, na_memberships_count))

        senate_memberships = political_positions.filter(title__slug='senator')
        senate_memberships_count = senate_memberships.count()
        if senate_memberships_count > 1:
            logger.error(
                '{} - Too many Senate memberships ({})'.format(self.object.slug, senate_memberships_count))

        if na_memberships_count:
            constituencies = Place.objects.filter(position=na_memberships[0]).distinct()
        elif senate_memberships_count:
            constituencies = Place.objects.filter(position=senate_memberships[0]).distinct()
        else:
            constituencies = []

        context['constituencies'] = constituencies

        return context

class KEPersonDetail(HansardPersonMixin, KEPersonDetailBase):
    pass


class KEPersonDetailAppearances(HansardPersonMixin, PersonDetailSub, KEPersonDetailBase):
    def get_context_data(self, **kwargs):
        context = super(KEPersonDetailAppearances, self).get_context_data(**kwargs)
        context['hansard_entries_to_show'] = ":5"
        context['lifetime_summary'] = context['hansard_entries'] \
            .monthly_appearance_counts()
        return context


class MITExperimentView(ExperimentViewDataMixin, TemplateView):

    def get_context_data(self, **kwargs):
{'fraction_non_alphanumeric': 0.1275713727023856, 'fraction_numerical': 0.004536566288619476, 'mean_word_length': 2.6783659378596085, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6502232', 'n_tokens_mistral': 4064, 'n_tokens_neox': 3965, 'n_words': 674}