from django.conf.urls import patterns, include, url
from rest_framework.urlpatterns import format_suffix_patterns

# Reference Model Views:
from oarndb.views import AdultChildRelationshipTypesList, AdultChildRelationshipTypesDetail
from oarndb.views import LanguagesList, LanguagesDetail
from oarndb.views import LanguageUseTypesList, LanguageUseTypesDetail
from oarndb.views import AdultFamilyRelationshipTypesList, AdultFamilyRelationshipTypesDetail
from oarndb.views import ChildFamilyRelationshipTypesList, ChildFamilyRelationshipTypesDetail
from oarndb.views import RacesList, RacesDetail
from oarndb.views import GendersList, GendersDetail
from oarndb.views import PersonTelephoneNumberTypesList, PersonTelephoneNumberTypesDetail
from oarndb.views import EmailTypesList, EmailTypesDetail
from oarndb.views import CountiesList, CountiesDetail
from oarndb.views import StatesList, StatesDetail
from oarndb.views import LocationTypesList, LocationTypesDetail
from oarndb.views import RolesList, RolesDetail
from oarndb.views import ContactTypesList, ContactTypesDetail
from oarndb.views import ProgramsList, ProgramsDetail
from oarndb.views import ServiceLevelsList, ServiceLevelsDetail
from oarndb.views import AttendanceStatusesList, AttendanceStatusesDetail
from oarndb.views import TransportTypesList, TransportTypesDetail
from oarndb.views import HomeVisitLocationsList, HomeVisitLocationsDetail
from oarndb.views import ReferredFromList, ReferredFromDetail
from oarndb.views import WaitlistStatusList, WaitlistStatusDetail
from oarndb.views import ServiceNeedList, ServiceNeedDetail

# Family Views:
from oarndb.views import PersonList, PersonDetail, PersonCreate
from oarndb.views import AdultList, AdultDetail
from oarndb.views import ChildList, ChildDetail
from oarndb.views import FamilyList, FamilyDetail, FamilyCreate
from oarndb.views import FamilyAddressList, FamilyAddressDetail, FamilyAddressCreate, FamilyNotesDetail
from oarndb.views import PersonRaceList, PersonRaceDetail, PersonLanguageList, PersonLanguageDetail
from oarndb.views import PersonTelephoneList, PersonTelephoneDetail, PersonEmailAddressList, PersonEmailAddressDetail
from oarndb.views import AdultFamilyRelationshipList, AdultFamilyRelationshipDetail
from oarndb.views import ChildFamilyRelationshipList, ChildFamilyRelationshipDetail

# Program Views:
from oarndb.views import CaseManagerList, CaseManagerCreate, CaseManagerDetail
from oarndb.views import FamilyEnrollmentList, FamilyEnrollmentDetail
from oarndb.views import PersonEnrollmentList, PersonEnrollmentDetail
from oarndb.views import ServiceLevelEnrollmentList, ServiceLevelEnrollmentDetail
from oarndb.views import FamilyEnrollmentReadOnlyList
from oarndb.views import WaitlistList, WaitlistDetail

# Home Visit Views:
from oarndb.views import HomeVisitList, HomeVisitDetail
from oarndb.views import ContactLogList, ContactLogDetail

# Assessment Views:
from oarndb.views import FamilyAssessmentList, FamilyAssessmentDetail
from oarndb.views import ChildAssessmentList, ChildAssessmentDetail
from oarndb.views import RiskFactorAssessmentList, RiskFactorAssessmentDetail
from oarndb.views import ASQList, ASQDetail
from oarndb.views import ASQSEList, ASQSEDetail
from oarndb.views import AssessmentIntervalList, AssessmentIntervalDetail
from oarndb.views import MaritalStatusList, MaritalStatusDetail
from oarndb.views import EmploymentList, EmploymentDetail
from oarndb.views import GrossMonthlyIncomeList, GrossMonthlyIncomeDetail
from oarndb.views import SizeOfFamilyList, SizeOfFamilyDetail
from oarndb.views import EmergencyServicesList, EmergencyServicesDetail
from oarndb.views import ReadingFrequencyList, ReadingFrequencyDetail
from oarndb.views import StrengthsScaleList, StrengthsScaleDetail
from oarndb.views import SmokeExposureScaleList, SmokeExposureScaleDetail
from oarndb.views import QualityScaleList, QualityScaleDetail
from oarndb.views import FrequencyScaleList, FrequencyScaleDetail
from oarndb.views import FrequencyScaleTwoList, FrequencyScaleTwoDetail
from oarndb.views import PrenatalCareList, PrenatalCareDetail
from oarndb.views import ChildWeightList, ChildWeightDetail
from oarndb.views import ChildHeightList, ChildHeightDetail
from oarndb.views import ImmunizationStatusList, ImmunizationStatusDetail
from oarndb.views import AsqseDevStatusList, AsqseDevStatusDetail
from oarndb.views import AsqScreeningAgeList, AsqScreeningAgeDetail
from oarndb.views import AsqseScreeningAgeList, AsqseScreeningAgeDetail
from oarndb.views import YesNoDkList, YesNoDkDetail
from oarndb.views import AsqIntervalList, AsqIntervalDetail
from oarndb.views import AsqseIntervalList, AsqseIntervalDetail

# Attendance Views:
from oarndb.views import ClassroomList, ClassroomDetail
from oarndb.views import ClassScheduleList, ClassScheduleDetail
from oarndb.views import PersonClassScheduleList, PersonClassScheduleDetail
from oarndb.views import PersonAttendanceList, PersonAttendanceDetail
from oarndb.views import CreateAttendanceRecords

# Org Views:
from oarndb.views import OrganizationAccessView, OrganizationLocationList, OrganizationLocationDetail

# Procedural Views:
from oarndb.views import AdultSearchList, ChildSearchList

