"""
Image Utilities for Galen
Author: Siddhant Sharma, 2019
"""
__author__ = "Siddhant Sharma"

import cv2
import torch
import numpy as np
from skimage import measure

def to_channels_last(img):
    """
    Turn (H, W, C) to (C, H, W)

    Args:
    * img
        image (`np.ndarray`)

    Returns:
    channels first (`np.ndarray`)
    """
    img = np.swapaxes(img, 0, 2)
    img = np.swapaxes(img, 1, 2)
    return img

def to_channels_first(img):
    """
    Turn (C, H, W) to (H, W, C)

    Args:
    * img
        image (`np.ndarray`)

    Returns:
    channels last image (`np.ndarray`)
    """
    img = np.swapaxes(img, 0, 2)
    img = np.swapaxes(img, 0, 1)
    return img

def img_to_tensor(img, resize=True, resize_dims=(128, 128), clahe=True):
    """
    Convert image to Pytorch Tensor

    Args:
    * img
        Image to convert to Pytorch Tensor
        NOTE: Assume `np.uint8` input dtype
    * resize
        OPTIONAL
        Resize image to `resize_dims` (bool)
        Default: True
    * resize_dims
        OPTIONAL
        Resize to given size
        Default: (128, 128)
    * clahe
        OPTIONAL
        Apply CLAHE to image (bool)
        Default: True

    Returns:
    Pytorch image Tensor
    """
    if resize:
        img = cv2.resize(img, resize_dims, interpolation = cv2.INTER_AREA)
    if clahe:
        img = clahe_image(img)
    img = img.astype('float32')
    img /= 255.
    img = to_channels_last(img)
    return torch.from_numpy(img[np.newaxis]).float()

def tensor_to_img(tensor):
    """
    Convert Pytorch Tensor to Numpy image

    Args:
    * tensor
        Pytorch Tensor to convert (`torch.Tensor`)

    Returns:
    Numpy image (`np.ndarray`)
    """
    tensor = tensor.data.numpy()
    tensor = tensor[0]
    return to_channels_first(tensor)

def clahe_image(img):
    """
    CLAHE-ify an image

    Args:
    * img
        image (`np.ndarray`)

    Returns:
    CLAHE-ified image (`np.ndarray`)
    """
    img = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
    lab_planes = cv2.split(img)
    clahe = cv2.createCLAHE(clipLimit=2,tileGridSize=(8, 8))
    lab_planes[0]= clahe.apply(lab_planes[0])
    lab = cv2.merge(lab_planes)
    return cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)

def surf_match(img1, img2, ratio=0.5, save=True):
    """
    Return SURF matching score between two images
    First image should be original/input image,
    second image should be reconstruction image
    NOTE: Assume all images are `np.float32`
    TODO: Find a better way to save SURF output,
          it's not pretty right now and hard to
          understand

    Args:
    * img1
        image (`np.ndarray`)
    * img2
        image (`np.ndarray`)
    * ratio
        OPTIONAL
        How accurate of a match (int)
        The lower the ratio, the more accurate the match
    * save
        OPTIONAL
        Save visual output of SURF or not (bool)
        Default: True

    Returns:
    SURF similarity score (float)
    """
    # Convert images to `np.uint8`
    img1 *= 255.
    img1 = img1.astype('uint8')
    img2 *= 255.
    img2 = img2.astype('uint8')

    # Create SURF descriptor and find keypoints in both images
    sift = cv2.xfeatures2d.SURF_create()
    kp_1, desc_1 = sift.detectAndCompute(img1, None)
    kp_2, desc_2 = sift.detectAndCompute(img2, None)

    # Search the keypoints for matches
    index_params = dict(algorithm = 0, trees = 5)
    search_params = dict()
    flann = cv2.FlannBasedMatcher(index_params, search_params)
    matches = flann.knnMatch(desc_1, desc_2, k=2)

    # Find matches (within some give or take)
    good_points = []
    for m, n in matches:
        if m.distance < ratio * n.distance:
            good_points.append(m)

    # Save the output
    if save:
        cv2.imwrite('./outputs/surf.png', cv2.drawMatches(img1, kp_1, img2, kp_2, good_points, None))

    # Return the score
    return len(good_points) * 100 / len(kp_2)

def kaze_match(img1, img2, ratio=0.4, save=True):
    """
    Return KAZE matching score between two images
    First image should be original/input image,
    second image should be reconstruction image
    NOTE: Assume all images are `np.float32`
    TODO: Find a better way to save KAZE output,
          it's not pretty right now and hard to
          understand

    Args:
    * img1
        image (`np.ndarray`)
    * img2
        image (`np.ndarray`)
    * ratio
        OPTIONAL
        How accurate of a match (int)
        The lower the ratio, the more accurate the match
    * save
        OPTIONAL
        Save visual output of KAZE or not (bool)
        Default: True

    Returns:
    KAZE similarity score (float)
    """
    # Convert images to `np.uint8`
    img1 *= 255.
    img1 = img1.astype('uint8')
    img2 *= 255.
    img2 = img2.astype('uint8')

    # Create KAZE descriptor and find keypoints in both images
    kaze = cv2.KAZE_create()
    kp_1, desc_1 = kaze.detectAndCompute(img1, None)
    kp_2, desc_2 = kaze.detectAndCompute(img2, None)

    # Search the keypoints for matches
    index_params = dict(algorithm = 0, trees = 5)
    search_params = dict()
    flann = cv2.FlannBasedMatcher(index_params, search_params)

    # Find matches (within some give or take)
    matches = flann.knnMatch(desc_1, desc_2, k=2)
    good_points = []
    for m,n in matches:
        if m.distance < ratio * n.distance:
            good_points.append(m)

    # Save the output
    if save:
        cv2.imwrite('./outputs/kaze.png', cv2.drawMatches(img1, kp_1, img2, kp_2, good_points, None))

    # Return the score
    return len(good_points) * 100 / len(kp_2)

def get_bbox(img1, img2):
    """
    Get the area of the largest difference between the original
    and reconstructions
    Only should be used if input image is unhealthy

    Args:
    * img1
        original image (`np.ndarray`)
    * img2
        reconstruction image (`np.ndarray`)

    Returns:
    bbox image (`np.ndarray`)
    """
    # Grayscale
    img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
    # Get differences using SSIM
    (score, diff) = measure.compare_ssim(img1_gray, img2_gray, full=True)
    diff = (diff * 255).astype("uint8")
    # Threshold differences
    thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
    # Extract contours
    contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    contours = contours[0] if len(contours) == 2 else contours[1]

    contour_sizes = [(cv2.contourArea(contour), contour) for contour in contours]

    # Find the largest contour (to a certain extent)
    # Some limits bc contour shouldn't be whole image
    largest = cv2.contourArea(contours[0])
    largest_idx = 0
    for c in range(len(contours)):
        area = cv2.contourArea(contours[c])
        if area > 40 and area < 6000:
            if largest < area:
                largest = area
                largest_idx = c
    img = np.copy(img1)
    x,y,w,h = cv2.boundingRect(contours[largest_idx])
    # Place contour bbox
    cv2.rectangle(img, (x, y), (x + w - 2, y + h - 2), (255,0,0), 2)
    return img

def get_heatmap(img1, img2):
    """
    Get the RGB difference between original and reconstruction
    First image should be original/input image
    Second image should be reconstruction image

    Args:
    * img1
        image (`np.ndarray`)
    * img2
        image (`np.ndarray`)

    Returns:
    heatmap image (`np.ndarray`)
    """
    error_r = np.fabs(np.subtract(img2[:,:,0], img1[:,:,0]))
    error_g = np.fabs(np.subtract(img2[:,:,1], img1[:,:,1]))
    error_b = np.fabs(np.subtract(img2[:,:,2], img1[:,:,2]))
    return np.maximum(np.maximum(error_r, error_g), error_b)


import os
import mp3Tagger

path = "data/"
fileExtension = ".mp3"
genre = "audio"
comment = "comment"

for root, dirs, files in os.walk(path):                                                 # root = directory or subdirectory within path
    counter = 0
    for file in files:                                                                  # EVERY file in path and subdirs of path
        counter += 1
        extension = os.path.splitext(file)[1]                                           # get extension of file
        if extension == fileExtension:                                                  # filter for desired files
            audio = os.path.relpath(os.path.join(root, file))                           # relative path to file

            mp3Tagger.setGenre(audio, genre)
            mp3Tagger.setComment(audio, comment)

            maxRequiredDigits = len(str(len(files)))                                    # Calculate required digits, in this loop-iteration 'files' contains all files of one root
            mp3Tagger.formatTracknumbersWithLeadingZeros(audio, maxRequiredDigits)
            mp3Tagger.setTrackNumberAsTitle(audio)

            newFileName = mp3Tagger.buildFileNameFromSomeID3Tags(audio, fileExtension)  # Build filename: Artist - Title - Album - CommentExtension
            newFileName = os.path.relpath(os.path.join(root, newFileName))              # relative path to file with new filename
            mp3Tagger.setFileName(audio, newFileName)

#            mp3Tagger.setTrack(audio, "")                                               # Delete Tracknumber

            print("%4d/" % (counter) + str(len(files)) + "\t" + os.path.basename(audio) + "\t --> \t" + os.path.basename(newFileName))


# full marks
from copy import deepcopy
def solve(grid):
    starts = []
    bestStarts = []
    gLength = 0
    res = 0
    for i in range(len(grid)):
        for j in range(len(grid[0])):
            if grid[i][j] != "X":
                # check left and right
                if grid[i][j-1] == "X" and grid[i][j+1] != "X":
                    starts.append([i,j])
                # check top and bottom
                elif grid[i-1][j] == "X" and grid[i+1][j] != "X":
                    starts.append([i,j])

    # check the lengths of the things that go from start
    for start in starts:
        cStart = deepcopy(start)
        # horizontal length
        hLength = 0
        while grid[start[0]][start[1]] != "X":
            hLength += 1
            start[1] += 1

        start = cStart
        cStart = deepcopy(start)
        # vertical length
        vLength = 0
        while grid[start[0]][start[1]] != "X":
            vLength += 1
            start[0] += 1

        start = cStart
        direction = 'h' if hLength > vLength else 'v'

        if max(hLength, vLength) == gLength:
            bestStarts.append([start[0], start[1], direction])
        elif max(hLength, vLength) > gLength:
            gLength = max(hLength, vLength)
            bestStarts = [[start[0], start[1], direction]]

    # find the largest number from the best starts
    for bStart in bestStarts:
        value = ''
        if bStart[2] == 'h':
            value = grid[bStart[0]][bStart[1] : bStart[1]+gLength]
        else:
            for x in range(gLength):
                value += grid[bStart[0] + x][bStart[1]]
        value = int(value)
        if value > res:
            res = value

    return res

n = [int(i) for i in input().split(" ")]
grid = []
grid.append("X" * (n[0] + 2))
for i in range(n[1]):
    grid.append("X" + input() + "X")
grid.append("X" * (n[0] + 2))
res = solve(grid)
print(res)


r"""Model description for the advection equation"""

import firedrake
from firedrake import max_value, min_value, inner, dx, ds
from . import forms

def make_equation(u, s, q_in=firedrake.Constant(0)):
    r"""Return a function that gives the weak form of the conservative
    advection equation."""
    def equation(q):
        Q = q.function_space()
        φ = firedrake.TestFunction(Q)

        F = q * u

        mesh = Q.mesh()
        n = firedrake.FacetNormal(mesh)
        c = abs(inner(u, n))

        sources = s * φ * dx
        fluxes = (
            forms.cell_flux(F, φ) +
            forms.central_facet_flux(F, φ) +
            forms.lax_friedrichs_facet_flux(q, c, φ) +
            q * max_value(0, inner(u, n)) * φ * ds +
            q_in * min_value(0, inner(u, n)) * φ * ds
        )

        return sources - fluxes

    return equation


