""" Encapsulation of tagline data in an sqlite database file. """

from __future__ import print_function
import os
import sqlite3
import shutil
from datetime import date
from sys import stderr

__db_version__ = 1

class Database:  # {{{1
    """ General management of the database. """

    class DatabaseError(Exception):  # {{{2
        """ Exception that is thrown if an error with sqlite occurs. """

        def __init__(self, message):
            super(Database.DatabaseError, self).__init__()
            self.args = (message,)

    def __init__(self, dbfilename=None):  # {{{2
        self.is_open = False
        self.db = None
        self.filename = None
        self.filters = {}
        self.exact_author = False
        self.keywords_or = False

        if dbfilename and not self.set_path(dbfilename):
            raise Exception("The given filename could not be opened.")

    def __del__(self):  # {{{2
        self.close()

    def set_path(self, path):  # {{{2
        """ Set the instance's database filename.

        If the path is valid, it is stored and True is returned. """

        filename = os.path.abspath(path)
        exists = os.path.exists(filename)
        isfile = os.path.isfile(filename)
        if exists and isfile:
            self.filename = filename
            return True
        return False

    def open(self):  # {{{2
        """ Open a connection to an existing database.

        Returns False if unsuccessful. """

        if self.is_open:
            return True
        self.db = sqlite3.connect(self.filename, detect_types=True)
        self.is_open = isinstance(self.db, sqlite3.Connection)

        if not self.version_is_current():
            self.upgrade_version()
        return self.is_open

    def initialise_file(self, filename):  # {{{2
        """ Initialise a new, empty database """

        if self.is_open:
            self.close()

        try:
            dbfile = open(filename, 'w')
            dbfile.close()
            self.filename = filename
            self.db = sqlite3.connect(self.filename)
            cursor = self.db.cursor()
            #db.text_factory=str
            cursor.execute('CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT, born INT DEFAULT NULL, died INT DEFAULT NULL)')
            cursor.execute('CREATE TABLE lines (id INTEGER PRIMARY KEY, tagline INT, date DATE, language VARCHAR(5), text TEXT)')
            # the keyword-tagline assignment table
            cursor.execute('CREATE TABLE kw_tl (id INTEGER PRIMARY KEY, keyword INT, tagline INT)')
            cursor.execute('CREATE TABLE taglines (id INTEGER PRIMARY KEY, author INT, source TEXT DEFAULT NULL, remark TEXT DEFAULT NULL, date DATE DEFAULT NULL)')
            cursor.execute('CREATE TABLE keywords (id INTEGER PRIMARY KEY, text TEXT UNIQUE)')
            cursor.execute('CREATE TABLE status (id INTEGER PRIMARY KEY, value TEXT)')
            # database version for later recognition (and conversion)
            cursor.execute('INSERT INTO status VALUES (0, ?)', (str(__db_version__),))
            self.db.commit()
            self.is_open = True
        except IOError as error:
            raise Database.DatabaseError(f"Error creating database file: {error.args[0]}")
        except sqlite3.Error as error:
            raise Database.DatabaseError(f"An sqlite3 error occurred: {error.args[0]}")

    def get_version(self):
        """ Extract schema version from database. """

        try:
            row = self.get_one("SELECT value FROM status WHERE id=0")
        # no status table (indicative of a first-version database)
        except sqlite3.OperationalError:
            return None

        if row is None:
            return None

        try:
            return int(row[0])
        except TypeError:
            return None

    def version_is_current(self):
        """ Determine whether the database schema needs to be upgraded. """

        version = self.get_version()
        return version is not None and version == __db_version__

    def upgrade_version(self):
        """ Do an automatic schema upgrade of the database. """

        try:
            row = self.get_one("SELECT value FROM status WHERE id=0")
        # no status table (indicative of a first-version database)
        except sqlite3.OperationalError:
            self.execute('CREATE TABLE status (id INTEGER PRIMARY KEY, value TEXT);')
            row = None

        if row is None:
            self.execute('INSERT INTO status VALUES (0, 0)')
            dbversion = 0
        else:
            try:
                dbversion = int(row[0])
            except TypeError:
                dbversion = 0

        if dbversion > __db_version__:
            raise Exception(
                "The database is newer than is supported by this program.")

        if dbversion < __db_version__:
            print("Database version is out of date. Need to upgrade first.",
                  file=stderr)
            print("Creating backup of database (appending .upgradebackup)",
                  file=stderr)
            shutil.copy(self.filename, self.filename + ".upgradebackup")
        while dbversion < __db_version__:
            dbversion += 1
            print(f"Upgrading to version {dbversion}...", file=stderr)

            if dbversion == 1:
                self.execute('ALTER TABLE tags RENAME TO keywords')
                self.execute('CREATE TABLE kw_tl (id INTEGER PRIMARY KEY, keyword INT, tagline INT)')
                self.execute('INSERT INTO kw_tl SELECT * FROM tag')
                self.execute('DROP TABLE tag')
                self.execute('UPDATE status SET value=? WHERE id=0', str(__db_version__))

        print("Upgrade complete.", file=stderr)

    def commit(self):  # {{{2
        """ Save any changes to the database that have not yet been committed. """

        if self.is_open:
            self.db.commit()

    def close(self):  # {{{2
        """ Close the instance's database connection. """

        if self.db and self.is_open:
            self.db.commit()
            self.db.close()
            self.db = None
            self.is_open = False

    def execute(self, query, args=None, commit=False, debug=False):  # {{{2
        """ Execute a query on the database and evaluate the result. """

        if not self.is_open and not self.open():
            return False
        cursor = self.db.cursor()
        if debug:
            print(query)
        if args:
            if debug:
                print(args)
            try:
                row = cursor.execute(query, args)
            except (sqlite3.OperationalError, sqlite3.InterfaceError):
                print("Query:", query)
                print("args:", args)
                raise
        else:
            row = cursor.execute(query)
        if commit and query.lower()[0:6] in ("insert", "update", "delete"):
            self.db.commit()
        return row

    def get_one(self, query, args=None):  # {{{2
        """ Shortcut function for a simply one-line retrieve. """

        cursor = self.execute(query, args)
        return cursor.fetchone() if cursor else None

    def parse_arguments(self, args):  # {{{2
        """ Evaluate given arguments and set appropriate option variables. """

        self.filters = {}
        self.exact_author = args.exactauthor
        self.keywords_or = args.orkeyword
        if args.author:
            self.filters["author"] = args.author
        if args.keyword:
            self.filters["keywords"] = args.keyword
        if args.lang:
            self.filters["language"] = args.lang
        if args.text:
            self.filters["text"] = args.text

    def random_tagline(self):  # {{{2
        """ Retrieve and return a random tagline text from the database. """

        cursor = self.taglines(True)
        if cursor:
            result = cursor.fetchone()
            if result:
                return result[0]
        return None

    def taglines(self, random=False):  # {{{2
        """ Retrieve and return taglines according to set filters. """

        query = "SELECT text FROM lines AS l"
        qargs = []
        where = []

        author = self.filters.get("author")
        if author:
            query += " JOIN taglines AS tl ON l.tagline=tl.id"
            if self.exact_author:
                query += " JOIN authors a ON a.name=? AND tl.author=a.id"
                qargs.append(author)
            else:
                query += " JOIN authors a ON a.name LIKE ? AND tl.author=a.id"
                qargs.append("%" + author + "%")

        keywords = self.filters.get("keywords")
        if keywords:
            where.append(
                f"""l.tagline IN (
                SELECT tagline FROM kw_tl JOIN keywords ON kw_tl.keyword=keywords.id
                WHERE text IN ({",".join(["?"] * len(keywords))})
                GROUP BY tagline{"" if self.keywords_or else " HAVING count(*)=?"}
                )""")
            qargs += keywords
            if not self.keywords_or:
                qargs.append(len(keywords))

        text = self.filters.get("text")
        if text:
            where.extend(["text like ?"] * len(text))
            for keyword in text:
                if not keyword.startswith('%') and not keyword.endswith('%'):
                    keyword = '%' + keyword + '%'
                qargs.append(keyword)

        lang = self.filters.get("language")
        if lang:
            where.append("l.language=?")
            qargs.append(lang)

        if where:
            query += " WHERE " + " AND ".join(where)

        if random:
            query += " ORDER BY RANDOM() LIMIT 1"
        else:
            query += " ORDER BY l.tagline, l.language"

        return self.execute(query, (qargs))

    def keywords(self, by_name=True):  # {{{2
        """ Retrieve and return all keywords and their names from the db. """

        query = "SELECT text FROM keywords"
        if by_name:
            query += " ORDER by text"
        return (row[0] for row in self.execute(query))

    def authors(self, by_name=True):  # {{{2
        """ Retrieve and return all authors and their data from the database. """

        query = "SELECT name, born, died FROM authors"
        if by_name:
            query += " ORDER BY name"
        return (name + (f' ({born if born else ""}-{died if died else ""})'
            if born or died else "") for name, born, died in self.execute(query))

    def stats(self):  # {{{2
        """ Calculate and return some statistical data on the database. """

        stats = {}
        stats["schema version"] = self.get_version()
        stats["keyword assignments"] = int(self.get_one("SELECT count(*) FROM kw_tl")[0])
        stats["keyword count"] = int(self.get_one("SELECT count(*) FROM keywords")[0])
        stats["tagline count"] = int(self.get_one("SELECT count(*) FROM taglines")[0])
        stats["line count"] = int(self.get_one("SELECT count(*) FROM lines")[0])
        stats["author count"] = int(self.get_one("SELECT count(*) FROM authors")[0])
        stats["language count"] = int(self.get_one(
            "SELECT COUNT(*) FROM (SELECT DISTINCT language FROM lines)")[0])

        cursor = self.execute("SELECT text FROM lines")
        linelengthsum = sum(len(row[0]) for row in cursor)
        stats["avg tagline length"] = linelengthsum / stats["line count"] if \
            stats["line count"] != 0 else 0

        return stats

