from utils import PAD_TOK, START_TOK, END_TOK
import sys
import os

sys.path.append(os.path.join(os.getcwd(), 'tgen'))
from tgen.data import DAI

class TokEmbeddingSeq2SeqExtractor(object):
    def __init__(self, tokenised_texts, max_length=None):
        self.vocab = set()
        for tokens in tokenised_texts:
            self.vocab.update(tokens)
        self.vocab.add(PAD_TOK)
        self.tok_to_embed = {tok: i for i, tok in enumerate(sorted(list(self.vocab)))}
        self.embed_to_tok = {i: tok for i, tok in enumerate(sorted(list(self.vocab)))}
        self.vocab_length = len(self.vocab)
        self.length = max([len(x) for x in tokenised_texts])
        if max_length is not None:
            self.length = min(self.length, max_length)
        self.start_emb = [self.tok_to_embed[START_TOK]]
        self.end_embs = [self.tok_to_embed[END_TOK], self.tok_to_embed[PAD_TOK]]
        self.empty_embedding = [self.tok_to_embed[PAD_TOK] for _ in range(self.length)]

    def get_embeddings(self, tokenised_texts, pad_from_end=True):
        embs = []
        for toks in tokenised_texts:
            emb = [self.tok_to_embed.get(x, self.tok_to_embed[PAD_TOK]) for x in toks]
            pad = [self.tok_to_embed[PAD_TOK] for _ in range(self.length - len(toks))]
            if pad_from_end:
                embs.append(emb + pad)
            else:
                embs.append(pad + emb)
        return [e[:self.length] for e in embs]

    def add_pad_to_embed(self, emb, to_start=False):
        pad = [self.tok_to_embed[PAD_TOK] for _ in range(self.length - len(emb))]
        if to_start:
            return pad + list(emb)
        else:
            return list(emb) + pad

    def reverse_embedding(self, embedding):
        return [self.embed_to_tok[e] for e in embedding]

    def remove_pad_from_embed(self, emb):
        return [x for x in emb if x != self.tok_to_embed[PAD_TOK]]

    def pad_to_length(self, text_emb, to_start=True):
        pads = [self.tok_to_embed[PAD_TOK]] * (self.length - len(text_emb))
        if to_start:
            return pads + text_emb
        else:
            return text_emb + pads