urlpatterns = (
    url(r'ref/adult-child-relationship-types/$', AdultChildRelationshipTypesList.as_view(),
        name='adult-child-relationship-types-list'),

    url(r'ref/adult-child-relationship-types/(?P<pk>[0-9]+)/$', AdultChildRelationshipTypesDetail.as_view(),
        name='adult-child-relationship-types-detail'),

    url(r'ref/languages/$', LanguagesList.as_view(), name='languages-list'),

    url(r'ref/languages/(?P<pk>[0-9]+)/$', LanguagesDetail.as_view(), name='languages-detail'),

    url(r'ref/language-use-types/$', LanguageUseTypesList.as_view(), name='language-use-types-list'),

    url(r'ref/language-use-types/(?P<pk>[0-9]+)/$', LanguageUseTypesDetail.as_view(), name='language-use-types-detail'),

    url(r'ref/adult-family-relationship-types/$', AdultFamilyRelationshipTypesList.as_view(),
        name='adult-family-relationship-types-list'),

    url(r'ref/adult-family-relationship-types/(?P<pk>[0-9]+)/$', AdultFamilyRelationshipTypesDetail.as_view(),
        name='adult-family-relationship-types-detail'),

    url(r'ref/child-family-relationship-types/$', ChildFamilyRelationshipTypesList.as_view(),
        name='child-family-relationship-types-list'),

    url(r'ref/child-family-relationship-types/(?P<pk>[0-9]+)/$', ChildFamilyRelationshipTypesDetail.as_view(),
        name='child-family-relationship-types-detail'),

    url(r'ref/races/$', RacesList.as_view(), name='races-list'),

    url(r'ref/races/(?P<pk>[0-9]+)/$', RacesDetail.as_view(), name='races-detail'),

    url(r'ref/genders/$', GendersList.as_view(), name='genders-list'),

    url(r'ref/genders/(?P<pk>[0-9]+)/$', GendersDetail.as_view(), name='genders-detail'),

    url(r'ref/person-telephone-number-types/$', PersonTelephoneNumberTypesList.as_view(),
        name='person-telephone-numbers-list'),

    url(r'ref/person-telephone-number-types/(?P<pk>[0-9]+)/$', PersonTelephoneNumberTypesDetail.as_view(),
        name='person-telephone-numbers-detail'),

    url(r'ref/email-types/$', EmailTypesList.as_view(), name='email-types-list'),

    url(r'ref/email-types/(?P<pk>[0-9]+)/$', EmailTypesDetail.as_view(), name='email-types-detail'),

    url(r'ref/counties/$', CountiesList.as_view(), name='counties-list'),

    url(r'ref/counties/(?P<pk>[0-9]+)/$', CountiesDetail.as_view(), name='counties-detail'),

    url(r'ref/states/$', StatesList.as_view(), name='states-list'),

    url(r'ref/states/(?P<pk>[0-9]+)/$', StatesDetail.as_view(), name='states-detail'),

    url(r'ref/location-types/$', LocationTypesList.as_view(), name='location-types-list'),

    url(r'ref/location-types/(?P<pk>[0-9]+)/$', LocationTypesDetail.as_view(), name='location-types-detail'),

    url(r'ref/roles/$', RolesList.as_view(), name='roles-list'),

    url(r'ref/roles/(?P<pk>[0-9]+)/$', RolesDetail.as_view(), name='roles-detail'),

    url(r'ref/contact-types/$', ContactTypesList.as_view(), name='contact-types-list'),

    url(r'ref/contact-types/(?P<pk>[0-9]+)/$', ContactTypesDetail.as_view(), name='contact-types-detail'),

    url(r'ref/programs/$', ProgramsList.as_view(), name='programs-list'),

    url(r'ref/programs/(?P<pk>[0-9]+)/$', ProgramsDetail.as_view(), name='programs-detail'),

    url(r'ref/service-levels/$', ServiceLevelsList.as_view(), name='service-levels-list'),

    url(r'ref/service-levels/(?P<pk>[0-9]+)/$', ServiceLevelsDetail.as_view(), name='service-levels-detail'),

    url(r'ref/attendance-statuses/$', AttendanceStatusesList.as_view()),
    url(r'ref/attendance-statuses/(?P<pk>[0-9]+)/$', AttendanceStatusesDetail.as_view()),
    url(r'ref/transport-types/$', TransportTypesList.as_view()),
    url(r'ref/transport-types/(?P<pk>[0-9]+)/$', TransportTypesDetail.as_view()),
    url(r'ref/home-visit-locations/$', HomeVisitLocationsList.as_view()),
    url(r'ref/home-visit-locations/(?P<pk>[0-9]+)/$', HomeVisitLocationsDetail.as_view()),
    url(r'ref/referred-from/$', ReferredFromList.as_view()),
    url(r'ref/referred-from/(?P<pk>[0-9]+)/$', ReferredFromDetail.as_view()),

    url(r'ref/marital-statuses/$', MaritalStatusList.as_view(), name='marital-status-list'),
    url(r'ref/marital-statuses/(?P<pk>[0-9]+)/$', MaritalStatusDetail.as_view(), name='marital-status-detail'),

    url(r'ref/employment-statuses/$', EmploymentList.as_view(), name='employment-status-list'),
    url(r'ref/employment-statuses/(?P<pk>[0-9]+)/$', EmploymentDetail.as_view(), name='employment-status-detail'),

    url(r'ref/gross-monthly-income/$', GrossMonthlyIncomeList.as_view(), name='gross-monthly-income-list'),
    url(r'ref/gross-monthly-income/(?P<pk>[0-9]+)/$', GrossMonthlyIncomeDetail.as_view(),
        name='gross-monthly-income-detail'),

    url(r'ref/size-of-family/$', SizeOfFamilyList.as_view(), name='size-of-family-list'),
    url(r'ref/size-of-family/(?P<pk>[0-9]+)/$', SizeOfFamilyDetail.as_view(),
        name='size-of-family-detail'),

    url(r'ref/emergency-services/$', EmergencyServicesList.as_view(), name='emergency-services-list'),
    url(r'ref/emergency-services/(?P<pk>[0-9]+)/$', EmergencyServicesDetail.as_view(),
        name='emergency-services-detail'),

    url(r'ref/reading-frequency/$', ReadingFrequencyList.as_view(), name='reading-frequency-list'),
    url(r'ref/reading-frequency/(?P<pk>[0-9]+)/$', ReadingFrequencyDetail.as_view(),
        name='reading-frequency-detail'),

    url(r'ref/strengths-scale/$', StrengthsScaleList.as_view(), name='strengths-scale-list'),
    url(r'ref/strengths-scale/(?P<pk>[0-9]+)/$', StrengthsScaleDetail.as_view(),
        name='strengths-scale-detail'),

    url(r'ref/smoke-exposure-scale/$', SmokeExposureScaleList.as_view(), name='smoke-exposure-scale-list'),
    url(r'ref/smoke-exposure-scale/(?P<pk>[0-9]+)/$', SmokeExposureScaleDetail.as_view(),
        name='smoke-exposure-scale-detail'),

    url(r'ref/quality-scale/$', QualityScaleList.as_view(), name='quality-scale-list'),
    url(r'ref/quality-scale/(?P<pk>[0-9]+)/$', QualityScaleDetail.as_view(),
        name='quality-scale-detail'),

    url(r'ref/assessment-intervals/$', AssessmentIntervalList.as_view(), name='assessment-interval-list'),
    url(r'ref/assessment-intervals/(?P<pk>[0-9]+)/$', AssessmentIntervalDetail.as_view(),
        name='assessment-interval-detail'),

    url(r'ref/frequency-scale/$', FrequencyScaleList.as_view(), name='frequency-scale-list'),
    url(r'ref/frequency-scale/(?P<pk>[0-9]+)/$', FrequencyScaleDetail.as_view(),
        name='frequency-scale-detail'),

    url(r'ref/frequency-scale-two/$', FrequencyScaleTwoList.as_view(), name='frequency-scale-two-list'),
    url(r'ref/frequency-scale-two/(?P<pk>[0-9]+)/$', FrequencyScaleTwoDetail.as_view(),
        name='frequency-scale-two-detail'),

    url(r'ref/yes-no-dk/$', YesNoDkList.as_view(), name='yes-no-dk-list'),
    url(r'ref/yes-no-dk/(?P<pk>[0-9]+)/$', YesNoDkDetail.as_view(),
        name='yes-no-dk-detail'),

    url(r'ref/asq-screening-age/$', AsqScreeningAgeList.as_view(), name='asq-screening-age-list'),
    url(r'ref/asq-screening-age/(?P<pk>[0-9]+)/$', AsqScreeningAgeDetail.as_view(),
        name='asq-screening-age-detail'),

    url(r'ref/asqse-screening-age/$', AsqseScreeningAgeList.as_view(), name='asqse-screening-age-list'),
    url(r'ref/asqse-screening-age/(?P<pk>[0-9]+)/$', AsqseScreeningAgeDetail.as_view(),
        name='asqse-screening-age-detail'),

    url(r'ref/asqse-dev-status/$', AsqseDevStatusList.as_view(), name='asqse-dev-status-list'),
    url(r'ref/asqse-dev-status/(?P<pk>[0-9]+)/$', AsqseDevStatusDetail.as_view(),
        name='asqse-dev-status-detail'),

    url(r'ref/immunization-status/$', ImmunizationStatusList.as_view(), name='immunization-status-list'),
    url(r'ref/immunization-status/(?P<pk>[0-9]+)/$', ImmunizationStatusDetail.as_view(),
        name='immunization-status-detail'),

    url(r'ref/child-height/$', ChildHeightList.as_view(), name='child-height-list'),
    url(r'ref/child-height/(?P<pk>[0-9]+)/$', ChildHeightDetail.as_view(),
        name='child-height-detail'),

    url(r'ref/child-weight/$', ChildWeightList.as_view(), name='child-weight-list'),
    url(r'ref/child-weight/(?P<pk>[0-9]+)/$', ChildWeightDetail.as_view(),
        name='child-weight-detail'),

    url(r'ref/prenatal-care/$', PrenatalCareList.as_view(), name='prenatal-care-list'),
    url(r'ref/prenatal-care/(?P<pk>[0-9]+)/$', PrenatalCareDetail.as_view(),
        name='prenatal-care-detail'),

    url(r'ref/asq-intervals/$', AsqIntervalList.as_view(), name='asq-interval-list'),
    url(r'ref/asq-intervals/(?P<pk>[0-9]+)/$', AsqIntervalDetail.as_view(),
        name='asq-interval-detail'),

    url(r'ref/asqse-intervals/$', AsqseIntervalList.as_view(), name='asqse-interval-list'),
    url(r'ref/asqse-intervals/(?P<pk>[0-9]+)/$', AsqseIntervalDetail.as_view(),
        name='asqse-interval-detail'),

    url(r'ref/service-needs/$', ServiceNeedList.as_view(), name='service-need-list'),
    url(r'ref/service-needs/(?P<pk>[0-9]+)/$', ServiceNeedDetail.as_view(),
        name='service-need-detail'),

    url(r'ref/waitlist-status/$', WaitlistStatusList.as_view(), name='waitlist-status-list'),
    url(r'ref/waitlist-status/(?P<pk>[0-9]+)/$', WaitlistStatusDetail.as_view(),
        name='waitlist-status-detail'),

    # Family Views:
    url(r'family/person/$', PersonList.as_view(), name='person-list'),
    url(r'family/person/(?P<pk>[0-9]+)/$', PersonDetail.as_view(), name='person-detail'),
    url(r'family/person/create/$', PersonCreate.as_view(), name='person-create'),

    url(r'family/adult-search/$', AdultSearchList.as_view(), name='adult-search-list'),
    url(r'family/child-search/$', ChildSearchList.as_view(), name='child-search-list'),

    url(r'family/$', FamilyList.as_view(), name='family-list'),
    url(r'family/(?P<pk>[0-9]+)/$', FamilyDetail.as_view(), name='family-detail'),
    url(r'family/create/$', FamilyCreate.as_view(), name='family-create'),

    url(r'family/addresses/$', FamilyAddressList.as_view(), name='addresses-list'),
    url(r'family/addresses/(?P<pk>[0-9]+)/$', FamilyAddressDetail.as_view(), name='addresses-detail'),
    url(r'family/addresses/create/$', FamilyAddressCreate.as_view(), name='addresses-create'),
    url(r'family/(?P<pk>[0-9]+)/notes/$', FamilyNotesDetail.as_view(), name='family-notes'),

    url(r'family/person/race/$', PersonRaceList.as_view(), name='race-list'),
    url(r'family/person/(?P<pk>[0-9]+)/race/$', PersonRaceDetail.as_view(), name='race-detail'),

    url(r'family/person/language/$', PersonLanguageList.as_view(), name='language-list'),
    url(r'family/person/language/(?P<pk>[0-9]+)/$', PersonLanguageDetail.as_view(), name='language-detail'),

    url(r'family/person/telephone/$', PersonTelephoneList.as_view(), name='telephone-list'),
    url(r'family/person/telephone/(?P<pk>[0-9]+)/$', PersonTelephoneDetail.as_view(), name='telephone-detail'),

    url(r'family/person/email/$', PersonEmailAddressList.as_view(), name='email-list'),
    url(r'family/person/email/(?P<pk>[0-9]+)/$', PersonEmailAddressDetail.as_view(), name='email-detail'),

    url(r'family/adult-family-relationship/$', AdultFamilyRelationshipList.as_view(), name='adult-family-list'),
    url(r'family/adult-family-relationship/(?P<pk>[0-9]+)/$', AdultFamilyRelationshipDetail.as_view(),
        name='adult-family-detail'),

    url(r'family/child-family-relationship/$', ChildFamilyRelationshipList.as_view(), name='child-family-list'),
    url(r'family/child-family-relationship/(?P<pk>[0-9]+)/$', ChildFamilyRelationshipDetail.as_view(),
        name='child-family-detail'),

    url(r'family/adult/$', AdultList.as_view(), name='adult-list'),
    url(r'family/adult/(?P<pk>[0-9]+)/$', AdultDetail.as_view(), name='adult-detail'),

    url(r'family/child/$', ChildList.as_view(), name='child-list'),
    url(r'family/child/(?P<pk>[0-9]+)/$', ChildDetail.as_view(), name='child-detail'),

    # Program Views:
    url(r'program/case-managers/$', CaseManagerList.as_view(), name='case-managers-list'),
    url(r'program/case-managers/(?P<pk>[0-9]+)/$', CaseManagerDetail.as_view(), name='case-managers-detail'),
    url(r'program/case-managers/create/$', CaseManagerCreate.as_view(), name='case-managers-create'),

    url(r'program/family-enrollment/$', FamilyEnrollmentList.as_view(), name='family-enrollment-list'),
    url(r'program/family-enrollment/(?P<pk>[0-9]+)/$', FamilyEnrollmentDetail.as_view(),
        name='family-enrollment-detail'),

    url(r'program/person-enrollment/$', PersonEnrollmentList.as_view(), name='person-enrollment-list'),
    url(r'program/person-enrollment/(?P<pk>[0-9]+)/$', PersonEnrollmentDetail.as_view(),
        name='person-enrollment-detail'),

    url(r'program/service-level-enrollment/$', ServiceLevelEnrollmentList.as_view(), name='service-level-list'),
    url(r'program/service-level-enrollment/(?P<pk>[0-9]+)/$', ServiceLevelEnrollmentDetail.as_view(),
        name='service-level-detail'),

    url(r'program/family-enrollment-full/$', FamilyEnrollmentReadOnlyList.as_view(), name='family-enrollment-full'),

    url(r'program/waitlist/$', WaitlistList.as_view(), name='waitlist-list'),
    url(r'program/waitlist/(?P<pk>[0-9]+)/$', WaitlistDetail.as_view(),
        name='waitlist-detail'),

    # Home Visit Views:
    url(r'family/home-visit/$', HomeVisitList.as_view(), name='home-visit-list'),
    url(r'family/home-visit/(?P<pk>[0-9]+)/$', HomeVisitDetail.as_view(), name='home-visit-detail'),

    url(r'family/contact-log/$', ContactLogList.as_view(), name='contact-log-list'),
    url(r'family/contact-log/(?P<pk>[0-9]+)/$', ContactLogDetail.as_view(), name='contact-log-detail'),

    # Org Views:
    url(r'organization/access/$', OrganizationAccessView.as_view(), name='organization-access-list'),

    url(r'organization/locations/$', OrganizationLocationList.as_view(), name='org-location-list'),
    url(r'organization/locations/(?P<pk>[0-9]+)/$', OrganizationLocationDetail.as_view(), name='org-location-detail'),

    # Assessment Views:
    url(r'assessments/family-assessments/$', FamilyAssessmentList.as_view(), name='family-assessment-list'),
    url(r'assessments/family-assessments/(?P<pk>[0-9]+)/$', FamilyAssessmentDetail.as_view(),
        name='family-assessment-detail'),

    url(r'assessments/child-assessments/$', ChildAssessmentList.as_view(), name='child-assessment-list'),
    url(r'assessments/child-assessments/(?P<pk>[0-9]+)/$', ChildAssessmentDetail.as_view(),
        name='child-assessment-detail'),

    url(r'assessments/risk-factor-assessments/$', RiskFactorAssessmentList.as_view(),
        name='risk-factor-assessment-list'),
    url(r'assessments/risk-factor-assessments/(?P<pk>[0-9]+)/$', RiskFactorAssessmentDetail.as_view(),
        name='risk-factor-assessment-detail'),

    url(r'assessments/asq/$', ASQList.as_view(),
        name='asq-list'),
    url(r'assessments/asq/(?P<pk>[0-9]+)/$', ASQDetail.as_view(),
        name='asq-detail'),

    url(r'assessments/asqse/$', ASQSEList.as_view(),
        name='asq-list'),
    url(r'assessments/asqse/(?P<pk>[0-9]+)/$', ASQSEDetail.as_view(),
        name='asq-detail'),

    # Attendance Views:
    url(r'attendance/classrooms/$', ClassroomList.as_view(), name='classroom-list'),
    url(r'attendance/classrooms/(?P<pk>[0-9]+)/$', ClassroomDetail.as_view(), name='classroom-detail'),

    url(r'attendance/class-schedules/$', ClassScheduleList.as_view(), name='class-schedule-list'),
    url(r'attendance/class-schedules/(?P<pk>[0-9]+)/$', ClassScheduleDetail.as_view(), name='class-schedule-detail'),

    url(r'attendance/person-class-schedules/$', PersonClassScheduleList.as_view(),
        name='person-class-schedule-list'),
    url(r'attendance/person-class-schedules/(?P<pk>[0-9]+)/$', PersonClassScheduleDetail.as_view(),
        name='person-class-schedule-detail'),

    url(r'attendance/person-attendance/$', PersonAttendanceList.as_view(),
        name='person-attendance-list'),
    url(r'attendance/person-attendance/(?P<pk>[0-9]+)/$', PersonAttendanceDetail.as_view(),
        name='person-attendance-detail'),

    url(r'attendance/create-attendance-records/$', CreateAttendanceRecords.as_view(), name='create-attendance-records'),
)

urlpatterns = format_suffix_patterns(urlpatterns)


#  dfs_upperbound.py
#
#   Heuristics - Case: Fruit fly
#   Authors: Mercylyn Wiemer (10749306), Shan Shan Huang (10768793) & Marwa Ahmed (10747141)
#
#   Implements algorithms to find the evolutionary path between fruit fly species.