class DatabaseTagline:  # {{{1
    """ Encapsulate a tagline in the database. """

    def __init__(self, db, tagline_id=None, author=None, keywords=None):  # {{{2
        """ Initialise data values depending on given id.

        @param _db: Handle to the sqlite database.
        @param _id: The ID of the tagline in the database.
                    If _id is None, the object is initialised empty. """

        self.db = db
        self.id = tagline_id
        self.is_changed = False

        if self.id is None:
            self.author = author
            self.author_name = None
            self.source = None
            self.remark = None
            self.when = None
            # pylint says keywords=set() in function interface is dangerous
            self.keywords = set() if keywords is None else set(keywords)
            self.texts = {}
        else:
            cursor = self.db.execute(
                """SELECT author, name, source, remark, date
                    FROM taglines AS t LEFT JOIN authors AS a ON a.id=t.author
                    WHERE t.id=?""",
                (self.id,))
            row = cursor.fetchone()
            if row:
                self.author = row[0]
                self.author_name = row[1]
                self.source = row[2]
                self.remark = row[3]
                self.when = row[4]
            self.texts = {}

            cursor = self.db.execute(
                "SELECT keyword FROM kw_tl WHERE tagline=?", (self.id,))
            self.keywords = set(keyword[0] for keyword in cursor)

            cursor = self.db.execute(
                "SELECT language, text FROM lines WHERE tagline=?", (self.id,))
            for row in cursor:
                self.texts[row[0]] = [row[1], False]

        # todo
        #self.last_changed = None

    def get_texts(self):
        """ Return a dict {language: text} from the internal list.

        The difference to self.texts is that the latter also contains a flag to
        store the changed state. """

        return {language: text[0] for language, text in self.texts.items()}

    def get_text(self, language):  # {{{2
        """ Retrieve the text with the given language from the internal list. """

        return self.texts[language][0] if language in self.texts else None

    def pop_text(self, language):  # {{{2
        """ Retrieve and remove the text with the given language from the internal list. """

        text = self.texts.pop(language, None)
        if text is None:
            return None
        self.is_changed = True
        return text[0]

    def set_text(self, language, text, old_language=None):  # {{{2
        """ Add a new text item for the given language.

        If old_language is given, replace it by the new item. """

        old_text = self.texts.get(language, None)
        if old_text is not None:
            if old_text[0] == text:
                return
        if old_language is not None:
            if old_language != language:
                self.texts.pop(old_language)
        self.texts[language] = [text, True]
        self.is_changed = True

    def set_information(self, source, remark, when):  # {{{2
        """ Assign values to the tagline's source, remark and date field. """

        if source == "":
            source = None
        if remark == "":
            remark = None
        if when == "":
            when = None
        self.is_changed = any((
            self.source != source,
            self.remark != remark,
            self.when != when))
        self.source = source
        self.remark = remark
        self.when = when
        #TODO: set changed

    def set_keywords(self, new_keywords):  # {{{2
        """ Change the set of keywords. """

        if new_keywords.symmetric_difference(self.keywords):
            self.is_changed = True
            self.keywords = new_keywords

    def commit(self):  #{{{2
        """ Write changed data to database. """

        if self.id is None:
            cursor = self.db.execute(
                "INSERT INTO taglines (author,source,remark,date) VALUES (?,?,?,?)", (
                    self.author,
                    self.source if self.source != "" else None,
                    self.remark if self.remark != "" else None,
                    self.when if self.when != "" else None))
            self.id = cursor.lastrowid

            present_languages = set()
            present_keywords = set()
        else:
            cursor = self.db.execute(
                "UPDATE taglines set author=?, source=?, remark=?, date=? WHERE id=?", (
                    self.author, self.source, self.remark, self.when, self.id))

            cursor = self.db.execute("SELECT language FROM lines WHERE tagline=?", (self.id,))
            present_languages = set(item[0] for item in cursor)

            cursor = self.db.execute("SELECT keyword FROM kw_tl WHERE tagline=?", (self.id,))
            present_keywords = set(item[0] for item in cursor)

        for lang, text in self.texts.items():
            if lang in present_languages:
                if text[1]:
                    self.db.execute(
                        "UPDATE lines set date=?, text=? WHERE tagline=? AND language=?",
                        (date.today().isoformat(), text[0], self.id, lang))
                present_languages.remove(lang)
            else:
                self.db.execute(
                    "INSERT INTO lines (tagline, date, language, text) VALUES (?,?,?,?)",
                    (self.id, date.today().isoformat(), lang, text[0]))
            text[1] = False
        for lang in present_languages:
            self.db.execute("DELETE FROM lines WHERE tagline=? AND language=?", (self.id, lang))

        for keyword in self.keywords:
            if keyword in present_keywords:
                present_keywords.remove(keyword)
            else:
                self.db.execute("INSERT INTO kw_tl (keyword, tagline) VALUES (?,?)", (keyword, self.id))
        for keyword in present_keywords:
            self.db.execute("DELETE FROM kw_tl WHERE keyword=? AND tagline=?", (keyword, self.id))

        self.db.commit()
        self.is_changed = False