class DAEmbeddingSeq2SeqExtractor(object):
    UNK_ACT = 'UNK_ACT'
    UNK_VALUE = 'UNK_VALUE'
    UNK_SLOT = 'UNK_SLOT'

    def __init__(self, das):
        self.acts = {self.UNK_ACT}
        self.slots = {self.UNK_SLOT}
        self.values = {self.UNK_VALUE}
        self.coocurrence = set()
        for da in das:
            for dai in da:
                self.acts.add(dai.da_type)
                self.slots.add(dai.slot)
                self.values.add(dai.value)
                self.coocurrence.add((dai.da_type, dai.slot, dai.value))
        taken_emb = 0
        self.act_emb = {act: taken_emb + i for i, act in enumerate(sorted(list(self.acts)))}
        self.rev_act_emb = {taken_emb + i: act for i, act in enumerate(sorted(list(self.acts)))}
        taken_emb += len(self.acts)
        self.slot_emb = {slo: taken_emb + i for i, slo in enumerate(sorted(list(self.slots)))}
        self.rev_slot_emb = {taken_emb + i: slo for i, slo in enumerate(sorted(list(self.slots)))}
        taken_emb += len(self.slots)
        self.val_emb = {val: taken_emb + i for i, val in enumerate(sorted(list(self.values)))}
        self.rev_val_emb = {taken_emb + i: val for i, val in enumerate(sorted(list(self.values)))}
        taken_emb += len(self.values)
        self.vocab_length = taken_emb
        self.inclusion_map = {val: i for i, val in enumerate(sorted(list(self.coocurrence)))}
        self.inclusion_rev = {i: val for i, val in enumerate(sorted(list(self.coocurrence)))}
        self.length = max([len(x) for x in das]) * 3
        self.inclusion_length = len(self.inclusion_map)
        self.empty_inclusion = [0 for _ in range(self.inclusion_length)]
        self.empty_embedding = self.get_embeddings([[]])[0]

    def get_embeddings(self, das):
        embs = []
        unk_ack_emb = self.act_emb[self.UNK_ACT]
        unk_slot_emb = self.slot_emb[self.UNK_SLOT]
        unk_val_emb = self.val_emb[self.UNK_VALUE]
        for da in das:
            emb = []
            for dai in sorted(da):
                emb.append(self.act_emb.get(dai.da_type, unk_ack_emb))
                emb.append(self.slot_emb.get(dai.slot, unk_slot_emb))
                emb.append(self.val_emb.get(dai.value, unk_val_emb))

            pad = [unk_ack_emb, unk_slot_emb, unk_val_emb] * (self.length // 3 - len(da))
            embs.append(pad + emb)
        return [e[-self.length:] for e in embs]

    def reverse_embedding(self, da_emb):
        i = 0
        das = []
        while i < len(da_emb):
            act = self.rev_act_emb[da_emb[i]]
            slot = self.rev_slot_emb[da_emb[i + 1]]
            val = self.rev_val_emb[da_emb[i + 2]]
            i += 3
            if act != self.UNK_ACT:
                das.append(DAI(act, slot, val))
        return das

    def remove_pad_from_embed(self, emb):
        results = []
        for i in range(0, len(emb), 3):
            if emb[i] == self.act_emb[self.UNK_ACT] and emb[i + 1] == self.slot_emb[self.UNK_SLOT] and emb[i + 2] == \
                    self.val_emb[self.UNK_VALUE]:
                continue
            results.append(emb[i])
            results.append(emb[i + 1])
            results.append(emb[i + 2])
        return results

    def add_pad_to_embed(self, emb, to_start=True):
        pad = [self.act_emb[self.UNK_ACT], self.slot_emb[self.UNK_SLOT], self.val_emb[self.UNK_VALUE]] \
              * ((self.length - len(emb))//3)
        if to_start:
            return pad+list(emb)
        else:
            return list(emb)+pad

    def get_inclusion(self, das):
        included = set()
        for dai in das:
            if (dai.da_type, dai.slot, dai.value) in self.inclusion_map:
                included.add(self.inclusion_map[(dai.da_type, dai.slot, dai.value)])
        return [(1 if x in included else 0) for x in range(self.inclusion_length)]

    def reverse_inclusion(self, inclusion):
        included = set()
        for i, x in enumerate(inclusion):
            if x == 1:
                included.add(i)
        return [self.inclusion_rev[x] for x in included]

if __name__ == "__main__":
    texts = ["<S> My name is James . <E>", "<S> My favourite food is steak . <E>", "<S> A <E>"]
    tokenized = [x.split(" ") for x in texts]
    print(tokenized)
    emb = TokEmbeddingSeq2SeqExtractor(tokenized)
    print(emb.get_embeddings(tokenized))
    print(emb.get_embeddings([['<S>']]))


from create_functions import create_tag, create_post, create_user, session_add
from models import User, Tag, Post, Base, engine
from sqlalchemy.orm import sessionmaker
import datetime

Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

while True:
    response = input('\n\nWhat to do:\n'
                     'Add user(au) | Add post(ap) | Add tag (at) | Tag some post (tp)\n'
                     'Show all users(su) | Show all posts(sp) | Show all tags(st)\n'
                     'Find post by User(fpu) | Find posts by Tag(fpt) ')

    if response not in ('au', 'ap', 'at', 'tp', 'su', 'sp', 'st', 'fpu', 'fpt', 'cp'):
        print('Wrong command. Reload app')
        exit()

    # Добавить нового пользователя
    elif response == 'au':
        name = input('Enter user nickname: ')
        email = input('Enter user email: ')
        # Base.metadata.create_all(engine)
        # проверка на наличие пользователей(Если пусто - создать первого)
        objects = session.query(User).first()
        if objects is None:
            create_user(name, email)
            print('Добавлен новый пользователь')
        else:
            # проверка на существование пользователя по email
            for email in session.query(User).filter_by(email=email):
                if email:
                    print('Error: User already exists!')
                    exit()

            create_user(name, email)
            print('New user was added')

    # Добавить новый пост
    elif response == 'ap':
        title = input('Enter post title: ')
        text = input('Enter post text: ')
        user_email = input('Enter author email: ')
        # Base.metadata.create_all(engine)
        for email in session.query(User).filter_by(email=user_email):
            if email:
                create_post(title, text, user_email)
                print('New post added: {}'.format(title))
                exit()

        response = input('There is no user with this email - create new user? y/n ')
        if response == 'y':
            name = input('Enter user nickname: ')
            create_user(name, user_email)
            create_post(title, text, user_email)
            print('New post with title: "{}" by new user "{}"'.format(title, name))
        else:
            exit()

    # Добавить новый тег в базу
    elif response == 'at':
        tag_name = input('Enter new TAG name: ')
        # Base.metadata.create_all(engine)
        # проверка на наличие тегов(Если пусто - создать первый)
        objects = session.query(Tag).first()
        if objects is None:
            create_tag(tag_name)
            print('New TAG: {} was added'.format(tag_name))
        else:
            # проверка на существование tag в базе
            for tag_name in session.query(Tag).filter_by(tag_name=tag_name):
                if tag_name:
                    print('Error: TAG already exists!')
                    exit()

            create_tag(tag_name)
            print('New TAG: {} was added'.format(tag_name))

    # Назначаем постам нужные теги
    elif response == 'tp':

        objects = session.query(Post).first()
        if objects is None:

            print('No post yet. Please, add first post!')
            break

        for post in session.query(Post).order_by(Post.id):
            print('\nPost id: {}, title : {}, text: {}, user_email: {}'.format(post.id, post.title, post.text,
                                                                               post.user_email))
        post_id = input('Choose post id which you want to tag: ')
        name_tag = input('Enter tags for this post, use , to split tag names: ').split(',')
        p = session.query(Post).filter_by(id=post_id).first()
        for tag in name_tag:

            if session.query(Tag).filter(Tag.tag_name == tag).first():
                print('Warning: TAG already exists!')
                t = session.query(Tag).filter_by(tag_name=tag).first()

                print(tag)
                p.tags.append(t)
                session.commit()

            else:
                new_tag = Tag(tag_name=tag)
                p = session.query(Post).filter_by(id=post_id).first()
                print(tag)
                p.tags.append(new_tag)
                session.commit()

    # Показать всех пользователей
    elif response == 'su':
        for user in session.query(User).order_by(User.id):
            print('\nUser id: {}, username: {}, email: {}'.format(user.id, user.nickname, user.email))

    # Показать все посты
    elif response == 'sp':
        for post in session.query(Post).order_by(Post.id):
            print('\nPost id: {}, created_at: {}, title : {}, text: {}, user_email: {} updated_at: {}'.format(post.id, post.created_date, post.title, post.text,
                                                                               post.user_email, post.on_update))

    # Показать все теги
    elif response == 'st':
        for tag in session.query(Tag).order_by(Tag.id):
            print('\nTag id: {}, tag_name : {}'.format(tag.id, tag.tag_name))

    # Показать посты по email пользователя
    elif response == 'fpu':
        email = input('Find posts by user email: ')

        for post in session.query(Post).filter_by(user_email=email):
            print('\nPost id: {}, title : {}, text: {}, user_email: {}'.format(post.id, post.title, post.text,
                                                                               post.user_email))

    # Показать посты по выбранному тегу
    elif response == 'fpt':
        tag = input('Find posts by tag: ').split(',')
        for elem in tag:
            tag_id = session.query(Tag.id).filter(Tag.tag_name == elem)

            for i in tag_id:
                for j in i:
                    for post in session.query(Post).join(tags_posts_table).filter_by(tag_id=j):
                        print('\nPost id: {},\n title : {},\n text: {},\n user_email: {}'.format(post.id, post.title,
                                                                                post.text, post.user_email))

    # Редактируем название и текст поста, обновляем updated_at
    elif response == 'cp':
        for post in session.query(Post).order_by(Post.id):
            print('\nPost id: {}, created_at: {}, title : {}, text: {}, user_email: {} updated_at: {}'.format(post.id, post.created_date, post.title, post.text,
                                                                               post.user_email, post.updated_at))
        post_id = input('Choose post ID you want to edit: ')

        post = session.query(Post).filter_by(id = post_id).first()
        print('You want to edit:\n{}'.format(post))
        new_title = input('Enter new titile: ')
        post.title = new_title
        new_text = input('Enter new text: ')
        post.text = new_text
        post.updated_at = datetime.datetime.today()
        session.commit()
        print('Done! Check it out:\n{}'.format(post))


import speech_recognition as sr
import pyaudio

r = sr.Recognizer()
#sr.recognize_google()

#recognizing audio file
#harvard = sr.AudioFile('harvard.wav')
#with harvard as source:
#    r.adjust_for_ambient_noise(source)
#    audio = r.record(source)

#print(r.recognize_google(audio))

#Using mIke

mic = sr.Microphone()

with mic as source:
    audio = r.listen(source)

print(r.recognize_google(audio))


# This file is part of django-ca (https://github.com/mathiasertl/django-ca).
#
# django-ca is free software: you can redistribute it and/or modify it under the terms of the GNU General
# Public License as published by the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# django-ca is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along with django-ca. If not, see
# <http://www.gnu.org/licenses/>.

"""Test :py:mod:`django_ca.profiles`."""

import doctest
import unittest
from datetime import timedelta
from typing import Any, Dict

from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.x509.oid import ExtensionOID, NameOID

from django.conf import settings
from django.test import TestCase, override_settings

from django_ca import ca_settings
from django_ca.constants import EXTENSION_DEFAULT_CRITICAL, EXTENSION_KEYS
from django_ca.models import Certificate, CertificateAuthority
from django_ca.profiles import Profile, get_profile, profile, profiles
from django_ca.signals import pre_sign_cert
from django_ca.tests.base import certs, dns, override_tmpcadir, uri
from django_ca.tests.base.mixins import TestCaseMixin

@override_settings(CA_MIN_KEY_SIZE=1024, CA_DEFAULT_KEY_SIZE=1024)
@unittest.skipIf(  # https://github.com/pyca/cryptography/issues/6363
    settings.CRYPTOGRAPHY_VERSION >= (35, 0), "cg>=35.0 has broken subject name strings"
)
class DocumentationTestCase(TestCaseMixin, TestCase):
    """Test sphinx docs."""

    def setUp(self) -> None:
        super().setUp()
        self.ca = self.load_ca(name=certs["root"]["name"], parsed=certs["root"]["pub"]["parsed"])

    def get_globs(self) -> Dict[str, Any]:
        """Get globals for doctests."""
        return {
            "Profile": Profile,
            "get_profile": get_profile,
            "ca": self.ca,
            "ca_serial": self.ca.serial,
            "csr": certs["root-cert"]["csr"]["parsed"],
        }

    @override_tmpcadir()
    def test_module(self) -> None:
        """Test doctests from main module."""
        # pylint: disable=import-outside-toplevel; we need the top-level module
        from django_ca import profiles as profiles_mod

        doctest.testmod(profiles_mod, globs=self.get_globs())

    @override_tmpcadir()
    def test_python_intro(self) -> None:
        """Test python/profiles.rst."""
        doctest.testfile("../../../docs/source/python/profiles.rst", globs=self.get_globs())

class ProfileTestCase(TestCaseMixin, TestCase):  # pylint: disable=too-many-public-methods
    """Main tests for the profile class."""

    def create_cert(  # type: ignore[override]
        self, prof: Profile, ca: CertificateAuthority, *args: Any, **kwargs: Any
    ) -> Certificate:
        """Shortcut to create a cert with the given profile."""
        cert = Certificate(ca=ca)
        cert.update_certificate(prof.create_cert(ca, *args, **kwargs))
        return cert

    def test_eq(self) -> None:
        """Test profile equality."""
        prof = None
        for name in ca_settings.CA_PROFILES:
            self.assertNotEqual(prof, profiles[name])
            prof = profiles[name]
            self.assertEqual(prof, prof)
            self.assertNotEqual(prof, None)
            self.assertNotEqual(prof, -1)

        self.assertNotEqual(profile, None)

    def test_init_django_ca_values(self) -> None:
        """Test django-ca extensions as extensions."""
        prof1 = Profile(
            "test",
            subject=[("C", "AT"), ("CN", self.hostname)],
            extensions={
                "ocsp_no_check": {},
            },
        )
        prof2 = Profile(
            "test",
            subject=[("C", "AT"), ("CN", self.hostname)],
            extensions={
                "ocsp_no_check": self.ocsp_no_check(),
            },
        )
        self.assertEqual(prof1, prof2)

    def test_init_none_extension(self) -> None:
        """Test profiles that explicitly deactivate an extension."""
        prof = Profile("test", extensions={"ocsp_no_check": None})
        self.assertEqual(
            prof.extensions,
            {ExtensionOID.OCSP_NO_CHECK: None, ExtensionOID.BASIC_CONSTRAINTS: self.basic_constraints()},
        )
        self.assertIsNone(prof.serialize()["extensions"]["ocsp_no_check"])

    def test_init_no_subject(self) -> None:
        """Test with no default subject."""
        # doesn't really occur in the wild, because ca_settings updates CA_PROFILES with the default
        # subject. But it still seems sensible to support this
        default_subject = (("CN", "testcase"),)

        with override_settings(CA_DEFAULT_SUBJECT=default_subject):
            prof = Profile("test")
        self.assertEqual(prof.subject, x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "testcase")]))

    def test_init_x509_subject(self) -> None:
        """Test passing a cryptography subject."""
        subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "testcase")])
        prof = Profile("test", subject=subject)
        self.assertEqual(prof.subject, subject)

    def test_init_expires(self) -> None:
        """Test the expire parameter."""
        prof = Profile("example", expires=30)
        self.assertEqual(prof.expires, timedelta(days=30))

        exp = timedelta(hours=3)
        prof = Profile("example", expires=exp)
        self.assertEqual(prof.expires, exp)

    def test_serialize(self) -> None:
        """Test profile serialization."""

        desc = "foo bar"
        key_usage = ["digital_signature"]
        prof = Profile(
            "test",
            cn_in_san=True,
            description=desc,
            subject=[("CN", self.hostname)],
            extensions={
                EXTENSION_KEYS[ExtensionOID.KEY_USAGE]: {"value": key_usage},
            },
        )
        self.assertEqual(
            prof.serialize(),
            {
                "cn_in_san": True,
                "subject": [("CN", self.hostname)],
                "description": desc,
                "extensions": {
                    EXTENSION_KEYS[ExtensionOID.BASIC_CONSTRAINTS]: {
                        "value": {"ca": False},
                        "critical": EXTENSION_DEFAULT_CRITICAL[ExtensionOID.BASIC_CONSTRAINTS],
                    },
                    EXTENSION_KEYS[ExtensionOID.KEY_USAGE]: {
                        "value": key_usage,
                        "critical": EXTENSION_DEFAULT_CRITICAL[ExtensionOID.KEY_USAGE],
                    },
                },
            },
        )

    @override_tmpcadir()
    def test_create_cert_minimal(self) -> None:
        """Create a certificate with minimal parameters."""
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        csr = certs["child-cert"]["csr"]["parsed"]

        prof = Profile("example", subject=[])
        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof,
                ca,
                csr,
                subject=self.subject,
                add_issuer_alternative_name=False,
            )
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, self.subject)
        self.assertExtensions(
            cert,
            [ca.get_authority_key_identifier_extension(), self.subject_alternative_name(dns(self.hostname))],
        )

    @override_tmpcadir()
    def test_alternative_values(self) -> None:
        """Test overriding most values."""
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        ca.issuer_alt_name = "https://example.com"
        ca.save()
        csr = certs["child-cert"]["csr"]["parsed"]
        country_name = x509.NameAttribute(NameOID.COUNTRY_NAME, "AT")
        subject = x509.Name([country_name, x509.NameAttribute(NameOID.COMMON_NAME, self.hostname)])

        prof = Profile("example", subject=[])

        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof,
                ca,
                csr,
                subject=x509.Name([country_name]),
                algorithm=hashes.SHA256(),
                expires=timedelta(days=30),
                extensions=[self.subject_alternative_name(dns(self.hostname))],
            )
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.cn, self.hostname)
        self.assertEqual(cert.subject, subject)
        self.assertExtensions(
            cert,
            [
                ca.get_authority_key_identifier_extension(),
                self.issuer_alternative_name(uri(ca.issuer_alt_name)),
                self.subject_alternative_name(dns(self.hostname)),
            ],
        )

    @override_tmpcadir()
    def test_overrides(self) -> None:
        """Test other overrides."""
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        csr = certs["child-cert"]["csr"]["parsed"]
        country_name = x509.NameAttribute(NameOID.COUNTRY_NAME, "AT")
        expected_subject = x509.Name([country_name, x509.NameAttribute(NameOID.COMMON_NAME, self.hostname)])

        prof = Profile(
            "example",
            subject=[("C", "AT")],
            add_crl_url=False,
            add_ocsp_url=False,
            add_issuer_url=False,
            add_issuer_alternative_name=False,
        )
        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(prof, ca, csr, subject=self.subject)
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, expected_subject)
        self.assertEqual(cert.ca, ca)

        self.assertExtensions(
            cert,
            [
                self.subject_key_identifier(cert),
                ca.get_authority_key_identifier_extension(),
                self.basic_constraints(),
                self.subject_alternative_name(dns(self.hostname)),
            ],
            expect_defaults=False,
        )

        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof,
                ca,
                csr,
                subject=self.subject,
                add_crl_url=True,
                add_ocsp_url=True,
                add_issuer_url=True,
                add_issuer_alternative_name=True,
            )
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, expected_subject)
        self.assertEqual(cert.ca, ca)
        self.assertExtensions(
            cert,
            [
                ca.get_authority_key_identifier_extension(),
                self.basic_constraints(),
                self.subject_alternative_name(dns(self.hostname)),
            ],
        )

    @override_tmpcadir()
    def test_none_extension(self) -> None:
        """Test passing an extension that is removed by the profile."""
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        csr = certs["child-cert"]["csr"]["parsed"]
        prof = Profile("example", subject=[("C", "AT")], extensions={"ocsp_no_check": None})

        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(prof, ca, csr, subject=self.subject, extensions=[self.ocsp_no_check()])
        self.assertEqual(pre.call_count, 1)
        self.assertNotIn(ExtensionOID.OCSP_NO_CHECK, cert.x509_extensions)

    @override_tmpcadir()
    def test_cn_in_san(self) -> None:
        """Test writing the common name into the SAN."""
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        csr = certs["child-cert"]["csr"]["parsed"]
        subject = x509.Name(
            [
                x509.NameAttribute(NameOID.COUNTRY_NAME, "AT"),
                x509.NameAttribute(NameOID.COMMON_NAME, self.hostname),
            ]
        )

        prof = Profile("example", subject=[("C", "AT")], add_issuer_alternative_name=False, cn_in_san=False)
        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(prof, ca, csr, subject=self.subject)
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, subject)
        self.assertExtensions(cert, [ca.get_authority_key_identifier_extension()])

        # Create the same cert, but pass cn_in_san=True to create_cert
        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(prof, ca, csr, subject=self.subject, cn_in_san=True)
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, subject)
        self.assertExtensions(
            cert,
            [ca.get_authority_key_identifier_extension(), self.subject_alternative_name(dns(self.hostname))],
        )

        # test that cn_in_san=True with a SAN that already contains the CN does not lead to a duplicate
        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof,
                ca,
                csr,
                subject=self.subject,
                cn_in_san=True,
                extensions=[self.subject_alternative_name(dns(self.hostname))],
            )
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, subject)
        self.assertExtensions(
            cert,
            [ca.get_authority_key_identifier_extension(), self.subject_alternative_name(dns(self.hostname))],
        )

        # test that cn_in_san=True with a SAN that does NOT yet contain the CN, so it's added
        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof,
                ca,
                csr,
                subject=self.subject,
                cn_in_san=True,
                extensions=[self.subject_alternative_name(dns(self.hostname + ".added"))],
            )
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, subject)
        self.assertExtensions(
            cert,
            [
                ca.get_authority_key_identifier_extension(),
                self.subject_alternative_name(dns(self.hostname + ".added"), dns(self.hostname)),
            ],
        )

        # test that the first SAN is added as CN if we don't have A CN
        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof, ca, csr, cn_in_san=True, extensions=[self.subject_alternative_name(dns(self.hostname))]
            )
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, subject)
        self.assertExtensions(
            cert,
            [ca.get_authority_key_identifier_extension(), self.subject_alternative_name(dns(self.hostname))],
        )

    @override_tmpcadir()
    def test_override_ski(self) -> None:
        """Test overriding the subject key identifier."""
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        csr = certs["child-cert"]["csr"]["parsed"]
        ski = x509.Extension(
            oid=ExtensionOID.SUBJECT_KEY_IDENTIFIER,
            critical=False,
            value=x509.SubjectKeyIdentifier(b"custom value"),
        )

        prof = Profile("example", subject=[])
        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof,
                ca,
                csr,
                subject=self.subject,
                add_crl_url=False,
                add_ocsp_url=False,
                add_issuer_url=False,
                add_issuer_alternative_name=False,
                extensions=[ski],
            )
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, self.subject)
        self.assertExtensions(
            cert,
            [
                ca.get_authority_key_identifier_extension(),
                self.basic_constraints(),
                self.subject_alternative_name(dns(self.hostname)),
                ski,
            ],
            expect_defaults=False,
        )

    @override_tmpcadir()
    def test_add_distribution_point_with_ca_crldp(self) -> None:
        """Pass a custom distribution point when creating the cert, which matches ca.crl_url"""
        prof = Profile("example", subject=[])
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        csr = certs["child-cert"]["csr"]["parsed"]

        # Add CRL url to CA
        ca.crl_url = "https://crl.ca.example.com"
        ca.save()

        added_crldp = self.crl_distribution_points([uri(ca.crl_url)])

        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof,
                ca,
                csr,
                subject=self.subject,
                add_crl_url=True,
                add_ocsp_url=False,
                add_issuer_url=False,
                add_issuer_alternative_name=False,
                extensions=[added_crldp],
            )
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, self.subject)
        ski = x509.SubjectKeyIdentifier.from_public_key(cert.pub.loaded.public_key())

        self.assertExtensions(
            cert,
            [
                ca.get_authority_key_identifier_extension(),
                self.basic_constraints(),
                x509.Extension(oid=ExtensionOID.SUBJECT_KEY_IDENTIFIER, critical=False, value=ski),
                self.subject_alternative_name(dns(self.hostname)),
                added_crldp,
            ],
            expect_defaults=False,
        )

    @override_tmpcadir()
    def test_with_algorithm(self) -> None:
        """Test a profile that manually overrides the algorithm"""

        root = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        csr = certs["child-cert"]["csr"]["parsed"]

        prof = Profile("example", subject=[], algorithm="SHA-512")

        # Make sure that algorithm does not match what is the default profile above, so that we can test it
        self.assertIsInstance(root.algorithm, hashes.SHA256)

        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof,
                root,
                csr,
                subject=self.subject,
                add_crl_url=True,
                add_ocsp_url=False,
                add_issuer_url=False,
                add_issuer_alternative_name=False,
            )
        self.assertEqual(pre.call_count, 1)
        self.assertIsInstance(cert.algorithm, hashes.SHA512)

    @override_tmpcadir()
    def test_issuer_alternative_name_override(self) -> None:
        """Pass a custom Issuer Alternative Name which overwrites the CA value."""
        prof = Profile("example", subject=[])
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        csr = certs["child-cert"]["csr"]["parsed"]

        # Add CRL url to CA
        ca.issuer_alt_name = "https://ian.ca.example.com"
        ca.save()

        added_ian_uri = uri("https://ian.cert.example.com")
        added_ian = self.issuer_alternative_name(added_ian_uri)

        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof,
                ca,
                csr,
                subject=self.subject,
                add_crl_url=False,
                add_ocsp_url=False,
                add_issuer_url=False,
                add_issuer_alternative_name=True,
                extensions=[added_ian],
            )
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, self.subject)
        ski = x509.SubjectKeyIdentifier.from_public_key(cert.pub.loaded.public_key())

        self.assertExtensions(
            cert,
            [
                ca.get_authority_key_identifier_extension(),
                self.basic_constraints(),
                x509.Extension(oid=ExtensionOID.SUBJECT_KEY_IDENTIFIER, critical=False, value=ski),
                self.subject_alternative_name(dns(self.hostname)),
                self.issuer_alternative_name(added_ian_uri),
            ],
            expect_defaults=False,
        )

    @override_tmpcadir()
    def test_merge_authority_information_access_existing_values(self) -> None:
        """Pass a custom distribution point when creating the cert, which matches ca.crl_url"""
        prof = Profile("example", subject=[])
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        csr = certs["child-cert"]["csr"]["parsed"]

        # Add CRL url to CA
        ca.ocsp_url = "https://ocsp.ca.example.com"
        ca.issuer_url = "https://issuer.ca.example.com"
        ca.save()

        cert_issuers = uri("https://issuer.cert.example.com")
        cert_issuers2 = uri("https://issuer2.cert.example.com")
        cert_ocsp = uri("https://ocsp.cert.example.com")

        added_aia = self.authority_information_access(
            ca_issuers=[cert_issuers, cert_issuers2], ocsp=[cert_ocsp]
        )

        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof,
                ca,
                csr,
                subject=self.subject,
                add_crl_url=False,
                add_ocsp_url=True,
                add_issuer_url=True,
                add_issuer_alternative_name=False,
                extensions=[added_aia],
            )
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, self.subject)

        ski = x509.SubjectKeyIdentifier.from_public_key(cert.pub.loaded.public_key())

        self.assertExtensions(
            cert,
            [
                ca.get_authority_key_identifier_extension(),
                self.basic_constraints(),
                x509.Extension(oid=ExtensionOID.SUBJECT_KEY_IDENTIFIER, critical=False, value=ski),
                self.subject_alternative_name(dns(self.hostname)),
                self.authority_information_access(
                    ca_issuers=[cert_issuers, cert_issuers2],
                    ocsp=[cert_ocsp],
                ),
            ],
            expect_defaults=False,
        )

    @override_tmpcadir()
    def test_extension_as_cryptography(self) -> None:
        """Test with a profile that has cryptography extensions."""
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        csr = certs["child-cert"]["csr"]["parsed"]

        prof = Profile("example", subject=[], extensions={EXTENSION_KEYS[ExtensionOID.OCSP_NO_CHECK]: {}})
        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof,
                ca,
                csr,
                subject=self.subject,
                add_issuer_alternative_name=False,
                extensions=[self.ocsp_no_check()],
            )
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, self.subject)
        self.assertExtensions(
            cert,
            [
                ca.get_authority_key_identifier_extension(),
                self.basic_constraints(),
                self.ocsp_no_check(),
                self.subject_alternative_name(dns(self.hostname)),
            ],
        )

    @override_tmpcadir()
    def test_extension_overrides(self) -> None:
        """Test that all extensions can be overwritten when creating a new certificate."""
        # Profile with extensions (will be overwritten by the command line).
        prof = Profile(
            "example",
            subject=[],
            extensions={
                EXTENSION_KEYS[ExtensionOID.AUTHORITY_INFORMATION_ACCESS]: self.authority_information_access(
                    ocsp=[uri("http://ocsp.example.com/profile")],
                    ca_issuers=[uri("http://issuer.example.com/issuer")],
                )
            },
        )
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])

        ca.ocsp_url = "http://ocsp.example.com/ca"
        ca.issuer_url = "http://issuer.example.com/issuer"
        ca.save()

        csr = certs["child-cert"]["csr"]["parsed"]

        expected_authority_information_access = self.authority_information_access(
            ocsp=[uri("http://ocsp.example.com/expected")],
            ca_issuers=[uri("http://issuer.example.com/expected")],
        )

        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof,
                ca,
                csr,
                subject=self.subject,
                add_issuer_alternative_name=False,
                add_issuer_url=True,
                add_ocsp_url=True,
                extensions=[expected_authority_information_access],
            )
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, self.subject)

        extensions = cert.x509_extensions
        self.assertEqual(
            extensions[ExtensionOID.AUTHORITY_INFORMATION_ACCESS], expected_authority_information_access
        )

    @override_tmpcadir()
    def test_partial_authority_information_access_override(self) -> None:
        """Test partial overwriting of the Authority Information Access extension"""

        prof = Profile(
            "example",
            subject=[],
            extensions={
                EXTENSION_KEYS[ExtensionOID.AUTHORITY_INFORMATION_ACCESS]: self.authority_information_access(
                    ocsp=[uri("http://ocsp.example.com/profile")],
                    ca_issuers=[uri("http://issuer.example.com/issuer")],
                )
            },
        )
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])

        ca.ocsp_url = "http://ocsp.example.com/ca"
        ca.issuer_url = "http://issuer.example.com/ca"
        ca.save()

        csr = certs["child-cert"]["csr"]["parsed"]

        # Only pass an OCSP responder
        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof,
                ca,
                csr,
                subject=self.subject,
                add_issuer_alternative_name=False,
                add_issuer_url=True,
                add_ocsp_url=True,
                extensions=[
                    self.authority_information_access(
                        ocsp=[uri("http://ocsp.example.com/expected")],
                    )
                ],
            )
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, self.subject)

        extensions = cert.x509_extensions
        self.assertEqual(
            extensions[ExtensionOID.AUTHORITY_INFORMATION_ACCESS],
            self.authority_information_access(
                ocsp=[uri("http://ocsp.example.com/expected")],
                ca_issuers=[uri("http://issuer.example.com/ca")],
            ),
        )

        # Only pass an CA issuer
        with self.mockSignal(pre_sign_cert) as pre:
            cert = self.create_cert(
                prof,
                ca,
                csr,
                subject=self.subject,
                add_issuer_alternative_name=False,
                add_issuer_url=True,
                add_ocsp_url=True,
                extensions=[
                    self.authority_information_access(
                        ca_issuers=[uri("http://issuer.example.com/expected")],
                    )
                ],
            )
        self.assertEqual(pre.call_count, 1)
        self.assertEqual(cert.subject, self.subject)

        extensions = cert.x509_extensions
        self.assertEqual(
            extensions[ExtensionOID.AUTHORITY_INFORMATION_ACCESS],
            self.authority_information_access(
                ocsp=[uri("http://ocsp.example.com/ca")],
                ca_issuers=[uri("http://issuer.example.com/expected")],
            ),
        )

    @override_tmpcadir()
    def test_no_cn_no_san(self) -> None:
        """Test creating a cert with no cn in san."""
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        csr = certs["child-cert"]["csr"]["parsed"]

        prof = Profile("example", subject=[("C", "AT")])
        msg = r"^Must name at least a CN or a subjectAlternativeName\.$"
        with self.mockSignal(pre_sign_cert) as pre, self.assertRaisesRegex(ValueError, msg):
            self.create_cert(prof, ca, csr, subject=None)
        self.assertEqual(pre.call_count, 0)

    @override_tmpcadir()
    def test_no_valid_cn_in_san(self) -> None:
        """Test what happens when the SAN has nothing usable as CN."""
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        csr = certs["child-cert"]["csr"]["parsed"]
        prof = Profile("example", subject=[], extensions={EXTENSION_KEYS[ExtensionOID.OCSP_NO_CHECK]: {}})
        san = self.subject_alternative_name(x509.RegisteredID(ExtensionOID.OCSP_NO_CHECK))

        with self.mockSignal(pre_sign_cert) as pre:
            self.create_cert(prof, ca, csr, cn_in_san=True, extensions=[san])
        self.assertEqual(pre.call_count, 1)

    @override_tmpcadir()
    def test_unparsable_cn(self) -> None:
        """Try creating a profile with an unparsable Common Name."""
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        csr = certs["child-cert"]["csr"]["parsed"]
        cname = "foo bar"

        prof = Profile("example", subject=[("C", "AT"), ("CN", cname)])
        msg = rf"^{cname}: Could not parse CommonName as subjectAlternativeName\.$"
        with self.mockSignal(pre_sign_cert) as pre, self.assertRaisesRegex(ValueError, msg):
            self.create_cert(prof, ca, csr)
        self.assertEqual(pre.call_count, 0)

    @override_tmpcadir(CA_DEFAULT_SUBJECT=None)
    def test_no_valid_subject(self) -> None:
        """Test case where no subject at all could be determined."""
        ca = self.load_ca(name="root", parsed=certs["root"]["pub"]["parsed"])
        csr = certs["child-cert"]["csr"]["parsed"]
        prof = Profile("test")
        with self.assertRaisesRegex(ValueError, r"^Cannot determine subject for certificate\.$"):
            self.create_cert(prof, ca, csr)

    def test_deprecated_hash_algorithms(self) -> None:
        """Test deprecated hash algorithm values."""

        msg = (
            r"^Support for non-standard hash algorithm names is deprecated and will be removed in "
            r"django-ca 1\.27\.0\.$"
        )
        with self.assertRemovedIn127Warning(msg):
            Profile("sha256", algorithm="sha256")

        with self.assertRemovedIn127Warning(msg):
            Profile("sha256", algorithm="SHA256")

        with self.assertRaisesRegex(ValueError, r"^Unknown hash algorithm: foo$"):
            Profile("sha256", algorithm="foo")

    def test_str(self) -> None:
        """Test str()."""
        for name in ca_settings.CA_PROFILES:
            self.assertEqual(str(profiles[name]), f"<Profile: {name}>")

    def test_repr(self) -> None:
        """Test repr()."""
        for name in ca_settings.CA_PROFILES:
            self.assertEqual(repr(profiles[name]), f"<Profile: {name}>")

