from django.urls import path
from news.views import *

urlpatterns = [
    path('register/', register, name='register'),
    path('logint/', user_login, name='user_login'),
    path('logout/', user_logout, name='user_logout'),
    path('', HomeNews.as_view(), name='home'),
    path('category/<int:category_id>/', NewsByCategory.as_view(), name='category'),
    path('news/<int:pk>/', ViewNews.as_view(), name='view_news'),
    path('news/add_news/', CreateNews.as_view(), name='add_news'),
    path('api/news/', NewsListView.as_view()),
    path('api/news/<int:pk>/', NewsSingleView.as_view()),
]


import speech_recognition as sr

# Create a recognizer instance
r = sr.Recognizer()

with sr.Microphone() as source:
    print("Press Enter to start recording...")
    input()  # Wait for Enter key to be pressed
    print("Recording audio... Speak now!")
    audio_data = r.listen(source, timeout=10)  # Listen for audio input

    try:
        print("Recognizing...")
        # Convert speech to text using Google Web Speech API
        text = r.recognize_google(audio_data)
        print("Transcribed Text:", text)
    except sr.UnknownValueError:
        print("Could not understand audio.")
    except sr.RequestError as e:
        print("Error requesting results from Google Web Speech API; {0}".format(e))


a=(int(input()))
b=[int(x) for  x in input().split()]
c,num=0,0
d=""
for i in b:
    if(i==1):
        if(c!=0):
            d=d+str(c)+" "
        c=1
        num+=1
    else:
        c+=1
d=d+str(c)
print(num)
print(d.rstrip())


import sys

sys.setrecursionlimit(10000)
input = sys.stdin.readline

n = int(input())

dp = [0] * (n+1)
dp[1] = 1
if n >= 2:
    dp[2] = 3
    for i in range(3, n+1):
        dp[i] = (dp[i-1] + 2 * dp[i-2]) % 10007

print(dp[n])


import geopandas as gpd
import pandas as pd

from ..services.file_service import get_path

# Default Path to the data folder
_DATA_FOLDER = get_path("data", "hmc")

def load_site_data(
    num_sites,
    norm_fac=1e9,
    data_folder=_DATA_FOLDER,
):
    # Read data file
    file_path = data_folder / f"hmc_{num_sites}SitesModel.csv"
    df = pd.read_csv(file_path)

    # Extract information
    z_2017 = df[f"z_2017_{num_sites}Sites"].to_numpy()
    zbar_2017 = df[f"zbar_2017_{num_sites}Sites"].to_numpy()
    theta = df[f"theta_{num_sites}Sites"].to_numpy()
    gamma = df[f"gamma_{num_sites}Sites"].to_numpy()
    forest_area_2017 = df[f"forestArea_2017_ha_{num_sites}Sites"].to_numpy()

    # Normalize Z data
    zbar_2017 /= norm_fac
    z_2017 /= norm_fac
    forest_area_2017 /= norm_fac

    # Read municipal level data
    municipal_theta_df = gpd.read_file(data_folder / "muni_data_theta.geojson")
    municipal_gamma_df = gpd.read_file(data_folder / "muni_data_gamma.geojson")

    # Read site level data
    site_theta_2017 = gpd.read_file(
        data_folder / f"site_{num_sites}_data_theta.geojson"
    )
    site_gamma_2017 = gpd.read_file(
        data_folder / f"site_{num_sites}_data_gamma.geojson"
    )

    # Remove geometries
    site_theta_2017_df = site_theta_2017.iloc[:, :-1]
    site_gamma_2017_df = site_gamma_2017.iloc[:, :-1]

    print(f"Data successfully loaded from {data_folder}")
    return (
        zbar_2017,
        gamma,
        z_2017,
        forest_area_2017,
        theta,
        site_theta_2017_df,
        site_gamma_2017_df,
        municipal_theta_df,
        municipal_gamma_df,
    )


from openfisca_core.model_api import *
from openfisca_core import periods

def str_to_instant(s):
    return periods.Instant(tuple(map(lambda s: int(s), s.split("-"))))

def backdate_parameters(
    root: str = None, first_instant: str = "2010-01-01"
) -> Reform:
    first_instant = str_to_instant(first_instant)

    def modifier(parameters):
        node = parameters
        if root is not None:
            for name in root.split("."):
                node = node[name]
        for param in node.get_descendants():
            if hasattr(param, "values_list"):
                earliest = param.values_list[-1]
                earliest_value = earliest.value
                earliest_instant = str_to_instant(earliest.instant_str)
                if first_instant < earliest_instant:
                    days = (earliest_instant.date - first_instant.date).days
                    param.update(
                        period=periods.Period(("day", first_instant, days)),
                        value=earliest_value,
                    )
        return parameters

    return modifier


import sys

# 全局变量
r,y,g = 0,0,0
staus = [1,3,2] # 红。绿。黄
setTime = {}

def signal(color, time, after):
    if color==0:
        return time
    color_index = staus.index(color)
    after %= (r+y+g)
    #计算到达时的状态
    while True:
        if after < time:
            time -= after
            break
        else:
            after -= time
            color_index = (color_index+1)%3 # 颜色状态转化
            color = staus[color_index]
            time = setTime[color]
    # 计算当前状态还需要等待的时间
    if color==1:
        return time
    if color==3:
        return 0
    if color == 2:
        return time+r

if __name__ == "__main__":
    inp = sys.stdin
    r,y,g = list(map(int,inp.readline().strip().split()))
    setTime = {1:r,3:g,2:y}
    n = int(inp.readline().strip())
    ret = 0
    for i in range(n):
        color, time = list(map(int,inp.readline().strip().split()))
        ret += signal(color,time,ret)
    print(ret)


from collections import defaultdict

def solution(n, paths, gates, summits):
    answer = [-1, float('inf')]
    graph = defaultdict(list)

    for i, j, w in paths:
        graph[i].append([j, w])
        graph[j].append([i, w])

    def dfs(current, intensity, visited):
        if visited[current] == 1:
            return
        elif visited[current] == -1:  # 입구
            return
        elif visited[current] == -2:  # 도착
            if answer[1] > intensity:
                answer[0] = current
                answer[1] = intensity
            elif answer[1] == intensity:
                answer[0] = min(current, answer[0])
        else:
            visited[current] = 1  # 방문
            for target, cost in graph[current]:
                if cost > answer[1]:
                    continue
                if cost > intensity:
                    dfs(target, cost, visited)
                else:
                    dfs(target, intensity, visited)

    visited = [0 for _ in range(n + 1)]
    for g in gates:
        visited[g] = -1
    for summit in summits:
        visited[summit] = -2
    for gate in gates:
        for path, w in graph[gate]:
            dfs(path, w, visited[:])
    return answer


read = input()
target = int(input())
nums = read.split(",")
nums = [int(nums[i]) for i in range(len(nums))]
location = -1;

for i in range(len(nums)):
    if(nums[i]==target):
        location = i
        break
if location == -1:
    nums.append(target)
    nums.sort()
    for i in range(len(nums)):
        if (nums[i] == target):
            location = i
            break
print(location)


import requests
from django.core.management.base import BaseCommand
from django.conf import settings
from nutella_fans.product.models import Category, Product, Brand, Store
from datetime import datetime
from dotenv import load_dotenv, find_dotenv

load_dotenv(find_dotenv())

class Command(BaseCommand):

    """
    standalone scripts to call the api and import data to database
    """

    def handle(self, *args, **options):
        """ BaseCommand requires the implementation of handle method
        Called all functions --> call and request of api
                             --> insert into data to database

        Args:
            *args: Description
            **options: Description
        """
        now = datetime.now()
        date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
        self.stdout.write(self.style.WARNING(
            "Début de la mise à jour des données %s ..." % date_time))

        category_list = self.get_category()
        for category_dict in category_list:
            products = self.get_products(category_dict)
            for product in products:
                p = self.create_product(product)
                if not p:
                    continue
                else:
                    category_names = product.get(
                        "categories").lower().split(",")
                    for category in category_names:
                        c, created = Category.objects.get_or_create(
                            name=category)
                        p.categories.add(c)
                    if product.get("stores"):
                        stores = product.get("stores").lower().split(",")
                        for store in stores:
                            s, created = Store.objects.get_or_create(
                                name=store)
                            p.stores.add(s)
        self.stdout.write(self.style.SUCCESS("Mise à jour réussie"))

        self.stdout.write(self.style.WARNING(
            "Fin de la mise à jour des données %s " % date_time))

    def get_category(self):
        """response of the request to extract data from API

        Returns:
            LIST: list of categories
        """
        self.stdout.write(self.style.WARNING(
            "Appel à l'api et récupération des 10 meilleurs catégories"))
        response = requests.get("https://fr.openfoodfacts.org/categories.json")
        result_category = response.json()
        data_category = result_category.get('tags')
        categories = [data.get('name') for data in data_category
                      if data.get("name")]
        category_name = categories[0:10]
        return category_name

    def get_products(self, category):
        """response of the request to extract data from API
            with queries parameters response : product list according to
            the best categories

        Parameters:
            category (STRING): one category

        Returns:
            LIST: list of products
        """
        self.stdout.write(self.style.WARNING(
            "Récupération des données openfoodfacts --> produits"))
        query = {
            "action": "process",
            "tagtype_0": "categories",
            "tag_contains_0": "contains",
            "tag_0": category,
            "sort_by": "unique_scans_n",
            "page_size": settings.MAX_IMPORT_PRODUCTS,
            "json": 1}
        response_product = requests.get(
            "https://fr.openfoodfacts.org/cgi/search.pl?", query)
        result_product = response_product.json()
        return result_product["products"]

    def create_product(self, product):
        """Creation of product on product_product table
            Get product_name or barcode from api for example and
            insert into on Model Product and others Model thanks to relationship

        Args:
            product (INT): one product

        Returns:
            Dict: one product information request to insert on database
        """
        if (product.get('product_name') and product.get('nutrition_grades')):
            name = product.get("product_name")
            nutriscore = product.get("nutrition_grades")
            nova = product.get("nova_group")
            url = product.get("url")
            description = product.get("ingredients_text")
            barcode = product.get("code")
            picture = product.get("image_front_url")
            fat_100g = product.get("nutriments", {}).get("fat_100g")
            fat_level = product.get("nutrient_levels", {}).get("fat")
            salt_100g = product.get("nutriments", {}).get("salt_100g")
            salt_level = product.get("nutrient_levels", {}).get("salt")
            saturated_fat_100g = product.get(
                "nutriments", {}).get("saturated-fat_100g")
            saturated_fat_level = product.get(
                "nutrient_levels", {}).get("saturated-fat")
            sugars_100g = product.get("nutriments", {}).get("sugars_100g")
            sugars_level = product.get("nutrient_levels", {}).get("sugars")
            brands = product.get("brands").lower().split(",")

            b, created = Brand.objects.get_or_create(
                name=brands[0])
            p, created = Product.objects.get_or_create(barcode=barcode, defaults={
                'name': name, 'nutriscore': nutriscore, 'nova': nova, 'url': url, 'description': description, 'picture': picture, 'fat_100g': fat_100g, 'fat_level': fat_level,
                'salt_100g': salt_100g, 'salt_level': salt_level, 'saturated_fat_100g': saturated_fat_100g,
                'saturated_fat_level': saturated_fat_level, 'sugars_100g': sugars_100g, 'sugars_level': sugars_level,
                'brand': b})

            return p


my_variable = "hello"

grades = [32, 45, 56, 78, 90, 93] # list

tuples_grades = (32, )  # tuples

set_grades = {45, 45, 89, 23, 59}  # unique and unordered

grades.append(34)

# print(sum(grades) / len(grades))

# print(set_grades)

# print(grades)

set_one = {1, 2, 3, 4, 5}
set_two = {3, 4, 5, 5.0, 6}

print(set_one.intersection(set_two))
print(set_one.union(set_two))
print(set_one.difference(set_two))


# #형변환
# stra = "Hello"
# inta = 5
# print(stra + str(inta))
# #int >> str 로 갈땐 str()
# #str >> int 로 갈땐 int()