from .classes.Fruitfly import Fruitfly
import numpy as np

def dfs_upperbound(root_genome):
    """ Depth-First Search (dfs) Random.
    This algorithm takes a
        Args:
            root: genome sequence of fruitfly provided by user.
    """

    print("Depth-First search")

    stack = []
    archive = {}
    current_layer = root_genome.get_generation()
    upperbound = len(root_genome) - 1

    solution = root_genome.solution()
    archive[str(root_genome)] = "parent"
    stack.append(root_genome)
    path = []

    print("Genome fruitfly:", root_genome)

    while stack:
        genome = stack.pop()
        genome_generation = genome.get_generation()

        if genome_generation < upperbound:
            children = genome.create_children()

            np.random.shuffle(children)

            for child in children:
                if child != solution:
                    # if not str(child) in archive.keys():
                    stack.append(child)
                        # current_layer = child.get_generation()
                        # value = "layer:" + str(current_layer)
                        # archive[str(child.get_genes())] = value

                else:
                    upperbound = child.get_generation()
                    path = child.path_solution()
                    path_length = child.path_length()
                    # print("solution found: {}, in layer {}, path: {}, swaps: {}".format(child, upperbound, path, path_length))

    print("Path to solution: ")
    for inversion in range(len(path)):
        print("Inversion: {:2d}".format(inversion), path[inversion])

    return upperbound


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from scipy.ndimage.filters import gaussian_filter

"""

Note: this script has been edited since the blog post to try to improve the
    heat map / test different levels of smoothing.

"""
def myplot(x, y, s, bins=1000):
    heatmap, xedges, yedges = np.histogram2d(x, y, bins=bins)
    heatmap = gaussian_filter(heatmap, sigma=s)

    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
    return heatmap.T, extent

fig, axs = plt.subplots(2, 2)

# Generate some test data
x = []
y = []
with open('predictions.txt', 'r') as fp:
    line = fp.readline()
    x.append(float(line.split(' ')[0]))
    y.append(float(line.split(' ')[1]))

sigmas = [0, 16, 32, 64]

for ax, s in zip(axs.flatten(), sigmas):
    if s == 0:
        ax.plot(x, y, 'k.', markersize=5)
        ax.set_title("Scatter plot")
    else:
        img, extent = myplot(x, y, s)
        ax.imshow(img, extent=extent, origin='lower', cmap=cm.jet)
        ax.set_title("Smoothing with  $\sigma$ = %d" % s)

plt.show()


import os
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
import datetime, json
from dateutil.tz import tzutc
from urllib.parse import urlparse, parse_qs, parse_qsl, urlencode, urlunparse
import qrcode

URL='https://www.e-future.co.kr/audio/info.do?bookkey=1031&cd_num=1'
driver = webdriver.Chrome(ChromeDriverManager().install())

parts = urlparse(URL)

#parse_qs의 결과를 dictionary로 캐스팅
qs = dict(parse_qsl(parts.query))

# 필요한 3-8뽑기 루프
for i in range(3,9):
    # i = 3
    qs['cd_num'] = i
    print(qs)
    parts = parts._replace(query=urlencode(qs))
    new_url = urlunparse(parts)
    print('new_url: ',new_url)
    driver.get(new_url)
    driver.implicitly_wait(4) #로딩까지 4초기다리기
    #li를 감싼 div
    firstList = driver.find_element(By.ID,'book_list')
    # div내에서 li리스트 검색
    titleList = firstList.find_elements(By.TAG_NAME,'li')

    # 치환
    special_char = '\/:*?"<>|' #타이틀에 들어가면 안되는것.
    #li는 여러개 이므로 for로 루프
    for li in titleList:
        aTag = li.find_element(By.TAG_NAME,'a')
        href = aTag.get_attribute('href')
        # print('타이틀: ',aTag.text)
        # print('링크: ',href)

        img = qrcode.make(href)
        fName = aTag.text.replace("\n","")
        for c in special_char:
            if c in fName:
                print(fName.find(c), c)
                fName = fName.replace(c, ' ')

        # print('fName::: ',fName)
        img.save("C:/Users/strin/Desktop/pyProject/ashley/qrImg/    "+fName+".png")
        driver.implicitly_wait(3)
        print(type(img))
        print(img.size)
        driver.implicitly_wait(3)


import math
import pdb
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn import metrics
from tensorflow.python.data import Dataset
import visualizations as vi
from matplotlib import pyplot as plt

def split_train_data(dataframe):

    # shuffle data
    dataframe.reindex(np.random.permutation(dataframe.index))

    # To Do: get file name from the dataframe and create test files using that
    total_rows = dataframe.shape[0]
    train = dataframe.loc[:int(total_rows * 0.6), :]                                # 60% rows for training
    val = dataframe.loc[train.shape[0] : train.shape[0] + int(total_rows * 0.2), :] # 20% rows for validation
    test = dataframe.loc[train.shape[0] + val.shape[0]:, :]                         # 20% rows for testing
    return train, val, test

ALL_FEATURES = [ "longitude",
                  "latitude",
                  "housing_median_age",
                  "total_rooms",
                  "total_bedrooms",
                  "population",
                  "households",
                  "median_income" ]

def get_input_features(dataframe):

    # select everything but the label / target (the value to be predicted)
    selected_features = dataframe[ ALL_FEATURES ]

    # synthesize new features

    # copy the dataframe to avoid modifying the input df
    proccessed_features = selected_features.copy()
    proccessed_features["rooms_per_person"] = proccessed_features["total_rooms"] / proccessed_features["population"]
    return proccessed_features

def get_targets(dataframe):
    # returns a dataframe for target values
    selected_targets = dataframe["median_house_value"]
    return pd.DataFrame(selected_targets.copy() / 1000, columns=["median_house_value"])

def input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):
    """Trains a linear regression model of multiple features.

    Args:
      features: pandas DataFrame of features
      targets: pandas DataFrame of targets
      batch_size: Size of batches to be passed to the model
      shuffle: True or False. Whether to shuffle the data.
      num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely
    Returns:
      Tuple of (features, labels) for next data batch
    """

    # Convert pandas data into a dict of np arrays.
    features = {key:np.array(value) for key,value in dict(features).items()}

    # Construct a dataset, and configure batching/repeating.
    ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit
    ds = ds.batch(batch_size).repeat(num_epochs)

    # Shuffle the data, if specified.
    if shuffle:
      ds = ds.shuffle(10000)

    # Return the next batch of data.
    features, labels = ds.make_one_shot_iterator().get_next()
    return features, labels

def train_model(
    learning_rate,
    steps,
    batch_size,
    training_examples,
    training_targets,
    validation_examples,
    validation_targets):
  """Trains a linear regression model of multiple features.

  In addition to training, this function also prints training progress information,
  as well as a plot of the training and validation loss over time.

  Args:
    learning_rate: A `float`, the learning rate.
    steps: A non-zero `int`, the total number of training steps. A training step
      consists of a forward and backward pass using a single batch.
    batch_size: A non-zero `int`, the batch size.
    training_examples: A `DataFrame` containing one or more columns from
      `california_housing_dataframe` to use as input features for training.
    training_targets: A `DataFrame` containing exactly one column from
      `california_housing_dataframe` to use as target for training.
    validation_examples: A `DataFrame` containing one or more columns from
      `california_housing_dataframe` to use as input features for validation.
    validation_targets: A `DataFrame` containing exactly one column from
      `california_housing_dataframe` to use as target for validation.

  Returns:
    A `LinearRegressor` object trained on the training data.
  """

  periods = 10
  steps_per_period = steps / periods

  print("Steps per period: " + str(steps_per_period))

  # Create a linear regressor object.
  my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
  my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)
  linear_regressor = tf.estimator.LinearRegressor(
      feature_columns=construct_feature_columns(training_examples),
      optimizer=my_optimizer
  )

  # Input functions.
  training_input_fn = lambda: input_fn(training_examples, training_targets["median_house_value"], batch_size = batch_size)
  predict_training_input_fn = lambda: input_fn(training_examples, training_targets["median_house_value"], num_epochs=1, shuffle=False)
  predict_validation_input_fn = lambda: input_fn(validation_examples, validation_targets["median_house_value"], num_epochs=1, shuffle=False)

  # Train the model, but do so inside a loop so that we can periodically assess
  # loss metrics.
  print("Training model...")
  print("RMSE (on training data):")
  training_rmse = []
  validation_rmse = []
  for period in range (0, periods):
    # Train the model, starting from the prior state.
    print(" Period: " + str(period))
    print("     Training")
    linear_regressor.train(
        input_fn=training_input_fn,
        steps=steps_per_period
    )

    print("     Computing Predictions")
    # 2. Take a break and compute predictions.
    training_predictions = linear_regressor.predict(input_fn = predict_training_input_fn)
    training_predictions = np.array([item['predictions'][0] for item in training_predictions])

    validation_predictions = linear_regressor.predict(input_fn = predict_validation_input_fn)
    validation_predictions = np.array([item['predictions'][0] for item in validation_predictions])

    # Compute training and validation loss.
    print("     Computing Loss")
    training_root_mean_squared_error = math.sqrt(
        metrics.mean_squared_error(training_predictions, training_targets))
    validation_root_mean_squared_error = math.sqrt(
        metrics.mean_squared_error(validation_predictions, validation_targets))
    # Occasionally print the current loss.
    print("     RMSE: %0.2f" % (training_root_mean_squared_error))
    # Add the loss metrics from this period to our list.
    training_rmse.append(training_root_mean_squared_error)
    validation_rmse.append(validation_root_mean_squared_error)

  print("Model training finished.")
    # Output a graph of loss metrics over periods.
  vi.plot_rmse_side_by_side(training_rmse, validation_rmse)

  return linear_regressor

def construct_feature_columns(input_features):
      # since all our features are of numeric type, we can construct the TensorFlow Feature Columns
  return set([tf.feature_column.numeric_column(my_feature)
              for my_feature in input_features])

def select_and_transform_features(source_df, relevant_features):
      transformed = source_df[ relevant_features ].copy()
      min = source_df["latitude"].min().astype(int)
      max = source_df["latitude"].max().astype(int)
      BINS = zip(range(min, max), range(min+1, max+1))
      for bin in BINS:
        transformed["latitude"] = source_df["latitude"].apply(
          lambda latitude: 1.0 if (bin[0] <= latitude and latitude < bin[1]) else 0.0
        )
      return transformed

tf.logging.set_verbosity(tf.logging.ERROR)
pd.options.display.max_rows = 10
pd.options.display.float_format = '{:.1f}'.format

california_housing_dataframe = pd.read_csv("./data/california_housing_train.csv")

print("Get an overview of data to figure out some oddities and possible corruption")
# print(california_housing_dataframe.describe())

# create data sets for training, validation and testing
raw_train_data, raw_val_data, raw_test_data = split_train_data(california_housing_dataframe)

# Note: both of the following calls can be combined in a single method but is done this way to make it more clear
train_input_features = get_input_features(raw_train_data)
train_targets = get_targets(raw_train_data)

validation_input_features = get_input_features(raw_val_data)
validation_targets = get_targets(raw_val_data)

# visualizations should be almost same as we have randomized the data, if not then data partition is not uniform
# vi.plot_coolwarm_side_by_side(train_input_features, train_targets, validation_input_features, validation_targets)

# inspect which features are affecting the target so that we are using only those features

correlation_df = train_input_features.copy()
correlation_df["targets"] = train_targets["median_house_value"]
print(correlation_df.corr())

# a positive number means target is directly proportional to feature value and negative means inversely proportional. We pick one, strongly proportional and one inversely proportional

relevant_features = ["median_income", "latitude"]

print("Selected features for training: %s" % relevant_features)
# Tranform and clean the selected features
transformed_train_input_features = select_and_transform_features(train_input_features, relevant_features)
transformed_validation_input_features = select_and_transform_features(validation_input_features, relevant_features)
# Note: We transformed only input features not targets

linear_regressor = train_model(0.01, 500, 50, transformed_train_input_features, train_targets, transformed_validation_input_features, validation_targets)
# Note: if learning rate is small, we would get jagged lines in plot of RMSEs due to jumping in convergence
test_input_features = get_input_features(raw_test_data)
test_targets = get_targets(raw_test_data)

predict_test_input_fn = lambda: input_fn(
                                         test_input_features,
                                         test_targets["median_house_value"],
                                         num_epochs=1,
                                         shuffle=False)