class GetProfileTestCase(TestCase):
    """Test the get_profile function."""

    def test_basic(self) -> None:
        """Basic tests."""
        for name in ca_settings.CA_PROFILES:
            prof = get_profile(name)
            self.assertEqual(name, prof.name)

        prof = get_profile()
        self.assertEqual(prof.name, ca_settings.CA_DEFAULT_PROFILE)

class ProfilesTestCase(TestCase):
    """Tests the ``profiles`` proxy."""

    def test_basic(self) -> None:
        """Some basic tests."""
        for name in ca_settings.CA_PROFILES:
            prof = profiles[name]
            self.assertEqual(prof.name, name)

        # Run a second time, b/c accessor also caches stuff sometimes
        for name in ca_settings.CA_PROFILES:
            prof = profiles[name]
            self.assertEqual(prof.name, name)

    def test_none(self) -> None:
        """Test the ``None`` key."""
        self.assertEqual(profiles[None], profile)

    def test_default_proxy(self) -> None:
        """Test using the default proxy."""
        self.assertEqual(profile.name, ca_settings.CA_DEFAULT_PROFILE)
        self.assertEqual(str(profile), f"<DefaultProfile: {ca_settings.CA_DEFAULT_PROFILE}>")
        self.assertEqual(repr(profile), f"<DefaultProfile: {ca_settings.CA_DEFAULT_PROFILE}>")

        self.assertEqual(profile, profile)
        self.assertEqual(profile, profiles[ca_settings.CA_DEFAULT_PROFILE])