# 출력
# # 콤마를 넣으면 자동으로 공백 삽입 그러나 +를 하면 공백삽입X
# # 콤마(,)는 모든 자료형의 값을 연결할 수 있는 반면, 덧셈(+)은 문자열들만을 연결
# print("출력값 숫자", 4)
# print("출력값 숫자 여러개", 4, 5, 6)
# su =5
# dan = 800
# print("su 주소 : " + str(id(su)))
# print("dan 주소 : " + str(id(dan)))
# print("금액 : " + str(su*dan))
# print("금액 :", su*dan)

# #입력
# num = input()
# print(num)
# num = input("숫자를 입력하세요")
# print(num)
# print(type(num))
# #파이썬에서는 항상 문자열로 입력을 받는다.
# fat = input("지방의 그램을 입력하세요 ")
# tan = input("탄수화물의 그램을 입력하세요 ")
# dan = input("단백질의 그램을 입력하세요 ")
# total = int(fat)*9 + int(dan)*4 + int(tan)*4
# print("총칼로리 :", total)

#연습문제 4.
word1 = input("첫번째 단어 : ")
word2 = input("두번째 단어 : ")
word3 = input("세번째 단어 : ")
print("===================")
abbr = word1[0] + word2[0] + word3[0]
print("약자 :", abbr)


from pprint import pprint

def get_data(fn):
    with open(fn) as open_file:
        temp_lines = open_file.readlines()
    input_lines = [int(line) for line in temp_lines]
    return input_lines

def part1(input_lines):
    count = 0
    local_max = input_lines[0]
    for i in input_lines[1:]:
        if i > local_max:
            count+=1
        local_max = i
    print(count)

def part2(data):
    count = 0
    i = 1
    list_list = [[data[0], data[1], data[2]], [data[1], data[2]], [data[2]]]
    running_max = sum(list_list[0])
    for d in data[3:]:
        i += 1
        for l in range(len(list_list)):
            if len(list_list[l]) == 3:
                local_max = sum(list_list[l])
                list_list[l] = []
                if local_max > running_max:
                    count += 1
                running_max = local_max
            list_list[l].append(d)
    for l in range(len(list_list)):
            if len(list_list[l]) == 3:
                local_max = sum(list_list[l])
                list_list[l] = []
                if local_max > running_max:
                    count += 1
    print(count)

def main():
    file_name = "input.txt"
    data = get_data(file_name)
    #part1(data)
    part2(data)

if __name__ == '__main__':
    main()


# Project Quex (http://quex.sourceforge.net); License: MIT;
# (C) 2005-2020 Frank-Rene Schaefer;
#_______________________________________________________________________________
from   quex.engine.analyzer.door_id_address_label  import DoorID, DialDB

from   quex.engine.misc.tools                      import typed
from   quex.blackboard import Lng, setup as Setup

from   operator import itemgetter

def do(StateRouterInfoList, dial_db):
    """Create code that allows to jump to a state based on an integer value.
    """
    # NOTE: Do not use 'IfDoorIdReferencedCode' because the state router may
    #       possibly not be tagged as 'gotoed', event if it is used.
    result = [
        "    __quex_assert_no_passage();\n",
        "    %s /* prevent unused label */\n" % Lng.GOTO(DoorID.global_state_router(dial_db), dial_db),
        "%s\n" % Lng.LABEL(DoorID.global_state_router(dial_db), dial_db)
    ]

    if not  Setup.computed_gotos_f and StateRouterInfoList:
        result.extend(__get_code(StateRouterInfoList))
    return result

def __get_code(StateRouterInfoList):
    # It is conceivable, that 'last_acceptance' is never set to a valid
    # terminal. Further, there might be solely the init state. In this
    # case the state router is void of states. But, the terminal router
    # requires it to be defined --> define a dummy state router.
    if len(StateRouterInfoList) == 0:
        return ["    QUEX_NAME(MF_error_code_set_if_first)(&self, E_Error_StateRouter_Empty);\n    return;\n"]

    variable = "target_state_index"
    case_code_list = sorted(StateRouterInfoList, key=itemgetter(0))
    default  = [
        "        default:\n"
        "            QUEX_NAME(MF_error_code_set_if_first)(&self, E_Error_StateRouter_UnkownStateIndex);\n"
        "            return;\n"
        "    }\n"
    ]
    txt = Lng.CASE_SELECT(variable, case_code_list, default)

    return txt

@typed(dial_db=DialDB)
def get_info(StateIndexList, dial_db):
    """
    NOTE: At least a 'dummy' state router is always equired so that 'goto
    QUEX_STATE_ROUTER;' does not reference a non-existing label. Then, we
    return an empty text array.

    <fschaef9/13y10m15d: "Still true with current dial_db implementation?">
    """
    if len(StateIndexList) == 0: return []

    # Make sure, that for every state the 'drop-out' state is also mentioned
    result = [None] * len(StateIndexList)
    for i, index in enumerate(StateIndexList):
        assert type(index) != str
        if index >= 0:
            # Transition to state entry
            adr = index
        else:
            assert False, "Is this still an issue?"
            # Transition to a templates 'drop-out'
            adr = DoorID.drop_out(- index, dial_db).related_address

        result[i] = (index, Lng.GOTO_ADDRESS(adr, dial_db))

    return result


import re

from state import State
from kik.messages.responses import TextResponse
from lib.message_types import MessageType

order = 1

class KeywordResponder(object):
    def __init__(self, fn, keyword, *alternates):
        global order
        self.fn = fn
        self.keyword = keyword

        # Create a regexp that has each of the tests for these words in a group with word boundaries. Drop all word-
        # boundary characters from the matchable list.
        words = [keyword] + list(alternates)
        escaped_words = (re.escape(w) for w in words)
        self.regexp = re.compile(unicode(r'(^|\s|\b)({})($|\s|\b)').format('|'.join(escaped_words)), flags=re.I)
        self.order = order
        order += 1

    def __call__(self, *args, **kwargs):
        return self.fn(*args, **kwargs)

    def match(self, body):
        if not body:
            return False
        return self.regexp.search(body)

def keyword_response(keyword, *alternates):
    def wrap(func):
        return KeywordResponder(func, keyword, *alternates)

    return wrap

class KeywordState(State):
    @staticmethod
    def type():
        raise NotImplementedError('KeywordState is an abstract class and should not be directly used')

    def __init__(self, *args, **kwargs):
        super(KeywordState, self).__init__(*args, **kwargs)
        self.keyword_responses = []
        self.hide_keyboard = False

        # Have to climb the inheritance hierarchy for the instance to make sure we get all keyword responses.
        inspect_class = self.__class__
        while not inspect_class == object:
            for x, y in inspect_class.__dict__.items():
                if isinstance(y, KeywordResponder):
                    self.keyword_responses.append(y)
            inspect_class = inspect_class.__bases__[0]

        self.keyword_responses.sort(key=lambda sr: sr.order)
        if len(self.keyword_responses) <= 20:
            self.suggested_responses = [TextResponse(body=kw.keyword)for kw in self.keyword_responses]
        else:
            self.suggested_responses = None

    def on_message(self, message):
        transition = None
        for sr in self.keyword_responses:
            if message.type == MessageType.TEXT and sr.match(message.body):
                transition = sr(self, message)
                break
        if not transition:
            transition = self.handle_unmatched(message)
        return transition

    def handle_unmatched(self, message):
        """
        Method that subclasses must implement in order to respond to messages that do not match the state's suggested
        responses list.
        :param message: The incoming message.
        :return: A Transition entity
        """
        raise NotImplementedError('KeywordState must return a Transition entity from its `handle_unmatched` method')


def minAvailableDuration(slots1, slots2, duration):  # doesn't work right
    slots1.sort()
    slots2.sort()
    i, j = 0, 0
    while i < len(slots1) and j < len(slots2):
        if slots1[i][0] > slots2[j][1]:
            j += 1
        elif slots2[j][0] > slots1[i][1]:
            i += 1
        elif slots1[i][0] <= slots2[j][1] and abs(max(slots1[i][0], slots2[j][0]) - min(slots1[i][0], slots2[j][1])) >= duration:
            return [max(slots1[i][0], slots2[j][0]), max(slots1[i][0], slots2[j][0]) + duration]
        elif slots2[j][0] <= slots1[i][1] and abs(max(slots1[i][0], slots2[j][0] - min(slots2[j][1], slots1[i][1]))) >= duration:
            return [max(slots1[i][0], slots2[j][0]), max(slots1[i][0], slots2[j][0]) + duration]
        elif slots2[j][0] <= slots1[i][1]:
            j += 1
        else:
            pass
    return []

def minAvailableDuration_alt(slots1, slots2, duration):
    if not slots1 or not slots2: return []
    slots1 = sorted(slots1, key = lambda x:x[0])
    slots2 = sorted(slots2, key = lambda x:x[0])
    i,j = 0, 0
    while (i<len(slots1) and j<len(slots2)):
        start1, end1 = slots1[i][0], slots1[i][1]
        start2, end2 = slots2[j][0], slots2[j][1]
        #print (' --> i, j, start1, start2 - ',i,j,start1, start2)
        if (start1 > end2):
            j += 1
        elif start2 > end1:
            i += 1
        elif start1 <= end2 and abs(max(start1, start2) - min(end1, end2)) >= duration:
            return [max(start1, start2) , max(start1, start2) +duration]
        elif start1 <= end2:
            i += 1
        elif start2 <= end1 and abs(max(start1, start2) - min(end1, end2)) >= duration:
            return [max(start1, start2) , max(start1, start2) + duration]
        elif start2 <= end1:
            j += 1
        else:
            pass
    return []

def minAvailableDuration_2_steps(slots1, slots2, duration):
    """
    Slightly different approach
    We can build a list candidates that contains intersections of slots1 and slots2
    Then we can go over candidates and check if there is an intersection that can fit our duration
    """
    if not slots1 or not slots2: return []
    slots1 = sorted(slots1, key = lambda x:x[0])
    slots2 = sorted(slots2, key = lambda x:x[0])
    candidates, res = [], []
    a, b = 0, 0
    while a < len(slots1) and b < len(slots2):
        st = max(slots1[a][0], slots2[b][0])
        end = min(slots1[a][1], slots2[b][1])
        if st <= end:
            candidates.append([st, end])
        if slots1[a][1] < slots2[b][1]:
            a += 1
        else:
            b += 1
    if len(candidates) == 0:
        return res
    for candidate in candidates:
        if candidate[1] - candidate[0] >= duration:
            res.append(candidate[0])
            res.append(candidate[0] + duration)
            break
    return res

if __name__ == '__main__':
    # print(minAvailableDuration([[10,50],[60,120],[140,210]], [[0,15],[60,70]], 8))
    # print(minAvailableDuration([[10,50],[60,120],[140,210]], [[0,15],[60,70]], 12))
    # print(minAvailableDuration_alt([[10,50],[60,120],[140,210]], [[0,15],[60,70]], 8))
    # print(minAvailableDuration_alt([[10,50],[60,120],[140,210]], [[0,15],[60,70]], 12))
    print(minAvailableDuration_2_steps([[10,50],[60,120],[140,210]], [[0,15],[60,70]], 8))
    print(minAvailableDuration_2_steps([[10,50],[60,120],[140,210]], [[0,15],[60,70]], 12))


# Sintaxis para definir una funcion
# def nombreDeLaFuncion(parametro1, parametros2):
#   codigo a ejecutar por la funcion.
#   return valor de retorno.

def calValorCuadrado(numero):
    numCuadrado = numero * numero
    return numCuadrado

# Para ingresar los valores, que le vamos a pasar a la funcion.
print("Hola amigos, inicio del programa")
miNumero = input("Introduzca un numero: ")
miNumero = int(miNumero)

# Resultado del numero ingresado y pasado a la funcion.
res = calValorCuadrado(miNumero)
print("Mi valor al cuadrado es: ", res) # Para ver el valor del resultado de la funcion.

# ------- funcion sin return -------
def imprimirPalomitas():
    print("PALOMITAS")

imprimirPalomitas()


def salary_parser(salary):
    temp = salary.split()
    coef = 1
    converter = {'руб.': 1, 'USD': 65, 'EUR': 72}
    for currency in converter.keys():
        if currency == temp[-1]:
            coef = converter[currency]
    try:
        print((int(temp[0]) + int(temp[1].split('-')[1]))*1000/2*coef)
        return (int(temp[0]) + int(temp[1].split('-')[1]))*1000/2*coef
    except:
        print(int(temp[1])*1000*coef)
        return int(temp[1])*1000*coef


# To test