from flask import Flask, render_template, url_for, request, redirect

global userid
userid = 1

app = Flask(__name__)
app.config['SECRET_KEY'] = 'feeltherythm'

@app.route('/', methods= ['GET', 'POST'])
@app.route('/home', methods= ['GET', 'POST'])
def home():
    if request.method == "POST":
        artist = request.form['']
    return render_template('home.html')

if __name__ == ('__main__'):
    app.run(debug=True)


import torchvision
from torch.utils.data import DataLoader

transform = torchvision.transforms.Compose([
        # torchvision.transforms.Resize([224, 224]),
        torchvision.transforms.ToTensor()
])
# 准备数据
train_sets = torchvision.datasets.FashionMNIST('./data', train=True, transform=transform, download=True)
test_sets = torchvision.datasets.FashionMNIST('./data', train=False, transform=transform, download=True)
# 数据长度
train_data_size = len(train_sets)
test_data_size = len(test_sets)
print("训练数据集长度：{}".format(train_data_size))
print("测试数据集长度：{}".format(test_data_size))
# DataLoader加载数据集
train_loader = DataLoader(train_sets, batch_size=64)
test_loader = DataLoader(test_sets, batch_size=64)

for imgs, targets in train_loader:
    print("训练数据形状：{}".format(imgs.size()))
    break