from PyQt4.QtGui import *
from PyQt4.QtCore import *

class StructDialogBase(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.mainlayout = QVBoxLayout(self)
        self.layout = QHBoxLayout()
        self.buttonOk = QPushButton('Ok')
        self.buttonCancel = QPushButton('Cancel')
        self.layout.addWidget(self.buttonOk)
        self.layout.addWidget(self.buttonCancel)
        self.connect(self.buttonOk,SIGNAL("clicked()"),self.accept)
        self.connect(self.buttonCancel,SIGNAL("clicked()"),self.reject)

    def createStructMemberLayout(self, name):
        tmplayout = QHBoxLayout()
        namewidget = QLabel()
        namewidget.setText(name)
        textwidget = QLineEdit()
        tmplayout.addWidget(namewidget)
        tmplayout.addWidget(textwidget)
        return tmplayout, textwidget


dist = [3.5, 3.2, 3, 2.8, 2.6, 2.5, 2.3, 2.2, 2.1, 1.9, 1.8, 1.7]

def calcmid(num, dist):
    return dist+num/2

past = [-0.25]
res = []
for elem in dist:
    length = sum(past) + len(past)*0.25
    r = calcmid(elem, length)
    past+= [elem]
    res += [r]

print(res)


f = open("input", "r")
tiles = []
for line in f:
    tiles.append(list(line.strip()))

num_minutes = 200

def is_empty(level):
    return level == [['.' for j in range(5)] for i in range(5)]
def next_levels(levels, minutes):
    if not is_empty(levels[1]):
        levels.insert(0, [['.' for j in range(5)] for i in range(5)])
    if not is_empty(levels[-2]):
        levels.append([['.' for j in range(5)] for i in range(5)])
    new_levels = []
    for i in range(len(levels)):
        if i == 0 or i == len(levels) - 1:
            new_levels.append([['.' for j in range(5)] for i in range(5)])
            continue
        tiles = levels[i]
        new_tiles = [r[:] for r in tiles]
        inner_tiles = levels[i+1]
        outer_tiles = levels[i-1]
        for i in range(5):
            for j in range(5):
                num_bugs = 0
                if i == 2 and j == 2: continue
                if i > 0 and tiles[i-1][j] == '#': num_bugs += 1
                if j > 0 and tiles[i][j-1] == '#': num_bugs += 1
                if i < 4 and tiles[i+1][j] == '#': num_bugs += 1
                if j < 4 and tiles[i][j+1] == '#': num_bugs += 1
                if i == 0 and outer_tiles[1][2] == '#': num_bugs += 1
                if j == 0 and outer_tiles[2][1] == '#': num_bugs += 1
                if i == 4 and outer_tiles[3][2] == '#': num_bugs += 1
                if j == 4 and outer_tiles[2][3] == '#': num_bugs += 1
                if (i, j) == (1, 2): num_bugs += sum([1 for t in inner_tiles[0] if t == '#'])
                if (i, j) == (2, 1): num_bugs += sum([1 for row in inner_tiles if row[0] == '#'])
                if (i, j) == (3, 2): num_bugs += sum([1 for t in inner_tiles[4] if t == '#'])
                if (i, j) == (2, 3): num_bugs += sum([1 for row in inner_tiles if row[4] == '#'])

                if num_bugs == 1: new_tiles[i][j] = '#'
                elif num_bugs == 2 and tiles[i][j] == '.': new_tiles[i][j] = '#'
                else: new_tiles[i][j] = '.'

        new_levels.append(new_tiles)
    return new_levels

def run(levels):
    for i in range(num_minutes):
        levels = next_levels(levels, i)
    tot = 0
    for l in levels:
        for row in l:
            for tile in row:
                if tile == '#':
                    tot += 1

    print(tot)

levels = [tiles]
levels.insert(0, [['.' for j in range(5)] for i in range(5)])
levels.append([['.' for j in range(5)] for i in range(5)])
run(levels)


from base64 import b64encode
from urllib.parse import urlencode

from tastypie.paginator import Paginator

from corehq.apps.api.util import get_datasource_records
from corehq.util import reverse

class NoCountingPaginator(Paginator):
    """
    The default paginator contains the total_count value, which shows how
    many objects are in the underlying object list. Obtaining this data from
    the database is inefficient, especially with large datasets, and unfiltered API requests.

    This class does not perform any counting and return 'null' as the value of total_count.

    See:
        * http://django-tastypie.readthedocs.org/en/latest/paginator.html
        * http://wiki.postgresql.org/wiki/Slow_Counting
    """

    def get_previous(self, limit, offset):
        if offset - limit < 0:
            return None

        return self._generate_uri(limit, offset - limit)

    def get_next(self, limit, offset, count):
        """
        Always generate the next URL even if there may be no records.
        """
        return self._generate_uri(limit, offset + limit)

    def get_count(self):
        """
        Don't do any counting.
        """
        return None

class DoesNothingPaginator(Paginator):
    def page(self):
        return {
            self.collection_name: self.objects,
            "meta": {'total_count': self.get_count()}
        }

class DoesNothingPaginatorCompat(Paginator):
    """Similar to DoesNothingPaginator this paginator
    does not do any pagination but it preserves the
    pagination fields for backwards compatibility.
    """
    def page(self):
        count = self.get_count()
        meta = {
            'offset': 0,
            'limit': None,
            'total_count': count,
            'previous': None,
            'next': None,
        }

        return {
            self.collection_name: self.objects,
            'meta': meta,
        }

def response_for_cursor_based_pagination(request, query, request_params, datasource_adapter):
    """Creates a response dictionary that can be used for cursor based pagination
     :returns: The response dictionary
    """
    records = get_datasource_records(query, datasource_adapter)
    return {
        "objects": records,
        "meta": {
            "next": _get_next_url_params(request.domain, request_params, records),
            "limit": request_params["limit"]
        }
    }

def _get_next_url_params(domain, request_params, datasource_records):
    """ Constructs the query string containing a base64-encoded cursor that points to the last entry in
    `datasource_records`
    :returns: The query string"""
    if not datasource_records:
        return None

    new_params = request_params.copy()
    # These are old values for `last_inserted_at` and `last_doc_id`
    new_params.pop('last_inserted_at', None)
    new_params.pop('last_doc_id', None)
    last_object = datasource_records[-1]
    cursor_params = {"last_doc_id": last_object["doc_id"], "last_inserted_at": last_object["inserted_at"]}
    encoded_cursor = b64encode(urlencode(cursor_params).encode('utf-8'))
    next_params = new_params | {'cursor': encoded_cursor}
    return reverse('api_get_ucr_data', args=[domain], params=next_params, absolute=True)


##################################################################################
# Author:   Adam Tipton
# Title:    Project Bogie Trainer
# Version:  1
#
# Company:  Brigham Young University - Idaho
# Course:   CSE 499 Senior Project
# Semester: Fall 2020
#
# Description:
#   Project Bogie is a Convolutional Neural Network written in the Python language.
#   This CNN will train a model from a dataset the ability to identify military
#   aircraft/jets.
#
#   Once trained, the program will create save the model for use in an application
#   that allows a user to input an image to test if it contains a military aircraft.
#
#   This version will use a 3 block CNN that draws from the VGG16 model. This gives
#   our model a headstart in training as many of the weights are preset, giving
#   us the advantage of a shortened training time.
#
#   Project Bogie uses TensorFlow as a backend and Keras as a driving force for training.
#
#   The TRAINER will be the primary workshorse for this project, which is divided into
#   two parts. Part I is this program, the trainer. Part II is the Predictor program.
#   The trainer is responsible for taking a data set of Modern Military Aircraft Images
#   and training a CNN to output a model. Therefore, the deliverable of this program
#   is to create h5 and hdf5 models.
#
#
# Sources:
#   Much inspiration and reusable code base is taken from the following tutorial -
#   URL: https://machinelearningmastery.com/how-to-develop-a-convolutional-neural-network-to-classify-photos-of-dogs-and-cats/
#   create_model(), diagnostics(), and train_and_evaluate_model() rely heavily on this
#   tutorial and code.
###################################################################################
###################################################################################

# System
import sys

# This important import gives us a headstart on training our model.
from keras.applications.vgg16 import VGG16

# Other important keras imports
from keras.models import Model
from keras.layers import Dense
from keras.layers import Flatten
from keras.optimizers import SGD
from keras.optimizers import Adam
from keras.optimizers import Adadelta
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ModelCheckpoint

# This import is for playing a sound
import winsound

# These imports are important for file handling
import os
from os import listdir

# This allows us to easily adjust epochs
epoch_rate = 200

# The learning rate is an important factor in training neural networks
learning_rate = 0.0016
# Import for pyplot
from matplotlib import pyplot

# The momentum variable can be adjusted to tweak learning
momentum_rate = 0.9

# The batch variable allows us to adjust batch sizes
batch = 42

# The model names
default_model_name = "Project_Bogie_Model.h5"
checkpoint_model_name = "weights.best"

# The location of our dataset for training
dataSet_dir = 'C:/Users/Adam/source/repos/military_aircraft/aircraft_folders_unsorted'

# The location of an alert sound we'd like to play once it finishes - replace with your own
sound_url = 'C:/Users/Adam/Music/Sounds/Soothing_Alert'

# The location of the model saves
model_save_path = ''

##########################################################
################         FUNCTIONS        ################
##########################################################

# This function welcomes the user with a informative message
def welcome():
    print(" ############################################################################################")
    print(" ############################################################################################")
    print(" ##################################                         #################################")
    print(" ##################################      PROJECT BOGIE      #################################")
    print(" ##################################         TRAINER         #################################")
    print(" ##################################                         #################################")
    print(" ##################################  Copyright BYU-I 2020   #################################")
    print(" ##################################  Author: Adam Tipton    #################################")
    print(" ##################################                         #################################")
    print(" ##################################  CS499 Final Project    #################################")
    print(" ##################################                         #################################")
    print(" ############################################################################################")
    print(" ############################################################################################")
    print(" #                                                                                #")
    print(" #                                 Welcome to Project Bogie.                                #")
    print(" #                                                                                #")
    print(" #                                        *  *  *  *                                        #")
    print(" #                                                                                #")
    print(" #  Project Bogie Trainer uses a Convolutional Neural Network trained against image data    #")
    print(" #  for the purpose of creating a predictive model that can determine the likelihood of an  #")
    print(" #  input image containing a modern military aircraft or something else. For the purposes   #")
    print(" #  of clarification, a modern military aircraft will generally be post-Vietnam War era     #")
    print(" #  vintage.                                                                                #")
    print(" #                                                                                #")
    print(" #  Generally, two classes of data are provided. The first class, which would produce near  #")
    print(" #  0 values, would contain modern military aircraft. The second class, which would produce #")
    print(" #  near 1 values, would contain other non-military aircraft and other unclassified random  #")
    print(" #  images. This is done in order to train the model to detect the difference between what  #")
    print(" #  we want to identify, modern military aircraft, and what we don't, everything else.      #")
    print(" #                                                                                #")
    print(" #  The trainer will produce a hierarchical model with the .h5 and/or the .hdf5 extension.  #")
    print(" #  As the training progresses, checkpoints will periodically save the current best model   #")
    print(" #  which will be saved in a directory in the .hdf5 extension. Several 'best' models may be #")
    print(" #  produced. Additionally, a final model witht he .hdf5 extension will be produced at the  #")
    print(" #  conclusion of the epoch cycle. This model may differ significantly from the 'best'      #")
    print(" #  checkpointed model in its accuracy, which is why both model types are provided. Testing #")
    print(" #  has shown that the checkpoing 'best' model will generally contain a higher accuracy     #")
    print(" #  than the end of epoch model, which has the possibility to degrade slightly. if you are  #")
    print(" #  unsure which model to chose, chose the checkpointed 'best' model, as it will guaruntee  #")
    print(" #  you the highest accuracy.                                                               #")
    print(" #                                                                                #")
    print(" ############################################################################################")
    print(" ############################################################################################")
    print("\n")
    print("\n")

# This function allows the user to initialize important variable if they choose and enter a save filename
def setup():

    # ask the user if they want to set up the variables
    response = input("\n Press 'Y' if you would like to setup the training variables or any other key to skip: ")
    if response == 'Y' or response == 'y':
        print("\n Sure . . .")
    else:
        print("\n Skipping setup . . . \n")
        return

    #epoch_rate
    global epoch_rate
    epoch_rate = input("\n Please enter the epoch rate (e.g. 50): ")
    #handle unexpected string input
    if not epoch_rate.isnumeric():
        epoch_rate = int(1);
    else:
        int(float(epoch_rate))
    if int(float(epoch_rate)) < int(1):
        print(" Epoch rate too low. Adjusting epoch rate to 1 . . .")
        epoch_rate = int(1)
    else:
        print(" Epoch rate is set to: ", str(epoch_rate))

    #learning_rate
    global learning_rate
    learning_rate = input("\n Please enter the learning rate (e.g. 0.001): ")
    #handle unexpected string input
    if not learning_rate.isnumeric():
        learning_rate = float(0.1)
    else:
        float(learning_rate)
    if float(learning_rate) >= float(1.0):
        print(" Learning rate too high. Adjusting learning rate to 0.1")
        learning_rate = float(0.1)
    else:
        print(" Learning rate is set to: ", str(learning_rate))

    #momentum_rate
    global momentum_rate
    momentum_rate = input("\n Please enter the momentum rate (e.g. 0.9): ")
    #handle unexpected string input
    if not momentum_rate.isnumeric():
        momentum_rate = float(0.1)
    else:
        float(momentum_rate)
    if float(momentum_rate) >= float(1):
        print(" Momentum rate too high. Adjusting momentum rate to 0.1")
        momentum_rate = float(0.1)
    else:
        print(" Momentum rate is set to: ", str(momentum_rate))

    #batch
    global batch
    batch = input("\n Please enter the batch count (e.g. 25): ")
    #handle unexpected string input
    if not batch.isnumeric():
        batch = int(10)
    else:
        int(batch)
    if int(batch) <= int(0):
        print(" Batch ammount is set too low. Adjusting batch to 10 . . .\n")
        batch = int(10)
    else:
        print(" Batch is set to: ", str(batch))
        print("\n")

# This function allows the user to set the model name
def set_model_name():
    #access global variables
    global default_model_name
    global checkpoint_model_name

    #save default model filename
    response = input("\n Press 'Y' if you would like to set the filenames for the models," +
                     " or press any other key to skip: ")
    if response == 'Y' or response == 'y':
        print("\n Sure . . .")
        #Default Model Name
        name = input("\n Please enter the new default model name: ")
        model_name = name + ".h5"
        print(" The Default model name is now set to: " , model_name)
        default_model_name = model_name

        #Checkpoint Model Name
        print("\n The current filename for the checkpoint model name is 'weights.best'"
              + "\n appended by the accuracy rate and the .hdf5 extension.")
        print(" Changing the filename will not remove the accuracy rate or the .hdf5 extension.")
        name2 = input("\n Please enter the new checkpoint model name (default: weights.best): ")
        print("\n The checkpoint model name is now set to: " , name2 + "-{the accuracy value}.hdf5")
        checkpoint_model_name = name2
    else:
        print("\n Skipping model name change.")
        # Ensuring default model name stays default
        default_model_name = "Project_Bogie_Model.h5"
        print("\n Default model name is: ", default_model_name)
        print("\n Checkpoint model name is: weights.best-{the accuracy value}.hdf5")

# This function allows the user to set the save path for the model
def set_model_save_path():
    # Ask the user if they want to set the save filepath for the model
    response = input("\n Enter 'Y' if you would like to set the save filepath for the default and checkpoint models: ")
    if response == 'y' or response == 'Y':
        print("\n Of course . . .\n")
    else:
        print(" Default save path selected.\n ")
        return

    # filepath
    filepath_found = False
    save_dir = ''

    # Prompt and check for valid path
    while not filepath_found:
        save_dir = input(" Please enter the filepath to the new save directory: ")

        # check if directory exists
        if not os.path.exists(save_dir):
            print("\n Filepath error: " + save_dir + " not found.\n")
        else:
            filepath_found = True
            print("\n Dataset directory found.\n")
            # Set the dataset directory to the new path
            global model_save_path
            model_save_path = save_dir

# This function allows the user to select a dataset directory path
def set_dataset_path():
    # Ask the user if they want to provide a different dataset dir
    print(" Project Bogie Trainer has a dataset directory that is hard coded.")
    response = input(" Enter 'Y' if you would like to set another dataset directory: ")
    if response == 'y' or response == 'Y':
        print("\n Of course . . .\n")
    else:
        print(" Default path selected.\n ")
        return

    # dataset
    datasetFound = False
    datasetDir = ''

    # Explain what is expected
    print(" For success, please ensure the directory path to the dataset contains classes (folders with images).")
    print(" You will need at least two classes (folders with images) to successfully train a model.\n")

    print(" The neural net will sort the classes inside the directory alphabetically, assigning them the value of 0-n.")
    print(" For example, class A (folder named A), will be assigned 0, class B will be assigned 1, etc,.\n")

    # Prompt and check for valid path
    while not datasetFound:
        datasetDir = input(" Please insert the directory location of the dataset: ")

        # check if directory exists
        if not os.path.exists(datasetDir):
            print("\n Filepath error: " + datasetDir + " not found.\n")
        else:
            datasetFound = True
            print("\n Dataset directory found.\n")
            # Set the dataset directory to the new path
            global dataSet_dir
            dataSet_dir = datasetDir

# This function will create our model. Here we call VGG16.
def create_model():
    # define a model variable and load the VGG16 information inside it.
    # it defines the expected shape of our files.
    model = VGG16(include_top=False, input_shape=(244, 244, 3))

    # Loop through and set the trainable flags to false for now.
    # We don't need to train them as VGG16 comes pretrained.
    for pre_existing_layer in model.layers:
        pre_existing_layer.trainable = False

    # Here we add new classifier layers to the model, see how they stack?
    # We'll use relu in class1 Dense(), and sigmoid in the output Dense()
    flat1 = Flatten()(model.layers[-1].output)
    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)
    output = Dense(1, activation='sigmoid')(class1)

    # New model definition created
    # The inputs are taken from the VGG16 model, the outputs are define above.
    model = Model(inputs=model.inputs, outputs=output)

    # Compile and then return the model
    #opt = Adadelta(lr = float(learning_rate), rho = 0.95, epsilon = 1e-06)
    opt = Adam(lr=float(learning_rate), beta_1=0.9, beta_2=0.999, epsilon=0.1)
    #opt = SGD(lr=float(learning_rate), momentum=float(momentum_rate))
    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])

    return model