# test
ko_list = ['K07290', 'K03129', 'K02799']
result = []
for ko in ko_list:
    try:
        result.extend(get_ko_hierachy(ko))
    except:
        print(ko, 'not found')
pd.DataFrame(result, columns=['ko', 'function_def','l3', 'l2', 'l1'])


# Advent of Code 2022

# Start Time: 1:30 AM
# Pt 1 End Time: 2:44 AM
    # Part 2 Start Time: 11:12 AM
# Pt 2 End Time: 11:26 AM
# Total Time: 1hr 25min

import re
import numpy as np # for nice 2d array manipulations in parsing
import copy

# parse input
with open('Day 5/Day5_Input.txt', 'rt', encoding='UTF-8') as f:
    lines = f.readlines()

    sep = lines.index('\n') # find where IC stops and instructions begin

    # parse out items in IC stacks  '[N] [C]    '
    num_stacks = len(lines[0])//4
    np_stacks = np.empty((sep-1, num_stacks), dtype=np.str_) # 2D array
    for i, line in enumerate(lines[:sep-1]):
        groups = re.findall(r'(?:\[(\w)\]|.{3})(?:.|\n)', line) # return all capture groups
        np_stacks[i,:] = groups

    # convert numpy to stacks vanilla lists
    IC_stacks = []
    for i in range(num_stacks):
        a = list(np.flip(np_stacks[:,i])) # vertical slice input space, and invert
        try:
            b = a[:a.index('')] # slice list before any empty entries
        except ValueError:
            b = a # no empty entry in lise
        IC_stacks.append(b)

    # parse instructions
    instructions = []
    for line in lines[sep+1:]:
        g = re.match(r'move (\w+) from (\w) to (\w)', line)
        instructions.append(tuple(map(int, g.groups())))

# Part 1 - Determine final configuration after running instruction
    # finally got done with parsing at 2:37 AM (1hr 07min)

stacks = copy.deepcopy(IC_stacks)
for num, orig, dest in instructions: # simulate instruction execution
    for _ in range(num): # do num moves
        stacks[dest-1].append( stacks[orig-1].pop() )

# get top box of each stack
sol1 = ""
for s in stacks:
    sol1 += s[-1]
print(f'The crates ontop of eaach stack after rearragement is {sol1}')  # actually simulating took only 7min after parsing

# Part 2 - Final configuration, but with moving multiple boxes at a time

stacks = copy.deepcopy(IC_stacks)
for num, orig, dest in instructions:
    stacks[dest-1].extend(stacks[orig-1][-num:])
    stacks[orig-1] = stacks[orig-1][:-num]

sol2 = ""
for s in stacks:
    sol2 += s[-1]
print(f'The crates ontop of each stack after multi-moving rearrangement is {sol2}')


import gym
import numpy as np
import matplotlib.pyplot as plt
import pickle
import math
import time
#create env
env = gym.make("CartPole-v1")
env.reset()

start_q_table = "qtable-cartpole-1607941327.pickle" # start of as nothing, or from filename

with open(start_q_table, "rb") as f:
    q_table = pickle.load(f)

EPISODES = 100
ALLOWED_STEPS = 1000
LEARNING_RATE = 0.1
DISCOUNT = 0.95

ep_rewards = []
aggr_ep_rewards = {'ep':[],'avg':[],'min':[],'max':[]}

time_tracked = []

buckets=(6, 6, 6, 6)
#convert the continuous value (float) into integers that fits in the discrete space...(chunking)
def get_discrete_state(state):
    upper_bounds = [env.observation_space.high[0], 0.5, env.observation_space.high[2], math.radians(50)]
    lower_bounds = [env.observation_space.low[0], -0.5, env.observation_space.low[2], -math.radians(50)]
    ratios = [(state[i] + abs(lower_bounds[i])) / (upper_bounds[i] - lower_bounds[i]) for i in range(len(state))]
    new_obs = [int(round((buckets[i] - 1) * ratios[i])) for i in range(len(state))]
    new_obs = [min(buckets[i] - 1, max(0, new_obs[i])) for i in range(len(state))]
    return tuple(new_obs)

#set the amount of episodes to train
for episode in range(EPISODES):
    start_time = time.time()
    discrete_state = get_discrete_state(env.reset()) #initialize the env state every new episode
    done = False
    duration = 0
    #for steps in range(ALLOWED_STEPS):
    while not done:
        action = np.argmax(q_table[discrete_state])

        new_state, reward, done, info = env.step(action)
        new_discrete_state = get_discrete_state(new_state)
        duration += reward
        #env.render()

        if not done:
            max_future_q = np.max(q_table[new_discrete_state])
            current_q = q_table[discrete_state + (action,)]
            new_q = current_q+LEARNING_RATE*(duration+DISCOUNT*max_future_q - current_q)
            q_table[discrete_state+(action,)] = new_q

        if not -math.radians(12) <= new_state[2] <= math.radians(12) or not -2.4 <= new_state[0] <= 2.4:
            break

        discrete_state = new_discrete_state

    # ep_rewards.append(duration)
    #
    # aggr_ep_rewards['ep'].append(episode)
    # aggr_ep_rewards['avg'].append(duration)
    end_time = time.time()

    time_tracked.append(end_time-start_time)
#print(q_table)
env.close()

plt.plot(time_tracked)
plt.show()

# plt.plot(aggr_ep_rewards['ep'], aggr_ep_rewards['avg'], label = "avg")
# plt.legend(loc = 4) #legend at lower right
# plt.show()


import base64
import datetime
import hashlib
import hmac
import logging
import time

import six

LOG = logging.getLogger(__name__)

def hash_it(data, hash_type="sha256"):
    """Returns hashed value of data."""
    if hash_type == "sha1":
        hash_obj = hashlib.sha1()
    elif hash_type == "md5":
        hash_obj = hashlib.md5()
    else:
        hash_obj = hashlib.sha256()
    try:
        hash_obj.update(data.encode())
        return hash_obj.hexdigest()
    except (TypeError, AttributeError) as e:
        LOG.error("Couldn't hash the data, exception raised: %s", e)
        return hash(data)

def hmac_it(data, key, hash_type="sha256"):
    """Returns HMAC based on the hash algorithm, data and key."""
    if hash_type == "md5":
        hash_obj = hashlib.md5
    elif hash_type == "sha1":
        hash_obj = hashlib.sha1
    else:
        hash_obj = hashlib.sha256
    try:
        h_digest = hmac.new(key.encode(), data.encode(), hash_obj)
        return h_digest.hexdigest()
    except (TypeError, AttributeError) as e:
        LOG.error("Couldn't hash the data, exception raised: %s", e)

def epoch_time(offset=0):
    """Returns time since epoch."""
    try:
        return time.time() - offset
    except TypeError as e:
        LOG.error("Couldn't reduce offset, %s, from epoch time, ex %s.",
                  offset, e)
        return time.time()

def utc_datetime():
    """Returns utc date time."""
    epoch = epoch_time()
    ts = datetime.datetime.fromtimestamp(epoch).strftime("%Y-%m-%d %H:%M:%S")
    return ts

def base64_encode(data):
    """Returns base 64 encoded value of data."""
    try:
        data = base64.b64encode(data.encode())
    except TypeError as e:
        LOG.error("Couldn't encode data to base64: %s", e)
    return data

def url_encode(url):
    """Returns encoded URL."""
    try:
        return six.moves.urllib.parse.quote_plus(url)
    except TypeError as e:
        LOG.error("Couldn't encode the URL: %s", e)
        return url


import math
import time

valid_resolutions = []
invalid_resolutions = []

# Helper functions for input
def get_integer_input(prompt, min_value=None, max_value=None, default_value=None):
    """
    Helper function to get integer input from the user.
    Args:
        prompt (str): The prompt message to display to the user.
        min_value (int, optional): The minimum allowed value. Defaults to None.
        max_value (int, optional): The maximum allowed value. Defaults to None.
        default_value (int, optional): The default value to return if no input is provided. Defaults to None.
    Returns:
        int: The integer value entered by the user.
    Raises:
        ValueError: If the input is not a valid integer.
    """
    while True:
        value_str = input(prompt)
        if not value_str and default_value is not None:
            return default_value
        try:
            value = int(value_str)
            if (min_value is not None and value < min_value) or (
                max_value is not None and value > max_value
            ):
                print(f"Please enter a value between {min_value} and {max_value}.")
                continue
            return value
        except ValueError:
            print("Please enter a valid integer.")

def get_aspect_ratio_input(prompt, default_value=""):
    """Helper function to get a valid aspect ratio input from the user."""
    while True:
        ratio = input(prompt)
        if not ratio:
            return default_value
        parts = ratio.split(":")
        if len(parts) != 2 or not parts[0].isdigit() or not parts[1].isdigit():
            print(
                "Please enter a valid aspect ratio format (e.g., 16:9) or leave blank."
            )
            continue
        return ratio

# Functions for working with resolutions

def populate_resolutions():
    global valid_resolutions, invalid_resolutions
    valid_resolutions_set = set()  # Set to store unique valid resolutions
    invalid_resolutions_set = set()  # Set to store unique invalid resolutions

    min_ratio, max_ratio = 0, float("inf")  # Default values for aspect ratio range
    if aspect_ratio_range:
        min_ratio, max_ratio = map(aspect_ratio_to_float, aspect_ratio_range.split("-"))  # Convert aspect ratio range to float values

    # Loop through all possible resolutions within the specified range
    for width in range(start_resolution, end_resolution + 1, increment):
        for height in range(width, end_resolution + 1, increment):  # Start from width to avoid duplicates
            aspect_ratio = get_aspect_ratio(width, height)  # Calculate aspect ratio for current resolution
            orientation = get_orientation(width, height)  # Determine orientation (landscape or portrait) for current resolution

            # Check if resolution is within the specified pixel limits
            if width * height <= max_pixel_limit and width * height >= min_pixel_limit:
                # Check if resolution meets the specified filters
                if (
                    (not filter_aspect_ratio or aspect_ratio == filter_aspect_ratio)  # Check if aspect ratio matches the filter or no filter is specified
                    and (not orientation_filter or orientation == orientation_filter)  # Check if orientation matches the filter or no filter is specified
                    and is_within_aspect_ratio_range(width, height, min_ratio, max_ratio)  # Check if aspect ratio is within the specified range
                ):
                    valid_resolutions_set.add((width, height))  # Add valid resolution to set
                    if width != height:
                        valid_resolutions_set.add((height, width))  # Add the same resolution with swapped width and height to handle both orientations
            else:
                invalid_resolutions_set.add((width, height))  # Add invalid resolution to set
                if width != height:
                    invalid_resolutions_set.add((height, width))  # Add the same resolution with swapped width and height to handle both orientations

    valid_resolutions = list(valid_resolutions_set)  # Convert set of valid resolutions to a list
    invalid_resolutions = list(invalid_resolutions_set)  # Convert set of invalid resolutions to a list

def is_within_aspect_ratio_range(width, height, min_ratio, max_ratio):
    """Check if the given width and height are within the specified aspect ratio range."""
    current_ratio = aspect_ratio_to_float(get_aspect_ratio(width, height))
    return min_ratio <= current_ratio <= max_ratio

def upscale_downscale_percentage_for_sort(base_resolution, target_resolution):
    """Calculate the upscale percentage from the base resolution to the target resolution.
    Args:
        base_resolution (tuple): The base resolution as a tuple of width and height.
        target_resolution (tuple): The target resolution as a tuple of width and height.
    Returns:
        float: The percentage by which the base resolution needs to be upscaled to reach the target resolution.
    """
    base_pixels = base_resolution[0] * base_resolution[1]
    target_pixels = target_resolution[0] * target_resolution[1]
    upscale_percent = ((target_pixels / base_pixels) * 100) - 100
    return upscale_percent

# Functions for resolution details and formatting

def get_aspect_ratio(width, height):
    """Helper function to calculate the aspect ratio."""
    gcd = math.gcd(width, height)
    return f"{width//gcd}:{height//gcd}"

def get_orientation(width, height):
    """Determines the orientation of a resolution based on its width and height."""
    if width > height:
        return "Horizontal"
    elif width < height:
        return "Vertical"
    else:
        return "Square"

def aspect_ratio_to_float(ratio):
    """Converts an aspect ratio string (e.g., '16:9') to a float (e.g., 1.7777)."""
    width, height = map(int, ratio.split(":"))
    return width / height