import itertools
import logging
from dataclasses import dataclass
from typing import Set, Iterable, List

import libcst as cst
from libcst.metadata import CodeRange

from .statistics_collectors import (
    AnnotationCollector,
    FunctionAnnotationInfo,
)

LOG: logging.Logger = logging.getLogger(__name__)

@dataclass(frozen=True)
class CoveredAndUncoveredRanges:
    covered_ranges: List[CodeRange]
    uncovered_ranges: List[CodeRange]

@dataclass(frozen=True)
class CoveredAndUncoveredLines:
    covered_lines: Set[int]
    uncovered_lines: Set[int]

@dataclass(frozen=True)
class FileCoverage:
    filepath: str
    covered_lines: List[int]
    uncovered_lines: List[int]

def collect_coverage_for_module(relative_path: str, module: cst.Module) -> FileCoverage:
    module_with_metadata = cst.MetadataWrapper(module)
    coverage_collector = CoverageCollector()
    try:
        module_with_metadata.visit(coverage_collector)
    except RecursionError:
        LOG.warning(f"LibCST encountered recursion error in `{relative_path}`")
    covered_and_uncovered_ranges = coverage_collector.covered_and_uncovered_ranges()
    covered_and_uncovered_lines = _covered_and_uncovered_ranges_to_lines(
        covered_and_uncovered_ranges
    )
    return FileCoverage(
        filepath=relative_path,
        covered_lines=sorted(covered_and_uncovered_lines.covered_lines),
        uncovered_lines=sorted(covered_and_uncovered_lines.uncovered_lines),
    )