test_predictions = linear_regressor.predict(input_fn= predict_test_input_fn)
test_predictions = np.array([item['predictions'][0] for item in test_predictions])

root_mean_squared_error = math.sqrt(metrics.mean_squared_error(test_predictions, test_targets))
print("Final RMSE (on test data): %0.2f" % root_mean_squared_error)
#


from gc import get_objects

from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator,InvalidPage,EmptyPage

# Create your views here.
from .models import category, product

def allProdCat(request,c_slug=None):
    c_page=None
    products=None

    if c_slug != None:
        c_page=get_object_or_404(category,slug=c_slug)
        products=product.objects.all().filter(category=c_page,available=True)
    else:
        products=product.objects.all().filter(available=True)

    paginator1=Paginator(products,6)
    try:
        page1=int(request.GET.get('page','1'))
    except:
        page1=1
    try:
        prod1=paginator1.page(page1)
    except (EmptyPage,InvalidPage):
        prod1=paginator1.page(paginator1.num_pages)

    return render(request,'category.html',{'category':c_page,'products':products,'pro':prod1})

def proDetail(request,c_slug,p_slug):
    try:
        prod=product.objects.get(category__slug=c_slug,slug=p_slug)
    except Exception as e:
        raise e
    return render(request,'product.html',{'pro_key':prod,})


from django.shortcuts import render
from .forms import StateForm, AirportForm, CallsignForm
from .models import Airport
from .mypy import pathfindingweb as pthfndr

# Create your views here.
def fuel_index(request):
    context = {}
    if request.method == "POST":
        if "callsign-submit" in request.POST:
            form = CallsignForm(request.POST)
            if form.is_valid():
                callsign1 = form.cleaned_data["callsign1"]
                callsign2 = form.cleaned_data["callsign2"]
                ac_cruise = form.cleaned_data["cruise"]
                ac_fuelburn = form.cleaned_data["fuel_burn"]
                ac_fuelcap = form.cleaned_data["fuel_capacity"]
                ac_fueltype = form.cleaned_data["fuel_type"]
                ac_reserves = form.cleaned_data["reserves"]
                ac = form.cleaned_data["aircraft"]
                sigma = form.cleaned_data["sigma"]
                ac_range = (1 - ac_reserves) * ac_fuelcap / ac_fuelburn * ac_cruise  # consider 10% of total fuel capacity is used for reserves
                ac_mileage = ac_cruise / ac_fuelburn

                results = pthfndr.main(str(callsign1), str(callsign2), float(ac_range), float(ac_mileage), ac_fueltype, float(ac_cruise), int(sigma))
    else:
        form = CallsignForm()
        results = None

    context = {'form': form, 'results': results}
    return render(request, 'fuel_index.html', context)

def note_index(request):

    return render(request, 'note_index.html')

def fuel_processing(request):
    context = {}
    return render(request, 'fuel_processing.html', context)


from TestData.excelDemo import sheet

class HomePageData:

    test_HomePage_Data = [{"firstname": "Dagny", "lastname": "Taggart", "gender": "Female"},
                            {"firstname": "Hank", "lastname": "Rearden", "gender": "Male"}]

    @staticmethod
    def getTestData(test_case_name):
        Dict = {}
        # book = openpyxl.load_workbook("/Users/lanabegunova/Downloads/PythonDemo.xlsx")
        # sheet = book.active
        for i in range(1, sheet.max_row + 1):  # get rows
            if sheet.cell(row=i, column=1).value == test_case_name:
                for j in range(2, sheet.max_column + 1):  # get columns
                    #  Dict["lastname"] = "Taggart"
                    Dict[sheet.cell(row=1, column=j).value] = sheet.cell(row=i, column=j).value
        return[Dict]


#
# @lc app=leetcode id=461 lang=python3
#
# [461] Hamming Distance
#

# @lc code=start
from audioop import reverse

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        h = x ^y
        br = bin(h)[2:]
        br = br[::-1]
        f = 0
        for i,n in enumerate(br):
            if n == '1':
                f+=1
        return f
s = Solution()
s.hammingDistance(3,1)
# @lc code=end


from tabula import read_pdf
from tabulate import tabulate
import pandas as pd

df = read_pdf("C:\\Users\\jayzo\\Downloads\\llm_sample_dataset.pdf", pages='1')
df = df[0]

x = list(df.columns)

new_row = pd.DataFrame({'applicant_id': x[0], 'application_date': x[1], 'age': x[2],
                        'cibil_score': x[3], 'loan_type': x[4], 'loan_amount': x[5]},
                       index=[0])

df = df.set_axis(['applicant_id', 'application_date', 'age', 'cibil_score', 'loan_type', 'loan_amount',
                  'interest_rate'], axis=1)

df = pd.concat([new_row, df]).reset_index(drop=True)

# for i in range(2, 5):
#     xdf = read_pdf("C:\\Users\\jayzo\\Downloads\\llm_sample_dataset.pdf", pages=i)
#     xdf = xdf[0]
#
#     x = list(df.columns)
#     xnew_row = pd.DataFrame({'applicant_id': x[0], 'application_date': x[1], 'age': x[2],
#                              'cibil_score': x[3], 'loan_type': x[4], 'loan_amount': x[5]},
#                             index=[0])
#
#     xdf = df.set_axis(['applicant_id', 'application_date', 'age', 'cibil_score', 'loan_type', 'loan_amount',
#                        'interest_rate'], axis=1)
#
#     xdf = pd.concat([xnew_row, xdf]).reset_index(drop=True)
#     print(xdf)
#     # df = pd.concat([df, xdf]).reset_index(drop=True)

print(df)

#
# def async_detect_document(gcs_source_uri, gcs_destination_uri):
#     """OCR with PDF/TIFF as source files on GCS"""
#     import json
#     import re
#     from google.cloud import vision
#     from google.cloud import storage
#
#     # Supported mime_types are: 'application/pdf' and 'image/tiff'
#     mime_type = "application/pdf"
#
#     # How many pages should be grouped into each json output file.
#     batch_size = 2
#
#     client = vision.ImageAnnotatorClient()
#
#     feature = vision.Feature(type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION)
#
#     gcs_source = vision.GcsSource(uri=gcs_source_uri)
#     input_config = vision.InputConfig(gcs_source=gcs_source, mime_type=mime_type)
#
#     gcs_destination = vision.GcsDestination(uri=gcs_destination_uri)
#     output_config = vision.OutputConfig(
#         gcs_destination=gcs_destination, batch_size=batch_size
#     )
#
#     async_request = vision.AsyncAnnotateFileRequest(
#         features=[feature], input_config=input_config, output_config=output_config
#     )
#
#     operation = client.async_batch_annotate_files(requests=[async_request])
#
#     print("Waiting for the operation to finish.")
#     operation.result(timeout=420)
#
#     # Once the request has completed and the output has been
#     # written to GCS, we can list all the output files.
#     storage_client = storage.Client()
#
#     match = re.match(r"gs://([^/]+)/(.+)", gcs_destination_uri)
#     bucket_name = match.group(1)
#     prefix = match.group(2)
#
#     bucket = storage_client.get_bucket(bucket_name)
#
#     # List objects with the given prefix, filtering out folders.
#     blob_list = [
#         blob
#         for blob in list(bucket.list_blobs(prefix=prefix))
#         if not blob.name.endswith("/")
#     ]
#     print("Output files:")
#     for blob in blob_list:
#         print(blob.name)
#
#     # Process the first output file from GCS.
#     # Since we specified batch_size=2, the first response contains
#     # the first two pages of the input file.
#     output = blob_list[0]
#
#     json_string = output.download_as_bytes().decode("utf-8")
#     response = json.loads(json_string)
#
#     # The actual response for the first page of the input file.
#     first_page_response = response["responses"][0]
#     annotation = first_page_response["fullTextAnnotation"]
#
#     # Here we print the full text from the first page.
#     # The response contains more information:
#     # annotation/pages/blocks/paragraphs/words/symbols
#     # including confidence scores and bounding boxes
#     print("Full text:\n")
#     print(annotation["text"])
#
#
# async_detect_document("C:\\Users\\jayzo\\Downloads\\llm_sample_dataset.pdf",
#                       "C:\\Users\\jayzo\\Downloads\\llm_sample_dataset.json")


import time

import cv2
import numpy as np
import torch
from mmcv.runner import get_dist_info

from ..builder import PIPELINES