def format_float(value):
    """Formats a float to a string, removing unnecessary trailing zeros and decimal points."""
    str_value = "{:.4f}".format(value)
    return str_value.rstrip("0").rstrip(".") if "." in str_value else str_value

def format_pixel_count(value):
    """Formats a number with commas."""
    return "{:,}".format(value)

# Functions for sorting and displaying resolutions

def sort_resolutions(method, order):
    """Sort the valid and invalid resolutions based on the specified method and order.
    Args:
        method (str): The method to use for sorting. Can be "width", "height", "average", "pixels", "aspect_ratio", or "upscale".
        order (str): The order in which to sort. Can be "asc", "desc", or "closest".
    Returns:
        None
    """
    global valid_resolutions, invalid_resolutions
    base_res = (start_resolution, start_resolution)

    # Define a dictionary mapping each sorting method to its corresponding key function
    key_map = {
        "width": lambda x: x[0],  # Sort based on width
        "height": lambda x: x[1],  # Sort based on height
        "average": lambda x: (x[0] + x[1]) / 2,  # Sort based on average of width and height
        "pixels": lambda x: x[0] * x[1],  # Sort based on total number of pixels
        "aspect_ratio": lambda x: abs(aspect_ratio_to_float(get_aspect_ratio(x[0], x[1])) - 1) if order == "closest" else aspect_ratio_to_float(get_aspect_ratio(x[0], x[1])),  # Sort based on aspect ratio, either as absolute difference from 1 or as the actual aspect ratio
        "upscale": lambda x: upscale_downscale_percentage_for_sort(base_res, x),  # Sort based on percentage of upscale/downscale required to reach the base resolution
        "aspect_ratio_decimal": lambda x: aspect_ratio_to_float(get_aspect_ratio(x[0], x[1])),  # Sort based on aspect ratio decimal
    }

    start_time = time.time()  # Start measuring time
    count = 0  # Initialize count

    # Sort the valid resolutions based on the specified method and order
    valid_resolutions.sort(key=key_map[method], reverse=(order != "asc" and order != "closest"))

    end_time = time.time()  # Stop measuring time

    # Count the number of sorted resolutions
    for resolution in valid_resolutions:
        count += 1

    print(f"Sorted {count} resolutions in {end_time - start_time:.2f} seconds.")
    print("Calculations complete.")

    # Sort the invalid resolutions based on the specified method and order
    invalid_resolutions.sort(key=key_map[method], reverse=(order != "asc" and order != "closest"))

def upscale_downscale_percentage(base_resolution, target_resolution):
    """Calculate the upscale/downscale percentage from the base resolution to the target resolution.
    Args:
        base_resolution (tuple): The base resolution as a tuple of width and height.
        target_resolution (tuple): The target resolution as a tuple of width and height.
    Returns:
        tuple: A tuple containing the upscale percentage and downscale percentage.
    """
    base_pixels = base_resolution[0] * base_resolution[1]
    target_pixels = target_resolution[0] * target_resolution[1]
    end_pixels = end_resolution * end_resolution

    upscale_percent = ((target_pixels / base_pixels) * 100) - 100
    downscale_percent = 100 - ((target_pixels / end_pixels) * 100)

    return upscale_percent, downscale_percent

def get_resolution_details(resolution, base_res, end_res):
    """Get resolution details including aspect ratio, orientation, and percentages."""
    aspect_ratio_str = get_aspect_ratio(resolution[0], resolution[1])
    aspect_ratio_float = format_float(aspect_ratio_to_float(aspect_ratio_str))
    total_pixels = resolution[0] * resolution[1]
    formatted_pixels = format_pixel_count(total_pixels)
    megapixels = total_pixels / 1_000_000
    orientation = get_orientation(resolution[0], resolution[1])
    upscale_percent, downscale_percent = upscale_downscale_percentage(base_res, resolution)
    megapixels_display = f"{megapixels:.2f} MP" if megapixels > 0 else ""
    upscale_display = (
        f"{int(upscale_percent)}% upscale of {base_res[0]}x{base_res[1]}"
        if upscale_percent % 1 == 0
        else f"{upscale_percent:.3f}% upscale of {base_res[0]}x{base_res[1]}"
    ) if total_pixels > 1 and not (base_res == resolution or (upscale_percent == 0 and downscale_percent == 0)) else ""
    downscale_display = (
        f"{int(downscale_percent)}% downscale of {end_res[0]}x{end_res[1]}"
        if downscale_percent % 1 == 0
        else f"{downscale_percent:.3f}% downscale of {end_res[0]}x{end_res[1]}"
    ) if total_pixels > 1 and not (base_res == resolution or (upscale_percent == 0 and downscale_percent == 0)) else ""

    return aspect_ratio_str, aspect_ratio_float, formatted_pixels, megapixels_display, orientation, upscale_display, downscale_display

def write_resolution_to_file(file, resolution, base_res, end_res):
    """Write resolution details to a file."""
    aspect_ratio_str, aspect_ratio_float, formatted_pixels, megapixels_display, orientation, upscale_display, downscale_display = get_resolution_details(resolution, base_res, end_res)

    total_pixels = resolution[0] * resolution[1]  # Add this line to define total_pixels

    megapixels_part = f"| {megapixels_display}" if megapixels_display else ""
    upscale_part = f"| {upscale_display}" if upscale_display else ""
    downscale_part = f"| {downscale_display}" if downscale_display else ""

    file.write(
        f"Resolution: {resolution[0]}x{resolution[1]} | Aspect Ratio: {aspect_ratio_str} | {orientation} | Aspect Ratio Decimal: {aspect_ratio_float} | {formatted_pixels} Pixel{'s' if total_pixels != 1 else ''} {megapixels_part} {upscale_part} {downscale_part}\n"
    )

def ask_to_save_invalid_resolutions():
    while True:
        save_invalid = input("Do you want to save invalid resolutions? (yes/no): ").strip().lower()
        if save_invalid in ("yes", "no"):
            return save_invalid == "yes"
        print("Please enter 'yes' or 'no'.")

# Functions for menu and user interactions

def display_and_save_results():
    # Set the base and end resolutions
    base_res = (start_resolution, start_resolution)
    end_res = (end_resolution, end_resolution)

    start_time = time.time()  # Start measuring time

    # Open the file in write mode
    with open("resolutions.txt", "w") as file:
        # Write the constraints used section
        file.write("Constraints Used:\n")
        file.write(f"Starting Resolution: {format_pixel_count(start_resolution)}\n")
        file.write(f"Ending Resolution: {format_pixel_count(end_resolution)}\n")
        file.write(f"Increment/Multiple: {format_pixel_count(increment)}\n")
        file.write(f"Maximum Pixel Limit: {format_pixel_count(max_pixel_limit)}\n")
        if filter_aspect_ratio:
            file.write(f"Aspect Ratio Filter: {filter_aspect_ratio}\n")
        file.write("\n")

        # Write the valid resolutions section
        file.write("Valid Resolutions:\n")
        for resolution in valid_resolutions:
            write_resolution_to_file(file, resolution, base_res, end_res)

        # Conditionally write the invalid resolutions section
        if save_invalid_resolutions:
            file.write("\nInvalid Resolutions (Exceeding Maximum Pixel Limit):\n")
            for resolution in invalid_resolutions:
                write_resolution_to_file(file, resolution, base_res, end_res)

        end_time = time.time()  # Stop measuring time

    print(f"Saved results to 'resolutions.txt' in {end_time - start_time:.2f} seconds.")

def menu(title, options, actions):
    while True:
        # Print the menu title
        print(f"\n{title}")

        # Print the menu options
        for i, option in enumerate(options, 1):
            print(f"{i}. {option}")

        # Get the user's choice
        choice = get_integer_input("Enter your choice: ", 1, len(options))

        # Check if the choice is a valid action
        if choice in actions:
            # Execute the chosen action
            actions[choice]()
        else:
            # Exit the menu loop if the choice is not a valid action
            break

def main_menu():
    # List of menu options
    menu_options = [
        "Sort by width",
        "Sort by height",
        "Sort by average of width and height",
        "Sort by total number of pixels",
        "Sort by aspect ratio",
        "Sort by aspect ratio decimal",
        "Sort by upscale percentage",
        "Choose new parameters",
        "Exit program",
    ]

    # Dictionary of menu actions corresponding to each option
    menu_actions = {
        1: lambda: sort_menu("width"),
        2: lambda: sort_menu("height"),
        3: lambda: sort_menu("average"),
        4: lambda: sort_menu("pixels"),
        5: lambda: sort_menu("aspect_ratio"),
        6: lambda: sort_menu("aspect_ratio_decimal"),
        7: lambda: sort_menu("upscale"),
        8: get_user_input,
        9: exit,
    }

    # Display the menu and execute the selected action
    menu("Choose a sorting method:", menu_options, menu_actions)

def sort_menu(method):
    # List of menu options
    menu_options = ["Ascending", "Descending", "Back to main menu"]

    # Insert additional option for "aspect_ratio" method
    if method == "aspect_ratio":
        menu_options.insert(1, "Closest to 1:1 first")
    elif method == "aspect_ratio_decimal":  # Add option for aspect ratio decimal sorting
        menu_options.insert(1, "Closest to 1:1 first (Decimal)")

    # Dictionary of menu actions corresponding to each option
    if method == "aspect_ratio":
        menu_actions = {
            1: lambda: (sort_resolutions(method, "asc"), display_and_save_results(), print_saved_message()),
            2: lambda: (sort_resolutions(method, "closest"), display_and_save_results(), print_saved_message()),
            3: lambda: (sort_resolutions(method, "desc"), display_and_save_results(), print_saved_message()),
            4: main_menu
        }
    elif method == "aspect_ratio_decimal":  # Add actions for aspect ratio decimal sorting
        menu_actions = {
            1: lambda: (sort_resolutions(method, "asc"), display_and_save_results(), print_saved_message()),
            2: lambda: (sort_resolutions(method, "closest"), display_and_save_results(), print_saved_message()),
            3: lambda: (sort_resolutions(method, "desc"), display_and_save_results(), print_saved_message()),
            4: main_menu
        }
    else:
        menu_actions = {
            1: lambda: (sort_resolutions(method, "asc"), display_and_save_results(), print_saved_message()),
            2: lambda: (sort_resolutions(method, "desc"), display_and_save_results(), print_saved_message()),
            3: main_menu
        }

    # Display the menu and execute the selected action
    menu(f"Sort by {method}:", menu_options, menu_actions)

def print_saved_message():
    # Print a message indicating that the results have been saved
    print("Results have been saved to resolutions.txt!")

def collect_resolution_parameters():
    """Collect resolution-related parameters from the user."""
    global start_resolution, end_resolution, increment, max_pixel_limit, min_pixel_limit
    start_resolution = get_integer_input(
        "Enter the starting resolution (e.g., 512): ", default_value=512
    )
    end_resolution = get_integer_input(
        "Enter the ending resolution (e.g., 2048): ",
        min_value=start_resolution,
        default_value=2048,
    )
    increment = get_integer_input(
        "Enter the increment/multiple (e.g., 64): ", default_value=64
    )
    max_pixel_limit = get_integer_input(
        "Enter the Maximum Pixel Limit (e.g., 1048576): ", default_value=1048576
    )
    min_pixel_limit = get_integer_input(
        "Enter the Minimum Pixel Limit (e.g., 262144): ", default_value=262144
    )

def collect_aspect_ratio_filter():
    """Collect aspect ratio filter from the user."""
    global filter_aspect_ratio
    filter_aspect_ratio = get_aspect_ratio_input(
        "Enter a specific aspect ratio to filter by (e.g., 16:9) or leave blank: ",
        default_value="",
    )

def collect_orientation_filter():
    """Collect orientation filter from the user."""
    global orientation_filter
    orientation_filter = input(
        "Filter by orientation (Horizontal, Vertical, Square) or leave blank: "
    ).capitalize()

def collect_aspect_ratio_range():
    """Collect custom aspect ratio range from the user."""
    global aspect_ratio_range
    while True:
        aspect_ratio_range = input(
            "Enter a custom aspect ratio range (e.g., 4:3-16:9) or leave blank: "
        )
        if not aspect_ratio_range or is_valid_aspect_ratio_range(aspect_ratio_range):
            break
        print("Invalid aspect ratio range format. Please use the format '4:3-16:9'.")