# Lets plot diagnostic data to see what is going on
def diagnostics(history):
    # plot loss
	pyplot.subplot(211)
	pyplot.title('Cross Entropy Loss')
	pyplot.plot(history.history['loss'], color='blue', label='train')
	pyplot.plot(history.history['val_loss'], color='red', label='test')
	# plot accuracy
	pyplot.subplot(212)
	pyplot.title('Classification Accuracy')
	pyplot.plot(history.history['accuracy'], color='blue', label='train')
	pyplot.plot(history.history['val_accuracy'], color='red', label='test')
	# save plot to file
	filename = sys.argv[0].split('/')[-1]
	pyplot.savefig(filename + '_plot.png')
	pyplot.close()

# This function will test and evaluate the model
# It takes a directory string for the sound we'd like to play
def train_and_evaluate_model(sound_url):
    # create the model
    model = create_model()

    # Here we create the data generator
    data_gen = ImageDataGenerator(featurewise_center=True,
                                  width_shift_range=0.25,
                                  height_shift_range=0.25,
                                  horizontal_flip=True,
                                  vertical_flip=False,
                                  rotation_range=45,
                                  brightness_range=[0.8, 1.2],
                                  zoom_range=[0.4, 1.4])

    # Here we specify the image mean values for centering purposes
    data_gen.mean = [123.68, 116.779, 103.939]

    # Create the iterator for file handling
    training_iterator = data_gen.flow_from_directory(dataSet_dir,
        class_mode='binary', batch_size=int(batch), target_size=(244, 244))

    #callback
    global model_save_path
    #filepath = "C:/Users/Adam/source/repos/ProjectBogieTrainer/" + str(checkpoint_model_name) + "-{val_accuracy:.2f}.hdf5"
    filepath = str(checkpoint_model_name) + "-{val_accuracy:.2f}.hdf5"
    checkpoint = ModelCheckpoint(filepath=model_save_path + filepath, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')
    callbacks_list = [checkpoint]

    # Fit the model
    history = model.fit_generator(training_iterator, steps_per_epoch=len(training_iterator),
        validation_data = training_iterator, epochs=int(epoch_rate), callbacks=callbacks_list, verbose=0)

    # Here we evalute the model
    _, acc = model.evaluate_generator(training_iterator, steps=len(training_iterator), verbose=0)
    print('Accuracy:')
    print('>%.3f' % (acc * 100.0))
    print("Learning Rate:")
    print(float(learning_rate))
    print('\n')

    # This will produce the learning curve graphs
    print('Summarizing daignostic curves...\n')
    diagnostics(history)

    # Now we save the model
    print("Saving Model...")
    model.save(model_save_path + default_model_name)

    # Play an alert when the model is done training. Replace the file with your own.
    winsound.PlaySound(sound_url, winsound.SND_FILENAME)
    print("Model now complete...\n")

def test():
    print("Epoch: ", epoch_rate)
    print("Learning rate: ", learning_rate)
    print("Momentum: ", momentum_rate)
    print("Batch: ", batch)
    print("Default Model Name: ", default_model_name)
    print("Checkpoint Model Name: ", checkpoint_model_name)
    print("Model save path: ", model_save_path)

# Welcome the user
welcome()

# Set the dataset dir
set_dataset_path()

# Setup important variables and model name
setup()
set_model_name()
set_model_save_path()
test()
# This is the entry point to our program. From here, all of the training begins.
train_and_evaluate_model(sound_url)


import asyncio

import pytest

from telegram import Contact, Voice
from telegram.error import BadRequest
from telegram.request import RequestData
from tests.auxil.slots import mro_slots

@pytest.fixture(scope="module")
def contact():
    return Contact(
        TestContactBase.phone_number,
        TestContactBase.first_name,
        TestContactBase.last_name,
        TestContactBase.user_id,
    )

class TestContactBase:
    phone_number = "+11234567890"
    first_name = "Leandro"
    last_name = "Toledo"
    user_id = 23

class TestContactWithoutRequest(TestContactBase):
    def test_slot_behaviour(self, contact):
        for attr in contact.__slots__:
            assert getattr(contact, attr, "err") != "err", f"got extra slot '{attr}'"
        assert len(mro_slots(contact)) == len(set(mro_slots(contact))), "duplicate slot"

    def test_de_json_required(self, bot):
        json_dict = {"phone_number": self.phone_number, "first_name": self.first_name}
        contact = Contact.de_json(json_dict, bot)
        assert contact.api_kwargs == {}

        assert contact.phone_number == self.phone_number
        assert contact.first_name == self.first_name

    def test_de_json_all(self, bot):
        json_dict = {
            "phone_number": self.phone_number,
            "first_name": self.first_name,
            "last_name": self.last_name,
            "user_id": self.user_id,
        }
        contact = Contact.de_json(json_dict, bot)
        assert contact.api_kwargs == {}

        assert contact.phone_number == self.phone_number
        assert contact.first_name == self.first_name
        assert contact.last_name == self.last_name
        assert contact.user_id == self.user_id

    def test_to_dict(self, contact):
        contact_dict = contact.to_dict()

        assert isinstance(contact_dict, dict)
        assert contact_dict["phone_number"] == contact.phone_number
        assert contact_dict["first_name"] == contact.first_name
        assert contact_dict["last_name"] == contact.last_name
        assert contact_dict["user_id"] == contact.user_id

    def test_equality(self):
        a = Contact(self.phone_number, self.first_name)
        b = Contact(self.phone_number, self.first_name)
        c = Contact(self.phone_number, "")
        d = Contact("", self.first_name)
        e = Voice("", "unique_id", 0)

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)

    async def test_send_contact_without_required(self, bot, chat_id):
        with pytest.raises(ValueError, match="Either contact or phone_number and first_name"):
            await bot.send_contact(chat_id=chat_id)

    async def test_send_mutually_exclusive(self, bot, chat_id, contact):
        with pytest.raises(ValueError, match="Not both"):
            await bot.send_contact(
                chat_id=chat_id,
                contact=contact,
                phone_number=contact.phone_number,
                first_name=contact.first_name,
            )

    async def test_send_with_contact(self, monkeypatch, bot, chat_id, contact):
        async def make_assertion(url, request_data: RequestData, *args, **kwargs):
            data = request_data.json_parameters
            phone = data["phone_number"] == contact.phone_number
            first = data["first_name"] == contact.first_name
            last = data["last_name"] == contact.last_name
            return phone and first and last

        monkeypatch.setattr(bot.request, "post", make_assertion)
        assert await bot.send_contact(contact=contact, chat_id=chat_id)