@PIPELINES.register_module()
class SelectRays:
    """random select rays when training
    Args:
        keys (Sequence[str]): Required keys to be converted.
    """
    def __init__(self,
                 enable=True,
                 sel_n=1024,
                 precrop_iters=0,
                 precrop_frac=0.5,
                 include_radius=False,
                 **kwargs):
        self.enable = enable
        self.precrop_iters = precrop_iters
        self.precrop_frac = precrop_frac
        self.kwargs = kwargs
        self.sel_n = sel_n
        self.include_radius = include_radius

    def __call__(self, results):
        """random select rays when training, support precrop
        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        """
        if self.enable:
            H, W, K = self.kwargs['H'], self.kwargs['W'], self.kwargs['K']
            if self.precrop_iters != 0 and results[
                    'iter_n'] < self.precrop_iters:
                # print(results['iter_n'], "precrop now!", flush=True)
                # 在blender数据集的train时，靠前的iter，只取中间部分训练
                dH = int(H // 2 * self.precrop_frac)
                dW = int(W // 2 * self.precrop_frac)
                coords = torch.stack(
                    torch.meshgrid(
                        torch.linspace(H // 2 - dH, H // 2 + dH - 1, 2 * dH),
                        torch.linspace(W // 2 - dW, W // 2 + dW - 1, 2 * dW)),
                    -1)
            else:
                coords = torch.stack(
                    torch.meshgrid(torch.linspace(0, H - 1, H),
                                   torch.linspace(0, W - 1, W)),
                    -1)  # (H, W, 2)
            coords = torch.reshape(coords, [-1, 2])  # (H * W, 2)

            rank, _ = get_dist_info(
            )  # to aviod sampling same rays over different gpu cards in ddp
            np.random.seed(
                int(time.time() + rank)
            )  # fix a bug, for detials please ref to https://github.com/pytorch/pytorch/issues/5059

            select_inds = np.random.choice(coords.shape[0],
                                           size=[self.sel_n],
                                           replace=False)  # (N_rand,)
            select_coords = coords[select_inds].long()  # (N_rand, 2)
            results['rays_o'] = results['rays_o'][
                select_coords[:, 0], select_coords[:, 1]]  # (N_rand, 3)
            results['rays_d'] = results['rays_d'][
                select_coords[:, 0], select_coords[:, 1]]  # (N_rand, 3)
            results['target_s'] = results['target_s'][
                select_coords[:, 0], select_coords[:, 1]]  # (N_rand, 3)
            if self.include_radius:
                results['radii'] = results['radii'][
                    select_coords[:, 0], select_coords[:, 1]]  # (N_rand, 1)
        return results

    def __repr__(self):
        return '{}:random select rays when training'.format(
            self.__class__.__name__)

@PIPELINES.register_module()
class NBSelectRays:
    """random select rays when training
    Args:
        keys (Sequence[str]): Required keys to be converted.
    """
    def __init__(self,
                 enable=True,
                 sel_n=1024,
                 sel_all=False,
                 sel_rgb=True,
                 **kwargs):
        self.enable = enable
        self.kwargs = kwargs
        self.sel_n = sel_n
        self.sel_all = sel_all
        self.sel_rgb = sel_rgb

    @staticmethod
    def get_bound_2d_mask(bounds, K, pose, H, W):
        min_x, min_y, min_z = bounds[0]
        max_x, max_y, max_z = bounds[1]
        corners_3d = np.array([
            [min_x, min_y, min_z],
            [min_x, min_y, max_z],
            [min_x, max_y, min_z],
            [min_x, max_y, max_z],
            [max_x, min_y, min_z],
            [max_x, min_y, max_z],
            [max_x, max_y, min_z],
            [max_x, max_y, max_z],
        ])

        def project(xyz, K, RT):
            xyz = np.dot(xyz, RT[:, :3].T) + RT[:, 3:].T
            xyz = np.dot(xyz, K.T)
            xy = xyz[:, :2] / xyz[:, 2:]
            return xy

        corners_2d = project(corners_3d, K, pose)
        corners_2d = np.round(corners_2d).astype(int)

        mask = np.zeros((H, W), dtype=np.uint8)
        cv2.fillPoly(mask, [corners_2d[[0, 1, 3, 2, 0]]], 1)
        cv2.fillPoly(mask, [corners_2d[[4, 5, 7, 6, 5]]], 1)
        cv2.fillPoly(mask, [corners_2d[[0, 1, 5, 4, 0]]], 1)
        cv2.fillPoly(mask, [corners_2d[[2, 3, 7, 6, 2]]], 1)
        cv2.fillPoly(mask, [corners_2d[[0, 2, 6, 4, 0]]], 1)
        cv2.fillPoly(mask, [corners_2d[[1, 3, 7, 5, 1]]], 1)
        return mask

    @staticmethod
    def get_near_far(bounds, ray_o, ray_d):
        """calculate intersections with 3d bounding box."""
        norm_d = np.linalg.norm(ray_d, axis=-1, keepdims=True)
        viewdir = ray_d / norm_d
        viewdir[(viewdir < 1e-5) & (viewdir > -1e-10)] = 1e-5
        viewdir[(viewdir > -1e-5) & (viewdir < 1e-10)] = -1e-5
        tmin = (bounds[:1] - ray_o[:1]) / viewdir
        tmax = (bounds[1:2] - ray_o[:1]) / viewdir
        t1 = np.minimum(tmin, tmax)
        t2 = np.maximum(tmin, tmax)
        near = np.max(t1, axis=-1)
        far = np.min(t2, axis=-1)
        mask_at_box = near < far
        near = near[mask_at_box] / norm_d[mask_at_box, 0]
        far = far[mask_at_box] / norm_d[mask_at_box, 0]
        return near, far, mask_at_box

    def sample_rays(self, results, bounds, bound_mask, human_mask):
        # sample pixels and calculate the ray-box intersections
        ray_o_list = []
        ray_d_list = []
        rgb_list = []
        near_list = []
        far_list = []

        nsampled_rays = 0
        while nsampled_rays < self.sel_n:
            n_body = int((self.sel_n - nsampled_rays) * 0.5)
            n_rand = self.sel_n - nsampled_rays - n_body

            # sample rays on body
            coord_body = np.argwhere(human_mask != 0)
            coord_body = coord_body[np.random.randint(0, len(coord_body),
                                                      n_body)]

            # sample rays in the bound mask
            coord = np.argwhere(bound_mask == 1)
            coord = coord[np.random.randint(0, len(coord), n_rand)]
            coord = np.concatenate([coord_body, coord], axis=0)

            # calculate the ray info
            ray_o_ = results['rays_o'][coord[:, 0], coord[:, 1]]
            ray_d_ = results['rays_d'][coord[:, 0], coord[:, 1]]
            if self.sel_rgb:
                rgb_ = results['img'][coord[:, 0], coord[:, 1]]
            near_, far_, mask_at_box = self.get_near_far(
                bounds, ray_o_, ray_d_)

            ray_o_list.append(ray_o_[mask_at_box])
            ray_d_list.append(ray_d_[mask_at_box])
            rgb_list.append(rgb_[mask_at_box])
            near_list.append(near_)
            far_list.append(far_)
            nsampled_rays += len(near_)

        results['rays_o'] = np.concatenate(ray_o_list).astype(np.float32)
        results['rays_d'] = np.concatenate(ray_d_list).astype(np.float32)
        if self.sel_rgb:
            results['target_s'] = np.concatenate(rgb_list).astype(np.float32)
        results['near'] = np.concatenate(near_list).astype(np.float32)[:, None]
        results['far'] = np.concatenate(far_list).astype(np.float32)[:, None]

        return results

    def select_all_rays(self, results, bounds):
        src_shape = results['rays_d'].shape
        results['src_shape'] = torch.tensor(src_shape)

        ray_o = results['rays_o'].reshape(-1, 3).astype(np.float32)
        ray_d = results['rays_d'].reshape(-1, 3).astype(np.float32)
        near, far, mask_at_box = self.get_near_far(bounds, ray_o, ray_d)
        near = near.astype(np.float32)
        far = far.astype(np.float32)
        ray_o = ray_o[mask_at_box]
        ray_d = ray_d[mask_at_box]

        results['rays_o'] = ray_o.astype(np.float32)
        results['rays_d'] = ray_d.astype(np.float32)
        if self.sel_rgb:
            rgb = results['img'].reshape(-1, 3).astype(np.float32)
            rgb = rgb[mask_at_box]
            results['target_s'] = rgb.astype(np.float32)
        results['near'] = near.astype(np.float32)[:, None]
        results['far'] = far.astype(np.float32)[:, None]
        results['mask_at_box'] = mask_at_box

        return results

    def __call__(self, results):
        """random select rays when training, support precrop
        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        """
        if self.enable:
            # calculate the 3D box that bounds the human
            smpl_verts = results['smpl_verts']
            min_xyz = np.min(smpl_verts, axis=0) - 0.05
            max_xyz = np.max(smpl_verts, axis=0) + 0.05
            bounds = np.stack([min_xyz, max_xyz], axis=0)

            # generate regions for sampling
            cfg = results['cfg']
            if cfg.mode == 'render':
                H, W = cfg.render_H, cfg.render_W
            else:
                H, W = results['img'].shape[:2]
            K, R, T = results['cam_K'], results['cam_R'], results['cam_T']
            pose = np.concatenate([R, T], axis=1)
            bound_mask = self.get_bound_2d_mask(bounds, K, pose, H, W)

            if self.sel_all:
                results = self.select_all_rays(results, bounds)
            else:
                human_mask = results['msk'] * bound_mask
                results = self.sample_rays(results, bounds, bound_mask,
                                           human_mask)

        return results

    def __repr__(self):
        return '{}:random select rays when training'.format(
            self.__class__.__name__)

@PIPELINES.register_module()
class PerturbZvals:
    """apply perturb to zvals
    Args:
        keys (Sequence[str]): Required keys to be converted.
    """
    def __init__(self, enable=True, **kwargs):
        self.enable = enable

    def __call__(self, results):
        """get intervals between samples
        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        """
        if self.enable:
            z_vals = results['z_vals']
            # get intervals between samples
            mids = .5 * (z_vals[..., 1:] + z_vals[..., :-1])
            upper = torch.cat([mids, z_vals[..., -1:]], -1)
            lower = torch.cat([z_vals[..., :1], mids], -1)
            t_rand = torch.rand(z_vals.shape).to(z_vals.device)
            results['z_vals'] = lower + (upper - lower) * t_rand
        return results

    def __repr__(self):
        return '{}:apply perturb to zvals'.format(self.__class__.__name__)

@PIPELINES.register_module()
class RandomBGColor:
    """random set background color, used in ngp
    Args:
        keys (Sequence[str]): Required keys to be converted.
    """
    def __init__(self, enable=True, **kwargs):
        self.enable = enable
        self.kwargs = kwargs

    def __call__(self, results):
        """BatchSlice
        Args:
            results (dict): The resulting dict to be modified and passed
                to the next transform in pipeline.
        """
        if self.enable:
            alpha = results['alpha']
            target_s = results['target_s']
            bg_color = np.random.rand(*list(results['target_s'].shape))
            # bg_color = np.zeros(list(results['target_s'].shape))
            target_s = target_s * alpha + bg_color * (1 - alpha)
            results['target_s'] = target_s.astype(np.float32)
            results['bg_color'] = bg_color.astype(np.float32)
        return results

    def __repr__(self):
        return '{}:sample a batch of rays from all rays'.format(
            self.__class__.__name__)


from quopri import decodestring

from .requests import PostRequests, GetRequests

class PageNotFound404:
    def __call__(self, request):
        return "404 WHAT", "404 PAGE Not Found"

class Framework:
    def __init__(self, routes_obj, fronts_obj):
        self.routes_lst = routes_obj
        self.fronts_lst = fronts_obj

    def __call__(self, environ, start_response):
        # получаем параметры запроса
        path = environ["PATH_INFO"]
        method = environ["REQUEST_METHOD"]

        # добавление закрывающего слеша
        if not path.endswith("/"):
            path = f"{path}/"

        request = {
            "method": method,
            "url": path,
        }

        if method == "GET":
            data = GetRequests().get_request_params(environ)
            request["params"] = data
            if len(data) > 0:
                print(f"Пришёл get-запрос с параметрами: {data}")
        if method == "POST":
            data = PostRequests().get_request_params(environ)
            request["params"] = Framework.decode_value(data)
            print(f"Пришёл post-запрос с параметрами: {Framework.decode_value(data)}")

        # находим нужный контроллер
        if path in self.routes_lst:
            view = self.routes_lst[path]
        else:
            view = PageNotFound404()

        # этот словарь получат все контроллеры
        for front in self.fronts_lst:
            front(request)

        # запуск контроллера с передачей объекта request
        code, body = view(request)
        start_response(code, [("Content-Type", "text/html")])
        return [body.encode("utf-8")]

    @staticmethod
    def decode_value(data):
        new_data = {}
        for k, v in data.items():
            val = bytes(v.replace("%", "=").replace("+", " "), "UTF-8")
            val_decode_str = decodestring(val).decode("UTF-8")
            new_data[k] = val_decode_str
        return new_data


import sys
from subprocess import Popen, PIPE
from optparse import OptionParser

def one_input_and_one_output(command, input_string, suffix="\n"):
    p = Popen(command, stdin=PIPE, stdout=PIPE)
    p.stdin.write(input_string + suffix)
    status_code = p.wait()
    return (status_code, p.stdout.read())

def some_input_and_each_output(command, input_string):
    p = Popen(command, stdin=PIPE, stdout=PIPE)
    result = ""
    for istr in input_string.rstrip("\n").split("\n"):
        (out, err) = p.communicate(istr + "\n")
        result += out
    status_code = p.wait()
    return (status_code, result)

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-i", "--input", dest="input", type="string")
    parser.add_option("-t", "--type", dest="type", type="string", default="one_input_and_one_output")
    (options, args) = parser.parse_args()
    (status_code, out) = 0, ""
    if options.type == "one_input_and_one_output":
        (status_code, out) = one_input_and_one_output(args, options.input)
    if options.type == "some_input_and_one_output":
        (status_code, out) = one_input_and_one_output(args, options.input, "")
    if options.type == "some_input_and_each_output":
        (status_code, out) = some_input_and_each_output(args, options.input)
    print(out)
    sys.exit(status_code)


import cv2 as cv
import numpy as np

lower_red = np.array([0, 150, 150])
upper_red = np.array([10, 255, 255])

# Capturing webcam footage
webcam_video = cv.VideoCapture(0)

while True:
    success, video = webcam_video.read()

    img = cv.cvtColor(video, cv.COLOR_BGR2HSV)

    mask = cv.inRange(img, lower_red, upper_red)

    mask_contours, hierarchy = cv.findContours(mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) # Finding contours in mask image

    if len(mask_contours) != 0:
        for mask_contour in mask_contours:
            if cv.contourArea(mask_contour) > 500:
                x, y, w, h = cv.boundingRect(mask_contour)
                cv.rectangle(video, (x, y), (x + w, y + h), (0, 0, 255), 3) #drawing rectangle

    cv.imshow("mask image", mask) # Displaying mask image

    cv.imshow("window", video) # Displaying webcam image

    cv.waitKey(1)


#armar un scrip que lea el archivo "archivo.txt" y crear otro archivo que va
# a contener los primeros 5 caracteres del archivo anterior

with open ("archivo.txt", "r") as mi_arch:
    with open ("archivo.txt", "a") as nuevo:
        nuevo.write(mi_arch.readline(5))

texto_leido = open ("archivo.txt", "r").read()
print (texto_leido)
print (texto_leido[0:6])

with open ("nuevo_archivo.txt", "w") as mi_arch:
    mi_arch.write(texto_leido[0:6])


import re
import random
import copy
import logging
import json
from typing import List, Any

#FROM SIX PAPER:
#try??
#set the (?P<room>kitchen|hall|bedroom) lights to (?P<color>blue|yellow|red)

class _Slot:

    slot_type = None

    def __init__(self, spec):
        self.name: str = spec["name"]
        self.required: bool = spec["required"]
        self.regex_placeholder: str = self.gen_regex_placeholder()

    def gen_regex_placeholder(self) -> str:
        raise NotImplementedError("_Slot is abstract")

    def get_random_value(self) -> Any:
        raise NotImplementedError("_Slot is abstract")

    def __iter__(self):
        for key, value in self.__dict__.items():
            yield key, value

class CategoricalSlot(_Slot):

    slot_type = "CategoricalSlot"

    def __init__(self, spec):
        self.legal_values: List[Any] = spec["legal_values"]
        super(CategoricalSlot, self).__init__(spec)

    def gen_regex_placeholder(self) -> str:
        return f"({'|'.join([str(val) for val in self.legal_values])})"

class NumericalSlot(_Slot):

    slot_type = "NumericalSlot"

    def __init__(self, spec):
        super(NumericalSlot, self).__init__(spec)

    def gen_regex_placeholder(self) -> str:
        return r"[-+]?[0-9]*\.?[0-9]+"

def create_slot(spec: dict) -> _Slot:
    if spec["slot_type"] == "categorical":
        return CategoricalSlot(spec)
    elif spec["slot_type"] == "Numerical":
        return NumericalSlot(spec)
    else:
        raise ValueError(f"Undefined Slot type {spec['slot_type']}")

class Intent:
    def __init__(self, spec: dict, sanitize_fn):
        self.logger = logging.getLogger("six_core.module.nlu.intent")
        self.test(spec)
        self.name = spec["name"]
        self.slots: List[_Slot] = [create_slot(slot_spec) for slot_spec in spec["slots"]]
        self.templates = [sanitize_fn(template) for template in spec["templates"]]
        self.samples = self.gen_samples()

    def gen_regex(self) -> str:
        regex_strs = []
        for template in self.templates:
            for slot in self.slots:
                template_regex_str = template.replace(f"[{slot.name}]", slot.regex_placeholder)
                regex_strs.append(template_regex_str)

        regex_str = '|'.join(regex_strs)
        return regex_str

    def __str__(self):
        return json.dumps({"name":self.name, "slots":[dict(slot) for slot in self.slots]})

    def gen_samples(self) -> list:
        samples = []
        for template in self.templates:
            sample = copy.copy(template)

            for slot in self.slots:
                sample = sample.replace(f"[{slot.name}]", str(slot.get_random_value()))

            self.logger.debug(f"created sample <{sample}>")
            samples.append(sample)

        return samples

    @staticmethod
    def test(spec):
        for key in ["name", "templates", "slots"]:
            try:
                val = spec[key]
            except KeyError:
                raise KeyError(f"Intent Spec missing key <{key}>")
        assert isinstance(spec["templates"], list) and len(spec["templates"]) > 0, f"Intent {spec['name']} has no templates"


"""
Clustering's Tasks
"""
import requests
from common.vectorize import Vectorize
from common.clustering import Clustering
from common import config

def do_clustering(clustering_id, peminjamans, url):
    juduls = []
    distinct_peminjamans = []
    for peminjaman in peminjamans:
        if peminjaman['buku_title'] not in juduls:
            juduls.append(peminjaman['buku_title'])
            distinct_peminjamans.append(peminjaman)
    vectorize = Vectorize(juduls)
    clustering = Clustering(datas=vectorize.vectors, features=vectorize.features, is_scale=True)
    print(clustering)

    peminjaman_by_cluster = {}
    for label in clustering.labels:
        peminjaman_by_cluster[label] = []
    print(peminjaman_by_cluster)

    for peminjaman_idx in range(len(distinct_peminjamans)):
        label = clustering.labels[peminjaman_idx]
        distinct_peminjamans[peminjaman_idx]['label'] = label
        peminjaman_by_cluster[label].append(distinct_peminjamans[peminjaman_idx])
    print(peminjaman_by_cluster)

    for cluster in peminjaman_by_cluster:
        payload = {
            'is_detail': 'true',
            'clustering_id': clustering_id,
            'cluster_label': cluster,
            'cluster_dict': clustering.dicts[cluster]
        }
        r = requests.post(f"{config.SERVER_URL}{url}", data=payload)
        print(f"{r.status_code}: {r.text}")
        for peminjaman in peminjaman_by_cluster[cluster]:
            payload = {
                'is_detail': 'false',
                'clustering_id': clustering_id,
                'cluster_label': cluster,
                'buku_id': peminjaman['buku_id']
            }
            r = requests.post(f"{config.SERVER_URL}{url}", data=payload)
            print(f"{r.status_code}: {r.text}")

    fpgrowth_request = requests.get(f"{config.SERVER_URL}/fpgrowth/?clustering_id={clustering_id}")
    print(f"FPGrowth Request {fpgrowth_request.status_code}: {fpgrowth_request.text}")


class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        mem = {}
        for i, val in enumerate(nums):
            mem[val] = i

        for i, val in enumerate(nums):
            rest = target - val
            if (rest in mem):
                j = mem[rest]
                if (i != j):
                    return [min(i, j), max(i, j)]

    def twoSum_more_simple(self, nums: List[int], target: int) -> List[int]:
        mem = {}

        for i, num in enumerate(nums):
            rest = target - num
            if (rest in mem):
                return [mem[rest], i]
            mem[num] = i


import uuid

from cas import CASPrincipal
from nanohttp import context
from restfulpy.orm import DeclarativeBase, Field, ModifiedMixin, \
    ActivationMixin, SoftDeleteMixin, relationship, DBSession, \
    FilteringMixin, PaginationMixin, OrderingMixin
from restfulpy.principal import JwtRefreshToken
from sqlalchemy import Unicode, Integer, ForeignKey, Boolean, Table

member_block = Table(
    'blocked',
    DeclarativeBase.metadata,
    Field(
        'member_id',
        Integer,
        ForeignKey('member.id'),
        primary_key=True,
    ),
    Field(
        'blocked_member_id',
        Integer,
        ForeignKey('member.id'),
        primary_key=True
    )
)

class MemberContact(DeclarativeBase):
    __tablename__ = 'member_contact'

    member_id = Field(Integer, ForeignKey('member.id'), primary_key=True)
    contact_member_id = Field(Integer, ForeignKey('member.id'), primary_key=True)

class TargetMember(DeclarativeBase):
    __tablename__ = 'target_member'

    target_id = Field(Integer, ForeignKey('target.id'), primary_key=True)
    member_id = Field(Integer, ForeignKey('member.id'), primary_key=True)

class Member(OrderingMixin, FilteringMixin, PaginationMixin, DeclarativeBase):
    __tablename__ = 'member'

    id = Field(Integer, primary_key=True)
    reference_id = Field(Integer, unique=True)
    email = Field(
        Unicode(100),
        unique=True,
        index=True,
        not_none=False,
        required=True,
        min_length=7,
        max_length=100,
        message='Loerm Ipsum',
        label='Email address',
        example='user@example.com',
        watermark='user@example.com',
        pattern=r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)',
        pattern_description='Valid email format, example: user@example.com',
    )
    access_token = Field(Unicode(512), protected=True)

    # FIXME: What is this?
    add_to_room = Field(Boolean, default=True)
    title = Field(
        Unicode(50),
        unique=True,
        index=True,
        nullable=True,
        max_length=20,
        min_length=3,
        label='Username',
        required=True,
        message='Loerm Ipsum',
        not_none=True,
        watermark='John_Doe',
        example='John_Doe',
    )
    phone = Field(
        Unicode(50),
        nullable=True,
        min_length=8,
        max_length=16,
        not_none=False,
        required=False,
        message='Loerm Ipsum',
        label='Phone',
        watermark='Enter your phone number',
        example='734 555 1212',
        pattern=r'\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}'
            r'[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}',
    )
    show_email = Field(Boolean, default=False)
    show_phone = Field(Boolean, default=False)
    avatar = Field(
        Unicode(200),
        label='Avatar',
        nullable=True,
        unique=False,
        not_none=False,
        required=False,
        example='Lorem Ipsum'
    )

    messages = relationship('Envelop')
    contacts = relationship(
        'Member',
        secondary='member_contact',
        primaryjoin=id == MemberContact.member_id,
        secondaryjoin=id == MemberContact.contact_member_id,
        lazy='selectin'
    )
    room = relationship('Room', back_populates='owner')
    blocked_members = relationship( 'Member',
        secondary=member_block,
        primaryjoin=id == member_block.c.member_id,
        secondaryjoin=id == member_block.c.blocked_member_id,
        lazy='selectin'
    )

    def create_jwt_principal(self, session_id=None):
        if session_id is None:
            session_id = str(uuid.uuid4())

        return CASPrincipal(dict(
            id=self.id,
            roles=self.roles,
            email=self.email,
            name=self.title,
            referenceId=self.reference_id,
            sessionId=session_id,
            avatar=self.avatar,
        ))

    def create_refresh_principal(self):
        return JwtRefreshToken(dict(
            id=self.id
        ))

    @classmethod
    def current(cls):
        return DBSession.query(cls) \
            .filter(cls.reference_id == context.identity.reference_id).one()

    def is_member(self, target_id):
        return DBSession.query(Member).join(TargetMember) \
            .filter(
                TargetMember.target_id == target_id,
                TargetMember.member_id == self.id
            ) \
            .count()

    def to_dict(self):
        member_dict = super().to_dict()
        member_dict['phone'] = self.phone if self.show_phone else None
        member_dict['email'] = self.email if self.show_email else None
        return member_dict

    @property
    def roles(self):
        return ['member']

    def __repr__(self):
        return f'Member: {self.id} {self.reference_id} {self.title} {self.email}'


import re
import string

frequency = {}
document_text = open('ЛИТЕРАТУРА.txt', 'r')
text_string = document_text.read().lower()

for i in range (len(data)-1):
    #data[i+1]=data[i+1].split('.,')[:-1]
    #string.data[i+1]find('.')+1.]
    data[i+1] = '.,'.join(data[i+1].split('.,')[:-1])
    print(data[i+1])

match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)
for word in match_pattern:
    count = frequency.get(word, 0)
    frequency[word] = count + 1

frequency_list = frequency.keys()
for words in frequency_list:
    print (words, frequency[words])


# -*- coding: utf-8 -*-
##############################################################################
#
#   ACHIEVE WITHOUT BORDERS
#
##############################################################################

from odoo import api, fields, models
from datetime import datetime

import logging

_logger = logging.getLogger(__name__)

class AccountMove(models.Model):
    _inherit = "account.move"

    statement_line_ids = fields.One2many(
        'account.statement.line', 'move_id', string="Statement Line")
    atm_ref = fields.Char(string="ATM Reference")
    period_covered = fields.Datetime(string="Period Covered")
    total_statement_balance = fields.Float(
        string="Total Statement Balance", compute='_compute_statement_balance')
    is_subscription = fields.Boolean(
        string="Is Subscribtion", compute="_compute_is_subscription")

    @api.depends('invoice_line_ids')
    def _compute_is_subscription(self):
        for rec in self:
            if rec.invoice_line_ids:
                for line in rec.invoice_line_ids:
                    if line.subscription_id:
                        rec.is_subscription = True
                    else:
                        rec.is_subscription = False

    @api.depends('statement_line_ids')
    def _compute_statement_balance(self):
        for rec in self:
            rec.total_statement_balance = sum(
                rec.statement_line_ids.mapped('amount'))

    def action_cron_generate(self):
        records = self.env['account.move'].search(
            [('type', 'in', ['out_invoice', 'in_invoice'])])
        _logger.debug(f'Record Invoice and Bill {records}')

        for rec in records:
            args = [('partner_id', '=', rec.partner_id.id),
                    ('company_id', '=', rec.company_id.id),
                    ('state', '=', 'posted'),
                    ('invoice_ids', 'in', rec.id)]
            payments = rec.env['account.payment'].search(args)

            args_refund = [('partner_id', '=', rec.partner_id.id),
                           ('company_id', '=', rec.company_id.id),
                           ('state', '=', 'posted'),
                           ('reversed_entry_id', '=', rec.id)]

            refunds = rec.env['account.move'].search(args_refund)

            _logger.debug(f'Refunds {refunds}')

            code = ''
            if rec.partner_id.subscriber_location_id.code:
                code = rec.partner_id.subscriber_location_id.code + '-'

            if rec.invoice_date_due:
                ref_date = '-' + rec.invoice_date_due.strftime('%m%y')
            else:
                ref_date = ''

            rec.atm_ref = f'{code}{rec.id:06}{ref_date}'

            lines = []
            # invoice Lines
            for line in rec.invoice_line_ids:
                data = {
                    'name': line.name,
                    'amount': line.credit,
                }
                lines.append((0, 0, data))
            # taxes
            for line in rec.line_ids:
                if line.tax_line_id:
                    data = {'name': line.name}
                    if line.tax_line_id.type_tax_use == 'sale':
                        data['amount'] = line.credit
                    elif line.tax_line_id.type_tax_use == 'purchase':
                        data['amount'] = line.debit
                    else:
                        data['amount'] = 0.0
                    lines.append((0, 0, data))

            # payments
            if payments:
                total_amount = 0
                for line in payments:
                    total_amount += line.amount

                data = {
                    'name': 'Payments',
                    'amount': total_amount * -1,
                }

                lines.append((0, 0, data))

            # refunds
            if refunds:
                total_amount = 0
                for line in refunds:
                    total_amount += (line.amount_total - line.amount_residual)
                data = {
                    'name': 'Credits/Rebates',
                    'amount': total_amount * -1,
                }

                lines.append((0, 0, data))

            _logger.debug(f'Inv Lines {rec.name}{lines}')
            rec.update({'statement_line_ids': None})
            rec.update({'statement_line_ids': lines})

class AccountStatementLine(models.Model):
    _name = "account.statement.line"

    name = fields.Char(string="Description")
    amount = fields.Float(string="Amount")

    move_id = fields.Many2one('account.move', string="Invoice")


from datetime import datetime

from bs4 import BeautifulSoup
import time
from selenium import webdriver
import pendulum

options = webdriver.ChromeOptions()
options.add_argument('--ignore-ssl-errors=yes')
options.add_argument('--ignore-certificate-errors')
driver = webdriver.Remote(
    command_executor='http://185.104.112.241:4444',
    options=options
)

class ConsulParser:
    URL = 'http://www.consultant.ru'

    def buh_ru(self, duration: pendulum.Duration) -> list:
        result = []
        now = pendulum.now('Europe/Moscow')
        checkpoint = now
        while now > (checkpoint - duration):
            RURL = f'{self.URL}/legalnews/chronomap/{now.year}/{now.month}/'
            driver.get(RURL)
            soup = BeautifulSoup(driver.page_source, 'html.parser')
            container = soup.find('div', class_='archive-month__listing')
            for article in container.find_all('div', class_='archive-month__item'):
                title = article.find('span').text
                href = article.find('a').get('href')
                tags = article.get('data-tags')
                date = self.__extract_date(article)
                result.append({
                    'title': title,
                    'href': href,
                    'tags': tags,
                    'date': date
                })
            time.sleep(15)
            now = now - pendulum.duration(months=1)
        return result

    def __extract_date(self, article) -> str:
        iso_date = article.get("data-published-at")
        return datetime.fromisoformat(iso_date).strftime("%Y/%m/%d")

def main():
    parser = ConsulParser()
    a = parser.buh_ru(pendulum.duration(months=1))
    for i in a:
        print(i)

if __name__ == '__main__':
    main()
    driver.quit()


def backtracking(n, depth ,data, val):
    global ans
    if depth>n: #지정된 날을 넘어가면 쓸모없는 정보
        return
    ans = max(ans, val) #그게 아니라면 지금까지 번 돈의 최대를 설정
    for i in range(depth, n):#일하는 날 동안은 다른일을 못하므로 일이 끝난날을 시작점으로
        day, pay = data[i][0], data[i][1] #일하는 걸리는날, 버는 돈
        backtracking(n, i+day, data, val+pay)#현재일+걸리는 시간, 총 번돈을 전달

def dynamic(n,data):
    dp = [0 for _ in range(n+1)]
    for i in range(n):
        day, pay = data[i]
        after = i+day
        if after<=n:
            # 현재값과 바로 직전값중 더 큰값을 선정(지금까지 pay의 누적합이므로),0번 인덱스 일때는 dp[-1]을 찍어서 상관없음
            dp[i] = max(dp[i], dp[i - 1])
            # 현재까지의 누적값과, i번째 값+pay중 더 많이 벌 수 있는것을 선택
            dp[after]=max(dp[after], dp[i]+pay)
    dp.sort()
    print(dp[-1])

if __name__ =="__main__":
    n = int(input())
    data = [list(map(int, input().split())) for _ in range(n)]
    ans = 0
    backtracking(n, 0,  data, 0)
    print(ans)
    dynamic(n,data)

"""
문제
- N+1일째 되는날 퇴사 예정, N일 동안 최대한 많은 상담을 하려함
- https://www.acmicpc.net/problem/14501
- 실버 3
문제 유형
- 그리디, dp, 입력 제한이 (1<=N<=15)개이므로 백트래킹도 가능할 듯
자료구조
- 1차원 리스트(dp 테이블 생성을 위해 사용)
사용한 아이디어
- 상담에 걸리는 시간 : day, 버는돈 : pay
- 현재일까지의 누적합+pay 와 현재일+day 날의 누적합 중 큰 값을 선택
- dp로 풀이 시 dp table의 범위를 넘어가는 값은 사용 불가한 값이므로 무시
- 계산 중 누적합을 계속 업데이트 하기 위해 dp[i] = max(dp[i], dp[i-1]) 해줌
"""


import random
import arcade
import math

SPRITE_SCALING = 0.5
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

class Medal(arcade.Sprite):

    def __init__(self, filename, sprite_scaling):
        """ Constructor. """
        # Call the parent class (Sprite) constructor
        super().__init__(filename, sprite_scaling)

        # Current angle in radians
        self.circle_angle = 0

        # How far away from the center to orbit, in pixels
        self.circle_radius = 0

        # How fast to orbit, in radians per frame
        self.circle_speed = 0.008

        # Set the center of the point we will orbit around
        self.circle_center_x = 0
        self.circle_center_y = 0

    def update(self):

        """ Update the ball's position. """
        # Calculate a new x, y
        self.center_x = self.circle_radius * math.sin(self.circle_angle) \
            + self.circle_center_x
        self.center_y = self.circle_radius * math.cos(self.circle_angle) \
            + self.circle_center_y

        # Increase the angle in prep for the next round.
        self.circle_angle += self.circle_speed

class Alien(arcade.Sprite):
    def update(self):
        self.center_y -= 1
        # See if we went off-screen
        if self.top < 0:
            self.bottom = SCREEN_HEIGHT

class MyGame(arcade.Window):
    """ Main application class. """

    def __init__(self, width, height):

        super().__init__(width, height)

        # Load the sounds from Game Assets for CMSC 150
        self.medal_collect_sound = arcade.load_sound("upgrade4.wav")
        self.alien_collide_sound = arcade.load_sound("lose5.wav")

        # Sprite lists
        self.player_list = None
        self.good_sprite_list = None
        self.bad_sprite_list = None

        # Set up the player
        self.score = 0
        self.player_sprite = None

    def start_new_game(self):
        """ Set up the game and initialize the variables. """

        # Sprite lists
        self.player_list = arcade.SpriteList()
        self.good_sprite_list = arcade.SpriteList()
        self.bad_sprite_list = arcade.SpriteList()

        # Set up the player
        self.score = 0

        # Craft speeder image from kenney.nl
        self.player_sprite = arcade.Sprite("craft_speederA_SE.png", SPRITE_SCALING / 2)
        self.player_sprite.center_x = 50
        self.player_sprite.center_y = 70
        self.player_list.append(self.player_sprite)

        for i in range(50):

            # Create the medal instance
            # Medal image from kenney.nl
            medal = Medal("flat_medal3.png", SPRITE_SCALING / 3)

            # Position the center of the circle the medal will orbit
            medal.circle_center_x = random.randrange(SCREEN_WIDTH)
            medal.circle_center_y = random.randrange(SCREEN_HEIGHT)

            # Random radius from 10 to 200
            medal.circle_radius = random.randrange(10, 200)

            # Random start angle from 0 to 2pi
            medal.circle_angle = random.random() * 2 * math.pi

            # Add the medal to the lists
            self.good_sprite_list.append(medal)

        for i in range(50):
            # Create the alien ship instance
            # Alien ship image from kenney.nl
            alien_ship = Alien("shipBlue_manned.png", SPRITE_SCALING / 3)

            # Position the alien ship
            alien_ship.center_x = random.randrange(SCREEN_WIDTH)
            alien_ship.center_y = random.randrange(SCREEN_HEIGHT)

            # Add the alien ship to the lists
            self.bad_sprite_list.append(alien_ship)

        # Don't show the mouse cursor
        self.set_mouse_visible(False)

        # Set the background color
        arcade.set_background_color(arcade.color.AMAZON)

    def on_draw(self):
        arcade.start_render()

        # Draw all the sprites.
        self.good_sprite_list.draw()
        self.player_list.draw()
        self.bad_sprite_list.draw()

        # Put the text on the screen.
        output = "Score: " + str(self.score)
        arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)

        # Game over when medals have been collected
        if len(self.good_sprite_list) == 0:
            arcade.draw_text("Game Over", 50, 400, arcade.color.WHITE, 125)

    def on_mouse_motion(self, x, y, dx, dy):

        if len(self.good_sprite_list) > 0:
            self.player_sprite.center_x = x
            self.player_sprite.center_y = y

    def update(self, delta_time):
        """ Movement and game logic """

        # Call update on all sprites
        self.good_sprite_list.update()

        # Game continues until medals are all collected
        if len(self.good_sprite_list) > 0:
            self.bad_sprite_list.update()

            # Generate a list of good sprites that collided with the player.
            hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.good_sprite_list)

            # Loop through each colliding sprite, remove it, and add to the score.
            for medal in hit_list:
                self.score += 1
                arcade.play_sound(self.medal_collect_sound)
                medal.remove_from_sprite_lists()

            # Generate a list of bad sprites that collided with the player
            hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.bad_sprite_list)

            for alien_ship in hit_list:
                self.score -= 1
                arcade.play_sound(self.alien_collide_sound)
                alien_ship.remove_from_sprite_lists()

