from datetime import datetime, timedelta

from selenium.webdriver import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import UnexpectedAlertPresentException
from time import sleep

def get_temperature():
    start_date = datetime.strptime("13.03.2023", "%d.%m.%Y")
    end_date = datetime.strptime("23.03.2023", "%d.%m.%Y")
    listTime = ["00:00", "03:00", "06:00", "09:00", "12:00", "15:00", "18:00", "21:00"]
    with open("temperature.csv", "w") as f:
        f.write("Date, Time, Temperature\n")
        chrome_options = Options()
        chrome_options.add_argument("--disable-extensions")
        chrome_options.add_argument("no-sandbox")
        #chrome_options.add_argument('--headless')
        #chrome_options.add_argument('--disable-gpu')  # Last I checked this was necessary.
        chrome_options.add_argument("--window-size=800,600")
        chrome_options.add_argument("--disable-dev-shm-usage")
        driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options= chrome_options)
        driver.implicitly_wait(5) # implicitly wait for 5 seconds for each element
        for current_date in daterange(start_date, end_date):
            for time in listTime:
                while True: # loop until the temperature value is parsed successfully
                    try:
                        driver.get("https://meteoinfo.ru/archive-pogoda/russia/tomsk-area")
                        Select(driver.find_element(by=By.CSS_SELECTOR, value="select#id_dt")).select_by_visible_text(
                            current_date.strftime("%Y-%m-%d") + " " + time)
                        temperature = driver.find_element(by=By.CSS_SELECTOR,
                                                          value="#div_3 tr:nth-child(3) > td:nth-child(2)").text
                        f.write(current_date.strftime("%Y-%m-%d") + "," + time + "," + temperature + "\n")
                        break # exit the while loop
                    except UnexpectedAlertPresentException:
                        print("Encountered unexpected alert pop-up, waiting and retrying...")
                        sleep(2)  # Wait for 2 seconds and retry
                    except:
                        print("Error occurred while retrieving data for " + current_date.strftime(
                            "%Y-%m-%d") + " " + time)
                        f.write(current_date.strftime("%Y-%m-%d") + "," + time + "," + "None" + "\n")
                        break # exit the while loop
        driver.quit()

def daterange(start_date, end_date):
    for n in range(int((end_date - start_date).days) + 1):
        yield start_date + timedelta(n)

def get_next_temperature(city):
    chrome_options = Options()
    chrome_options.add_argument("--disable-extensions")
    chrome_options.add_argument("no-sandbox")
    # chrome_options.add_argument('--headless')
    # chrome_options.add_argument('--disable-gpu')  # Last I checked this was necessary.
    chrome_options.add_argument("--window-size=1000,800")
    chrome_options.add_argument("--disable-dev-shm-usage")
    driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)
    driver.get("https://meteoinfo.ru")
    driver.find_element(by=By.CSS_SELECTOR, value="#select2-sel_search-container").click()
    driver.find_element(by=By.CSS_SELECTOR, value="body > span > span > span.select2-search.select2-search--dropdown > input").send_keys(""+city)
    driver.find_element(by=By.CSS_SELECTOR, value="body > span > span > span.select2-search.select2-search--dropdown > input").send_keys(Keys.ENTER)
    answer = driver.find_element(by=By.CSS_SELECTOR, value="#div_print_0  tr:nth-child(3)").text
    return answer


#!/usr/bin/env python
# encoding: utf-8
"""
@author: HuRuiFeng
@file: 202_continuous-substrings.py
@time: 2023/7/20 13:47
@project: huawei-od-python
@desc: 202 连续子串
"""

def solve_method(t, p):
    # 实现 t.find(p) + 1
    p_len = len(p)
    for i in range(len(t) - p_len + 1):
        substring = t[i:i + p_len]
        if substring == p:
            return i + 1

    return "No"

if __name__ == '__main__':
    assert solve_method("AVERDXIVYERDIAN", "RDXI") == 4


from gui.widgets import PyPushButton
from qt_core import *
import sys

class Window(QWidget):
    def __init__(self):  # 对象的初始化方法
        super().__init__()  # 调用父类的初始化方法
        self.setUI()

    def setUI(self):  # 控件的各种配置的方法，如果需要修改控件的配置，只需要在该方法中修改即可
        self.resize(500, 500)
        self.move(400, 200)

        button = PyPushButton(
            text="注册",
            radius=8,
            color="red",
            bg_color="red",
            bg_color_hover="red",
            bg_color_pressed="red"
        )

        self.show()

# 用于驱动整个程序
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    sys.exit(app.exec_())


def polygons2txt(polygons,
             path='src\output\polygons.txt',
             duplicate_first_point_to_end=True):
    """Создаёт файл содержащий многоугольники из массива"""
    f = open(path, 'w')
    f.write(str(len(polygons)) + '\n')
    for polygon in polygons:
        s = ''
        for point in polygon:
            s += str(point[0]) + ' ' + str(point[1]) + ' '
        if duplicate_first_point_to_end:
            f.write(s + str(polygon[0][0]) + ' ' + str(polygon[0][1]) + '\n')
        else:
            f.write(s + '\n')
    f.close()


import json
import time

data = {}
data["picoID"] = "chickens"
data["sensor"] = "T"
data["reading"] = ""
data["units"] = "C"

for i in range(20):
    data["reading"] = i
    with open("testDB.json", "a") as f:
        f.write(json.dumps(data)+'\n')
    time.sleep(2)


#Nick Caravaggio
# CSV Organizer Example

import tkinter as tk

#Importing 100 records from csv file
file_name = "Video_Games_Sales_as_at_22_Dec_2016.csv"
file_object = open(file_name, "r")
#Declaring primary use lists
game_records = []
game_record_column_headers = []
categories = {}
counter = 0
version = "1.0"

#list order being assigned to names for easier access
name = 0
platform = 1
year_of_release = 2
genre = 3
publisher = 4
NA_sales = 5
EU_sales = 6
JP_sales = 7
other_sales = 8
global_sales = 9
critic_score = 10
critic_count = 11
user_score = 12
user_count = 13
developer = 14
rating = 15

#For loop appends all data to game_records
for line in file_object:
    row = line.split(",")
    if counter == 0:
        game_record_column_headers = row
    #elif statement to decrease output to 20, for faster testing.
    #elif counter == 20:
        #break
    else:
        game_records.append(row)
    counter += 1

#function High_Critic_Score asks user for minimum score, returns list of games
#with a critic score above that input.
def high_critic_score():
    minimum_score = int(input("Enter minimum score: "))
    for items in game_records:
        #Ignores games where no critic score is reported.
        if items[critic_score] == '':
            pass
        elif float(items[critic_score]) > float(minimum_score):
            print("Name:", items[name], "| Score:", items[critic_score])

#Function sort_platform() asks user for a platform, or will list all available
#platforms if the user types !help
def sort_platform():
    the_platform = input("Enter platform ('!help' for examples): ")
    if the_platform == "!help":
        print("Examples: 3DS, DS, GBA, N64, PC, PS, PS2, PS3, PS4,"\
              " SNES, X360, XB")
        sort_platform()
    else:
        print("------------------\nGames on: ", the_platform,\
              "\n------------------")
        for items in game_records:
            if items[platform] == the_platform:
                print(items[name])

#Function sort_publisher asks user for a platform, or will list all available
#publishers if the user types !help
def sort_publisher():
    the_publisher = input("Enter publisher ('!help' for examples): ")
    if the_publisher == "!help":
        print("Examples: Activision, Nintendo, Sony Computer Entertainment,"\
              "Ubisoft, etc.")
        sort_publisher()
    else:
        print("------------------\nGames from: ", the_publisher,\
              "\n------------------")
        for items in game_records:
            if items[publisher] == the_publisher:
                print(items[name])

#Function to ask user for minimum amount of copies sold.
def ask_for_sales():
    return float(input("Enter minimum copies sold (in millions): "))

#function high_sales() will ask user which region they'd like to see sales
#higher than their minimum inputted number.
def high_sales():
    region = input("Which region would you like to see minimum copies sold"\
                    " in? \n(!help for options): ")
    if region == "!help":
        print("Region Options: 'NA', 'EU', 'JP', 'Other', or 'Global'. "\
              "(Note: Case-sensitive.)")
        high_sales()
    elif region == "NA":
        minimum_sales = ask_for_sales()
        for items in game_records:
            if float(items[NA_sales]) > minimum_sales:
                print("Name:", items[name], "| "\
                      "Copies Sold:", items[NA_sales])
    elif region == "EU":
        minimum_sales = ask_for_sales()
        for items in game_records:
            if float(items[EU_sales]) > minimum_sales:
                print("Name:", items[name], "| "\
                      "Copies Sold:", items[EU_sales])
    elif region == "JP":
        minimum_sales = ask_for_sales()
        for items in game_records:
            if float(items[JP_sales]) > minimum_sales:
                print("Name:", items[name], "| "\
                      "Copies Sold:", items[JP_sales])
    elif region == "Other":
        minimum_sales = ask_for_sales()
        for items in game_records:
            if float(items[other_sales]) > minimum_sales:
                print("Name:", items[name], "| "\
                      "Copies Sold:", items[other_sales])
    elif region == "Global":
        minimum_sales = ask_for_sales()
        for items in game_records:
            if float(items[global_sales]) > minimum_sales:
                print("Name:", items[name], "| "\
                      "Copies Sold:", items[global_sales])
    else:
        print("ERROR: Not a valid region.")
        high_sales()

def print_available_functions():
    print("------------------\n"\
          "Programs Available as of Version", version, "\n"\
          "1. Sort by Game's minimum Critic Score (scale 1-100)\n"\
          "2. Sort by Game's Platform (ex. Xbox, PS3, etc.)\n"\
          "3. Sort by Game's Publisher (ex. Activision, EA, Nintendo)\n"\
          "4. Sort by Game's minimum copies sold (in millions)")

#default program that runs
def default():
    choice = input("------------------\n"\
                   "What would you like to do now? \n"\
                   "(Type function #, !help, or !end): ")
    if choice == "!help":
        print_available_functions()
        default()
    elif choice == "1":
        high_critic_score()
        default()
    elif choice == "2":
        sort_platform()
        default()
    elif choice == "3":
        sort_publisher()
        default()
    elif choice == "4":
        high_sales()
        default()
    elif choice == "!end":
        print("------------------\n"\
              "Thank you for using Nick's video game sales data sorting"\
              " program!\nHave a nice day :)")
    else:
        print("That is not a function or command.")
        default()

if __name__ == "__main__":
    print("Hi! Welcome to Nick's video game sales data sorting program!")
    print_available_functions()
    default()


from kgcnn.data.datasets.MatBenchDataset2020 import MatBenchDataset2020

class MatProjectEFormDataset(MatBenchDataset2020):
    r"""Store and process :obj:`MatProjectEFormDataset` from `MatBench <https://matbench.materialsproject.org/>`__
    database.  Name within Matbench: 'matbench_mp_e_form'.

    Matbench test dataset for predicting DFT formation energy from structure.
    Adapted from Materials Project database. Removed entries having formation energy more than 2.5eV and those
    containing noble gases. Retrieved April 2, 2019. For benchmarking w/ nested cross validation,
    the order of the dataset must be identical to the retrieved data; refer to the Automatminer/Matbench publication
    for more details.

        * Number of samples: 132752.
        * Task type: regression.
        * Input type: structure.

    """

    def __init__(self, reload=False, verbose: int = 10):
        r"""Initialize 'matbench_mp_e_form' dataset.

        Args:
            reload (bool): Whether to reload the data and make new dataset. Default is False.
            verbose (int): Print progress or info for processing where 60=silent. Default is 10.
        """
        # Use default base class init()
        super(MatProjectEFormDataset, self).__init__("matbench_mp_e_form", reload=reload, verbose=verbose)
        self.label_names = "e_form"
        self.label_units = "eV/atom"