import tkinter
from quiz_brain import QuizBrain

THEME_COLOR = "#375362"

class QuizAppUserInterface:

    def __init__(self, quiz_brain: QuizBrain):
        self.window = tkinter.Tk()
        self.quiz = quiz_brain
        self.window.title("Quizzler")
        self.window.config(padx=20, pady=20)
        self.score = tkinter.Label(text="Score: 0", fg="white")
        self.score.grid(column=1, row=0)
        self.score.config(bg=THEME_COLOR)

        self.canvas = tkinter.Canvas(width=300, height=250)
        self.question_text = self.canvas.create_text(150, 125, width=280, text="Hello", fill="black",
                                                     font=("Arial", 20, "italic"))
        self.canvas.grid(column=0, row=1, columnspan=2, pady=50)

        self.correct_image = tkinter.PhotoImage(file="images/true.png")
        self.false_image = tkinter.PhotoImage(file="images/false.png")
        self.correct_image_button = tkinter.Button(image=self.correct_image, highlightthickness=0,
                                                   command=self.correct_answer)
        self.correct_image_button.grid(column=0, row=2)
        self.false_image_button = tkinter.Button(image=self.false_image, highlightthickness=0,
                                                 command=self.wrong_answer)
        self.false_image_button.grid(column=1, row=2)

        self.window.config(bg=THEME_COLOR)
        self.get_question()
        self.window.mainloop()

    def get_question(self):
        if self.quiz.still_has_questions():
            next_question = self.quiz.next_question()
            self.canvas.itemconfig(self.question_text, text=next_question)
        else:
            self.canvas.itemconfig(self.question_text, text="THE END")
            self.correct_image_button.config(state="disabled")
            self.false_image_button.config(state="disabled")

    def correct_answer(self):
        is_right = self.quiz.check_answer('True')
        self.give_feedback(is_right)

    def wrong_answer(self):
        is_right = self.quiz.check_answer('False')
        self.give_feedback(is_right)

    def give_feedback(self, is_right):
        if is_right:
            self.score.config(text=f"Score: {self.quiz.score}")
            self.canvas.config(bg="green")
            self.window.after(500, func=self.flash)
        else:
            self.canvas.config(bg="red")
            self.window.after(500, func=self.flash)

    def flash(self):
        self.canvas.config(bg="white")
        self.get_question()


import pytest
from black_jack.blackjack_model import Card, BlackjackModel #, # calculate_black_jack_sum

# example test without parametrization
# def test_calculate_black_jack_sum():
#     result = calculate_black_jack_sum([Card('3', 'C'), Card('3', 'C')])
#     expected_result = 6
#     assert result == expected_result

# working test with parametrization (allows you to run the same test with multiple inputs) note that 'test_input,
# expected_output' is a SINGLE string!
# also note the class must be instantiated first. pytest methods do not take the 'self' keyword, you must *always*
# instantiate your test class.
@pytest.mark.parametrize('test_input, expected_output', (
                                                         ([], 0),
                                                         ([Card('10', 'C')], 10),
                                                         ([Card('3', 'C'), Card('3', 'C')], 6),
                                                         ([Card('5', 'C'), Card('K', 'C'), Card('Q', 'C')], 25),
                                                         ([Card('A', 'C'), Card('A', 'D')], 12),
                                                         ([Card('A', 'C'), Card('A', 'D'), Card('A', 'D')], 13),
                                                         ([Card('A', 'C'), Card('J', 'D')], 21),
                                                         ([Card('A', 'C'), Card('A', 'D'), Card('Q', 'D')], 12)))
def test_calculate_black_jack_sum(test_input, expected_output):
    model = BlackjackModel()
    result = model.calculate_black_jack_sum(test_input)
    assert result == expected_output


import sqlite3
from sqlite3 import Error

db_file = "NaizDB.db"
conn = sqlite3.connect(db_file)

cur = conn.cursor()
cur.execute("SELECT * FROM CameraList")
rows = cur.fetchall()
iTotal = len(rows)
iCount = 0
isAlive = 0

for row in rows :
    if (row[2].startswith("10.")) == True :
        if (row[5]==1) : isAlive = isAlive + 1
        iCount = iCount + 1
        print( row )

print("Total    = " + str(iTotal))
print("4 Campus = " + str(iCount))
print("Alive    = " + str(isAlive))
#for row in rows :  print( row )


from .grampstype import GrampsType
from ..const import GRAMPS_LOCALE as glocale

_ = glocale.translation.sgettext

class NoteType(GrampsType):
    UNKNOWN = -1
    CUSTOM = 0
    GENERAL = 1
    RESEARCH = 2
    TRANSCRIPT = 3
    # per object with notes a Type to distinguish the notes
    PERSON = 4
    ATTRIBUTE = 5
    ADDRESS = 6
    ASSOCIATION = 7
    LDS = 8
    FAMILY = 9
    EVENT = 10
    EVENTREF = 11
    SOURCE = 12
    SOURCEREF = 13
    PLACE = 14
    REPO = 15
    REPOREF = 16
    MEDIA = 17
    MEDIAREF = 18
    CHILDREF = 19
    PERSONNAME = 20
    # other common types
    SOURCE_TEXT = 21  # this is used for verbatim source text in SourceRef
    CITATION = 22
    REPORT_TEXT = 23  # this is used for notes used for reports
    # indicate a note is html code
    HTML_CODE = 24
    TODO = 25
    # indicate a note used as link in another note
    LINK = 26
    ANALYSIS = 27

    _CUSTOM = CUSTOM
    _DEFAULT = GENERAL

    _DATAMAPREAL = [
        (UNKNOWN, _("Unknown"), "Unknown"),
        (CUSTOM, _("Custom"), "Custom"),
        (GENERAL, _("General"), "General"),
        (RESEARCH, _("Research"), "Research"),
        (ANALYSIS, _("Analysis"), "Analysis"),
        (TRANSCRIPT, _("Transcript"), "Transcript"),
        (SOURCE_TEXT, _("Source text"), "Source text"),
        (CITATION, _("Citation"), "Citation"),
        (REPORT_TEXT, _("Report"), "Report"),
        (HTML_CODE, _("Html code"), "Html code"),
        (TODO, _("To Do", "notetype"), "To Do"),
        (LINK, _("Link", "notetype"), "Link"),
    ]

    _DATAMAPIGNORE = [
        (PERSON, _("Person Note"), "Person Note"),
        (PERSONNAME, _("Name Note"), "Name Note"),
        (ATTRIBUTE, _("Attribute Note"), "Attribute Note"),
        (ADDRESS, _("Address Note"), "Address Note"),
        (ASSOCIATION, _("Association Note"), "Association Note"),
        (LDS, _("LDS Note"), "LDS Note"),
        (FAMILY, _("Family Note"), "Family Note"),
        (EVENT, _("Event Note"), "Event Note"),
        (EVENTREF, _("Event Reference Note"), "Event Reference Note"),
        (SOURCE, _("Source Note"), "Source Note"),
        (SOURCEREF, _("Source Reference Note"), "Source Reference Note"),
        (PLACE, _("Place Note"), "Place Note"),
        (REPO, _("Repository Note"), "Repository Note"),
        (REPOREF, _("Repository Reference Note"), "Repository Reference Note"),
        (MEDIA, _("Media Note"), "Media Note"),
        (MEDIAREF, _("Media Reference Note"), "Media Reference Note"),
        (CHILDREF, _("Child Reference Note"), "Child Reference Note"),
    ]

    _DATAMAP = _DATAMAPREAL + _DATAMAPIGNORE

    def __init__(self, value=None):
        GrampsType.__init__(self, value)

    def get_ignore_list(self, exception):
        """
        Return a list of the types to ignore and not include in default lists.

        Exception is a sublist of types that may not be ignored

        :param exception: list of integer values corresponding with types that
                          have to be excluded from the ignore list
        :type exception: list
        :returns: list of integers corresponding with the types to ignore when
                  showing a list of different types
        :rtype: list

        """
        ignlist = [x[0] for x in self._DATAMAPIGNORE]
        if exception:
            for type_ in exception:
                try:
                    del ignlist[ignlist.index(type_)]
                except ValueError:
                    pass
        return ignlist


import streamlit as st

st.set_page_config(layout="wide")

import threading

import src.pages.front_page as front_page
import src.pages.air_quality as air_quality
import src.pages.monthly_averages as monthly_averages
import src.pages.pickups_dropoffs as pickups_dropoffs

import ag_grid_hack

import base64
import json

## retro code review comment

PAGES = {
    "Central Business District Tolling Program": {
        "NYC Air Quality": air_quality,
        "TLC Monthly Averages": monthly_averages,
        "TLC Pickups and Dropoffs": pickups_dropoffs
    }
}

## retro code review comment

def set_session_state(page_session_key, parent_selection, child_selection):
    st.session_state[page_session_key] = {"parent_selection": parent_selection, "child_selection": child_selection}

## retro code review comment

def main() -> None:
    """Main function of the App"""
    # render_svg_example()

    ag_grid_hack.inject_css()

    st.markdown(
        """ <style>
        .css-18e3th9 {{
                padding-top: 0rem;
                padding-right: -1rem;
                padding-left: 1rem;
                padding-bottom: 0rem;
                width: 10rem;
            }}
        .css-12oz5g7 {{
            padding-top: 0rem;
            padding-right: -1rem;
            padding-left: 1rem;
            padding-bottom: 0rem;
            max-width: 80%;
        }}
        #MainMenu {visibility: hidden;}
        footer {visibility: hidden;}
         </style> """,
        unsafe_allow_html=True,
    )
## retro code review comment

    # Initialize session state:
    page_session_key = "page_selected"
    if page_session_key not in st.session_state:
        st.session_state[page_session_key] = None

    # Multi hierarchy sidebar:
    with st.sidebar:
        parents = [k for k in PAGES.keys()]
        parent_selection = None
        child_selection = None
        expanders = {}
        for parent in parents:
            expanders[parent] = st.expander(parent, expanded=False)
            for page in PAGES[parent].keys():
                with expanders[parent]:
                    blank, button_col = st.columns((0.05, 0.95))
                    with button_col:
                        st.button(
                            page,
                            key=f"{parent}${page}",
                            on_click=set_session_state,
                            args=(page_session_key, parent, page),
                        )
## retro code review comment

    # Call page
    if st.session_state[page_session_key]:
        parent_selection = st.session_state[page_session_key]["parent_selection"]
        child_selection = st.session_state[page_session_key]["child_selection"]
        PAGES[parent_selection][child_selection].app()
        # report statistics
        # count_pageview(f"{parent_selection}: {child_selection}")
    else:
        front_page.app()

if __name__ == "__main__":
    # # Load CSS
    # with open(".streamlit/style") as css:
    #     st.markdown(f"<style>{css.read()}</style>", unsafe_allow_html=True)

    # Run app
    main()


#This is a program used to calculate tip when splitting the bill

print("Welcome to the Tip calculator")
bill = input("What is the total bill? $")
tip = input("What is the percent tip you would like to use? 10, 12, or 15? ")
people = input("How many people will be splitting the bill? ")

percent_tip = (int(tip) / 100 + 1)
final_bill = round((float(bill) / int(people)) * percent_tip, 2)
print(f"Each person should pay: ${final_bill}")


import argparse
import sys
from items import ImageDatabase
from PIL import Image
import settings
import os
import pickle
from glob import glob
import math
import time
import utilities

sys.stdout.reconfigure(encoding='utf-8')