def main():
    window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT)
    window.start_new_game()
    arcade.run()

if __name__ == "__main__":
    main()


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="bioimageit_formats",
    version="0.2.0",
    author="Sylvain Prigent and BioImageIT team",
    author_email="bioimageit@gmail.com",
    description="Manage data formats for BioImageIT project",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/bioimageit/bioimageit_formats",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: BSD License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.7',
    install_requires=[
        "numpy",
        "pandas",
        "scikit-image>=0.18.3",
        "zarr>=2.12.0"
    ],
)


import numpy as np
import cv2
import pandas as pd
import Read_data
from keras.preprocessing import image

def clean_data(img_raw,label_raw,threshold=25):
    bool_arr=np.array(map(lambda x:True if (x.shape[0]>threshold or x.shape[1]>threshold) else False,img_raw))
    return img_raw[bool_arr],label_raw[bool_arr]

def scale_data(img,full_shape=(129,129)):
    def pad_data(img):
        (fh, fw) = full_shape
        (h, w) = img.shape
        result = np.full(full_shape,0)
        result =result.astype(img.dtype)
        if h>w:
            img=cv2.resize(img,(int(w*fh/float(h)),fh))
            (h, w) = img.shape
            y=0 if (fw-w)==0 else np.random.randint(0,fw-w)
            result[:,y:img.shape[1]+y]=img
        else:
            img=cv2.resize(img,(fw,int(h*fw/float(w))))
            (h, w) = img.shape
            x=0 if (fh-h)==0 else np.random.randint(0,fh-h)
            result[x:img.shape[0]+x,:]=img
        return result.reshape(fh,fw,1)
    return np.array(map(pad_data,img))

