from app.config.mysqlconnection import connectToMySQL
from flask import flash
from app import  DATABASE
from app.models.user import User

class Recipe:
    def __init__(self, data):
        self.id = data["id"]
        self.name = data["name"]
        self.description = data["description"]
        self.instructions = data["instructions"]
        self.date_made = data["date_made"]
        self.under_thirty = data["under_thirty"]
        self.user_id = data["user_id"]
        self.created_at = data["created_at"]
        self.updated_at = data["updated_at"]

    @classmethod
    def create(cls, data):
        query = "INSERT INTO recipes (name, description, instructions, date_made, under_thirty, user_id) VALUES (%(name)s,%(description)s,%(instructions)s,%(date_made)s,%(under_thirty)s,%(user_id)s);"

        return connectToMySQL(DATABASE).query_db(query, data)   #returns an id

    @classmethod
    def get_all_recipes_with_users(cls):
        query = "SELECT * FROM recipes JOIN users on recipes.user_id = users.id"

        results = connectToMySQL(DATABASE).query_db(query) # list of dicts with all data from both tables

        #now we want to
        list_recipes = []
        for row in results:
            current_recipe = cls(row)
            user_data = {
                **row,
                "created_at": row["users.created_at"],
                "updated_at": row["users.updated_at"],
                "id": row["users.id"]
            }

            current_user = User( user_data)         #user in that recipe
            current_recipe.user = current_user      #add instance attribute to this recipe of that user
            list_recipes.append( current_recipe )   #append this instance into a list (of all other recipes with users attributes added)

        return list_recipes

    @classmethod
    def get_one_with_user(cls, data):
        query = "SELECT * FROM recipes JOIN users on recipes.user_id = users.id WHERE recipes.id = %(id)s"
        results = connectToMySQL(DATABASE).query_db(query, data) # list of one result of the right id

        if len(results) > 0:
            current_recipe = cls( results[0])
            user_data = {
                **results[0],
                "created_at": results[0]["users.created_at"],
                "updated_at": results[0]["users.updated_at"],
                "id": results[0]["users.id"]
            }
            current_recipe.user = User(user_data)
            return current_recipe
        else:
            return None

    # @app.route("/recipes/<int:id>/update")
    # def display_updated_recipe(id):

    @staticmethod
    def validate_recipe(data):
        is_valid = True

        if data["name"] == "":
            flash("Name must not be empty", "error_recipe_name")
            is_valid = False
        if data["description"] == "":
            flash("description must not be empty", "error_recipe_description")
            is_valid = False
        if data["instructions"] == "":
            flash("instructions must not be empty", "error_recipe_instructions")
            is_valid = False
        if data["date_made"] == "":
            flash("date made must not be empty", "error_recipe_date_made")
            is_valid = False
        if len(data["name"]) < 3:
            flash("name must be at least 3 chars long", "error_recipe_name")
            is_valid = False
        if len(data["description"]) < 3:
            flash("description must be at least 3 chars long", "error_recipe_description")
            is_valid = False
        if len(data["instructions"]) < 3:
            flash("instructions must be at least 3 chars long", "error_recipe_instructions")
            is_valid = False

        return is_valid


import os
from googleapiclient.discovery import build
import json
from .twitter_classifier.classifier import predict
from .yt_request import get_id_from_url, service, APIkey

def filter_for_comments(json):
    '''FILTERS ONLY Comment texts OUT OF DICT AND RETURNS comments in dataframe as tweet'''
    # CREATE EMPTY DICT
    tweet = ""
    data = []
    # ITERATE OVER COMMENTS
    for item in json['items']:
        # GET RELEVANT DATA
        tweet = item["snippet"]["topLevelComment"]["snippet"]["textOriginal"]
    # FILL IN THE OUTPUT DICT
        data.append({'tweet': tweet})
        # IF THERE ARE REPLIES ADD THESE TO THE EXPORT DATA
        if "replies" in item:
            for reply in item["replies"]["comments"]:
                # REPLY COMMENTS HAVE ADDITIONAL KEYS reply_no & parent_comment
                tweet = reply["snippet"]["textOriginal"]
                data.append({
                    'tweet': tweet
                })
    return data

# MAKES A GET REQUEST AND RETURNS A DICT/JSON

def get_all_vid_data(vidID, MAX_REQUEST_NUMBER = 20):
    '''makes MAX_REQUEST_NUMBER of requests, filters for comments text and returns dataframe'''
    number_of_requests = 1

    request = service.commentThreads().list(
        part="snippet, replies",
        videoId=vidID,
        maxResults=100
    )
    response = request.execute()
    data = filter_for_comments(response)

    while response.get("nextPageToken") and number_of_requests <= MAX_REQUEST_NUMBER:
        number_of_requests += 1
        request = service.commentThreads().list(
            part="snippet, replies",
            videoId=vidID,
            maxResults=100,
            pageToken=response.get("nextPageToken")
        )
        response = request.execute()
        data.extend(filter_for_comments(response))

    return data

def get_prediction(vidID, MAX_REQUEST_NUMBER = 20, hate=10, threshold=0.6):
    '''It makes MAX_REQUEST_NUMBER of requests, predict those comments and displays hate comments with highest predictions. Prediction are only valid above a threshold probability.'''
    prediction = predict(get_all_vid_data(vidID, MAX_REQUEST_NUMBER), hate, threshold)
    return prediction


import random
def sort(isreverse):
    a = [int(random.random() * 100) for _ in range(int(input('количество элементов списка: ')))]
    for j in range(len(a)):
        maxa = 0
        for i in range(len(a) - j):
            if a[i] > maxa:
                maxa = a[i]
        a.append(a.pop(a.index(maxa)))
        #print(a)                                   это можно использовать для отслеживания изменения списка
    if isreverse:
        a = a[::1]
    else:
        a = a[::-1]
    return a