def _load_database(folder, size, repeat, pieces_required):
    database_folder = utilities.get_database_structure(folder).folder

    # first, try load from existing database if exists
    if os.path.isdir(database_folder) and (
            size < settings.DATABASE_IMAGE_WIDTH or size < settings.DATABASE_IMAGE_HEIGHT):
        try:
            # try to load files existing database
            print('Attempting to load database from folder: {}'.format(database_folder))
            existing_database = ImageDatabase.load(folder, size, size)

            number_of_images_in_existing_database = len(existing_database.images)

            if not repeat and number_of_images_in_existing_database < pieces_required:
                raise ValueError('Existing database does not contain enough pictures: {} < {}'.format(
                    number_of_images_in_existing_database, pieces_required))

            number_of_images_in_specified_folder = len(glob(folder + '/*[jpg|png]'))

            #
            # if number of images are the same then high chance database is unchanged,
            # return if settings allowed to return
            #
            if number_of_images_in_existing_database == number_of_images_in_specified_folder \
                    and settings.ALLOW_USE_EXISING_IF_SEEM_SAME:
                # print('Existing database seem to be coherent {} == {}'.format(number_of_images_in_specified_folder,
                #                                                               number_of_images_in_existing_database))
                return existing_database
            # ask if they want to use the existing database if reached here
            while True:
                ans = input('Existing database found with size requirement satisfied, ' + os.linesep +
                            'existing database:{}, specified folder:{}, use existing? [y/n]:'.format(
                                number_of_images_in_existing_database,
                                number_of_images_in_specified_folder))
                if ans == 'y':
                    return existing_database
                elif ans == 'n':
                    break
                print('Please give answer as \'y\' or \'n\'')

        except pickle.PicklingError:  # raise when failed checking before loading database
            print('Failed to load existing database: {}'.format(database_folder))
        except ValueError as e:  # raise by internal checking
            print(e)
        except EOFError:  # raise when loading fails
            print('Data is corrupted in existing database {}'.format(database_folder))

    #
    # database folder does not exists or user wants to create new database if reached here
    #
    print('Creating new database from folder: {}'.format(folder))

    database = ImageDatabase(size, size, folder)

    #
    # checks before actually process the image files found
    #
    files_found = len(database.files)

    if not repeat and pieces_required > files_found:
        raise ValueError(
            'Number of pictures in folder {} is not enough: {} < {}'.format(folder, files_found, pieces_required))

    if settings.MAX_CHUNKS_USE:
        limited_pieces = settings.MAX_CHUNKS_USE * settings.MAX_CACHE_PROCESSED_IMAGES
        if not repeat and pieces_required > limited_pieces:
            raise ValueError(
                'Number of pictures limited {} is not enough: {} < {}, try to increase settings.MAX_CHUNKS_USE'.format(
                    folder, limited_pieces, pieces_required))

    # now actually process the files
    database.process_and_save_files()

    # finished
    return database

def make_from(source, folder, size, factor, use_repeat=True):
    src_width, src_height = source.size
    width = int(src_width * factor)
    height = int(src_height * factor)
    source = source.resize((width, height))

    pieces_required = math.ceil(width / size) * math.ceil(height / size)

    print('=' * 50)
    print('factor:', factor)
    print('result dimension:', width, height)
    print('total pieces:', pieces_required)
    print('repeat:', use_repeat)
    print('algorithm:', settings.COLOR_DIFF_METHOD)
    print('=' * 50)

    if size < 1 or size < 1:
        raise ValueError('width or height for each small piece of images is less than 1px: {} {} < {}'.format(
            width, height, size))

    database = _load_database(folder, size, use_repeat, pieces_required)
    database.process_images()

    print('=' * 50)
    print('Database size:', database.size)
    print('=' * 50)

    chunk_count = 0
    background = Image.new(source.mode, source.size, 'black')
    print('building image from database ...')
    start_time = time.time()
    for h in range(0, height, size):
        for w in range(0, width, size):
            btmx = w + size
            btmy = h + size
            if btmx > width:
                btmx = width
            if btmy > height:
                btmy = height
            curr_chunk = source.crop((w, h, btmx, btmy))
            best_match = database.find_closest(curr_chunk, use_repeat, method=settings.COLOR_DIFF_METHOD)
            background.paste(best_match, (w, h))
            chunk_count += 1
            utilities.print_progress(chunk_count, pieces_required)
    utilities.print_done(time.time() - start_time)

    return source, background

def main():
    parser = argparse.ArgumentParser(description='build image from images')
    parser.add_argument('-src', '--source', help='the image to stimulate')
    parser.add_argument('-s', '--size', type=int, help='the size of each pieces')
    parser.add_argument('-f', '--folder', help='the folder containing images used to stimulate the source')
    parser.add_argument('-d', '--dest', help='the base name of the output file, not including extension')
    parser.add_argument('-r', '--repeat', action='store_true', help='allow build with repeating images')
    parser.add_argument('-fa', '--factor', type=int, help='result size factor compared to original')
    args = parser.parse_args()

    input_file = args.source
    database_folder = args.folder
    src = Image.open(input_file).convert('RGB')
    source, background = make_from(src, database_folder, args.size, args.factor, use_repeat=args.repeat)

    print('Blending & saving images ... ')

    folder = args.dest
    if not os.path.isdir(folder):
        os.mkdir(folder)

    background_file = folder + '/background_{}.jpg'
    background.save(background_file.format('repeat' if args.repeat else 'no_repeat'))

    output_file = folder + '/{}.jpg'
    blend_range = 10
    for index, blend_percent in enumerate(range(0, blend_range)):
        blend_percent = blend_percent / blend_range
        image = Image.blend(source, background, blend_percent)
        image.save(output_file.format(blend_percent))
        utilities.print_progress(index+1, blend_range)
    utilities.print_done(folder)

if __name__ == '__main__':
    main()


import random
import numpy as np

from Vcuckoofilter14_7 import VCuckooFilter14_7
from Vcuckoofilter14_6 import VCuckooFilter14_6
from Vcuckoofilter14_5 import VCuckooFilter14_5
from Vcuckoofilter14_4 import VCuckooFilter14_4
from Vcuckoofilter14_3 import VCuckooFilter14_3
from Vcuckoofilter14_2 import VCuckooFilter14_2
from Vcuckoofilter14_1 import VCuckooFilter14_1

raw_data = []
with open('C:/Users/fptjy/pydaima/cuckoopy-master/cuckoopy/data_test_8676622.csv', 'r') as fin:
    for line in fin:
        raw_data.append(line.replace(",\n", ""))
fin.close()

number = 1

#存储结果

cf_fp_result = []

vcf7_fp_result = []
vcf6_fp_result = []
vcf5_fp_result = []
vcf4_fp_result = []
vcf3_fp_result = []
vcf2_fp_result = []
vcf1_fp_result = []

D_vcf8_fp_result = []
D_vcf7_fp_result = []
D_vcf6_fp_result = []
D_vcf5_fp_result = []
D_vcf4_fp_result = []
D_vcf3_fp_result = []
D_vcf2_fp_result = []
D_vcf1_fp_result = []

fingersize = 14
print("实验中指纹值长度为：", fingersize)

###filter size取2 ** 20
##设置参数
capacity1 = [2 ** 20]