class augment_class(object):
    def __init__(self):
        pass

    @staticmethod
    def rotate(x, row_axis=0, col_axis=1, channel_axis=2, fill_mode='nearest', cval=0.):
        rotate_limit=(-30, 30)
        theta = np.pi / 180 * np.random.uniform(rotate_limit[0], rotate_limit[1])
        rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0],[np.sin(theta), np.cos(theta), 0],[0, 0, 1]])
        h, w = x.shape[row_axis], x.shape[col_axis]
        transform_matrix = image.transform_matrix_offset_center(rotation_matrix, h, w)
        x = image.apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)
        return x

    @staticmethod
    def shear(x, row_axis=0, col_axis=1, channel_axis=2, fill_mode='nearest', cval=0.):
        intensity=0.5
        sh = np.random.uniform(-intensity, intensity)
        shear=sh
        shear_matrix = np.array([[1, -np.sin(shear), 0],[0, np.cos(shear), 0],[0, 0, 1]])
        h, w = x.shape[row_axis], x.shape[col_axis]
        transform_matrix = image.transform_matrix_offset_center(shear_matrix, h, w)
        x = image.apply_transform(x, transform_matrix, channel_axis, fill_mode, cval)
        return x

def augment_data(img):
    img_rotate=np.array(map(augment_class.rotate,img))
    img_shear=np.array(map(augment_class.shear,img))
    return img,img_rotate,img_shear

if __name__=='__main__':
    img_raw,label_raw=Read_data.load_data()
    img,label=clean_data(img_raw,label_raw)
    img=scale_data(img)
    img,img_rotate,img_shear=augment_data(img)