def binary():
    a = [25, 6, 4, 18, 32, 64, 124]
    print(a)
    while len(a) != 1:
        if a[len(a) // 2] > a[len(a) // 2 - 1]:
            a = a[:len(a) // 2:]
        else:
            a = a[len(a) // 2::]
    print(a[0])
if __name__ == '__main__':
    i = int(input('1 - сортировка рандомного списка\n 2 - бинарный поиск'))
    if i == 1:
        print(sort(True))
    elif i == 2:
        binary()


from custom_exceptions import *  # Empty classes for exceptional errors

"""
input:
peter@gmail.com
petergmail.com
"""

data = input()
domains = (".com", ".bg", ".net", ".org")  # container for domains

while not data == "End":  # in input examples there is no End, but from description should be in code

    if '@' not in data:
        raise MustContainAtSymbolError("Email must contain @")          # MustContainAtSymbolError

    name, domain_part = data.split("@")

    if len(name) < 4:
        raise NameTooShortError("Name must be more than 4 characters")  # NameTooShortError

    # comment this, before uncomment code bellow and vise versa
    flag = any([True for _ in domains if domain_part.endswith(_)])  # check for present domain with dot
    # flag = False                                                  # in the end of domain part
    # for _ in domains:
    #     if domain_part.endswith(_):           # same without list comprehension
    #         flag = True

    if not flag:                                                         # InvalidDomainError
        raise InvalidDomainError("Domain must be one of the following: .com, .bg, .org, .net")

    print("Email is valid")
    data = input()

"""
output:
Email is valid
Traceback (most recent call last):
  File ".\email_validator.py", line 18, in <module>
    raise MustContainAtSymbolError("Email must contain @")
__main__.MustContainAtSymbolError: Email must contain @
"""


from datetime import datetime
from abc import ABC
from abc import abstractmethod
from typing import List
import logging
from pyAutomation.DataObjects.PointReadOnlyAbstract import PointReadOnlyAbstract
from pyAutomation.DataObjects.PointAbstract import PointAbstract

class i2cPrototype(ABC):

    def __init__(self, name: str, logger: str) -> None:
        self.device_points = []  # type: List[PointAbstract]
        self._has_write_data = False  # type: bool
        self.last_io_attempt = datetime.now()  # type: datetime.datetime
        self.is_setup = False
        self.name = name
        self._logger = None
        self.logger = logging.getLogger(logger)
        self.logger.debug(
          "created device %s using logger %s",
          self.name,
          logger,
        )
        self.delay_until = None

    @abstractmethod
    def read_data(self):
        pass

    @abstractmethod
    def write_data(self):
        pass

    @abstractmethod
    def setup(self):
        pass

    @abstractmethod
    def config(self):
        pass

    def _get_name(self) -> str:
        return self._name

    def _set_name(self, name: str) -> None:
        self._name = name

    name = property(_get_name, _set_name)

    def _get_logger(self):
        return self._logger

    def _set_logger(self, logger) -> None:
        self._logger = logger

    logger = property(_get_logger, _set_logger)

    @property
    def interrupt_points(self) -> List[PointReadOnlyAbstract]:
        return []

    @property
    def has_write_data(self) -> bool:
        if self.delay_until is not None:
            if self.delay_until < datetime.now():
                self.delay_until = None
            else:
                return False

        if hasattr(self, '_has_write_data'):
            return self._has_write_data
        else:
            return False

    @property
    def next_update(self) -> datetime:
        if self.delay_until is not None:
            if self.delay_until < datetime.now():
                self.delay_until = None
            else:
                return self.delay_until

        next_point = "no point"
        next_update = datetime.max
        if self.device_points is not None:
            for p in self.device_points:
                if p is not None:
                    next_update_time = p.next_update

                    if next_update_time is None:
                        continue
                    else:
                        if next_update_time < next_update:
                            next_update = next_update_time
                            next_point = p.name

        if datetime.max == next_update:
            next_update = None

        self.logger.debug(
          "next update for: %s is %s (%s)",
          self.name,
          next_update,
          next_point,
        )

        return next_update


from json import load, dump

def get_stored_username():
    """Get stored username if available."""
    filename = "username.json"
    try:
        with open(filename) as f_obj:
            username = load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """Prompt for a new username."""
    username = input("What is your name? ")
    filename = "username.json"
    with open(filename, "w") as file_object:
        dump(username, file_object)
    return username

def greet_user():
    """Load the username, if it has been stored previously.
    Otherwise, prompt for the username and store it."""
    username = get_stored_username()
    current_user = input(f"Is this your username: {username}, 'yes' or 'no'? ")
    if current_user == "no":
        username = get_new_username()
    else:
        if username:
            print(f"Welcome back, {username}!")
        else:
            username = get_new_username()
            print(f"Next time you login, we will remember you, {username}")

if __name__ == "__main__":
    greet_user()


from QuoteEngine.IngestorInterface import IngestorInterface
from QuoteEngine.QuoteModel import QuoteModel

class TextImporter(IngestorInterface):
    """Module to read TXT files"""

    allowed_extensions = ["txt"]

    @classmethod
    def parse(cls, path: str):
        """Parse the TXT files containing the quotes."""
        if not cls.can_ingest(path):
            raise Exception(f"File type not supported for {path}")

        quotes = []

        with open(path, 'r') as f:
            lines = f.readlines()

        for line in lines:
            body = line.split("-")[0].strip().strip('"')
            author = line.split("-")[1].strip()
            new_quote = QuoteModel(body, author)
            quotes.append(new_quote)
        return quotes


import eul

def eul23():
    """Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers."""
    upper = 28123
    abundants = set([x for x in range(12, upper) if sum(eul.get_proper_divisors(x)) > x])
    abundant_sums = set([(i + j) for i in abundants for j in abundants if i+j < upper])
    return sum(set([x for x in range(1, upper)]) - abundant_sums)

print(eul23())
# 4179871


"""
20. 有效的括号
给定一个只包括 '('，')'，'{'，'}'，'['，']'的字符串，判断字符串是否有效。

有效字符串需满足：

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true
示例2:

输入: "()[]{}"
输出: true
示例3:

输入: "(]"
输出: false
示例4:

输入: "([)]"
输出: false
示例5:

输入: "{[]}"
输出: true

"""

class Solution:
    def isValid(self, s: str) -> bool:

        dict = {'(':')',
                '{':'}',
                '[':']'}
        stack = []
        for char in s:
            if char in dict:
                stack.append(dict[char])
            else:
                if len(stack) != 0:
                    top_element = stack.pop()
                    if char != top_element:
                        return False
                    else:
                        continue
                else:
                    return False
        return len(stack) == 0

solution = Solution()
result = solution.isValid("}{")
print(result)


#! /usr/bin/env python3

"""
markdowndoc.py

Written by Patrick Laban and Geremy Condra

Licensed under GPLv3

Released 28 April 2009

This module contains a simple class to output Markdown-style
pydocs.
"""

import pydoc, inspect, re, builtins

class MarkdownDoc(pydoc.TextDoc):

	underline = "*" * 40

	def process_docstring(self, obj):
		"""Get the docstring and turn it into a list."""
		docstring = pydoc.getdoc(obj)
		if docstring:
			return docstring + "\n\n"
		return ""

	def process_class_name(self, name, bases, module):
		"""Format the class's name and bases."""
		title = "## class " + self.bold(name)
		if bases:
			# get the names of each of the bases
			base_titles = [pydoc.classname(base, module) for base in bases]
			# if its not just object
			if len(base_titles) > 1:
				# append the list to the title
				title += "(%s)" % ", ".join(base_titles)
		return title

	def process_subsection(self, name):
		"""format the subsection as a header"""
		return "### " + name

	def docclass(self, cls, name=None, mod=None):
		"""Produce text documentation for the class object cls."""

		# the overall document, as a line-delimited list
		document = []

		# get the object's actual name, defaulting to the passed in name
		name = name or cls.__name__

		# get the object's bases
		bases = cls.__bases__

		# get the object's module
		mod = cls.__module__

		# get the object's MRO
		mro = [pydoc.classname(base, mod) for base in inspect.getmro(cls)]

		# get the object's classname, which should be printed
		classtitle = self.process_class_name(name, bases, mod)
		document.append(classtitle)
		document.append(self.underline)

		# get the object's docstring, which should be printed
		docstring = self.process_docstring(cls)
		document.append(docstring)

		# get all the attributes of the class
		attrs = []
		for name, kind, classname, value in pydoc.classify_class_attrs(cls):
			if pydoc.visiblename(name):
				attrs.append((name, kind, classname, value))

		# sort them into categories
		data, descriptors, methods = [], [], []
		for attr in attrs:
			if attr[1] == "data" and not attr[0].startswith("_"):
				data.append(attr)
			elif attr[1] == "data descriptor" and not attr[0].startswith("_"):
				descriptors.append(attr)
			elif "method" in attr[1] and not attr[2] is builtins.object:
				methods.append(attr)

		if data:
			# start the data section
			document.append(self.process_subsection(self.bold("data")))
			document.append(self.underline)

			# process your attributes
			for name, kind, classname, value in data:
				if hasattr(value, '__call__') or inspect.isdatadescriptor(value):
					doc = getdoc(value)
				else:
					doc = None
				document.append(self.docother(getattr(cls, name), name, mod, maxlen=70, doc=doc) + '\n')

		if descriptors:
			# start the descriptors section
			document.append(self.process_subsection(self.bold("descriptors")))
			document.append(self.underline)

			# process your descriptors
			for name, kind, classname, value in descriptors:
				document.append(self._docdescriptor(name, value, mod))

		if methods:
			# start the methods section
			document.append(self.process_subsection(self.bold("methods")))
			document.append(self.underline)

			# process your methods
			for name, kind, classname, value in methods:
				document.append(self.document(getattr(cls, name), name, mod, cls))

		return "\n".join(document)

	def bold(self, text):
		""" Formats text as bold in markdown. """
		if text.startswith('_') and text.endswith('_'):
			return "__\%s\__" %text
		elif text.startswith('_'):
			return "__\%s__" %text
		elif text.endswith('_'):
			return "__%s\__" %text
		else:
			return "__%s__" %text

	def indent(self, text, prefix=''):
		"""Indent text by prepending a given prefix to each line."""
		return text

	def section(self, title, contents):
		"""Format a section with a given heading."""
		clean_contents = self.indent(contents).rstrip()
		return "# " + self.bold(title) + '\n\n' + clean_contents + '\n\n'

	def docroutine(self, object, name=None, mod=None, cl=None):
		"""Produce text documentation for a function or method object."""
		realname = object.__name__
		name = name or realname
		note = ''
		skipdocs = 0
		if inspect.ismethod(object):
			object = object.__func__
		if name == realname:
			title = self.bold(realname)
		else:
			if (cl and realname in cl.__dict__ and cl.__dict__[realname] is object):
				skipdocs = 1
			title = self.bold(name) + ' = ' + realname
		if inspect.isfunction(object):
			args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann = inspect.getfullargspec(object)
			argspec = inspect.formatargspec(
				args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann,
				formatvalue=self.formatvalue,
				formatannotation=inspect.formatannotationrelativeto(object))
			if realname == '<lambda>':
				title = self.bold(name) + ' lambda '
				# XXX lambda's won't usually have func_annotations['return']
				# since the syntax doesn't support but it is possible.
				# So removing parentheses isn't truly safe.
				argspec = argspec[1:-1] # remove parentheses
		else:
			argspec = '(...)'
		decl = "#### " + "def " + title + argspec + ':' + '\n' + note

		if skipdocs:
			return decl + '\n'
		else:
			doc = pydoc.getdoc(object) or ''
			return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n')

	def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None):
		"""Produce text documentation for a data object."""
		line = "#### " + object.__name__ + "\n"
		line += super().docother(object, name, mod, parent, maxlen, doc)
		return line + "\n"

	def _docdescriptor(self, name, value, mod):
		results = ""
		if name: results += "#### " + self.bold(name) + "\n"
		doc = pydoc.getdoc(value) or ""
		if doc: results += doc + "\n"
		return results


"""Unittest for Main."""
# !/usr/bin/python
# -*- coding: utf-8 -*-
from unittest.mock import patch, DEFAULT

import config
import main
import config_test

@patch.multiple('main',
                # get_kibana=DEFAULT,
                # get_opsview=DEFAULT,
                # get_card_reboot=DEFAULT,
                # picup_traffic_check=DEFAULT,
                # post_jsnap=DEFAULT,
                # compare_jsnap=DEFAULT,
                auto_ticket=DEFAULT,
                # insert_data_to_history=DEFAULT,
                # shutdown_pic=DEFAULT,
                # uptime_check=DEFAULT,
                # traffic_check_by_hour=DEFAULT,
                # history_check=DEFAULT,
                # insert_data_to_error_devices=DEFAULT,
                # pre_jsnap=DEFAULT,
                # reboot_pic=DEFAULT
                )
def test(
    # get_kibana,
    # get_opsview,
    # get_card_reboot,
    # picup_traffic_check,
    # post_jsnap,
    # compare_jsnap,
    auto_ticket,
    # traffic_check_by_hour,
    # insert_data_to_history,
    # shutdown_pic,
    # uptime_check,
    # history_check,
    # insert_data_to_error_devices,
    # pre_jsnap,
    # reboot_pic
):
    """Process 1+2-Test case 1."""
    # get data
    # get_kibana.return_value = config_test.KIBANA
    # get_opsview.return_value = []
    # get_card_reboot.return_value = [{'log_message': 'SPD_CONN_OPEN_FAILURE', 'card': '11/0/0', 'device_name': 'HNI-MX960-LAB',
    #                                  'fpc_slot': '11', 'device_ip': '118.70.0.137', 'time_stamp': '2018-12-26 8:50:00', 'pic_slot': '0'}]
    # traffic_check_by_hour.return_value = config_test.traffic_check_by_hour(
    #     True)
    # uptime_check.return_value = config_test.uptime_check(True)

    # insert_data_to_error_devices.return_value = None
    # # history check = Falsel
    # history_check.return_value = False
    # # pre jsnap = False
    # pre_jsnap.return_value = {'result': True}
    # # shutdown pic = True
    # shutdown_pic.return_value = config_test.shutdown_pic(True)
    # # reboot pic = True
    # reboot_pic.return_value = config_test.reboot_pic(True)
    # insert_data_to_history.return_value = None
    auto_ticket.return_value = 2222
    # # picup_traffic_check = True
    # picup_traffic_check.return_value = config_test.picup_traffic_check(True)
    # # post_jsnap = True
    # post_jsnap.return_value = {'result': True}
    # # compare_jsnap = True
    # compare_jsnap.return_value = {'result': True}
    # run
    main.main(config)

if __name__ == '__main__':
    test()


from django.conf.urls import url

from .views import facebook, add_date, post_date, update_project, post_project, select_supply, post_supply

"""URL routing for views.py"""

urlpatterns = [
    url('^facebook', facebook, name='Facebook'),
    url(r'^date', add_date, name='due_date'),
    url(r'^post_date', post_date, name='post_date'),
    url(r'^project', update_project, name='update_project'),
    url(r'^post_project', post_project, name='post_date'),
    url(r'^pattern', select_supply, name='select_pattern'),
    url(r'^post_supply', post_supply, name='post_supply'),
    url(r'^material', select_supply, name='select_material')
]


import cv2
import numpy as np
from math import pi, cos, sin

def conv1D(inSignal: np.ndarray, kernel1: np.ndarray) -> np.ndarray:
    """
    Convolve a 1-D array with a given kernel
    :param inSignal: 1-D array
    :param kernel1: 1-D array as a kernel
    :return: The convolved array
    """
    flip_kernel = kernel1[::-1]
    kernel_len = len(kernel1)
    signal_longer = inSignal

    # padding with zeros the inSignal arr:
    for i in range(kernel_len - 1):
        signal_longer = np.insert(signal_longer, 0, 0)
        signal_longer = np.append(signal_longer, 0)

    new_img = np.zeros(len(inSignal) + kernel_len - 1)
    for i in range(kernel_len + len(inSignal) - 1):
        new_img[i] = ((flip_kernel * signal_longer[i:kernel_len + i]).sum())

    return new_img

def conv2D(inImage: np.ndarray, kernel2: np.ndarray) -> np.ndarray:
    """
    Convolve a 2-D array with a given kernel
    :param inImage: 2D image
    :param kernel2: A kernel
    :return: The convolved image
    """
    flip_kernel = np.flipud(np.fliplr(kernel2))
    kernel_row = flip_kernel.shape[0]
    kernel_col = flip_kernel.shape[1]

    new_img = np.zeros_like(inImage)
    padded_img = padded_replicate(inImage, kernel_row, kernel_col)

    for x in range(inImage.shape[0]):
        for y in range(inImage.shape[1]):
            new_img[x, y] = (padded_img[x: x + kernel_col, y: y + kernel_row] * flip_kernel).sum()
            if flip_kernel.sum() != 0:
                new_img[x, y] /= flip_kernel.sum()

    return new_img

def padded_replicate(inImage: np.ndarray, kernel_row: int, kernel_col: int) -> np.ndarray:
    add_row = int((kernel_row - 1) / 2)
    add_col = int((kernel_col - 1) / 2)

    padded_img = np.zeros((inImage.shape[0] + kernel_row - 1, inImage.shape[1] + kernel_col - 1))
    padded_img[kernel_row - 2:-(kernel_row - 2), kernel_col - 2:-(kernel_col - 2)] = inImage

    up_row = padded_img[add_row]
    down_row = padded_img[-add_row - 1]
    padded_img_flip = np.flipud(np.fliplr(padded_img))
    left_col = padded_img_flip[add_col]
    right_col = padded_img_flip[-add_col - 1]

    for i in range(add_row):
        padded_img[i] = up_row
        padded_img[-i] = down_row
    for j in range(add_col):
        for row in range(padded_img.shape[0]):
            padded_img[row, j] = left_col[row]
            padded_img[row, -j] = right_col[-row]

    return padded_img

def convDerivative(inImage: np.ndarray) -> (np.ndarray, np.ndarray, np.ndarray, np.ndarray):
    """
    Calculate gradient of an image
    :param inImage: Grayscale image
    :return: (directions, magnitude, x_der, y_der)
    """
    kernel_x = np.array([[0, 0, 0], [1, 0, -1], [0, 0, 0]])
    kernel_y = np.array([[0, 1, 0], [0, 0, 0], [0, -1, 0]])

    # derivative by rows:
    Ix = cv2.filter2D(inImage, -1, kernel_x)  # , borderType=cv2.BORDER_REPLICATE

    # derivative by columns:
    Iy = cv2.filter2D(inImage, -1, kernel_y)

    eps = 0.0000000001
    magnitude = pow(Ix ** 2 + Iy ** 2, 0.5)
    direction = np.arctan(Iy / (Ix + eps))

    return direction, magnitude, Ix, Iy

# bonus:
def blurImage1(in_image: np.ndarray, kernel_size: np.ndarray) -> np.ndarray:
    """
    Blur an image using a Gaussian kernel
    :param in_image: Input image
    :param kernel_size: Kernel size
    :return: The Blurred image
    """
    size = kernel_size[0]
    sigma = 1
    x, y = np.mgrid[-size:size + 1, -size:size + 1]
    normal = 1 / (2.0 * np.pi * sigma ** 2)
    g = np.exp(-((x ** 2 + y ** 2) / (2.0 * sigma ** 2))) * normal
    in_image = cv2.filter2D(in_image, -1, g)
    return in_image

def blurImage2(in_image: np.ndarray, kernel_size: np.ndarray) -> np.ndarray:
    """
    Blur an image using a Gaussian kernel using OpenCV built-in functions
    :param in_image: Input image
    :param kernel_size: Kernel size
    :return: The Blurred image
    """
    gaussian_kernel = cv2.getGaussianKernel(kernel_size[0], sigma=0)
    out_img = cv2.filter2D(in_image, -1, gaussian_kernel)
    return out_img

def edgeDetectionSobel(img: np.ndarray, thresh: float = 0.7) -> (np.ndarray, np.ndarray):
    """
    Detects edges using the Sobel method
    :param img: Input image
    :param thresh: The minimum threshold for the edge response
    :return: opencv solution, my implementation
    """
    img = cv2.GaussianBlur(img, (3, 3), 0)

    Gx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
    Gy = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
    thresh = thresh * 255

    smooth_x = cv2.filter2D(img, -1, Gx, borderType=cv2.BORDER_REPLICATE).astype(float)
    smooth_y = cv2.filter2D(img, -1, Gy, borderType=cv2.BORDER_REPLICATE).astype(float)

    my_sobel_image = np.sqrt(smooth_x ** 2 + smooth_y ** 2)

    sobel_x = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3)
    sobel_y = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3)
    cv_ans = np.sqrt(sobel_x ** 2 + sobel_y ** 2)

    change_by_thresh(my_sobel_image, thresh)
    change_by_thresh(cv_ans, thresh)

    return cv_ans, my_sobel_image

