import os
import re
from urllib.parse import urlparse

def get_name(
    page_url, link=False, directory=False
):  # передаем исходную ссылку на страницу, link and directory - типа флаги, говорят для чего мы формируем име, для файла или для папки
    domain_name = urlparse(page_url).netloc  # разбираем URL
    if link:  # если нам передана полная ссылка до файла в интернете
        root, extension = os.path.splitext(
            link
        )  # берем отдельно https://ru.hexlet.io/packs/js/runtime  и  .js
        path_parts = urlparse(
            root
        ).path  # берем только путь, без домена и без разширения файла /packs/js/runtime
        extension = (
            ".html" if extension == "" else extension
        )  # если расширения не было то делаем html, если было то берем его
    else:  # если ссылки не было
        path_parts = urlparse(page_url).path  # берем только путь, без домена /courses
        extension = ".html"
    name = "{0}{1}".format(
        domain_name, path_parts.rstrip("/")
    )  # формируем имя ru.hexlet.io/courses
    if directory:
        return convert_name(name)
    return convert_name(name), extension

def convert_name(resource):
    return re.sub(
        r"\W", "-", resource
    )  # все НЕ буквы меняем на минусы и формируем имя для папки

def get_file_name(page_url, source_link=False):
    return "{0}{1}".format(*get_name(page_url, link=source_link))

def get_directory_name(page_url):
    return "{0}{1}".format(get_name(page_url, directory=True), "_files")


class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        graph = [[] for _ in range(numCourses)]
        visited = [0 for _ in range(numCourses)]
        #create graph
        for pair in prerequisites:
            x, y = pair
            graph[x].append(y)
        #visit each node
        for i in range(numCourses):
            if not self.dfs(graph,visited,i):
                return False
        return True

    def dfs(self,graph,visited, i):
        """
        if a node v has not been visted, mark it as 0
        if a node v is being visited, then mark it as -1. during dfs , if we find a vertex marked as -, then
            we have found a cycle.
            if a node v has been visited, then mark it as 1. during dfs, if a vertex was marked 1, then no cycle has v or its successors
        """
        ## if ith node is marked as being visited, then a cycle is found
        if visited[i] == -1:
            return False
        ## if it is done visted, then do not visit again
        if visited[i] == 1:
            return True
        # mark as being visited
        visited[i] = -1
        #visit all the neighbors
        for j in graph[i]:
            if not self.dfs(graph,visited,j):
                return False
        #after visit all the neighbors, mark it as done visited
        visited[i] = 1
        return True


"""
MeetUp 011 - Beginners Python Support Sessions 15-May-2019

@author D Tim Cummings

Challenges:

The following challenges will develop some tools for you to analyse your bank account data using Python.
They use the example excel workbook bank_accounts.xlsx

Challenge 9: Read first two sheets of excel workbook and calculate the total opening balance of those accounts

Challenge 10: Calculate and plot the total balance of 'savings' and 'credit_card' on a chart versus date

Advanced challenge 10A: All lines on plot to be vertical or horizontal (no diagonal) to represent balance in accounts
Advanced challenge 10B: If balance goes up and down on same day just show final balance

Challenge 11: Read all sheets from excel spreadsheet. Assume sheets are asset values unless they contain the
word liability in which case amounts and balances have to be negated to convert from liabilities to negative assets.

If using PyCharm Edu:

requirements.txt
xlrd
pandas

"""

import pandas as pd
# from pandas.plotting import register_matplotlib_converters
# import matplotlib.pyplot as plt

# register_matplotlib_converters()  # required to show dates on plots
sheet_name = 'savings'
dct_accounts = pd.read_excel("bank_accounts.xlsx", sheet_name=[sheet_name])
# print("Type of dct_accounts", type(dct_accounts))
df = dct_accounts[sheet_name]
# print(df.tail())
# print(df.shape)
print("Closing balance = ", df.at[df.shape[0]-1, 'Balance'])

# Challenge 9: Read sheets 'savings' and 'credit_card' of excel workbook and calculate the combined opening balance

dct_accounts = pd.read_excel("bank_accounts.xlsx", sheet_name=["savings", "credit_card"])
balance = 0
for sheet_name, df in dct_accounts.items():
    print(sheet_name)
    print(df.head())
    if df.shape[0] > 0:
        balance += df.at[0, 'Balance']
        balance -= df.at[0, 'Amount']
print(balance)

# Challenge 10: Calculate and plot the combined balance of 'savings' and 'credit_card' on a chart versus date
# Advanced challenge 10A: All lines on plot to be vertical or horizontal (no diagonal) to represent balance in accounts
# Advanced challenge 10B: If balance goes up and down on same day just show final balance

import matplotlib.pyplot as plt

# following required to stop warning about dates on plots
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

df_combined = pd.concat(dct_accounts.values(), ignore_index=True).sort_values(by="Date")
dct_balance = {}
for index, row in df_combined.iterrows():
    balance += row['Amount']
    df_combined.at[index, 'Balance'] = balance
    dct_balance[row['Date']] = balance
print(df_combined)

plt.figure(figsize=(10, 10))

# plt.title("Challenge 10 solution")
# plt.plot(df_combined["Date"], df_combined["Balance"])  # Ch. 10 solution

# plt.title("Challenge 10A solution")
# plt.plot(df_combined["Date"], df_combined["Balance"], drawstyle="steps-post")  # Ch 10A solution

# plt.title("Challenge 10B solution")
# plt.plot(list(dct_balance.keys()), list(dct_balance.values()))  # Ch 10B solution

plt.title("Challenge 10A and 10B solution")
plt.plot(list(dct_balance.keys()), list(dct_balance.values()), drawstyle="steps-post")  # Ch 10A and 10B solution

plt.xticks(rotation='vertical')
plt.show()

# Challenge 11: Read all sheets from excel spreadsheet. Assume sheets are asset values unless they contain the
# word liability in which case amounts and balances have to be negated to convert from liabilities to negative assets.

dct_accounts = pd.read_excel("bank_accounts.xlsx", sheet_name=None, skiprows=0)
for sheet_name, df in dct_accounts.items():
    if len(df) > 0:
        if 'liability' in sheet_name:
            df.Amount *= -1
            df.Balance *= -1
balance = 0
for sheet_name, df in dct_accounts.items():
    print(sheet_name)
    print(df.head())
    if df.shape[0] > 0:
        balance += df.at[0, 'Balance']
        balance -= df.at[0, 'Amount']
    df['Account'] = sheet_name
    df['Amount'] = df['Amount'].round(2)
df_combined = pd.concat(dct_accounts.values(), ignore_index=True).sort_values(by="Date")
dct_balance = {}
for index, row in df_combined.iterrows():
    balance += row['Amount']
    df_combined.at[index, 'Balance'] = balance
    dct_balance[row['Date']] = balance
print(df_combined)

plt.figure(figsize=(10, 10))
plt.title("Challenge 11 solution")
plt.plot(list(dct_balance.keys()), list(dct_balance.values()), drawstyle="steps-post")
plt.xticks(rotation='vertical')
plt.show()


if __name__=='__main__':
    m,d = map(int,input().split(' '))
    a = int(input())
    b = int(input())
    d = str(d)
    s = (a-a%m)+m
    count = 0
    for i in range(s,b+1,m):
        S = str(i)
        if i<10:    S=S+'0'
        if d not in S:  continue
        else:   found = True
        if d in S[::2] or d*int(len(S)/2)!=S[1::2]:
            found = False
            continue
        '''
        for j in range(len(S)):
            if (S[j]==d and (j+1)%2!=0) or (S[j]!=d and (j+1)%2==0):
                found = False
                break
        '''
        if found:   count +=1
    print (count%(pow(10,9)+7))

'''

D. Magic Numbers
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Consider the decimal presentation of an integer. Let's call a number d-magic if digit d appears in decimal presentation of the number on even positions and nowhere else.

For example, the numbers 1727374, 17, 1 are 7-magic but 77, 7, 123, 34, 71 are not 7-magic. On the other hand the number 7 is 0-magic, 123 is 2-magic, 34 is 4-magic and 71 is 1-magic.

Find the number of d-magic numbers in the segment [a, b] that are multiple of m. Because the answer can be very huge you should only find its value modulo 109 + 7 (so you should find the remainder after dividing by 109 + 7).
Input

The first line contains two integers m, d (1 ≤ m ≤ 2000, 0 ≤ d ≤ 9) — the parameters from the problem statement.

The second line contains positive integer a in decimal presentation (without leading zeroes).

The third line contains positive integer b in decimal presentation (without leading zeroes).

It is guaranteed that a ≤ b, the number of digits in a and b are the same and don't exceed 2000.
Output

Print the only integer a — the remainder after dividing by 109 + 7 of the number of d-magic numbers in segment [a, b] that are multiple of m.
Examples
Input

2 6
10
99

Output

8

Input

2 0
1
9

Output

4

Input

19 7
1000
9999

Output

6

Note

The numbers from the answer of the first example are 16, 26, 36, 46, 56, 76, 86 and 96.

The numbers from the answer of the second example are 2, 4, 6 and 8.

The numbers from the answer of the third example are 1767, 2717, 5757, 6707, 8797 and 9747.
'''


#encoding: utf-8

import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

def splitf(fsrc,freq,rsp):
	cursave=1
	minib=16
	maxdl=16
	with open(freq) as frd:
		with open(fsrc) as fsrd:
			cache=[]
			for line in frd:
				tmp=line.strip()
				if tmp:
					tmp=tmp.decode("utf-8")
					lgth,freq=tmp.split("	")
					lgth=int(lgth)
					freq=int(freq)
					if freq>minib:
						if cache:
							nstore=0
							for cu in cache:
								nstore+=cu[-1]
							with open(rsp+str(cursave)+".txt","w") as fwrt:
								for i in xrange(nstore):
									lind=fsrd.readline()
									lind=lind.strip()
									lind=lind.decode("utf-8")
									lind+="\n"
									fwrt.write(lind.encode("utf-8"))
							cursave+=1
							cache=[]
						with open(rsp+str(cursave)+".txt","w") as fwrt:
							for i in xrange(freq):
								lind=fsrd.readline()
								lind=lind.strip()
								lind=lind.decode("utf-8")
								lind+="\n"
								fwrt.write(lind.encode("utf-8"))
						cursave+=1
					else:
						if cache:
							if cache[0][0]-lgth<maxdl:
								cache.append([lgth,freq])
								nstore=0
								for cu in cache:
									nstore+=cu[-1]
								if nstore>minib:
									with open(rsp+str(cursave)+".txt","w") as fwrt:
										for i in xrange(nstore):
											lind=fsrd.readline()
											lind=lind.strip()
											lind=lind.decode("utf-8")
											lind+="\n"
											fwrt.write(lind.encode("utf-8"))
									cursave+=1
									cache=[]
							else:
								nstore=0
								for cu in cache:
									nstore+=cu[-1]
								with open(rsp+str(cursave)+".txt","w") as fwrt:
									for i in xrange(nstore):
										lind=fsrd.readline()
										lind=lind.strip()
										lind=lind.decode("utf-8")
										lind+="\n"
										fwrt.write(lind.encode("utf-8"))
								cursave+=1
								cache=[[lgth,freq]]
						else:
							cache=[[lgth,freq]]

def splitfl(srcfl,frqfl,rsflp):
	for i in xrange(len(srcfl)):
		splitf(srcfl[i],frqfl[i],rsflp[i])

if __name__=="__main__":
	fd=["train","test","dev"]
	splitfl([i+"s.txt" for i in fd],[i+"f.txt" for i in fd],["rs\\"+i for i in fd])