def get_user_input():
    global save_invalid_resolutions
    collect_resolution_parameters()
    collect_aspect_ratio_filter()
    collect_orientation_filter()
    collect_aspect_ratio_range()

    # Prompt the user to save invalid resolutions or not
    save_invalid_resolutions = ask_to_save_invalid_resolutions()

    # Populate the resolutions list based on user input
    populate_resolutions()

if __name__ == "__main__":
    # Get user input and display the main menu
    get_user_input()
    main_menu()


from matplotlib import pyplot as plt
import matplotlib
import numpy as np
import warnings
import sys

from _common import *

def create_icmap_example_plot(seed=73323):
    import rescomp as rc

    # fix the seed for consistency
    np.random.seed(seed)
    # ignore a FutureWarning in rescomp
    warnings.filterwarnings('ignore', category=FutureWarning, module='networkx')

    # Generate a system trajectory from the Lorenz attractor
    t, U = rc.orbit('lorenz', trim=True, duration=30)
    num_pts=300
    tr_t = t[1000:1000+num_pts]
    tr_signal = U[1000:1000+num_pts]

    # Create a reservoir computer
    res_sz = 50
    rescomp = rc.ResComp(res_sz=res_sz, mean_degree=0.1, map_initial='activ_f')
    r0 = rescomp.initial_condition(tr_signal[0])
    res_signal = rescomp.internal_state_response(tr_t, tr_signal, r0)

    try:
        # figure time
        fig = plt.figure(figsize=(12,6))
        ax_sys = fig.add_subplot(1,2,1,projection='3d')
        ax_res = fig.add_subplot(1,2,2)

        # This one is for arrows, &c
        ax_overlay = fig.add_subplot(1,1,1)
        ax_overlay.axis([0,1,0,1])
        ax_overlay.axis('off')

        # Plot the trajectory
        train_split = num_pts - 10
        ax_sys.plot(U[:,0], U[:,1], U[:,2], '-', alpha=0.7, color=(0.0, 0.3, 0.8))
        train_color = (0.3, 0.3, 0.1)
        ax_sys.plot(tr_signal[:train_split,0], tr_signal[:train_split,1], tr_signal[:train_split,2], '-', color=train_color)
        ax_sys.plot(tr_signal[train_split:,0], tr_signal[train_split:,1], tr_signal[train_split:,2], '--', color=train_color)
        ax_sys.plot(tr_signal[0,0], tr_signal[0,1], tr_signal[0,2], 'k*', markersize=12.)

        clear_3d_axis_labels(ax_sys)
        #ax_sys.axis('off')

        # Plot reservoir states
        order = np.argsort(res_signal[0])
        for i,c in enumerate(plt.get_cmap('plasma')(np.linspace(0,0.8,res_sz))):
            ax_res.plot(tr_t, res_signal[:, order[i]], '-', color=c, alpha=0.8)
        ax_res.plot([tr_t[0]]*res_sz, res_signal[0], 'k.')

        ax_res.spines['top'].set_visible(False)
        ax_res.spines['right'].set_visible(False)
        ax_res.spines['bottom'].set_position('zero')
        ax_res.set_xticks([])
        ax_res.set_yticks([-1,0,1])

        # Label for initial conditions
        textparams = {
            'fontsize': 16,
            'horizontalalignment': 'center',
        }
        ax_sys.text(tr_signal[0,0], tr_signal[0,1], tr_signal[0,2]+5, r"$\mathbf{u}_0$", **textparams)
        ax_res.text(tr_t[0], 1.0, r"$\mathbf{r}_0$", **textparams)

        bounding_box = ax_res.get_position()
        height = 0.5
        bounding_box.y0 = 0.5 - height/2
        bounding_box.y1 = 0.5 + height/2
        ax_res.set_position(bounding_box)

        # temporary; show bounds of the overlay subplot
        #ax_overlay.plot([0,0,1,1,0],[0,1,1,0,0], 'k:')
        #ax_overlay.plot([0,1],[1,0], 'k:')
        #ax_overlay.plot([0,1],[0,1], 'k:')

        # Arrow showing mappings
        path_t = np.linspace(-1,1,3)
        path_x = 0.5 + path_t * 0.15
        path_y = 0.15*(1-path_t**2)
        codes = [
            matplotlib.path.Path.MOVETO
        ] + [
            matplotlib.path.Path.CURVE3
        ] * (len(path_t) - 1)

        path1 = matplotlib.path.Path(np.column_stack((path_x, 0.85+path_y)), codes=codes)
        path2 = matplotlib.path.Path(np.column_stack((path_x, 0.18-path_y)), codes=codes)

        ax_overlay.add_patch(matplotlib.patches.FancyArrowPatch(path=path1, arrowstyle="->", mutation_scale=20.))
        ax_overlay.add_patch(matplotlib.patches.FancyArrowPatch(path=path2, arrowstyle="<-", mutation_scale=20.))
        textparams = {
            'fontsize': 18,
            'horizontalalignment': 'center',
            'transform': ax_overlay.transAxes,
        }
        ax_overlay.text(0.5, 0.95, r'$\Phi$', **textparams)
        ax_overlay.text(0.5, 0.05, r'$W_{\mathrm{out}}\approx \Phi^{-1}$', **textparams)

        plt.show()
    except Exception as e:
        # cleanup
        plt.close('all')
        raise


import unittest
import io
from gdl import Lexer, NoInputError

class MockFile(io.StringIO):
    name = '__mock__'

class TestLexer(unittest.TestCase):
    def test_lex_tokens(self):
        answer = ['(', '<=', '(', 'ancestor', '?a', '?c', ')', '(', 'parent', '?a', '?b', ')', '(', 'ancestor', '?b', '?c', ')', ')']
        string = '(<= (ancestor ?a ?c) (parent ?a ?b) (ancestor ?b ?c))'
        tokens = list(t.value for t in Lexer().lex(string))
        self.assertEqual(tokens, answer)

    def test_lex_superflouos_whitespace(self):
        answer = ['(', '<=', '(', 'ancestor', '?a', '?c', ')', '(', 'parent', '?a', '?b', ')', '(', 'ancestor', '?b', '?c', ')', ')']
        string = '''
        (  <=  (ancestor   ?a  ?c    )                 (
                parent   ?a  ?b
        ) (
                ancestor ?b                ?c  )   )
        '''
        tokens = list(t.value for t in Lexer().lex(string))
        self.assertEqual(tokens, answer)

    def test_lex_columns(self):
        answer = [1, 2, 5, 6, 15, 18, 20, 22, 23, 30, 33, 35, 37, 38, 47, 50, 52, 53]
        string = '(<= (ancestor ?a ?c) (parent ?a ?b) (ancestor ?b ?c))'
        columns = list(t.column for t in Lexer().lex(string))
        self.assertEqual(columns, answer)

    def test_lex_linenos(self):
        answer = [1] * 7 + [2] * 5 + [3] * 6
        string = '''(<= (ancestor ?a ?c)
                        (parent ?a ?b)
                        (ancestor ?b ?c))
                 '''
        linenos = list(t.lineno for t in Lexer().lex(string))
        self.assertEqual(linenos, answer)

    def test_lex_lines(self):
        answer = ['(<= (ancestor ?a ?c)\n'] * 7 + \
                 ['                        (parent ?a ?b)\n'] * 5 + \
                 ['                        (ancestor ?b ?c))\n'] * 6
        string = '''(<= (ancestor ?a ?c)
                        (parent ?a ?b)
                        (ancestor ?b ?c))
                 '''
        lines = list(t.line for t in Lexer().lex(string))
        self.assertEqual(lines, answer)

    def test_lex_file(self):
        answer = [('(', 1, 1),
                  ('<=', 1, 2),
                  ('(', 1, 5),
                  ('ancestor', 1, 6),
                  ('?a', 1, 15),
                  ('?c', 1, 18),
                  (')', 1, 20),
                  ('(', 2, 30),
                  ('parent', 2, 31),
                  ('?a', 2, 38),
                  ('?b', 2, 41),
                  (')', 2, 43),
                  ('(', 3, 30),
                  ('ancestor', 3, 31),
                  ('?b', 3, 40),
                  ('?c', 3, 43),
                  (')', 3, 45),
                  (')', 3, 46)]
        fp = MockFile('''(<= (ancestor ?a ?c)
                             (parent ?a ?b)
                             (ancestor ?b ?c))
                 ''')
        tokens = list((t.value, t.lineno, t.column) for t in Lexer().lex(file=fp))
        self.assertEqual(tokens, answer)

    def test_lex_no_input_error(self):
        with self.assertRaises(NoInputError):
            Lexer().lex()

    def test_lex_case_insensitive(self):
        answer = ['(', '<=', '(', 'ancestor', '?a', '?c', ')', '(', 'parent', '?a', '?b', ')', '(', 'ancestor', '?b', '?c', ')', ')']
        string = '(<= (ANCESTOR ?A ?C) (PARENT ?A ?B) (ANCESTOR ?B ?C))'
        tokens = list(t.value for t in Lexer().lex(string))
        self.assertEqual(tokens, answer)

    def test_lex_comments(self):
        answer = ['(', '<=', '(', 'ancestor', '?a', '?c', ')', '(', 'parent', '?a', '?b', ')', '(', 'ancestor', '?b', '?c', ')', ')']
        string = '''(<= (ancestor ?a ?c)
                        ;;; doc string goes here ;;;
                        (parent ?a ?b)
                        (ancestor ?b ?c)) ;NOTE: this is recursive'''
        tokens = list(t.value for t in Lexer().lex(string))
        self.assertEqual(tokens, answer)


import matplotlib.pyplot as plt
import pandas as pd
import spacy
import streamlit as st
import string

from joblib import dump, load
from spacy.lang.pt.stop_words import STOP_WORDS

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.naive_bayes import MultinomialNB

from tweepy import API
from tweepy import Cursor
from tweepy import OAuthHandler

# File storing the user credentials to access the Twitter API.
import my_twitter_credentials

VOCABULARY_FILENAME = 'better_learned_vocabulary.joblib'
MODEL_FILENAME = 'better_fitted_multinomial_nb.joblib'

###############################################################################
# Code related to Tweepy.
###############################################################################
class TwitterAuthenticator():
    """
    Class for authenticating our requests to Twitter.
    """
    def authenticate_app(self):
        # The keys are unique identifiers that authenticate the app.
        auth = OAuthHandler(my_twitter_credentials.CONSUMER_KEY,
                            my_twitter_credentials.CONSUMER_KEY_SECRET)
        # The tokens allow the app to gain specific access to Twitter data.
        auth.set_access_token(my_twitter_credentials.ACCESS_TOKEN,
                              my_twitter_credentials.ACCESS_TOKEN_SECRET)
        return auth

class TwitterClient():
    """
    Class for browsing through tweets via the Twitter API.
    """
    def __init__(self):
        self.auth = TwitterAuthenticator().authenticate_app()
        self.api = API(self.auth)

    def search_tweet(self, query_string):
        cursor = Cursor(self.api.search, q=query_string, lang='pt', count=5)
        return cursor.items(5)
###############################################################################

###############################################################################
# Code related to spaCy.
###############################################################################
nlp = spacy.load('pt_core_news_sm')
STOP_WORDS_LIST = list(STOP_WORDS)
PUNCTUATION_CHARACTERS_LIST = list(string.punctuation)

# Tokenizer used by the CountVectorizer.
def spacy_tokenizer(tweet):
    # Tokenizes tweet and lemmatizes the tokens.
    # It also gets rid of stop words and punctuation characters.
    doc = nlp(tweet)
    tokens = [token.lemma_ for token in doc]
    tokens = [token for token in tokens
              if token not in STOP_WORDS_LIST
              and token not in PUNCTUATION_CHARACTERS_LIST]
    return tokens
###############################################################################

###############################################################################
# Execution code.
###############################################################################
def get_training_data():
    df = pd.read_csv('50k.csv', sep=';')
    X = df['tweet_text']
    y = df['sentiment']
    return df, train_test_split(X, y, test_size=0.01, random_state=17)