def change_by_thresh(img: np.ndarray, thresh: float = 0.7):
    for x in range(img.shape[0]):
        for y in range(img.shape[1]):
            if img[x, y] >= thresh:
                img[x, y] = 255
            else:
                img[x, y] = 0

def edgeDetectionZeroCrossingLOG(img: np.ndarray) -> np.ndarray:
    """
    Detecting edges using the "ZeroCrossingLOG" method
    :param img: Input image
    :return: :return: Edge matrix
    """

    # smooth the image with a Gaussian filter:
    img = img.astype(np.float)
    smooth_img = cv2.GaussianBlur(img, (3, 3), 0)

    # convolve the smoothed image with the Laplacian filter:
    kernel_laplacian = np.array([[0, 1, 0],
                                 [1, -4, 1],
                                 [0, 1, 0]])
    derive2_img = cv2.filter2D(smooth_img, -1, kernel=kernel_laplacian,
                               borderType=cv2.BORDER_REPLICATE)  # ddepth=cv2.CV_16S,

    # find the following patterns {-,0,+} or {-,+} :
    edge_img = np.zeros_like(derive2_img)
    row, col = img.shape
    for x in range(1, row - 1):
        for y in range(1, col - 1):
            wind = derive2_img[x - 1:x + 2, y - 1:y + 2]
            wind_max = wind.max()
            wind_min = wind.min()
            pixel = derive2_img[x, y]
            if pixel == 0.0 and wind_min <= 0.0 <= wind_max != wind_min:
                edge_img[x, y] = 255
            elif (wind_min <= 0.0 <= pixel != wind_min) or (pixel < 0.0 < wind_max != pixel):
                edge_img[x, y] = 255
            else:
                edge_img[x, y] = 0

    return edge_img

def edgeDetectionCanny(img: np.ndarray, thrs_1: float, thrs_2: float) -> (np.ndarray, np.ndarray):
    """
    Detecting edges usint "Canny Edge" method
    :param img: Input image
    :param thrs_1: T1
    :param thrs_2: T2
    :return: opencv solution, my implementation
    """
    # smooth the image with a Gaussian filter:
    smooth_img = cv2.GaussianBlur(img, (3, 3), 0)

    # Compute the partial derivatives Ix, Iy, and magnitude and direction of the gradient:
    directions, magnitude, Ix, Iy = convDerivative(smooth_img)
    angle = np.degrees(directions)
    magnitude = (magnitude / magnitude.max()) * 255

    # non maximum suppression:
    edge_img = np.zeros_like(magnitude)
    M, N = img.shape
    for i in range(1, M - 1):
        for j in range(1, N - 1):
            ni1 = ni2 = magnitude[i, j]
            # angle 0
            if (0 <= angle[i, j] < 22.5) or (157.5 <= angle[i, j] <= 180):
                ni1 = magnitude[i, j + 1]
                ni2 = magnitude[i, j - 1]
            # angle 45
            elif 22.5 <= angle[i, j] < 67.5:
                ni1 = magnitude[i + 1, j - 1]
                ni2 = magnitude[i - 1, j + 1]
            # angle 90
            elif 67.5 <= angle[i, j] < 112.5:
                ni1 = magnitude[i + 1, j]
                ni2 = magnitude[i - 1, j]
            # angle 135
            elif 112.5 <= angle[i, j] < 157.5:
                ni1 = magnitude[i - 1, j - 1]
                ni2 = magnitude[i + 1, j + 1]
            if (magnitude[i, j] >= ni1) and (magnitude[i, j] >= ni2):
                edge_img[i, j] = magnitude[i, j]
            else:
                edge_img[i, j] = 0

    # hysteresis:
    strong_edges = np.zeros_like(edge_img)
    for x in range(M):
        for y in range(N):
            if edge_img[x, y] > thrs_1:
                strong_edges[x, y] = edge_img[x, y]

    for x in range(M):
        for y in range(N):
            if edge_img[x, y] <= thrs_2:
                edge_img[x, y] = 0
            if thrs_2 < edge_img[x, y] <= thrs_1:
                if strong_edges[x - 1, y] == strong_edges[x + 1, y] == strong_edges[x, y - 1] == strong_edges[
                    x, y + 1] == strong_edges[x - 1, y - 1] == strong_edges[x + 1, y + 1] == strong_edges[
                    x + 1, y - 1] == strong_edges[x - 1, y + 1] == 0:
                    edge_img[x, y] = 0

    cv_ans = cv2.Canny(img, thrs_2, thrs_1)
    return cv_ans, edge_img

def houghCircle(img: np.ndarray, min_radius: float, max_radius: float) -> list:
    """
    Find Circles in an image using a Hough Transform algorithm extension
    :param img: Input image
    :param min_radius: Minimum circle radius
    :param max_radius: Maximum circle radius
    :return: A list containing the detected circles,
    [(x,y,radius),(x,y,radius),...]
    """

    canny_cv, canny_my = edgeDetectionCanny(img, 200, 100)
    edges = []

    for x in range(canny_cv.shape[0]):
        for y in range(canny_cv.shape[1]):
            if canny_cv[x, y] == 255:
                edges.append((x, y))

    thresh = 0.47  # at least 47% of the pixels of a circle must be detected
    steps = 100  # number of samples from each circle

    points = []
    for r in range(min_radius, max_radius + 1):
        for t in range(steps):
            alpha = 2 * pi * t / steps
            x = int(r * cos(alpha))
            y = int(r * sin(alpha))
            points.append((x, y, r))

    temp_circles = {}  # dict{circle center, radius: counter}
    for x, y in edges:  # iterate the pixels of the edges:
        for dx, dy, r in points:
            b = x - dx
            a = y - dy
            count = temp_circles.get((a, b, r))
            if count is None:
                count = 0
            temp_circles[(a, b, r)] = count + 1

    # now add the appropriate circles to the ans list:
    circles = []
    sorted_temp = sorted(temp_circles.items(), key=lambda i: -i[1])
    for circle, counter in sorted_temp:
        x, y, r = circle
        # once a circle has been selected, we reject all the circles whose center is inside that circle
        if counter / steps >= thresh and all((x - xc) ** 2 + (y - yc) ** 2 > rc ** 2 for xc, yc, rc in circles):
            circles.append((x, y, r))

    return circles


import requests
import os
import csv
import json
from pprint import pprint

PATH = os.path.dirname(__file__)
DATA = "SYMBOL_chart.json"
DATAPATH = os.path.join(PATH, DATA)

def api_call(ticker):
    try:
        response = requests.get('https://api.iextrading.com/1.0/stock/{}/chart'.format(ticker))
        payload = response.json()
        return payload
    except ValueError:
        return False

def api_download():
    data = {}
    while True:
        ticker = input("enter a ticker symbol or q to quit ")
        payload = api_call(ticker)
        if ticker.lower() == "q":
            print("done")
            break
        elif not payload:
            print("please try again ")
            continue
        else:
            with open(DATA, "w+") as json_file:
                columns = ['date', 'open', 'high', 'low', 'close', 'volume', 'unadjustedVolume', 'change', 'changePercent', 'vwap', 'label' , 'changeOverTime']
                writer = csv.DictWriter(json_file, fieldnames=columns)
                data[ticker] = payload
                json.dump(data, json_file)

if __name__ == "__main__":
    api_download()
#goog, aapl, tsla


import os
dirname = os.path.dirname(__file__)

from qiskit.algorithms.optimizers import SPSA
import torch
from torch.autograd import Variable
from sklearn.ensemble import IsolationForest
import numpy as np

import sys
sys.path.append(os.path.join(dirname, '../../'))
from modules.classical_autoencoder.classical_autoencoder import ClassicalAutoencoder
from modules.preprocessing.preprocessing import preprocess, sample_training_data, sample_vqc_training_data
from modules.QVC_autoencoder.utils import OptimizerLog, get_classification_probabilities

sys.path.append(os.path.join(dirname, '../../../HAE_demonstrator'))
from train.models import TrainJob