class TestContactWithRequest(TestContactBase):
    @pytest.mark.parametrize(
        ("default_bot", "custom"),
        [
            ({"allow_sending_without_reply": True}, None),
            ({"allow_sending_without_reply": False}, None),
            ({"allow_sending_without_reply": False}, True),
        ],
        indirect=["default_bot"],
    )
    async def test_send_contact_default_allow_sending_without_reply(
        self, default_bot, chat_id, contact, custom
    ):
        reply_to_message = await default_bot.send_message(chat_id, "test")
        await reply_to_message.delete()
        if custom is not None:
            message = await default_bot.send_contact(
                chat_id,
                contact=contact,
                allow_sending_without_reply=custom,
                reply_to_message_id=reply_to_message.message_id,
            )
            assert message.reply_to_message is None
        elif default_bot.defaults.allow_sending_without_reply:
            message = await default_bot.send_contact(
                chat_id, contact=contact, reply_to_message_id=reply_to_message.message_id
            )
            assert message.reply_to_message is None
        else:
            with pytest.raises(BadRequest, match="message not found"):
                await default_bot.send_contact(
                    chat_id, contact=contact, reply_to_message_id=reply_to_message.message_id
                )

    @pytest.mark.parametrize("default_bot", [{"protect_content": True}], indirect=True)
    async def test_send_contact_default_protect_content(self, chat_id, default_bot, contact):
        tasks = asyncio.gather(
            default_bot.send_contact(chat_id, contact=contact),
            default_bot.send_contact(chat_id, contact=contact, protect_content=False),
        )
        protected, unprotected = await tasks
        assert protected.has_protected_content
        assert not unprotected.has_protected_content