class CoverageCollector(AnnotationCollector):
    def covered_functions(self) -> List[FunctionAnnotationInfo]:
        return [f for f in self.functions if f.is_annotated]

    def uncovered_functions(self) -> List[FunctionAnnotationInfo]:
        return [f for f in self.functions if not f.is_annotated]

    def covered_and_uncovered_ranges(self) -> CoveredAndUncoveredRanges:
        covered_ranges = []
        uncovered_ranges = []
        for info in itertools.chain(
            self.globals, self.attributes, self.parameters(), self.returns()
        ):
            if info.is_annotated:
                covered_ranges.append(info.code_range)
            else:
                uncovered_ranges.append(info.code_range)
        return CoveredAndUncoveredRanges(covered_ranges, uncovered_ranges)

def _code_ranges_to_lines(code_ranges: Iterable[CodeRange]) -> Set[int]:
    lines: Set[int] = set()
    for code_range in code_ranges:
        lines |= set(range(code_range.start.line - 1, code_range.end.line))
    return lines

def _covered_and_uncovered_ranges_to_lines(
    covered_and_uncovered_ranges: CoveredAndUncoveredRanges,
) -> CoveredAndUncoveredLines:
    covered_lines = _code_ranges_to_lines(covered_and_uncovered_ranges.covered_ranges)
    uncovered_lines = _code_ranges_to_lines(
        covered_and_uncovered_ranges.uncovered_ranges
    )
    # We show partially covered lines as covered
    return CoveredAndUncoveredLines(covered_lines, uncovered_lines - covered_lines)


import mlflow

from sklearn.model_selection import train_test_split
from sklearn.datasets import load_diabetes
from sklearn.ensemble import RandomForestRegressor

mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.autolog()

db = load_diabetes()

X_train, X_test, y_train, y_test = train_test_split(db.data, db.target)

# rf = mlflow.sklearn.load_model("mlflow-artifacts:/0/d0b27e09077744cd8ad21cec5e4f5aab/artifacts/myModel")

model_name = "test_r_m"
model_version = 2
rf = mlflow.sklearn.load_model(model_uri=f"models:/{model_name}/{model_version}")

print(X_test)

predictions = rf.predict(X_test)

print(predictions)


import os
import pygame

def load_image(name):
    fullname = os.path.join(os.path.join(
        os.path.dirname(__file__), 'imgs'), name)
    image = pygame.image.load(fullname).convert_alpha()
    return image

def load_sprite_sheet(sheet_name, nx, scale):
    fullname = os.path.join(os.path.join(
        os.path.dirname(__file__), 'imgs'), sheet_name)
    sheet = pygame.image.load(fullname)
    sheet = pygame.transform.scale(
        sheet, (int(sheet.get_width() * scale), int(sheet.get_height() * scale)))
    sheet = sheet.convert_alpha()

    sheet_rect = sheet.get_rect()

    image_list = []

    size_x = sheet_rect.width / nx
    size_y = sheet_rect.height

    for i in range(0, nx):
        rect = pygame.Rect((i * size_x, 0, size_x, size_y))
        image = pygame.Surface(rect.size, pygame.SRCALPHA)
        image = image.convert_alpha()
        image.blit(sheet, (0, 0), rect)

        image_list.append(image)

    return image_list


import random
class BankAccount:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
    def deposit(self, a):
        self.balance += a
        print(f"{a} было зачислено на аккаунт клиента {self.name}")
    def withdraw(self, a):
        if a > self.balance:
            print(f"Недостаточно средств на счете клиента {self.name}")
        else:
            self.balance -= a
            print(f"{a} было снято со счета клиента {self.name}")
    def check_balance(self):
        print(f"Текущий баланс средств на счете клиента {self.name} - {self.balance}")

acc_a = BankAccount('Anton', 5000)
print(acc_a.deposit(400))