class QVCAutoencoder:
	def __init__(self, qc_index=0, custom_qc={}, job=None, max_iter=100, loss_value_classical=0.023, n_samples=150):
		path_cl = f'../../data/training_results/classical/training_result_loss_{loss_value_classical}.pt'
		self.cae = ClassicalAutoencoder()
		self.cae.load_state_dict(torch.load(os.path.join(dirname, path_cl)))
		self.cae.eval()

		fit_data = Variable(torch.FloatTensor(sample_training_data(1000)[0]))
		fit_data_latent = self.cae.get_latent_space_state(fit_data).tolist()
		self.if_model = IsolationForest().fit(fit_data_latent)

		self.max_iter = max_iter
		self.n_samples = n_samples
		self.job = job
		self.log = OptimizerLog(job)
		self.optimizer = SPSA(maxiter=max_iter, callback=self.log.update)
		self.qc_index = qc_index
		self.custom_qc = custom_qc

	def loss_function_multiclass(self, theta):
		cost = 0
		x, labels = sample_vqc_training_data(self.n_samples, True)
		x = self.cae.get_latent_space_state(Variable(torch.FloatTensor(x))).tolist()

		classifications = get_classification_probabilities(x,theta, self.qc_index, self.custom_qc)
		for i, classification in enumerate(classifications):
			p = classification.get(labels[i])
			cost += -np.log(p + 1e-10)
		cost /= len(x)
		return cost

	def loss_function_binary(self, theta):
		cost = 0
		x, labels = sample_vqc_training_data(self.n_samples, True)
		labels = np.array(labels)
		labels = np.where(labels>3, 1, 0)
		x = self.cae.get_latent_space_state(Variable(torch.FloatTensor(x))).tolist()

		classifications = get_classification_probabilities(x,theta, self.qc_index, self.custom_qc, True)
		for i, classification in enumerate(classifications):
			p = classification.get(labels[i])
			cost += -np.log(p + 1e-10)
		cost /= len(x)
		return cost

	def train(self, initial_point, is_binary=False):
		if is_binary:
			loss_func = self.loss_function_binary
		else:
			loss_func = self.loss_function_multiclass

		print(f"Training Started. \n Data points in Data set: {self.n_samples} \n Max Iter: {self.max_iter}")

		result = self.optimizer.minimize(loss_func, initial_point)
		opt_theta = result.x
		min_cost = result.fun

		if self.job:
			train_job = TrainJob.objects.get(id=self.job["id"])
			custom_pqc_job =  train_job.customCircuitJob

		if self.qc_index:
			if is_binary:
				directory = f"../../data/training_results_QVC/pqc{self.qc_index}/binary_cl/"
				path = f"../../data/training_results_QVC/pqc{self.qc_index}/binary_cl/loss_{round(min_cost, 5)}.txt"
			else:
				directory = f"../../data/training_results_QVC/pqc{self.qc_index}/multi_cl/"
				path = f"../../data/training_results_QVC/pqc{self.qc_index}/multi_cl/loss_{round(min_cost, 5)}.txt"
		elif self.custom_qc:
			directory = f"../../data/training_results_QVC/custom/{'binary_cl' if is_binary else 'multi_cl'}/"
			path = f"../../data/training_results_QVC/custom/{'binary_cl' if is_binary else 'multi_cl'}/custom_{custom_pqc_job.id}_loss_{round(min_cost, 5)}.txt"
		result_path = os.path.join(dirname, path)

		try:
			f = open(result_path, 'a')
		except FileNotFoundError:
			os.makedirs(os.path.join(dirname, directory))
			f = open(result_path, 'a')

		for theta in opt_theta:
			f.write(str(theta)+"\n")
		f.close()
		return result_path

	def eval(self, theta, test_data, is_binary=False):
		x = self.cae.get_latent_space_state(Variable(torch.FloatTensor(test_data))).tolist()

		probs = get_classification_probabilities(x,theta, self.qc_index, self.custom_qc, is_binary)

		if is_binary:
			predictions = [-1 if p[0] >= p[1] else 1 for p in probs]
		else:
			predictions = [-1 if p[1]+p[2]+p[3] >= p[4]+p[5]+p[6]+p[7] else 1 for p in probs]

		return predictions


# Tai Sakuma <tai.sakuma@gmail.com>
import time
import itertools
import threading
import multiprocessing

import pytest

from atpbar import atpbar
from atpbar import register_reporter, find_reporter, flush, disable

##__________________________________________________________________||
@pytest.mark.parametrize('niterations', [10, 1, 0])
def test_one_loop(mock_create_presentation, niterations):
    disable()
    for i in atpbar(range(niterations)):
        pass
    presentations = mock_create_presentation.presentations
    assert 0 == len(presentations)

##__________________________________________________________________||
def test_nested_loops(mock_create_presentation):
    disable()
    for i in atpbar(range(4)):
        for j in atpbar(range(3)):
            pass

##__________________________________________________________________||
def run_with_threading(nthreads=3, niterations=[5, 5, 5]):
    def task(n, name):
        for i in atpbar(range(n), name=name):
            time.sleep(0.0001)
    threads = [ ]
    for i in range(nthreads):
        name = 'thread {}'.format(i)
        n = niterations[i]
        t = threading.Thread(target=task, args=(n, name))
        t.start()
        threads.append(t)
    for t in threads:
        t.join()
    flush()