import os

import cv2
import mediapipe as mp
import time
from math import hypot
import numpy as np

# Root to images dir, note that images MUST be png with transparent background
# Image size doesnt matter as it is auto-scaled
ROOT = "some_dir\\Hats"

class FaceMeshDetector():
    def __init__(self, staticMode=False, maxFaces=1, minDetectionCon=0.5, minTrackCon=0.5):

        self.staticMode = staticMode
        self.maxFaces = maxFaces
        self.minDetectionCon = minDetectionCon
        self.minTrackCon = minTrackCon
        self.controlPoints = []

        self.mpDraw = mp.solutions.drawing_utils
        self.mpFaceMesh = mp.solutions.face_mesh
        self.faceMesh = self.mpFaceMesh.FaceMesh(static_image_mode=self.staticMode, max_num_faces=self.maxFaces,
                                                 min_detection_confidence=self.minDetectionCon, min_tracking_confidence=self.minTrackCon)
        self.drawSpec = self.mpDraw.DrawingSpec(thickness=1, circle_radius=2)

    def findFaceMesh(self, img, draw=True):
        self.imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        self.results = self.faceMesh.process(self.imgRGB)
        faces = []
        self.controlPoints = []
        if self.results.multi_face_landmarks:
            for faceLms in self.results.multi_face_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(img, faceLms, self.mpFaceMesh.FACEMESH_FACE_OVAL,
                                               self.drawSpec, self.drawSpec)
                face = []
                for id, lm in enumerate(faceLms.landmark):
                    ih, iw, ic = img.shape
                    x, y = int(lm.x * iw), int(lm.y * ih)
                    # Uncomment this to find your points
                    # cv2.putText(img, str(id), (x, y), cv2.FONT_HERSHEY_PLAIN,
                    #           0.7, (0, 255, 0), 1)

                    face.append([x, y])
                faces.append(face)
                for face in faces:
                    # 54 and 284 are the points of forehead, you can find your points via cv2.putText up
                    self.controlPoints.append([face[54], face[284]])
        return img

    # Images still being black after overlay, open Merge request if you managed to solve this
    def transparentOverlay(self, img, overlayImage):
        if not len(self.controlPoints):
            return img
        h, w, _ = overlayImage.shape  # Size of foreground
        rows, cols, _ = img.shape  # Size of background Image
        unparsedXLeft, unparsedYLeft = self.controlPoints[0][0][0], self.controlPoints[0][0][1]
        xLeft, yLeft = int(unparsedXLeft), int(unparsedYLeft)
        yLeft -=20
        xLeft -= 50
        unparsedXRight, unparsedYRight = self.controlPoints[0][1][0], self.controlPoints[0][1][1]
        xRight, yRight = int(unparsedXRight), int(unparsedYRight)
        xRight +=50
        hatWidth = int(hypot((xRight - xLeft), (yRight - yLeft)))
        hatScale = hatWidth / w

        overlayImage = cv2.resize(overlayImage, (0, 0), fx=hatScale, fy=hatScale)
        hatHeight, hatWidth, _ = overlayImage.shape  # Size of foreground
        print(self.controlPoints, yLeft)
        if yLeft - hatHeight <= 0 or yLeft >= rows or xLeft <= 0 or xLeft + hatWidth >= cols:
            return img
        bg = img[yLeft - hatHeight: yLeft, xLeft:xLeft + hatWidth]
        np.multiply(bg, np.atleast_3d(255 - overlayImage[:, :, 3]) / 255.0, out=bg, casting="unsafe")

        img[yLeft - hatHeight: yLeft, xLeft:xLeft + hatWidth] = bg

        return img

def main():
    cap = cv2.VideoCapture(0)
    cap.set(cv2.CAP_PROP_FPS, 30)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)

    listImg = os.listdir(ROOT)
    print(listImg)
    imgList = []
    for imgPath in listImg:
        img = cv2.imread(f'{ROOT}\\{imgPath}', cv2.IMREAD_UNCHANGED)
        imgList.append(img)
    print(len(imgList))
    indexImg = 0

    pTime = 0
    detector = FaceMeshDetector()

    while True:
        success, img = cap.read()
        # Set draw=True if you would like to see face mesh
        img = detector.findFaceMesh(img, draw=False)

        if (len(imgList)):
            detector.transparentOverlay(img, imgList[indexImg])

        cTime = time.time()
        fps = 1 / (cTime - pTime)
        pTime = cTime
        cv2.putText(img, f'FPS: {int(fps)}', (20, 70), cv2.FONT_HERSHEY_PLAIN,
                    3, (0, 255, 0), 3)
        cv2.imshow("Image", img)
        key = cv2.waitKey(1)
        if key == ord('a'):
            if indexImg > 0:
                indexImg -= 1
        elif key == ord('d'):
            if indexImg < len(imgList) - 1:
                indexImg += 1
        elif key == ord('q'):
            break

if __name__ == "__main__":
    main()


from socket import *
import threading

# Define variables that hold the desired port and buffer size
SERVER_PORT = 3602
BUFFER_SIZE = 32