x,y=map(int,input().split())
count=0
for i in range(x,y):
	for j in range(100):
		a=j*j
		if(a==i):
			count=count+1
		elif(a>i):
			break
print(count)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import ChristmasTree, BlindMaster, BlindTeam

import time

from .utils import is_raspberry_pi

if is_raspberry_pi:
    # noinspection PyUnresolvedReferences
    import RPi.GPIO as GPIO
    import Adafruit_WS2801
    import Adafruit_GPIO.SPI as SPI
    from ledstrip.led_light import wheel

import threading
import pygame  # Need also to do: sudo apt-get install git curl libsdl2-mixer-2.0-0 libsdl2-image-2.0-0 libsdl2-2.0-0

# Configure the count of pixels:
PIXEL_COUNT = 6

# Alternatively specify a hardware SPI connection on /dev/spidev0.0:
SPI_PORT   = 0
SPI_DEVICE = 0

thread_running = False
thread_stop = False

if is_raspberry_pi:
    blue  = Adafruit_WS2801.RGB_to_color(0, 0, 255)
    white = Adafruit_WS2801.RGB_to_color(100, 100, 100)
    red   = Adafruit_WS2801.RGB_to_color(255, 0, 0)
else:
    blue = white = red = None

def unicolor(color):
    if is_raspberry_pi:
        LED_power_off()

        for i in range(96):
            pixels.set_pixel(i, color)
            pixels.show()