def execute_pipeline(X_train, X_test, y_train, y_test):
    loaded = False
    try:
        vectorizer = load(VOCABULARY_FILENAME)
        classifier = load(MODEL_FILENAME)
        pipeline = Pipeline([('vectorizer', vectorizer),
                             ('classifier', classifier)], verbose=True)
        loaded = True
    except OSError:
        # The parameter to the tokenizer is a callable.
        vectorizer = CountVectorizer(tokenizer=spacy_tokenizer)
        classifier = MultinomialNB()
        # Pipeline for cleaning, vectorizing and classifying tweets.
        pipeline = Pipeline([('vectorizer', vectorizer),
                             ('classifier', classifier)], verbose=True)
        status = st.text('[STATUS] Fitting model...')
        pipeline.fit(X_train, y_train)
        status.text('[STATUS] Model was fit.')
        dump(vectorizer, VOCABULARY_FILENAME)
        dump(classifier, MODEL_FILENAME)
    return loaded, pipeline

def plot_chart(input_df):
    input_df['tweet_date'] = pd.to_datetime(input_df['tweet_date'])
    input_df.sort_values(by=['tweet_date'], inplace=True)

    positive_df = input_df[input_df['sentiment'] == 1]
    positive_df['month'] = positive_df['tweet_date'].map(lambda d: d.month)
    positive_df['day'] = positive_df['tweet_date'].map(lambda d: d.day)
    agg_positive_df = positive_df.groupby(['month', 'day']).count()
    positive_counts = agg_positive_df['id'].tolist()

    negative_df = input_df[input_df['sentiment'] == 0]
    negative_df['month'] = negative_df['tweet_date'].map(lambda d: d.month)
    negative_df['day'] = negative_df['tweet_date'].map(lambda d: d.day)
    agg_negative_df = negative_df.groupby(['month', 'day']).count()
    negative_counts = agg_negative_df['id'].tolist()

    x_labels = pd.date_range(start='09/28/2018', end='10/12/2018')
    x_labels = [str(d).split()[0] for d in x_labels.to_series().tolist()]

    positive_dates = [
        '2018-09-28', '2018-09-30', '2018-10-01',
        '2018-10-02', '2018-10-03', '2018-10-05',
        '2018-10-06', '2018-10-08', '2018-10-12'
    ]
    negative_dates = [
        '2018-10-01', '2018-10-02', '2018-10-08'
    ]

    positive_y_values = [0] * len(x_labels)
    negative_y_values = [0] * len(x_labels)
    for i in range(len(x_labels)):
        if x_labels[i] in positive_dates:
            positive_y_values[i] = positive_counts.pop(0)
        if x_labels[i] in negative_dates:
            negative_y_values[i] = negative_counts.pop(0)

    plt_fig, ax = plt.subplots()
    ax.plot(range(len(x_labels)), positive_y_values,
            label='Positive', color='#4287f5')
    ax.plot(range(len(x_labels)), negative_y_values,
            label='Negative', color='#f54242')
    ax.set_title('Tweet sentiment evolution of training set')
    ax.set_xlabel('Day')
    ax.set_xticks(range(len(x_labels)))
    ax.set_xticklabels(x_labels, rotation='vertical')
    ax.set_ylabel('Number of tweets')
    ax.legend()
    st.pyplot(fig=plt_fig)

if __name__ == '__main__':
    st.title('Twitter App')
    client = TwitterClient()

    df, (X_train, X_test, Y_train, Y_test) = get_training_data()
    loaded, pipeline = execute_pipeline(X_train, X_test, Y_train, Y_test)
    if loaded:
        st.write('Vocabulary and model successfully loaded.')
    st.text(f'Model accuracy on test data: {pipeline.score(X_test, Y_test)}')

    theme_options = ('Weather', 'Politics')
    theme = st.radio("Pick your theme to search for a tweet.", theme_options)
    if theme == 'Weather':
        keywords = 'calor OR quente OR aquecimento OR queimadas'
    else:
        keywords = 'bolsonaro OR mito OR lula OR pt OR trump'

    # Shows tweets with predictions.
    count = 0
    tweets = client.search_tweet(keywords)
    for tweet in tweets:
        area_key = 'a' + str(count)
        st.text_area('Fetched tweet', value=tweet.text, key=area_key)
        count += 1

        prediction = pipeline.predict([tweet.text])
        if prediction[0] == 0:
            st.info('Prediction: negative')
        else:
            st.info('Prediction: positive')

    # Shows plot.
    plot_chart(df)
###############################################################################


# load a Tkinter listbox with data lines from a file,
# sort data lines, select a data line, display the data line,
# edit the data line, update listbox with the edited data line
# add/delete a data line, save the updated listbox to a data file
# used a more modern import to give Tkinter items a namespace
# tested with Python24       vegaseat       16nov2006
import Tkinter as tk
import ttk
import tkMessageBox
import io
root = tk.Tk()

# create the listbox (note that size is in characters)
listbox1 = tk.Listbox(root, width=50, height=20)
listbox1.grid(row=0, column=0)
listbox2 = tk.Listbox(root, width=50, height=20)
listbox2.grid(row=0, column=2)

def add_item():
    """
    add the text in the Entry widget to the end of the listbox
    """
    listbox1.insert(tk.END, enter1.get())
def delete_item():
    """
    delete a selected line from the listbox
    """
    try:
        # get selected line index
        index = listbox1.curselection()[0]
        listbox1.delete(index)
    except IndexError:
        pass

def get_list(event):
    """
    function to read the listbox selection
    and put the result in an entry widget
    """
    # get selected line index
    index = listbox1.curselection()[0]
    # get the line's text
    seltext = listbox1.get(index)
    # delete previous text in enter1
    enter1.delete(0, 50)
    # now display the selected text
    enter1.insert(0, seltext)
def set_list(event):
    """
    insert an edited line from the entry widget
    back into the listbox
    """
    try:
        index = listbox1.curselection()[0]
        # delete old listbox line
        listbox1.delete(index)
    except IndexError:
        index = ttk.END
    # insert edited item back into listbox1 at index
    listbox1.insert(index, enter1.get())
def sort_list():
    """
    function to sort listbox items case insensitive
    """
    temp_list = list(listbox2.get(0, tk.END))
    temp_list.sort(key=str.lower)
    # delete contents of present listbox
    listbox2.delete(0, tk.END)
    # load listbox with sorted data
    for item in temp_list:
        listbox2.insert(ttk.END, item)
def save_list():
    """
    save the current listbox contents to a file
    """
    # get a list of listbox lines
    temp_list = list(listbox1.get(0, tk.END))
    # add a trailing newline char to each line
    temp_list = [lista + '\n' for lista in temp_list]
    # give the file a different name
    fout = open("lista.txt", "w")
    fout.writelines(temp_list)
    fout.close()

# def listbox2
def moveDown():

    move_text = listbox1.selection_get()
    curindex = int(listbox1.curselection()[0])

    listbox2.insert(tk.END, move_text)

def save_list2():
    """
    save the current listbox contents to a file
    """
    # get a list of listbox lines
    temp_list2 = list(listbox2.get(0, tk.END))
    # add a trailing newline char to each line
    temp_list2 = [comprar + '\n' for comprar in temp_list2]
    # give the file a different name
    fout2 = open("comprar.txt","w")
    fout2.writelines(temp_list2)
    fout2.close()

def delete_item2():
    """
    delete a selected line from the listbox
    """
    try:
        # get selected line index
        index2 = listbox2.curselection()[0]
        listbox2.delete(index2)
    except IndexError:
        pass

def combine2():

    delete_item2()
    save_list2()

def mail():
    execfile("mail2.py")
    tkMessageBox.showinfo(":)", "Correo enviado")

var = tk.StringVar(root) # initial value
choices = ['1','2','3','4','5','6','7','8','9']
option = tk.OptionMenu(root, var, *choices)
var.set('1')
option.grid(row = 1, column =1)

def moveDown_and_select():

    move_text = listbox1.selection_get()
    curindex = int(listbox1.curselection()[0])
    sf = "value is %s" % var.get()

    var4 = '%s %s' % (move_text, var.get())

    listbox2.insert(tk.END, var4)

def combine():
    moveDown_and_select()
    save_list2()

# create the sample data file
str1 = """
Aceite de oliva 0,4-Ybarra-5L-Lata
Caja-Aceite girasol-Happyday-1L-Cajar
Aceite refinado girasol-Diplo-25L-Garrafa
Aceite de oliva extra virgen-Vivo-5L-Botella
Aceituna manzanilla s/hueso-Escamilla-1,900g-Bote
Alcaparras-Luxeappers-1kg-Bote
Arroz grano largo-Rocio-1kg-Caja
Azucar-Amogoldi-1kg-Paquete
Atun lata mediana-Lata
Bacon ahumado-Granjaflor-2,40kg
Caldo de pescado-Knorr-1kg-Bote
Caldo de pollo Knorr-1kg-Bote
Canela en rama-La Barraca-250g-Bote
Canela molida-Diplo-720g-Bote",
Champignon laminado lata-Diamante-355g-Lata
Comino molido-La Barraca-670g
Espaguetis Nr.2-La Islena-Caja
Guindillas Rama-La Barraca-180g-Botes
Jamon cocido Fiambre-El Pozo-4kg-Barra
Ketchup-Diplo-1,900g-Bote
Laurel hoja-La Barraca-60g-Bote
Leche-Rio/Gallega-6cartones-Caja
Mantequilla-Harmony-5kg-Barra
Mayonesa-Ybarra-1,8L-Cubo
Mayonesa-Ybarra-2,5L-Cubos
Mostaza-Diamante-1,900g-1Bote
Nata liquida-Krona-1L-Carton
Nata spray-Krona-500ml-Botes
Oregano-La Barraca-200g-Bote
Pimenton dulce-La Barraca-810g-Bote
Pimenton picante-La Barraca-810g-Bote
Pimienta negra molida-La Barraca-750g-Bote
Pimienta blanca molida-La Barraca-810g-Bote
Pimienta verde bote-Diamante-65g-Bote
Pina-El pilar-340g-Lata
Queso-GranjaFlor-3,5kg-Barra
Rabo de buey-Knorr-700g-Bote
Salsa-HP sauce-2L-1Bote
Salsa Perrys-Lea & Perrins-150ml-Bote
Salsa Tabasco-60ml-Bote
Tomate frito carton-Orlando-2,65kg-Carton
Tomate triturado-Orlando-2,5kg-Lata
Vinagre de vino-Diplo-5L
Vino blanco-Cruzares-1L-Carton
Botellitas de aceite y vinagre de cristal

             ----------Productos postres----------

Bizcocho soletilla-Paquete
Chocolate blanco-Tirma-150g
Chocolate con leche-Tirma-150g
Chocolate negro-Tirma-150g
Chocolate para fundir-Tirma-150g
Galletas-Maria Oro-Paquete
Sirope caramelo-Carta DOr-875ml-Bote
Sirope chocolate-Carta DOr-875ml-Bote
Sirope fresa-Carta DOr-875ml-Bote"
Cuajada sobres-Paquete

        ----------Productos limpieza y varios---------

Desengrasante-Kidel-10kg
Detergente liquido-Calgonit finish Prof.
kh-7-Bote grande
Fregona algodon industrial
Guantes plancha    Talla M
Jabon liquido banos
Lavavajillas mano (garrafa)-Fairy-5L
Lejia-Conejo-4L
Lejia-marca blanca-4L
Papel termico(rollos de 6cm)
Palillos enfundados
Pinchos brocheta

       --------------Bebidas-----------------

Akuavit
Amaretto
Anis Chinchon
Anis Sambuca
Baileys
Brandy 103
Brandy Carlos I
Brandy Carlos III
Brandy cocina barato
Brandy Magno
Brandy Veterano
Cerveza Coronita
Cerveza S.Miguel
Cordon negro Freixenet
Cordon negro Freixenet mini
Cynar
Drambuie
Fernet Branca
Frangelico
Ginebra barata
Ginebra Beefeater
Ginebra Gordons
Granadina
Jaergermeister
Licor de Lima
Licor de Platano
Martini blanco
Martini dry
Martini rosso
Orujo Aguardiente
Orujo Hierbas
Pacharan
Pampelmuse
Ramazotti
Ron Bacardi
Ron Blanco Arehucas
Ron miel Cayest-Caja
Ron Oro Arehucas
Ron Santa Teresa
Ron Santiago de Cuba
San Miguel
Tia Maria
Triple Seco
Vino fino Tio Pepe
Vino Protos
Vino tinto RVA. Marques del Riscal
Vodka Caramelo
Vodka Moskoskaya
Vodka Smirnoff
Whisky 100 pp
Whisky barato
Whisky E.N.
Whisky E.R.
Whisky J.B.
Whisky J.H.
"""
fout = open("lista.txt", "w")
fout.write(str1)
fout.close()