class BasicTCPEchoServer(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.sock = socket(AF_INET, SOCK_STREAM)
        self.sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        self.sock.bind((self.host, self.port))

    def start(self):
        self.sock.listen(50)
        print('The server is listening...')
        while True:
            client, address = self.sock.accept()
            self.silly_debugging_function("this is silly")
            print("Accepted connection from ", address)

            message = client.recv(BUFFER_SIZE)
            if message:
                message = message.decode()

                print('Echoing "', message, '" to ', address)
                client.send(message.encode())
            else:
                print("Client disconnected")
                client.close()

    def silly_debugging_function(self, test):
        pass

if __name__ == "__main__":
    BasicTCPEchoServer('', SERVER_PORT).start()


# $Id$

# Web service for campus directory project

import re
import xmlrpclib
Randy_Loch = '192.168.0.1'
Kim_Nguyen_G5 = '192.168.0.1'

def CampusDirectoryZEM001VALUOVW (self, org_unit='None'):
    request = self.REQUEST
    RESPONSE =  request.RESPONSE
    remote_addr = request.REMOTE_ADDR
    if remote_addr in [Randy_Loch, Kim_Nguyen_G5, '127.0.0.1', ]:
        conn = getattr(self, 'Oracle_Database_Connection_Campus_Directory')
        connstr = conn.connection_string
        try:
            if not conn.connected():
                conn.connect(connstr)
        except:
            conn.connect(connstr)
        dbc = conn()
        tablename = 'PS_ZEM001VALUOVW'
        if org_unit == 'None':
            querystr = "select * from %s" % (tablename)
        else:
            querystr = "select * from %s where z_univ_org = '%s'" % (tablename, org_unit)
        try:
            retlist = dbc.query (querystr)
        except:
            conn.connect(connstr)
            dbc = conn()
            retlist = dbc.query (querystr)
        myMarshaller = xmlrpclib.Marshaller()
        return myMarshaller.dumps(retlist[1])


import json
import unittest
from unittest import mock

from flask_api import status
import requests

from app import app
import movies.es

MOVIE_SEARCH_MOCK_RESPONSE = [
    {
        "genres": ["Adventure", "Animation", "Children", "Comedy", "Fantasy"],
        "id": 1,
        "tags": ["pixar", "fun"],
        "title": "Toy Story (1995)",
    },
    {
        "genres": ["Adventure", "Children", "Fantasy"],
        "id": 2,
        "tags": ["fantasy", "magic board game", "Robin Williams", "game"],
        "title": "Jumanji (1995)",
    },
    {
        "genres": ["Comedy", "Romance"],
        "id": 3,
        "tags": ["moldy", "old"],
        "title": "Grumpier Old Men (1995)",
    },
    {
        "genres": ["Comedy", "Drama", "Romance"],
        "id": 4,
        "tags": [],
        "title": "Waiting to Exhale (1995)",
    },
]

class TestCase(unittest.TestCase):
    @mock.patch("movies.es.search")
    def test_route(self, movie_search_mock):
        movie_search_mock.return_value = (
            MOVIE_SEARCH_MOCK_RESPONSE,
            len(MOVIE_SEARCH_MOCK_RESPONSE),
        )
        c = app.test_client()

        page = 1
        page_size = 4
        response = c.get(f"/movies?page={page}&page_size={page_size}")
        data = response.json

        self.assertEqual(response.status_code, 200)
        # Our mock should be preserved
        self.assertEqual(len(data["data"]), data["pagination"]["row_count"])
        # Page and page size params should be preserved
        self.assertEqual(data["pagination"]["page"], page)
        self.assertEqual(data["pagination"]["page_size"], page_size)

        # Empty query params should be okay
        response = c.get(f"/movies?q=&genres=&tags=&page=&page_size=")
        self.assertEqual(response.status_code, 200)

    @mock.patch("movies.es.search")
    def test_route_bad_input(self, movie_search_mock):
        movie_search_mock.return_value = (
            MOVIE_SEARCH_MOCK_RESPONSE,
            len(MOVIE_SEARCH_MOCK_RESPONSE),
        )
        c = app.test_client()

        # page and page_size must be postive integers
        bad_pages = [-1, 0, "a string"]
        for page in bad_pages:
            page_size = 4
            response = c.get(f"/movies?page={page}&page_size={page_size}")
            self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

        bad_page_sizes = [-1, 0, "a string"]
        for page_size in bad_page_sizes:
            page = 1
            response = c.get(f"/movies?page={page}&page_size={page_size}")
            self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_parse_response(self):
        es_response_json = """
        {
            "_shards":{
                "failed":0,
                "skipped":0,
                "successful":2,
                "total":2
            },
            "hits":{
                "hits":[
                    {
                        "_id":"588",
                        "_index":"search",
                        "_score":6.9985013,
                        "_source":{
                            "genres":["Adventure","Animation","Children","Comedy","Musical"],
                            "tags":["Disney"],
                            "title":"Aladdin (1992)"
                        },
                        "_type":"_doc"
                    }
                ],
                "max_score":6.9985013,
                "total":{
                    "relation":"eq",
                    "value":22
                }
            },
            "timed_out":false,
            "took":9
        }
        """
        expected_parsed_rows = [
            {
                "genres": ["Adventure", "Animation", "Children", "Comedy", "Musical"],
                "tags": ["Disney"],
                "title": "Aladdin (1992)",
                "id": 588,
            }
        ]
        expected_parsed_row_count = 22
        parsed_rows, parsed_row_count = movies.es._parse_response(
            json.loads(es_response_json)
        )

        self.assertEqual(parsed_rows, expected_parsed_rows)
        self.assertEqual(parsed_row_count, expected_parsed_row_count)

    def test_build_query(self):
        q = "abc"
        genres = ["One", "Two"]
        tags = ["Three", "Four", "Five"]
        expected_query_json = """
        {
            "query": {
                "bool": {
                    "must": [
                        {
                            "match": {
                                "title": "abc"
                            }
                        },
                        {
                            "bool": {
                                "must": [
                                    {"term": {"genres": "One"}},
                                    {"term": {"genres": "Two"}},
                                    {"term": {"tags": "Three"}},
                                    {"term": {"tags": "Four"}},
                                    {"term": {"tags": "Five"}}
                                ]
                            }
                        }
                    ]
                }
            }
        }
        """
        query = movies.es._build_query(q, genres, tags)

        self.assertEqual(query, json.loads(expected_query_json))


#리스트 특정값 원소 개수는 .count(값)

lottos = [44, 1, 0, 0, 31, 25]
win_nums = [31, 10, 45, 1, 6, 19]

def solution(lottos, win_nums):
    rank = [6, 6, 5, 4, 3, 2, 1]
    cnt_0 = lottos.count(0)

    correct = 0
    for lot in lottos:
        if lot in win_nums:
            correct += 1

    return [rank[correct + cnt_0], rank[correct]]

level1/로또의최고순위와최저순위.py

로또의최고순위와최저순위.py


import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk

class BoxConBotons (Gtk.Box):
    def __init__(self):
        super().__init__()

        self.set_orientation(orientation = Gtk.Orientation.HORIZONTAL)
        self.set_spacing(5)

        caixa1Color = Gtk.Box(orientation = Gtk.Orientation.VERTICAL, spacing = 10)
        caixa2Color = Gtk.Box(orientation = Gtk.Orientation.VERTICAL, spacing = 10)

        # añadimos los botones a la caja
        caixa1Color.pack_start(self.buttonWithColor("red"), True, True, 5)
        caixa1Color.pack_start(self.buttonWithColor("yellow"), True, True, 5)
        caixa1Color.pack_start(self.buttonWithColor("purple"), True, True, 5)

        # hacemos los botones de la segunda caja y se los añadimos
        caixa2Color.pack_start(self.buttonWithColor("red"), True, True, 5)
        caixa2Color.pack_start(self.buttonWithColor("purple"), True, True, 5)

        # tienen expand y fill
        self.pack_start(caixa1Color,True, True, 5)
        self.pack_start(self.buttonWithColor("green"), True, True, 5)
        self.pack_start(caixa2Color, True, True, 5)

    def on_debuxa(self, control, cr, datos):
        contexto = control.get_style_context()
        ancho = control.get_allocated_width()
        alto = control.get_allocated_height()
        Gtk.render_background(contexto,cr,0,0, ancho, alto)

        r, g, b, a = datos["color"]
        cr.set_source_rgba (r, g, b, a)
        cr.rectangle(0, 0, ancho, alto)
        cr.fill()

    def buttonWithColor(self, color):
        rgba = Gdk.RGBA()
        rgba.parse(color)

        boton = Gtk.Button()
        area = Gtk.DrawingArea()
        area.set_size_request(32,24)
        area.connect("draw",self.on_debuxa, {"color": rgba})

        boton.add(area)
        return boton

    # button: sirve cualquier nombre para recoger una referencia al control que generó
    # la señal (el evento clicked), lo tiene que recibir SIEMPRE!!!
    def buttonPressed(self, boton):
        if len(self.editText.get_text())==0:
            self.lblEtiqueta.set_text("Pa que tocas")
        else:
            self.lblEtiqueta.set_text(self.editText.get_text())
        self.editText.set_text("")


from django.shortcuts import render

# Create your views here.

educations = [
        {
            'date': 'JANUARY 2003 - JANUARY 2004',
            'stage': 'Primary institute',
            'desc': 'People only remember the First and forget the Rest',
            'name': 'Nou-Bahini institute,Dhaka',
        },
        {
            'date': 'FEBRUARY 2004- DECEMBER 2006 FEBRUARY 2011- MARCH 2014',
            'stage': 'Primary & Secondary institute',
            'desc': 'The Golden moment of my Life',
            'name': 'Nou-Bahini institute,Dhaka',
        }
    ]

experiences = [
    {
        'date': 'JOCTOBER 2021 - PRESENT',
        'stage': 'Software Development Engineer',
        'desc': 'Reactjs , Python, Django',
        'name': 'Datasoft Systems Bangladesh, LTD',
    },
    {
        'date': 'FEBRUARY 2021 - SEPTEMBER 2021',
        'stage': 'Full-stack Web Developer',
        'desc': 'Nodejs, Reactjs, AWS',
        'name': 'Doodle Technologies',
    }
]

details = {
    'email': 'mahidulmoon@gmail.com',
    'phone': '+8801771042196',
    'address': "YounusKhan's scholar's Garden Ashulia Savar, Dhaka."
}

links = {
    'f': 'https://www.facebook.com/mdmahidul.moon/',
    't': '',
    'i': 'https://www.instagram.com/m4h1dul_m00n/',
    'in': 'https://www.linkedin.com/authwall?trk='
          'bf&trkInfo=AQEtgCk16MjpuAAAAX85s524nsDG2UiMvBQAs8ePGeJCDF8aoEPEmHHnTYUdmKy_'
          'iFTQdDwJHoWWuTW3HLLK015oRbO_pA_fcgGs8vcO7N-bQzc1PhxdtXupy2VNZDAkKPIsv7U=&originalReferer='
          '&sessionRedirect=https%3A%2F%2Fwww.linkedin.com%2Fin%2Fmahidul-moon-281509144%2F',
}

context = {
    'educations': educations,
    'experiences': experiences,
    'details': details,
    'links': links,
}

def home(request):
    return render(request, 'crud/index.html', context)

def education(request):
    return render(request, 'crud/education.html', context)

def experience(request):
    return render(request, 'crud/experience.html', context)

def message(request):
    return render(request, 'crud/message.html', context)

def contact(request):
    return render(request, 'crud/contact.html', context)


import rclpy
from std_srvs.srv import SetBool
from std_msgs.msg import Float64MultiArray
from rclpy.node import Node

class Service(Node):
      def __init__(self):
         super().__init__('service_velocity')
         self.service=self.create_service(SetBool,'shaft_velocity',self.SetBool_callback)

      def SetBool_callback(self,request,response):
          self.publisher_=self.create_publisher(Float64MultiArray,'velocity_controller/commands',10)
          command=Float64MultiArray()

          if request.data==True:
           command.data.append(2.0)
           self.publisher_.publish(command)
           self.get_logger().info('publising %s' %command)
           response.success=False
           response.message='rotating'

          if request.data==False:
           command.data.append(0.0)
           self.publisher_.publish(command)
           self.get_logger().info('publishing %s' %command)
           response.success=False
           response.message='stopping'
          return response
def main(args=None):
    rclpy.init()
    rotating_service=Service()
    rclpy.spin(rotating_service)
    rclpy.shutdown()

if __name__=='__main__':
   main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 24 2015
@author: Julio Barbieri
"""

import logging
import sys
import re
import os.path

from nltk.stem.porter import PorterStemmer

CONFIG_SEPARATOR		=	'='
CSV_SEPARATOR			=	';'
INDEXER_FILENAME		=	'config/index.cfg'
QP_FILENAME				=	'config/pc.cfg'
SEARCHER_FILENAME		=	'config/busca.cfg'

EVALUATION_FILENAME		=	'config/avaliacao.cfg'

PATH 					=	'files/'

CMD_LEIA				=	'LEIA'
CMD_ESCREVA				=	'ESCREVA'
CMD_CONSULTAS			=	'CONSULTAS'
CMD_RESULTADOS			=	'RESULTADOS'
CMD_MODELO				=	'MODELO'

STEMMER					=	'STEMMER'
NOSTEMMER				=	'NOSTEMMER'

LINE					=	'linha '
EXITED_WITH_ERROR		=	'Programa encerrado com erros, verificar o log de execução.'
FORMAT_ERROR 			=	'Erro na formatação do arquivo inserido, ' + LINE
NE_INSTRUCTION_ERROR	=	'Instrução não existente, ' + LINE
INSTRUCTION_ORDER_ERROR	=	'Instrução de leia após instrução de escreva, ' + LINE + '%d.'
NE_IO_INSTRUCTION_ERROR	=	'Instrução não existente ou ordem de leia e escreva invertidas, ' + LINE + '%d.'
FILE_NOT_FOUND			=	'Arquivo não encontrado, nome: %s.'

NAME_IIG_LOGGER			=	'inverted_index_generator_logger'
NAME_INDEXER_LOGGER		=	'indexer_logger'
NAME_QP_LOGGER			=	'query_processor_logger'
NAME_SEARCHER_LOGGER	=	'searcher_logger'
NAME_EVALUATION_LOGGER	=	'evalutation_looger'

II_GENERATOR_LOG		=	'logs/inverted_index_generator.log'
INDEXER_LOG				=	'logs/indexer.log'
QUERY_PROCESSOR_LOG		=	'logs/query_processor.log'
SEARCHER_LOG			=	'logs/searcher.log'
EVALUATION_LOG			=	'logs/evaluation.log'

CONFIG_READ_HEADER		=	'Leitura do arquivo de configuração para geração da lista invertida'
READ_CONFIG_STARTED		=	'Iniciando leitura do arquivo de configuração: %s.'
TUPLES_READED_FILE		=	'Lidas %d tuplas do arquivo: %s.'
LINES_READED_USED_FILE	=	'Lidas %d linhas (%d aproveitadas) do arquivo: %s.'
LINES_READED_FILE		=	'Lidas %d linhas do arquivo: %s.'
GENERATING_INV_LIST		=	'Gerando a lista invertida com base nos dados lidos.'
WRITING_INVERTED_INDEX	=	'Escrevendo a lista invertida gerada em: %s.'
CONFIG_END_PROCESSING	=	'Finzalizando a leitura do arquivo de configuração: %s.'
LINES_READED_CONFIG		=	'Lidas %d linhas do arquivo de configuração.'
NO_FILE_SPECIFIED		=	'Arquivo não especificado para geração da lista invertida.'
SAVING_STRUCTURE		=	'Salvando estrutura do modelo vetorial no arquivo: %s.'
STRUCTURE_LOADED		=	'Estrutura carregada à partir do arquivo: %s.'
WRITING_QUERIES			=	'Escrevendo as consultas no arquivo: %s.'
WRITING_METRIC			=	'Escrevendo a métrica no arquivo: %s.'
PLOTTING_METRIC			=	'Plotando a métrica em um gráfico: %s.'
WRITING_EXPECTED_RESULTS=	'Escrevendo os resultados esperados das consultas no arquivo: %s.'
WRITING_RESULTS			=	'Escrevendo os resultados das consultas no arquivo: %s.'
READING_QUERIES			=	'Lendo as consultas no arquivo: %s.'
STEMMER_ENABLED			=	'Uso de stemmer ativado.'
STEMMER_DISABLED		=	'Uso de stemmer desativado.'
CALC_METRIC				=	'Calculando métricas.'
SAVING_METRIC			=	'Salvando métricas.'
METRIC_SAVED			=	'As métricas foram salvas em %s segundos.'
METRIC_CALCULATED		=	'As métricas foram calculadas em %s segundos.'
QUERIES_TIME			=	'As consultas requeridas foram processadas e realizadas em %s segundos.'
DOCUMENTS_TIME			=	'Os documentos requeridos foram lidos e processados em %s segundos.'
WORDS_TIME				=	'As palavras requeridas foram lidas e processadas em %s segundos.'
INDEX_TIME				=	'Os documentos foram indexados em %s segundos.'
INDEX_START				=	'Indexação dos documentos solicitados iniciada.'

QUERIES_READ_TIME		=	'As consultas foram lidas e processadas em %s segundos'

def setup_logger(name, filename):
	logger = logging.getLogger(name)

	if not len(logger.handlers):
		logger = logging.getLogger(name)
		logger.setLevel(logging.DEBUG)

		file_handler = logging.FileHandler(filename)
		file_handler.setLevel(logging.DEBUG)

		console_handler = logging.StreamHandler()
		console_handler.setLevel(logging.ERROR)

		formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
		console_handler.setFormatter(formatter)
		file_handler.setFormatter(formatter)

		logger.addHandler(console_handler)
		logger.addHandler(file_handler)

	return logger

def verify_stemmer(line, count, log_name, log_file):
	logger =  setup_logger(log_name, log_file)

	if line.endswith('\n'):
		line = line[:-1]

	if line == STEMMER:
		logger.debug(STEMMER_ENABLED)
		return PorterStemmer()
	elif line == NOSTEMMER:
		logger.debug(STEMMER_DISABLED)
		return None
	else:
		logger.error(NE_INSTRUCTION_ERROR + str(count + 1))
		exit_error(EXITED_WITH_ERROR)

def get_values(line, count, separator, log_name, log_file):
	logger =  setup_logger(log_name, log_file)

	cmd = line.split(separator)
	if len(cmd) < 2 or len(cmd) > 2:
		logger.error(FORMAT_ERROR + str(count + 1))
		exit_error(EXITED_WITH_ERROR)

	next_cmd = cmd[0]
	filename = cmd[1]

	if filename.endswith('\n'):
		filename = filename[:-1]

	return (next_cmd, filename)

def valida_termo(termo):
	if len(termo) > 1 and re.match("^[A-Z]*$", termo):
		return termo
	else:
		return None

def format_text(text):
	chars_to_remove = ['.', ',', '!', '?', ';', ':', '(', ')', '\n']
	sc = set(chars_to_remove)
	text = ''.join([c for c in text if c not in sc])

	return text.upper()

def exit_error(message):
	sys.exit(message)

def file_exists(filepath):
	return os.path.isfile(filepath)


#!/usr/bin/env python3
"""modul"""
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    """route func"""
    return render_template('0-index.html')

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


'''Using VAE on keyword occurrence submissions dataset using MLP

The VAE has a modular design. The encoder, decoder and VAE
are 3 models that share weights. After training the VAE model,
the encoder can be used to generate latent vectors.

The decoder can be used to generate eyword occurrence submissions
by sampling the latent vector from a Gaussian distribution
with mean = 0 and std = 1.

[1] Kingma, Diederik P., and Max Welling.
"Auto-Encoding Variational Bayes."
https://arxiv.org/abs/1312.6114

Code based on keras example:
https://blog.keras.io/building-autoencoders-in-keras.html
'''

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from keras.layers import Lambda, Input, Dense
from keras.models import Model
from keras.losses import mse
from keras.utils import plot_model
from keras import backend as K
from keras import metrics
from matplotlib import colors
from matplotlib import cm

import argparse
import math
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import seaborn as sns
import sys
from scipy import stats

exp_ints = {
	'no_response' : 0,
	'absolutely_none': 1,
	'other_language' : 2,
	'know_python' : 3,
	'veteran' : 4
	}

# reparameterization trick
# instead of sampling from Q(z|X), sample epsilon = N(0,I)
# z = z_mean + sqrt(var) * epsilon
def sampling(args):
	'''
	Reparameterization trick by sampling from an isotropic unit Gaussian.
	# Arguments
		args (tensor): mean and log of variance of Q(z|X)
	# Returns
		z (tensor): sampled latent vector
	'''
	z_mean, z_log_var = args
	batch = K.shape(z_mean)[0]
	dim = K.int_shape(z_mean)[1]
	# by default, random_normal has mean = 0 and std = 1.0
	epsilon = K.random_normal(shape=(batch, dim))
	return z_mean + K.exp(0.5 * z_log_var) * epsilon

def pad(array, reference_shape, offsets):
    '''
    Pads the array with zeros to fit the reference shape at the offsets given
    [0, 0] to align with top left
    :param array: Array to be padded
    :param reference_shape: tuple of size of ndarray to create
    :param offsets: list of offsets (number of elements must be equal to the dimension of the array)
    will throw a ValueError if offsets is too big and the reference_shape cannot handle the offsets
    '''
    result = np.zeros(reference_shape)
    insertHere = [slice(offsets[dim], offsets[dim] + array.shape[dim]) for dim in range(array.ndim)]
    result[insertHere] = array
    return result

def plot_training_loss(training_history, epochs, unit, problem):
	'''
	Plots the losses during training given the History object,
	number of epochs, and keyword list. Plots total, reconstruction,
	KL divergence, and feature-specific losses.
	:param training_history: the training history returned from model.fit
	:param epochs: number of epochs to train
	:param unit: course unit
	:param problem: course problem
	'''
	l = np.array(training_history.history['loss'])
	r_l = np.array(training_history.history['mse'])
	k_l = np.array(training_history.history['kl'])
	v_l = np.array(training_history.history['val_loss'])
	plt.plot(np.linspace(1, epochs, epochs), l, 'b+')
	plt.plot(np.linspace(1, epochs, epochs), r_l, 'c.')
	plt.plot(np.linspace(1, epochs, epochs), k_l, 'g.')
	plt.plot(np.linspace(1, epochs, epochs), v_l, 'r+')
	plt.legend(['training loss', 'reconstruction loss', 'KL divergence', 'validation loss'])
	plt.xlabel('epoch')
	plt.ylabel('loss')
	plt.title('Training Loss MSE+KL for Problem {}-{}'.format(unit, problem))
	os.makedirs('loss_plots', exist_ok=True)
	plt.savefig('loss_plots/flattraj_training_loss_{}_{}'.format(unit, problem))
	plt.close()

def plot_mean_results(models,
				 x_test,
				 y_test,
				 y1_test,
				 unit,
				 problem,
				 batch_size=128):
	'''
	Plots labels and vis of samples
		as a function of the 2D latent vector
	# Arguments
		models (tuple): encoder and decoder models
		x_test: test data
		y_test: first set of labels (experience)
		y1_test: second set of labels (video engagement)
		unit (int): course unit
		problem (int): course problem
		batch_size (int): prediction batch size
	'''
	encoder, decoder = models

	os.makedirs('means', exist_ok=True)

	# display a 2D plot of the experience classes in the latent space
	z_mean, _, _ = encoder.predict(x_test, batch_size=batch_size)

	for this_y in [y_test, y1_test]:
		plt.figure(figsize=(12, 10))
		sns.scatterplot(x=z_mean[:, 0], y=z_mean[:, 1], hue=this_y)
		plt.xlabel('z[0]')
		plt.ylabel('z[1]')
		if this_y is y_test:
			filename = 'means/vae_flattraj_mean_{}_{}_ytest.png'.format(unit, problem)
		else:
			filename = 'means/vae_flattraj_mean_{}_{}_y1test.png'.format(unit, problem)
		plt.savefig(filename)
		plt.close()

	# plot a density map in the latent space to contextualize the scatterplots
	filename = 'means/vae_flattraj_mean_{}_{}_kde.png'.format(unit, problem)
	plt.figure(figsize=(12, 10))
	cmap = sns.dark_palette("purple", as_cmap=True)
	ax = sns.kdeplot(z_mean[:, 0], z_mean[:, 1], n_levels=30, cmap=cmap)
	plt.xlabel('z[0]')
	plt.ylabel('z[1]')
	plt.savefig(filename)

	# mutate all y data to integers
	y_test = np.array([exp_ints[exp] for exp in y_test])
	y1_test = np.array([0 if vid==False else 1 for vid in y1_test])

	for this_y in [y_test, y1_test]:
		if this_y is y_test:
			print('EXPERIENCE')
		else:
			print('VIDEO ENGAGEMENT')
		_, _, r2, _, _ = stats.linregress(z_mean[:, 0], this_y)
		print('r-squared from regression z0 and this y:', r2)
		_, _, r2, _, _ = stats.linregress(z_mean[:, 1], this_y)
		print('r-squared from regression z1 and this y:', r2)

		pear = stats.pearsonr(z_mean[:, 0], this_y)
		print('r-squared from pearson correlation z0 and this y:', pear)
		pear = stats.pearsonr(z_mean[:, 1], this_y)
		print('r-squared from pearson correlation z1 and this y:', pear)

	return

def plot_latent_sampled(models,
				 x_test,
				 y_test,
				 y1_test,
				 unit,
				 problem):
	'''
	Plots vis of samples from latent space
	as a function of the 2D latent vector
	:param models (tuple): trained encoder and decoder networks
	:param x_test: test data
	:param y_test: labels
	:param unit: course unit
	:param problem: course problem
	'''
	encoder, decoder = models

	# display a 2D manifold of submissions
	n = 10
	num_keywords = 10
	max_subs = 30
	figure = np.zeros((1 * n, num_keywords * max_subs * n))
	latent_l1 = np.zeros((n, n))
	latent_l2 = np.zeros((n, n))

	# linearly spaced coordinates corresponding to
	# 2D plot of digit classes in latent space
	grid_x = np.linspace(-4, 4, n)
	grid_y = np.linspace(-4, 4, n)[::-1]

	for i, yi in enumerate(grid_y):
		for j, xi in enumerate(grid_x):
			z_sample = np.array([[xi, yi]])
			x_decoded = decoder.predict(z_sample)
			digit = x_decoded[0].reshape(1, num_keywords*max_subs)
			figure[i : (i + 1), j * num_keywords*max_subs: (j + 1) * num_keywords*max_subs] = np.rint(30*digit)
			latent_l1[i:i+1, j:j+1] = np.sum(np.rint(30*digit))
			latent_l2[i:i+1, j:j+1] = np.linalg.norm(np.rint(30*digit))

	viridis = cm.get_cmap('viridis', 256)

	os.makedirs('sample_vis', exist_ok=True)
	for norm in ['l1', 'l2']:
		filename = 'sample_vis/flattraj_subs_over_latent_{}_{}_{}.png'.format(norm, unit, problem)

		fig, ax = plt.subplots()
		if norm == 'l2':
			psm = ax.pcolormesh(latent_l2, cmap=viridis, rasterized=True)
		else:
			psm = ax.pcolormesh(latent_l1, cmap=viridis, rasterized=True)
		fig.colorbar(psm, ax=ax)

		ax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=2)
		ax.set_xticks([])
		ax.set_yticks([])

		plt.xlabel('z[0]')
		plt.ylabel('z[1]')
		if norm == 'l2':
			latent_title = 'L2 norm of submissions generated \n from sampled 2D latent space for Problem {}-{}'
		else:
			latent_title = 'L1 norm of submissions generated \n from sampled 2D latent space for Problem {}-{}'
		plt.title(latent_title.format(unit, problem), fontsize=10)
		plt.savefig(filename)
	return

# specify a save name based on the features you're using
# this will be added to output filenames of generated figures and plots
savename = 'vae_flattraj_kw_occ'

# specify problem to consider
unit = 2
pb = 3

# load keyword occurrence submissions dataset
sub_data_csv = '../../data/keyword_occurrence/trajectory/unit{}_pb{}_kw_occ_traj.csv'
sub_data = pd.read_csv(sub_data_csv.format(unit, pb), index_col=None)

sub_data['kw_occ_matrix'] = sub_data['kw_occ_matrix'].apply(lambda x:eval(x))
x_data = np.array([pad(np.array(row), (30, 10), [0, 0]) for row in sub_data['kw_occ_matrix'].to_numpy()])
# flatten trajectory matrices
original_dim = x_data[0].shape[0] * x_data[0].shape[1]
x_data = np.reshape(x_data, [-1, original_dim])

# in this case, y is experience level
exp_data = sub_data['user_exp'].to_numpy()
y_data = exp_data

# in this case, y1 is video engagement
video_data = sub_data['video_engaged'].to_numpy()
y1_data = video_data

# split train / test
train_pct = 0.7
i = math.ceil(0.7*x_data.shape[0])
x_train, x_test = x_data[0:i, :], x_data[i:, :]
y_train, y_test = y_data[0:i], y_data[i:]
y1_train, y1_test = y1_data[0:i], y1_data[i:]

# normalize
largest = x_data.max()
print('largest', largest)
x_train, x_test = x_train.astype('float32') / largest, x_test.astype('float32') / largest

print(x_train.shape, x_test.shape)
print(y_train.shape, y_test.shape)
print(y1_train.shape, y1_test.shape)

# Keyword occurrence network params
input_shape = (original_dim, )
batch_size = 50
intermediate_dim = 100
latent_dim = 2
epochs = 75

# VAE model = encoder + decoder
# build encoder model
inputs = Input(shape=input_shape, name='encoder_input')
print('input matrix is ', inputs)

x = Dense(intermediate_dim, activation='relu')(inputs)
z_mean = Dense(latent_dim, name='z_mean')(x)
z_log_var = Dense(latent_dim, name='z_log_var')(x)

# use reparameterization trick to push the sampling out as input
# note "output_shape" isn't necessary with the TensorFlow backend
z = Lambda(sampling, output_shape=(latent_dim,), name='z')([z_mean, z_log_var])

# instantiate encoder
encoder = Model(inputs, [z_mean, z_log_var, z], name='encoder')
encoder.summary()
plot_model(encoder, to_file='{}_encoder.png'.format(savename), show_shapes=True)

# build decoder
latent_inputs = Input(shape=(latent_dim,), name='z_sampling')
x = Dense(intermediate_dim, activation='relu')(latent_inputs)
outputs = Dense(original_dim, activation='sigmoid')(x)

# instantiate decoder
decoder = Model(latent_inputs, outputs, name='decoder')
decoder.summary()
plot_model(decoder, to_file='{}_decoder.png'.format(savename), show_shapes=True)

# instantiate VAE
outputs = decoder(encoder(inputs)[2])
vae = Model(inputs, outputs, name='vae_flattraj')

if __name__ == '__main__':

	print('inputs \n', inputs)
	print('input shape \n', inputs.shape)

	parser = argparse.ArgumentParser()

	help_ = "Load h5 model trained weights"
	parser.add_argument("-w", "--weights", help=help_)

	args = parser.parse_args()

	models = (encoder, decoder)

	def recon_loss(inp, out, in_dim):
		reconstruction_loss = mse(inp, out)
		reconstruction_loss *= in_dim
		return reconstruction_loss

	def kl_div_loss(mean, log_var):
		kl_loss = 1 + log_var - K.square(mean) - K.exp(log_var)
		kl_loss = K.sum(kl_loss, axis=-1)
		kl_loss *= -0.5
		return kl_loss

	reconstruction_loss = recon_loss(inputs, outputs, original_dim)
	kl_loss = kl_div_loss(z_mean, z_log_var)
	vae_loss = K.mean(reconstruction_loss + kl_loss)
	vae.add_loss(vae_loss)

	vae.compile(loss=None, optimizer='adam')
	# https://github.com/keras-team/keras/issues/9526
	vae.summary()
	plot_model(vae, to_file='{}.png'.format(savename), show_shapes=True)

	# add custom metrics
	# https://github.com/keras-team/keras/issues/9459
	vae.metrics_tensors.append(K.mean(reconstruction_loss))
	vae.metrics_names.append("mse")

	vae.metrics_tensors.append(K.mean(kl_loss))
	vae.metrics_names.append("kl")

	if args.weights:
		vae.load_weights(args.weights)
	else:
		# train autoencoder
		train_h = vae.fit(x_train,
				epochs=epochs,
				batch_size=batch_size,
				validation_data=(x_test, None))

		# inspect training losses
		plot_training_loss(train_h, epochs, unit, pb)

		# save trained weights
		os.makedirs('weights', exist_ok=True)
		w_filename = 'weights/{}_{}_{}.h5'.format(savename, unit, pb)
		vae.save_weights(w_filename)

	# show means of test set in latent space
	plot_mean_results(models,
				 x_test,
				 y_test,
				 y1_test,
				 unit,
				 pb,
				 batch_size=batch_size)

	# visualize generated vectors from sampling the latent space
	plot_latent_sampled(models, x_test, y_test, y1_test, unit, pb)


import os.path as osp
import os, datetime, sys
import gym
import fnmatch
import time
import joblib
import logging
import numpy as np
import tensorflow as tf
from baselines import logger

from baselines.common import set_global_seeds, explained_variance
from baselines.common.vec_env.subproc_vec_env import SubprocVecEnv
from baselines.common.atari_wrappers import wrap_deepmind

from baselines.a2c.utils import discount_with_dones
from baselines.a2c.utils import Scheduler, make_path, find_trainable_variables
from baselines.a2c.policies import CnnPolicy
from baselines.a2c.utils import cat_entropy, mse

class Model(object):

    def __init__(self, policy, ob_space, ac_space, nenvs, nsteps, nstack, num_procs,
            ent_coef=0.01, vf_coef=0.5, max_grad_norm=0.5, lr=7e-4,
            alpha=0.99, epsilon=1e-5, total_timesteps=int(80e6), lrschedule='linear', nModelsToKeep=5):
        config = tf.ConfigProto(allow_soft_placement=True,
                                intra_op_parallelism_threads=num_procs,
                                inter_op_parallelism_threads=num_procs)
        config.gpu_options.allow_growth = True
        sess = tf.Session(config=config)
        nact = ac_space.n
        nbatch = nenvs*nsteps

        A = tf.placeholder(tf.int32, [nbatch])
        ADV = tf.placeholder(tf.float32, [nbatch])
        R = tf.placeholder(tf.float32, [nbatch])
        LR = tf.placeholder(tf.float32, [])

        step_model = policy(sess, ob_space, ac_space, nenvs, 1, nstack, reuse=False)
        train_model = policy(sess, ob_space, ac_space, nenvs, nsteps, nstack, reuse=True)

        neglogpac = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=train_model.pi, labels=A)
        pg_loss = tf.reduce_mean(ADV * neglogpac)
        vf_loss = tf.reduce_mean(mse(tf.squeeze(train_model.vf), R))
        entropy = tf.reduce_mean(cat_entropy(train_model.pi))
        loss = pg_loss - entropy*ent_coef + vf_loss * vf_coef

        params = find_trainable_variables("model")
        grads = tf.gradients(loss, params)
        if max_grad_norm is not None:
            grads, grad_norm = tf.clip_by_global_norm(grads, max_grad_norm)
        grads = list(zip(grads, params))
        trainer = tf.train.RMSPropOptimizer(learning_rate=LR, decay=alpha, epsilon=epsilon)
        _train = trainer.apply_gradients(grads)

        lr = Scheduler(v=lr, nvalues=total_timesteps, schedule=lrschedule)

        def train(obs, states, rewards, masks, actions, values):
            advs = rewards - values
            for step in range(len(obs)):
                cur_lr = lr.value()
            td_map = {train_model.X:obs, A:actions, ADV:advs, R:rewards, LR:cur_lr}
            if states != []:
                td_map[train_model.S] = states
                td_map[train_model.M] = masks
            policy_loss, value_loss, policy_entropy, _ = sess.run(
                [pg_loss, vf_loss, entropy, _train],
                td_map
            )
            return policy_loss, value_loss, policy_entropy

        def save():
            modelfile = os.path.join(logger.get_dir(), datetime.datetime.now().strftime("model-%Y-%m-%d-%H-%M-%S-%f"))

            ps = sess.run(params)
            joblib.dump(ps, modelfile)
            logger.log('Model saved to %s'%modelfile)

            model_files = sorted(fnmatch.filter(os.listdir(logger.get_dir()), "model-*"))
            if len(model_files) > nModelsToKeep:
                for old_file in model_files[0:-nModelsToKeep]:
                    os.remove(os.path.join(logger.get_dir(), old_file))

        def load(load_path):
            loaded_params = joblib.load(load_path)
            restores = []
            for p, loaded_p in zip(params, loaded_params):
                restores.append(p.assign(loaded_p))
            ps = sess.run(restores)
            logger.log('Model loaded from %s'%load_path)

        self.train = train
        self.train_model = train_model
        self.step_model = step_model
        self.step = step_model.step
        self.value = step_model.value
        self.initial_state = step_model.initial_state
        self.save = save
        self.load = load
        tf.global_variables_initializer().run(session=sess)

class Runner(object):

    def __init__(self, env, model, nsteps=5, nstack=4, gamma=0.99):
        self.env = env
        self.model = model
        nh, nw, nc = env.observation_space.shape
        nenv = env.num_envs
        self.nEnvs = nenv
        self.batch_ob_shape = (nenv*nsteps, nh, nw, nc*nstack)
        self.nc = nc
        self.gamma = gamma
        self.nsteps = nsteps
        def reset():
            self.obs = np.zeros((nenv, nh, nw, nc*nstack), dtype=np.uint8)
            obs = env.reset()
            self.update_obs(obs)
            self.states = model.initial_state
            self.dones = [False for _ in range(nenv)]
        self.reset = reset
        self.reset()

    def update_obs(self, obs):
        # Do frame-stacking here instead of the FrameStack wrapper to reduce
        # IPC overhead
        self.obs = np.roll(self.obs, shift=-self.nc, axis=3)
        self.obs[:, :, :, -self.nc:] = obs

    def run(self):
        mb_obs, mb_rewards, mb_actions, mb_values, mb_dones = [],[],[],[],[]
        mb_states = self.states
        for n in range(self.nsteps):
            actions, values, states = self.model.step(self.obs, self.states, self.dones)
            mb_obs.append(np.copy(self.obs))
            mb_actions.append(actions)
            mb_values.append(values)
            mb_dones.append(self.dones)
            obs, rewards, dones, _ = self.env.step(actions)
            self.states = states
            self.dones = dones
            for n, done in enumerate(dones):
                if done:
                    self.obs[n] = self.obs[n]*0
            self.update_obs(obs)
            mb_rewards.append(rewards)
        mb_dones.append(self.dones)
        #batch of steps to batch of rollouts
        mb_obs = np.asarray(mb_obs, dtype=np.uint8).swapaxes(1, 0).reshape(self.batch_ob_shape)
        mb_rewards = np.asarray(mb_rewards, dtype=np.float32).swapaxes(1, 0)
        mb_actions = np.asarray(mb_actions, dtype=np.int32).swapaxes(1, 0)
        mb_values = np.asarray(mb_values, dtype=np.float32).swapaxes(1, 0)
        mb_dones = np.asarray(mb_dones, dtype=np.bool).swapaxes(1, 0)
        mb_masks = mb_dones[:, :-1]
        mb_dones = mb_dones[:, 1:]
        last_values = self.model.value(self.obs, self.states, self.dones).tolist()
        #discount/bootstrap off value fn
        for n, (rewards, dones, value) in enumerate(zip(mb_rewards, mb_dones, last_values)):
            rewards = rewards.tolist()
            dones = dones.tolist()
            if dones[-1] == 0:
                rewards = discount_with_dones(rewards+[value], dones+[0], self.gamma)[:-1]
            else:
                rewards = discount_with_dones(rewards, dones, self.gamma)
            mb_rewards[n] = rewards
        mb_rewards = mb_rewards.flatten()
        mb_actions = mb_actions.flatten()
        mb_values = mb_values.flatten()
        mb_masks = mb_masks.flatten()
        return mb_obs, mb_states, mb_rewards, mb_masks, mb_actions, mb_values

    def eval(self, maxStepsPerEpisode=4500, nEpisodes=50):
        total_rewards, total_dones = [],[]
        total_steps, total_episodes = 0, 0

        # Run for maxStepsPerEpisode steps, or nEpisodes episodes, whichever is shorter
        while total_steps < maxStepsPerEpisode and total_episodes < nEpisodes:
            self.reset()
            step_rewards, step_dones = [],[]
            ep_dones = np.asarray(self.dones, dtype=np.bool)

            for n in range(int(maxStepsPerEpisode)):
                actions, values, states = self.model.step(self.obs, self.states, self.dones)
                step_dones.append(self.dones)
                obs, rewards, dones, _ = self.env.step(actions)
                self.states = states
                self.dones = dones
                for i, done in enumerate(dones):
                    if done:
                        self.obs[i] = self.obs[i]*0 # ignore observation
                self.update_obs(obs)
                step_rewards.append(rewards)
                ep_dones = np.logical_or(ep_dones, np.asarray(dones, dtype=np.bool))
                if np.all(ep_dones):
                    break
            ep_steps = n+1
            step_dones.append(self.dones)

            #batch of steps to batch of rollouts
            env_rewards = np.asarray(step_rewards, dtype=np.float32).swapaxes(1, 0)
            env_dones = np.asarray(step_dones, dtype=np.bool).swapaxes(1, 0)
            env_dones = env_dones[:, 1:]

            ep_dones, ep_rewards = [], []
            # compute total scores
            for n, (rewards, dones) in enumerate(zip(env_rewards, env_dones)):
                rewards = rewards.tolist()
                dones = dones.tolist()
                rawscore = discount_with_dones(rewards, dones, gamma=1.0)[0]
                done = (True in dones)
                ep_rewards.append(rawscore)
                ep_dones.append(done)

            total_rewards.append(ep_rewards)
            total_dones.append(ep_dones)
            total_steps += ep_steps
            total_episodes += self.nEnvs

        total_rewards = np.asarray(total_rewards, dtype=np.float32)
        total_dones = np.asarray(total_dones, dtype=np.bool)
        total_rewards = total_rewards.flatten()
        total_dones = total_dones.flatten()

        avg_score = np.mean(total_rewards)
        n_timeouts = np.size(total_dones) - np.sum(total_dones)

        logger.log("Evaluation complete:")
        logger.record_tabular("eval_avg_score", avg_score)
        logger.record_tabular("eval_steps", total_steps*self.nEnvs)
        logger.record_tabular("eval_episodes", total_episodes)
        logger.record_tabular("eval_n_timeouts", n_timeouts)
        logger.dump_tabular()

def learn(policy, env, eval_env, seed, nsteps=5, nstack=4, total_timesteps=int(80e6),
    vf_coef=0.5, ent_coef=0.01, max_grad_norm=0.5, lr=7e-4, lrschedule='linear',
    epsilon=1e-5, alpha=0.99, gamma=0.99, log_interval=100, eval_interval=12500, model_path=""):
    tf.reset_default_graph()
    set_global_seeds(seed)

    nenvs = env.num_envs
    ob_space = env.observation_space
    ac_space = env.action_space
    num_procs = len(env.remotes) # HACK
    model = Model(policy=policy, ob_space=ob_space, ac_space=ac_space, nenvs=nenvs, nsteps=nsteps, nstack=nstack, num_procs=num_procs, ent_coef=ent_coef, vf_coef=vf_coef,
        max_grad_norm=max_grad_norm, lr=lr, alpha=alpha, epsilon=epsilon, total_timesteps=total_timesteps, lrschedule=lrschedule)
    if model_path:
        model.load(model_path)
    runner = Runner(env, model, nsteps=nsteps, nstack=nstack, gamma=gamma)
    eval_runner = Runner(eval_env, model, nsteps=1, nstack=nstack, gamma=gamma)

    nbatch = nenvs*nsteps
    tstart = time.time()
    for update in range(1, total_timesteps//nbatch+1):
        obs, states, rewards, masks, actions, values = runner.run()
        policy_loss, value_loss, policy_entropy = model.train(obs, states, rewards, masks, actions, values)
        nseconds = time.time()-tstart
        fps = int((update*nbatch)/nseconds)
        if update % log_interval == 0 or update == 1:
            ev = explained_variance(values, rewards)
            logger.record_tabular("nupdates", update)
            logger.record_tabular("total_timesteps", update*nbatch)
            logger.record_tabular("fps", fps)
            logger.record_tabular("policy_entropy", float(policy_entropy))
            logger.record_tabular("value_loss", float(value_loss))
            logger.record_tabular("explained_variance", float(ev))
            logger.dump_tabular()
        if update % eval_interval == 0 or update == 1:
            logger.record_tabular("nupdates", update)
            logger.record_tabular("total_timesteps", update*nbatch)
            eval_runner.eval()
            model.save()

    logger.record_tabular("nupdates", update)
    logger.record_tabular("total_timesteps", update*nbatch)
    eval_runner.eval()
    model.save()

if __name__ == '__main__':
    main()


"""
A splash screen widget with support for positioning of the message text.

"""

from PyQt4.QtGui import (
    QSplashScreen,  QWidget, QPixmap, QPainter, QTextDocument,
    QTextBlockFormat, QTextCursor, QApplication
)
from PyQt4.QtCore import Qt

from .utils import is_transparency_supported

class SplashScreen(QSplashScreen):
    """
    Splash screen widget.

    Parameters
    ----------
    parent : :class:`QWidget`
        Parent widget

    pixmap : :class:`QPixmap`
        Splash window pixmap.

    textRect : :class:`QRect`
        Bounding rectangle of the shown message on the widget.

    """
    def __init__(self, parent=None, pixmap=None, textRect=None, **kwargs):
        QSplashScreen.__init__(self, parent, **kwargs)
        self.__textRect = textRect
        self.__message = ""
        self.__color = Qt.black
        self.__alignment = Qt.AlignLeft

        if pixmap is None:
            pixmap = QPixmap()

        self.setPixmap(pixmap)

        self.setAutoFillBackground(False)
        # Also set FramelesWindowHint (if not already set)
        self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)

    def setTextRect(self, rect):
        """
        Set the rectangle (:class:`QRect`) in which to show the message text.
        """
        if self.__textRect != rect:
            self.__textRect = rect
            self.update()

    def textRect(self):
        """
        Return the text message rectangle.
        """
        return self.__textRect

    def showEvent(self, event):
        QSplashScreen.showEvent(self, event)
        # Raise to top on show.
        self.raise_()

    def drawContents(self, painter):
        """
        Reimplementation of drawContents to limit the drawing
        inside `textRext`.

        """
        painter.setPen(self.__color)
        painter.setFont(self.font())

        if self.__textRect:
            rect = self.__textRect
        else:
            rect = self.rect().adjusted(5, 5, -5, -5)
        if Qt.mightBeRichText(self.__message):
            doc = QTextDocument()
            doc.setHtml(self.__message)
            doc.setTextWidth(rect.width())
            cursor = QTextCursor(doc)
            cursor.select(QTextCursor.Document)
            fmt = QTextBlockFormat()
            fmt.setAlignment(self.__alignment)
            cursor.mergeBlockFormat(fmt)
            painter.save()
            painter.translate(rect.topLeft())
            doc.drawContents(painter)
            painter.restore()
        else:
            painter.drawText(rect, self.__alignment, self.__message)

    def showMessage(self, message, alignment=Qt.AlignLeft, color=Qt.black):
        """
        Show the `message` with `color` and `alignment`.
        """
        # Need to store all this arguments for drawContents (no access
        # methods)
        self.__alignment = alignment
        self.__color = color
        self.__message = message
        QSplashScreen.showMessage(self, message, alignment, color)
        QApplication.instance().processEvents()

    # Reimplemented to allow graceful fall back if the windowing system
    # does not support transparency.
    def setPixmap(self, pixmap):
        self.setAttribute(Qt.WA_TranslucentBackground,
                          pixmap.hasAlpha() and \
                          is_transparency_supported())

        self.__pixmap = pixmap

        QSplashScreen.setPixmap(self, pixmap)
        if pixmap.hasAlpha() and not is_transparency_supported():
            self.setMask(pixmap.createHeuristicMask())

    def repaint(self):
        QWidget.repaint(self)
        QApplication.flush()

    def event(self, event):
        if event.type() == event.Paint:
            pixmap = self.__pixmap
            painter = QPainter(self)
            if not pixmap.isNull():
                painter.drawPixmap(0, 0, pixmap)
            self.drawContents(painter)
            return True
        return QSplashScreen.event(self, event)


from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def css_classes(context, first, last, odd, even):
    """
    Maps loop variables of :tag:`for` tag to CSS classes string.

    Takes names of first, last, odd, even CSS classes, respectively

    Example usage::

        {% css_classes "first" "last" "odd" "even" %}
    """

    classes = []
    if context['forloop'].get('first', False):
        classes.append(first)
    if context['forloop'].get('last', False):
        classes.append(last)
    if context['forloop']['revcounter'] % 2 == 1:
        classes.append(odd)
    else:
        classes.append(even)

    return u' '.join(classes)


import cv2 as cv
import glob
import nibabel as nib
import numpy as np
import os

def nii2png(save_dir, image_path, is_label=False):
    num = 0
    os.mkdir(os.path.join(save_dir, os.path.basename(image_path)[:-4]))
    image = nib.load(image_path)
    fdata = image.get_fdata()
    x, y, z = fdata.shape
    for i in range(z):
        image_arr = fdata[:, :, i].astype(np.uint8)
        if is_label:
            image_arr = np.where(image_arr == 1, 255, image_arr)
            image_arr = np.where(image_arr == 2, 128, image_arr)
        cv.imwrite(os.path.join(save_dir, os.path.basename(image_path)[:-4], os.path.basename(image_path)[:-4] + '-' + str(num) + '.png'), image_arr)
        num += 1

def main():
    train_image_dir = 'data/train/image'
    train_label_dir = 'data/train/label'
    test_image_dir = 'data/test/image'
    train_image_path = glob.glob(os.path.join(train_image_dir, '*.nii'))
    train_label_path = glob.glob(os.path.join(train_label_dir, '*.nii'))
    test_image_path = glob.glob(os.path.join(test_image_dir, '*.nii'))
    train_image_path.sort()
    train_label_path.sort()
    test_image_path.sort()

    train_image_save = 'visualized/train/image'
    train_label_save = 'visualized/train/label'
    test_image_save = 'visualized/test/image'

    for train_label in train_label_path:
        nii2png(train_label_save, train_label, True)

    for train_image in train_image_path:
        nii2png(train_image_save, train_image)

    for test_image in test_image_path:
        nii2png(test_image_save, test_image)

if __name__ == '__main__':
    main()


"""Add radius to user

Revision ID: db3b724303df
Revises: 9aa8b8cbaad0
Create Date: 2021-01-26 01:51:25.641500

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'db3b724303df'
down_revision = '9aa8b8cbaad0'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('user', sa.Column('radius', sa.Float(), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('user', 'radius')
    # ### end Alembic commands ###


# Write a program to input two and perform the following operations:
# 1. Display the list having maximum number of elements
# 2. Display the uinion
# Example:
# Enter first list
# [9,5,6,9,2]
# Enter second list
# [8,5,2,9]
# Thw e list having max no. of elements is [9,5,6,9,2]
# The union is
# [2,5,6,8,9]

list1=eval(input("Enter First list ==> "))
list2=eval(input("Enter Second list ==> "))
length1=len(list1)
length2=len(list2)
if length1==length2:
    print("Both the lisths have same number of elements")
elif length1>length2:
    print("The list havaing max no. elements is",list1)
else:
    print("The list having max no. of elements is",list2)
#union
list1.extend(list2)
list1.sort()
unique=[]
for val in list1:
    if val not in unique:
        unique.append(val)
print("Union is ==> ",unique)


class Twitter:

    def __init__(self):
        self.hashmap = {}
        self.tweets = []

    def postTweet(self, userId: int, tweetId: int) -> None:
        self.tweets.append([userId, tweetId])

    def getNewsFeed(self, userId: int) -> List[int]:
        returned = []
        followed = {}
        if userId in self.hashmap:
            followed = self.hashmap[userId]
        for i in range(len(self.tweets)):
            if self.tweets[i][0] in followed:
                returned.insert(0,self.tweets[i][1])
            elif userId == self.tweets[i][0]:
                returned.insert(0,self.tweets[i][1])
            if len(returned) == 11:
                returned.pop(-1)
        return returned

    def follow(self, followerId: int, followeeId: int) -> None:
        if followerId not in self.hashmap:
            self.hashmap[followerId] = {followeeId}
        else:
            self.hashmap[followerId].add(followeeId)

    def unfollow(self, followerId: int, followeeId: int) -> None:
        if followerId in self.hashmap:
            self.hashmap[followerId].remove(followeeId)

# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId)


import base64
import cherrypy
import io
import matplotlib.pyplot as plt
import numpy as np
import os
import re
from scipy import special

def sharlie(n):
    return special.erfinv((n - 1) / n) * np.sqrt(2)

def statistics(x):
    """return mean, sample std"""
    return x.mean(), np.sqrt(np.sum((x - x.mean()) ** 2) / (len(x) - 1))

def metric(x):
    """return normalized deviation"""
    mean, sko = statistics(x)
    return np.abs(x - mean) / sko

def borders(x):
    """return borders for good values"""
    sh = sharlie(len(x))
    s = np.sqrt(np.sum((x - x.mean()) ** 2) / (len(x) - 1))
    m = x.mean()
    return m - sh * s, m + sh * s

def find_bad(x):
    """return good and bad values in dataset"""
    test = metric(x)
    mask = test > sharlie(len(x))
    bad = x[mask]
    x = x[~mask]
    return x, bad

def plt_to_base64(x, ok, bad, size=5):
    """draw plot graph"""
    border = borders(ok) if len(ok) > 0 else None
    iterator_ok = np.arange(len(x))[np.isin(x, ok)]
    iterator_bad = np.arange(len(x))[np.isin(x, bad)]
    plt.figure(figsize=(size, size))
    plt.grid(True)
    plt.title("Обработка выборки")
    plt.xlabel("#")
    plt.ylabel("Значение")
    if border is not None:
        plt.hlines(border, 0, len(x) - 1, color="r", linestyles="dashed")
    plt.scatter(iterator_ok, ok, label="Хорошие значения")
    plt.scatter(iterator_bad, bad, label="Промахи")
    plt.legend()
    b = io.BytesIO()
    plt.savefig(b, format="png")
    b.seek(0)
    return base64.b64encode(b.read()).decode()

def calc(x):
    history = []
    x = np.array(x)
    bad = [0]  # do-while loop
    ok = x.copy()
    while len(bad) != 0 and len(ok) > 1:
        mean, sko = statistics(ok)
        sh = sharlie(len(ok))
        ok, bad = find_bad(ok)
        history.append({"ok": ok.tolist(), "bad": bad.tolist(), "plot": plt_to_base64(x, ok, bad), "mean": mean, "sko": sko, "sharlie": sh})
    return history

def get_page():
    with open("index.html", 'r', encoding='utf8') as f:
        return f.read()

page = None
if os.environ.get('DEVELOPMENT') is None:
    page = get_page()

class Root(object):
    @cherrypy.expose
    def index(self):
        return get_page() if page is None else page

    @cherrypy.expose
    @cherrypy.tools.json_out()
    @cherrypy.tools.json_in()
    def calc(self):
        data = list(map(float, " ".join(re.findall('[0-9.]*', cherrypy.request.json["data"].replace(",", "."))).split()))
        return calc(data)

if __name__ == '__main__':
    cherrypy.config.update({
        'server.socket_host': '0.0.0.0',
        'server.socket_port': 8080,
        'tools.proxy.on': True,
    })
    cherrypy.quickstart(Root())


from covidApi import *
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import uic
form_class = uic.loadUiType("covid.ui")[0]

class MyWindow(QMainWindow, form_class):

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.covidapi = covidApi()
        self.setTableWidgetData()
    def setTableWidgetData(self):
        for j in range(0, 18):
            for i in range(0, 6):
                item = QTableWidgetItem(self.covidapi.data[i][j].text)
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget.setItem(j, i, item)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWindow = MyWindow()
    myWindow.show()
    app.exec_()


from django.urls import path
from . import views
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('pkmn_viewset', views.PokemonViewSet)

urlpatterns = [
    path('<int:pk>', views.PokemonRetrieveAPIView.as_view()),
    path('create', views.PokemonListCreateAPIView.as_view()),
    path('<int:pk>/delete', views.PokemonDestroyAPIView.as_view()),
    path('<int:pk>/update', views.PokemonUpdateAPIView.as_view())
] + router.urls


import re

import requests
from bs4 import BeautifulSoup, Tag

from .constants import EDUCATION_LEVELS_NAMES
from .education_plan_file import EducationPlanFile

MIREA_URL = "https://www.mirea.ru"
MIREA_PLANS_URL = f"{MIREA_URL}/sveden/education/"

PLANS_TABLE_SELECTOR = "table[itemprop='eduOp']"

def _get_plans_table() -> Tag:
    response = requests.get(MIREA_PLANS_URL)

    if response.status_code != 200:
        return None

    soup = BeautifulSoup(response.text, "html.parser")
    return soup.select_one(PLANS_TABLE_SELECTOR)

def get_plans() -> list[EducationPlanFile]:
    plans_table = _get_plans_table()

    if plans_table is None:
        return []

    plans = []

    rows = plans_table.select("tr")
    # Skip first two rows (header and empty row)
    for row in rows[2:]:
        cells = row.select("td")
        if len(cells) < 5:
            continue

        code = cells[0].get_text().strip()

        # The name and if there is a profile, then it is in parentheses.
        # For example: Applied Mathematics and Computer Science
        # (Mathematical Modeling and Computational Mathematics)
        name = cells[1].text.strip()
        if "(" in name:
            name = name[: name.find("(")].strip()
            # Get value in ( ... ) with regex
            profile = re.search(r"\((.*)\)", cells[1].text.strip())[1].strip()

            if "«" in profile:
                # Get value in « ... » with regex
                profile = re.search(r"«(.*)»", profile)[1].strip()
        else:
            profile = None

        cell_val = cells[2].get_text()
        education_level = next(
            (
                key
                for key, value in EDUCATION_LEVELS_NAMES.items()
                if value in cell_val.lower()
            ),
            None,
        )

        if education_level is None:
            continue

        urls = cells[5].select("a")
        for url in urls:
            href = url.get("href")
            if href is None:
                continue
            if not href.endswith(".pdf"):
                continue

            href = MIREA_URL + href

            plans.append(
                EducationPlanFile(
                    url=href,
                    code=code,
                    name=name,
                    year=int(href.split("_")[-1].split(".")[0].strip()),
                    education_level=education_level,
                    profile=profile,
                )
            )

    return plans


import zipfile
import chardet

def unarchive_book(path):
    title = path.rsplit("/", 1)[1].replace(".zip", "")
    archive = zipfile.ZipFile(path, 'r')

    for txt_file in archive.namelist():
        print(title)
        if txt_file.endswith(".txt"):
            raw_text = archive.read(txt_file)
            break

    detect = chardet.detect(raw_text)

    raw_text = raw_text.decode(detect["encoding"])

    return raw_text


import pygame
import math
import sys, os

from Settings import *

class PresentWord:

    def __init__(self, word):

        self.word = word

        self.normal_font = pygame.font.Font(FONT_LOCATION, FONT_SIZE_MENU_B)
        self.small_font = pygame.font.Font(FONT_LOCATION, FONT_SIZE_MENU)

        self.word_font = pygame.font.Font(FONT_LOCATION, FONT_TITLE_B)

        self.background_color = ((255, 255, 255))
        self.text_color = ((10,10,10))
        self.word_color = ((50, 180, 50))

        self.start_timer = -1000
        self.total_time = 4000
        self.time_after_word = 1000
        self.word_shrik_time = 100
        self.resize = 10
        self.start_resize = 500

    def get_word_surface(self):

        word_surface = self.word_font.render(self.word, False, self.word_color, (0,0,0)).convert_alpha()
        word_surface.set_colorkey((0,0,0))

        rect = word_surface.get_rect()

        ticks = pygame.time.get_ticks()

        # TODO: Here by manipulating the math cool things can happen
        x_factor = (ticks - self.start_timer) / self.time_after_word
        x_factor = x_factor**2  # Faster at the end (sqrt is slower at the end)
        if x_factor > 1:
            x_factor = 1

        mult_factor = self.resize + (1 - self.resize) * x_factor

        new_size = (rect.width * mult_factor, rect.height * mult_factor)

        new_surface = pygame.transform.scale(word_surface, new_size)
        new_surface.set_colorkey((0,0,0))
        return new_surface

    def can_press_return(self):
        ticks = pygame.time.get_ticks()
        if ticks - self.start_timer > self.start_resize + self.word_shrik_time:
            return True
        return False

    def blit_text(self, screen):
        ticks = pygame.time.get_ticks()

        text = self.normal_font.render("Compose the word...", False, self.text_color, (0,0,0))
        text.set_colorkey((0,0,0))

        text_rect = text.get_rect()
        screen_rect = screen.get_rect()

        text_rect.center = screen_rect.center
        text_rect.y = screen_rect.height / 3 - text_rect.height / 2

        screen.blit(text, text_rect)

        if self.can_press_return():
            text =  self.small_font.render("Press enter to start", False, self.text_color, (0,0,0))
            text.set_colorkey((0,0,0))
            text_rect = text.get_rect()
            screen_rect = screen.get_rect()

            text_rect.center = screen_rect.center
            text_rect.y = screen_rect.height * 2 / 3

            # Make it flicker
            alpha = (math.sin(2 * math.pi * ticks / 800) + 1) / 2
            alpha *= 255
            text.set_alpha(alpha)

            screen.blit(text, text_rect)

        if ticks - self.start_timer > self.start_resize:
            # Blit the main word here
            surface = self.get_word_surface()
            surf_rect = surface.get_rect()
            surf_rect.center = screen_rect.center

            screen.blit(surface, surf_rect)

    def run(self):

        screen = pygame.display.get_surface()
        self.start_timer = pygame.time.get_ticks()

        clock = pygame.time.Clock()
        running = True
        while running:
            clock.tick(60)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()

                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_RETURN and self.can_press_return():
                        running = False

            screen.fill(self.background_color)
            self.blit_text(screen)

            pygame.display.flip()


#-------------------------------------------------------------------------------
# . File      : ConjugateGradientMinimizer.py
# . Program   : pDynamo-1.9.0                           (http://www.pdynamo.org)
# . Copyright : CEA, CNRS, Martin J. Field (2007-2014)
# . License   : CeCILL French Free Software License     (http://www.cecill.info)
#-------------------------------------------------------------------------------
"""Conjugate gradient minimizer with a choice of step methods."""

# . The spectral modification follows the method of E. G. Birgin and J. M. Martinez (2001).

import math

from MultiDimensionalMinimizer import MultiDimensionalMinimizer, MultiDimensionalMinimizerState
from MoreThuenteLineSearch     import MoreThuenteLineSearcher
from ObjectiveFunction         import UniDimensionalObjectiveFunction
from Real1DArray               import Real1DArray

#
# . Notes:
#
#   - Additional line search methods.
#   - Methods for determining the initial step for the line search (see NocWri99 p58).
#   - Restart methods (e.g. Pow77 section 4).
#   - Ways of exiting gracefully or recovering if an SCF fails to converge.
#

#===================================================================================================================================
# . Parameters.
#===================================================================================================================================
# . Default parameters for the line searcher.
_LineSearcherParameters = { "bisectionFactor"              :  0.66    ,
                            "functionTolerance"            :  1.0e-04 ,
                            "gradientTolerance"            :  0.1     , # . Better for CG methods?
                            "initialStep"                  :  1.0     ,
                            "logFrequency"                 : -1       ,
                            "lowerStepExtrapolationFactor" :  1.1     ,
                            "maximumIterations"            : 20       ,
                            "safeguardFactor"              :  0.66    ,
                            "upperStepExtrapolationFactor" :  4.0     ,
                            "variableTolerance"            :  1.0e-15 }

#===================================================================================================================================
# . Class.
#===================================================================================================================================
class CGObjectiveFunction ( UniDimensionalObjectiveFunction ):
    """The line search objective function."""

    defaultAttributes = { "d"                 : None ,
                          "f"                 : None ,
                          "f0"                : None ,
                          "fB"                : None ,
                          "g"                 : None ,
                          "g0"                : None ,
                          "gB"                : None ,
                          "objectiveFunction" : None ,
                          "vB"                : None ,
                          "x"                 : None ,
                          "x0"                : None ,
                          "xB"                : None }
    defaultAttributes.update ( UniDimensionalObjectiveFunction.defaultAttributes )

    @classmethod
    def FromOptions ( selfClass, **options ):
        """Constructor from options."""
        self = selfClass ( )
        for ( key, value ) in options.iteritems ( ): setattr ( self, key, value )
        return self

    def FunctionGradient ( self, alpha ):
        """Evaluate the function and gradient."""
        # . Save the explicit variable.
        self.variable = alpha
        # . Set up the implicit variables.
        self.x0.CopyTo ( self.x )
        self.x.AddScaledArray ( alpha, self.d )
        #print "\nRMS and Maximum Step> ", alpha * self.d.RootMeanSquare ( ), alpha * self.d.AbsoluteMaximum ( ),
        # . Function and gradients.
        self.f = self.objectiveFunction.FunctionGradients ( self.x, self.g )
        return ( self.f, self.d.Dot ( self.g ) )

#    def GetBounds ( self ): return ( 0.0, _LargeNumber )

    def GetValuesAtOrigin ( self ):
        """Get the values at the origin."""
        return ( 0.0, self.f0, self.g0 )

    def SetValuesAtOrigin ( self, f0, g0 ):
        """Set the values at the origin."""
        self.f0 = f0
        self.g0 = g0

    def RestoreBestToCurrent ( self ):
        """Make the best point the current one."""
        self.f        = self.fB
        self.variable = self.vB
        self.gB.CopyTo ( self.g )
        self.xB.CopyTo ( self.x )

    def StoreCurrentAsBest ( self ):
        """Save the current point as the best point."""
        self.fB = self.f
        self.vB = self.variable
        self.g.CopyTo ( self.gB )
        self.x.CopyTo ( self.xB )

#===================================================================================================================================
# . Class.
#===================================================================================================================================
class ConjugateGradientMinimizerState ( MultiDimensionalMinimizerState ):
    """Conjugate gradient minimizer state."""

    # . Default attributes.
    defaultAttributes = { "g0"                          : None ,
                          "gDotG"                       : 0.0  ,
                          "lineSearchObjectiveFunction" : None ,
                          "s"                           : None ,
                          "theta"                       : 1.0  ,
                          "x0"                          : None ,
                          "y"                           : None }
    defaultAttributes.update ( MultiDimensionalMinimizerState.defaultAttributes )

    def SetUp ( self ):
       """Set up the state."""
       # . Arrays.
       super ( ConjugateGradientMinimizerState, self ).SetUp ( )
       self.g0 = Real1DArray.WithExtent ( self.numberOfVariables ) ; self.g0.Set ( 0.0 )
       self.s  = Real1DArray.WithExtent ( self.numberOfVariables ) ; self.s.Set  ( 0.0 )
       self.x0 = Real1DArray.WithExtent ( self.numberOfVariables ) ; self.x0.Set ( 0.0 )
       self.y  = Real1DArray.WithExtent ( self.numberOfVariables ) ; self.y.Set  ( 0.0 )
       # . Line-search objective function.
       # . s and y are used here as they are only used for workspace and not for persistent storage.
       self.lineSearchObjectiveFunction = CGObjectiveFunction.FromOptions ( d                 = self.d                 ,
                                                                            g                 = self.g                 ,
                                                                            gB                = self.s                 ,
                                                                            objectiveFunction = self.objectiveFunction ,
                                                                            x                 = self.x                 ,
                                                                            x0                = self.x0                ,
                                                                            xB                = self.y                 )

#===================================================================================================================================
# . Class.
#===================================================================================================================================
class ConjugateGradientMinimizer ( MultiDimensionalMinimizer ):
    """Conjugate gradient multidimensional minimizer."""

    # . Possible betaTypes are:
    #   1 and everything else - Perry
    #   2                     - Fletcher-Reeves
    #   3                     - Polak-Ribiere
    #   4                     - Polak-Ribiere Plus

    # . Default attributes.
    defaultAttributes = { "betaType"                 : 1       ,
                          "initialStep"              : 1.0     ,
                          "lineSearcher"             : None    ,
                          "maximumTheta"             : 1.0e+10 ,
                          "minimumTheta"             : 1.0e-10 ,
                          "steepestDescentTolerance" : 1.0e-03 ,
                          "useSpectralTheta"         : True    }
    defaultAttributes.update ( MultiDimensionalMinimizer.defaultAttributes )

    # . Default attribute names.
    defaultAttributeNames = { "Beta Type"                  : "betaType"                 ,
                              "Initial Step"               : "initialStep"              ,
                              "Line Searcher"              : "lineSearcher"             ,
                              "Maximum Theta"              : "maximumTheta"             ,
                              "Minimum Theta"              : "minimumTheta"             ,
                              "Steepest Descent Tolerance" : "steepestDescentTolerance" ,
                              "Use Spectral Theta"         : "useSpectralTheta"         }
    defaultAttributeNames.update ( MultiDimensionalMinimizer.defaultAttributeNames )

    # . State class.
    stateObject = ConjugateGradientMinimizerState

    def Initialize ( self, state ):
        """Initialization before iteration."""
        super ( ConjugateGradientMinimizer, self ).Initialize ( state )
        state.f0 = state.f
        state.g.CopyTo ( state.g0 )
        state.x.CopyTo ( state.x0 )
        self.InitialSearchDirection ( state )
        parameters = _LineSearcherParameters
        parameters["initialStep"] = self.initialStep
        if self.lineSearcher is None: self.lineSearcher = MoreThuenteLineSearcher ( **parameters )

    def InitialSearchDirection ( self, state ):
        """Determine an initial search direction."""
        state.g.CopyTo ( state.d )
        state.d.Scale  ( -1.0 )
        state.d.Normalize ( )
        state.alpha = self.initialStep
        state.gDotG = state.g.Dot ( state.g )

    def Iteration ( self, state ):
        """Perform an iteration."""
        try:
            self.LineSearch         ( state )
            self.NewSearchDirection ( state )
        except Exception as error:
            state.error = error[0]
            import traceback, sys
            traceback.print_exc ( file = sys.stdout )
        state.numberOfIterations += 1

    def Label ( self ): return " Conjugate Gradient Minimizer"

    def LineSearch ( self, state ):
        """Do a line search."""
        # . Do the line search and return the best point.
        self.lineSearcher.initialStep = state.alpha
        state.lineSearchObjectiveFunction.SetValuesAtOrigin ( state.f0, state.d.Dot ( state.g0 ) )
        report = self.lineSearcher.Iterate ( state.lineSearchObjectiveFunction, log = None )
        # . Get the results.
        state.alpha                  = report["Variable"      ]
        state.f                      = report["Function Value"]
        state.numberOfFunctionCalls += report.get ( "Function Calls", 0 )
        state.rmsGradient            = state.g.RootMeanSquare ( )
        # . Determine the line search step type (success, partial, error).
        if report["Converged"]:
            statusFlag  = "s"
        elif state.f < state.f0:
            statusFlag  = "p"
        else:
            statusFlag  = "e"
            state.error = "Line search error: " + report["Status Message"]
        state.stepType = "L{:d}{:s}".format ( report.get ( "Iterations", 0 ), statusFlag )

    def NewSearchDirection ( self, state ):
        """Determine a new search direction."""
        # . Save data.
        state.f0 = state.f
        state.g.CopyTo ( state.y  ) ; state.y.AddScaledArray ( -1.0, state.g0 )
        state.x.CopyTo ( state.s  ) ; state.s.AddScaledArray ( -1.0, state.x0 )
        state.g.CopyTo ( state.g0 )
        state.x.CopyTo ( state.x0 )
        # . Dot factors.
        gDotG0      = state.gDotG
        state.gDotG = state.g.Dot ( state.g )
        gNorm2      = math.sqrt ( state.gDotG )
        sDotS       = state.s.Dot ( state.s )
        sDotY       = state.s.Dot ( state.y )
        # . Calculate the theta part of the direction.
        # . Theta is always one if the spectral method is not being used.
        theta0 = state.theta
        if self.useSpectralTheta:
            if sDotY <= 0.0: state.theta = self.maximumTheta
            else:            state.theta = min ( self.maximumTheta, max ( self.minimumTheta, sDotS / sDotY ) )
        state.g.CopyTo (  state.d     )
        state.d.Scale  ( -state.theta )
        # . Calculate the beta part of the direction.
        beta = 0.0
        # . Fletcher-Reeves.
        if self.betaType == 2:
            a = state.theta * state.gDotG
            b = state.alpha * theta0 * gDotG0
        # . Polak-Ribiere (normal and plus).
        elif ( self.betaType == 3 ) or ( self.betaType == 4 ):
            a = state.theta * state.g.Dot ( state.y )
            b = state.alpha * theta0 * gDotG0
            if self.betaType == 4: b = max ( b, 0.0 )
        # . Perry.
        # . y is used as workspace as it is no longer needed (although s is).
        else:
            state.y.Scale ( state.theta )
            state.y.AddScaledArray ( -1.0, state.s )
            a = state.y.Dot ( state.g )
            b = sDotY
        # . Do nothing if beta is undefined (i.e. use the steepest descent direction).
        if b != 0.0:
            beta = a / b
            state.d.AddScaledArray ( beta, state.s )
        # . Choose a steepest descent direction if the composite step is too uphill.
        dNorm2 = state.d.Norm2 ( )
        if state.g.Dot ( state.d ) > ( - self.steepestDescentTolerance * dNorm2 * gNorm2 ):
            state.g.CopyTo ( state.d )
            state.d.Scale  ( -1.0 )
        state.objectiveFunction.ApplyLinearConstraints ( state.d )
        state.d.Normalize ( )
        # . Alpha keeps its last value at the moment.
        # . Have an option to reset?

#===================================================================================================================================
# . Testing.
#===================================================================================================================================
if __name__ == "__main__" :
    pass


import math
# test pi
def distanceBetweenCoordinates(point_a, point_b):
    lat_a, lon_a = point_a
    lat_b, lon_b = point_b
    earthRadius = 6371                                       # earth Radius km

    distance_lat = math.radians(lat_b-lat_a)
    distance_lon = math.radians(lon_b-lon_a)
    a = math.sin(distance_lat/2) * math.sin(distance_lat/2) + math.cos(math.radians(lat_a)) * math.cos(math.radians(lat_b)) * math.sin(distance_lon/2) * math.sin(distance_lon/2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    d = earthRadius * c
    return d

def totalDistance(list_coordinates):
    list_lat = []
    list_lng = []

    for coordinate in list_coordinates:
        list_lat.append(coordinate[0])
        list_lng.append(coordinate[1])

    total_distance = 0
    for i in range(len(list_coordinates)-1):
        distance = distanceBetweenCoordinates((list_lat[i], list_lng[i]), (list_lat[i+1], list_lng[i+1]))
        total_distance += distance

    return round(total_distance, 2)