def rainbow_cycle(pixels, wait=0.005):
    global thread_stop

    for j in range(256): # one cycle of all 256 colors in the wheel
        for i in range(pixels.count()):
            pixels.set_pixel(i, wheel(((i * 256 // pixels.count()) + j) % 256))
        pixels.show()
        if wait > 0:
            time.sleep(wait)
        if thread_stop == True:
            break

def blink_color(pixels, blink_times=5, wait=0.5, color=(255, 0, 0)):
    global thread_stop

    for i in range(blink_times):
        # blink two times, then wait
        pixels.clear()
        for j in range(2):
            for k in range(pixels.count()):
                pixels.set_pixel(k, Adafruit_WS2801.RGB_to_color( color[0], color[1], color[2]))
            pixels.show()
            time.sleep(0.08)
            pixels.clear()
            pixels.show()
            time.sleep(0.08)
        time.sleep(wait)
        if thread_stop == True:
            break

def moving(pixels):
    nb_pixels = 5
    list_led = list(range(96 - nb_pixels)) + list(range(96 - nb_pixels, 0, -1))
    for i2 in list_led:
        pixels.clear()

        for i in range(96 - nb_pixels):
            if i == i2:
                pixels.set_pixel(i + 0, blue)
                pixels.set_pixel(i + 1, blue)
                pixels.set_pixel(i + 2, white)
                pixels.set_pixel(i + 3, white)
                pixels.set_pixel(i + 4, red)
                pixels.set_pixel(i + 5, red) # update nb_pixels accordingly
        pixels.show()
        time.sleep(0.02)
        if thread_stop == True:
            break

def doCycle(effect):
    global pixels, thread_running, thread_stop

    thread_running = True
    thread_stop = False
    print("thread started")

    while thread_stop == False:
        if effect == 'rainbow':
            rainbow_cycle(pixels, wait=0.01)
        elif effect == 'blink':
            blink_color(pixels, color=(255, 255, 255))
        elif effect == 'moving':
            moving(pixels)

    thread_running = False
    print("thread stopped")

def LED_power_on(effect):
    if is_raspberry_pi:
        if thread_running == False:
            t = threading.Thread(target=doCycle, daemon=True, args=(effect,))
            t.start()

def LED_power_off():
    if is_raspberry_pi:
        global pixels, thread_stop, thread_running

        thread_stop = True
        while thread_running == True:
            time.sleep(0.1)

        pixels.clear()
        pixels.show()

############################################################################
# Create your views here

def home_page(request):

    # If this is a POST request then process the Form data
    if request.method == 'POST':

        # Create a form instance and populate it with data from the request (binding)
        form = ChristmasTree(request.POST)

        # Check if the form is valid
        if form.is_valid():
            print(form.cleaned_data['LED_effect'])
            if form.cleaned_data['LED_effect'] == 'off':
                LED_power_off()
            elif form.cleaned_data['LED_effect'] != '':
                LED_power_off()
                LED_power_on(form.cleaned_data['LED_effect'])

            if form.cleaned_data['music'] == 'off':
                stop_music()
            elif form.cleaned_data['music'] != '':
                play_music(form.cleaned_data['music'])

            if form.cleaned_data['volume'] != None:
                set_volume(form.cleaned_data['volume'])

            # redirect to a new URL:
            return HttpResponseRedirect('/')

    # If this is a GET (or any other method) create the default form
    else:
        form = ChristmasTree()

    return render(request, 'ledstrip/home_page.html', context={'form': form})

############################################################################
faster_team_to_answer = None
blue_score = 0
red_score = 0

def master(request):
    global faster_team_to_answer, blue_score, red_score

    # If this is a POST request then process the Form data
    if request.method == 'POST':

        # Create a form instance and populate it with data from the request (binding)
        form = BlindMaster(request.POST)

        # Check if the form is valid:
        if form.is_valid():
            if form.cleaned_data['blind_music'] == 'off':
                stop_music()
            elif form.cleaned_data['blind_music'] != '':
                faster_team_to_answer = None
                unicolor(white)
                play_music(form.cleaned_data['blind_music'])

            if form.cleaned_data['volume'] != None:
                set_volume(form.cleaned_data['volume'])

            if form.cleaned_data['add_point'] == 'blue':
                blue_score += 1
                unicolor(white)
            elif form.cleaned_data['add_point'] == 'red':
                red_score += 1
                unicolor(white)
            if form.cleaned_data['remove_point'] == 'blue':
                blue_score -= 1
            elif form.cleaned_data['remove_point'] == 'red':
                red_score -= 1
            elif form.cleaned_data['remove_point'] == 'reset':
                blue_score = 0
                red_score = 0

            if form.cleaned_data['bad_answer_continue'] == True:
                faster_team_to_answer = None
                unicolor(white)
                continue_music()

            # redirect to a new URL
            return HttpResponseRedirect('/master')

    # If this is a GET (or any other method) create the default form
    else:
        form = BlindMaster()

    context = {'form': form, 'faster_team_to_answer': faster_team_to_answer,
               'blue_score': blue_score, 'red_score': red_score}
    return render(request, 'ledstrip/master.html', context=context)

def blueteam(request):
    return team(request, 'blue', blue)

def redteam(request):
    return team(request, 'red', red)

def team(request, color, rgb_color):
    global faster_team_to_answer, blue_score, red_score

    # If this is a POST request then process the Form data
    if request.method == 'POST':

        # Create a form instance and populate it with data from the request (binding)
        form = BlindTeam(request.POST)

        # Check if the form is valid:
        if form.is_valid():
            if faster_team_to_answer == None:
                faster_team_to_answer = color
                stop_music()
                unicolor(rgb_color)

            # redirect to a new URL
            return HttpResponseRedirect(f'/{color}team')

    # If this is a GET (or any other method) create the default form
    else:
        form = BlindTeam()

    context = {'form': form, 'team': color, 'faster_team_to_answer': faster_team_to_answer,
               'blue_score': blue_score, 'red_score': red_score}
    return render(request, 'ledstrip/team.html', context=context)

############################################################################

def play_music(filepath):
    pygame.mixer.music.load(filepath)
    print("playing", filepath)
    pygame.mixer.music.play()

def stop_music():
    print("stop music")
    pygame.mixer.music.pause()

def continue_music():
    print("continue music")
    pygame.mixer.music.unpause()

def set_volume(volume):
    ''' Set the volume of the music playback.
    The volume argument is a float between 0.0 and 1.0 that sets volume.
    '''
    print(f"set volume {volume}%")
    pygame.mixer.music.set_volume(volume / 100)

#if __name__ == '__main__':
# Executed when app is loaded
print("init pygame mixer")
pygame.mixer.init()

if is_raspberry_pi:
    print("init Adafruit_WS2801")
    pixels = Adafruit_WS2801.WS2801Pixels(96, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE), gpio=GPIO)

    LED_power_on('rainbow')


from __future__ import print_function
import sys
import numpy as np

def alg(mSize, fname):
  #walk around the tree
  my_matr = readMatr(mSize, fname)
  for i in range((mSize - 1),-1,-1):
    for j in range(i):
      sum1 = my_matr[i-1][j] + my_matr[i][j]
      sum2 = my_matr[i-1][j] + my_matr[i][j+1]
      my_matr[i-1][j] = max(sum1, sum2)
  return my_matr[0][0]

def test():
  print("test = ", alg(4, filepath+"my_test_matr18.txt"))

def readMatr(matrSize, fname):
  #read diagonal matr of size matrSize from file fname into memory
  a = np.zeros((matrSize, matrSize))
  f = open(fname)
  it = 0
  for line in f:
    tmp = [int(s) for s in line.rstrip().split(' ')]      #break the line into list
    for j in range(it+1):
      a[it][j] = tmp[j]
    it = it + 1
  f.close()
  return a

def main():
  #test()
  filepath = "/home/victoria/Progs_local/EulerPro/data/"
  print("result for prob18 = ", alg(15, filepath+"my_matr18.txt"))
  #try to use the same algo to solve problem 67...
  print("result for prob67 = ", alg(100, filepath+"p067_triangle.txt"))

if __name__ == "__main__":
  sys.exit(main())


import requests
from bs4 import BeautifulSoup
#模拟浏览器
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
          }
#请求url
print('笔趣库网站www.biquku.la')
print('例子：小说《飞剑问道》 格式：http://www.biquku.la/0/65/')
urls=input('请输入笔趣库需要下载的小说的url：')
url=urls
r = requests.get(url,headers = header)
r.encoding = 'utf-8'
soup = BeautifulSoup(r.text, "lxml")
content = soup.find_all('div', id="list")
xsmz=soup.find_all('div', id="info")
for xs in xsmz:
    xs= xs.find_all('h1')
    for xs in xs:
     print('准备下载：'+xs.text)
for list in content:
    urls = list.find_all('a')
    for td in urls:
        zj_url=td["href"]
        section_name=td.text
        xsurl=url+zj_url
        res2 = requests.get(xsurl, headers=header)
        res2.encoding = 'utf-8'
        soup = BeautifulSoup(res2.text, "lxml")
        content = soup.find_all('div', id="content")
        mc = soup.find_all('script', language="javascript")
        for nr,mc in zip(content,mc):
         section_text = nr.text
         mc=mc.text
         mc=mc.split(';')[5]
         section_mc = mc.split('"')[1]
         fo = open(section_mc+'.txt', "ab+")  # 打开小说文件
         # 以二进制写入章节题目 需要转换为utf-8编码，否则会出现乱码
         fo.write(('\r' + section_name + '\r\n').encode('UTF-8'))
         # 以二进制写入章节内容
         fo.write((section_text).encode('UTF-8'))
         fo.close()
         print(section_name+'    '+'写入文本成功')  # 关闭小说文件