class Car:
    def __init__(self, model):
        self.model = model
        self.speed = 0

    def start(self):
        self.speed += 10
        return (f'Текущая скорость - {self.speed} км/ч')

    def stop(self):
        self.speed = 0
        return (f'Текущая скорость - {self.speed} км/ч')
    def honk(self):
        return('Бип-бип')

car1 = Car('KIA')
print(car1.stop(), car1.honk())

class Person:
    def __init__(self, name, age, address):
        self.name = name
        self.age = age
        self.address = address

PersonA = Person('Anton', 22, 'Alexandr ave.')

print(PersonA.address)

class University:
    def __init__(self, name, address, students_n):
        self.name = name
        self. address = address
        self.students_n = students_n
YAGPU = University('ЯГПУ', 'Которосльная наб. 66', 200)
print(YAGPU.name)

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
    def area(self):
        return self.width * self.height

    def p(self):
        return 2*(self.width + self.height)

r = Rectangle(20, 10)
print(r.area(), r.p())

class Product:
    def __init__(self, name:str,  price:float, brand='R'):
        self.name = name
        self.price = price
        self.brand = brand

class Cart:
    def __init__(self, owner:str):
        self.owner = owner
        self.l = list()

    def add(self, *args:Product):
        for arg in args:
            self.l.append(arg)

    def __str__(self):
        p_str=''
        for p in self.l:
            p_str += p.name + ', '
        return f'{self.owner}. Your products: {p_str}'

    def remove_one(self, p_name):
        for i in range(len(self.l)):
            if self.l[i].name == p_name:
                self.l.pop(i)
                break
    def counter(self):
        c=0
        for i in self.l:
            c+=1
        return f'Number of prods - {c}'
    def total(self):
        pr = 0
        for i in self.l:
            pr+= i.price
        return pr

mango = Product('Mango', 5.3)
milk = Product('Milk', 1.2)
apple = Product('Apple', 3.1)

p1 = Cart('Anton')

p1.add(mango, mango, milk, apple)
print(p1.remove_one('Mango'))
print(p1)

class Game:
    def __init__(self, p_name, score=0, hp=0, level=0):
        self.p_name = p_name
        self.score = score
        self.hp = hp
        self.level = level

    def start(self):
        self.hp += 3
        print(f'Welcome to the Game, {self.p_name}')

    def over(self):
        self.hp = 0
        self.level = 0
        self.score = 0

    def restart(self):
        if self.hp != 3:
            self.hp = 3
        if self.score != 0:
            self.score = 0
        if self.level != 0:
            self.level = 0
    def check_stats(self):
        if self.hp == 0:
            return 'Game Over'
        if self.score // 10:
            self.level += self.score // 10
        print(
            f'Имя игрока - {self.p_name}, кол-во жизней - {self.hp}, очки - {self.score}, уровень игрока - {self.level}')
    def get_score(self):
        self.score += random.randrange(0, 100, 10)
        print(f'Игрок {self.p_name} заработал очки - {self.score}')

p1 = Game('Kukoj')
p1.start()
p1.get_score()
p1.check_stats()

from docx import Document
from docx.shared import Cm
document = Document()
document.add_heading('Заголовок документа, созданного в Python', 0)
p = document.add_paragraph('Обычный абзац, в котором есть ')
p.add_run('полужирный шрифт').bold = True
p.add_run(' и немного ')
p.add_run('курсива.').italic = True
document.add_heading('Заголовок первого уровня', level=1)
document.add_paragraph('А прямо под ним подчеркнутый текст', style='Intense Quote')
document.add_heading('Куда я хочу поехать', level=2)
document.add_paragraph('Лондон ', style='List Bullet')
document.add_paragraph('Берлин ', style='List Bullet')
document.add_paragraph('Париж ', style='List Bullet')
document.add_picture('Л.jpg', width=Cm(6.5))
document.add_picture('Б.jpg', width=Cm(6.5))
document.add_picture('П.jpg', width=Cm(6.5))

document.save('demo.docx')

from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "Goods"
data = [['Название', 'Количество', 'Цена'], ['Карандаш', 5, 15], ['Ручка', 6, 29.9], ['Альбом', 2, 89], ['Тетрадь', 8, 16]]
for row in data:
    ws.append(row)