# read the data file into a list
fin = open("lista.txt", "r")
temp_list3 = fin.readlines()
fin.close()
# strip the trailing newline char
temp_list3 = [lista.rstrip() for lista in temp_list3]

# use entry widget to display/edit selection
enter1 = tk.Entry(root, width=50, bg='yellow')
enter1.insert(0, '')
enter1.grid(row=1, column=0)
# pressing the return key will update edited line
enter1.bind('<Return>', set_list)
# or double click left mouse button to update line
enter1.bind('<Double-1>', set_list)
# button to sort listbox
#button1 = ttk.Button(root, text='Orden alfabetico', command=sort_list)
#button1.grid(row=2, column=3, sticky=tk.E)
# button to save the listbox's data lines to a file
button2 = ttk.Button(root, text='Guardar lista', command=save_list)
button2.grid(row=3, column=0, sticky=tk.W)
# button to add a line to the listbox
button3 = ttk.Button(root, text='Insertar producto', command=add_item)
button3.grid(row=2, column=0, sticky=tk.E)
# button to delete a line from listbox
button4 = ttk.Button(root, text='Borrar producto     ', command=delete_item)
button4.grid(row=3, column=0, sticky=tk.E)

#button of listbox2
button5 = ttk.Button(root, text="Comprar", command=combine)
button5.grid(row=2, column=1, sticky=tk.E)
button6 = ttk.Button(root, text="Borrar", command=combine2)
button6.grid(row=2, column=2, sticky=tk.W)

button7 = ttk.Button(root, text="Correo", command=mail)
button7.grid(row=2, column=2, sticky=tk.E)

# load the listbox with data
for item in temp_list3:
    listbox1.insert(tk.END, item)

# left mouse click on a list item to display selection

root.mainloop()


from codecs import getdecoder
import time

def startTime():
    anchor = 1627101900
    current_time = time.time()
    time_since = current_time-anchor
    complete_5_min_periods = time_since // 300
    last_segment = anchor + complete_5_min_periods*300
    start_time = last_segment + 300.5

    return start_time

def wait(start_time):
    time.sleep(300.0 - ((time.time() - start_time) % 300.0))


## Q1 Initials
# Write your code below:
##############################

meeting_pop = int(input("How many people will attend the meeting? "))
participants = []

while len(participants) < meeting_pop:
    participants.append(input("Participant " + str(len(participants) + 1) + " "))

initials = []
for p in participants:
    initial = ''
    p_split = p.split(' ')
    for p_seg in p_split:
        if p_seg[0] != ' ': initial += p_seg[0]
    initials.append(initial)

print("The initials of the participants are as follows:")
for i in initials:
    print(i)


# -*- coding: UTF-8 -*-

import setuptools
from distutils.core import setup

# http://stackoverflow.com/a/7071358/735926
import re
VERSIONFILE='tidytree/__init__.py'
verstrline = open(VERSIONFILE, 'rt').read()
VSRE = r'^__version__\s+=\s+[\'"]([^\'"]+)[\'"]'
mo = re.search(VSRE, verstrline, re.M)
if mo:
    verstr = mo.group(1)
else:
    raise RuntimeError("Unable to find version string in %s." % VERSIONFILE)

setup(
    name='tidytree',
    version=verstr,
    author='Salmon Thomas',
    author_email='ths871@gmail.com',
    packages=['tidytree'],
    url='https://github.com/tsalmon/tidytree',
    license=open('LICENSE', 'r').read(),
    description='manager directories',
    long_description=open('README.rst', 'r').read(),
    install_requires=[
        'requests >= 2.3.0',
        'argparse >= 1.1',
    ],
    classifiers=[
        'Environment :: Console',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],
    entry_points={
        'console_scripts':[
            'tidytree = tidytree.cli:main'
        ]
    },
)


from tkinter import *
from PIL import Image,ImageTk
from random import choice

myFrame = Tk()

myFrame.title("Rock Paper Scissors")
myFrame.configure(background= "SteelBlue1")

# pictures
rockImage = ImageTk.PhotoImage(Image.open("imgs/rockUser.png"))
paperImage = ImageTk.PhotoImage(Image.open("imgs/paperUser.png"))
scissorsImage = ImageTk.PhotoImage(Image.open("imgs/scissorsUser.png"))
rockImageComp = ImageTk.PhotoImage(Image.open("imgs/rockComp.png"))
paperImageComp = ImageTk.PhotoImage(Image.open("imgs/paperComp.png"))
scissorsImageComp = ImageTk.PhotoImage(Image.open("imgs/scissorsComp.png"))
# insert pictures
userLabel = Label(myFrame,image=scissorsImage,bg="SteelBlue1")
compLabel = Label(myFrame,image=scissorsImageComp,bg="SteelBlue1")
userLabel.grid(row=1,column=4)
compLabel.grid(row=1,column=0)
# scors
playerScore = Label(myFrame,text=0,font=100,bg="SteelBlue1",fg="white")
compScore = Label(myFrame,text=0,font=100,bg="SteelBlue1",fg="white")

playerScore.grid(row=1,column=3)
compScore.grid(row=1,column=1)

# indicators

userIndicator = Label(myFrame,font=50,text="USER",bg="SteelBlue1",fg="white").grid(row=0,column=3)
compIndicator = Label(myFrame,font=50,text="COMPUTER",bg="SteelBlue1",fg="white").grid(row=0,column=1)

message = Label(myFrame,font=50,bg="SteelBlue1",fg="white")
message.grid(row=3,column=2)

# update message
def updateMessage(msg):
    message['text'] = msg

def updateUserScore():
    score = int(playerScore["text"])
    score+=1
    playerScore['text'] = str(score)

def updateComputerScore():
    score = int(compScore["text"])
    score+=1
    compScore['text'] = str(score)

def checkWiner(player,computer):
    if player == computer:
        updateMessage("it's a tie")
    elif player == 'rock':
        if computer == 'paper':
            updateMessage('You Loose')
            updateComputerScore()
        else:
            updateMessage('You Win')
            updateUserScore()
    elif player == 'paper':
        if computer == 'scissors':
            updateMessage('You Loose')
            updateComputerScore()
        else:
            updateMessage('You Win')
            updateUserScore()
    elif player == 'scissors':#scissors
        if computer == 'rock':
            updateMessage('You Loose')
            updateComputerScore()
        else:
            updateMessage('You Win')
            updateUserScore()
    else:
        pass

# set the choices
choices = ['rock','paper','scissors']
# update choices
def updateChoices(click):
    # for computer
    compChoice = choice(choices)
    if compChoice == 'rock':
        compLabel.configure(image= rockImageComp)
    elif compChoice == "paper":
        compLabel.configure(image= paperImageComp)
    else:
        compLabel.configure(image= scissorsImageComp)
    # for user
    if click == 'rock':
        userLabel.configure(image= rockImage)
    elif click == "paper":
        userLabel.configure(image= paperImage)
    else:
        userLabel.configure(image= scissorsImage)

    checkWiner(click,compChoice)

# button
rock = Button(myFrame,width=20,height=2,text="ROCK",bg="#ff3e4d",fg="white",command=lambda:updateChoices("rock")).grid(row=2,column=1)
paper = Button(myFrame,width=20,height=2,text="PAPER",bg="#ff3e4d",fg="white",command=lambda:updateChoices("paper")).grid(row=2,column=2)
scissors = Button(myFrame,width=20,height=2,text="SCISSORS",bg="#ff3e4d",fg="white",command=lambda:updateChoices("scissors")).grid(row=2,column=3)

myFrame.mainloop()


# https://www.acmicpc.net/problem/2630

import sys
count = int(sys.stdin.readline().strip())
arr = [sys.stdin.readline().strip().split() for _ in range(count)]
white = 0
blue = 0

def check(x, y, length):
    flag = arr[x][y]
    for i in range(x, x+length):
        for k in range(y, y+length):
            if flag != arr[i][k]:
                return False
    return True

def recursive(x=0, y=0, length=count):
    global blue, white

    if length == 0:
        return

    if check(x, y, length):
        if arr[x][y] == '1':
            blue += 1
        else:
            white += 1
    else:
        for i in range(x, x+length, length//2):
            for k in range(y, y+length, length//2):
                recursive(i, k, length//2)

recursive()
print(white)
print(blue)


from django.urls import path

from .views import GameListView, GameDetailView, ReviewCreateViewSet, GameCreateView, \
    GameDeleteOrUpdateView

urlpatterns = [
    path('game/', GameListView.as_view({'get': 'list'})),
    path('game/<int:pk>/', GameDetailView.as_view({'get': 'retrieve'})),
    path('review/', ReviewCreateViewSet.as_view({'post': 'create'})),
    path('game/create/',  GameCreateView.as_view({'post': 'create'})),
    path('game/<int:pk>/edit-delete/', GameDeleteOrUpdateView.as_view(), name='game-edit-delete'),
]


#%% INPUT
wdir  = r"E:\Tulips\DEM"
files = ["1","2","3"]

#%% PACKAGES AND FUNCTIONS
import rasterio
import gdal
import cv2
import numpy as np
import numpy.matlib
import matplotlib.pyplot as plt
from scipy import ndimage
import os

def calculate_slope(DEM):
        gdal.DEMProcessing('slope.tif', DEM, 'slope', alg = 'ZevenbergenThorne', scale = 500000)
        with rasterio.open('slope.tif') as dataset:
            slope=dataset.read(1)
        return slope

def odd(f):
        return np.ceil(f / 2.) * 2 + 1

def raster_calc(slope,p,u):
    out = np.ones(slope.shape)
    hist = np.histogram(slope[slope>0],bins=90,density=True)
    for h in range(10,len(hist[0])):
        if hist[0][h] <= p:
            t1=h
            break
    t2=u
    for h in range(u,len(hist[0])-1):
        if hist[0][h+1] > hist[0][h]:
            t2=h
    out[slope>t2] = 0
    out[slope<t1] = 0
    return out

#%% CREATE PATH
path = []
for x in range(len(files)):
    path.append(wdir+"\\"+files[x]+".tif")

#%% LOAD ARRAY AND SLOPE, SLOPE MANIPULATION, GAUSSIAN FILTER, SAVING IMAGE
for i in range(len(path)):
    file = gdal.Open(path[i])
    band = file.GetRasterBand(1)
    exec("gt"+str(i)+" = file.GetGeoTransform()")
    exec("array"+str(i)+" = band.ReadAsArray()")
    exec("slope"+str(i)+" = calculate_slope(path[i])")
    exec("slope"+str(i)+"_p = raster_calc(slope"+str(i)+",1/2000,75)")
    exec("slope"+str(i)+"_pp = ndimage.gaussian_filter(slope"+str(i)+"_p, sigma=10, order=0)")

    plt.clf()
    exec("fig = plt.imshow(slope"+str(i)+"_pp, cmap='hot', interpolation='nearest')")
    plt.axis('off')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)
    plt.savefig(wdir+"\\temp"+str(i)+".png", bbox_inches='tight', pad_inches = 0)

#%% HARRIS CORNER DETECTION
for i in range(len(path)):
    exec("size_x = len(slope"+str(i)+"[:,0])")
    exec("size_y = len(slope"+str(i)+"[0,:])")
    bsize  = int(odd(min(size_x,size_y)/200))
    ksize  = int(min(31,odd(min(size_x,size_y)/1000)))
    target = 4
    thresh = 0.01
    k      = 0.01
    for j in range(0,500):
        img = cv2.imread(wdir+"\\temp"+str(i)+".png")
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray = np.float32(gray)
        dst = cv2.cornerHarris(gray,bsize,ksize,k)
        ret, dst = cv2.threshold(dst,0.1*dst.max(),255,0)
        dst = np.uint8(dst)
        ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)
        criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, 0.001)
        corners = cv2.cornerSubPix(gray,np.float32(centroids),(20,20),(-1,-1),criteria)
        if len(corners) == target+1:
            break
        elif len(corners) <= target:
            thresh = thresh+0.01
            k=k+0.0001
        elif len(corners) >= target+2:
            thresh = thresh-0.01
            k=k+0.0001
    fact = size_x/len(img)
    file = gdal.Open(path[i])
    gt = file.GetGeoTransform()
    corn = corners * fact
    exec("corn"+str(i)+" = corn[1:,:]")
    exec("coor"+str(i)+" = np.matrix([gt[0] + gt[1]*corn[:,0] + gt[2]*corn[:,1],gt[3] + gt[4]*corn[:,0] + gt[5]*corn[:,1]]).transpose()")
    print('Image nr '+str(i)+' processed after '+str(j)+' alternations. Found '+str(len(corners)-1)+' corners.')