for j in range(len(capacity1)):
    for num in range(number):

        # 局部变量存储查询返回True的结果数量
        cf_fp = 0
        vcf7_fp = 0
        vcf6_fp = 0
        vcf5_fp = 0
        vcf4_fp = 0
        vcf3_fp = 0
        vcf2_fp = 0
        vcf1_fp = 0
        D_vcf1_fp = 0
        D_vcf2_fp = 0
        D_vcf3_fp = 0
        D_vcf4_fp = 0
        D_vcf5_fp = 0
        D_vcf6_fp = 0
        D_vcf7_fp = 0
        D_vcf8_fp = 0

        #构造100% none existed 的数据
        testdata1 = random.sample(raw_data, capacity1[j])
        list1 = list(set(raw_data) - set(testdata1))
        testdata2 = random.sample(list1, capacity1[j])

        cf = VCuckooFilter14_7(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            cf.I_insert0(testdata1[i])

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if cf.I_contains0(testdata1[i]):
                cf_fp += 1
        cf_fp_result.append((cf_fp) / cf.size)

        Vcf7 = VCuckooFilter14_7(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            Vcf7.I_insert7(testdata1[i])

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if Vcf7.I_contains7(testdata1[i]):
                vcf7_fp += 1
        vcf7_fp_result.append((vcf7_fp) / Vcf7.size)

        Vcf6 = VCuckooFilter14_6(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            Vcf6.I_insert6(testdata1[i])

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if Vcf6.I_contains6(testdata1[i]):
                vcf6_fp += 1
        vcf6_fp_result.append((vcf6_fp) / Vcf6.size)

        Vcf5 = VCuckooFilter14_5(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            Vcf5.I_insert5(testdata1[i])

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if Vcf5.I_contains5(testdata1[i]):
                vcf5_fp += 1
        vcf5_fp_result.append((vcf5_fp) / Vcf5.size)

        Vcf4 = VCuckooFilter14_4(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            Vcf4.I_insert4(testdata1[i])

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if Vcf4.I_contains4(testdata1[i]):
                vcf4_fp += 1
        vcf4_fp_result.append((vcf4_fp) / Vcf4.size)

        Vcf3 = VCuckooFilter14_3(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            Vcf3.I_insert3(testdata1[i])

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if Vcf3.I_contains3(testdata1[i]):
                vcf3_fp += 1
        vcf3_fp_result.append((vcf3_fp) / Vcf3.size)

        Vcf2 = VCuckooFilter14_2(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            Vcf2.I_insert2(testdata1[i])

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if Vcf2.I_contains2(testdata1[i]):
                vcf2_fp += 1
        vcf2_fp_result.append((vcf2_fp) / Vcf2.size)

        Vcf1 = VCuckooFilter14_1(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            Vcf1.I_insert1(testdata1[i])

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if Vcf1.I_contains1(testdata1[i]):
                vcf1_fp += 1
        vcf1_fp_result.append((vcf1_fp) / Vcf1.size)

        D_vcf1 = VCuckooFilter14_7(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            D_vcf1.D_insert(testdata1[i], 2**13*(1-0.125), 2**13*(1+0.125))

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if D_vcf1.D_contains(testdata1[i], 2**13*(1-0.125), 2**13*(1+0.125)):
                D_vcf1_fp += 1
        D_vcf1_fp_result.append((D_vcf1_fp) / D_vcf1.size)

        D_vcf2 = VCuckooFilter14_7(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            D_vcf2.D_insert(testdata1[i], 2 ** 13 * (1 - 0.25), 2 ** 13 * (1 + 0.25))

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if D_vcf2.D_contains(testdata1[i], 2 ** 13 * (1 - 0.25), 2 ** 13 * (1 + 0.25)):
                D_vcf2_fp += 1
        D_vcf2_fp_result.append((D_vcf2_fp) / D_vcf2.size)

        D_vcf3 = VCuckooFilter14_7(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            D_vcf3.D_insert(testdata1[i], 2 ** 13 * (1 - 0.375), 2 ** 13 * (1 + 0.375))

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if D_vcf3.D_contains(testdata1[i], 2 ** 13 * (1 - 0.375), 2 ** 13 * (1 + 0.375)):
                D_vcf3_fp += 1
        D_vcf3_fp_result.append((D_vcf3_fp) / D_vcf3.size)

        D_vcf4 = VCuckooFilter14_7(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            D_vcf4.D_insert(testdata1[i], 2 ** 13 * (1 - 0.5), 2 ** 13 * (1 + 0.5))

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if D_vcf4.D_contains(testdata1[i], 2 ** 13 * (1 - 0.5), 2 ** 13 * (1 + 0.5)):
                D_vcf4_fp += 1
        D_vcf4_fp_result.append((D_vcf4_fp) / D_vcf4.size)

        D_vcf5 = VCuckooFilter14_7(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            D_vcf5.D_insert(testdata1[i], 2 ** 13 * (1 - 0.625), 2 ** 13 * (1 + 0.625))

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if D_vcf5.D_contains(testdata1[i], 2 ** 13 * (1 - 0.625), 2 ** 13 * (1 + 0.625)):
                D_vcf5_fp += 1
        D_vcf5_fp_result.append((D_vcf5_fp) / D_vcf5.size)

        D_vcf6 = VCuckooFilter14_7(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            D_vcf6.D_insert(testdata1[i], 2 ** 13 * (1 - 0.75), 2 ** 13 * (1 + 0.75))

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if D_vcf6.D_contains(testdata1[i], 2 ** 13 * (1 - 0.75), 2 ** 13 * (1 + 0.75)):
                D_vcf6_fp += 1
        D_vcf6_fp_result.append((D_vcf6_fp) / D_vcf6.size)

        D_vcf7 = VCuckooFilter14_7(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            D_vcf7.D_insert(testdata1[i], 2 ** 13 * (1 - 0.875), 2 ** 13 * (1 + 0.875))

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if D_vcf7.D_contains(testdata1[i], 2 ** 13 * (1 - 0.875), 2 ** 13 * (1 + 0.875)):
                D_vcf7_fp += 1
        D_vcf7_fp_result.append((D_vcf7_fp) / D_vcf7.size)

        D_vcf8 = VCuckooFilter14_7(capacity=capacity1[j] // 4, bucket_size=4, fingerprint_size=fingersize)
        for i in range(capacity1[j]):
            D_vcf8.D_insert(testdata1[i], 0, 2 ** 14)

        #  进行100% none existed的对象查询实验，以测试假阳性
        for i in range(capacity1[j]):
            if D_vcf8.D_contains(testdata1[i], 0, 2 ** 14):
                D_vcf8_fp += 1
        D_vcf8_fp_result.append((D_vcf8_fp) / D_vcf8.size)

print("cf")
print(np.mean(cf_fp_result))
print("   ")
print("   ")

print("Vcf7")
print(np.mean(vcf7_fp_result))
print("   ")
print("   ")

print("Vcf6")
print(np.mean(vcf6_fp_result))
print("   ")
print("   ")

print("Vcf5")
print(np.mean(vcf5_fp_result))
print("   ")
print("   ")

print("Vcf4")
print(np.mean(vcf4_fp_result))
print("   ")
print("   ")

print("Vcf3")
print(np.mean(vcf3_fp_result))
print("   ")
print("   ")

print("Vcf2")
print(np.mean(vcf2_fp_result))
print("   ")
print("   ")

print("Vcf1")
print(np.mean(vcf1_fp_result))
print("   ")
print("   ")

print("D_vcf1")
print(np.mean(D_vcf1_fp_result))
print("   ")
print("   ")

print("D_vcf2")
print(np.mean(D_vcf2_fp_result))
print("   ")
print("   ")

print("D_vcf3")
print(np.mean(D_vcf3_fp_result))
print("   ")
print("   ")

print("D_vcf4")
print(np.mean(D_vcf4_fp_result))
print("   ")
print("   ")

print("D_vcf5")
print(np.mean(D_vcf5_fp_result))
print("   ")
print("   ")

print("D_vcf6")
print(np.mean(D_vcf6_fp_result))
print("   ")
print("   ")

print("D_vcf7")
print(np.mean(D_vcf7_fp_result))
print("   ")
print("   ")

print("D_vcf8")
print(np.mean(D_vcf8_fp_result))
print("   ")
print("   ")


import sqlite3, json
from flask_restful import Resource, reqparse
from flask_jwt import jwt_required

class Item(Resource):
	item_parser = reqparse.RequestParser()
	# item_parser.add_argument(
	# 	'name',
	# 	type = str,
	# 	required = True,
	# 	help = "Null value, this is a required field.")
	item_parser.add_argument(
		'price',
		type = float,
		required = True,
		help = "Null value, this is a required field." )

	def find_item(self, name):
		"""
			This method is used to find an item by name in the database
			returns the item or none
		"""
		connection = sqlite3.connect('data.db')
		cursor = connection.cursor()
		sql_item = "SELECT * FROM items WHERE name = ?"

		row = cursor.execute(sql_item, (name,)).fetchone()
		# above is cleaner than:
		# rows = cursor.execute(sql_item, (name,))
		# row = rows.fetchone()
		#print(type(row)) <class 'tuple'>
		connection.close()
		if row:
			# this converts the tuple to a list
			# return json.dumps(row)
			# vs
			return {'id':row[0],'name':row[1],'price':row[2]}
		return None

		# return next(filter(lambda item: item['name'] == name, items), None)

	def insert_item(self, name, price):
		connection = sqlite3.connect('data.db')
		cursor = connection.cursor()
		sql_insert_item = "INSERT INTO items (name,price) VALUES (?, ?)"

		cursor.execute(sql_insert_item, (name, price,))
		connection.commit()
		connection.close()

	@jwt_required()
	def get(self, name):
		# when using an in memory database
		# lets see if we can swap out the storage without changing this method
		item = self.find_item(name)
		return {'item': item}, 200 if item else 404

	@jwt_required()
	def post(self, name):

		data = self.item_parser.parse_args()
		# data = request.get_json()
			# ways to deal with request payloads (content-type = application/json)
			# force=True  # deal with the junk data
			# silent=True # return null but not an error

		item_check = self.find_item(name)
		if item_check:
			return {'message':'Found existing item {}.'.format(item_check['name'])}, 400

		try:
			self.insert_item(name, data['price'])
		except:
			return {'message':'Error, failed to add item {}'.format(name)}, 500

		return {'message':'Item {} added.'.format(name)}, 201

	@jwt_required()
	def delete(self, name):
		# item_check = self.find_item(name)
		# if item_check is None:
		# 	return {'message':'Item {} does not exist.'.format(name)}, 400

		# global items
		# items = list(filter(lambda item: item['name'] != name, items))
		# return {'message':'Item {} has been deleted.'.format(name)}, 200

		connection = sqlite3.connect('data.db')
		cursor = connection.cursor()

		sql_delete_item = "DELETE FROM items WHERE name = ?"

		cursor.execute(sql_delete_item, (name,))
		connection.commit()
		connection.close()
		return {'message':'Item {} has been deleted.'.format(name)}, 200

	@jwt_required()
	def put(self, name):
		data = self.item_parser.parse_args()

		item = self.find_item(name)
		if item:
			try:
				self.update_item(item)
			except:
				return {'message':'Error, failed to update item {}'.format(item['name'])}, 500
			return {'message':'Item {} updated to price {}.'.format(item['name'],item['price'])}, 201
		else:
			try:
				self.insert_item(name, data['price'])
			except:
				return {'message':'Error, failed to add item {}'.format(name)}, 500
			return {'message':'Item {} added.'.format(name)}, 201

	def update_item(self, item):
		sql_update_item = "UPDATE items SET price = ? WHERE name = ?"
		connection = sqlite3.connect('data.db')
		cursor = connection.cursor()
		cursor.execute(sql_update_item, (item['price'],item['name'],))
		connection.commit()
		connection.close()

class Items(Resource):
	@jwt_required()
	def get(self):
		sql_items = "SELECT name, price FROM items"
		connection = sqlite3.connect('data.db')
		cursor = connection.cursor()
		rows = cursor.execute(sql_items)

		# items_list = [ {row['name']: row['price']} for row in rows ]
		items_list = [ {'name':row[0],'price':row[1]} for row in rows ]
		connection.close()
		return {'items': items_list}, 202


with open('../input.txt', 'r') as handle:
    text = handle.read().splitlines()
    nums = [ int(text[0]), int(text[1]), int(text[2]) ]
    previous_sum = sum(nums)
    times_increased = 0
    limit = len(text) - 2
    i = 1

    while i < limit:
        nums.append(int(text[i + 2]))

        current_sum = nums[i] + nums[i + 1] + nums[i + 2]
        if current_sum > previous_sum:
            times_increased += 1

        previous_sum = current_sum
        i += 1

    print(times_increased)


#!/usr/bin/env python3

from datetime import datetime
import time
import os
import json

# ToDo
# use it as a command line tool
# have a log file to calculate how many sessions one has done

def main():
    show_header()
    data = read_data() # it is called first because the user might want to see only the progress
    user, user_input = get_user()
    sleep_time(user_input)
    save_data(data, user_input)

def show_header():
    print("=======================")
    print("Welcome to PomFocal")
    print("=======================")

def get_user():
    user = input("What is your name?")
    print(f"Hello {user}")
    choice = ['Pomodoro', 'Long Break', 'Short Break']
    print("What do you wish? - 1. Pomodoro focused work, 2. Long Break and 3. Short Break")
    print(f"""{user} for
    Pomodoro focused work enter : 1
    Long Break enter : 2
    Short Break : 3 """)
    print(" ")
    user_input = input("What do you wish? ")
    return user,user_input

def sleep_time(user_input):
    now = datetime.now()
    if user_input == "1":
        time.sleep(25)
        print("Your Pomodoro session is over, it is time for a break.")
    if user_input == "2":
        time.sleep(15)
        print("Your Long Break is over, it is time for another Pomodoro session.")
    if user_input == "3":
        time.sleep(5)
        print("Your Short Break is over, it is time for another Pomodoro session.")

def read_data():
    # create a json file to keep the data
    # check if the file exists if no - return None
    # if yes - read the file, write new data in it and return the changed file

    directory = os.path.dirname(__file__)
    filename = os.path.join(directory, 'log.json')

    if not os.path.exists(filename):
        return {}
    else:
        with open (filename) as fobj:
           data = json.load(fobj)
           return data

def save_data(data, user_input):
    # check if today's date exists in data, if not create dictionary with default value,0
    # increase based on user input and save the data

    today = datetime.now().strftime("%Y-%B-%d")
    if not data.get(today):
        current_data = {'pomodoro':0,'long_break':0,'short_break':0}
    else:
        current_data = data.get(today)

    # Now we have the todays information we have to increase the changes in there
    # breakpoint()

    if user_input == '1':
        current_data['pomodoro'] +=1
    if user_input == '2':
        current_data['long_break'] +=1
    if user_input == '3':
        current_data['short_break'] +=1
    data[today] = current_data

    directory = os.path.dirname(__file__)
    filename = os.path.join(directory, 'log.json')

    with open(filename,"w") as fobj:
        json.dump(data,fobj)

if __name__ == "__main__":
    main()


from collections import deque

def solution(s):
    alphabet = {
        'zero': "0",
        'one': '1',
        'two': '2',
        'three': '3',
        'four': '4',
        'five': '5',
        'six': '6',
        'seven': '7',
        'eight': '8',
        'nine': '9',
    }
    alphabet = []
    s = deque(s)
    answer = ''
    temp = ''

    while s:
        i = s.popleft()
        if i.isdigit():
            answer += i

        else:
            temp += i
            if temp in alphabet:
                answer += alphabet[temp]
                temp = ''

    return int(''.join(answer))

num_dic = {"zero": "0", "one": "1", "two": "2", "three": "3", "four": "4",
           "five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9"}
def solution2(s):
    answer = s
    for key, value in num_dic.items():
        print(answer.replace(key, value))
        # answer = answer.replace(key, value)
    # return int(answer)
s = "2three45sixseven"
print(solution2(s))

숫자 문자열과 영단어.py


from model.basic import *

class MobileUnet(nn.Module):
    def __init__(self, in_channels=3, n_classes=2):

        super(MobileUnet, self).__init__()

        self.mobilenet_block = MobileNetBlock(in_channels)

        self.unet_block1 = UetBlock(320, 96, dilation=2)
        self.unet_block2 = UetBlock(192, 32, dilation=6)
        self.unet_block3 = UetBlock(64, 24, dilation=12)
        self.unet_block4 = UetBlock(48, 16, dilation=18)

        self.last_conv = nn.Sequential(
            nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1, bias=False),
            nn.BatchNorm2d(32),
            nn.Conv2d(32, n_classes, kernel_size=1, stride=1)
        )
        self._init_weight()

    def _init_weight(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
                nn.init.xavier_normal_(m.weight)
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def forward(self, x):

        e1, e2, e3, e4, feature_map = self.mobilenet_block(x)

        feature_map = self.unet_block1(e4, feature_map)
        feature_map = self.unet_block2(e3, feature_map)
        feature_map = self.unet_block3(e2, feature_map)
        feature_map = self.unet_block4(e1, feature_map)

        heat_map = self.last_conv(feature_map)

        heat_map = F.upsample(heat_map, scale_factor=2, mode='bilinear', align_corners=True)

        return F.sigmoid(heat_map)


import requests
from tkinter import *
from tkinter import messagebox

window = Tk()
window.geometry("500x500")
window.title("Weather App")
window.config(bg="black")

city = StringVar

def display_result():

    # initialize weather request from API
    try:
        get_city = city_entry.get()
        r = requests.get(
            "https://api.openweathermap.org/data/2.5/weather?q=" + get_city + "&appid=36e6aefc64df32f4ca03bd2cbd44d4d7")
        data = r.json()
        # display labels
        display_temp = Label(window, text=int(data['main']['temp'] - 273.15), font='Helvetica',
                                                                                fg="black",
                                 bg="white")
        display_temp.place(x=200, y=110)
        display_wind_speed = Label(window, text=str(data['wind']['speed']) + "KM/h",
        font='Helvetica',
                                   fg="black",
                                   bg="white")
        display_wind_speed.place(x=200, y=200)
        display_humidity = Label(window, text=str(data['main']['humidity']), font='Helvetica',
                                 fg="black",
                                 bg="white")
        display_humidity.place(x=200, y=150)
        display_cloud_cover = Label(window, text=str(data['weather'][0]['main'] + " skies"),
        font='Helvetica',
                                    fg="black",
                                    bg="white")
        display_cloud_cover.place(x=200, y=250)

    except KeyError:
         messagebox.showinfo("ERROR","PLEASE ENTER YOUR CITY")

def exiting():
    window.destroy()

# Widgets

city_entry=Entry(window, textvariable="city", bg="white")
city_entry.place(x=200, y=73, width=150)

label_Title = Label(window, text="WEATHER APPLICATION", bg="black", fg="white")
label_Title.place(x=200, y=10)
label_Choose = Label(window, text="Choose Location", bg="black", fg="white")
label_Choose.place(x=220, y=50)

label_Temperature = Label(window, text="Temperature", bg="black", fg="white")
label_Temperature.place(x=100, y=110)
label_Humidity = Label(window, text="Humidity", bg="black", fg="white")
label_Humidity.place(x=100, y=150)
label_Wind_speed = Label(window, text="Wind Speed", bg="black", fg="white")
label_Wind_speed.place(x=100, y=200)
label_Cloud_Cover = Label(window, text="Cloud Cover", bg="black", fg="white")
label_Cloud_Cover.place(x=100, y=250)
# Buttons
button_Display = Button(window, text="Display", bg="white", command=display_result)
button_Display.place(x=100, y=300)
# button_clear = Button(window, text="Clear", bg="white", )
# button_clear.place(x=200, y=300)
button_exit = Button(window, text="Exit", bg="white", command=exiting)
button_exit.place(x=300, y=300)
window.mainloop()


from bs4 import BeautifulSoup
import csv

"""
## Example program for processing an xml and saving information as a csv
Typically if we had an XML file already, we'd just process it and not convert.

However, serialization is a key part of Data Engineering & the ETL process,
so we will use this to help expand our ability to process one of the many
file formats available (XML/HTML) and our ability to create another (CSV).
"""

"""
### Tools/Acknowledgements
Using xml data from JAXB files. For Java Implementation see:
  http://www.vogella.com/articles/JAXB/article.html
More information on BeautifulSoup (an HTML/XML scrapper):
  https://www.crummy.com/software/BeautifulSoup/bs4/doc/#parsing-xml

Note - use of bookstore2.xml which has three book stores
"""

"""
### Steps (Algorithm):
----------------------
1. Load xml file into memory and pass to BeautifulSoup
2. Open a csv file for writing
3. Then write the header row
4. Then walk through the top_level items and pass as list to the
   csv writer
"""

xml_report = open('bookstores2.xml', 'r').read()
soup = BeautifulSoup(xml_report, "lxml")

#Open a csv for writing (not appending)
with open('bookstore_report.csv', 'w', newline='') as outfile:
  report = csv.writer(outfile, delimiter=",", quoting=csv.QUOTE_ALL)

  #write the header row
  report.writerow(['isbn', 'title', 'author', 'publisher',
                   'store', 'location'])
  #parse bookstore, create list of books, write to csv
  for bookstore in soup.findAll("bookstore"):
    books = bookstore.booklist
    for book in books:
      if book.name == "book": #i.e. don't write if no books
        report.writerow([
          book.get("isbn"),
          book.title.get_text(),
          book.author.get_text(),
          bookstore.publisher.get_text(),
          bookstore.store.get_text(),
          bookstore.location.get_text()])


import torch
import numpy as np
import torch.nn.functional as F

from torch import nn, Tensor

from einops.layers.torch import Rearrange, Reduce
from einops import rearrange, reduce, repeat

###########################################################################################################################
##### Building Blocks used in implementation1.py
###########################################################################################################################

class PatchEmbedding(nn.Module):
    def __init__(self, in_channels: int = 3, patch_size: int = 16, emb_size: int = 768, img_size: int = 224):

        self.patch_size = patch_size
        super().__init__()
        self.projection = nn.Sequential(
            # Use conv layer to directly extract patches and to linearly project them to the hidden dimension (latent query & key vector space)
            nn.Conv2d(in_channels, emb_size, kernel_size=patch_size, stride=patch_size),
            Rearrange('b e (h) (w) -> b (h w) e'),
        )

        self.cls_token = nn.Parameter(torch.randn(1,1, emb_size))
        self.positions = nn.Parameter(torch.randn((img_size // patch_size) **2 + 1, emb_size))

    def forward(self, x: Tensor) -> Tensor:

        b, _, _, _ = x.shape
        x = self.projection(x)
        cls_tokens = repeat(self.cls_token, '() n e -> b n e', b=b)

        # prepend the cls token to the input
        x = torch.cat([cls_tokens, x], dim=1)

        # add position embedding
        x += self.positions
        return x

class MultiHeadAttention(nn.Module):
    """
    PyTorch already has a nn.MultiheadAttention implementation.
    This class serves as an example for self-attention in multiple "heads".
    """
    def __init__(self, emb_size: int = 768, num_heads: int = 8, dropout: float = 0):
        super().__init__()
        self.emb_size = emb_size
        self.num_heads = num_heads
        self.qkv = nn.Linear(emb_size, emb_size * 3) # fuse the queries, keys and values in one matrix
        self.att_drop = nn.Dropout(dropout)
        self.projection = nn.Linear(emb_size, emb_size)

    def forward(self, x : Tensor, mask: Tensor = None) -> Tensor:

        # split keys, queries and values in num_heads
        qkv = rearrange(self.qkv(x), "b n (h d qkv) -> (qkv) b h n d", h=self.num_heads, qkv=3)
        queries, keys, values = qkv[0], qkv[1], qkv[2]

        # sum up products of query and key vectors over the last axis
        energy = torch.einsum('bhqd, bhkd -> bhqk', queries, keys) # batch, num_heads, query_len, key_len
        if mask is not None:
            fill_value = torch.finfo(torch.float32).min
            energy.mask_fill(~mask, fill_value)

        # attention weights
        scaling = self.emb_size ** (1/2)
        att = F.softmax(energy, dim=-1) / scaling
        att = self.att_drop(att)

        # sum up products of attention weights and value vectors over the third axis
        out = torch.einsum('bhal, bhlv -> bhav ', att, values)
        out = rearrange(out, "b h n d -> b n (h d)")

        # linear embedding
        out = self.projection(out)
        return out

class ResidualAdd(nn.Module):
    """
    Residual connection between layers.
    """
    def __init__(self, fn):
        super().__init__()
        self.fn = fn

    def forward(self, x, **kwargs):
        res = x
        x = self.fn(x, **kwargs)
        x += res
        return x

class FeedForwardBlock(nn.Sequential):
    """
    2-layer MLP with GELU (Gaussian Error Linear Units) activation function.
    The hidden dimension of the MLP is typically larger than the input/output layers. Here, this is achieved through the expansion factor of 4 on the embedding size.
    (Subclass nn.Sequential to avoid writing the forward method for each layer.)
    """
    def __init__(self, emb_size: int, expansion: int = 4, drop_p: float = 0.):
        super().__init__(
            nn.Linear(emb_size, expansion * emb_size),
            nn.GELU(),
            nn.Dropout(drop_p),
            nn.Linear(expansion * emb_size, emb_size),
        )

class TransformerEncoderBlock(nn.Sequential):
    """
    Encoder Block of a Transformer composed by a Multi-Head Self-Attention layer, an MLP layer, and additionally Residual Connections and Normalization Layers.
    """
    def __init__(self,
                 emb_size: int = 768,
                 drop_p: float = 0.,
                 forward_expansion: int = 4,
                 forward_drop_p: float = 0.,
                 ** kwargs):
        super().__init__(
            # MHSA
            ResidualAdd(nn.Sequential(
                nn.LayerNorm(emb_size),
                MultiHeadAttention(emb_size, **kwargs),
                nn.Dropout(drop_p)
            )),
            # MLP
            ResidualAdd(nn.Sequential(
                nn.LayerNorm(emb_size),
                FeedForwardBlock(
                    emb_size, expansion=forward_expansion, drop_p=forward_drop_p),
                nn.Dropout(drop_p)
            )
            ))

class TransformerEncoder(nn.Sequential):
    """
    In ViT only the Encoder part of the original transformer is used. The encoder is L blocks of TransformerBlock.
    """
    def __init__(self, depth: int = 12, **kwargs):
        super().__init__(*[TransformerEncoderBlock(**kwargs) for _ in range(depth)])

class ClassificationHead(nn.Sequential):
    """
    The last layer is a normal fully connected layer that gives the class probability. It first performs a basic mean over the whole sequence.
    """
    def __init__(self, emb_size: int = 768, n_classes: int = 1000):
        super().__init__(
            Reduce('b n e -> b e', reduction='mean'),
            nn.LayerNorm(emb_size),
            nn.Linear(emb_size, n_classes)) # Softmax/Sigmoid activation missing? nn.Linear layers do not output probabilities, but logits. Maybe it is used at some other point.

class ViT(nn.Sequential):
    """
    Vision Transformer Model:
    Input Image -> Patch Extraction & Linear Embedding -> Multi-Head Attention & MLP -> Classification Head
    """
    def __init__(self,
                in_channels: int = 3,
                patch_size: int = 16,
                emb_size: int = 768,
                img_size: int = 224,
                depth: int = 12,
                n_classes: int = 1000,
                **kwargs):
        super().__init__(
            PatchEmbedding(in_channels, patch_size, emb_size, img_size),
            TransformerEncoder(depth, emb_size=emb_size, **kwargs),
            ClassificationHead(emb_size, n_classes)
        )

###########################################################################################################################
##### Building Blocks used in implementation2.py
###########################################################################################################################

def patchify(images, n_patches):
    n, c, h, w = images.shape

    assert h == w, "Patchify method is implemented for square images only"

    patches = torch.zeros(n, n_patches ** 2, h * w // n_patches ** 2)
    patch_size = h // n_patches

    for idx, image in enumerate(images):
        for i in range(n_patches):
            for j in range(n_patches):
                patch = image[:, i * patch_size: (i + 1) * patch_size, j * patch_size: (j + 1) * patch_size]
                patches[idx, i * n_patches + j] = patch.flatten()
    return patches

def get_positional_embeddings(sequence_length, d):
    result = torch.ones(sequence_length, d)
    for i in range(sequence_length):
        for j in range(d):
            result[i][j] = np.sin(i / (10000 ** (j / d))) if j % 2 == 0 else np.cos(i / (10000 ** ((j - 1) / d)))
    return result

class MyMSA(nn.Module):
    """
    Multi-Head Self-Attention Class.
    By using loops instead of matrix multiplications, the computations are inefficient here, but good for learning purposes.
    """
    def __init__(self, d, n_heads=2):
        super(MyMSA, self).__init__()
        self.d = d
        self.n_heads = n_heads

        assert d % n_heads == 0, f"Can't divide dimension {d} into {n_heads} heads"

        d_head = int(d / n_heads)
        self.q_mappings = nn.ModuleList([nn.Linear(d_head, d_head) for _ in range(self.n_heads)])
        self.k_mappings = nn.ModuleList([nn.Linear(d_head, d_head) for _ in range(self.n_heads)])
        self.v_mappings = nn.ModuleList([nn.Linear(d_head, d_head) for _ in range(self.n_heads)])
        self.d_head = d_head
        self.softmax = nn.Softmax(dim=-1)

    def forward(self, sequences):
        # Sequences has shape (N, seq_length, token_dim)
        # We go into shape    (N, seq_length, n_heads, token_dim / n_heads)
        # And come back to    (N, seq_length, item_dim)  (through concatenation)
        result = []
        for sequence in sequences:
            seq_result = []
            for head in range(self.n_heads):
                q_mapping = self.q_mappings[head]
                k_mapping = self.k_mappings[head]
                v_mapping = self.v_mappings[head]

                seq = sequence[:, head * self.d_head: (head + 1) * self.d_head]
                q, k, v = q_mapping(seq), k_mapping(seq), v_mapping(seq)

                attention = self.softmax(q @ k.T / (self.d_head ** 0.5))
                seq_result.append(attention @ v)
            result.append(torch.hstack(seq_result))
        return torch.cat([torch.unsqueeze(r, dim=0) for r in result])

class MyViTBlock(nn.Module):
    """
    Encoder Block of a Transformer composed by a Multi-Head Self-Attention layer, an MLP layer, and additionally Residual Connections and Normalization Layers.
    """
    def __init__(self, hidden_d, n_heads, mlp_ratio=4):
        super(MyViTBlock, self).__init__()
        self.hidden_d = hidden_d
        self.n_heads = n_heads

        self.norm1 = nn.LayerNorm(hidden_d)
        self.mhsa = MyMSA(hidden_d, n_heads)
        self.norm2 = nn.LayerNorm(hidden_d)
        self.mlp = nn.Sequential(
            nn.Linear(hidden_d, mlp_ratio * hidden_d),
            nn.GELU(),
            nn.Linear(mlp_ratio * hidden_d, hidden_d)
        )

    def forward(self, x):
        out = x + self.mhsa(self.norm1(x))
        out = out + self.mlp(self.norm2(out))
        return out

class MyViT(nn.Module):
    def __init__(self, chw, n_patches=7, n_blocks=2, hidden_d=8, n_heads=2, out_d=10):
        super(MyViT, self).__init__()

        # Attributes
        self.chw = chw # input shape ( C , H , W )
        self.n_patches = n_patches
        self.n_blocks = n_blocks
        self.n_heads = n_heads
        self.hidden_d = hidden_d

        # Input and patch sizes
        assert chw[1] % n_patches == 0, "Input shape not entirely divisible by number of patches"
        assert chw[2] % n_patches == 0, "Input shape not entirely divisible by number of patches"
        self.patch_size = (chw[1] / n_patches, chw[2] / n_patches)

        # 1) Linear mapper
        self.input_d = int(chw[0] * self.patch_size[0] * self.patch_size[1])
        self.linear_mapper = nn.Linear(self.input_d, self.hidden_d)

        # 2) Learnable classification token
        self.class_token = nn.Parameter(torch.rand(1, self.hidden_d))

        # 3) Positional embedding
        self.pos_embed = nn.Parameter(get_positional_embeddings(self.n_patches ** 2 + 1, self.hidden_d).clone())
        self.pos_embed.requires_grad = False

        # 4) Transformer encoder blocks
        self.blocks = nn.ModuleList([MyViTBlock(hidden_d, n_heads) for _ in range(n_blocks)])

        # 5) Classification MLP
        self.mlp = nn.Sequential(
            nn.Linear(self.hidden_d, out_d),
            nn.Softmax(dim=-1)
        )

    def forward(self, images):
        # Dividing images into patches
        n, c, h, w = images.shape
        patches = patchify(images, self.n_patches).to(self.pos_embed.device)

        # Map the vector corresponding to each patch to the hidden dimension
        tokens = self.linear_mapper(patches)

        # Adding classification token
        tokens = torch.stack([torch.vstack((self.class_token, tokens[i])) for i in range(len(tokens))])

        # Adding positional embedding
        pos_embed = self.pos_embed.repeat(n, 1, 1)
        out = tokens + pos_embed

        # Transformer Blocks
        for block in self.blocks:
            out = block(out)

        # Getting the classification token only
        out = out[:, 0]

        return self.mlp(out) # Map to output dimension, output category distribution


import random
from abc import ABC, abstractmethod
from collections import namedtuple
from typing import Optional

import pandas as pd
import sqlalchemy as sa

from .db_util import TempTable

CMU = namedtuple(
    "CMU",
    ["category", "measurement", "unit", "age", "race", "sex"],
    defaults=["cases", "cumulative", "people", "all", "all", "all"]
)

class DatasetBase(ABC):
    autodag: bool = True
    data_type: str = "general"
    table_name: str

    def __init__(self):
        pass

    def extract_cat_measurement_unit(self, df, cmu):
        """
        Adds columns "category", "measurement", and "unit" to df

        Parameters
        ----------
        df : pd.DataFrame
            This DataFrame must have the column `variable` and the
            unique elements of `variable` must be keys in the
            `cmu_dict`
        cmu : dict(str -> CMU)
            This dictionary maps variable names into a subcategory,
            measurement, and unit using a CMU namedtuple

        Returns
        -------
        df : pd.DataFrame
            A copy of the DataFrame passed in that has new columns
            "category", "measurement", and "unit"
        """
        return df.assign(
            category=df["variable"].map(lambda x: cmu[x].category),
            measurement=df["variable"].map(lambda x: cmu[x].measurement),
            unit=df["variable"].map(lambda x: cmu[x].unit),
            age=df["variable"].map(lambda x: cmu[x].age),
            race=df["variable"].map(lambda x: cmu[x].race),
            sex=df["variable"].map(lambda x: cmu[x].sex),
        )

    @abstractmethod
    def put(self, conn, df):
        pass

    def _retrieve_dt(self, tz="US/Eastern"):
        out = pd.Timestamp.utcnow().tz_convert(tz).normalize().tz_localize(None)

        return out

    def _retrieve_vintage(self):
        return pd.Timestamp.utcnow().floor("h")

        pass

class DatasetBaseNoDate(DatasetBase, ABC):
    get_needs_date = False

    @abstractmethod
    def get(self):
        raise NotImplementedError("Must be implemented by subclass")

class DatasetBaseNeedsDate(DatasetBase, ABC):
    get_needs_date = True

    @abstractmethod
    def get(self, date: str):
        raise NotImplementedError("Must be implemented by subclass")

    def transform_date(self, date: pd.Timestamp) -> pd.Timestamp:
        return date

    def quit_early(self, date: pd.Timestamp) -> bool:
        return False

def _build_on_conflict_do_nothing_query(
        df: pd.DataFrame, t_home: str, t_temp: str, pk: str
    ):
    colnames = ", ".join(list(df))
    cols = "(" + colnames + ")"
    if not pk.startswith("("):
        pk = f"({pk})"

    return f"""
    INSERT INTO data.{t_home} {cols}
    SELECT {colnames} from {t_temp}
    ON CONFLICT {pk} DO NOTHING;
    """

class InsertWithTempTable(DatasetBase, ABC):
    pk: str

    def _insert_query(
            self, df: pd.DataFrame, table_name: str, temp_name: str, pk: str
        ):

        out = _build_on_conflict_do_nothing_query(df, table_name, temp_name, pk)
        return out

    def _put(self, connstr: str, df: pd.DataFrame, table_name: str, pk: str):
        temp_name = "__" + table_name + str(random.randint(1000, 9999))

        with sa.create_engine(connstr).connect() as conn:
            kw = dict(temp=False, if_exists="replace", destroy=True)

            with TempTable(df, temp_name, conn, **kw):
                sql = self._insert_query(df, table_name, temp_name, pk)
                conn.execute(sql)

    def put(self, connstr: str, df=None):
        if df is None:
            if hasattr(self, "df"):
                df = self.df
            else:
                raise ValueError("No df found, please pass")

        if not hasattr(self, "pk"):
            msg = "field `pk` must be set on subclass of OnConflictNothingBase"
            raise ValueError(msg)

        self._put(connstr, df, self.table_name, self.pk)


import time as t
import sys
import netifaces as ni
import random
import datetime
import threading
import uuid

from cassandra.cluster import Cluster
from cassandra.policies import DCAwareRoundRobinPolicy
from datetime import datetime as dt
from datetime import date

# Table Creation
#CREATE TABLE Reservation(reservation_id uuid, seans_id int, seat_number int, node varchar, room int, seat_row varchar, time timestamp, PRIMARY KEY ((seans_id),seat_number,seat_row));
#CREATE TABLE ReservationNode(reservation_id uuid, node varchar, seans_id int, seat_number int, seat_row varchar, PRIMARY KEY (reservation_id));
#CREATE TABLE AvailableSeat(id varchar primary key, seans_id int, seat_number int, seat_row varchar);
#Create Table Seans(seans_id int Primary Key, film_name text, date text, room int, all_place_occupied boolean);

# Create Table Rooms(room int Primary Key, capacity int, numberOfRows int); #ulatwienie dziala tylko kidy sale maja ta sama ilosc miejsc w kazdym rzedzie
# room 2 razy nie jest potrzebne ale wydaje mi sie e dla wygody moze zostac

#Inserts
#Insert into Rooms(room, capacity, numberOfRows) values (1, 20, 4);
#Insert into Reservation(reservation_id,seans_id,seat_number,node, room,seat_row,time) values (1,1,3,'192.168.0.15',1,'C', TIME);
#Insert into ReservationNode(reservation_id,node,seans_id,seat_number,seat_row) values (1,'192.168.0.15',1,3,'C');
#Insert into Seans(seans_id, film_name, date, room, all_place_occupied) values (1,'joker','20:00 : 3.12.2019',1,false);

def PrintSeanses():
    seanses = session.execute('SELECT *  FROM Seans')

    #places = session.execute("select * from Rooms")
    for s in seanses:
        reservations = session.execute(
            "select count(*) from reservation where seans_id=%s", [s.seans_id]) #not most optimal if there are a lot of senses, but good for testing
        print ("ID: "+str(s.seans_id)+" Film: "+s.film_name +"  Date: " +s.date+"  Room: " +str(s.room) +" reservations: " +str(reservations[0].count))

def GetLastReservationID():
    latestentry=session.execute('SELECT Max(reservation_id)  FROM Reservation ')
   # print(" last "+str(latestentry[0])) #not most elegant...mona sprbowac loswac id zamaiast dawac kolejne
    return latestentry[0].system_max_reservation_id

def GetLastSeansID():
    latestentry=session.execute('SELECT Max(seans_id)  FROM Seans ')
    #print(" last "+str(latestentry[0].system_max_seans_id)) #not most elegant...mona sprbowac loswac id zamaiast dawac kolejne
    return latestentry[0].system_max_seans_id

def GetRandomReservationID():
    id = uuid.uuid1()
    return id

def RegisterSeans(filmname, newdate, roomnumber):
    seansid = GetLastSeansID()
    if (seansid != None): seansid = seansid + 1
    else: seansid = 1

    session.execute("""Insert into Seans(seans_id, film_name, date, room, all_place_occupied)
    values (%(seans_id)s,%(film_name)s,%(date)s,%(room)s,%(all_place_occupied)s)""",
                    {'seans_id': seansid, 'film_name': filmname, 'date': newdate, 'room': roomnumber,
                     'all_place_occupied': False})

    room = session.execute("Select * from rooms where room=%s ", [roomnumber])
    seats_per_row =room[0].capacity/ room[0].numberofrows
    for row in range(0,room[0].numberofrows):
        for seat in range(1, int(seats_per_row)+1):
            session.execute("""Insert into AvailableSeat(id, seans_id, seat_number, seat_row) values (%(id)s,%(seans_id)s,%(seat_number)s,%(seat_row)s)""",                {'id': str(seansid)+chr(65+row)+str(seat), 'seans_id': seansid, 'seat_number': seat, 'seat_row': chr(65+row)})
    print("you've added seans")

def PrintSeansSeatsWithReservations(selected_seans):

    reservations = session.execute("Select * from reservation where seans_id =%s", [selected_seans])

    if(reservations==[]): #printing empty room
        return

    rooms = session.execute("Select * from Rooms where room=%s ", [reservations[0].room])

    print(" Room: "+str( [reservations[0].room]))
    reserved_places = []
    for r in reservations:
        reserved_places.append((ord(r.seat_row) - 65, r.seat_number,))

    #   print("seans: " + str(r.seans_id) + "  Room: " + str(r.room))

    number_of_seats_in_row = rooms[0].capacity / rooms[0].numberofrows
    number_of_seats_in_row = number_of_seats_in_row + 1
    for row in range(0, rooms[0].numberofrows):
        for seat in range(1, int(number_of_seats_in_row)):
            empty = True
            for ra, rb in reserved_places:
                # print(ra,rb)
                if row == ra and seat == rb:
                    print(" " + chr(65 + row) + str(seat) + "X ", end="", flush=True)
                    empty = False

            if (empty):
                print(" " + chr(65 + row) + str(seat) + " ", end="", flush=True)  # ascii translation.. not safest
        print("\n")

def Make_Reservation(selected_seans,row,seat, nodeid):
    room = session.execute("Select * from Seans where seans_id=%(seans_id)s", {'seans_id' : selected_seans})
    if not room:return #seans
    rooms = session.execute("Select * from Rooms where room=%s", [room[0].room])
    number_of_seats_in_row = rooms[0].capacity / rooms[0].numberofrows

    if seat>number_of_seats_in_row: return

    rowexist=0

    for rowcount in range(0, rooms[0].numberofrows):
        if row==chr(65 + rowcount): rowexist=1
    if rowexist==0: return

    wanted_seat=session.execute("select * from reservation where seans_id=%(seans_id)s and seat_number=%(seat)s and seat_row=%(row)s",{'seans_id' : selected_seans, 'seat' : seat,'row' : row})

    if wanted_seat==[]: #add checking if seat exists ?
        new_id = GetRandomReservationID()
        #if (new_id != None): new_id = new_id + 1
        #else: new_id = 1
        seanses = session.execute('SELECT * FROM Seans where seans_id=%s', [selected_seans])

       #making sure that got latest id
        # while True:
        #     new_id = GetLastReservationID()
        #     new_id = new_id + 1
        #     it = 0
        #     check_reservationid = session.execute(
        #         "select * from reservationnode where reservation_id=%(reservation_id)s",
        #         {'reservation_id': new_id})
        #
        #     for check in check_reservationid:
        #         it = it + 1
        #     if it == 0:
        #         break

        print(nodeid + " making...reservation " + str(new_id))

        #no timestamps here I think last write wins here
        session.execute("""Insert into ReservationNode(reservation_id,node,seans_id,seat_number,seat_row) values (%(reservation_id)s,%(node)s,%(seans_id)s,%(seat_number)s,%(seat_row)s)""",  {'reservation_id': new_id,'node' : nodeid,'seans_id': selected_seans,'seat_number': seat, 'seat_row': row})
        t.sleep(0.1)

        #check_reservation = session.execute(
        #    "select * from reservation where reservation_id=%(reservation_id)s",
        #   {'reservation_id': new_id})
        check_reservation = session.execute(
             "select * from reservationnode where reservation_id=%(reservation_id)s",
           {'reservation_id': new_id})

        if check_reservation[0].node == nodeid: #check if reservation is not doubled

            session.execute("""Insert into Reservation(reservation_id,seans_id,seat_number,node,room ,seat_row, time)
                                    values (%(reservation_id)s,%(seans_id)s,%(seat_number)s,%(node)s,%(room)s,%(seat_row)s,%(time)s)""",
                            {'reservation_id': new_id, 'seans_id': selected_seans, 'seat_number': seat,
                             'node': nodeid, 'room': seanses[0].room, 'seat_row': row, 'time': dt.now()})
            session.execute("delete from AvailableSeat where id=%(id)s",
                            {'id': str(selected_seans) + str(row) + str(seat)})

            t.sleep(0.1)
            check_reservation2 = session.execute(
                "select * from reservation where seat_row=%(seat_row)s and seat_number=%(seat_number)s and seans_id = %(seans_id)s",
                {'seat_row': row, 'seat_number': seat, 'seans_id': selected_seans})

            it=0
            for check in check_reservation2:
                it=it+1

            if it>1:
                #nawet jeeli nigdy tu nie wchodzi to teoretycznie moze i trzeba prownujac timestamp anulowac
                Cancel_Reservation(new_id,nodeid)
                print("note: reservation cancelled due to timestamp")
                return False
            else:

                print("reservation complete")
                return True

        #else :
         #   print("Failed to make reservation try again")

   #else :
    return False

def Cancel_Reservation(reservation_id, nodeid):
    print("cancelling starting.........................................")
    reservation_id=uuid.UUID(reservation_id)
    wanted_seat=session.execute("select * from reservationnode where reservation_id=%(reservation_id)s",{'reservation_id' : reservation_id})
    if not wanted_seat: return
    check_reservation2 = session.execute(
                "select * from reservation where seat_row=%(seat_row)s and seat_number=%(seat_number)s and seans_id = %(seans_id)s",
                {'seat_row': wanted_seat[0].seat_row, 'seat_number': wanted_seat[0].seat_number, 'seans_id': wanted_seat[0].seans_id})

    it=0
    for check in check_reservation2:
        it=it+1

    if it>1:
       max_time=session.execute("select max(time) from reservation where seans_id=%(seans_id)s and seat_number=%(seat_number)s and seat_row=%(seat_row)s",{'seans_id' : check_reservation2[0].seans_id, 'seat_number' : check_reservation2[0].seat_number, 'seat_row' : check_reservation2[0].seat_row})
       session.execute("delete from reservation where seans_id=%(seans_id)s and seat_number=%(seat_number)s and seat_row=%(seat_row)s and time=%(time)s",{'seans_id' : check_reservation2[0].seans_id, 'seat_number' : check_reservation2[0].seat_number, 'seat_row' : check_reservation2[0].seat_row, 'time' : max_time[0].time})
       session.execute("delete from reservationnode where reservation_id=%(reservation_id)s",{'reservation_id' : check_reservation2[0].reservation_id})
    else:
         if wanted_seat[0].node!=str(nodeid):
            print("can't remove reservation, this node didn't make reservation")
            return
         session.execute("""Insert into AvailableSeat(id, seans_id, seat_number, seat_row) values (%(id)s, %(seans_id)s,%(seat_number)s,%(seat_row)s)""",                {'id': str(wanted_seat[0].seans_id)+ str(wanted_seat[0].seat_row)+str(wanted_seat[0].seat_number),'seans_id': wanted_seat[0].seans_id, 'seat_number': wanted_seat[0].seat_number, 'seat_row': wanted_seat[0].seat_row})
         session.execute("delete from reservation where seans_id=%(seans_id)s and seat_number=%(seat_number)s and seat_row=%(seat_row)s",{'seans_id' : wanted_seat[0].seans_id, 'seat_number' : wanted_seat[0].seat_number, 'seat_row' : wanted_seat[0].seat_row})
         session.execute("delete from reservationnode where reservation_id=%(reservation_id)s",{'reservation_id' : reservation_id})
    print("reservation %s canceled!!!",[reservation_id])

def Force_Cancel_Reservation(reservation_id):
    print("cancelling starting!!!")
    reservation_id = uuid.UUID(reservation_id)
    wanted_seat = session.execute("select * from reservationnode where reservation_id=%(reservation_id)s",
                                  {'reservation_id': reservation_id})
    if not wanted_seat: return

    session.execute(
        """Insert into AvailableSeat(id, seans_id, seat_number, seat_row) values (%(id)s, %(seans_id)s,%(seat_number)s,%(seat_row)s)""",
        {'id': str(wanted_seat[0].seans_id) + str(wanted_seat[0].seat_row) + str(wanted_seat[0].seat_number),
         'seans_id': wanted_seat[0].seans_id, 'seat_number': wanted_seat[0].seat_number,
         'seat_row': wanted_seat[0].seat_row})
    session.execute(
        "delete from reservation where seans_id=%(seans_id)s and seat_number=%(seat_number)s and seat_row=%(seat_row)s",
        {'seans_id': wanted_seat[0].seans_id, 'seat_number': wanted_seat[0].seat_number,
         'seat_row': wanted_seat[0].seat_row})
    session.execute("delete from reservationnode where reservation_id=%(reservation_id)s",
                    {'reservation_id': reservation_id})

class TestThread (threading.Thread) :
    def __init__(self, seans , ip):
        threading.Thread.__init__(self)
        self.seans=seans
        self.ip=ip

    def run(self):
        print("starting thread with ipnode :" + self.ip)
        stressTestFunction1(self.seans, self.ip)

# class TestThread2 (threading.Thread) :
#     def __init__(self, seans , ip, numberOf):
#         threading.Thread.__init__(self)
#         self.seans=seans
#         self.ip=ip
#         self.numberOf=numberOf
#
#
#     def run(self):
#         print("starting thread with ipnode :" + self.ip)
#         stressTestFunction3(self.seans, self.ip,self.numberOf)

#function for removing random
# def stressTestFunction3(seansid,ip,numberOf) :
#     time_start = dt.now().time()
#     se = session.execute("Select * from seans where seans_id =%s ", [seansid])
#     if se != []:
#         reservations = session.execute("select reservation_id from reservation where seans_id=%s", [seansid])
#         array_available=[]
#         for row in reservations:
#          array_available.append(row[0])
#          #print("to free " + str(row[0]))
#
#         for x in array_available :
#             print("to free "+ str(x))

def stressTestFunction2(seansid,ip): #seats in order
    time_start = dt.now().time()
    se = session.execute("Select * from seans where seans_id =%s ", [seansid])
    if se != []:
        room = session.execute("Select * from rooms where room=%s ", [se[0].room])
        seats_per_row = room[0].capacity / room[0].numberofrows
        seats_per_row = seats_per_row + 1

        notcompleted = 0
        #while (reservationscount[0].count < room[0].capacity):
        for row in range(0,room[0].numberofrows):
            for seat in range(1,int(seats_per_row)):
                status = Make_Reservation(seansid, chr(65+row), seat,
                                          ip)
                if status == False:
                    notcompleted = notcompleted + 1
                    print("seat was already reserved.......")

        time_end = dt.now().time()
        time = dt.combine(datetime.date.today(), time_end) - dt.combine(datetime.date.today(), time_start)
        print("Thread: " + ip + " time: ", time)
        print("Thread: " + ip + " not completed reservations: ", notcompleted)

def stressTestFunction1(seansid,ip): #seats random

    time_start = dt.now().time()
    se = session.execute("Select * from seans where seans_id =%s ", [seansid])
    if se != []:
        room = session.execute("Select * from rooms where room=%s ", [se[0].room])
        seats_per_row = room[0].capacity / room[0].numberofrows
        seats_per_row = seats_per_row + 1
        reservationscount = session.execute("select count(*) from reservation where seans_id=%s", [seansid])
        fill_array = session.execute("select * from AvailableSeat")
        array_available = []
        for row in fill_array:
            if row.id.startswith(str(seansid)):
                array_available.append(row.id)

        notcompleted = 0
        while (reservationscount[0].count < room[0].capacity):
            rand_seat = random.choice(array_available)
            rand_seat_row = session.execute("select * from AvailableSeat where id=%s", [rand_seat])
            if rand_seat_row != []:
                status = Make_Reservation(seansid, rand_seat_row[0].seat_row, rand_seat_row[0].seat_number,
                                          ip)
                if status == True:
                    array_available.remove(rand_seat)
                else:
                    notcompleted = notcompleted + 1
                    print("seat was already reserved...please select another one")
            reservationscount = session.execute("select count(*) from reservation where seans_id=%s", [seansid])
        time_end = dt.now().time()
        time = dt.combine(datetime.date.today(), time_end) - dt.combine(datetime.date.today(), time_start)
        print("Thread: "+ip + " time: ", time)
        print("Thread: "+ip + " not completed reservations: ", notcompleted)

def DisplayOptions () :
    print("0 - help")
    print("-1 - exit")
    print("1 - see all seanses")
    print("2 - see all seats for selected seans")
    print("3 - add new seans")
    print("4 - make reservation")
    print("5 - cancel reservation")
    print("6 - stress test")

cluster = Cluster(['10.10.0.1', '10.10.0.2'])
interface='eth1'

print("connecting to database")
session = cluster.connect('project') #make sure it's connected

print("connected")

print("Welcome to Cinema Reservation System")

print("What do you want do do (press 0 to see options) :")

choice=0
ni.ifaddresses(interface)
nodeid=ni.ifaddresses(interface)[ni.AF_INET][0]['addr']

while (choice!=-1) :
    choice=int(input("awaiting key:  "))

    if(choice==0):
        DisplayOptions();
    elif(choice==1):
        PrintSeanses()
    elif(choice==2):
        seans=int(input("type seans_id:  "))
        PrintSeansSeatsWithReservations(seans)
    elif (choice == 3):
        film=str(input("type film name:  "))
        date=str(input("type date:  "))
        room=int(input("type room number:  "))
        RegisterSeans(film,date,room)
    elif (choice == 4):
        reservation_choice = int(input("type number of reservations you want make or type 0 to reserve all seats  "))
        if (reservation_choice == 0):
            seans = int(input("type  seans id:  "))
            time_start=dt.now().time()
            se = session.execute("Select * from seans where seans_id =%s ", [seans])
            if se!=[]:
                room = session.execute("Select * from rooms where room=%s ", [se[0].room])
                seats_per_row =room[0].capacity/ room[0].numberofrows
                seats_per_row=seats_per_row+1
                reservationscount = session.execute("select count(*) from reservation where seans_id=%s", [seans])

                fill_array=session.execute("select * from AvailableSeat")
                array_available=[]
                for row in fill_array:
                    if row.id.startswith(str(seans)):
                       array_available.append(row.id)

                notcompleted=0

                while(reservationscount[0].count<room[0].capacity):
                    rand_seat=random.choice(array_available)
                    rand_seat_row=session.execute("select * from AvailableSeat where id=%s", [rand_seat])
                    if rand_seat_row != []:
                       status = Make_Reservation(seans, rand_seat_row[0].seat_row, rand_seat_row[0].seat_number, nodeid)
                       if status==True:
                          array_available.remove(rand_seat)
                       else:
                          notcompleted=notcompleted+1
                          print("seat was already reserved...please select another one")
                    reservationscount = session.execute("select count(*) from reservation where seans_id=%s", [seans])

            time_end=dt.now().time()
            time = dt.combine(datetime.date.today(),time_end) - dt.combine(datetime.date.today(),time_start)
            print("time: ",time)
            print("not completed reservations: ", notcompleted)
        else :
                 seans = int(input("type  seans id:  "))
                 for i in range(reservation_choice):
                    row = str(input("type selected row:  "))
                    seat = int(input("type selected seat:  "))
                    status = Make_Reservation(seans,row,seat, nodeid)
                    if (status==False):
                       fill_array=session.execute("select * from AvailableSeat")
                       array_available=[]
                       startswith=str(seans)+str(row)
                       for row in fill_array:
                           if row.id.startswith(startswith):
                              array_available.append(row.id)
                       if (len(array_available)==0):
                          for row in fill_array:
                              if row.id.startswith(str(seans)):
                                 array_available.append(row.id)
                       if (len(array_available)==0):
                          print("seat was already reserved...please select another one in other seans")
                       else:
                          rand_seat=random.choice(array_available)
                          rand_seat_row=session.execute("select * from AvailableSeat where id=%s", [rand_seat])
                          print("seat was already reserved...please select another one..."+str(rand_seat_row[0].seat_row)+str(rand_seat_row[0].seat_number)+" is available")

    elif(choice==5):
        can_id = input("type reservation id that you want to cancel:  ")
        Cancel_Reservation(can_id, nodeid)
    elif(choice==6):

        RegisterSeans('Test', '00:00:0000 :0:0', 1)
        test_seans_id1 = GetLastSeansID()
        thread1 = TestThread(test_seans_id1, '10.10.0.3')
        thread2 = TestThread(test_seans_id1, '10.10.0.4')

        thread1.start()
        thread2.start()

        RegisterSeans('Test2', '00:00:0000 :0:0', 1)
        test_seans_id2 = GetLastSeansID()
        thread3 = TestThread(test_seans_id2, '10.10.0.5')
        thread4 = TestThread(test_seans_id2, '10.10.0.6')
        thread5 = TestThread(test_seans_id2, '10.10.0.7')

        thread3.start()
        thread4.start()
        thread5.start()

        RegisterSeans('Test3', '00:00:0000 :0:0', 1)
        test_seans_id3 = GetLastSeansID()
        thread6 = TestThread(test_seans_id3, '10.10.0.9')
        thread7 = TestThread(test_seans_id3, '10.10.0.10')
        thread8 = TestThread(test_seans_id3, '10.10.0.11')
        thread9 = TestThread(test_seans_id3, '10.10.0.12')
        thread10 = TestThread(test_seans_id3, '10.10.0.13')

        thread6.start()
        thread7.start()
        thread8.start()
        thread9.start()
        thread10.start()

        #t.sleep(7)

        RegisterSeans('Test4', '00:00:0000 :0:0', 1)
        test_seans_id4 = GetLastSeansID()

        thread11 = TestThread(test_seans_id4, '10.10.0.13')
        thread12 = TestThread(test_seans_id4, '10.10.0.14')
        thread13 = TestThread(test_seans_id4, '10.10.0.15')

        thread11.start()
        thread12.start()
        thread13.start()

    elif (choice == 7):
        seans_id = int(input("type seans id that you want to display:  "))
        seans_rows = session.execute("select seans_id,seat_row,seat_number,reservation_id from reservation where seans_id=%s;", [seans_id])

        for sr in seans_rows:
            print(str(sr[0]) +" | "+sr[1]+" : "+str(sr[2]) + " -> "+str(sr[3]))

    elif (choice ==8):
        threadarray=[]
        RegisterSeans('Test5', '00:00:0000 :0:0', 1)
        test_seans_id5 = GetLastSeansID()
        for i in range(1,1000):
            ip="10.10.0.%d" % (i+13)
       	    thread=TestThread(test_seans_id5,ip)
            threadarray.append(thread)
       	for thr in threadarray:
            thr.start()

    else :
        continue


import graphene
from graphene_django.types import DjangoObjectType
from .models import Service

class ServiceType(DjangoObjectType):
    class Meta:
        model = Service

class Query(graphene.ObjectType):
    services = graphene.List(ServiceType)

    def resolve_services(self, info, **kwargs):
        return Service.objects.all()


# PFAM: Pretrained_Feature_Attention_Module
import torch
import torch.nn as nn
import torch.nn.functional as F
from .block.MFCSAM import SELayer,mfcsa_module_layer_2,mfcsa_module_layer_4

def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)

class PFAM(nn.Module):

    def __init__(self, layer1_channel, layer3_channel, conv_kernels = [3, 5, 7, 9], conv_groups = [1, 4, 8, 16]):
        super().__init__()

        self.conv1_ = conv1x1(layer1_channel, layer1_channel)

        # MFCSAM
        self.att_mfcsam_2_x1 = mfcsa_module_layer_2(layer1_channel, layer1_channel, stride=1, conv_kernels=conv_kernels,
                                                    conv_groups=conv_groups)
        self.att_mfcsam_4_x1 = mfcsa_module_layer_4(layer1_channel, layer1_channel, stride=1, conv_kernels=conv_kernels,
                                                 conv_groups=conv_groups)
        self.att_mfcsam_2 = mfcsa_module_layer_2(layer3_channel, layer3_channel, stride=1, conv_kernels=conv_kernels,
                                                 conv_groups=conv_groups)
        self.att_mfcsam_4 = mfcsa_module_layer_4(layer3_channel, layer3_channel, stride=1, conv_kernels=conv_kernels,
                                                 conv_groups=conv_groups)

    def forward(self, input):
        x_1 = input[0]
        batch_size_1, channels_1, height_1, width_1 = x_1.shape
        x_2 = input[1]
        x_3 = input[2]

        batch_size_3, channels_3, height_3, width_3 = x_3.shape

        x_1_atten = self.att_mfcsam_2_x1(x_1)
        x_1_conv = self.conv1_(x_1)
        x_1 = x_1_conv + x_1_atten

        x_3 = self.att_mfcsam_2(x_3)

        output = [x_1, x_2, x_3]
        return output


lista = [3, 5 , 8 , 9, 1, 2]

primero, *los_demas = lista
diferencia = []

for value in los_demas:
    calculo = abs(value - primero)
    diferencia.append(calculo)

# lo nuevo. obtención del menor
menor = min(diferencia)
donde_esta_el_menor = diferencia.index(menor)
el_numero_mas_cerca_del_primero = los_demas[donde_esta_el_menor]

print(f'los datos originales:{lista}')
print(f'El primero es:{primero}')
print(f'las diferencias respecto al primero son:{diferencia}')
print(el_numero_mas_cerca_del_primero)