ws['D1'] = 'Общая стоимость'
ws['D2'] = '=B2:B5*C2:C5'
ws.formula_attributes['D2'] = {'t': 'array', 'ref': "D2:D5"}

wb.save('Wb.xlsx')


import RPi.GPIO as GPIO
import numpy as np
import cv2
import time
from time import sleep

GPIO.setmode(GPIO.BCM)

GPIO_TRIGGER1 = 27      #Left ultrasonic sensor
GPIO_ECHO1 = 17

GPIO_TRIGGER2 = 25      #Front ultrasonic sensor
GPIO_ECHO2 = 22

GPIO_TRIGGER3 = 24      #Right ultrasonic sensor
GPIO_ECHO3 = 23

MOTOR1B=6  #Left Motor
MOTOR1E=5
MOTOR2B=20  #Right Motor
MOTOR2E=21

GPIO.setwarnings(False)
GPIO.setup(GPIO_TRIGGER1,GPIO.OUT)  # Trigger
GPIO.setup(GPIO_ECHO1,GPIO.IN)      # Echo
GPIO.setup(GPIO_TRIGGER2,GPIO.OUT)  # Trigger
GPIO.setup(GPIO_ECHO2,GPIO.IN)      # Echo
GPIO.setup(GPIO_TRIGGER3,GPIO.OUT)  # Trigger
GPIO.setup(GPIO_ECHO3,GPIO.IN)      # Echo

# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER1, False)
GPIO.output(GPIO_TRIGGER2, False)
GPIO.output(GPIO_TRIGGER3, False)

GPIO.setup(MOTOR1B, GPIO.OUT)
GPIO.setup(MOTOR1E, GPIO.OUT)
GPIO.setup(MOTOR2B, GPIO.OUT)
GPIO.setup(MOTOR2E, GPIO.OUT)

#Define Robot Command
def reverse():
      GPIO.output(MOTOR1B, GPIO.HIGH)
      GPIO.output(MOTOR1E, GPIO.LOW)
      GPIO.output(MOTOR2B, GPIO.HIGH)
      GPIO.output(MOTOR2E, GPIO.LOW)

def forward():
      GPIO.output(MOTOR1B, GPIO.LOW)
      GPIO.output(MOTOR1E, GPIO.HIGH)
      GPIO.output(MOTOR2B, GPIO.LOW)
      GPIO.output(MOTOR2E, GPIO.HIGH)

def rightturn():
      GPIO.output(MOTOR1B,GPIO.LOW)
      GPIO.output(MOTOR1E,GPIO.HIGH)
      GPIO.output(MOTOR2B,GPIO.HIGH)
      GPIO.output(MOTOR2E,GPIO.LOW)

def leftturn():
      GPIO.output(MOTOR1B,GPIO.HIGH)
      GPIO.output(MOTOR1E,GPIO.LOW)
      GPIO.output(MOTOR2B,GPIO.LOW)
      GPIO.output(MOTOR2E,GPIO.HIGH)

def stop():
      GPIO.output(MOTOR1E,GPIO.LOW)
      GPIO.output(MOTOR1B,GPIO.LOW)
      GPIO.output(MOTOR2E,GPIO.LOW)
      GPIO.output(MOTOR2B,GPIO.LOW)

# Function For the distance between Utrasonic
def sonar(GPIO_TRIGGER,GPIO_ECHO):
      start=0
      stop=0
      # Set pins as output and input
      GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  # Trigger
      GPIO.setup(GPIO_ECHO,GPIO.IN)      # Echo

      # Set trigger to False (Low)
      GPIO.output(GPIO_TRIGGER, False)

      # Allow module to settle
      time.sleep(0.01)

      #while distance > 5:
      #Send 10us pulse to trigger
      GPIO.output(GPIO_TRIGGER, True)
      time.sleep(0.00001)
      GPIO.output(GPIO_TRIGGER, False)
      begin = time.time()
      while GPIO.input(GPIO_ECHO)==0 and time.time()<begin+0.05:
            start = time.time()

      while GPIO.input(GPIO_ECHO)==1 and time.time()<begin+0.1:
            stop = time.time()

      # Calculate pulse length
      elapsed = stop-start
      distance = elapsed * 34000

      # That was the distance there and back so halve the value
      distance = distance / 2

      print("Distance : %.1f" % distance)
      # Reset GPIO settings
      return distance