#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Stack.py
@author Luc Kusters
@date 11-11-2023
"""

import abc

class BaseNode(abc.ABC):

    @abc.abstractproperty
    def value(self):
        pass

    @abc.abstractproperty
    def next(self):
        pass

class NextNodeTypeError(TypeError):
    pass

class Node(BaseNode):

    def __init__(self, value, next_node=None):
        super().__init__()
        self.__value = value
        self.__next = next_node

    @property
    def value(self):
        return self.__value

    @property
    def next(self):
        return self.__next

    @next.setter
    def next(self, next_node: BaseNode):
        if not isinstance(next_node, (Node, type(None))):
            raise NextNodeTypeError(
                "Node.next only allows"
                " setting objects of type"
                f" {type(self).__name__} or None."
                )
        self.__next = next_node

    def __repr__(self):
        return f"Node(value={self.value}, next={self.next})"

class Stack(object):
    """Implements a Stack using a linked list"""

    def __init__(self):
        self.__head = None
        self.__counter: int = 0

    def push(self, value) -> None:
        """Push a value to the stack

        The stack creates a new Node object
        and sets its next_node to the current head.

        The new head is then set to the new node
        """
        new_node = Node(value, next_node=self.__head)
        self.__head = new_node
        self.__counter += 1

    def pop(self) -> Node.value:
        node = self.__head
        if node is not None:
            self.__head = self.__head.next
        self.__counter -= 1
        return node.value

    def head(self) -> Node.value:
        if self.__head is None:
            return None
        return self.__head.value

    def to_list(self):
        out = []
        current = self.__head
        while current is not None:
            out.append(current)
            current = current.next
        return reversed(out)

    def to_tuple(self):
        return tuple(self.to_list())

    def __len__(self):
        return self.__counter

    def __repr__(self):
        return f"Stack{tuple(n.value for n in self.to_list())}"

if __name__ == "__main__":
    # basic node tests
    assert Node(1).value == 1
    assert Node("a").value == "a"
    assert Node("abcdeg1234").value == "abcdeg1234"
    assert Node("abcdeg1234").next == None
    # linked list like tests
    assert isinstance(Node(1, Node(2)), Node)
    assert Node(1, Node(2)).next.value == 2
    assert Node(1, Node(2)).next.next == None
    # setting tests
    try:
        node = Node(1)
        node.next = Node(2)
        assert node.next.value == 2
        node.next = None
    except Exception:
        raise AssertionError("This try except block should"
                             " not raise any exceptions")
    try:
        node = Node(1)
        node.next = "a"
        node.next = 1
        node.next = 1.
        node.next = 1.j
        node.next = 1.j
        raise AssertionError("this try except block should"
                             " raise an exception but"
                             " didn't")
    except NextNodeTypeError:
        pass
    except Exception as e:
        raise AssertionError("this try except block should"
                             " only raise NextNodeTypeError"
                             " but raised the following"
                             f" exception:\n{e}")

    # stack tests
    stack = Stack()
    stack.push(1)
    stack.push(2)
    stack.push("c")
    assert stack.pop() == "c"
    assert stack.pop() == 2
    assert stack.pop() == 1


from geocoder import get_coordinates, get_nearest_object

import sys

def main():
    address = ''
    try:
        address = " ".join(sys.argv[1:])
    except:
        print('No data')
        exit(1)

    if not address:
        print('No data')
        exit(1)
    address_point = get_coordinates(address)
    district_name = get_nearest_object(address_point, "district")
    print(district_name)

if __name__ == "__main__":
    main()


class MatrixConverter:

    """
    def do_search(self, received_list, matrix):
        item = self.convert_matrix_to_number(matrix)
        first = 0
        last = len(received_list) - 1
        found = False
        while first <= last and not found:
            midpoint = (first + last) // 2
            if received_list[midpoint] == item:
                found = True
            else:
                if item < received_list[midpoint]:
                    last = midpoint - 1
                else:
                    first = midpoint + 1
        return found
        """

    def convert_matrix_to_number(self, matrix):
        number_str = ''
        for i in range(0, len(matrix)):
            for j in range(0, len(matrix[i])):
                number_str += matrix[i][j]
        item = int(number_str)
        return item


from stacks import TestStackSolutions
from two_pointers import TestTwoPointerSolutions
# from sliding_window import TestSlidingWindowSolutions
from binary_tree import TestBinaryTreeSolutions

# Map problem numbers to their respective test methods
PROBLEM_TESTS = {
    # Stack
    "20": ("testIsValid", TestStackSolutions),
    "94": ("testInorderTraversal", TestStackSolutions),
    "32": ("testLongestValidParentheses", TestStackSolutions),
    "239": ("testMaxSlidingWindow", TestStackSolutions),
    # Two Pointer
    "42": ("testTrappingRainWater", TestTwoPointerSolutions),
    "643": ("testFindMaxAverage", TestTwoPointerSolutions),
    # Binary Tree
    "103": ("testZigzagLevelOrder", TestBinaryTreeSolutions),
    "112": ("testHasPathSum", TestBinaryTreeSolutions),
}

def execute():
    problem_num = input("Which problem number would you like test? ")

    if problem_num not in PROBLEM_TESTS:
        print("Sorry, this problem number hasn't been solved yet.\n")
        return

    print(f"\nOK, executing problem number {problem_num}.\n")

    # Call the corresponding test method
    method_name, test_class = PROBLEM_TESTS[problem_num]
    test = test_class()
    try:
        getattr(test, method_name)()
    except Exception as e:
        print(f"An error occurred while running {method_name}: {str(e)}")

if __name__ == "__main__":
    execute()


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from pathlib import Path

import numpy as np
import tensorflow as tf
from dotenv import load_dotenv

from annotation.black_effect.pseudo_ou_effect import BlackPseudoOuEffect
from ..white_all_check import WhiteAllCheckLayer
from annotation.direction import Direction

__author__ = 'Yasuhiro'
__date__ = '2018/3/25'

class TestCheckCase1(tf.test.TestCase):
    @classmethod
    def setUpClass(cls):
        dotenv_path = Path(__file__).parents[3] / '.env'
        load_dotenv(str(dotenv_path))

        cls.data_format = os.environ.get('DATA_FORMAT')
        cls.use_cudnn = bool(os.environ.get('USE_CUDNN'))

    def test_case1(self):
        """
        動作確認中に発覚したものについて調べる
         .  n  .  .  .  .  .  n  .
         l  .  k  .  g  .  s  .  l
         .  s  .  p  .  .  .  .  .
         .  p  .  g  p  p  r  p  p
         .  .  p  .  .  R  p  P  .
         p  .  .  G  .  P  G  .  .
         P  P  P  .  .  .  .  B  P
         .  B  .  .  .  .  .  .  L
         L  N  S  .  K  .  S  N  .

         p*3

        :return:
        """
        board = np.array([[28, 15, 28, 14, 28, 28,  0,  1, 28],
                          [16, 28, 28, 14,  0, 28,  4, 28,  2],
                          [28, 17, 28, 19, 14,  6, 28, 28,  3],
                          [28, 28, 28, 14,  5,  0, 28, 28, 28],
                          [28, 20, 28, 14, 28, 28, 28, 28,  7],
                          [28, 28, 14, 20, 28,  6, 28, 28, 28],
                          [28, 21, 28, 28, 14, 28,  0, 28,  3],
                          [16, 28, 17, 14, 28, 28,  0,  4,  2],
                          [28, 15, 28, 28, 28, 14,  0, 28,  1]],
                         dtype=np.int32)
        shape = (1, 1, 9, 9) if self.data_format == 'NCHW' else (1, 9, 9, 1)
        board = np.reshape(board, shape)

        pseudo_effect = BlackPseudoOuEffect(
            data_format=self.data_format, use_cudnn=self.use_cudnn
        )(board)

        all_check, long_check = WhiteAllCheckLayer()(board, pseudo_effect)

        with self.test_session() as sess:
            all_check_, long_check_ = sess.run([all_check, long_check])

        for direction, check in all_check_.items():
            with self.subTest(direction=direction):
                self.assertFalse(check)

        for direction, check in long_check_.items():
            with self.subTest(direction=direction):
                self.assertFalse(check)


# https://stackoverflow.com/questions/35160256/how-do-i-output-lists-as-a-table-in-jupyter-notebook
# http://nbviewer.jupyter.org/github/ipython/ipython/blob/4.0.x/examples/IPython%20Kernel/Rich%20Output.ipynb
# https://meta.stackexchange.com/questions/5916/allow-marking-text-as-fixed-width-font

import IPython
import pylab as py
import collections

def main():
    base_addr = 0x60000000
    size_t = 4
    no_cell = 20

    memory_map_random(base_addr, size_t, no_cell)

def memory_map_random(base_addr, size_t, no_cell):

    contents_dict = malloc(size_t, no_cell, base_addr)

    show(contents_dict)

def show(contents_dict):
    """
    Show md table in the ipynb
    """
    rows_list = get_md_table(contents_dict)

    IPython.display.display(IPython.display.Markdown('\n'.join(rows_list)))

def malloc(element_size, num_elements,base_addr=0x60000000):
    """
    Build an OrderdDict of (int : int) pairs for a memory map starting a base memory address
    """
    contents_dict = collections.OrderedDict(
        {
            'header': ['Address (hex)','Content (hex)'], # header list
            'content_formatter': f'
%0{2*element_size}x
' # adjustable to element_size
        }
    )

    # Content builder loop
    for i in range(base_addr, base_addr+(num_elements*element_size)+1, element_size):
        key = i
        value = py.randint(0, 2**31-1)

        contents_dict[key] = value

    return contents_dict

def get_md_table(contents_dict):
    """
    Convert an OrderdDict of (int : int) pairs into a multiline md table string
    contents_dict : orderd dictionary of (int : int) pairs
    """
    rows_list = [
        '|'.join(contents_dict['header']), # header list -> header string
        '|'.join([':-----:'] * len(contents_dict['header'])) # separator string
    ]

    # Markdown converter table
    for key in contents_dict:
        if  not isinstance(key, str): # to skip keys of strings
            columns_list = [f'
{key:08x}
',
            contents_dict['content_formatter'] % contents_dict[key]]

            # Indicate a row of the table
            rows_list.append('|'.join(columns_list))

    return rows_list

if "__main__" == __name__:
    main()


n = input("Enter a number up to which you'd like a list of prime numbers")
try:
    n = int(n)
except:
    print('Please enter an integer as digits')

a_range = range(2,n)
lst = list(a_range)
prime_lst = []

while True:
    if len(lst) == 0:
        break
    else:
        p = lst[0]
        prime_lst.append(p)
        lst = list(i for i in lst if i % p)

print(prime_lst)


import pandas as pd
from modules import DataDrop as DD
from modules import threeGroups as tg

class Kerosene:
    def __init__(self, rawDataPath):
        self.rawDataPath = rawDataPath
        self.df = pd.read_csv(rawDataPath)
        self.df["supplied_at"] = pd.to_datetime(self.df["supplied_at"], format="%Y-%m-%d %X")
        self.id = pd.Series(pd.unique(self.df["customer_id"]))
        self.split()

    def split(self):
        self.road_heating = self.df[self.df["purpose"] == "R"]
        self.road_heating_id = pd.Series(pd.unique(self.road_heating["customer_id"]))
        self.road_heating.reset_index(inplace=True)
        self.normal_use = self.df[self.df["purpose"] != "R"]
        self.normal_use_id = pd.Series(pd.unique(self.normal_use["customer_id"]))
        self.normal_use.reset_index(inplace=True)

    def threeGroups(self, weatherPath):
        df_weather = pd.read_csv(weatherPath)
        df_weather = DD.weather_drop(df_weather)

        self.normal_use_drop = self.normal_use.copy()
        # Drop zero first
        for i in range(self.normal_use_drop.shape[0]):
            if self.normal_use_drop.loc[i, "volume"] == 0:
                self.normal_use_drop.drop(i, inplace=True)
        self.normal_use_drop.reset_index(inplace=True, drop=True)
        # Then Drop interval
        self.normal_use_drop = DD.supply_data_drop(self.normal_use_drop)
        self.normal_use_drop.reset_index(inplace=True, drop=True)
        normal_use_in_season = self.normal_use_drop.copy()

        ALL_ID = pd.unique(normal_use_in_season["customer_id"])
        self.Highcc, self.Lowcc = tg.split_three_group(normal_use_in_season, ALL_ID, df_weather)
        # Find HighccOneSeason's id, it is hard to find it directly. so we drop others.
        to_drop = list(self.Highcc.keys()) + list(self.Lowcc.keys())
        normal_use_in_season.set_index("customer_id", inplace=True)

        self.HighccOneSeason = normal_use_in_season.drop(to_drop).copy()
        self.HighccOneSeason.reset_index(inplace=True)
        # self.HighccOneSeason = self.HighccOneSeason.drop('index', axis=1)


##### 문제 #####
# 이진 검색 트리는 다음과 같은 세 가지 조건을 만족하는 이진 트리이다.
# 노드의 왼쪽 서브트리에 있는 모든 노드의 키는 노드의 키보다 작다.
# 노드의 오른쪽 서브트리에 있는 모든 노드의 키는 노드의 키보다 크다.
# 왼쪽, 오른쪽 서브트리도 이진 검색 트리이다.
# 이진 검색 트리를 전위 순회한 결과가 주어졌을 때, 이 트리를 후위 순회한 결과를 구하는 프로그램을 작성하시오.

##### 입력 #####
# 트리를 전위 순회한 결과가 주어진다.
# 노드에 들어있는 키의 값은 106보다 작은 양의 정수이다.
# 모든 값은 한 줄에 하나씩 주어지며, 노드의 수는 10,000개 이하이다.
# 같은 키를 가지는 노드는 없다.

##### 출력 #####
# 입력으로 주어진 이진 검색 트리를 후위 순회한 결과를 한 줄에 하나씩 출력한다.

import sys
sys.setrecursionlimit(100000)

# pre_order 결과를 일단 만든다.
pre_order = []
while True:
    try :
        pre_order.append(int(sys.stdin.readline().rstrip()))
    except:
        break

def get_post_order(pre_order):
    length = len(pre_order)

    # 들어온 값이 1개 미만이라면 그냥 그 값을 반환한다.
    if length <= 1:
        return pre_order

    # pre_order에 root 다음 숫자부터, root와 비교한다.
    for i in range(1, length):
        # root보다 큰 수를 기준으로 다시 함수를 호출한다.
        if pre_order[i] > pre_order[0]:
            # root보다 큰 수 전까지, 큰 수 부터 끝까지, root
            return get_post_order(pre_order[1:i]) + get_post_order(pre_order[i:]) + [pre_order[0]]

    return get_post_order(pre_order[1:]) + [pre_order[0]]

result = get_post_order(pre_order)
for num in result :
    print(num)


import sys

def get_grammar():
    productions = []
    print("Ingrese su gramática:")
    production = input().replace(" ", "")
    if not production:
        print("Error: Debe ingresar al menos una producción.")
        sys.exit()
    initial_symbol = production.split('->')[0].strip()
    right_side = production.split('->')[1].split('|')
    productions.extend([production.replace(production.split('->')[1], rs) for rs in right_side])

    while True:
        production = input().replace(" ", "")
        if not production:
            break
        if '->' in production:
            right_side = production.split('->')[1].split('|')
            productions.extend([production.replace(production.split('->')[1], rs) for rs in right_side])
        else:
            productions.extend([p.replace('->', production) for p in productions[-len(right_side):]])

    return productions, initial_symbol

def terminales(G):
    terminales = set()   #Al ser conjunto no se agregan carácteres repetidos
    for i in G:
        char = i.split('->')
        for j in char[1].strip():
            if j.isupper() == False and j != '.' and j != '':
                terminales.add(j)

    terminales.add('$')
    return terminales

def no_terminales(G):
    nterminales = set()  #Al ser conjunto no se agregan carácteres repetidos
    for i in G:
        char = i.split('->')
        for j in char[1].strip():
            if j.isupper():
                nterminales.add(j)
    return nterminales


import webget
import pandas as pd
import numpy as np
import re
from collections import Counter
import matplotlib.pyplot as plt

# Setting up useable csv file
webget.download("https://raw.githubusercontent.com/fivethirtyeight/data/master/twitter-ratio/BarackObama.csv")
webget.download("https://raw.githubusercontent.com/fivethirtyeight/data/master/twitter-ratio/realDonaldTrump.csv")

obama_df = pd.read_csv("BarackObama.csv", encoding='ANSI')
donald_df = pd.read_csv("realDonaldTrump.csv", encoding='ANSI')
obama_matrix = obama_df.as_matrix()
donald_matrix = donald_df.as_matrix()
#                              0        1   2   3       4           5       6
#Help understanding, lines: created_at,text,url,replies,retweets,favorites,user - Trump and Obama .. Both datasets.

# See columns for later use
# print(ks_df.dtypes)
def question_1():
    count = Counter(donald_matrix[:,6])
    print("Question 1:")
    print(sum(count.values()))

def question_2():
    count = Counter(obama_matrix[:,6])
    print("Question 2:")
    print(sum(count.values()))

def question_3():
    obama_text = ''.join(obama_matrix[:,1]).lower()
    obama_count = [m.start() for m in re.finditer('yes we can', obama_text)]

    donald_text = ''.join(donald_matrix[:,1]).lower()
    donald_count = [m.start() for m in re.finditer('makeamericagreatagain', donald_text)]
    donald_count2 = [m.start() for m in re.finditer('make america great again', donald_text)]
    print("Question 3:")
    print("Obama mentions his slogan: " + str(len(obama_count))+" times")
    print("Donald mentions his slogan: " + str(len(donald_count)+len(donald_count2))+" times")

def question_4():
    obama_text = ''.join(obama_matrix[:,1]).lower()
    obama_count = [m.start() for m in re.finditer('iran', obama_text)]

    donald_text = ''.join(donald_matrix[:,1]).lower()
    donald_count = [m.start() for m in re.finditer('iran', donald_text)]
    print("Question 4:")
    print("Obama mentions Iran: " + str(len(obama_count)) + " times")
    print("Donald mentions Iran: " + str(len(donald_count)) + " times")

def question_5():
    obama_text = ''.join(obama_matrix[:,1]).lower()
    obama_count = [m.start() for m in re.finditer('obamacare', obama_text)]

    donald_text = ''.join(donald_matrix[:,1]).lower()
    donald_count = [m.start() for m in re.finditer('obamacare', donald_text)]
    print("Question 5:")
    print("Obama mentions Obamacare: " + str(len(obama_count)) + " times")
    print("Donald mentions Obamacare: " + str(len(donald_count)) + " times")

question_1()
question_2()
question_3()
question_4()
question_5()


from sympy import *

expr = cos(x) + 1
print(expr.subs(x, y))
x, y, z = symbols("x y z")
print(expr=x**y)
print(expr)
expr = sin(2 * x) + cos(2 * x)
print(expand_trig(expr))
print(expr.subs(sin(2 * x), 2 * sin(x) * cos(x)))
expr = x**4 - 4 * x**3 + 4 * x**2 - 2 * x + 3
replacements = [(x**i, y**i) for i in range(5) if i % 2 == 0]
print(expr.subs(replacements))
str_expr = "x**2 + 3*x - 1/2"
expr = sympify(str_expr)
expr
expr.subs(x, 2)
expr = sqrt(8)
print(expr.evalf())
expr = cos(2 * x)
expr.evalf(subs={x: 2.4})
one = cos(1) ** 2 + sin(1) ** 2
print((one - 1).evalf())


import cv2
import sys
import numpy as np
import os
import tensorflow
import keras.backend
config = tensorflow.ConfigProto()
config.inter_op_parallelism_threads = 1
keras.backend.set_session(tensorflow.Session(config=config))

sys.path.append("/Users/stephaniexia/Documents/lab/Code/Mask_RCNN")
from sample.inference import detect_by_maskrcnn

class_names = ['person', 'bicycle', 'car', 'motorcycle', 'airplane',
               'bus', 'train', 'truck', 'boat', 'traffic light',
               'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
               'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
               'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
               'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
               'kite', 'baseball bat', 'baseball glove', 'skateboard',
               'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
               'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
               'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
               'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
               'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
               'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
               'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
               'teddy bear', 'hair drier', 'toothbrush']

category_index = {}
for class_id in range(len(class_names)):
    category_index[class_id+1] = {class_names[class_id]}

def getTrainingData(window_name, camera_id):
    cv2.namedWindow(window_name) # 创建窗口
    cap = cv2.VideoCapture(camera_id) # 打开摄像头

    color = (0,255,0) #

    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        output_rgb = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

        boxes, classes, scores = detect_by_maskrcnn(output_rgb)
        print(boxes, classes, scores)

        boxes = np.squeeze(boxes, axis=0)
        classes = np.squeeze(classes,axis = 0)
        scores = np.squeeze(scores, axis=0)

        print(boxes, classes, len(scores))

        if len(scores) > 0:
            for idx in range(len(scores)):
                x1,y1,x2,y2 = boxes[idx]

                cv2.rectangle(frame, (x1,y1), (x2,y2), color, 2) # 画出矩形框
                font = cv2.FONT_HERSHEY_SIMPLEX # 获取内置字体
                cv2.putText(frame, ("{} : {}".format(category_index[classes[idx]], scores[idx])), (x1+30, y1+30), font, 1, (255,0,255), 4) # 调用函数，对人脸坐标位置，添加一个(x+30,y+30）的矩形框用于显示当前捕捉到了多少人脸图片

        cv2.imshow(window_name, frame)
        c = cv2.waitKey(10)
        if c & 0xFF == ord('q'):
            break

    cap.release()#释放摄像头并销毁所有窗口
    cv2.destroyAllWindows()
    print('Finished.')
#主函数
if __name__ =='__main__':
    print ('catching your face and writting into disk...')
    getTrainingData('getTrainData',0)


# UVA - 11112 / Babylonian Roulette
# Ad hoc

import math
while(True):
    p0, b, pf = map(int, input(). split())
    if(p0 + b + pf == 0):
        break
    if((pf - p0) % b):
        print("No accounting tablet")
    else:
        foo = abs(pf - p0)/b
        print(math.ceil(foo/3))


from Bio.Blast import NCBIXML
import re

#Define file names which are to be parsed
filename = ["result.xml"]
genelist = []

#Driving loop
for i in filename:
	bout = open(i)
	b_records = NCBIXML.parse(bout) #Main parsing function
	outfile = open("record_%s.record" % i,'w') #Each parsed sequence is stored in a new file
	for b_record in b_records:
		for alig in b_record.alignments:
			for hsp in alig.hsps:
				text = alig.hit_def
				m = re.findall(r'\bGN=\w+', text)
				m = m[0]
				print (m)
				z = m.split('=')
				genelist.append(z[1])
				outfile.write("%s\n" % z[1])
	outfile.close()
print (genelist)


#!/usr/bin/env python3

"""Write 4 coils to True, wait 2s, write False and redo it."""

import time
from pyModbusTCP.client import ModbusClient

# init
c = ModbusClient(host='localhost', port=502, auto_open=True, debug=False)
bit = True

# main loop
while True:
    # write 4 bits in modbus address 0 to 3
    print('write bits')
    print('----------\n')
    for ad in range(4):
        is_ok = c.write_single_coil(ad, bit)
        if is_ok:
            print('coil #%s: write to %s' % (ad, bit))
        else:
            print('coil #%s: unable to write %s' % (ad, bit))
        time.sleep(0.5)

    print('')
    time.sleep(1)

    # read 4 bits in modbus address 0 to 3
    print('read bits')
    print('---------\n')
    bits = c.read_coils(0, 4)
    if bits:
        print('coils #0 to 3: %s' % bits)
    else:
        print('coils #0 to 3: unable to read')

    # toggle
    bit = not bit
    # sleep 2s before next polling
    print('')
    time.sleep(2)


"""공부 후 작성해본 코드"""

import sys
sys.stdin = open('input1.txt')
input = sys.stdin.readline

N, K = map(int, input().split())
numbers = list(map(int, input().split()))

odd_cnt = even_cnt_max = e = size = 0

if N == 1:
    print(0) if numbers[0] % 2 else print(1)
else:
    for s in range(N):
        # 0. 이미 e는 끝지점에 도착했는가?
        if e < N-1:
            # 1. s -> e: 홀수가 K개 될때까지 없애면서 부분수열 만들기
            while odd_cnt <= K:
                # 홀수일 경우
                if numbers[e] % 2 == 1:
                    if odd_cnt == K:
                        break
                    odd_cnt += 1
                    size += 1
                # 짝수일 경우
                else:
                    size += 1

                # e가 끝지점에 도달했을때의 처리과정
                if e <= N-2:
                    e += 1
                elif e == N-1:
                    break

        # 2. 짝수인 최장부분수열 갱신
        if size - odd_cnt > even_cnt_max:
            even_cnt_max = size - odd_cnt

        # 3. s가 다음으로 넘어가면 size가 하나 줄어든다!
        size -= 1
        if numbers[s] % 2 == 1:
            odd_cnt -= 1
    print(even_cnt_max)

2022/0504/[BOJ_22857]가장 긴 짝수 연속한 부분 수열 (small)/김혜림.py


#! /usr/bin/env python
# -*- coding: utf-8 -*-

#L = []
#for x in range(1, 11):
#    L.append(x * x)
#print(L)

#L = [x * x for x in range(1, 11)]
#print(L)
#L = [m + n for m in 'ABC' for n in 'XYZ']
#print(L)
#d = {'x': 'A', 'y': 'B', 'z': 'C' }
#print([k + '=' + v for k, v in d.items()])
L = ['Hello', 'World', 'ORACLE', 'APPle']
t = [s.lower() for s in L]
print(t)


import os
import sys
import time
import math
import numpy as np
import tensorflow as tf
# We'll use matplotlib for graphics.
import matplotlib.pyplot as plt
import threading

from sklearn.neighbors import RadiusNeighborsClassifier,KNeighborsClassifier
from sklearn.manifold import TSNE
from .utils import *

def metric_visualization(data_metric, lbls, attr_names, outfile):
    X_embedded = TSNE(n_components=2).fit_transform(data_metric)
    # plot the result
    vis_x = X_embedded[:, 0]
    vis_y = X_embedded[:, 1]
    n_cls = len(attr_names)
    plt.scatter(vis_x, vis_y,
        c=lbls, marker='.',
        cmap=plt.cm.get_cmap("jet", n_cls))
    plt.colorbar(ticks=range(n_cls)).set_ticklabels(attr_names)
    plt.clim(-0.5, 9.5)
    plt.savefig(outfile)
    plt.close()

def softmax(x, axis=None):
    x = x - x.max(axis=axis, keepdims=True)
    y = np.exp(x)
    return y / y.sum(axis=axis, keepdims=True)

class SemiTrainer(object):
    def __init__(self, datasets, batchsize):
        self.datasets = datasets
        self.current_epoch = tf.Variable(0, name='current_epoch', dtype=tf.int32)
        self.current_batch = tf.Variable(0, name='current_batch', dtype=tf.int32)
        self.batchsize = batchsize
        self.perm = None
        self.test_mode = False
        self.data_metric = None
        self.data_labels = None
        self.num_semi = 0
        self.semi_mask = None

    def init_semi_perm(self):
        self.perm = np.random.permutation(len(self.datasets))

        if not hasattr(self.data_labels, 'get_semi_labels'):
            self.semi_mask = None
            self.num_semi = 0
        else:
            semi_tgts, mask_train, mask_confidence = self.datasets.get_semi_labels()
            self.semi_mask = mask_train == 0
            self.num_semi = np.count_nonzero(self.semi_mask)
            self.datasets.attrs[self.semi_mask, :] = 0
            semi_confidence_mask = np.logical_and(self.semi_mask, mask_confidence)
            self.datasets.attrs[semi_confidence_mask, :] = 0.5 * semi_tgts[semi_confidence_mask, :]

        print("Num Semi: %d" % self.num_semi)

        return self.perm

    def shuffle_perm(self):
        if self.perm is None:
            return self.init_semi_perm()
        self.perm = np.random.permutation(len(self.datasets))
        return self.perm

    def prepare_test_data(self, model):
        imgs_t, c_t = self.datasets.get_test_data()
        self.test_data = {'test_input': imgs_t, 'c_test': c_t}
        model.test_data = self.test_data

    def create_directory(self, model):
        # Create output directories if not exist
        self.out_dir = os.path.join(model.output, model.name)
        if not os.path.isdir(self.out_dir):
            os.makedirs(self.out_dir)

        self.res_out_dir = os.path.join(self.out_dir, 'results')
        if not os.path.isdir(self.res_out_dir):
            os.makedirs(self.res_out_dir)

        self.chk_out_dir = os.path.join(self.out_dir, 'checkpoints')
        if not os.path.isdir(self.chk_out_dir):
            os.makedirs(self.chk_out_dir)

        time_str = time.strftime('%Y%m%d_%H%M%S', time.localtime())
        log_out_dir = os.path.join(self.out_dir, 'log', time_str)
        if not os.path.isdir(log_out_dir):
            os.makedirs(log_out_dir)

        return log_out_dir

    def print_eta(self, e, b, bsize):
        num_data = len(self.datasets)
        # Print current status
        elapsed_time = time.time() - self.start_time
        eta = elapsed_time / (b + bsize) * (num_data - (b + bsize))
        ratio = 100.0 * (b + bsize) / num_data
        print('Epoch #%d,  Batch: %d / %d (%6.2f %%)  ETA: %s' % \
              (e + 1, b + bsize, num_data, ratio, time_format(eta)))

    def print_losses(self, losses):
        for i, (k, v) in enumerate(losses):
            text = '%s = %8.6f' % (k, v)
            print('  %25s' % (text), end='')
            if (i + 1) % 3 == 0:
                print('')

    def update_metrics(self, model, e):
        num_data = len(self.datasets)
        for b in range(self.current_batch.eval(), num_data, self.batchsize):
            # Check batch size
            bsize = min(self.batchsize, num_data - b)
            x_batch = (self.datasets.images[b:b+bsize], self.datasets.attrs[b:b+bsize])
            ret_batch = model.predict(x_batch)
            self.data_metric[b:b+bsize, :] = ret_batch['z_measure']
            self.data_labels[b:b+bsize, :] = ret_batch['y_predict']

    def metric_visualization(self, e):
        if e % 50 != 0:
            return
        outfile = os.path.join(self.res_out_dir, 'data_metric_epoch_%d' % (e+1))
        np.savez(outfile, data_metric = self.data_metric, data_labels = self.data_labels)

        # threading.Thread(target=metric_visualization, kwargs=dict(
        #     data_metric = self.data_metric[self.perm_full],
        #     lbls = np.argmax(self.datasets.attrs[self.perm_full], axis=1),
        #     attr_names = self.datasets.attr_names,
        #     outfile = os.path.join(self.res_out_dir, 'metric_epoch_%04d.png' % (e + 1))
        #     )
        # ).start()

    def label_propagation(self, model, e):
        if self.num_semi <= 0:
            return
#        radnn = RadiusNeighborsClassifier(radius=2, outlier_label=np.zeros(model.num_attrs))
        radnn = KNeighborsClassifier(n_neighbors=5, weights='distance')
        radnn.fit(self.data_metric[self.semi_mask==0], self.datasets.attrs[self.semi_mask==0])
        lbls = radnn.predict(self.data_metric[self.semi_mask])
        lbls_mask = np.any(lbls, axis=1)
        print("Label Propagation: %d" % np.count_nonzero(lbls_mask))
        data_consider = self.data_labels[self.semi_mask]
        coherence = np.argmax(data_consider, axis=1) == np.argmax(lbls, axis=1)
        coherence[lbls_mask==0] = 0
        confidence = np.max(softmax(data_consider, axis=1), axis=1) > 0.9
        coh_and_cof = np.logical_and(coherence, confidence)
        print("Label Coherence: %d, confidence: %d, coh_and_cof: %d" %
              (np.count_nonzero(coherence), np.count_nonzero(confidence), np.count_nonzero(coh_and_cof)))
        lbls[coh_and_cof == 0] = 0
        self.datasets.attrs[self.semi_mask, :] = 0.5*lbls

    def do_batch(self, model, e, b):
        num_data = len(self.datasets)
        # Check batch size
        bsize = min(self.batchsize, num_data - b)
        indx = self.perm[b:b+bsize]
        if bsize < self.batchsize:
            return

        # Get batch and train on it
        x_batch = model.make_batch(self.datasets, indx)
        ret_batch = model.train_on_batch(x_batch, e * num_data + (b + bsize))

        self.print_eta(e, b, bsize)
        self.print_losses(ret_batch.losses)
        # self.update_weights(indx, ret_batch.results)

        print('\n')
        sys.stdout.flush()

        # Save generated images
        save_period = 10000
        if b != 0 and ((b // save_period != (b + bsize) // save_period) or ((b + bsize) == num_data)):
            outfile = os.path.join(self.res_out_dir, 'epoch_%04d_batch_%d.png' % (e + 1, b + bsize))
            model.save_images(outfile)
            model.test_accruacy()
            outfile = os.path.join(self.chk_out_dir, 'epoch_%04d' % (e + 1))
            model.save_model(outfile)

    def main_loop(self, model, epochs=100):
        """
        Main learning loop
        """
        log_out_dir = self.create_directory(model)

        # Make test data
        self.prepare_test_data(model)

        # Start training
        with model.sess.as_default():
            model.resume_model()

            # Update rule
            num_data = len(self.datasets)
            update_epoch = self.current_epoch.assign(self.current_epoch + 1)
            update_batch = self.current_batch.assign(tf.mod(tf.minimum(self.current_batch + self.batchsize, num_data), num_data))

            model.writer = tf.summary.FileWriter(log_out_dir, model.sess.graph)
            model.sess.graph.finalize()

            print('\n\n--- START TRAINING ---\n')
            for e in range(self.current_epoch.eval(), epochs):
                self.data_metric = np.zeros((len(self.datasets), model.metric_dims), dtype=np.float32)
                self.data_labels = np.zeros((len(self.datasets), model.num_attrs), dtype=np.float32)
                self.shuffle_perm()
                self.start_time = time.time()
                for b in range(self.current_batch.eval(), num_data, self.batchsize):
                    # Update batch index
                    model.sess.run(update_batch)
                    self.do_batch(model, e, b)
                    if self.test_mode:
                        print('\nFinish testing: %s' % self.name)
                        return
                print('')
                if e+1 >= 50:
                    self.update_metrics(model, e)
                    self.metric_visualization(e)
                    self.label_propagation(model, e)
                model.sess.run(update_epoch)

        print('Finished training')


from http import HTTPStatus
from typing import Any, Dict, List, Optional

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...types import Response

def _get_kwargs(
    workspace: str,
    *,
    client: AuthenticatedClient,
    json_body: List[str],
) -> Dict[str, Any]:
    url = "{}/api/v1.0/workspaces/{workspace}/table-order".format(client.base_url, workspace=workspace)

    headers: Dict[str, str] = client.get_headers()
    cookies: Dict[str, Any] = client.get_cookies()

    json_json_body = json_body

    return {
        "method": "patch",
        "url": url,
        "headers": headers,
        "cookies": cookies,
        "timeout": client.get_timeout(),
        "follow_redirects": client.follow_redirects,
        "json": json_json_body,
    }

def _parse_response(*, client: Client, response: httpx.Response) -> Optional[Any]:
    if response.status_code == HTTPStatus.OK:
        return None
    if client.raise_on_unexpected_status:
        raise errors.UnexpectedStatus(response.status_code, response.content)
    else:
        return None

def _build_response(*, client: Client, response: httpx.Response) -> Response[Any]:
    return Response(
        status_code=HTTPStatus(response.status_code),
        content=response.content,
        headers=response.headers,
        parsed=_parse_response(client=client, response=response),
    )

def sync_detailed(
    workspace: str,
    *,
    client: AuthenticatedClient,
    json_body: List[str],
) -> Response[Any]:
    """Change the order of tables in a workspace

     Specify the order of tables, e.g., when viewing a workspace on the website, or when requesting the
    table list via API.

     A total order for all tables can be given, but table names can be left out.
     Given tables will be moved to the front, and all not explicitly listed tables will appear
    afterwards.

    Args:
        workspace (str):  Example: workspace-name.
        json_body (List[str]):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[Any]
    """

    kwargs = _get_kwargs(
        workspace=workspace,
        client=client,
        json_body=json_body,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(client=client, response=response)

async def asyncio_detailed(
    workspace: str,
    *,
    client: AuthenticatedClient,
    json_body: List[str],
) -> Response[Any]:
    """Change the order of tables in a workspace

     Specify the order of tables, e.g., when viewing a workspace on the website, or when requesting the
    table list via API.

     A total order for all tables can be given, but table names can be left out.
     Given tables will be moved to the front, and all not explicitly listed tables will appear
    afterwards.

    Args:
        workspace (str):  Example: workspace-name.
        json_body (List[str]):

    Raises:
        errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
        httpx.TimeoutException: If the request takes longer than Client.timeout.

    Returns:
        Response[Any]
    """

    kwargs = _get_kwargs(
        workspace=workspace,
        client=client,
        json_body=json_body,
    )

    async with httpx.AsyncClient(verify=client.verify_ssl) as _client:
        response = await _client.request(**kwargs)

    return _build_response(client=client, response=response)


# Script control setup area
# script info
#__script__.title = 'Scan Guide'
#__script__.version = '1.0'

# Use below example to create parameters.
# The type can be string, int, float, bool, file.
guide_names = Par('string', 'ga,g1,g2,g3,g4,g5,g6,g7,g8,g9')
count_mode = Par('string', 'time', options=['time', 'count'])
count_preset = Par('float', 30)
att = Par('float', 270)

# Use below example to create a button
act1 = Act('act1_changed()', 'run scan')
def act1_changed():
    guides = guide_names.value
    if len(guides) > 0:
        if count_mode.value == 'time':
            mode = 'time'
        else:
            mode = 'count'
        guideList = guides.split(',')

        config.clear()
        for g in guideList:
            slog('drive guide ' + g)
            config.guide = g
            config.drive()

            quokka.driveAtt(att.value)

            slog('scan ' + str(mode) + ' ' + str(count_preset.value))
            quokka.scan(mode, count_preset.value)
            slog('file saved at ' + sics.get_base_filename())

# Use below example to create a new Plot
# Plot4 = Plot(title = 'new plot')

# This function is called when pushing the Run button in the control UI.
def __run_script__(fns):
    act1_changed()

def __dispose__():
    global Plot1
    global Plot2
    global Plot3
    Plot1.clear()
    Plot2.clear()
    Plot3.clear()


productsList = []

#Welcome notes
print('Welcome to your very own app - CookIt')
print('What would you like to do today?')

#Start menu
def StartMenuChoice():
    print('''
    1   See inventory
    2   Create new product
    3   Amend the inventory
    4   Exit app''')

    choicemade = int(input())
    return choicemade

def create_product(NewProd = 'not known'):
    if NewProd != 'not known':
        NewItem = NewProd
    else:
        NewItem = input('What is your new product called? ')
    productsList.append(NewItem)
    print(f'{NewItem} has been added to your inventory')

def see_inv():
    print(' ')
    for i in productsList:
        print(i)
    print(' ')

def amend_product():
    print('This is how your inventory currently looks')
    see_inv()
    item = input('Which item would you like to amend? ')
    if item in productsList:
        for i in range(len(productsList)):
            product = productsList[i]
            if item.lower() == product.lower():
                new_name = input(f'What would you like {product} to change to? ')
                productsList[i] = new_name
                print(f'{product} has been updated to {new_name}. This is how the inventory now looks:')
                see_inv()
                return
    else:
        ans = input('''I\'m sorry, that item does not exist in your inventory. Would you like to add it? Y/N
        ''')
        if ans.upper() == 'Y':
            create_product(item)
            return
        elif ans.upper() == 'N':
            if input('Would you like to try again? Y/N').upper() =='Y':
                amend_product()
            else:
                return

#Ask what they would like to do
choice =1
while choice!=4: # keep asking what they want to do until they ask to quit
    choice = StartMenuChoice()

    #run different functions based on choice
    if choice == 1:
        print('You have chosen to see your inventory')
        see_inv()
    elif choice ==2:
        print('You have chosen to create a new product')
        create_product()
        print('This is how your inventory now looks:')
        see_inv()
    elif choice ==3:
        print('You have chosen to amend the inventory')
        amend_product()
    else:
        print('Thanks for visiting today')
        quit()

    print('What would you like to do next?')


import os, pymonetdb
import subprocess

db = os.getenv("TSTDB")
port = os.getenv("MAPIPORT")

client1 = pymonetdb.connect(database=db, port=port, autocommit=True)
cur1 = client1.cursor()
cur1.execute('''
CREATE TABLE test (x INTEGER, y STRING);
INSERT INTO test VALUES (42, 'Hello'), (NULL, 'World');
''')

cur1.close()
client1.close()

cmd = ['example_proxy', port, db]
results = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')

if results.stderr:
    print(results.stderr)

lines = results.stdout.splitlines()

if len(lines) != 3:
    print(results.stdout)
    print("Received {} lines, expected 3".format(len(lines)))
    exit(1)

def test_equal(expected, received):
    if received != expected:
        print("expected:")
        print(expected)
        print("received:")
        print(received)
        exit(1)

expected="Query result with 2 cols and 2 rows"
test_equal(expected, lines[0])

expected="42, Hello"
test_equal(expected, lines[1])

expected="NULL, World"
test_equal(expected, lines[2])


data_dir = './data'

data_type = 'val2017'

val_path = f"{data_dir}/annotations/uitviic_captions_{data_type}.json"

# results: trên tập test, eval: trên tập eval
subtypes = ['results', 'eval']

alg_name = 'machineoutput'

[res_file, eval_file]= \
    [f'{data_dir}/results/captions_{data_type}_{alg_name}_{subtype}.json' for subtype in subtypes]

# tokenizer = 'nltk'
tokenizer = 'pyvi'


# TABUADA v3.0
# Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário. O programa será interrompido quando o número solicitado for negativo.

while True:
    n = int(input('Digite um numero: '))
    print('=-' * 20)
    if n < 0:
        break
    for c in range(1, 11):
        result = n * c
        print(f'{n} x {c} = {result}')
    print('=-' * 20)

print('Numero invalido. Finalizando o programa.')


import json
from collections import namedtuple, defaultdict, OrderedDict
from timeit import default_timer as time
from heapq import heappop, heappush
from math import inf

Recipe = namedtuple('Recipe', ['name', 'check', 'effect', 'cost'])

class State(OrderedDict):
    """ This class is a thin wrapper around an OrderedDict, which is simply a dictionary which keeps the order in
        which elements are added (for consistent key-value pair comparisons). Here, we have provided functionality
        for hashing, should you need to use a state as a key in another dictionary, e.g. distance[state] = 5. By
        default, dictionaries are not hashable. Additionally, when the state is converted to a string, it removes
        all items with quantity 0.

        Use of this state representation is optional, should you prefer another.
    """

    def __key(self):
        return tuple(self.items())

    def __hash__(self):
        return hash(self.__key())

    def __lt__(self, other):
        return self.__key() < other.__key()

    def copy(self):
        new_state = State()
        new_state.update(self)
        return new_state

    def __str__(self):
        return str(dict(item for item in self.items() if item[1] > 0))

def make_checker(rule):
    # Implement a function that returns a function to determine whether a state meets a
    # rule's requirements. This code runs once, when the rules are constructed before
    # the search is attempted.

    def check(state):
        # This code is called by graph(state) and runs millions of times.
        # Tip: Do something with rule['Consumes'] and rule['Requires'].
        curr_state = state.copy()
        if "Requires" in rule.keys():
            for item in rule["Requires"]:
                if curr_state[item] <= 0:
                    return False

        if "Consumes" in rule.keys():
            for item in rule["Consumes"]:
                if curr_state[item] < rule["Consumes"][item]:  # fixed this
                    return False
        return True

    return check

def make_effector(rule):
    # Implement a function that returns a function which transitions from state to
    # new_state given the rule. This code runs once, when the rules are constructed
    # before the search is attempted.

    def effect(state):
        # This code is called by graph(state) and runs millions of times
        # Tip: Do something with rule['Produces'] and rule['Consumes'].
        curr_state = state.copy()
        next_state = None
        if "Consumes" in rule.keys():
            for item in rule["Consumes"]:
                curr_state[item] -= rule["Consumes"][item]

        for keys in rule["Produces"].keys():
            curr_state[keys] += rule["Produces"][keys]
        next_state = curr_state
        return next_state

    return effect

def make_goal_checker(goal):
    # Implement a function that returns a function which checks if the state has
    # met the goal criteria. This code runs once, before the search is attempted.
    for key in goal.keys():
        print("key",key)
    def is_goal(state):
        # This code is used in the search process and may be called millions of times.
        for key in goal.keys():
            if state[key] < goal[key]:
                return False
            #print("key!!",key)
        return True
        #for item in state: #Changed back to this one because the other one was causing an error
        #    if goal.get(item) is not None:  # check if this item is the one we want
        #        if state.get(item) >= goal.get(item):  # check if our state has a sufficient amount of it
        #            print(item, "found")
        #            return True
        #return False

    return is_goal

def graph(state):
    # Iterates through all recipes/rules, checking which are valid in the given state.
    # If a rule is valid, it returns the rule's name, the resulting state after application
    # to the given state, and the cost for the rule.
    #print("stuck in graph?")
    for r in all_recipes:
        if r.check(state):
            yield (r.name, r.effect(state), r.cost)

def heuristic(state, action, rule, Crafting, consumed, required, goals):
    # Implement your heuristic here!
    #print("////////////",action)
    modifier = 0

    for product in Crafting["Recipes"][action]["Produces"]:
        if product in goals:
            if product not in required and product not in consumed:
                modifier -= 400
            modifier -= 300
        elif product in required or product in consumed:
            if product is "stick" and state[product] <= 2:
                modifier -= 100
            elif product is "wood" and state[product] <= 4:
                modifier -= 100
            elif product is "coal" and state[product] <= 2:
                modifier -= 100
            if product is "rail" and state[product] <= 36:
                modifier -= 100
            elif state[product] <= 8:
                modifier -= 100

    for rules in rule:
        if "Requires" in rules:
            for item in rules["Requires"]:
                if item in Crafting["Recipes"][action]["Produces"]:
                    modifier -= 300
                    # modifier += 0

                if "Consumes" in Crafting["Recipes"][action]:
                    if "Consumes" in rules:
                        for item in rules["Consumes"]:
                            if item in Crafting["Recipes"][action]["Consumes"]:
                                modifier -= 50

    tools = ["stone_pickaxe","bench","cart","wooden_pickaxe","iron_pickaxe","wooden_axe","stone_axe","iron_axe","furnace"]
    best_tools = ["iron_pickaxe","iron_axe"]
    good_tools = ["stone_pickaxe","stone_axe"]
    usable_tools = ["wooden_pickaxe","wooden_axe"]

    for key in state.keys():
        if key in best_tools and state[key] == 1:
            #print("00000000000000000000key", key, "--action", action)
            if key is "iron_pickaxe" and ("stone_pickaxe for" in action or "wooden_pickaxe for" in action):
                return inf
            elif key is "iron_axe" and ("stone_axe for" in action or "wooden_axe for" in action):
                return inf
        elif key in good_tools and state[key] == 1:
            #print("00000000000000000000key", key, "--action", action)
            if key is "stone_pickaxe" and "wooden_pickaxe for" in action:
                #print("here")
                return inf
            elif key is "stone_axe" and "wooden_axe for" in action:
                return inf
        elif key in usable_tools and "punch" in action:
            #print("00000000000000000000key", key, "--action", action)
            return inf

        if key in tools and state[key] > 2:
            return inf

    return modifier

def search(graph, state, is_goal, limit, heuristic, rule, Crafting, consumed, required, goals):

    start_time = time()
    # Implement your search here! Use your heuristic here!
    # When you find a path to the goal return a list of tuples [(state, action)]
    # representing the path. Each element (tuple) of the list represents a state
    # in the path and the action that took you to this state
    path = []

    """frontier[] all unexplored nodes (priority queue)
    costsofar{} of costs with key state: value (action, cost)
    exploring = tuple (timecost, actionname, inventorystate)
    graph() finds neighbor of the heappop(state) in frontier

    for actions in graph(current_state)
        calculate timecost
        if timecost not in costsofar or less than prerecorded timecost
            costsofar[next] = newcost
            priority = newcost + heuristic(currstate)
            frontier.heappush(prioirty, action, nextstate)
            camefrom[next] = current
    """
    curr_state = state.copy()
    frontier = []
    came_from = {}
    cost_so_far={}

    #cost = 0
    frontier.append((0,"Start",curr_state))
    came_from[curr_state] = ("start", None)
    cost_so_far[curr_state] = 0

    while frontier and time() - start_time < limit:
        exploring = heappop(frontier)
        #print("explore",exploring)
        if is_goal(exploring[2]):

            prev_state = came_from[exploring[2]]
            came_from[exploring[2]] = ("Goal", exploring[2])
            path = path_find(prev_state, prev_state,path,came_from,0)
            path = [(exploring[2],exploring[1])] + path
            path.reverse()
            print(time() - start_time, 'seconds.')
            return path

        for next in graph(exploring[2]):
            name, effect, cost = next
            new_cost = cost_so_far[exploring[2]] + cost
            if effect not in cost_so_far.keys() or new_cost < cost_so_far[effect]:
                cost_so_far[effect] = new_cost
                priority = new_cost + heuristic(effect, name, rule, Crafting, consumed, required, goals)
                #if priority < 1000:
                    #print("name", name, "cost", new_cost, "effect", effect, "priority", priority)
                    #cost = new_cost
                heappush(frontier,(priority,name,effect))
                came_from[effect] = (exploring[1],exploring[2])
        #print("------------------------")

    # Failed to find a path
    print(time() - start_time, 'seconds.')
    #print("cost",cost)
    print("Failed to find a path from", state, 'within time limit.')
    return None

def path_find(starting_state, prev_state, path, came_from,count):
    if count <= len(came_from):
        path.append((prev_state[1], prev_state[0]))
        if prev_state[1] not in came_from.keys() or starting_state is prev_state[1]:
            return path
        count += 1
        path_find(starting_state, came_from[prev_state[1]],path,came_from,count)
    return path

def required_for_goal(Crafting, action, required, consumed):
    #the first action will be the one that makes the goal
    if "Requires" in Crafting["Recipes"][action]: #if the action  requires something
        for required_item in Crafting["Recipes"][action]["Requires"]: # for item that (the action) requires
            #print ("required item",required_item)
            for product_action in Crafting["Recipes"]:
                if required_item in Crafting["Recipes"][product_action]["Produces"]:
                    #print("product",required_item)
                    if required_item not in required:
                        required.append(required_item) # put it into the requires list
                        # check what that items creation requires
                        required2, consumed2 = required_for_goal(Crafting,product_action,required,consumed)
                        for new_items in required2:
                            if new_items not in required:
                                required.append(new_items)
    # exact same thing for consumes
    if "Consumes" in Crafting["Recipes"][action]:
        for consumed_item in Crafting["Recipes"][action]["Consumes"]:
            #print ("consumed item",consumed_item)
            for product_action in Crafting["Recipes"]:
                if consumed_item in Crafting["Recipes"][product_action]["Produces"]:
                    #print("product",consumed_item)
                    if consumed_item not in consumed:
                        consumed.append(consumed_item)
                        required2, consumed2 = required_for_goal(Crafting,product_action,required,consumed)
                        for new_items in consumed2:
                            if new_items not in consumed:
                                consumed.append(new_items)
    return required, consumed

if __name__ == '__main__':
    with open('Crafting.json') as f:
        Crafting = json.load(f)

    # # List of items that can be in your inventory:
    # print('All items:', Crafting['Items'])
    #
    # # List of items in your initial inventory with amounts:
    #print('Initial inventory:', Crafting['Initial'])
    #
    # # List of items needed to be in your inventory at the end of the plan:
    print('Goal:',Crafting['Goal'])
    #
    # # Dict of crafting recipes (each is a dict):
    #print('Example recipe:','craft stone_pickaxe at bench ->',Crafting['Recipes']['craft stone_pickaxe at bench'])

    # Build rules
    all_recipes = []
    req_rule = []

    for name, rule in Crafting['Recipes'].items():
        checker = make_checker(rule)
        effector = make_effector(rule)
        recipe = Recipe(name, checker, effector, rule['Time'])
        all_recipes.append(recipe)

        for key in rule["Produces"]:
            if key in Crafting["Goal"].keys():
                req_rule.append(rule)

    # Create a function which checks for the goal
    is_goal = make_goal_checker(Crafting['Goal'])

    # Initialize first state from initial inventory
    state = State({key: 0 for key in Crafting['Items']})
    state.update(Crafting['Initial'])

    # Traceback the actions leading to the goal
    required = []
    consumed = []
    goals = []
    best_action = None
    smallest = 999
    for rule in Crafting["Recipes"]:
        for goal in Crafting["Goal"]:
            if goal in Crafting["Recipes"][rule]["Produces"]:
                if "Requires" in Crafting["Recipes"][rule]:
                    req = len(Crafting["Recipes"][rule]["Requires"])
                else:
                    req = 0
                if "Consumes" in Crafting["Recipes"][rule]:
                    con = len(Crafting["Recipes"][rule]["Consumes"])
                else:
                    con = 0
                if req + con < smallest: # finds the action with the smallest list of required/consumed items
                # this could be modified to consider that wooden pickaxe is an easier item to get than iron_pixaxe and
                # prefer the rule that uses wooden_pickaxe
                    best_action = rule
                    smallest = req + con
    #print("best_action",best_action)
    required, consumed = required_for_goal(Crafting, best_action, required, consumed)
    for item in Crafting["Goal"]:
        goals.append(item)
        if "Requires" in Crafting["Recipes"][best_action]: #if the action  requires something
            for required_item in Crafting["Recipes"][best_action]["Requires"]: # for item that (the action) requires
                goals.append(required_item)
        if "Consumes" in Crafting["Recipes"][best_action]: #if the action  requires something
            for consumed_item in Crafting["Recipes"][best_action]["Consumes"]: # for item that (the action) requires
                goals.append(consumed_item)

    print("required",required)
    print("consumed",consumed)
    print("goals",goals)
    # Search for a solution
    resulting_plan = search(graph, state, is_goal, 300, heuristic, req_rule, Crafting, consumed, required, goals)
    # resulting_plan = False
    if resulting_plan:
        # Print resulting plan
        print("All Items")
        print("Initial Inventory",state)
        print("Goal",Crafting['Goal'])
        print("PATH:")
        del resulting_plan[0]
        for state, action in resulting_plan:
            print('\t',state)
            print(action)


"""
生成question和preview表格