def solution(m, musicinfos):

    # 샾(#)이 붙은 음은 인덱스 처리가 어려움으로 묶어서 소문자로 전부 치환
    m = m.replace('C#', 'c')
    m = m.replace('D#', 'd')
    m = m.replace('F#', 'f')
    m = m.replace('G#', 'g')
    m = m.replace('A#', 'a')

    melodies = []

    # musicinfos에서 각각 노래의 총 플레이 시간과 악보를 통해 곡별 전체 반복된 악보를 구함
    for music in musicinfos:
        start, end, name, melody = music.split(',')
        duration = (int(end[:2]) - int(start[:2])) * 60 + (int(end[3:]) - int(start[3:]))

        melody = melody.replace('C#', 'c')
        melody = melody.replace('D#', 'd')
        melody = melody.replace('F#', 'f')
        melody = melody.replace('G#', 'g')
        melody = melody.replace('A#', 'a')

        whole_melody = melody * (duration // len(melody)) + melody[:(duration % len(melody))]
        melodies.append((name, duration, whole_melody))

    # 기억한 멜로디와 일치하는 곡이 있으면 그 곡 정보를 answer 리스트에 저장
    answer = []
    index = 0
    for name, duration, melody in melodies:
        if melody.find(m) != -1:
            answer.append((-duration, index, name))
        index += 1

    # 일치하는 멜로디 -> 재생시간이 제일 긴 음악 -> 먼저 입력된 음악 순서에 맞게 오름차순 정렬 후 맨 앞 결과 출력
    answer.sort()
    if answer:
        return answer[0][2]
    else:
        return '(None)'

[3차] 방금그곡 - 김현우.py


import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext

win = tk.Tk()

# 修改标题
win.wm_title("Hello World")

# 窗体设置为不可改变大小
win.resizable(width=False, height=False)

# 创建标签组件并设置布局位置(此处使用网格布局)
ttk.Label(win, text='Enter your name').grid(column=0, row=0)
ttk.Label(win, text='Chose a number').grid(column=1, row=0)

# 定义回调函数
def clickMe():
    action.configure(text="Hello " + nameEntry.get() + numberChosen.get())
    # 关闭按钮组件
    action.configure(state='disabled')

# 定义一个字符串变量，tkinter需要指定变量类型才能够使用
name = tk.StringVar()
# 创建文本框组件(组件关联的窗体，长度，文本变量)并设置网格布局位置
nameEntry = ttk.Entry(win, width=12, textvariable=name)
nameEntry.grid(column=0, row=1)
# 定义游标位置
nameEntry.focus()
# 创建按钮(按钮所关联的窗体，按钮文字，回调函数)
action = ttk.Button(win, text='Click Me', command=clickMe)
action.grid(column=2, row=1)

number = tk.StringVar()
# 创建下拉列表组件(该组件关联的窗体，长度，文本变量，状态为只读若不指定则可编辑)
numberChosen = ttk.Combobox(win, width=12, textvariable=number, state='readonly')
numberChosen.grid(column=1, row=1)
# 创建列表的内容
numberChosen['value'] = (1, 2, 3, 4, 5)
# 设定起始位置索引
numberChosen.current(0)

# 创建整型变量，勾选状态其值为1，非勾选状态其值为0
chVarDis = tk.IntVar()
# 创建checkbutton组件(关联窗体，提示文本，状态变量，组件状态)
check1 = ttk.Checkbutton(win, text='Disabled', variable=chVarDis, state='disabled')
# 设置组件状态变量为关闭状态，勾选
check1.state(['disabled', 'selected'])
# sticky=tk.W表示该组件在网格中左对齐
check1.grid(column=0, row=2, sticky=tk.W)

chVarUn = tk.IntVar()
check2 = ttk.Checkbutton(win, text='Unabled', variable=chVarUn)
# 设置组件状态变量为启动，非勾选
check2.state(['!disabled', '!selected'])
check2.grid(column=1, row=2, sticky=tk.W)

chVarEn = tk.IntVar()
check3 = ttk.Checkbutton(win, text='Enabled', variable=chVarEn)
# 设置组件状态变量为启动，勾选
check3.state(['!disabled', 'selected'])
check3.grid(column=2, row=2, sticky=tk.W)

# 创建颜色列表
colors = ["Blue", "Red", "Gold"]

def radCall():
    radSel = radVar.get()
    if radSel == 0:
        win.configure(background=colors[0])
    elif radSel == 1:
        win.configure(background=colors[1])
    elif radSel == 2:
        win.configure(background=colors[2])

# 创建整数变量
radVar = tk.IntVar()
# 此变量应在列表索引之外的值，否则的话在创建GUI时，被索引到的组件将被选中而并没有调用回调函数
radVar.set(99)

for col in range(len(colors)):
    # 创建radiobutton(关联窗体，提示文本，关联变量，本地变量，回调函数)
    curRad = ttk.Radiobutton(win, text=colors[col], variable=radVar, value=col, command=radCall)
    curRad.grid(column=col, row=3, sticky=tk.W)

# 定义滚动文本框的宽度和高度
scroW = 30
scroH = 3
# 创建滚动文本框(关联窗体，宽度，高度，以单词为单位进行换行)
scr = scrolledtext.ScrolledText(win, width=scroW, height=scroH, wrap=tk.WORD)
# 指定该组件所在网格位置以及跨行个数
scr.grid(column=0, row=4, columnspan=3, sticky='WE')

# 创建标签框架(关联主窗口，标题)
labelsFrame = ttk.Labelframe(win, text='Labels in a Frame')
labelsFrame.grid(column=0, row=5, padx=20, pady=40)
# 在标签框架中创建标签并指定在标签框架中的网格位置
ttk.Label(labelsFrame, text='Label1').grid(column=0, row=0)
ttk.Label(labelsFrame, text='Label2').grid(column=1, row=0)
ttk.Label(labelsFrame, text='Label3').grid(column=2, row=0)
# 为标签框架中的所有组件设置间距
for child in labelsFrame.winfo_children():
    child.grid_configure(padx=8, pady=4)

# 循环监听窗体事件
win.mainloop()

# 最终显示结果比较丑，因为网格布局中的一列宽度是动态的(该列所有组件的最大宽度)，同理一行也是这样


# Simple debug file that will be removed or integrated into gym later (not decided yet)
from Game.Arena import arena
from Game.player import Player
from Animal.abstractAnimal import DebugAnimal
from Animal.Sets.Set1.tier1 import *

def playBattle():
    playerOne = Player()
    playerTwo = Player()

    playerOne.addPet(DebugAnimal(name="Pet0"), 0)
    playerOne.addPet(Ant("Anti"), 1)
    playerOne.addPet(DebugAnimal(name="Pet4"), 4)
    playerTwo.addPet(DebugAnimal(), 0)
    playerTwo.addPet(DebugAnimal(name="Ultra Pet", attack=10, health=10), 1)

    print(f"PlayerOne Team: {str(playerOne)}")
    print(f"PlayerTwo Team: {str(playerTwo)}")

    customArena = arena.Arena()

    customArena.setPlayerOne(playerOne)
    customArena.setPlayerTwo(playerTwo)
    battleInfo = customArena.battle()
    print(battleInfo.winnerMessage)

if __name__ == "__main__":
    playBattle()


import sys

input = sys.stdin.readline

dp = [0] * 1001
dp[1] = 1
for i in range(2, 1001):
    if i % 2 == 0:  # 너비가 짝수면
        dp[i] = (2 * dp[i - 1] + 1) % 10007
    else:  # 너비가 홀수면
        dp[i] = (2 * dp[i - 1] - 1) % 10007

n = int(input())
print(dp[n])


# Created a python program to remove strings in a text filename

infile = "Project-replace.txt"
outfile = "Cleaned-project-replace.txt"

delete_list = ["Stuck? Get a hint"]
fin = open(infile, "rt", encoding='utf8')
fout = open(outfile, "w+")
for line in fin:
    for word in delete_list:
        line = line.replace(word, "")
    fout.write(line)
fin.close()
fout.close()


import networkx as nx
import matplotlib.pyplot as plt

url_graph_file = 'TestDataset/url_graph_file'
url_id_mapping = 'TestDataset/url_id_mapping'

G = nx.DiGraph()

# Read in URL id mapping
url_map = {}
with open(url_id_mapping, 'r') as f:
    for line in f:
        node_id, url = line.strip().split()
        url_map[node_id] = url

# Read in URL graph
with open(url_graph_file, 'r') as f:
    for line in f:
        nodes = line.strip().split()
        source = nodes[0]
        targets = nodes[1:]
        for target in targets:
            G.add_edge(url_map[source], url_map[target])

pr = nx.hits(G)
hubs = pr[0].items()
authority = pr[1].items()

with open("hits_results.txt", "w") as f:
    # Print min and max of PR results
    f.write("Node ID\tHub\tAuthority\n")

    # Print results
    for hub_value, auth_value in zip(hubs, authority):
        f.write(f"Node: {hub_value[0]}, Hubs: {hub_value[1]:.8f}, Authority: {auth_value[1]:.8f}\n")


import unittest

from decimal import Decimal
from unittest import TestCase

from pyspark.sql import types as T

class SparkTestCase(TestCase):

    '''
    Custom TestCase fully dedicated to the unit test between pyspark dataframes
    '''

    def __init__(self, methodName=None):

        if methodName:
            unittest.TestCase.__init__(self, methodName)

    def assertDataFrameEqual(self, df1, df2, verbose=True, msg=None):

        '''
        When two dataframes are equal it means that not only the data but also the metadata is the same
        '''

        df1.cache()
        df2.cache()

        if df1.schema != df2.schema:

            raise self.failureException('DFs schemas are not equal %s : %s' % (df1.schema, df2.schema))

        if any([
            df1.subtract(df2).count() != 0,
            df2.subtract(df1).count() != 0,
        ]):
            df1.show(truncate = False)
            df2.show(truncate = False)

            if verbose:
                print("'{df1} \ {df2}'")
                df1.subtract(df2).show(truncate = False)
                print("'{df2} \ {df1}'")
                df2.subtract(df1).show(truncate = False)

            raise self.failureException('DFs values are not equal %s : %s' %(df1.collect(), df2.collect()))

    def assertDictAlmostEqual(self, d1, d2, places=7):

        '''
        Function that guarantees that the keys and values are the same
        Values being compared up to specified precision
        '''

        self.assertListEqual(sorted(d1.keys()), sorted(d2.keys()))

        def loop(l):

            if not l:

                return None

            i, j = l[0]
            key1, value1 = i
            key2, value2 = j

            if type(value1) != type(value2):

                raise self.failureException('Values are not equal %s : %s' %(value1, value2, key1))

            elif isinstance(value1, dict):

                self.assertDictAlmostEqual(value1, value2, places)

            elif isinstance(value1, Decimal):

                self.assertAlmostEqual(value1, value2, places)

            else:

                self.assertEqual(value1, value2)

            loop(l[1:])

        items = zip(sorted(d1.items()), sorted(d2.items()))

        loop(items)

    def assertDataFrameAlmostEqual(self, df1, df2, places=7):

        '''
        Asserts two dataframes are equal up to an acceptable precision
        '''

        df1.cache()
        df2.cache()

        if df1.schema != df2.schema:

            raise self.failureException('DFs schemas are not equal %s : %s' %(df1.schema, df2.schema))

        if any([
            df1.subtract(df2).count() != 0,
            df2.subtract(df1).count() != 0,
        ]):
            has_decimals = any([isinstance(f.dataType, T.DecimalType) for f in df1.schema.fields])

            if not has_decimals:

                df1.show()
                df2.show()
                raise self.failureException('DFs values are not equal %s : %s' %(df1.collect(), df2.collect()))

            for r1, r2 in zip(sorted(df1.collect(), sorted(df2.collect()))):

                self.assertDictAlmostEqual(r1.asDict(), r2.asDict(), places)


import numpy as np
import matplotlib.pyplot as plt
from scipy.special import factorial
from matplotlib.widgets import Slider

from scipy.stats import expon

def function(la,x):
    return np.exp(-la)*np.power(la,x)/factorial(x)

def exponential(x,scale):
    return expon.pdf(x,0,scale)

x = np.arange(0,20,0.1)
fig, ax = plt.subplots()
line, = ax.plot(x, function(5,x), lw=2)
line2, = ax.plot(x,exponential(x,0.2),'r-',lw=2)
ax.set_ylim(0,0.6)

fig.subplots_adjust(left=0.25, bottom=0.25)
axfreq = fig.add_axes([0.25, 0.1, 0.65, 0.03])
slider = Slider(
    ax = axfreq,
    label='Lambda',
    valmin= 0,
    valmax= 10,
    valinit = 5
)

def update(val):

    Y = function(slider.val,x)
    Y2 = exponential(x,1/slider.val)
    line.set_ydata(Y)
    line2.set_ydata(Y2)
    fig.canvas.draw_idle()

slider.on_changed(update)

plt.show()