#lower_and_upper = adaptive_hsv_filter.set_hsv_filter_object()
#print(lower_and_upper)
MIN_PIXEL_BALL = 700
MAX_PIXEL_BALL = 20000
min_pixel_found = False
car_near_ball = False

#Start
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

while cap.isOpened():
    #distance coming from front ultrasonic sensor
    distanceC = sonar(GPIO_TRIGGER2,GPIO_ECHO2)
    #distance coming from right ultrasonic sensor
    distanceR = sonar(GPIO_TRIGGER3,GPIO_ECHO3)
    #distance coming from left ultrasonic sensor
    distanceL = sonar(GPIO_TRIGGER1,GPIO_ECHO1)
    ret, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    lower_red = np.array([0,50,50])
    upper_red = np.array([10,255,255])
    mask0 = cv2.inRange(hsv, lower_red, upper_red)
    lower_red = np.array([170,50,50])
    upper_red = np.array([180,255,255])
    mask1 = cv2.inRange(hsv, lower_red, upper_red)
    mask = mask0+mask1
    roi_left = mask[0:480,0:212]
    roi_center = mask[0:480,212:425]
    roi_right = mask[0:480,425:640]
    #cv2.imshow("roi_left", roi_left)
    #cv2.imshow("roi_center", roi_center)
    #cv2.imshow("roi_right", roi_right)
    #se la distanza dall'ultrasonic e maggiore di 15 la macchina riparte con la ricerca
    if distanceC > 15:
        car_near_ball = False
    #Dividiamo il frame il 3 porzioni Left Right e Central
    central_white_pixel = np.sum(roi_center == 255)
    left_white_pixel = np.sum(roi_left == 255)
    right_white_pixel = np.sum(roi_right == 255)
    print("left:" + str(left_white_pixel) + " center: " + str(central_white_pixel) + " right: " + str(right_white_pixel))

    if not car_near_ball:
        if central_white_pixel > MIN_PIXEL_BALL or left_white_pixel > MIN_PIXEL_BALL or right_white_pixel > MIN_PIXEL_BALL:
            min_pixel_found = True
        else:
            min_pixel_found = False

        if min_pixel_found:
            #se ci sono piu pixel bianchi nell frame centrale la macchina va avanti
            if central_white_pixel >= left_white_pixel and central_white_pixel >= right_white_pixel:
                print("go_on")
                forward()
                sleep(0.05)
                stop()
            #se ci sono piu pixel bianchi nell frame di destra la macchina va a destra
            elif right_white_pixel > central_white_pixel:
                print("go_right")
                rightturn()
                sleep(0.05)
                stop()
            #se ci sono piu pixel bianchi nell frame di sinistra la macchina va a sinistra
            elif left_white_pixel > central_white_pixel:
                print("car_left")
                leftturn()
                sleep(0.05)
                stop()
            #se la macchina si sta per scontrare / si è avvicinata all'oggetto rosso si ferma
            if distanceC < 15:
                car_near_ball = True

        else:
            #fase di ricerca della palla, gira a sinistra con pausa
            print("research")
            leftturn()
            sleep(0.1)
            print("stop_car")
            stop()
            sleep(0.1)

    if cv2.waitKey(1) == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()


#2018-11-27
#打开摄像头，识别人脸

import os
os.chdir('C:\\Users\\VISSanKCJ\\Desktop\\AI工程师计算机视觉\\CLASSDATA_第三门_计算机视觉库OpenCV（9.3更新）\\10.人脸检测识别')

import cv2
from imutils import *

# 0代表从摄像头获取图像数据，也可输入视频路径，读取视频
cap = cv2.VideoCapture(0)

while(True):
    #有两个返回值
    # ret 读取成功True或失败Falseq
    # frame读取到的图像的内容
    # 读取一帧数据，一帧代表一幅图像
    ret,frame = cap.read()

    # 级联分类器
    detector = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
    rects = detector.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=2, minSize=(10,10), flags=cv2.CASCADE_SCALE_IMAGE)
    for (x,y,w,h) in rects:
	    # 画矩形框
	    cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2)

    cv2.imshow('frame',frame)
    #给图片取个名字'frame'
    # waitKey功能是不断刷新图像，单位ms，下面为延时1毫秒，延时后会读取到键盘的一个输入，有个返回值是当前键盘按键值
    # ord返回对应的ASCII数值
    if cv2.waitKey(1) & 0xff == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Python/AI course/Course/CV_base of Dl/摄像头人脸检测.py