the statistics of this file:
lines(count)    understand_level(h/m/l)    classes(count)    functions(count)    fields(count)
000000000158    ----------------------m    00000000000001    0000000000000000    ~~~~~~~~~~~~~
"""

from PyQt5.QtWidgets import (QTableWidget, QAbstractItemView, QHeaderView,
                             QWidget, QVBoxLayout, QLabel, QListWidget, QTextEdit)
from PyQt5.QtGui import QPixmap

from generate_json import read_from_json_file

__author__ = '与C同行'

class QuestionPreview:
    def __init__(self, question_table: QTableWidget, preview_table: QTableWidget,
                 json_file):
        self.question_table = question_table
        self.preview_table = preview_table
        self.json_dict = read_from_json_file(json_file)
        self.text_edit_dict = {}
        json_dict_length = len(self.json_dict)
        self.question_table.setColumnCount(1)
        self.question_table.setRowCount(json_dict_length)
        self.question_table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.question_table.horizontalHeader().setVisible(False)
        self.question_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.preview_table.setColumnCount(1)
        self.preview_table.setRowCount(json_dict_length)
        self.preview_table.horizontalHeader().setVisible(False)
        self.preview_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        for i in range(json_dict_length):
            question_widget, preview_widget = QuestionPreview.cell_widget(self.json_dict, i+1)
            self.question_table.setCellWidget(i, 0, question_widget)
            self.preview_table.setCellWidget(i, 0, preview_widget)

    @classmethod
    def cell_widget(cls, json_dict_para, i, is_readonly=False):
        def set_question(content_para, question_vbox_para, preview_vbox_para):
            question = content_para['question']
            if question['type'] == 'text':
                question_question_text = QTextEdit()
                preview_question_text = QTextEdit()
                question_question_text.setText(question['content'])
                preview_question_text.setText(question['content'])
                question_question_text.setReadOnly(True)
                preview_question_text.setReadOnly(True)
                question_question_text.setMaximumHeight(60)
                preview_question_text.setMaximumHeight(60)
                question_vbox_para.addWidget(question_question_text)
                preview_vbox_para.addWidget(preview_question_text)
            else:
                question_question_label = QLabel()
                preview_question_label = QLabel()
                question_question_label.setPixmap(QPixmap(question['src']))
                preview_question_label.setPixmap(QPixmap(question['src']))
                question_vbox_para.addWidget(question_question_label)
                preview_vbox_para.addWidget(preview_question_label)

        def set_attach(content_para, question_vbox_para):
            attach = content_para.get('attach')
            if attach:
                for attach_img_path in attach:
                    question_attach_label = QLabel()
                    question_attach_label.setPixmap(QPixmap(attach_img_path))
                    question_vbox_para.addWidget(question_attach_label)

        def set_remark(content_para, question_vbox_para):
            question_remark_label = QLabel('备注')
            question_vbox.addWidget(question_remark_label)
            question_edit_text = QTextEdit()
            setattr(question_edit_text, 'is_remark', True)
            remark_text = content_para.get('remark')
            if remark_text:
                question_edit_text.setText(remark_text)
            question_edit_text.setReadOnly(is_readonly)
            question_edit_text.setMaximumHeight(50)
            question_vbox_para.addWidget(question_edit_text)

        div = json_dict_para[str(i)]
        question_widget = QWidget()
        question_vbox = QVBoxLayout()
        preview_widget = QWidget()
        preview_vbox = QVBoxLayout()
        content = div['content']
        if div['type'] == 'title':
            question_title_label = QLabel(div['content'])
            question_title_label.setStyleSheet("color:rgb(250, 128, 10)")
            preview_title_label = QLabel(div['content'])
            question_vbox.addWidget(question_title_label)
            question_widget.setLayout(question_vbox)
            preview_vbox.addWidget(preview_title_label)
            preview_widget.setLayout(preview_vbox)
            setattr(question_widget, 'is_tag', True)
        elif div['type'] == 'tag':
            question_tag_label = QLabel(div['content'])
            preview_tag_label = QLabel(div['content'])
            question_tag_label.setStyleSheet("color:rgb(250, 128, 10)")
            question_vbox.addWidget(question_tag_label)
            question_widget.setLayout(question_vbox)
            preview_vbox.addWidget(preview_tag_label)
            preview_widget.setLayout(preview_vbox)
            setattr(question_widget, 'is_tag', True)
        elif div['type'] == '选择题':
            set_question(content, question_vbox, preview_vbox)
            options = content['options']
            options_img_path = options.get('img')
            if options_img_path:
                question_options_img_label = QLabel()
                question_options_img_label.setPixmap(QPixmap(options_img_path))
                question_vbox.addWidget(question_options_img_label)
            else:
                items = options['items']
                question_options_listwidget = QListWidget()
                # question_options_listwidget.setStyleSheet('::item{border:0px solid #000000}')
                question_options_listwidget.setMaximumHeight(100)
                question_options_listwidget.addItems(items)
                question_vbox.addWidget(question_options_listwidget)
            set_attach(content, question_vbox)
            set_remark(content, question_vbox)
        elif div['type'] == '填空题':
            set_question(content, question_vbox, preview_vbox)
            set_attach(content, question_vbox)
            set_remark(content, question_vbox)
        elif div['type'] == '简答题':
            set_question(content, question_vbox, preview_vbox)
            answer = content['answer']
            if answer['type'] == 'text':
                question_answer_text = QTextEdit()
                question_answer_text.setText(answer['content'])
                question_answer_text.setReadOnly(True)
                question_answer_text.setMaximumHeight(60)
                question_vbox.addWidget(question_answer_text)
            else:
                question_answer_label = QLabel()
                question_answer_label.setPixmap(QPixmap(answer['src']))
                question_vbox.addWidget(question_answer_label)
            set_attach(content, question_vbox)
            set_remark(content, question_vbox)
        question_widget.setLayout(question_vbox)
        preview_widget.setLayout(preview_vbox)
        return question_widget, preview_widget
        # self.text_edit_dict[str(i)] = question_edit_text

    def give_question_table(self):
        return self.question_table

    def give_preview_table(self):
        return self.preview_table

    def give_text_edit_dict(self):
        return self.text_edit_dict

    def give_json_dict(self):
        return self.json_dict


import cv2

cap=cv2.VideoCapture(0)

face_cascade=cv2.CascadeClassifier("HAAR cascades/haarcascades/haarcascade_frontalface_default.xml")

while cap.isOpened():
    status,frame=cap.read()
    frame=cv2.flip(frame,180)
    res=face_cascade.detectMultiScale(frame,1.2,5)
    for (x,y,w,h) in res:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),5)
    cv2.imshow("Video",frame)
    if cv2.waitKey(1) & 0xFF==27:
        break
cv2.destroyAllWindows()


import cv2
import numpy as np

image = cv2.imread("C:/Users/hp/Desktop/Computer vision CA/background.jpeg", 0)

# Define the parameters for speckle noise
speckle_intensity = 0.1
speckle_image = image + speckle_intensity * image * np.random.normal(0, 1, image.shape)

# Clip the values to ensure they are within the valid range [0, 255]
speckle_image = np.clip(speckle_image, 0, 255).astype(np.uint8)

cv2.imshow('Original Image', image)
cv2.imshow('Speckle Noisy Image', speckle_image)

# Define the threshold value
threshold_value = 200  # Adjust this value as needed

# Apply non-adaptive thresholding to the speckle noisy image
_, thresholded_image = cv2.threshold(speckle_image, threshold_value, 255, cv2.THRESH_BINARY)

cv2.imshow('Thresholded Image', thresholded_image)

cv2.waitKey(0)

cv2.destroyAllWindows()


from flask import Blueprint,json, jsonify, render_template, request, flash
from flask_login import login_required,current_user
from . import db
from .models import Note

# setup file as Blueprint
views = Blueprint('views', __name__)

# this is where we store out routes

@views.route('/', methods=['GET','POST'])
@login_required
def home():
    if request.method == 'POST':
        note = request.form.get('note')

        # not sure why so long
        if len(note) <= 8:
            # print(len(note))
            flash('Note empty.', category='error')
        else:
            # print('note')
            # print(len(note))
            new_note = Note(data=note, user_id=current_user.id)
            db.session.add(new_note)
            db.session.commit()
            flash('Note added', category='success')
    return render_template("home.html", user=current_user)

@views.route('/delete-note', methods=['POST'])
def delete_note():
    # take data from POST request
    note = json.loads(request.data)
    noteId = note['noteId']
    note = Note.query.get(noteId)
    if note:
        if note.user_id == current_user.id:
            db.session.delete(note)
            db.session.commit()

    return jsonify({})


# This script is used to control the step motor

from time import sleep
import pigpio

DIR = 20
STEP = 21
SLEEP = 2

# Connect to pigpiod daemon
pi = pigpio.pi()

# Set up pins as an output
pi.set_mode(DIR, pigpio.OUTPUT)
pi.set_mode(STEP, pigpio.OUTPUT)
pi.set_mode(SLEEP, pigpio.OUTPUT)

MODE = (14, 15, 18)   # Microstep Resolution GPIO Pins

RESOLUTION = {'Full': (0, 0, 0),
              'Half': (1, 0, 0),
              '1/4': (0, 1, 0),
              '1/8': (1, 1, 0),
              '1/16': (0, 0, 1),
              '1/32': (1, 0, 1)}
for i in range(3):
    pi.write(MODE[i], RESOLUTION['1/32'][i])

pi.write(DIR, 1)  # Set direction

def rotate(flag):
	if flag:
		pi.write(SLEEP, 1)
		# Set duty cycle and frequency
		pi.set_PWM_dutycycle(STEP, 128)  # PWM 1/2 On 1/2 Off
		pi.set_PWM_frequency(STEP, 500)  # 500 pulses per second
	else:
		pi.write(STEP, 0)
		sleep(2)
		pi.write(SLEEP, 0)
		# sleep(2)
		# pi.write(SLEEP, 0)

def run(time):
	rotate(True)
	sleep(time)
	rotate(False)

delta_time = 1.6

def update_state(new_state):
	if new_state == 1:
		pi.write(DIR, 1)
		run(delta_time)
	elif new_state == 2:
		pi.write(DIR, 0)
		run(delta_time)
	elif new_state == 3:
		pi.write(DIR, 0)
		run(delta_time * 3)

def update_state_reverse(pre_state):
	if pre_state == 1:
		pi.write(DIR, 0)
		run(delta_time)
	elif pre_state == 2:
		pi.write(DIR, 1)
		run(delta_time)
	elif pre_state == 3:
		pi.write(DIR, 1)
		run(delta_time * 3)

if __name__ == "__main__":
	try:
	    while True:
	    	time = input("Please input the seconds you want to run： ")
	    	if float(time) > 0:
	    		pi.write(DIR, 1)  # Set direction
	    	else:
	    		pi.write(DIR, 0)
	    	rotate(True)
	    	sleep(abs(float(time)))
	    	rotate(False)
	except KeyboardInterrupt:
	    print ("\nCtrl-C pressed.  Stopping PIGPIO and exiting...")
	finally:
		rotate(False)
		pi.write(SLEEP, 0)
		pi.write(STEP, 0)
		pi.write(DIR, 0)
		pi.stop()


"""
THIS SCRIPT IS FOR..................