#%% GEOREFERENCE THE POINTS
for i in range(len(path)):
    if i >= 1:
        exec("coordinates = coor"+str(i))
        os.system("gdal_translate -of GTiff -gcp " + str(coordinates[0,0]) +" "+ str(coordinates[0,1]) +" "+ str(coor0[0,0]) +" "+ str(coor0[0,1])
        +" -gcp " + str(coordinates[1,0]) +" "+ str(coordinates[1,1]) +" "+ str(coor0[1,0]) +" "+ str(coor0[1,1])
        +" -gcp " + str(coordinates[2,0]) +" "+ str(coordinates[2,1]) +" "+ str(coor0[2,0]) +" "+ str(coor0[2,1])
        +" -gcp " + str(coordinates[3,0]) +" "+ str(coordinates[3,1]) +" "+ str(coor0[3,0]) +" "+ str(coor0[3,1])
        +" \""+path[i]+"\" \""+wdir+"\\temp"+files[i]+".tif\"")
        os.system("gdalwarp -r near -tps -co COMPRESS=NONE \""+wdir+"\\temp.tif\" \""+wdir+"\\"+files[i]+"_adjusted.tif\"")

#%% PLOT WHATEVER YOU WANT
check = corn2
array = array2
plt.imshow(array, cmap='hot', interpolation='nearest')
for l in range(len(check)):
    plt.scatter(check[l,0],check[l,1])


import itertools

test_input_1 = [
    [[-6, 0, 0], [3, 0, 0], [0, 0, 0]],
    [[-4, 0, 0], [2, 0, 0], [0, 0, 0]],
    [[-2, 0, 0], [1, 0, 0], [0, 0, 0]],
    [[3, 0, 0], [-1, 0, 0], [0, 0, 0]]
]

def parse_input():
    with open('data.txt') as file:
        lines = file.read().split('\n')

    input_data = []

    for line in lines:
        particle = []
        for parameter in line.split(', '):
            particle.append(list(map(int, parameter[3:-1].split(","))))
        input_data.append(particle)

    return input_data

def simulate(particles, expected_confidence):
    confidence = 0
    current_count = 0

    while confidence < expected_confidence:
        # update the velocities and positions
        for particle in particles:
            particle[1][0] += particle[2][0]
            particle[1][1] += particle[2][1]
            particle[1][2] += particle[2][2]
            particle[0][0] += particle[1][0]
            particle[0][1] += particle[1][1]
            particle[0][2] += particle[1][2]

        # mark collided particles for deletion
        to_delete = []
        for particle_1, particle_2 in itertools.combinations(particles, 2):
            if particle_1[0] == particle_2[0]:
                to_delete.append(particle_1)
                to_delete.append(particle_2)

        # delete particles that collided
        for particle in to_delete:
            try:
                particles.remove(particle)
            except ValueError:
                pass

        # count the particles
        new_count = len(particles)

        # if particle count didn't change in this step, increase the confidence
        # otherwise change the particle count and reset the confidence
        if new_count == current_count:
            confidence += 1
        else:
            current_count = new_count
            confidence = 0

    return current_count

def main():
    test_1 = simulate(test_input_1, 10)
    print("test_1:", test_1)

    answer = simulate(parse_input(), 10)
    print("answer:", answer)

if __name__ == "__main__":
    main()


# 재귀 이용했더니 시간초과 뜸
def fibo(n):
  if n <= 1:
    return n
  return fibo(n-1) + fibo(n-2)

def solve():
  n = int(input())
  print(fibo(n))

def solve2():
  n = int(input())
  memo = [0,1]
  for index in range(2,n+1):
    memo.append(memo[index-1] + memo[index-2])
  print(memo[n])

if __name__ == '__main__':
    solve2()


# -*- coding: utf-8 -*-
"""
Created on Mon Apr 16 13:12:45 2018

@author: Luna
"""

#Лоренц Джинни

import numpy as np
import matplotlib.pyplot as plt
N = 10
x = np.arange(0,N+1,1)
x = x/N
y = np.array( [2,2,2,2,2,2,5,5,9,   13])
y2 = np.array([1,1,1,1,1,1,1,1,13.5,13.5])
y3 = np.array([0.1,0.3,0.3,2.5,2.9,4.2,4,5,6,   6])

def cum(y):
    y_max = y.sum()
    a = 0
    y_cum = np.zeros(N+1)

    for (y_next,i) in zip(y, np.arange(1,N+1)):
        a = a + y_next
        y_cum[i]= a/y_max
    return y_cum
#Gini=[]
#Gini.append(1 - np.sum((X_k - X_k_1) * (Y_k + Y_k_1)))

def ginny(y):

    h = x[1]
    S= h*y[N]/2 + h*y[1:N].sum()

    return (0.5-S)/0.5

def ginny2(x,y):

    S = 0
    for i in np.arange(len(x)-1):
        dx = x[i+1]-x[i]
        s = 0.5*dx*(y[i+1]-y[i])+(y[i]*dx)
        S +=s

    return (0.5-S)/0.5

plt.plot(x, cum(y), label ="1, {:.3f}".format(ginny(cum(y))))
#plt.plot(x, cum(y2),label = "1, {}".format(ginny(cum(y2))))
plt.plot(x, cum(y3),label = "1, {:.3f}".format(ginny(cum(y3))))
plt.plot(x,x)
plt.legend(loc = 'best')

print("Ginny",ginny2(x, cum(y3)))


""" HOSPITAL MODEL CREATION """
from scipy.stats import truncnorm
from classes import Localization, TypeLocalization
import config

# Function that initialize a new hospital
# er_nbeds = nº beds in the ER
# icu_nbeds = nº beds in the ICU
# nwards = nº of wards
# wards_nrooms = nº of rooms in each ward
# room_nbeds = nº of beds in each ward room
# sx_nrooms = nº of operation rooms
# rx_nrooms = nº of radiology rooms
# rx_nbeds = nº of beds in each radiology room
def initialize_hospital(er_nbeds, icu_nbeds, nwards, wards_nrooms, sx_nrooms, rx_nrooms, room_nbeds, rx_nbeds):
    # ER, ICU
    er = Localization(0, TypeLocalization.ER)
    icu = Localization(1, TypeLocalization.ICU)
    L = [er, icu]

    # WARDS
    index = 2
    wards = []
    for i in range(nwards):
        ward = Localization(index, TypeLocalization.Ward)
        wards.append(ward)
        L.append(ward)
        index = index + 1

    # OPERATING ROOMS
    for i in range(sx_nrooms):
        surgery = Localization(index, TypeLocalization.Surgery)
        L.append(surgery)
        index = index + 1

    # RADIOLOGY ROOMS
    rxs = []
    for i in range(rx_nrooms):
        rx = Localization(index, TypeLocalization.Radiology)
        rxs.append(rx)
        L.append(rx)
        index = index + 1

    # ER AND ICU BEDS
    beds_er, index = create_beds(er_nbeds, index, er, 0)
    L = L + beds_er
    beds_icu, index = create_beds(icu_nbeds, index, icu, 1)
    L = L + beds_icu

    # WARDS ROOMS AND BEDS
    for i in range(nwards):
        rooms, beds, index = create_rooms(wards_nrooms[i], room_nbeds, index, wards[i])
        L = L + rooms
        L = L + beds

    # RADIOLOGY ROOMS BEDS
    for i in range(rx_nrooms):
        beds, index = create_beds(rx_nbeds, index, rxs[i], 0)
        L = L + beds

    return L

# Function that returns new nbeds beds following the id index, located in located_in and in the floor floor
def create_beds(nbeds, index, located_in, floor):
    beds = []
    for i in range(nbeds):
        beds.append(Localization(index, TypeLocalization.Bed, located_in))
        index = index + 1
    for b in beds:
        b.adjacent = [bed for bed in beds if bed is not b]
    located_in.children = beds
    return beds, index

# Function that returns new nrooms rooms with room_nbeds beds following the id index, located in located_in
def create_rooms(nrooms, room_nbeds, index, located_in):
    rooms = []
    beds = []
    for i in range(nrooms):
        r = Localization(index, TypeLocalization.Room, located_in)
        rooms.append(r)
        index = index + 1
        bs, index = create_beds(room_nbeds, index, r, 1)
        beds.extend(bs)

    located_in.children = rooms
    return rooms, beds, index

# Function that returns the daily hospital occupancy rate following a normal distribution
def normal_distr_occupancy_rate():
    max_beds = round(config.hosp_occupancy_rate / config.required_parameters['n_patients'])
    mean = config.hosp_occupancy_rate
    sd = 30
    tn = truncnorm((0 - mean) / sd, (max_beds - mean) / sd, loc=mean, scale=sd)
    return int(tn.rvs())


import os
from raw_data_processing import Reader
from os import sep as sep

path = r'F:\Lior\Network mistakes experiment 9\network_mistakes_exp9v2'
reader = Reader.FileReader(path, 'tif')

for filename in reader.file_list:
    subfolder = str.split(filename, sep)[-2]
    old_name = str.split(filename, sep)[-1]
    new_name = old_name[:5] + '2' + old_name[6:]

    dst = path + sep + subfolder + sep + new_name

    os.rename(filename,dst)

a=1


from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.multiclass import OneVsRestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import recall_score, f1_score, precision_score
from merger import train_bl as train, valid_bl as valid, test_bl as test, y_train, y_valid, y_test

vectorizer = TfidfVectorizer(max_features=2000)
x_train = vectorizer.fit_transform(train).toarray()
x_valid = vectorizer.fit_transform(valid).toarray()
x_test = vectorizer.fit_transform(test).toarray()

x_train.shape

lr_td_idf = OneVsRestClassifier(estimator=LogisticRegression()).fit(x_train, y_train)

preds_valid_td_idf = lr_td_idf.predict(x_valid)
#Accuracy
print(recall_score(y_valid, preds_valid_td_idf, average='weighted'))
#Recall
print(recall_score(y_valid.T, preds_valid_td_idf.T, average='macro'))
#Precision
print(precision_score(y_valid.T, preds_valid_td_idf.T, average='macro'))
#F1
print(f1_score(y_valid.T, preds_valid_td_idf.T, average='macro'))

preds_test_td_idf = lr_td_idf.predict(x_test)
#Accuracy
print(recall_score(y_test, preds_test_td_idf, average='weighted'))
#Recall
print(recall_score(y_test.T, preds_test_td_idf.T, average='macro'))
#Precision
print(precision_score(y_test.T, preds_test_td_idf.T, average='macro'))
#F1
print(f1_score(y_test.T, preds_test_td_idf.T, average='macro'))


import heapq
from collections import defaultdict

class PriorityQuene:
    def __init__(self):
        self.heap = []
        self.count = defaultdict(int)

    def push(self, x):
        heapq.heappush(self.heap, x)
        self.count[x] += 1

    def pop(self):
        res = self.top()
        self.remove(res)
        return res

    def top(self):
        return self.heap[0]

    def remove(self, x):
        if self.count[x] == 0:
            return
        self.count[x] -= 1
        while self.heap:
            if self.count[self.top()]:
                break
            heapq.heappop(self.heap)

    def __bool__(self):
        return bool(self.heap)

n = int(input())
int0 = lambda x: int(x) - 1
(*a,) = map(int0, input().split())
(*b,) = map(int0, input().split())
(*p,) = map(int0, input().split())
if any(a[i] <= b[p[i]] and i != p[i] for i in range(n)):
    print(-1)
    exit()
q = [None] * n
for i in range(n):
    q[p[i]] = i
heap = PriorityQuene()
for i in range(n):
    heap.push((a[i], i))
ans = []
while heap:
    _, i = heap.pop()
    j = i
    while q[j] != i:
        ans.append(j)
        j = q[j]
        heap.remove((a[j], j))
print(len(ans))
for j in ans:
    print(j + 1, q[j] + 1)