@pytest.mark.parametrize('niterations', [[5, 4, 3], [5, 0, 1], [0], [1]])
@pytest.mark.parametrize('nthreads', [3, 1, 0])
def test_threading(mock_create_presentation, nthreads, niterations):
    disable()

    # make niterations as long as nthreads. repeat if necessary
    niterations = list(itertools.chain(*itertools.repeat(niterations, nthreads//len(niterations)+1)))[:nthreads]

    run_with_threading(nthreads, niterations)

    presentations = mock_create_presentation.presentations
    assert 0 == len(presentations)

##__________________________________________________________________||
def run_with_multiprocessing(nprocesses, ntasks, niterations):
    def task(n, name):
        for i in atpbar(range(n), name=name):
            time.sleep(0.0001)
    def worker(reporter, task, queue):
        register_reporter(reporter)
        while True:
            args = queue.get()
            if args is None:
                queue.task_done()
                break
            task(*args)
            queue.task_done()
    reporter = find_reporter()
    queue = multiprocessing.JoinableQueue()
    for i in range(nprocesses):
        p = multiprocessing.Process(target=worker, args=(reporter, task, queue))
        p.start()
    for i in range(ntasks):
        name = 'task {}'.format(i)
        n = niterations[i]
        queue.put((n, name))
    for i in range(nprocesses):
        queue.put(None)
        queue.join()
    flush()

@pytest.mark.xfail()
@pytest.mark.parametrize('niterations', [[5, 4, 3], [5, 0, 1], [0], [1]])
@pytest.mark.parametrize('ntasks', [3, 1, 0])
@pytest.mark.parametrize('nprocesses', [4, 1])
def test_multiprocessing(mock_create_presentation, nprocesses, ntasks, niterations):
    disable()

    # make niterations as long as ntasks. repeat if necessary
    niterations = list(itertools.chain(*itertools.repeat(niterations, ntasks//len(niterations)+1)))[:ntasks]

    run_with_multiprocessing(nprocesses, ntasks, niterations)

    presentations = mock_create_presentation.presentations
    assert 0 == len(presentations)

##__________________________________________________________________||
def test_call_twice():
    disable()
    disable()

##__________________________________________________________________||


import logging
import warnings

logging.getLogger("transformers").setLevel(logging.ERROR)

from transformers import (
    ElectraTokenizerFast,
    ElectraConfig,
    TFBertMainLayer,
    BertTokenizerFast,
    BertConfig,
    XLMRobertaTokenizer,
    XLMRobertaConfig,
    T5Tokenizer,
    T5Config,
    AlbertTokenizerFast,
    AlbertConfig,
    BertTokenizer,
    LongformerTokenizerFast,
    LongformerConfig,
)
from transformers.models.t5.modeling_tf_t5 import TFT5Model
from transformers.models.electra.modeling_tf_electra import TFElectraMainLayer
from transformers.models.roberta.modeling_tf_roberta import TFRobertaMainLayer
from transformers.models.albert.modeling_tf_albert import TFAlbertMainLayer
from transformers.models.longformer.modeling_tf_longformer import TFLongformerMainLayer

from transformers.models.xlm_roberta.tokenization_xlm_roberta import (
    VOCAB_FILES_NAMES,
    PRETRAINED_VOCAB_FILES_MAP,
    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES,
)

from finetune.util.huggingface_interface import finetune_model_from_huggingface

HFXLMRoberta = finetune_model_from_huggingface(
    pretrained_weights="jplu/tf-xlm-roberta-base",
    archive_map={
        "jplu/tf-xlm-roberta-base": "https://s3.amazonaws.com/models.huggingface.co/bert/jplu/tf-xlm-roberta-base/tf_model.h5"
    },
    hf_featurizer=TFRobertaMainLayer,
    hf_tokenizer=XLMRobertaTokenizer,
    hf_config=XLMRobertaConfig,
    weights_replacement=[
        (
            "tfxlm_roberta_for_masked_lm/roberta",
            "model/featurizer/tf_roberta_main_layer",
        )
    ],
)

HFLongformer = finetune_model_from_huggingface(
    pretrained_weights="allenai/longformer-base-4096",
    archive_map={
        "allenai/longformer-base-4096": "https://cdn.huggingface.co/allenai/longformer-base-4096/tf_model.h5"
    },
    hf_featurizer=TFLongformerMainLayer,
    hf_tokenizer=LongformerTokenizerFast,
    hf_config=LongformerConfig,
    weights_replacement=[
        (
            "tf_longformer_for_masked_lm/longformer",
            "model/featurizer/tf_longformer_main_layer",
        )
    ],
    config_overrides={
        "low_memory_mode": True,
        "batch_size": 2,
        "n_epochs": 16,
        "lr": 1.68e-3,
        "max_grad_norm": 1.1,
        "lr_warmup": 0.7,  # Not a typo - just weird.
        "l2_reg": 0.194,
    },
)

HFElectraGen = finetune_model_from_huggingface(
    pretrained_weights="google/electra-base-generator",
    archive_map={
        "google/electra-base-generator": "https://cdn.huggingface.co/google/electra-base-generator/tf_model.h5"
    },
    hf_featurizer=TFElectraMainLayer,
    hf_tokenizer=ElectraTokenizerFast,
    hf_config=ElectraConfig,
    weights_replacement=[
        ("tf_electra_for_masked_lm/electra", "model/featurizer/tf_electra_main_layer")
    ],
)

HFElectraDiscrim = finetune_model_from_huggingface(
    pretrained_weights="google/electra-base-discriminator",
    archive_map={
        "google/electra-base-discriminator": "https://cdn.huggingface.co/google/electra-base-discriminator/tf_model.h5"
    },
    hf_featurizer=TFElectraMainLayer,
    hf_tokenizer=ElectraTokenizerFast,
    hf_config=ElectraConfig,
    weights_replacement=[
        (
            "tf_electra_for_pre_training/electra",
            "model/featurizer/tf_electra_main_layer",
        )
    ],
)

HFBert = finetune_model_from_huggingface(
    pretrained_weights="bert-base-uncased",
    archive_map={
        "bert-base-uncased": "https://cdn.huggingface.co/bert-base-uncased-tf_model.h5"
    },
    hf_featurizer=TFBertMainLayer,
    hf_tokenizer=BertTokenizerFast,
    hf_config=BertConfig,
    weights_replacement=[
        ("tf_bert_for_pre_training_2/bert/", "model/featurizer/tf_bert_main_layer/"),
        ("tf_bert_for_pre_training/bert/", "model/featurizer/tf_bert_main_layer/"),
    ],
)

HFT5 = finetune_model_from_huggingface(
    pretrained_weights="t5-base",
    archive_map={"t5-base": "https://cdn.huggingface.co/t5-base-tf_model.h5"},
    hf_featurizer=TFT5Model,
    hf_tokenizer=T5Tokenizer,
    hf_config=T5Config,
    weights_replacement=[
        ("tf_t5with_lm_head_model/shared/", "model/featurizer/shared/shared/"),
        ("tf_t5with_lm_head_model/encoder", "model/featurizer/encoder"),
        ("tf_t5with_lm_head_model/decoder", "model/target/decoder"),
    ],
    include_bos_eos="eos",
    add_tokens=["{", "}", "<"],  # "[", "]"],
)

HFT5Small = finetune_model_from_huggingface(
    pretrained_weights="t5-small",
    archive_map={"t5-small": "https://cdn.huggingface.co/t5-small-tf_model.h5"},
    hf_featurizer=TFT5Model,
    hf_tokenizer=T5Tokenizer,
    hf_config=T5Config,
    weights_replacement=[
        ("tf_t5with_lm_head_model/shared/", "model/featurizer/shared/shared/"),
        ("tf_t5with_lm_head_model/encoder", "model/featurizer/encoder"),
        ("tf_t5with_lm_head_model/decoder", "model/target/decoder"),
    ],
    include_bos_eos="eos",
    add_tokens=["{", "}", "<"],  # "[", "]"],
)

HFAlbert = finetune_model_from_huggingface(
    pretrained_weights="albert-base-v2",
    archive_map={
        "albert-base-v2": "https://cdn.huggingface.co/albert-base-v2-tf_model.h5"
    },
    hf_featurizer=TFAlbertMainLayer,
    hf_tokenizer=AlbertTokenizerFast,
    hf_config=AlbertConfig,
    weights_replacement=[
        ("tf_albert_for_masked_lm_1/albert/", "model/featurizer/tf_albert_main_layer/")
    ],
    config_overrides={"n_embed": 768, "n_epochs": 8, "lr": 2e-5, "batch_size": 8},
    aggressive_token_alignment=True,
)

HFAlbertXLarge = finetune_model_from_huggingface(
    pretrained_weights="albert-xlarge-v2",
    archive_map={
        "albert-xlarge-v2": "https://cdn.huggingface.co/albert-xlarge-v2-tf_model.h5"
    },
    hf_featurizer=TFAlbertMainLayer,
    hf_tokenizer=AlbertTokenizerFast,
    hf_config=AlbertConfig,
    weights_replacement=[
        ("tf_albert_for_masked_lm_5/albert/", "model/featurizer/tf_albert_main_layer/")
    ],
    config_overrides={"n_embed": 2048, "n_epochs": 8, "lr": 1e-5, "batch_size": 2},
    aggressive_token_alignment=True,
)


def reverse_string(st):
  rev = ""
  for i in st:
    rev = i + rev

  return rev
  # l = 0
  # r = len(st)-1

  # while l < r:
  #   st[l], st[r] = st[r], st[l]
  #   l += 1
  #   r -= 1

  # return st

print("Reversed String: ", reverse_string("Omkar"))


from utility.globalStuff import Tile, Cord2d
import random

class FoodGenerator(object):
    def __init__(self, game, count=1):
        self.foodList = []
        self.game = game
        self.count = count
        self.addNewFood()

    def setFoodCount(self, count):
        self.count = count

    def foodEaten(self, food):
        self.foodList.remove(food)
        self.game.removeTile(food)
        self.addNewFood()

    def reset(self):
        for food in self.foodList:
            self.game.removeTile(food)
        num = len(self.foodList)
        self.foodList = []
        for i in range(num):
            self.addNewFood()

    def addNewFood(self):
        add = self.count - len(self.foodList)
        for i in range(add):
            randx = random.randint(1, self.game.sizeX - 2)
            randy = random.randint(1, self.game.sizeY - 2)
            for food in self.foodList:
                if(randx == food.x and randy == food.y):
                    self.addNewFood()
                    return
            for snake in self.game.snakeList:
                for cord in snake.body:
                    if(randx == cord.x and randy == cord.y):
                        self.addNewFood()
                        return

            food = Tile(randx, randy, 1)
            self.foodList.append(food)
            self.game.addTile(food)


"""
1초마다 반복해서 동작하는 GUI 코드 만들기
"""

import tkinter
import tkinter.font
import pyupbit
import threading
import threading
import time

coin_price = 0

# 1초마다 비트코인의 시세를 가져와 coin_price 전역변수에 저장하는 쓰레드 프로그램을 생성
# 데몬 쓰레드로 생성하여 메인 프로그램이 종료되면 함께 종료된다.
def get_coin_price():
    # 함수 안에서 coin_price의 전역변수를 사용하기 위해 global를 붙여 전역변수인 coin_price를 사용
    global coin_price
    while True:
        coin_price = pyupbit.get_current_price("KRW-BTC")
        time.sleep(1.0)

t1 = threading.Thread(target=get_coin_price)
t1.daemon = True
t1.start()

# window 객체 생성
window = tkinter.Tk()

# 타이틀을 정의
window.title("비트코인 실시간 가격")

# GUI의 사이즈를 설정
window.geometry("400x50")

# 가로세로의 크기를 조절하지 못하도록 설정
window.resizable(False, False)

# 폰트를 적용하여 텍스트 출력
font = tkinter.font.Font(size=30)
label = tkinter.Label(window, text="", font=font)
label.pack()

# 1초마다 실행되는 함수, coin_price의 가격을 1초마다 GUI에 표시
def get_coin_1sec():
    global coin_price
    now_btc_price = str(coin_price)

    # 라벨의 text를 변경
    label.config(text=now_btc_price)

    # 1초 후에 get_coin_1sec 함수를 불러온다.
    window.after(1000, get_coin_1sec)

# 한 번 실행 후 자기 자신을 1초마다 호출
get_coin_1sec()

# GUI를 계속 실행하기 위해 mainloop를 살행
window.mainloop()


import torch
from torch import nn
from AcT import AcT

"""
Code based on: Action Transformer: A Self-Attention Model for Short-Time Pose-Based
Human Action Recognition
From Author: Vittori Mazzia, Simone Angarano1, Francesco Salvetti, Federico Angelin and Marcello Chiaberge
"""
class Ensemble(nn.Module):
	""" Ensemble of AcT models

		Parameters:
		-----------

		Attributes
		----------:

			"""
	def __init__(self, ensemble_size, B=40, T=5, N=17, C=3, nhead=1, num_layer=4, d_last_mlp=256, classes=20):

		super().__init__()

		self.ensemble = nn.ModuleList()
		self.ensemble_size = ensemble_size
		self.B = B
		self.T = T
		self.N = N
		self.C = C
		self.nhead = nhead
		self.num_layer = num_layer
		self.d_last_mlp = d_last_mlp
		self.classes = classes

	def load_weights(self, PATH):

		for i in range(0, self.ensemble_size):
			self.ensemble.append(AcT(B=self.B, T=self.T, N=self.N, C=self.C, nhead=self.nhead, num_layer=self.num_layer, d_last_mlp=self.d_last_mlp
										,classes=self.classes))
			self.ensemble[i].load_state_dict(torch.load(PATH+'/models/model_'+str(i+1)+'.pth'))
			self.ensemble[i].eval()

	def forward(self, X_in):
		out = torch.zeros(self.classes)

		for i, l in enumerate(self.ensemble):
			out = l(X_in) + out

		return out / self.ensemble_size # [B, T+1, D_model]

"""
---------------------------------------
	Testing Zone
---------------------------------------
"""
if __name__=="__main__":
	# Layer-testing zone

	batch_size, T, N, C, nhead, num_layer, classes = 1, 30, 17, 3, 2, 4, 20
	X_in = torch.randn([batch_size,T,N,C])

	model = Ensemble(B=batch_size, T=30, N=17, C=3, nhead=3, num_layer=6, d_last_mlp=502, classes=20)
	out = model(X_in)

	if batch_size == 1:
		print("models voted for: ", out.argmax(0))
	else:
		print("models voted for: ", out.argmax(1))


"""
Tests for example generation.
"""
from __future__ import unicode_literals
from textwrap import dedent

import pytest
from yaml import safe_load

from traitlets import TraitError

from straitlets.serializable import Serializable
from straitlets.test_utils import assert_serializables_equal, multifixture
from straitlets.traits import (
    Bool,
    Dict,
    Instance,
    Integer,
    Unicode,
)

class Point(Serializable):
    x = Integer().example(100)
    y = Integer().example(101)

class ExampleClass(Serializable):

    bool_tag = Bool().example(True)
    bool_default = Bool(default_value=False)
    bool_both = Bool(default_value=False).example(True)

    int_tag = Integer().example(1)
    int_default = Integer(default_value=2)
    int_both = Integer(default_value=100).example(3)

    dict_tag = Dict().example({'a': 'b'})
    dict_default = Dict(default_value={'c': 'd'})
    dict_both = Dict(default_value={'z': 'z'}).example({'e': 'f', 'g': 'h'})

    instance_tag = Instance(Point).example(Point(x=0, y=1))
    instance_default = Instance(Point, default_value=Point(x=2, y=3))
    instance_both = Instance(Point, default_value=Point(x=4, y=5)).example(
        Point(x=6, y=7),
    )
    # Instance provides a default example if the value is a Serializable
    # that can provide an example.
    instance_neither = Instance(Point)

@pytest.fixture
def expected_instance():
    return ExampleClass(
        bool_tag=True,
        bool_default=False,
        bool_both=True,
        int_tag=1,
        int_default=2,
        int_both=3,
        dict_tag={'a': 'b'},
        dict_default={'c': 'd'},
        dict_both={'e': 'f', 'g': 'h'},
        instance_tag=Point(x=0, y=1),
        instance_default=Point(x=2, y=3),
        instance_both=Point(x=6, y=7),
        instance_neither=Point(x=100, y=101),
    )

@pytest.fixture
def expected_yaml():
    return dedent(
        """
        bool_tag: true
        bool_default: false
        bool_both: true
        int_tag: 1
        int_default: 2
        int_both: 3
        dict_tag:
            a: b
        dict_default:
            c: d
        dict_both:
            e: f
            g: h
        instance_tag:
            x: 0
            y: 1
        instance_default:
            x: 2
            y: 3
        instance_both:
            x: 6
            y: 7
        instance_neither:
            x: 100
            y: 101
        """
    )

@multifixture
def skip_names():
    yield ()
    yield ('bool_tag',)
    yield ('bool_tag', 'int_tag')
    yield ('dict_tag', 'instance_tag', 'instance_neither')
    yield [
        name for name in ExampleClass.class_trait_names()
        if name.endswith('tag')
    ]

def test_example_instance(expected_yaml, expected_instance):
    instance = ExampleClass.example_instance()

    assert_serializables_equal(instance, expected_instance)
    assert_serializables_equal(instance, ExampleClass.from_yaml(expected_yaml))

    assert ExampleClass.example_yaml() == expected_instance.to_yaml()

def test_example_skip_names(expected_instance, skip_names):
    instance = ExampleClass.example_instance(skip=skip_names)
    assert_serializables_equal(instance, expected_instance, skip=skip_names)

    for name in skip_names:
        with pytest.raises(TraitError):
            getattr(instance, name)

def test_write_example_yaml(tmpdir, expected_instance, skip_names):

    path = tmpdir.join("test.yaml").strpath
    ExampleClass.write_example_yaml(path, skip=skip_names)

    from_file = ExampleClass.from_yaml_file(path)
    assert_serializables_equal(
        from_file,
        expected_instance,
        skip=skip_names,
    )

    for name in skip_names:
        with pytest.raises(TraitError):
            getattr(from_file, name)

def test_nested_example():

    class C(Serializable):
        point = Instance(Point)
        unicode_ = Unicode().tag(example='foo')

    class B(Serializable):
        value = Integer().tag(example=ord('b'))
        next_ = Instance(C)

    class A(Serializable):
        value = Integer().tag(example=ord('a'))
        next_ = Instance(B)

    expected = A(
        value=ord('a'),
        next_=B(
            value=ord('b'),
            next_=C(
                point=Point.example_instance(),
                unicode_='foo',
            ),
        ),
    )

    assert_serializables_equal(expected, A.example_instance())

def test_readme_example():

    class Point(Serializable):
        x = Integer().example(0)
        y = Integer().example(0)

    class Vector(Serializable):
        head = Instance(Point)
        tail = Instance(Point).example(Point(x=1, y=3))

    example_yaml = Vector.example_instance().to_yaml()
    expected = {
        "head": {"x": 0, "y": 0},
        "tail": {"x": 1, "y": 3},
    }
    assert safe_load(example_yaml) == expected


def collatz(number):
    if number%2 == 0:
        return number//2
    else:
        return (3*number+1)
number = int(input("enter a number: "))
print("enter a valid integer")
while number!=1:
    number = collatz(number)
    print(number)


import os

APP_VERSION = 'v1.0'

# Menu shortcuts
COPY_SC = 'Ctrl+D'
SAVE_SC = 'Ctrl+S'
EXIT_SC = 'Ctrl+Q'
UNDO_SC = 'Ctrl+Z'

# Translation
if os.getenv('LANG', 'zh-hans'):
    LANG = 'CN'
else:
    LANG = 'EN'

LANG = 'EN'

if LANG == 'EN':
    from Translation_EN import *
elif LANG == 'CN':
    from Translation_CN import *
else:
    raise EnvironmentError('No language specified.')

# Layout Settings
PIC_WIDTH = 400
PIC_HEIGHT = 400
CTRL_WIDTH = 250
CTRL_HEIGHT = 290
STATUS_WIDTH = 250
STATUS_HEIGHT = PIC_HEIGHT - CTRL_HEIGHT
MENU_HEIGHT = 27
DEFAULT_WIDTH = PIC_WIDTH + CTRL_WIDTH
DEFAULT_HEIGHT = PIC_HEIGHT + MENU_HEIGHT

# Calculation
MAX_ITER = 50
MAX_MOD = 4
FREQ_UPDATE_LINE = 2
EXP_VIEW1 = 'z^2+0.3'
EXP_VIEW2 = 'z^2-0.75'
EXP_VIEW3 = 'z^2-0.123+0.745i'
EXP_VIEW4 = 'z^2-0.8+0.15i'
EXP_VIEW5 = 'z^2-1.755'
EXP_VIEW6 = 'z^3-0.6+0.3i'

# Initial Image Settings
INIT_EXP = '99'
EMPTY_EXP = '99'
INIT_SHIFTX = 0
INIT_SHIFTY = 0
INIT_RX = 2
INIT_RY = 2


# The minimum distances between cores.
minimum_core_distance = 42
# How often do we try to place a core, anyways?
core_offset = 2
# How much do we want to damp the noise to create chunks that are similar to each other next to each other?
# 1 creates basically no chunks. 0 doesn't work.
noise_damping_factor = 0.025
# This is used to select a sprite from the output of OpenSimplex noise, normalized between 0 and 1.
terrain_sprite_bins = [0, 0.2, 0.25, 0.5, 0.55, 0.6, 0.7, 0.8, 0.825, 0.875, 0.9, 0.915, 0.25, 1.0]

"""
Stats for enemy units.
name: Friendly name for the unit, probably displayed in the UI.
speed: How many seconds per hex can this enemy move?
sprite_id: Sprite ID to load, presently needs to match the filename - extension.
health: how many hitpoints does this enemy have.
level: level of the enemy.
"""
enemy_stats = {
    1: {"name": "red creep", "speed": .225, "sprite_id": "enemy test 1", "health": 1, "level": 0.25},
}


import distutils.sysconfig
import os
from os.path import basename, exists, splitext

SWIG='.'
SIMAVR = SWIG+'/simavr'  # simavr path

SIM = SIMAVR + '/simavr/sim'
CORES = SIMAVR + '/simavr/cores'
INCLUDE_SIMAVR = SIMAVR + '/simavr'
INCLUDE_AVR = SWIG+'/include'
INCLUDE_PYTHON = distutils.sysconfig.get_python_inc()
#INCLUDE_PYTHON = '/usr/include/python3.6m' #No scons for py3 yet..
PARTS = SWIG+'/parts'
UTILS = SWIG+'/utils'

#Base environment common to both C and C++
envBase = Environment(
                  ENV=os.environ,
                  CPPDEFINES=['NO_COLOR'],
                  );
envBase.SetOption('num_jobs', 4)
#Use RUNPATH + $origin to add the runtime linker a hint where to load the shared libraries from (_simavr.so).
#Since pysimavr is not putting the .so files on the usual system directories included in the LD_LIBRARY_PATH.
#https://bitbucket.org/scons/scons/wiki/UsingOrigin
#http://stackoverflow.com/questions/4513799/how-to-set-the-runtime-path-rpath-of-an-executable-with-gcc-under-mac-osx
#http://stackoverflow.com/questions/19123623/python-runtime-library-dirs-doesnt-work-on-mac

envBase.Append( LINKFLAGS = Split('-z origin -Wl,--enable-new-dtags') ) #Include RUNPATH beside the RPATH
envBase.Append( RPATH = envBase.Literal("\\$$ORIGIN"))

#g++ -o _utils.so -z origin --enable-new-dtags -shared -Wl,-rpath=\$ORIGIN utils/LoggerCallback.os utils/TimerCallback.os utils_wrap.os _simavr.so

CCFLAGS=['-Wall',
         #'-g', #Debug info
         '-Wno-sign-compare', #simavr code has tons of  mixed unsign/sign compares
         ]

# C Environemnt
env = envBase.Clone(
                  CCFLAGS=CCFLAGS+[
                           '--std=gnu99',
                           ],
                  );
# C++ Environment
envCPP = envBase.Clone(
                  CCFLAGS=CCFLAGS+[
                  #The Fast get feature seems broken in py2.7 (TypeError on avr_t * cast). Disable.
                  '-DSWIG_PYTHON_SLOW_GETSET_THIS',
                  ],
                  );

#######################################
# swig simavr
#######################################
def filtered_glob(env, pattern, omit=[],
  ondisk=True, source=False, strings=False):
    return filter(
      lambda f: basename(f.path) not in omit,
      env.Glob(pattern))

env.AddMethod(filtered_glob, "FilteredGlob");

EXCLUDE = ['sim_mega324.c', 'sim_mega128rfr2.c']
source=[
     'simavr.i',
     Glob(SIM + '/*.c'),
#     Glob(CORES + '/sim_*.c'),
     env.FilteredGlob(CORES + '/sim_*.c', EXCLUDE),
 ]

swig_simavr = env.SharedLibrary(
                  'simavr',
                  source=source,
                  LIBS=['elf'],
                  SWIGFLAGS=['-python'],
                  SHLIBPREFIX="_",
                  CPPPATH=[
                                 SIM,
                                 INCLUDE_AVR,
                                 INCLUDE_SIMAVR,
                                 INCLUDE_PYTHON,
                            ],
                  SWIGPATH=[
                                 SIM,
                                 ],
                  )

def part(name):
    cfile = Dir(PARTS).File(name + '.c')
    ifile = Dir(SWIG).File(name + '.i')

    swig_part = env.SharedLibrary(
                      name,
                      source=[
                              cfile,
                              ifile,
#                       'sim/sim_cycle_timers.c',
#                       'sim/sim_irq.c',
#                       'sim/sim_io.c',
#                       Glob('sim/*.c'),
#                       Glob('cores/sim_*.c'),
                       ],
                      LIBPATH=[Dir(SWIG)],
                      LIBS=[':_simavr.so.so'], #Scons (incorrectly?) removes ".so" even when the ':' prefix is used
                      SWIGFLAGS=['-python'],
                      SHLIBPREFIX="_",
                      CPPPATH=[
                                 SIM,
                                 INCLUDE_AVR,
                                 INCLUDE_SIMAVR,
                                 INCLUDE_PYTHON,
                                 PARTS,
                                ],
                      SWIGPATH=[
                                 SIM,
                                 PARTS,
                                 ]
                      )
    Requires(swig_part, swig_simavr) #_simavro.so must exist first, but doesn't need to be recompiled necessary.

#######################################
# swig parts
#######################################
part('sgm7')
part('ledrow')
part('inverter')
part('hd44780')
part('ac_input')
part('button')
part('uart_udp')
part('spk')
part('uart_buff')

#######################################
# swig utils
#######################################
swig_utils = envCPP.SharedLibrary(
                  'utils',
                  source=[Glob(UTILS + '/*.cpp'),
                          Dir(SWIG).File('utils.i'),
                          #Dir(SWIG).File('_simavr.so'),
                          ],
                  LIBPATH=[Dir(SWIG)],
                  LIBS=[':_simavr.so.so'], #Scons (incorrectly?) removes ".so" even when the ':' prefix is used
                  SWIGFLAGS=['-python', '-c++', '-threads'],
                  SHLIBPREFIX="_",
                  CPPPATH=[
                                 SIM,
                                 INCLUDE_AVR,
                                 INCLUDE_SIMAVR,
                                 INCLUDE_PYTHON,
                                 UTILS,
                            ],
                  SWIGPATH=[
                                 SIM,
                                 UTILS,
                                 ],
                  )
Requires(swig_utils, swig_simavr)


########
# USDN #
########
# data stored as string in requests
import datetime
import time
def archive(browser, wa, folder):
    name = 'USDN'
    time_str = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
    browser.retry('https://neutrino.at/stats')
    time.sleep(10)
    browser.archive_mhtml('{}/{}-{}.mhtml'.format(folder, name, time_str))


# "THE BEER-WARE LICENSE" (Revision 42):
# T. Yamaguchi wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return.

__all__ = ["demo", "ecm", "efgm", "fem", "mesh", "numeical", "utils"]

__author__ = "T. Yamaguchi <https://github.com/yamaguchi-takazumi/simkitpy>"
__status__ = "in development"
__version__ = "0.0.0"


import asyncio
import datetime
from mpapi.constants import get_credentials
from mpapi.module import Module
from mpapi.search import Search
from MpApi.aio.chunky import Chunky
from MpApi.aio.session import Session
from pathlib import Path
import pytest

user, pw, baseURL = get_credentials()

@pytest.mark.asyncio
async def test_results():
    async with Session(user=user, pw=pw) as session:
        # print (f"{session=}")
        # print (f"{session.appURL}")
        chnkr = Chunky(baseURL=baseURL)
        rno, cno = await chnkr.count_results(
            session=session, qtype="group", target="Object", ID=182397
        )
        assert rno == 49
        assert cno == 1

@pytest.mark.asyncio
async def test_related():
    chnkr = Chunky(baseURL=baseURL)
    m = Module(file="getItem-Object590013.xml")
    results_set = await chnkr.analyze_related(data=m)
    assert results_set == {
        "Conservation",
        "Address",
        "Person",
        "Multimedia",
        "Literature",
        "Registrar",
        "CollectionActivity",
        "ObjectGroup",
    }

@pytest.mark.asyncio
async def test_query_maker():
    chnkr = Chunky(baseURL=baseURL)
    q = await chnkr.query_maker(
        qtype="group", target="Object", ID=12345, offset=100, limit=chnkr.chunk_size
    )
    assert isinstance(q, Search)

@pytest.mark.asyncio
async def test_get_by_type():
    chnkr = Chunky(baseURL=baseURL)
    async with Session(user=user, pw=pw) as session:
        m = await chnkr.get_by_type(session=session, qtype="group", ID=182397)
        assert m
        print(m)

def test_chunk_path():  # function, not coro
    chnkr = Chunky(baseURL=baseURL)
    path = chnkr._chunk_path(qtype="group", ID=182397, cno=1, suffix=".xml", job="test")
    print("{path=}")
    date: str = datetime.datetime.today().strftime("%Y%m%d")

    p = Path("test") / date / "group-182397-chunk1.xml"
    assert str(path) == str(p)


import os
import sys
from scapy.all import *

import common
# logger printing everything on stdout

class TestLogger:
    """
    Log test data to a folder (stdout and pcap)
    """

    def __init__(self, folder, name, verbose=0):
        self._folder = folder
        self._name = name
        self._verbose = verbose

        self._txt_trace_file = None
        self._pcap_out = None

        if folder is not None and name is not None:
            if not os.path.isdir(folder):
                os.makedirs(folder)
            self._txt_trace_file = open(folder + "/" + name + ".txt", "w")

        self.pkt_list = []

    def write_pkt(self, pkt):
        """
        Add a packet to the packet list, THIS DOES NOT WRITE A PCAP !
        see write_pcap
        """
        self.pkt_list.append(pkt)

    def write_pcap(self):
        """
        Write the pcap output file, with packets from pkt_list
        """
        if self._folder is not None and self._name is not None:
            self._pcap_out = wrpcap(
                self._folder + "/" + self._name + ".pcap", self.pkt_list)

    def println(self, msg="", verbose=-1):
        self.write(msg + "\n", verbose)

    def write(self, msg, verbose=-1):
        if self._verbose >= verbose:
            sys.stdout.write(msg)
            sys.stdout.flush()
        self._txt_trace(msg)

    def log_warning(self, msg):
        if self._verbose > 0:
            common.print_warning(msg)
        self._txt_trace("[!] WARNING : " + msg + "\n")

    def log_error(self, msg):
        if self._verbose > 0:
            common.print_error(msg)
        self._txt_trace("[!] ERROR : " + msg + "\n")

    def close(self):
        """
        Logger must be closed after use :
        closes the txt output file
        write the pkt_list to the pcap_output file
        """
        if self._txt_trace_file is not None:
            self._txt_trace_file.close()
        self.write_pcap()

    def _txt_trace(self, msg):
        if self._txt_trace_file is not None:
            self._txt_trace_file.write(msg)

none_logger = TestLogger(None, None, -1)
stdout_logger = TestLogger(None, None, 32768)


#Exercice 1

board = ""

for i in range(1,8) :
    for j in range(1, 17) :
        if (j+i)%2==0 :
            board += "O"
        else :
            board += "X"
    board += "\n"
board += "\n"

print(board)

#Exercice 2

matrix = ""

for i in range(1,5) :
    for j in range(1,5) :
        if i == j :
            matrix += "1 \n"
        else :
            matrix += "0 \n"
    matrix += "-------- \n"

print(matrix)

#Exercice 3

def is_odd(amont) :
    amont = round(int(amont))
    if amont%2 == 0 :
        print(True)
    else :
        print(False)

is_odd(24.32)
is_odd(33.34)

#Exercice 4

def factorielle(value) :
    if isinstance(value, int) :
        result = 1
        for i in range (1,value) :
            result += result * i
        print(result)
    else :
        print("erreur")

factorielle(4)

#Exercice 5

def to_underscore(string) :
    if isinstance(string, str) :
        string = string.replace('-', "_")
        print(string)
    else :
        print("Attention il faut passer une string en argument")

to_underscore('Une-phrase-avec des tirets')

#Exercice 6

shoppingList = [
    "pâtes",
    "riz",
    "viande",
    "coca",
    "haricots"
]

print("Il faut acheter : " + shoppingList[0])
print("Il faut acheter : " + shoppingList[-1])
print("Il faut acheter : " + shoppingList[2])

#Exercice 7

people = [
    ["Paul","Homme",44],
    ["Stephanie","Femme",32],
    ["Marc","Homme",24]
]

def showPeople(list_of_people) :
    for people in list_of_people :
        print('------------')
        for value in people:
            print(value)

showPeople(people)

#Exercice 8

list_of_numbers = [12, 45, 190, 150, 8, 21]

def findBiggestNumber(numbers) :
    biggestNumber = numbers[0]
    for number in list_of_numbers:
        if number > biggestNumber :
            biggestNumber = number
    print(biggestNumber)

findBiggestNumber(list_of_numbers)

#Exercice 9

tasks = []
task = ""

while task != "fin" :
  task = input("Que devez-vous faire ?")
  tasks.append(task)

for task in tasks :
  print(task)


#!/usr/bin/env python
# -*- coding: utf8 -*-
import RPi.GPIO as GPIO
import time
import sys, os
import termios, fcntl
import random
from decimal import *

def pause(ms):
	l = Decimal(ms)/Decimal(1000)
	time.sleep(Decimal(ms)/Decimal(1000))

def blinke(led,led2,tim):
	GPIO.output(led,1)
	pause(tim)
	GPIO.output(led,0)
	GPIO.output(led2,1)
	pause(tim)
	GPIO.output(led2,0)

fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

led = 17
led2 = 22
GPIO.setup(led,GPIO.OUT)
GPIO.setup(led2,GPIO.OUT)

tim = 15
try:
	print("Zum Beenden 'x' drücken")
	while 1:
		try:
			blinke(led,led2,tim)
			tim+=10
			tim = random.randrange(15,1000,1)
			tastatur = sys.stdin.read(1)
			if tastatur == 'x':
				break
		except IOError: pass
finally:
	termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
	fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

print("Programm beendet")
GPIO.cleanup()


import os
import sys
import logging

from common import get_spark_session

# spark session
spark = get_spark_session("ETL", "thrift://hive:9083", "http://minio:9000",
                          "spark", "spark12345")
# Set log4j
spark.sparkContext.setLogLevel("ERROR")
log4jLogger = spark._jvm.org.apache.log4j
logger = log4jLogger.LogManager.getLogger("LOGGER")
logger.setLevel(log4jLogger.Level.INFO)

spark.sql("""SELECT * FROM delta_bitcoin WHERE timestamp = 1424702340""").show()
# update
spark.sql(
    """UPDATE delta_bitcoin SET low = 237.2 WHERE timestamp = 1424705640;""").show()
spark.sql("""SELECT * FROM delta_bitcoin WHERE timestamp = 1424705640""").show()
# delete
spark.sql("DELETE FROM delta.`s3a://datalake/deltatables/bitcoin/` WHERE timestamp = 1429197120").show()
spark.sql("DELETE FROM delta_bitcoin WHERE timestamp = 1424702340").show()
# spark.sql("""SELECT * FROM delta_bitcoin WHERE timestamp = 1424702340""").show()

spark.stop()


import blitterbike
import glob
import time
import random
from twisted.python import log

try:
	from PIL import Image
	from PIL import ImageOps
except ImportError:
	import Image
	import ImageOps

class BikeMode (blitterbike.BlitterBikeMode):

	def __init__(self):
		self.fullSpeed = 130.0;
		self.bootGif = blitterbike.BLITTER_BIKE_PATH  + "/gifs/bike.gif"
		self.gifPath = blitterbike.BLITTER_BIKE_PATH + "/gifs/bike/"
		self.im = None
		self.gifList = []
		self.gifList.append({"gif":"boo.gif", "step":12, "wait":100, "loops":[{"speed":0.05, "start":0, "end":0}, {"speed":1.0, "start":1, "end":26}]})
		self.gifList.append({"gif":"corgi.gif", "step":12, "wait":100, "loops":[{"speed":1.0, "start":0, "end":3}]})
		self.gifList.append({"gif":"mario.gif", "step":12, "wait":100, "loops":[{"speed":1.0, "start":0, "end":2}]})
		self.gifList.append({"gif":"megaman.gif", "step":12, "wait":300, "loops":[{"speed":0.02, "start":0, "end":6}, {"speed":0.65, "start":7, "end":10}, {"speed":1.0, "start":11, "end":29}]})
		self.gifList.append({"gif":"nyan.gif", "step":12, "wait":100, "loops":[{"speed":1.0, "start":0, "end":11}]})
		self.gifList.append({"gif":"pony_run.gif", "step":12, "wait":100, "loops":[{"speed":1.0, "start":0, "end":3}]})
		self.gifList.append({"gif":"rabbit.gif", "step":12, "wait":100, "loops":[{"speed":1.0, "start":0, "end":7}]})
		self.gifList.append({"gif":"samus.gif", "step":12, "wait":100, "loops":[{"speed":1.0, "start":0, "end":9}]})
		self.gifList.append({"gif":"sonic.gif", "step":6, "wait":200, "loops":[{"speed":0.02, "start":0, "end":7}, {"speed":0.5, "start":8, "end":15}, {"speed":0.75, "start":16, "end":19}, {"speed":1.0, "start":20, "end":23}]})
		self.gifList.append({"gif":"yoshi.gif", "step":12, "wait":100, "loops":[{"speed":1.0, "start":0, "end":9}]})

	def start(self):
		self.mirrorFlag = False
		self.flipFlag = False
		self.scratchFlag = False
		self.invertFlag = False
		self.updateFlag = False

		self.gifIndex = 0
		self.gif = None
		self.im = None
		self.frame = None
		self.lastFrame = None
		self.startIndex = 0
		self.lastTime = 0
		self.delay = 0
		self.newFlag = False
		self.loadingFlag = False
		self.current = None

		log.msg("BIKE MODE")
		random.shuffle(self.gifList, random.random)

		self.loadingFlag = True
		self.loadGif(self.gifList[self.gifIndex])
		self.loadingFlag = False

	def stop(self):
		pass

	def update(self, speed):

		result = None

		if self.updateFlag:
			self.im = None
			self.updateFlag = False
			self.loadGif(self.gifList[self.gifIndex])

		if not self.im == None:
			if self.newFlag and self.frame != None:
				self.newFlag = False
				result = self.frame

			else:

				currentTime = int(round(time.time() * 1000))
				elapsed = currentTime - self.lastTime

				if len(self.current["loops"]) > 1:
					if speed < self.current["loops"][0]["speed"]:
						if elapsed > self.current["wait"]:
							self.lastTime = currentTime
							self.nextFrame(speed)
							result = self.frame
					else:
						if elapsed >= (self.current["step"]/speed) * 1000:
							self.lastTime = currentTime
							self.nextFrame(speed)
							result = self.frame

				else:
					if speed > 0:
						currentTime = int(round(time.time() * 1000))
						elapsed = currentTime - self.lastTime

						if elapsed >= (self.current["step"]/speed) * 1000:
							self.lastTime = currentTime
							self.nextFrame(speed)
							result = self.frame

		if result != None:
			result = result.convert("RGB")

			if self.mirrorFlag:
				result = result.transpose(Image.FLIP_LEFT_RIGHT)

			if self.flipFlag:
				result = result.transpose(Image.FLIP_TOP_BOTTOM)

			if self.invertFlag:
				result = ImageOps.invert(result)

			result = result.getdata()

		return result

	def onButtonDown(self, button):
		if button == blitterbike.RIGHT_BUTTON:
			self.gifIndex += 1
			if self.gifIndex == len(self.gifList):
				self.gifIndex = 0

			self.updateFlag = True

		if button == blitterbike.LEFT_BUTTON:
			self.gifIndex -= 1
			if self.gifIndex == -1:
				self.gifIndex = len(self.gifList) - 1

			self.updateFlag = True

		if button == blitterbike.UP_BUTTON:
			self.gifIndex += 5
			if self.gifIndex >= len(self.gifList):
				self.gifIndex -= len(self.gifList)

			self.updateFlag = True

		if button == blitterbike.DOWN_BUTTON:
			self.gifIndex -= 5
			if self.gifIndex < 0:
				self.gifIndex += len(self.gifList)

			self.updateFlag = True

		if button == blitterbike.A_BUTTON:
			self.mirrorFlag = not self.mirrorFlag

		if button == blitterbike.E_BUTTON:
			self.flipFlag = not self.flipFlag

		if button == blitterbike.D_BUTTON:
			self.scratchFlag = True

		if button == blitterbike.H_BUTTON:
			self.invertFlag = not self.invertFlag

	def onButtonUp(self, button):
		pass

	def loadGif(self, info):

		self.current = info
		self.frame = None
		imagePath = "%s%s" % (self.gifPath, self.current["gif"])

		log.msg(imagePath)
		self.im = Image.open(imagePath)
		self.frame = Image.new("RGBA", (32, 32), (0,0,0))

		self.lastFrame = next = self.im.convert("RGBA")
		self.frame.paste(next, next.getbbox(), mask=next)
		self.lastTime = int(round(time.time() * 1000))
		self.newFlag = True

	def nextFrame(self, speed):
		if self.im != None:

			try:
				self.im.seek(self.im.tell() + 1)
			except EOFError:
				self.im.seek(0)
				self.frame = Image.new("RGBA", (32, 32), (0,0,0))

			percent = speed/self.fullSpeed

			if percent > 1.0:
				percent = 1.0

			index = 0
			while percent > self.current["loops"][index]["speed"]:
				index += 1

			start = self.current["loops"][index]["start"]
			end = self.current["loops"][index]["end"]

			while self.im.tell() > end:
				try:
					self.im.seek(self.im.tell() + 1)
				except EOFError:
					self.im.seek(0)
					self.frame = Image.new("RGBA", (32, 32), (0,0,0))

			while self.im.tell() < start:
				self.im.palette.dirty = 1
				self.im.palette.rawmode = "RGB"

				next = self.im.convert("RGBA")

				self.frame.paste(next, next.getbbox(), mask=next)
				self.im.seek(self.im.tell() + 1)

			self.im.palette.dirty = 1
			self.im.palette.rawmode = "RGB"

			next = self.im.convert("RGBA")

			self.frame.paste(next, next.getbbox(), mask=next)

			self.lastFrame = next

			try:
				self.delay = self.im.info['duration']
			except KeyError:
				self.delay = 100

			if self.delay < 20:
				self.delay = 100


from util import Save, Load
from nn import CheckGrad, Train
from cnn import InitCNN, CNNForward, CNNBackward, CNNUpdate
from nn_plot import save_figure, evaluate_model
import numpy as np
import matplotlib.pyplot as plt

# Turn interactive plotting off
plt.ioff()

def cnn_with_args(eps=0.1,
                  momentum=0.5,
                  num_epochs=30,
                  filter_size=5,
                  num_filters_1=8,
                  num_filters_2=16,
                  batch_size=100):
    # Input-output dimensions.
    num_channels = 1
    num_outputs = 7

    # Initialize model.
    model = InitCNN(num_channels, filter_size, num_filters_1, num_filters_2, num_outputs)

    # Check gradient implementation.
    print('Checking gradients...')
    x = np.random.rand(10, 48, 48, 1) * 0.1
    CheckGrad(model, CNNForward, CNNBackward, 'W3', x)
    CheckGrad(model, CNNForward, CNNBackward, 'b3', x)
    CheckGrad(model, CNNForward, CNNBackward, 'W2', x)
    CheckGrad(model, CNNForward, CNNBackward, 'b2', x)
    CheckGrad(model, CNNForward, CNNBackward, 'W1', x)
    CheckGrad(model, CNNForward, CNNBackward, 'b1', x)

    # Train model.
    model, stats = Train(model, CNNForward, CNNBackward, CNNUpdate, eps, momentum, num_epochs, batch_size)

    # Construct file name
    fname = str(eps) + '_' + str(momentum) + '_' + str(num_epochs) + '_' + str(filter_size) + '_' + \
            str(num_filters_1) + '_' + str(num_filters_2) + '_' + str(batch_size)

    # Save the training statistics.
    Save('cnn_model/' + fname, model)
    Save('cnn_stats/' + fname, stats)

def plot_figures(stats_fname):
    stats = Load(stats_fname)
    train_ce_list = stats['train_ce']
    valid_ce_list = stats['valid_ce']
    train_acc_list = stats['train_acc']
    valid_acc_list = stats['valid_acc']
    figure_path = get_cnn_path(stats_fname)
    save_figure(train_ce_list, valid_ce_list, 'Cross Entropy', figure_path)
    save_figure(train_acc_list, valid_acc_list, 'Accuracy', figure_path)
    print('Figures saved to ' + figure_path)

def get_cnn_path(stats_fname):
    sep = stats_fname.find('/')
    figure_name = stats_fname[sep + 1:-4]
    return "cnn_figure/" + figure_name

def plot_first_filters(model_fname):
    model = Load(model_fname)
    W1 = model['W1']
    plt.clf()
    for i in xrange(W1.shape[3]):
        plt.subplot(1, W1.shape[3], i + 1)
        plt.imshow(W1[:, :, 0, i], cmap=plt.cm.gray)
    plt.savefig('visualization/cnn_first_layer_filters.png')
    print("cnn_first_layer_filters.png saved")

def cnn_main(*args):
    # Run CNN and save model, stats
    cnn_with_args(*args)
    # Get file name based on arguments
    fname = str(args[0]) + '_' + str(args[1]) + '_' + str(args[2]) + '_' + str(args[3]) + '_' + \
            str(args[4]) + '_' + str(args[5]) + '_' + str(args[6])
    # Plot and save figure based on model, stats
    plot_figures('cnn_stats/' + fname + '.npz')
    # Evaluate model and save results
    evaluate_model('cnn_model/' + fname + '.npz', 'cnn_result/' + fname, CNNForward, args[6])
    # Plot the first layer filters
    # plot_first_filters('cnn_model/' + fname + '.npz')

if __name__ == '__main__':
    cnn_main(0.1,  # eps
             0.0,  # momentum
             30,  # num_epochs
             5,  # filter_size
             8,  # num_filters_1
             16,  # num_filters_1
             100)  # batch_size


import cv2
import numpy as np

# CTR digit constants
DIGIT_WIDTH = 13
DIGIT_HEIGHT = 22
DIGIT_MULTIPLIER = 3
DIGIT_SIZE = (DIGIT_WIDTH, DIGIT_HEIGHT)
DIGIT_SIZE_HIGH = (DIGIT_WIDTH * DIGIT_MULTIPLIER, DIGIT_HEIGHT * DIGIT_MULTIPLIER)
KERNEL = np.ones((4, 4), np.uint8)

# Color constants
BLACK = 0
WHITE = 255
GRAY = 127

def detect_edges(img):
    ''' Detects edges from pictures of CTR digits.
        @param img: image of the CTR digit '''

    height, width = img.shape
    # Get the average color of the grayscale image
    color_mean = np.mean(img)
    color_mean *= 1.05

    # Loop every pixel
    for i in range(height):
        for j in range(width):
            # Select the darkest pixels as edges and color them black
            if img[i, j] >= color_mean:
                img[i, j] = WHITE
            else:
                img[i, j] = BLACK

    return img

def add_border(img):
    ''' Add a black border surrounding the digit, removing noise.
        @param img: image of the CTR digit '''

    height, width = img.shape

    # Calculating the mean distance of the border to the
    # black pixels surrounding the number
    left_mean = 0
    right_mean = 0
    # Number of valid black pixels detected
    right_row = 0
    left_row = 0

    # Looping every height
    # since we're starting with the right and left border
    for i in range(height):
        visited_left = False
        visited_right = False

        # Looping half of the width pixels to prevent
        # detecting black pixels in case of the image having holes
        # surrounding the edges of the number
        for j in range(width // 2):

            # If a black pixel is detected, j is its distance to the border
            # Lock the loop from detecting further pixels
            # by toogling the visited boolean
            if not visited_right and img[i, width - 1 - j] == BLACK:
                right_mean += j
                right_row += 1
                visited_right = True

            if not visited_left and img[i, j] == BLACK:
                left_mean += j
                left_row += 1
                visited_left = True

            # If both blacks were found, we can go to the next height
            if visited_left and visited_right:
                break

    # Same code as before, but now for the up and down sides
    up_mean = 0
    up_row = 0
    down_mean = 0
    down_row = 0
    for i in range(width):
        visited_up = False
        visited_down = False

        for j in range(height // 2):
            if not visited_down and img[height - 1 - j, i] == BLACK:
                down_mean += j
                down_row += 1
                visited_down = True

            if not visited_up and img[j, i] == BLACK:
                up_mean += j
                up_row += 1
                visited_up = True

            if visited_down and visited_up:
                break

    # We're safe to assume that the entire rectangle from the border
    # to the average value of the first black pixel is noise.
    # Thus, we remove it by making the entire rectangle be black.

    # Left and right sides
    for i in range(height):
        for j in range(max(right_mean // right_row, 1)):
            img[i, width - 1 - j] = BLACK
        for j in range(max(left_mean // left_row, 1)):
            img[i, j] = BLACK

    # Up and down sides
    for i in range(width):
        for j in range(max(down_mean // down_row, 1)):
            img[height - 1 - j, i] = BLACK
        for j in range(max(up_mean // up_row, 1)):
            img[j, i] = BLACK

    return img

def paint_colored_area(img, pixel, color_area, color_paint, diagonal=True):
    ''' Gets the colored area in a picture starting at pixel.
        @param img: image that you want to detect the area.
        @param pixel: tuple of the coordinates starting pixel.
        @param color_area: color of the areas that you want to find.
        @param color_paint: color that you want to paint the area.
        @param diagonal: set to True if you want to consider pixels in
        surrounding the diagonals as neighbors '''

    # Coordinates of the starting pixel
    (i, j) = pixel
    # Stack holds every single pixel that could have neighbors
    stack = []
    # Every pixel coordinates found in the area
    pixels = []

    # Paint the start pixel in order to avoid it being detected again
    img[i, j] = color_paint
    # Add start pixel to the stack, so you can start searching for neighbors
    stack.append((i, j))

    # While there are unverified pixels left
    while len(stack) > 0:
        # Get the next element to search for neighbors
        (i, j) = stack.pop(0)
        # Insert this pixel in the total
        # number of pixels in this area
        pixels.append((i, j))

        # Find more neighbors and store them in the stack
        if img[i - 1, j] == color_area:
            img[i - 1, j] = color_paint
            stack.append((i - 1, j))

        if img[i + 1, j] == color_area:
            img[i + 1, j] = color_paint
            stack.append((i + 1, j))

        if img[i, j - 1] == color_area:
            img[i, j - 1] = color_paint
            stack.append((i, j - 1))

        if img[i, j + 1] == color_area:
            img[i, j + 1] = color_paint
            stack.append((i, j + 1))

        if diagonal:
            if img[i + 1, j + 1] == color_area:
                img[i + 1, j + 1] = color_paint
                stack.append((i + 1, j + 1))

            if img[i - 1, j + 1] == color_area:
                img[i - 1, j + 1] = color_paint
                stack.append((i - 1, j + 1))

            if img[i + 1, j - 1] == color_area:
                img[i + 1, j - 1] = color_paint
                stack.append((i + 1, j - 1))

            if img[i - 1, j - 1] == color_area:
                img[i - 1, j - 1] = color_paint
                stack.append((i - 1, j - 1))

    return pixels

def detect_colored_areas(img, color_area, color_paint, color_rejected, size=150, diagonal=True):
    ''' Detects colored areas in a picture. This function doesn't check the pixels
        in the border of the picture.
        @param img: image that you want to extract the areas.
        @param color_area: color of the areas that you want to find.
        @param color_paint: color that you want to paint the area.
        @param color_rejected: color to paint every area that has color_area, but
        is less than your threshold size.
        @param size: minimum number of pixels required to be considered an area.
        @param diagonal: set to True if you want to consider pixels in
        surrounding the diagonals as neighbors '''

    height, width = img.shape
    # If the digit size is small, use a smaller threshold
    if height == DIGIT_HEIGHT:
        size = 20

    areas = []
    # Loop every single pixel in the image
    for i in range(1, height):
        for j in range(1, width):
            # If a good pixel was found
            if img[i, j] == color_area:
                # Detect the pixels in that area
                pixels = paint_colored_area(img, (i, j), color_area, color_paint, diagonal)

                # Once you have the area, if the size of it is less
                # than your threshold, then paint every pixel as rejected
                if len(pixels) < size:
                    for (pix_i, pix_j) in pixels:
                        img[pix_i, pix_j] = color_rejected
                else:
                    # Append pixels of that area to the total areas found
                    areas.append(pixels)

    return areas

def remove_noisy_areas(img):
    ''' Removes small white pixel areas from the picture.
        @param img: image of the CTR digit.
        @param size: size of the area. '''

    height, width = img.shape

    # Remove the smaller areas of the image. Default threshold is 150 pixels.
    # Areas too small usually are just noise, so removing helps cleaning up the image,
    # which helps predicting the right number.
    areas = detect_colored_areas(img, WHITE, GRAY, BLACK)
    for area in areas:
        paint_colored_area(img, area[0], GRAY, WHITE)

    # Dilate each white part of the picture. This helps witH glueing parts of the number
    # which are separated by a few black pixels, and also removes a bit of remaining noise.
    img = cv2.dilate(img, KERNEL, iterations=1)

    # If the height is the height of a digit that will be used for prediction
    if height != DIGIT_HEIGHT:

        # Adding a black border to the image
        for i in range(width):
            img[0, i] = BLACK
            img[height - 1, i] = BLACK
        for i in range(height):
            img[i, 0] = BLACK
            img[i, width - 1] = BLACK

        # Our dataset consists of CTR digits, which are unique and never changes.
        # However, depending on the capture card quality, the alligment of the Y axis
        # does change from video to video. So, in order to fix it and help getting a more
        # accurate prediction, I'm alligning the number with the top of the picture.

        # Variable to store the distance from the first WHITE pixel in the Y axis
        fix_height = 0
        # Looping every pixel, ignoring the border
        for i in range(1, height):
            found = False
            for j in range(1, width - 1):

                # Whenever you find a white pixel, the distance from where you start will be
                # y = the current height - 1, since we ignore the border
                if img[i, j] == WHITE:
                    fix_height = i - 1
                    found = True
                    break

            if found:
                break

        # If the distance from the first white pixel needs to be adjusted
        if fix_height > 0:

            # Move all pixels up, ignoring the border
            for i in range(1, height - fix_height):
                for j in range(1, width - 1):
                    img[i, j] = img[i + fix_height, j]

            # Erase the remaining pixels by painting them as BLACK
            for i in range(height - fix_height, height):
                for j in range(width):
                    img[i, j] = BLACK

    return img

def process_digit(digit):
    ''' Does all the pre-processing of a grayscale CTR digit.
        @param digit: grayscale image of a CTR digit '''

    digit = detect_edges(digit)
    digit = add_border(digit)
    digit = remove_noisy_areas(digit)

    return digit


file = input ("please enter a file name\n")
try:
    fname = open(file)
except:
    print ("you have entered an incorrect name\n")
    exit()

for line in fname:
    line = line.rstrip()
    line = line.upper()
    print (line)