"""
# IMPORT SECTION

import os, sys
from os import  system

# include root path in sys.path
ROOT_DIR = os.path.abspath(os.curdir)
# check in what server is app
if "iggWebNz" in ROOT_DIR:              # pythonanywhere
    ROOT_DIR = ROOT_DIR + "/mysite"
else:                                   # working in localhost server
    pass
sys.path.insert(1, ROOT_DIR)

# import "My Own Funct" from root path
from MyFunc import *

# CONSTANTS

# print char by char
def print_char_by_char(my_text):
    for ch in my_text:
        print(ch)

# funtion to encrypt a text
def encrypt(text):
    global encripted_text
    #list_changes_chars = {'a':128, 'b':129, 'c':130}
    text=text.replace('a','128')
    text=text.replace('b','129')
    text=text.replace('c','130')
    encripted_text=text

def decipher(text):
    global decoded_text
    text=text.replace('128','a')
    text=text.replace('129','b')
    text=text.replace('130','c')
    decoded_text = text

#
# ---------- MAIN ----------
#
if __name__ == "__main__":

    system('cls')
    print(frGREEN("---------- main ----------"))
    pause()

    # your code
    encripted_text = ''
    decoded_text = ''

    my_text = 'Mi buen amigo, como has estado?'
    print(frGREEN(f"orig text: {my_text}"))

    encrypt(my_text)
    print(frGREEN(f"encripted text: {encripted_text}"))

    decipher(encripted_text)
    print(frGREEN(f"decoded text: {decoded_text}"))

    # ------------------------------------------------
    #          SHOW VARS CHARACTERISTICS
    #------------------------------------------------

    yesss=True
    while yesss:
        _msg = "Do you want to see attributes for a specific VAR ? (Y,N): "
        answer=Y_N_2(_msg)
        if answer in ['Y','N']: yesss = False

    if answer == 'Y':
        # add question for name of var.....
        _what_var = str(input("What VAR ? "))
        try:
            _what_var
            _my_Obj_name = eval(_what_var)
            print(f"{FR_GREEN}---------- INFO FOR OBJECT '{_my_Obj_name}' ----------{NO_COLOR}")
            pause()
            # my objects functions
            mostrar(_my_Obj_name)

        except NameError:
            print(f"\t{FR_RED}---- Var '{_what_var}' doesn't exits ----")
            print(f"{FR_GREEN}--------------- That's all for today ---------------{NO_COLOR}")
            #_my_Obj_name = None

    else:
        print(f"{FR_GREEN}---------- That's all for today ----------{NO_COLOR}")

else:
    # something wrong
    print(frRED("---- upsssssssss something is wrong ---"))
    pause()


import hoomd
import hoomd.md
import numpy as np
import os
import sys
hoomd.context.initialize("");

def print_lammpstrj(myinput, thisL, myname):

        f = open(myname,"w")
        howmany = myinput.shape[0]

        f.write("ITEM: TIMESTEP\n%ld\n" % 0);
        f.write("ITEM: NUMBER OF ATOMS\n%ld\n" % howmany);
        f.write("ITEM: BOX BOUNDS pp pp pp\n%.0f %.1f\n%.0f %.1f\n%.0f %.1f\n" % (0.,thisL,0.,thisL,0.,thisL));
        f.write("ITEM: ATOMS id type x y z\n");
        for i in range(howmany):
                f.write("%d %d %.5f %.5f %.5f 0 0 0\n" % (i+1,0, myinput[i,0], myinput[i,1], myinput[i,2]));

        f.close()

def make_dendron(gen):

    blobs=2**(gen+1)-1
    dendron=np.zeros((blobs,3))
    a=np.zeros((1,3))
    theta0 = 60
    b=np.array([1*np.cos(theta0*np.pi/180),1*np.sin(theta0*np.pi/180),1.0])+np.array([0,0,1])
    c=np.array([1*np.cos((180-theta0)*np.pi/180),1*np.sin((180-theta0)*np.pi/180),-1.0])+np.array([0,0,-1])
    dendron_1 = [a, [b,c]]
    dendron_2 = [a, [b,c]]
    dendron_3 = [a, [b,c]]
    outmap = [[0,1],[0,2]]
    idx = [0, [1,2]]

    ww=3
    thetas = [20,20,20,20,20,20,20]
# xunit=np.array([1,0,0])
# zunit=np.array([0,0,1])
# yunit=np.array([0,1,0])
    for i in range (2,gen+1):
        blobs=2**(gen+1)-1
        dendron=np.zeros((blobs,3))
        a=np.zeros((1,3))
        theta0 = 60
        b=np.array([1*np.cos(theta0*np.pi/180),1*np.sin(theta0*np.pi/180),0])+np.array([0,0.1,0.1])
        c=np.array([1*np.cos((180-theta0)*np.pi/180),1*np.sin((180-theta0)*np.pi/180),0])+np.array([0,0.1,-0.1])
        dendron_1 = [a, [b,c]]
        dendron_2 = [a, [b,c]]
        #print ("b is =",b,"c is =",c)
        outmap = [[0,1],[0,2]]
        #unitvect=[[0],[1,2]]
        idx = [0, [1,2]]

        ww=3
        thetas = [20,20,20,20,20,20,20]
        for i in range (2,gen+1):
            dendron_1.append([])
            dendron_2.append([])
            #dendron_3.append([])
            idx.append([])
            #print("generation", i)
            curr_g = dendron_2[i-1]
            curridx = idx[i-1]

            rot=np.array([np.cos(thetas[i]*np.pi/180),np.sin(thetas[i]*np.pi/180),0,-np.sin(thetas[i]*np.pi/180),np.cos(thetas[i]*np.pi/180),0,0,0,1])
            rot=rot.reshape(3,3)
            rot1=np.copy(rot)
            rot1[0,1] = -rot1[0,1]; rot1[1,0] = -rot1[1,0] #Changing first and second row?
#         rotx1=np.array([1.,0.,0.,0.,np.cos(phi*np.pi/180),-np.sin(phi*np.pi/180),0,np.sin(phi*np.pi/180),np.cos(phi*np.pi/180)])
#         rotx1=rotx1.reshape(3,3)
#         rotx2=np.copy(rotx1)
#         rotx2[2,1] = -rotx1[2,1]; rotx2[1,2] = -rotx1[1,2]

            for j in range(2**(i-1)):
                    v = dendron_1[i-1][j]
                    ref_idx = curridx[j]
                    for k in [0,1]:

                        if k == 0:
                            dendron_1[i].extend([np.dot(rot,v)])
                            #+np.array([0.5,0.2,0.04])
                            dendron_2[i].extend([np.dot(rot,v)+curr_g[j]])
                        #dendron_3[i].extend(np.dot(([np.dot(rot,v)+curr_g[j]]),xunit))
                            idx[i].extend([ww]); outmap.append([ref_idx,ww]); ww+=1
                        else:
                            #+np.array([-0.5,-0.2,-0.04])
                            dendron_1[i].extend([np.dot(rot1,v)])
                            dendron_2[i].extend([np.dot(rot1,v)+curr_g[j]])
                            idx[i].extend([ww]); outmap.append([ref_idx,ww]); ww+=1

        kk=1
        for i in range(1,gen+1):
            kstart=kk
            for j in dendron_2[i]:
                dendron[kk,:] = j
                kk+=1

    return dendron, outmap

def assemble_unit(monomer, dendron): #assembles monomer linker and dendron

    out = np.empty((dendron.shape[0]+1+1,3)) #dendron.shape[0] gives number of rows

    out[0,:] = monomer #writes monomer on first row of array out
    out[1,:] = monomer + [0,1,0] #writes monomer on second row of array out adding a y-translation
    #np.broadcast_to turns monomer+ y-translation to an array with shape similar to out but with two less
    #rows, basically this translated the dendron array to y=2 since in the function creating the dendron
    #the dendron starts from zero and here the backbone monomer starts at zero.
    out[2:,:] = dendron + np.broadcast_to(monomer + [0,2,0], (out.shape[0]-2,3))

    return out

################# Functions loaded ##########################################3
Nmon = 500 #t(sys.argv[1]) # of monomers
gen = 1 ##int(sys.argv[2])   # generation
xbox =1.5*Nmon##float(sys.argv[3])
ybox = xbox #float(sys.argv[4])
zbox =xbox #float(sys.argv[5])
if os.path.isdir("G%d_%d"%(gen,Nmon))==False:
	os.mkdir("G%d_%d"%(gen,Nmon))

path_to_store="G%d_%d"%(gen,Nmon)
ldendron = 2**(gen+1)-1

nbonds_dendr = np.sum(np.asarray([2**i for i in range(1,gen+1)]))

allparticles = np.empty((Nmon*(2+(2**(gen+1)-1)),3), dtype = float)

centerx = xbox/2.; centery = ybox/2.; centerz = zbox/2.- Nmon/2

dendron, bondmap= make_dendron(gen)
kk = 0
radius0 = 1.1
snapshot = hoomd.data.make_snapshot(N=allparticles[:,0].size,box=hoomd.data.boxdim(Lx=xbox, Ly=ybox, Lz=zbox),particle_types=['A', 'B','C'],bond_types=['backbone','linker','dendron'],angle_types=['backbone','linker'])
### Set Positions ####
for i in range(Nmon):
    radius = radius0
    myx = centerx
    myy = centery
    myz = centerz + radius*i #grows the chain each time by one radius
    monomer = np.asarray([myx,myy,myz]) #gives coordinates
    dendronized = assemble_unit(monomer, dendron) #calls function with monomer coordinates and dendron coordinates
    #uses allparticles array's corrseponding row to copy the dendronized array
    allparticles[i*(2+(2**(gen+1)-1)):(i+1)*(2+(2**(gen+1)-1)),:] =np.copy(dendronized)
    dendronized=dendronized-np.array([xbox/2,xbox/2,xbox/2])
    snapshot.particles.position[kk]=[dendronized[0,0],dendronized[0,1],dendronized[0,2]];
    snapshot.particles.typeid[kk]=0;
    kk+=1
    snapshot.particles.position[kk]=[dendronized[1,0],dendronized[1,1],dendronized[1,2]];
    snapshot.particles.typeid[kk]=1;
    kk+=1
    for j in range((2**(gen+1)-1)):
        snapshot.particles.typeid[kk]=2;
        snapshot.particles.position[kk]=[dendronized[j+2,0],dendronized[j+2,1],dendronized[j+2,2]];kk+=1
### Randomize Velocities #####

#snapshot.thermalize_particle_momenta(filter=hoomd.filter.All, kT=1.0)
#print (len(bondmap))
snapshot.bonds.resize(Nmon-1+2*Nmon+Nmon*len(bondmap))
#print("Bonds are: %d"%(Nmon-1+2*Nmon+Nmon*len(bondmap)))
kk=0
for k in range (0,Nmon-1):
    snapshot.bonds.group[kk]=[k*(2+(2**(gen+1)-1)),(k+1)*(2+(2**(gen+1)-1))]
    #print("Backbone:",(k)*(2+(2**(gen+1)-1)),(k+1)*(2+(2**(gen+1)-1)))
    snapshot.bonds.typeid[kk]=0
    kk+=1
for k in range (Nmon):
    snapshot.bonds.group[kk]=[k*(2+(2**(gen+1)-1))+1-1, k*(2+(2**(gen+1)-1))+2-1]
    #print("Linker 1")
    #print(k*(2+(2**(gen+1)-1))+1-1, k*(2+(2**(gen+1)-1))+2-1)
    snapshot.bonds.typeid[kk]=1
    kk+=1
    snapshot.bonds.group[kk]=[k*(2+(2**(gen+1)-1))+2-1, k*(2+(2**(gen+1)-1))+3-1]
   # print("Linker 2")
    #print(k*(2+(2**(gen+1)-1))+2-1, k*(2+(2**(gen+1)-1))+3-1)
    snapshot.bonds.typeid[kk]=1
    kk+=1
for k in range (Nmon):
    for w,l in bondmap:
        snapshot.bonds.group[kk]=[k*(2+(2**(gen+1)-1))+3+w-1,k*(2+(2**(gen+1)-1))+3+l-1];
 #       print("Dendron")
  #      print(k*(2+(2**(gen+1)-1))+3+w-1)
   #     print(k*(2+(2**(gen+1)-1))+3+l-1)
        snapshot.bonds.typeid[kk]=2;
        kk+=1
#print("Bonds Added:",kk)

#### Angles #####
kk=0
snapshot.angles.resize(Nmon-2+Nmon)

for k in range (Nmon-2):
	snapshot.angles.group[kk]=[k*(2+(2**(gen+1)-1)),(k+1)*(2+(2**(gen+1)-1)),(k+2)*(2+(2**(gen+1)-1))];
	snapshot.angles.typeid[kk]=0;kk+=1
for k in range(Nmon):
	snapshot.angles.group[kk]=[k*(2+(2**(gen+1)-1)),k*(2+(2**(gen+1)-1))+1,k*(2+(2**(gen+1)-1))+2]
	snapshot.angles.typeid[kk]=1;kk+=1

hoomd.init.read_snapshot(snapshot)

#nl = hoomd.md.nlist.cell();
nl=hoomd.md.nlist.tree()
### Pair Potential ##########
#wca=hoomd.md.pair.force_shifted_lj(r_cut=2**(1/6),nlist=nl)
#wca.pair_coeff.set('A','A',epsilon=1.0,sigma=1.0,r_cut=2**(1/6))
#wca.pair_coeff.set('B','B',epsilon=1.0,sigma=1.0,r_cut=2**(1/6))
#wca.pair_coeff.set('A','B',epsilon=1.0,sigma=1.0,r_cut=2**(1/6))
#wca.pair_coeff.set('A','C',epsilon=1.0,sigma=0.9,r_cut=0.9*2**(1/6))
#wca.pair_coeff.set('B','C',epsilon=1.0,sigma=0.9,r_cut=0.9*2**(1/6))
#wca.pair_coeff.set('C','C',epsilon=1.0,sigma=0.8,r_cut=0.8*2**(1/6))

gauss = hoomd.md.pair.gauss(r_cut=2**(1/6.), nlist = nl)
gauss.pair_coeff.set('A','A',epsilon=10.0,sigma=0.25,r_cut=2**(1/6))
gauss.pair_coeff.set('B','B',epsilon=10.0,sigma=0.25,r_cut=2**(1/6))
gauss.pair_coeff.set('A','B',epsilon=10.0,sigma=0.25,r_cut=2**(1/6))
gauss.pair_coeff.set('A','C',epsilon=10.0,sigma=0.18,r_cut=0.9*2**(1/6))
gauss.pair_coeff.set('B','C',epsilon=10.0,sigma=0.18,r_cut=0.9*2**(1/6))
gauss.pair_coeff.set('C','C',epsilon=10.0,sigma=0.16,r_cut=0.8*2**(1/6))

### Bonding Potential #######
#fene=hoomd.md.bond.fene()
#fene.bond_coeff.set('backbone',k=30.0,r0=1.5,sigma=1.0,epsilon=1.0)
#fene.bond_coeff.set('linker',k=30.0,r0=1.5,sigma=1.0,epsilon=1.0)
#fene.bond_coeff.set('dendron',k=30.0,r0=1.5,sigma=0.9,epsilon=1.0)

harm = hoomd.md.bond.harmonic()
harm.bond_coeff.set('backbone',k=100.0,r0=1.0)
harm.bond_coeff.set('linker',k=100.0,r0=1.0,)
harm.bond_coeff.set('dendron',k=100.0,r0=1.0)

###Bending Potential####
angular=hoomd.md.angle.harmonic()
angular.angle_coeff.set('backbone',k=6.0,t0=np.pi)
angular.angle_coeff.set('linker',k=240.0,t0=np.pi)
itg=hoomd.md.integrate.langevin(group=hoomd.group.all(),kT=1.0,seed=np.random.randint(1e6)+1)
#itg.randomize_velocities(kT=1.0,s)
itg.set_gamma('A',gamma=10.0)
itg.set_gamma('B',gamma=10.0)
itg.set_gamma('C',gamma=10.0)

hoomd.md.integrate.mode_standard(dt=0.001);
to_run = 1e9
frames=100
hoomd.dump.gsd(filename=path_to_store+'/traj.gsd',period=int(to_run/frames), group=hoomd.group.all(),overwrite=True)
hoomd.analyze.log(filename=path_to_store+"/log-output.log",quantities=['potential_energy', 'temperature'],period=int(to_run/100) ,overwrite=True)

hoomd.run (to_run)