import numpy as np
import pandas as pd

from agots.multivariate_generators.multivariate_extreme_outlier_generator import MultivariateExtremeOutlierGenerator
from agots.multivariate_generators.multivariate_shift_outlier_generator import MultivariateShiftOutlierGenerator
from agots.multivariate_generators.multivariate_trend_outlier_generator import MultivariateTrendOutlierGenerator
from agots.multivariate_generators.multivariate_variance_outlier_generator import MultivariateVarianceOutlierGenerator

INITIAL_VALUE_MIN = 0
INITIAL_VALUE_MAX = 1

class MultivariateDataGenerator:
    def __init__(self, stream_length, n, k, shift_config=None, behavior=None, behavior_config=None):
        """Create multivariate time series using outlier generators
        :param stream_length: number of values in each time series
        :param n: number of time series at all
        :param k: number of time series that should correlate. If all should correlate with the first
        one, set k=n.
        :param shift_config: dictionary from index of the time series to how much it should be displaced in time (>=0)
        """

        if not shift_config:
            self.shift_config = {}
            self.max_shift = 0
        else:
            self.shift_config = shift_config
            self.max_shift = max(list(self.shift_config.values()))
        self.behavior = behavior
        self.behavior_config = behavior_config if behavior_config is not None else {}

        self.STREAM_LENGTH = stream_length
        self.N = n
        self.K = k
        self.data = pd.DataFrame()
        self.outlier_data = pd.DataFrame()

        assert self.STREAM_LENGTH > 0, 'stream_length must at least be 1'
        assert self.N > 0, 'n must at least be 1'
        assert self.K >= 0, 'k must at least be 0'
        assert self.K <= self.N, 'k must be less than or equal to n'
        assert 0 not in self.shift_config.keys(), 'The origin time series cannot be shifted in time'

        if k == 0:  # There is no difference between k=0 and k=1.
            self.K = 1

    def generate_baseline(self, correlation_min=0.9, correlation_max=0.7, initial_value_min=INITIAL_VALUE_MIN,
                          initial_value_max=INITIAL_VALUE_MAX):
        """
        Generate the multivariate data frame
        :param correlation_min: how much the k columns should at least correlate with the first one
        :param correlation_max: how much the n-k-1 columns should at max correlate with the first one
        :param initial_value_min: minimal possible value of the first entry of the time series
        :param initial_value_max: maximal possible value of the first entry of the time series
        :return: a DataFrame with columns ['timestamp', 'x0', ... 'xn-1'] in which the first column
        is the original time series. The following k columns correlate at least with correlation_min
        with it and the remaining n-k columns correlate at max correlation_max with it.
        """

        df = self.init_dataframe(self.N)
        # Create k correlating time series
        df = self.create_correlating_time_series(self.K, correlation_min, df, initial_value_min, initial_value_max)

        # Create the remaining n - k time series randomly
        df = self.create_not_correlating_time_series(self.K, self.N, correlation_max, df, initial_value_min,
                                                     initial_value_max)

        # Perform the shifts: currently all time series have n+max_shift elements
        # Each one should start at index max_shift - own_shift such that the padded measurements of a time series before
        # the origin time series starts descend from a self-correlating distribution
        for k, column_name in enumerate(df.columns):
            own_shift = 0 if k not in self.shift_config.keys() else self.shift_config[k]
            df[column_name] = df[column_name].shift(own_shift)

        df.dropna(axis=0, inplace=True)
        df.reset_index(inplace=True, drop=True)

        assert not df.isnull().values.any(), 'There is at least one NaN in the generated DataFrame'
        self.data = df
        return self.data

    def init_dataframe(self, number_time_series):
        columns = ['timestamp']
        for value_column_index in range(number_time_series):
            columns.append('x{}'.format(value_column_index))
        df = pd.DataFrame(columns=columns)
        return df

    def create_basic_time_series(self, df, initial_value_min=INITIAL_VALUE_MIN, initial_value_max=INITIAL_VALUE_MAX):
        if initial_value_min != initial_value_max:
            start = np.random.randint(initial_value_min, initial_value_max)
        else:
            start = initial_value_min

        if self.behavior is not None:
            behavior_generator = self.behavior(**self.behavior_config)

        # Create basic time series
        x = [start]
        timestamps = [0]
        for i in range(1, self.STREAM_LENGTH + self.max_shift):
            timestamps.append(i)
            value = x[i - 1] + np.random.normal(0, 1)
            if self.behavior is not None:
                value += next(behavior_generator)
            x.append(value)
        df['x0'] = x
        df['timestamp'] = timestamps
        df.set_index('timestamp', inplace=True)
        return df

    def create_correlating_time_series(self, number_time_series, correlation_min, df,
                                       initial_value_min=INITIAL_VALUE_MIN,
                                       initial_value_max=INITIAL_VALUE_MAX):
        # First time series
        df = self.create_basic_time_series(df=df, initial_value_min=initial_value_min,
                                           initial_value_max=initial_value_max)
        origin_offset = df.iloc[0, 0]

        # number_time_series time series which are correlating
        for index_correlating in range(1, number_time_series):
            while True:
                x = [0]
                if initial_value_min != initial_value_max:
                    offset = np.random.randint(initial_value_min, initial_value_max)
                else:
                    offset = initial_value_min
                for index_timeseries_length in range(self.STREAM_LENGTH - 1 + self.max_shift):
                    # Take 50% of time series 0 and add 50% randomness
                    original_value = df.iloc[index_timeseries_length, 0] - origin_offset
                    x.append(0.5 * original_value + 0.5 * (np.random.random() - 0.5))
                df['x' + str(index_correlating)] = x
                df['x' + str(index_correlating)] += offset
                if abs(df.corr().iloc[0, index_correlating]) >= correlation_min:
                    break
            assert (len(df) == self.STREAM_LENGTH + self.max_shift)
        return df

    def create_not_correlating_time_series(self, k, n, correlation_max, df, initial_value_min=INITIAL_VALUE_MIN,
                                           initial_value_max=INITIAL_VALUE_MAX):
        for index_not_correlation in range(k, n):
            if self.behavior is not None:
                behavior_generator = self.behavior(**self.behavior_config)
            while True:
                if initial_value_min != initial_value_max:
                    x = [np.random.randint(initial_value_min, initial_value_max)]
                else:
                    x = [initial_value_min]
                for index_timeseries_length in range(self.STREAM_LENGTH - 1 + self.max_shift):
                    value = x[index_timeseries_length] + (np.random.random() - 0.5)
                    if self.behavior is not None:
                        value += next(behavior_generator)
                    x.append(value)
                df['x' + str(index_not_correlation)] = x
                if abs(df.corr().iloc[0, index_not_correlation]) <= correlation_max:
                    break
            assert(len(df) == self.STREAM_LENGTH + self.max_shift)
        return df

    def add_outliers(self, config):
        """Adds outliers based on the given configuration to the base line

         :param config: Configuration file for the outlier addition e.g.
         {'extreme': [{'n': 0, 'timestamps': [(3,)]}],
          'shift':   [{'n': 3, 'timestamps': [(4,10)]}]}
          would add an extreme outlier to time series 0 at timestamp 3 and a base shift
          to time series 3 between timestamps 4 and 10
         :return:
         """
        OUTLIER_GENERATORS = {'extreme': MultivariateExtremeOutlierGenerator,
                              'shift': MultivariateShiftOutlierGenerator,
                              'trend': MultivariateTrendOutlierGenerator,
                              'variance': MultivariateVarianceOutlierGenerator}

        generator_keys = []

        # Validate the input
        for outlier_key, outlier_generator_config in config.items():
            assert outlier_key in OUTLIER_GENERATORS, 'outlier_key must be one of {} but was'.format(OUTLIER_GENERATORS,
                                                                                outlier_key)
            generator_keys.append(outlier_key)
            for outlier_timeseries_config in outlier_generator_config:
                n, timestamps = outlier_timeseries_config['n'], outlier_timeseries_config['timestamps']
                assert n in range(self.N), 'n must be between 0 and {} but was {}'.format(self.N - 1, n)
                for timestamp in list(sum(timestamps, ())):
                    assert timestamp in range(
                        self.STREAM_LENGTH), 'timestamp must be between 0 and {} but was {}'.format(self.STREAM_LENGTH,
                                                                                timestamp)

        df = self.data
        if self.data.shape == (0, 0):
            raise Exception('You have to first compute a base line by invoking generate_baseline()')
        for generator_key in generator_keys:
            for outlier_timeseries_config in config[generator_key]:
                n, timestamps = outlier_timeseries_config['n'], outlier_timeseries_config['timestamps']
                generator_args = dict([(k, v) for k, v in outlier_timeseries_config.items() if k not in ['n', 'timestamps']])
                generator = OUTLIER_GENERATORS[generator_key](timestamps=timestamps, **generator_args)
                df[df.columns[n]] += generator.add_outliers(self.data[self.data.columns[n]])

        assert not df.isnull().values.any(), 'There is at least one NaN in the generated DataFrame'
        self.outlier_data = df
        return df


"""
An RPC server base class for encapsulating a service class and receiving requests that
will call that encapsulated class. This is part of a remote service that communicates
with the projectServer.
"""
import os
import sys
import re
import time
import json
import pickle
import logging
import argparse
import threading
import websocket
from base64 import b64encode, b64decode
from rtCommon.remoteable import RemoteHandler
from rtCommon.projectUtils import generateDataParts
from rtCommon.utils import DebugLevels, trimDictBytes
from rtCommon.errors import RequestError
from rtCommon.projectUtils import login, certFile, checkSSLCertAltName, makeSSLCertFile

class WsRemoteService:
    remoteHandler = RemoteHandler()
    commLock = threading.Lock()
    shouldExit = False

    def __init__(self, args, channelName):
        """
        Args:
            args: Argparse args for establishing a connection to the projectServer
            channelName: the websocket channel to connect on, e.g. 'wsData'
        """
        self.channelName = channelName
        self.args = args
        self.sessionCookie = None
        self.needLogin = True
        self.started = False

        # # Starts the receiver in it's own thread
        # self.recvThread = threading.Thread(name='recvThread', target=self.wsReceiver)
        # self.recvThread.setDaemon(True)
        # self.recvThread.start()

    def addHandlerClass(self, classType, classInstance):
        """Register the class that will handle the received requests via the class type"""
        WsRemoteService.remoteHandler.registerClassInstance(classType, classInstance)

    def addHandlerClassName(self, className, classInstance):
        """Register the class that will handle the received requests via the class name"""
        WsRemoteService.remoteHandler.registerClassNameInstance(className, classInstance)

    def runForever(self):
        """Run the receiver loop. This function doesn't return."""
        # go into loop trying to do webSocket connection periodically
        args = self.args
        # print(f'args {self.args}')
        WsRemoteService.shouldExit = False
        while not WsRemoteService.shouldExit:
            try:
                if self.needLogin or self.sessionCookie is None:
                    self.sessionCookie = login(args.server, args.username, args.password, testMode=args.test)
                wsAddr = os.path.join('wss://', args.server, self.channelName)
                if args.test:
                    print("Warning: using non-encrypted connection for test mode")
                    wsAddr = os.path.join('ws://', args.server, self.channelName)
                logging.log(DebugLevels.L6, "Trying connection: %s", wsAddr)
                ws = websocket.WebSocketApp(wsAddr,
                                            on_message=WsRemoteService.on_message,
                                            on_close=WsRemoteService.on_close,
                                            on_error=WsRemoteService.on_error,
                                            cookie="login="+self.sessionCookie)
                logging.log(logging.INFO, "Connected to: %s", wsAddr)
                print("Connected to: {}".format(wsAddr))
                self.started = True
                ws.run_forever(sslopt={"ca_certs": certFile})
            except Exception as err:
                logging.log(logging.INFO, "WsRemoteService Exception {}: {}".format(type(err).__name__, str(err)))
            print('sleep {}'.format(args.interval))
            time.sleep(args.interval)

    @staticmethod
    def stop():
        WsRemoteService.shouldExit = True

    @staticmethod
    def send_response(client, response):
        WsRemoteService.commLock.acquire()
        try:
            client.send(json.dumps(response))
        finally:
            WsRemoteService.commLock.release()

    @staticmethod
    def on_message(client, message):
        """
        Main message dispatcher that will get the request from projectServer
        and call the registered handler to process the request. It will then
        return the result of the handler function back to the projectServer.
        """
        response = {'status': 400, 'error': 'unhandled request'}
        cmd = 'unknown'
        try:
            request = json.loads(message)
            request = decodeByteTypeArgs(request)
            # print(f'on_message: message {request} type: {type(request)}')
            # create the response message but without data objects
            response = request.copy()
            response.pop('data', None)
            response.pop('args', None)
            response.pop('kwargs', None)
            trimDictBytes(response)
            cmd = request.get('cmd')
            # decode any encoded byte args
            # TODO - spin off a thread for each request passing in client so the thread call client.send
            callResult = WsRemoteService.remoteHandler.runRemoteCall(request)
            # serialize the callResult
            # print(f'callresult type: {type(callResult)}')
            if isNativeType(callResult):
                if type(callResult) == bytes:
                    data = callResult
                    response['dataSerialization'] = 'bytes'
                else:
                    # encode to json and then as a byte string
                    data = json.dumps(callResult).encode()
                    response['dataSerialization'] = 'json'
            else:
                data = pickle.dumps(callResult)
                response['dataSerialization'] = 'pickle'
            # return callResult
            response['status'] = 200
            compress = False
            if len(data) > 1024 * 1024:
                compress = True
            for msgPart in generateDataParts(data, response, compress=compress):
                WsRemoteService.send_response(client, msgPart)
        except Exception as err:
            errStr = "RPC Exception: {}: {}".format(cmd, err)
            print(errStr)
            response.update({'status': 400, 'error': errStr})
            WsRemoteService.send_response(client, response)
            if cmd == 'error':
                sys.exit()
            return

    @staticmethod
    def on_error(client, error):
        if type(error) is KeyboardInterrupt:
            WsRemoteService.shouldExit = True
        else:
            logging.log(logging.WARNING, "on_error: WsRemoteService: {} {}".
                        format(type(error), str(error)))

    @staticmethod
    def on_close(client, code, reason):
        print('## Connection closed, check if projectServer allows remote services.')
        print('## May need to restart projectServer with --dataRemote --subjectRemote options.')
        logging.info(f'Connection closed {code} {reason}')

def isNativeType(var):
    nativeTypes = (int, float, str, bytes, list, dict, set, tuple, bytearray, memoryview, range, complex)
    if var in nativeTypes:
        return True
    return False

def encodeByteTypeArgs(cmd) -> dict:
    """
    Check if any args are of type 'bytes' and if so base64 encode them.
    The original arg will be replaced with a tag that will reference the encoded bytes
        within the cmd dict.
    Args:
        cmd: a dictionary of the command to check
    Returns:
        A cmd dictionary with the byte args encoded
    """
    args = cmd.get('args', ())
    byteArgIndices = []
    for i, arg in enumerate(args):
        if type(arg) is bytes:
            byteArgIndices.append(i)

    if len(byteArgIndices) != 0:
        # convert args from tuple to list so we can modify it
        args = list(args)
        for i in byteArgIndices:
            # encode as base64 and put a tag holder in place
            encdata = b64encode(args[i]).decode('utf-8')
            tag = 'encodedBytes_' + str(i)
            args[i] = tag
            cmd[tag] = encdata
        cmd['args'] = tuple(args)
        cmd['encodedByteArgs'] = byteArgIndices

    # Check and encode keyword args also
    kwargs = cmd.get('kwargs', {})
    byteKwargKeys = []
    for key, arg in kwargs.items():
        if type(arg) is bytes:
            byteKwargKeys.append(key)
            encdata = b64encode(arg).decode('utf-8')
            kwargs[key] = encdata
    if len(byteKwargKeys) != 0:
        cmd['encodedByteKwargs'] = byteKwargKeys
        cmd['kwargs'] = kwargs

    return cmd

def decodeByteTypeArgs(cmd) -> dict:
    """
    Decodes rpc args that were previously encoded with encodeByteTypeArgs.
    Args:
        cmd: a dictionary with encoded args
    Returns:
        cmd: a dictionary with decoded args
    """
    byteArgIndices = cmd.get('encodedByteArgs')
    if byteArgIndices is not None:
        args = cmd.get('args', ())
        args = list(args)
        for i in byteArgIndices:
            tag = 'encodedBytes_' + str(i)
            encdata = cmd.get(tag)
            if encdata is None or args[i] != tag:
                raise RequestError(f'Byte encoded data error: index {i} tag {tag}')
            decodedData = b64decode(encdata)
            args[i] = decodedData
            cmd.pop(tag, None)
        cmd.pop('encodedByteArgs')
        cmd['args'] = tuple(args)
    return cmd

def parseConnectionArgs():
    # parse args for client to connect to server
    # argv = sys.argv[1:]
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', action="store", dest="server", default="localhost:8888",
                        help="Server Address with Port [server:port]")
    parser.add_argument('-i', action="store", dest="interval", type=int, default=5,
                        help="Retry connection interval (seconds)")
    parser.add_argument('-u', '--username', action="store", dest="username", default=None,
                        help="rtcloud website username")
    parser.add_argument('-p', '--password', action="store", dest="password", default=None,
                        help="rtcloud website password")
    parser.add_argument('--test', default=False, action='store_true',
                        help='Use unsecure non-encrypted connection')
    args, _ = parser.parse_known_args()

    if not re.match(r'.*:\d+', args.server):
        print("Error: Expecting server address in the form <servername:port>")
        parser.print_help()
        sys.exit()

    # Check if the ssl certificate is valid for this server address
    addr, _ = args.server.split(':')
    if checkSSLCertAltName(certFile, addr) is False:
        # Addr not listed in sslCert, recreate ssl Cert
        makeSSLCertFile(addr)

    return args


N, M = map(int,input().split())
arr = list(map(int,input().split()))

num = 0
A = []
for i in range(len(arr)):
    num += arr[i]
    A.append(num)

x = 0
y = 0
cnt = 0
for i in range(N):
    if A[i]==M:
        cnt += 1
while x<N and y<N:
    cal = A[y]-A[x]
    if cal == M:
        #print("Goal",x,y)
        cnt += 1
        if x+1 < y:
            x += 1
        else:
            x += 1
            y += 1
    elif cal > M:
        if x+1 < y:
            x += 1
        else:
            x += 1
            y += 1
    else:
        y += 1
print(cnt)
'''
1 4 6 9 11 12 15 18
2
1 4 붙어있으면 x옮기기
4 6 만족하므로
6 9
9 11
11 12 M보다 작으므로 y옮기기
11 15 M보다 크고 안붙어있으므로 x옮기기
12 15 M보다 크고 붙어있으므로 x옮기기 x==y이므로 y
15 18
'''


from nicegui import ui

dict_of_tabs = {
    "Tab1": "Content of Tab1",
    "Tab2": "Content of Tab2",
}

# initialize tab_counter with the length of the dict_of_tabs
tab_counter = len(dict_of_tabs)

def add_tab():
    global tab_counter
    # use the tab_counter to create a new tab name
    new_tab_name = f'Tab{tab_counter + 1}'
    tab_counter += 1
    dict_of_tabs[new_tab_name] = f'Content of {new_tab_name}'
    tabs.refresh()

def delete_tab(title):
    if title in dict_of_tabs:
        del dict_of_tabs[title]
        tabs.refresh()

@ui.refreshable
def tabs():
    with ui.tabs().classes('w-full') as tabs:
        for title in dict_of_tabs:
            with ui.tab(name=title, label=''):
                with ui.row().classes('items-center justify-between'):
                    ui.label(title).classes('text-lg')
                    ui.button(icon='close', on_click=lambda t=title: delete_tab(t)).classes('m-0 p-0 text-black dark:text-white text-xs').props('flat')

        with ui.tab(name="+", label='').classes('p-0 m-0'):
            ui.button(icon='add', on_click=add_tab).props('outline').classes('h-full w-full m-0 text-black dark:text-white')

    with ui.tab_panels(tabs):
        for title in dict_of_tabs:
            with ui.tab_panel(title):
                ui.label(dict_of_tabs[title])
        with ui.tab_panel("+"):
            pass

tabs()

ui.run()


# number_1 = 25
# number_2 = 24
# number_3 = 26
# number_4 = number_1 + number_2 + number_3 / 3
# print(f"Number 1 is {number_1}, \nNumber 2 is {number_2} Number 3 is {number_3}\nand Total average is {number_4}")

# user input
num1 = input("Enter 1st number")
num2 = input("Enter 2nd number")
num3 = input("Enter 3rd Number")

Average = {(int(num1) + int(num2) + int(num3)) / 3}

print(f"num1 is {num1},num2 is {num2},num3 is{num3},and average is{Average}")


'''

一、什么是变量？

变量就是可以变化的量，量指的是事物的状态，比如人的年龄、性别，游戏角色的等级、金钱等等

二、为什么要有变量？
为了让计算机能够像人一样去记忆事物的某种状态，并且状态是可以发生变化的
详细地说：
程序执行的本质就是一系列状态的变化，变是程序执行的直接体现，所以我们需要有一种机制能够反映或者说是保存下来程

三、如何用变量
'''
# 1、变量基本使用
# 原则：先定义，后引用
# name = 'egon'  # 定义-》存
# print(name)  # 引用-》取

# age = 18
# print(age)

# 2、内存管理：垃圾回收机制
# 垃圾：当一个变量值被绑定的变量名的个数为0时，该变量值无法被访问到，称之为垃圾
# 引用计数增加
x = 10  # 10的引用计数为1
y = x  # 10的引用计数为2
z = x  # 10的引用计数为3

# 引用计数减少
del x  # 解除变量名x与值10的绑定关系，10的引用计数变为2
# print(y)
del y  # 10的引用计数变为1
# print(z)
z = 12345  # # 10的引用计数变为0
# print(z)

# 3、变量有三大组成部分
# I：变量名=》是指向等号右侧值的内存地址的，用来访问等号右侧的值
# II：赋值符号：将变量值的内存地址绑定给变量名
# III：变量值：代表记录的事物的状态

# 4、变量名的命名的规则
# 原则：变量名的命名应该见名知意
# 4.1. 变量名只能是 字母、数字或下划线的任意组合
# 4.2. 变量名的第一个字符不能是数字
# 4.3. 关键字不能声明为变量名，常用关键字如下
# ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from','global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
# age=18
# print='egon'

# ps：不要用拼音，不要用中文，在见名知意的前提下尽可能短
# mingzi='egon'
# 名字='egon'
# print(名字)

# 5、变量名的命名风格
# 5.1 纯小写加下划线的方式(在python中，关于变量名的命名推荐使用这种方式)
age_of_alex = 73
# print(age_of_alex)
# 5.2 驼峰体
AgeOfAlex = 73
# print(AgeOfAlex)

# 6、变量值三个重要的特征
# name='egon'
# id：反映的是变量值的内存地址，内存地址不同id则不同
# print(id(name))
# type：不同类型的值用来表示记录不同的状态
# print(type(name))
# value：值本身
# print(name)

# 6.2 is与==
# is：比较左右两个值身份id是否相等
# ==：比较左右两个值他们的值是否相等
'''
id不同的情况下，值有可能相同，即两块不同的内存空间里可以存相同的值
id相同的情况下，值一定相同，x is y成立，x == y也必然成立
>>>
>>> x='info：Egon：18'
>>> y='info：Egon：18'
>>> print(x,y)
info：Egon：18 info：Egon：18
>>> print(id(x),id(y))
4565819264 4566192176
>>>
>>>
>>>
>>> x == y
True
>>> x is y
False
'''

# 了解：小整数池[-5,256]
# 从python解释器启动那一刻开始，就会在内存中事先申请
# 好一系列内存空间存放好常用的整数
'''
>>> m=10
>>> n=10
>>> id(m)
4562619328
>>> id(n)
4562619328
>>>
>>> res=4+6
>>> res
10
>>> id(res)
4562619328
'''

'''
>>> x=-5
>>> y=-5
>>> x is y
True
>>> x=-6
>>> y=-6
>>> x is y
False
'''

'''
>>> x='aaa'
>>> y='aaa'
>>>
>>>
>>> id(x)
4566200880
>>> id(y)
4566200880
'''

'''
x=-6
y=-6
print(id(x))
print(id(y))
print(x is y)
'''

# 7、常量：不变的量
# 注意：python语法中没有常量的概念，但是在程序的开发过程中会涉及到常量的概念
AGE_OF_ALEX = 73  # 小写字母全为大写代表常量，这只是一种约定、规范
AGE_OF_ALEX = 74
print(AGE_OF_ALEX)

1python基础/开发基础-纯小白都能学会/day4-变量与基础数据类型/代码/01 变量.py


"""
qfly | Qualisys Drone SDK Example Script: Control Engineering / Step Response Demo

UNSTABLE / EXPERIMENTAL / UNDER DEVELOPMENT
"""

import pynput
from time import sleep, time

import numpy as np
import matplotlib.pyplot as plt

from qfly import Pose, QualisysCrazyflie, World

# SETTINGS
cf_body_name = 'E7E7E7E704'  # QTM rigid body name
cf_uri = 'radio://0/80/2M/E7E7E7E704'  # Crazyflie address
cf_marker_ids = [41, 42, 43, 44]

# Watch key presses with a global variable
last_key_pressed = None

# Set up keyboard callback
def on_press(key):
    """React to keyboard."""
    global last_key_pressed
    last_key_pressed = key
    if key == pynput.keyboard.Key.esc:
        fly = False

# Listen to the keyboard
listener = pynput.keyboard.Listener(on_press=on_press)
listener.start()

# Set up world - the World object comes with sane defaults
world = World()

# Prepare for liftoff
with QualisysCrazyflie(cf_body_name,
                       cf_uri,
                       world,
                       marker_ids=cf_marker_ids) as qcf:

    # Let there be time
    t = time()
    dt = 0

    print("Beginning maneuvers...")

    log = []

    # MAIN LOOP WITH SAFETY CHECK
    while(qcf.is_safe()):

        # Terminate upon Esc command
        if last_key_pressed == pynput.keyboard.Key.esc:
            break

        # Mind the clock
        dt = time() - t

        # Keep track of altitude
        log.append(qcf.pose)

        # Take off and hover in the center of safe airspace for 5 seconds
        if dt < 20:
            print(f'[t={int(dt)}] Ascending...')
            qcf.rise_in_place()
            continue

        if dt < 30:
            qcf.land_in_place()
            continue

        # if dt < 50:
        #     print(f'[t={int(dt)}] Ascending...')
        #     qcf.rise_in_place(0.7)
        #     continue

        # if dt < 60:
        #     qcf.land_in_place()
        #     continue

        # if dt < 80:
        #     print(f'[t={int(dt)}] Ascending...')
        #     qcf.rise_in_place(0.4)
        #     continue

        # if dt < 90:
        #     qcf.land_in_place()
        #     continue

        else:
            break

    # Land calmly
    qcf.land_in_place()

# Plot z-axis response
_t = range(len(log))
_x = list(pose.x for pose in log)
_y = list(pose.y for pose in log)
_z = list(pose.z for pose in log)
fig, ax = plt.subplots()
ax.scatter(_x, _y)

plt.show()


# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'

# %%
import tensorflow as tf
import sklearn
import numpy as np
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
from sklearn.metrics import silhouette_score
import tensorflow.keras as keras
mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
from utils.print_result import print_result

train_labels=train_labels[:10000]
train_images=train_images[:10000]
train_images=train_images.reshape(-1,784)
train_images=train_images/255.0

#mnist = input_data.read_data_sets("MNIST_data/", one_hot=False)
#trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images,\
   # mnist.test.labels
class RBM_t1(object):
    def __init__(self, input_size, output_size):
        # Defining the hyperparameters
        self._input_size = input_size  # Size of input
        self._output_size = output_size  # Size of output
        self.epochs = 5  # Amount of training iterations
        self.learning_rate = 1.0  # The step used in gradient descent
        self.batchsize = 100  # The size of how much data will be used for training per sub iteration

        # Initializing weights and biases as matrices full of zeroes
        self.w = np.zeros([input_size, output_size], np.float32)  # Creates and initializes the weights with 0
        self.hb = np.zeros([output_size], np.float32)  # Creates and initializes the hidden biases with 0
        self.vb = np.zeros([input_size], np.float32)  # Creates and initializes the visible biases with 0

    # Fits the result from the weighted visible layer plus the bias into a sigmoid curve
    def prob_h_given_v(self, visible, w, hb):
        # Sigmoid
        return tf.nn.sigmoid(tf.matmul(visible, w) + hb)

    # Fits the result from the weighted hidden layer plus the bias into a sigmoid curve
    def prob_v_given_h(self, hidden, w, vb):
        return tf.nn.sigmoid(tf.matmul(hidden, tf.transpose(w)) + vb)

    # Generate the sample probability
    def sample_prob(self, probs):
        return tf.nn.relu(tf.sign(probs - tf.random_uniform(tf.shape(probs))))

    # Training method for the model
    def train(self, X):
        # Create the placeholders for our parameters
        _w = tf.placeholder("float", [self._input_size, self._output_size])
        _hb = tf.placeholder("float", [self._output_size])
        _vb = tf.placeholder("float", [self._input_size])

        prv_w = np.zeros([self._input_size, self._output_size],
                         np.float32)  # Creates and initializes the weights with 0
        prv_hb = np.zeros([self._output_size], np.float32)  # Creates and initializes the hidden biases with 0
        prv_vb = np.zeros([self._input_size], np.float32)  # Creates and initializes the visible biases with 0

        cur_w = np.zeros([self._input_size, self._output_size], np.float32)
        cur_hb = np.zeros([self._output_size], np.float32)
        cur_vb = np.zeros([self._input_size], np.float32)
        v0 = tf.placeholder("float", [None, self._input_size])

        # Initialize with sample probabilities
        h0 = self.sample_prob(self.prob_h_given_v(v0, _w, _hb))
        v1 = self.sample_prob(self.prob_v_given_h(h0, _w, _vb))
        h1 = self.prob_h_given_v(v1, _w, _hb)

        # Create the Gradients
        positive_grad = tf.matmul(tf.transpose(v0), h0)
        negative_grad = tf.matmul(tf.transpose(v1), h1)

        # Update learning rates for the layers
        update_w = _w + self.learning_rate * (positive_grad - negative_grad) / tf.to_float(tf.shape(v0)[0])
        update_vb = _vb + self.learning_rate * tf.reduce_mean(v0 - v1, 0)
        update_hb = _hb + self.learning_rate * tf.reduce_mean(h0 - h1, 0)

        # Find the error rate
        err = tf.reduce_mean(tf.square(v0 - v1))

        # Training loop
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            # For each epoch
            for epoch in range(self.epochs):
                # For each step/batch
                for start, end in zip(range(0, len(X), self.batchsize), range(self.batchsize, len(X), self.batchsize)):
                    batch = X[start:end]
                    # Update the rates
                    cur_w = sess.run(update_w, feed_dict={v0: batch, _w: prv_w, _hb: prv_hb, _vb: prv_vb})
                    cur_hb = sess.run(update_hb, feed_dict={v0: batch, _w: prv_w, _hb: prv_hb, _vb: prv_vb})
                    cur_vb = sess.run(update_vb, feed_dict={v0: batch, _w: prv_w, _hb: prv_hb, _vb: prv_vb})
                    prv_w = cur_w
                    prv_hb = cur_hb
                    prv_vb = cur_vb
                error = sess.run(err, feed_dict={v0: X, _w: cur_w, _vb: cur_vb, _hb: cur_hb})
                print('Epoch: %d' % epoch, 'reconstruction error: %f' % error)
            self.w = prv_w
            self.hb = prv_hb
            self.vb = prv_vb

    # Create expected output for our DBN
    def rbm_outpt(self, X):
        input_X = tf.constant(X)
        _w = tf.constant(self.w)
        _hb = tf.constant(self.hb)
        out = tf.nn.sigmoid(tf.matmul(input_X, _w) + _hb)
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            return sess.run(out)

class RBM_t2(object):
    def __init__(self,input_size,output_size,learning_rate=1.0):
        self._input_size=input_size
        self._output_size=output_size
        self.w=np.zeros([input_size,output_size],np.float32)
        self.hb=np.zeros([output_size],np.float32)
        self.vb=np.zeros([input_size],np.float32)

        self.learning_rate=learning_rate
    # Fits the result from the weighted visible layer plus the bias into a sigmoid curve
    def prob_h_given_v(self, visible, w, hb):
        # Sigmoid
        return tf.math.sigmoid(tf.linalg.matmul(visible, w) + hb)
     # Fits the result from the weighted hidden layer plus the bias into a sigmoid curve
    def prob_v_given_h(self, hidden, w, vb):
        return tf.math.sigmoid(tf.linalg.matmul(hidden, tf.transpose(w)) + vb)
    def sample_prob(self,probs):
        return tf.nn.relu(tf.sign(probs-tf.random.uniform(tf.shape(probs))))

    def runG(self,batch,_w,_hb,_vb):
        v0=tf.cast(batch,tf.float32)

        h0=self.sample_prob(self.prob_h_given_v(v0,_w,_hb))
        v1=self.sample_prob(self.prob_v_given_h(h0,_w,_vb))
        h1=self.prob_h_given_v(v1,_w,_hb)

        positive_grad=tf.linalg.matmul(tf.transpose(v0),h0)
        negative_grad=tf.linalg.matmul(tf.transpose(v1),h1)

        update_w=_w+self.learning_rate*(positive_grad-negative_grad)/tf.cast(tf.shape(v0)[0],dtype=tf.float32)
        update_vb=_vb+self.learning_rate*tf.reduce_mean(v0-v1,0)
        update_hb=_hb+self.learning_rate*tf.reduce_mean(h0-h1,0)

        loss=tf.reduce_mean(tf.square(v0-v1))
        return update_w,update_hb,update_vb,loss
    def train(self,X,epochs=5,batchsize=100):
        prv_w=np.zeros([self._input_size,self._output_size],np.float32)
        prv_hb=np.zeros([self._output_size],np.float32)
        prv_vb=np.zeros([self._input_size],np.float32)

        cur_w=np.zeros([self._input_size,self._output_size],np.float32)
        cur_hb=np.zeros([self._output_size],np.float32)
        cur_vb=np.zeros([self._input_size],np.float32)
        for epoch in range(epochs):
            for start,end in zip(range(0,len(X),batchsize),range(batchsize,len(X),batchsize)):
                batch=X[start:end]

                cur_w,cur_hb,cur_vb,_=self.runG(batch,prv_w,prv_hb,prv_vb)

                prv_w=cur_w
                prv_hb=cur_hb
                prv_vb=cur_vb
            _a,_b,_c,loss=self.runG(X,cur_w,cur_hb,cur_vb)
            print('Epoch: %d' % epoch, 'loss: %f' % loss)

        self.w=prv_w
        self.hb=prv_hb
        self.vb=prv_vb

    def rbm_outpt(self, X):
        input_X = tf.constant(X,dtype=tf.float32)
        _w = tf.constant(self.w)
        _hb = tf.constant(self.hb)
        out = tf.math.sigmoid(tf.linalg.matmul(input_X, _w) + _hb)
        return out

# %%
trX=train_images[:10000]
trY=train_labels[:10000]
print(trY[:100])
rbm=RBM_t2(784,500)
rbm.train(trX)
out=rbm.rbm_outpt(trX)

print_result(10, out, trY, count=10)

# %%
print(trX[0])
# %%


from flask import Flask, render_template
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import logging
from .common.filters import format_datetime

login_manager = LoginManager()
db = SQLAlchemy()
migrate = Migrate()

def create_app(settings_module):

    app = Flask(__name__, instance_relative_config=True)

    app.config.from_object(settings_module)

    if app.config.get('TESTING'):
        app.config.from_pyfile('config_testing.py', silent=True)
    else:
        app.config.from_pyfile('config.py')

    login_manager.init_app(app)
    login_manager.login_view = "auth.login"

    db.init_app(app)
    migrate.init_app(app, db)

    #Registro de los filtros
    register_filters(app)

    # Registro de los blueprints
    from .public import public_bp
    app.register_blueprint(public_bp)
    from .admin import admin_bp
    app.register_blueprint(admin_bp)
    from .auth import auth_bp
    app.register_blueprint(auth_bp)

    register_error_handlers(app)

    configure_logging(app)

    return app

def register_error_handlers(app):

    @app.errorhandler(500)
    def base_error_handler(e):
        return render_tempalte("500.html"), 500

    @app.errorhandler(404)
    def error_400_handler(e):
        print('llamando al error handler 400')
        return render_template("404.html"), 404

def configure_logging(app):

    # Eliminamos los posibles manejadores del logger por defecto (si existen)
    del app.logger.handlers[:]

    #Añadimos el logger por defecto a la lista de loggers
    loggers = [app.logger, ]
    handlers = []

    #Creamos un manejador para escribir los mensajes por consola
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)
    console_handler.setFormatter(logging.Formatter('[%(asctime)s] - %(name)s - %(levelname)s - %(message)s'))
    handlers.append(console_handler)

    file_handler = logging.FileHandler("flask-blog.log")
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(logging.Formatter('[%(asctime)s] - %(name)s - %(levelname)s - %(message)s'))
    handlers.append(file_handler)

    #Añadimos cada uno de los handlers a cada uno de los loggers

    for l in loggers:
        for handler in handlers:
            l.addHandler(handler)
        l.propagate = False
        l.setLevel(logging.DEBUG)

def register_filters(app):
    app.jinja_env.filters['datetime'] = format_datetime


str_s = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
         'w', 'x', 'y', 'z']
result = ['-', '_', '.']

def solution(new_id):
    answer_1 = ''
    answer_2 = ''
    answer_3 = ''
    answer_4 = ''
    answer_5 = ''
    answer_6 = ''
    answer_7 = ''
    # 1단계
    for i in new_id:
        if ord(i) >= 65 and ord(i) <= 90:
            i = chr(ord(i) + 32)
        answer_1 += i
    # 2단계
    for i in answer_1:
        if i.isdigit() or i in str_s or i in result:
            answer_2 += i
    # 3단계
    for i in range(len(answer_2)):
        if i + 1 < len(answer_2) and answer_2[i] == '.' and answer_2[i + 1] == '.':
            continue
        answer_3 += answer_2[i]
    # 4단계
    for i in range(len(answer_3)):
        if i == 0 and answer_3[i] == '.':
            continue
        if i == len(answer_3) - 1 and answer_3[i] == '.':
            continue
        answer_4 += answer_3[i]
    # 5단계
    if len(answer_4) == 0:
        answer_5 = 'a'
    else:
        answer_5 = answer_4

    # 6단계
    for i in range(len(answer_5)):
        if i == 14 and answer_5[i] == '.':
            continue
        if i >= 15:
            continue
        answer_6 += answer_5[i]
    # 7단계
    if len(answer_6) <= 2:
        answer_7 = answer_6
        while len(answer_7) < 3:
            answer_7 += answer_6[-1]
    else:
        answer_7 = answer_6
    answer = answer_7

    return answer
print(solution("...!@BaT#*..y.abcdefghijklm"))


from django.db.models import Q

from Ads_Project.functions import LoginRequiredMixin
from django.views.generic import CreateView, UpdateView, ListView, TemplateView
from django.utils.safestring import mark_safe
from django_datatables_view.base_datatable_view import BaseDatatableView
import simplejson as json
from system.models import User, HistoryIndirect
from django.db.models import Sum

class Chart_2_View(LoginRequiredMixin, TemplateView):
    template_name = "system/moshahede/chart_2.html"

    def get_context_data(self, *args, **kwargs):
        context = context = super().get_context_data(**kwargs)
        chart_config={
            'chart': {
                'container': "#OrganiseChart1",
                'rootOrientation': 'WEST',  # NORTH || EAST || WEST || SOUTH
                'scrollbar': "fancy",
                # 'levelSeparation': 30,
                'siblingSeparatio': 40,
                'subTeeSeparation': 80,
                'connectors': {
                    'type': 'step'
                },
                'node': {
                    'HTMLclass': 'nodeExample1'
                }
            }
        }
        user=self.request.user
        parrent=self.request.user.code_moaref
        print(parrent)
        if parrent is not None:
            chart_config['nodeStructure']={
                'text':{
                    'name': "دعوت کننده شما:",
                    'title': parrent.first_name + " " + parrent.last_name
                },
                'image': "/static/img/avatar/avatar.png",
                'children': []
            }
        else:
            chart_config['nodeStructure'] = {
                'text': {
                    'name':user.first_name + ' ' + user.last_name ,
                    'title': "شما در سطح یک قرار دارید"
                },
                'image': "/static/img/avatar/avatar.png",
                'children': []
            }
        print(chart_config)
        context['chart_config'] = mark_safe(str(chart_config))
        return context

class Chart_1_View(LoginRequiredMixin, TemplateView):
    template_name = "system/moshahede/parent_children.html"

class ParentChildrenDatatableView(LoginRequiredMixin, BaseDatatableView):
    model = User
    columns = ['first_name','sath','daramad']

    def get_initial_queryset(self):
        user=self.request.user
        qs = super().get_initial_queryset()
        qs = qs.filter(list_parent__contains="[{}]".format(user.id))
        return qs

    def render_column(self, row:User, column):
        jsonDec = json.decoder.JSONDecoder()
        parents = jsonDec.decode(row.list_parent)
        if column == 'first_name':
            return row.first_name + " " +row.last_name
        if column =='sath':
            return parents.index([self.request.user.id])+1
        if column =="daramad":
            history=HistoryIndirect.objects.filter(parent=self.request.user,montasher_konande=row).all().aggregate(Sum('mablagh'))
            return history['mablagh__sum']
        return super().render_column(row, column)

class Parent_Children_List_View(LoginRequiredMixin, ListView):
    model = User
    template_name = 'system/moshahede/list_of_parent_children.html'


from __future__ import annotations

from dataclasses import dataclass
from dataclasses import field

import symforce.symbolic as sf
from symforce import jacobian_helpers
from symforce import typing as T

@dataclass
class ResidualBlock:
    """
    A single residual vector, with associated extra values.  The extra values are not used in the
    optimization, but are intended to be additional outputs used for debugging or other purposes.
    """

    residual: sf.Matrix
    extra_values: T.Optional[T.Dataclass] = None
    metadata: T.Optional[T.Dict[str, T.Any]] = None

    def compute_jacobians(
        self,
        inputs: T.Sequence[T.Element],
        residual_name: str = None,
        key_names: T.Sequence[str] = None,
    ) -> T.Sequence[sf.Matrix]:
        """
        Compute the jacobians of this residual block with respect to a sequence of inputs

        Args:
            inputs: Sequence of inputs to differentiate with respect to
            residual_name: Optional human-readable name of the residual to be used for debug
                           messages
            key_names: Optional sequence of human-readable names for the inputs to be used for debug
                       messages

        Returns:
            Sequence of jacobians of the residual with respect to each entry in inputs
        """
        return jacobian_helpers.tangent_jacobians(self.residual, inputs)

    def set_metadata(self, key: str, value: T.Any) -> ResidualBlock:
        """
        Sets a metadata field of the residual block and returns the residual block.
        """
        if self.metadata is None:
            self.metadata = {key: value}
        else:
            self.metadata[key] = value
        return self

@dataclass
class ResidualBlockWithCustomJacobian(ResidualBlock):
    """
    A residual block, with a custom jacobian for the residual

    This should generally only be used if you want to override the jacobian computed by SymForce,
    e.g. to stop derivatives with respect to certain variables or directions, or because the
    jacobian can be analytically simplified in a way that SymForce won't do automatically.  The
    ``custom_jacobians`` field should then be filled out with a mapping from all inputs to the
    residual which may be differentiated with respect to, to the desired jacobian of the residual
    with respect to each of those inputs.
    """

    custom_jacobians: T.Dict[T.Element, sf.Matrix] = field(default_factory=dict)

    def compute_jacobians(
        self,
        inputs: T.Sequence[T.Element],
        residual_name: str = None,
        key_names: T.Sequence[str] = None,
    ) -> T.Sequence[sf.Matrix]:
        """
        Compute the jacobians of this residual block with respect to a sequence of inputs

        Args:
            inputs: Sequence of inputs to differentiate with respect to
            residual_name: Optional human-readable name of the residual to be used for debug
                           messages
            key_names: Optional sequence of human-readable names for the inputs to be used for debug
                       messages

        Returns:
            Sequence of jacobians of the residual with respect to each entry in inputs
        """
        residual_jacobians = []
        for i, input_element in enumerate(inputs):
            if input_element in self.custom_jacobians:
                # The user provided a derivative with respect to this input
                residual_jacobians.append(self.custom_jacobians[input_element])
            else:
                # The user did not provide a derivative with respect to this input.  So,
                # compute it.  If it's nonzero, raise an error, since the user probably
                # wants to provide custom jacobians for all the variables if they
                # provided one
                residual_input_jacobian = self.residual.jacobian(input_element)
                if (
                    residual_input_jacobian
                    != sf.matrix_type_from_shape(residual_input_jacobian.shape).zero()
                ):
                    residual_name = residual_name or str(self)

                    if key_names is not None:
                        key_name = key_names[i]
                    else:
                        key_name = str(input_element)

                    raise ValueError(
                        f"The residual `{residual_name}` has a nonzero jacobian with respect to "
                        f"input `{key_name}`.  Custom jacobians were provided for this residual, "
                        "but not for this input variable.  If you wish to use the automatically "
                        "computed jacobian for this input, please compute it using "
                        "`jacobian_helpers.tangent_jacobians(residual, [input])[0]` and add it to "
                        "the custom_jacobians dictionary"
                    )
                residual_jacobians.append(residual_input_jacobian)
        return residual_jacobians


from __future__ import division
import numpy as np
import pandas as pd
from matplotlib.colors import to_rgb

from logomaker.src.error_handling import check
from logomaker.src.matrix import ALPHABET_DICT

# Sets default color schemes specified sets of characters
CHARS_TO_COLORS_DICT = {
    tuple('ACGT'): 'classic',
    tuple('ACGU'): 'classic',
    tuple('ACDEFGHIKLMNPQRSTVWY'): 'weblogo_protein',
}

weblogo_blue = [.02, .09, .74]
weblogo_pink = [.83, .11, .75]
weblogo_green = [.13, .83, .15]
weblogo_red = [.83, .04, .08]
weblogo_black = [0, 0, 0]

# COLOR_SCHEME_DICT provides a default set of logo colorschemes
# that can be passed to the 'color_scheme' argument of Logo()
three_ones = np.ones(3)
COLOR_SCHEME_DICT = {
    'classic': {
        'G': [1, .65, 0],
        'TU': [1, 0, 0],
        'C': [0, 0, 1],
        'A': [0, .5, 0]
    },

    'grays': {
        'A': .2 * three_ones,
        'C': .4 * three_ones,
        'G': .6 * three_ones,
        'TU': .8 * three_ones
    },

    'base_pairing': {
        'TAU': [1, .55, 0],
        'GC': [0, 0, 1]
    },

    # Suggested by Ryan Z. Friedman
    # https://twitter.com/rfriedman22/status/1085722502649786368
    'colorblind_safe': {
        'A': '#009980',
        'C': '#59B3E6',
        'G': '#E69B04',
        'TU': '#1A1A1A'
    },

    # Weblogo: http://weblogo.berkeley.edu/examples.html
    # BlockLogo: http://research4.dfci.harvard.edu/cvc/blocklogo/HTML/examples.php
    'weblogo_protein': {
        'RHK' : weblogo_blue, # positive charge
        'DE' : weblogo_red, # negative charge
        'QN' : weblogo_pink, # polar uncharged long
        'GCSTY' : weblogo_green, # polar uncharged short and special cases (???)
        'ILMAFVPW' : weblogo_black # hydrophobic
    },

    # Skylign: http://skylign.org/logo/example
    'skylign_protein': {
        'F': [.16, .99, .18],
        'Y': [.04, .40, .05],
        'L': [.99, .60, .25],
        'V': [1.0, .80, .27],
        'I': [.80, .60, .24],
        'H': [.40, .02, .20],
        'W': [.42, .79, .42],
        'A': [.99, .60, .42],
        'S': [.04, .14, .98],
        'T': [.17, 1.0, 1.0],
        'M': [.80, .60, .80],
        'N': [.21, .40, .40],
        'Q': [.40, .41, .79],
        'R': [.59, .02, .04],
        'K': [.40, .20, .03],
        'E': [.79, .04, .22],
        'G': [.95, .94, .22],
        'D': [.99, .05, .11],
        'P': [.10, .61, .99],
        'C': [.09, .60, .60]
    },

    # dmslogo: https://jbloomlab.github.io/dmslogo/dmslogo.colorschemes.html
    'dmslogo_charge': {
        'A': '#000000',
        'C': '#000000',
        'D': '#0000FF',
        'E': '#0000FF',
        'F': '#000000',
        'G': '#000000',
        'H': '#FF0000',
        'I': '#000000',
        'K': '#FF0000',
        'L': '#000000',
        'M': '#000000',
        'N': '#000000',
        'P': '#000000',
        'Q': '#000000',
        'R': '#FF0000',
        'S': '#000000',
        'T': '#000000',
        'V': '#000000',
        'W': '#000000',
        'Y': '#000000'
    },

    # dmslogo: https://jbloomlab.github.io/dmslogo/dmslogo.colorschemes.html
    'dmslogo_funcgroup': {
        'A': '#f76ab4',
        'C': '#ff7f00',
        'D': '#e41a1c',
        'E': '#e41a1c',
        'F': '#84380b',
        'G': '#f76ab4',
        'H': '#3c58e5',
        'I': '#12ab0d',
        'K': '#3c58e5',
        'L': '#12ab0d',
        'M': '#12ab0d',
        'N': '#972aa8',
        'P': '#12ab0d',
        'Q': '#972aa8',
        'R': '#3c58e5',
        'S': '#ff7f00',
        'T': '#ff7f00',
        'V': '#12ab0d',
        'W': '#84380b',
        'Y': '#84380b'
    },

    'hydrophobicity': {
        'RKDENQ': [0, 0, 1],
        'SGHTAP': [0, .5, 0],
        'YVMCLFIW': [0, 0, 0]
    },

    'chemistry': {
        'GSTYC': [0, .5, 0],
        'QN': [.5, 0, .5],
        'KRH': [0, 0, 1],
        'DE': [1, 0, 0],
        'AVLIPWFM': [0, 0, 0]
    },

    'charge': {
        'KRH': [0, 0, 1],
        'DE': [1, 0, 0],
        'GSTYCQNAVLIPWFM': [.5, .5, .5]
    },

    'NajafabadiEtAl2017': {
        'DEC': [.42, .16, .42],
        'PG': [.47, .47, 0.0],
        'MIWALFV': [.13, .35, .61],
        'NTSQ': [.25, .73, .28],
        'RK': [.74, .18, .12],
        'HY': [.09, .47, .46],
    },
}

def list_color_schemes():
    """
    Provides user with a list of valid color_schemes built into Logomaker.

    returns
    -------
    colors_df: (dataframe)
        A pandas dataframe listing each color_scheme and the corresponding
        set of characters for which colors are specified.
    """

    names = list(COLOR_SCHEME_DICT.keys())
    colors_df = pd.DataFrame()
    for i, name in enumerate(names):
        color_scheme = COLOR_SCHEME_DICT[name]
        characters = list(''.join(list(color_scheme.keys())))
        characters.sort()
        colors_df.loc[i, 'color_scheme'] = name
        colors_df.loc[i, 'characters'] = ''.join(characters)

    return colors_df

def _restrict_dict(in_dict, keys_to_keep):
    """ Restricts a in_dict to keys that fall within keys_to_keep. """
    return dict([(k, v) for k, v in in_dict.items() if k in keys_to_keep])

def _expand_color_dict(color_dict):
    """ Expands the string keys in color_dict, returning new_dict that has
    the same values but whose keys are single characters. These single
    characters are both uppercase and lowercase versions of the characters
    in the color_dict keys. """
    new_dict = {}
    for key in color_dict.keys():
        value = color_dict[key]
        for char in key:
            new_dict[char.upper()] = value
            new_dict[char.lower()] = value
    return new_dict

def get_rgb(color_spec):
    """
    Safely returns an RGB np.ndarray given a valid color specification
    """

    # TODO: the following code should be reviewed for edge-cases:
    # initalizing rgb to handle referenced before assignment type error
    rgb = None

    # If color specification is a string
    if isinstance(color_spec, str):
        try:
            rgb = np.array(to_rgb(color_spec))

        # This will trigger if to_rgb does not recognize color_spec.
        # In this case, raise an error to user.
        except:
            check(False, 'invalid choice: color_spec=%s' % color_spec)

    # Otherwise, if color_specification is array-like, it should
    # specify RGB values; convert to np.ndarray
    elif isinstance(color_spec, (list, tuple, np.ndarray)):

        # color_spec must have length 3 to be RGB
        check(len(color_spec) == 3,
              'color_scheme, if array, must be of length 3.')

        # color_spec must only contain numbers between 0 and 1
        check(all(0 <= x <= 1 for x in color_spec),
              'Values of color_spec must be between 0 and 1 inclusive.')

        # Cast color_spec as RGB
        rgb = np.array(color_spec)

    # Otherwise, throw error
    else:
        check(False, 'type(color_spec) = %s is invalid.' % type(color_spec))

    # Return RGB as an np.ndarray
    return rgb

def get_color_dict(color_scheme, chars):
    """
    Return a color_dict constructed from a user-specified color_scheme and
    a list of characters
    """

    # Check that chars is a list
    check(isinstance(chars, (str, list, tuple, np.ndarray)),
          "chars must be a str or be array-like")

    # Check that chars has length of at least 1
    check(len(chars) >= 1, 'chars must have length >= 1')

    # Sort characters
    chars = list(chars)
    chars.sort()

    # Check that all entries in chars are strings of length 1
    for i, c in enumerate(chars):
        c = str(c) # convert from unicode to string to work with python 2
        check(isinstance(c, str) and len(c)==1,
              'entry number %d in chars is %s; ' % (i, repr(c)) +
              'must instead be a single character')

    # if color_scheme is None, choose default based on chars
    if color_scheme is None:
        key = tuple(chars)
        color_scheme = CHARS_TO_COLORS_DICT.get(key, 'gray')
        color_dict = get_color_dict(color_scheme, chars)

    # otherwise, if color_scheme is a dictionary
    elif isinstance(color_scheme, dict):

        # make sure all the keys are strings
        for key in color_scheme.keys():
            check(isinstance(key, str),
                  'color_scheme dict contains a key (%s) ' % repr(key) +
                  'that is not of type str.')

        # expand the dictionary
        color_dict = _expand_color_dict(color_scheme)

        # set all values to rgb
        for key in color_dict.keys():
            color_dict[key] = to_rgb(color_dict[key])

    # otherwise, if color_scheme is a string, it must either be a valid key in
    # COLOR_SCHEME_DICT or a named matplotlib color
    elif isinstance(color_scheme, str):

        # If a valid key, get the color scheme dict and expand
        if color_scheme in COLOR_SCHEME_DICT.keys():
            tmp_dict = COLOR_SCHEME_DICT[color_scheme]
            color_dict = _expand_color_dict(tmp_dict)

            # Force each color to rgb
            for c in color_dict.keys():
                color = color_dict[c]
                rgb = to_rgb(color)
                color_dict[c] = np.array(rgb)

        # Otherwise, try to convert color_scheme to RGB value, then create
        # color_dict using keys from chars and setting all values to RGB value.
        else:
            try:
                rgb = to_rgb(color_scheme)
                color_dict = dict([(c, rgb) for c in chars])

            # This will trigger if to_rgb does not recognize color_scheme.
            # In this case, raise an error to user.
            except:
                check(False, 'invalid choice: color_scheme=%s' % color_scheme)

    # Otherwise, if color_scheme is array-like, it should be an RGB value
    elif isinstance(color_scheme, (list, tuple, np.ndarray)):

        # color_scheme must have length 3 to be RGB
        check(len(color_scheme) == 3,
              'color_scheme, if array, must be of length 3.')

        # Cast color_scheme as RGB
        rgb = np.ndarray(color_scheme)

        # Construct color_dict with rgb as value for every character in chars
        color_dict = dict([(c, rgb) for c in chars])

    # Otherwise, raise error
    else:
        check(False,
              'Error: color_scheme has invalid type %s'
              % type(color_scheme))

    # If all the characters in chars are not also within the keys of color_dict,
    # add them with color 'black'
    if not set(chars) <= set(color_dict.keys()):
        for c in chars:
            if not c in color_dict:
                print(" Warning: Character '%s' is not in color_dict. " % c +
                      "Using black.")
                color_dict[c] = to_rgb('black')

    return color_dict


# flask_web/app.py

from flask import Flask

def create_app():
    f_app = Flask(__name__)
    return f_app

app = create_app()

@app.route('/')
def hello_world():
    return 'Hey, we have Flask in a Docker container!'

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')


import functools
import os
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING, Callable, Dict, Optional, Type, Tuple, Union

from ray.air import session
from ray.air.checkpoint import Checkpoint
from ray.air.config import DatasetConfig, RunConfig, ScalingConfig
from ray.train.torch import TorchConfig
from ray.train.trainer import GenDataset

from ray.train.torch import TorchTrainer, get_device
from ray.train.torch.config import _set_torch_distributed_env_vars

ACCELERATE_IMPORT_ERROR: Optional[ImportError] = None

try:
    from ray.train.huggingface.accelerate._accelerate_utils import (
        launch_command,
        AccelerateDefaultNamespace,
        AccelerateConfigWrapper,
        load_accelerate_config,
    )
except ImportError as e:
    ACCELERATE_IMPORT_ERROR = e
    launch_command = None
    AccelerateDefaultNamespace = None
    AccelerateConfigWrapper = None
    load_accelerate_config = None

if TYPE_CHECKING:
    from ray.data.preprocessor import Preprocessor
    from ray.tune.trainable import Trainable

class AccelerateTrainer(TorchTrainer):
    """A Trainer for data parallel HuggingFace Accelerate training with PyTorch.

    This Trainer is a wrapper around the :class:`~ray.train.torch.TorchTrainer`,
    providing the following extra functionality:
    1. Loading and parsing of Accelerate configuration files (created by
    ``accelerate config`` CLI command),
    2. Applying the configuration files on all workers, making sure the environment
    is set up correctly.

    This Trainer runs the function ``train_loop_per_worker`` on multiple Ray
    Actors. These actors already have the necessary torch process group
    configured for distributed PyTorch training, as well as all environment variables
    required by Accelerate, as defined in the configuration file. This allows you
    to use Accelerate APIs (such as ``Accelerator``) inside ``train_loop_per_worker``
    as you would without Ray.

    Inside the ``train_loop_per_worker`` function, In addition to Accelerate APIs, you
    can use any of the :ref:`Ray AIR session methods <air-session-ref>`.
    See full example code below.

    .. testcode::

        def train_loop_per_worker():
            # Report intermediate results for callbacks or logging and
            # checkpoint data.
            session.report(...)

            # Get dict of last saved checkpoint.
            session.get_checkpoint()

            # Session returns the Dataset shard for the given key.
            session.get_dataset_shard("my_dataset")

            # Get the total number of workers executing training.
            session.get_world_size()

            # Get the rank of this worker.
            session.get_world_rank()

            # Get the rank of the worker on the current node.
            session.get_local_rank()

    For more information, see the documentation of
    :class:`~ray.train.torch.TorchTrainer`.

    .. note::

        You need to use ``session.report()`` to communicate results and checkpoints
        back to Ray Train.

    Accelerate integrations with DeepSpeed, FSDP, MegatronLM etc. are fully supported.
    If the Accelerate configuration contains a path to a DeepSpeed config file
    (``deepspeed_config_file``), that file will also be loaded and applied on the
    workers.

    The following Accelerate configuration options will be ignored and automatically
    set by the Trainer according to Ray AIR configs (eg. ``ScalingConfig``):
    - Number of machines (``num_machines``)
    - Number of processes (``num_processes``)
    - Rank of the current machine (``machine_rank``)
    - Local rank of the current machine
    - GPU IDs (``gpu_ids``)
    - Number of CPU threads per process (``num_cpu_threads_per_process``)
    - IP of the head process (``main_process_ip``)
    - Port of the head process (``main_process_port``)
    - Whether all machines are on the same network (``same_network``)
    - Whether to force a CPU-only mode (``cpu``/``use_cpu``)
    - rdzv backend (``rdzv_backend``)
    - Main training function (``main_training_function``)
    - Type of launcher

    This Trainer requires ``accelerate>=0.17.0`` package.
    It is tested with ``accelerate==0.17.1``.

    Example:
        .. testcode::

            import torch
            import torch.nn as nn

            from accelerate import Accelerator

            import ray
            from ray.air import session, Checkpoint
            from ray.train.huggingface import AccelerateTrainer
            from ray.air.config import ScalingConfig
            from ray.air.config import RunConfig
            from ray.air.config import CheckpointConfig

            # If using GPUs, set this to True.
            use_gpu = False

            # Define NN layers archicture, epochs, and number of workers
            input_size = 1
            layer_size = 32
            output_size = 1
            num_epochs = 200
            num_workers = 3

            # Define your network structure
            class NeuralNetwork(nn.Module):
                def __init__(self):
                    super(NeuralNetwork, self).__init__()
                    self.layer1 = nn.Linear(input_size, layer_size)
                    self.relu = nn.ReLU()
                    self.layer2 = nn.Linear(layer_size, output_size)

                def forward(self, input):
                    return self.layer2(self.relu(self.layer1(input)))

            # Define your train worker loop
            def train_loop_per_worker():

                # Initialize the Accelerator
                accelerator = Accelerator()

                # Fetch training set from the session
                dataset_shard = session.get_dataset_shard("train")
                model = NeuralNetwork()

                # Loss function, optimizer, prepare model for training.
                # This moves the data and prepares model for distributed
                # execution
                loss_fn = nn.MSELoss()
                optimizer = torch.optim.Adam(
                    model.parameters(), lr=0.01, weight_decay=0.01
                )
                model, optimizer = accelerator.prepare(model, optimizer)

                # Iterate over epochs and batches
                for epoch in range(num_epochs):
                    for batches in dataset_shard.iter_torch_batches(
                        batch_size=32, dtypes=torch.float
                    ):

                        # Add batch or unsqueeze as an additional dimension [32, x]
                        inputs, labels = torch.unsqueeze(batches["x"], 1), batches["y"]
                        output = model(inputs)

                        # Make output shape same as the as labels
                        loss = loss_fn(output.squeeze(), labels)

                        # Zero out grads, do backward, and update optimizer
                        optimizer.zero_grad()
                        accelerator.backward(loss)
                        optimizer.step()

                        # Print what's happening with loss per 30 epochs
                        if epoch % 20 == 0:
                            print(f"epoch: {epoch}/{num_epochs}, loss: {loss:.3f}")

                    # Report and record metrics, checkpoint model at end of each
                    # epoch
                    session.report(
                        {"loss": loss.item(), "epoch": epoch},
                        checkpoint=Checkpoint.from_dict(
                            dict(
                                epoch=epoch,
                                model=accelerator.unwrap_model(model).state_dict(),
                            )
                        ),
                    )

            torch.manual_seed(42)
            train_dataset = ray.data.from_items(
                [{"x": x, "y": 2 * x + 1} for x in range(200)]
            )

            # Define scaling and run configs
            scaling_config = ScalingConfig(num_workers=3, use_gpu=use_gpu)
            run_config = RunConfig(checkpoint_config=CheckpointConfig(num_to_keep=1))

            trainer = AccelerateTrainer(
                train_loop_per_worker=train_loop_per_worker,
                # Instead of using a dict, you can run ``accelerate config``.
                # The default value of None will then load that configuration
                # file.
                accelerate_config={},
                scaling_config=scaling_config,
                run_config=run_config,
                datasets={"train": train_dataset},
            )

            result = trainer.fit()

            best_checkpoint_loss = result.metrics["loss"]

            # Assert loss is less 0.09
            assert best_checkpoint_loss <= 0.09

    .. testoutput::
        :hide:
        :options: +ELLIPSIS

        ...

    Args:
        train_loop_per_worker: The training function to execute.
            This can either take in no arguments or a ``config`` dict.
        train_loop_config: Configurations to pass into
            ``train_loop_per_worker`` if it accepts an argument.
        accelerate_config: Accelerate configuration to be applied on every worker.
            This can be a path to a file generated with ``accelerate config``,
            a configuration dict or None, in which case it will load the configuration
            file from the default location as defined by Accelerate.
        torch_config: Configuration for setting up the PyTorch backend. If set to
            None, use the default configuration. This replaces the ``backend_config``
            arg of ``DataParallelTrainer``.
        scaling_config: Configuration for how to scale data parallel training.
        dataset_config: Configuration for dataset ingest.
        run_config: Configuration for the execution of the training run.
        datasets: Any Datasets to use for training. Use
            the key "train" to denote which dataset is the training
            dataset. If a ``preprocessor`` is provided and has not already been fit,
            it will be fit on the training dataset. All datasets will be transformed
            by the ``preprocessor`` if one is provided.
        preprocessor: A ``ray.data.Preprocessor`` to preprocess the
            provided datasets.
        resume_from_checkpoint: A checkpoint to resume training from.
    """

    def __init__(
        self,
        train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]],
        *,
        train_loop_config: Optional[Dict] = None,
        accelerate_config: Optional[Union[dict, str, Path, os.PathLike]] = None,
        torch_config: Optional[TorchConfig] = None,
        scaling_config: Optional[ScalingConfig] = None,
        dataset_config: Optional[Dict[str, DatasetConfig]] = None,
        run_config: Optional[RunConfig] = None,
        datasets: Optional[Dict[str, GenDataset]] = None,
        preprocessor: Optional["Preprocessor"] = None,
        resume_from_checkpoint: Optional[Checkpoint] = None,
    ):

        if ACCELERATE_IMPORT_ERROR is not None:
            raise ACCELERATE_IMPORT_ERROR

        self.accelerate_config = accelerate_config
        (
            self._accelerate_config_raw,
            self._deepspeed_config_file_raw,
        ) = self._unwrap_accelerate_config_if_needed(accelerate_config)

        super().__init__(
            train_loop_per_worker=train_loop_per_worker,
            train_loop_config=train_loop_config,
            torch_config=torch_config,
            scaling_config=scaling_config,
            dataset_config=dataset_config,
            run_config=run_config,
            datasets=datasets,
            preprocessor=preprocessor,
            resume_from_checkpoint=resume_from_checkpoint,
        )

    def _unwrap_accelerate_config_if_needed(
        self,
        accelerate_config: Optional[
            Union[dict, str, Path, os.PathLike, AccelerateConfigWrapper]
        ],
    ) -> Tuple[str, Optional[str]]:
        # The AccelerateConfigWrapper is used to deal with the issue of the
        # Trainer being initialized twice (by the user and by us in the Trainable).
        # If it's initialized by the user, accelerate_config will not be an instance
        # of AccelerateConfigWrapper. This means we should read the config file from
        # given path.
        # If accelerate_config is an instance of AccelerateConfigWrapper, that means
        # we are dealing with a file that was already read, and we should instead use
        # the string in the wrapper as the raw contents of the file. This should
        # only happen internally, during initialization of this class in the Trainable.
        if isinstance(accelerate_config, AccelerateConfigWrapper):
            return (
                accelerate_config.config_raw,
                accelerate_config.deepspeed_config_raw,
            )
        else:
            return load_accelerate_config(accelerate_config)

    def as_trainable(self) -> Type["Trainable"]:
        # We want to load the config when the Trainer is first instantiated,
        # and share the contents with the Trainables (which may be on different)
        # nodes
        old_accelerate_config = self._param_dict.get("accelerate_config", None)
        self._param_dict["accelerate_config"] = AccelerateConfigWrapper(
            self._accelerate_config_raw, self._deepspeed_config_file_raw
        )
        try:
            ret = super().as_trainable()
        finally:
            self._param_dict["accelerate_config"] = old_accelerate_config
        return ret

    def training_loop(self) -> None:
        old_train_loop_per_worker = self._train_loop_per_worker
        self._train_loop_per_worker = self._wrap_train_loop_per_worker(
            self._train_loop_per_worker,
            self._accelerate_config_raw,
            self._deepspeed_config_file_raw,
        )
        try:
            ret = super().training_loop()
        finally:
            self._train_loop_per_worker = old_train_loop_per_worker
        return ret

    @classmethod
    def _wrap_train_loop_per_worker(
        cls,
        train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]],
        accelerate_config_raw: str,
        deepspeed_config_file_raw: str,
    ):
        """Wrap around train_loop_per_worker to set necessary Accelerate env vars."""

        @functools.wraps(train_loop_per_worker)
        def _accelerate_train_loop_per_worker(*args, **kwargs):
            with tempfile.TemporaryDirectory() as tempdir:
                # Write Accelerate config to file so it can be read
                # by Accelerate
                temp_config_file = os.path.join(tempdir, "default_config.yaml")
                with open(temp_config_file, "w") as f:
                    f.write(accelerate_config_raw)

                # Set by TorchBackend
                master_addr = os.environ["MASTER_ADDR"]
                master_port = os.environ["MASTER_PORT"]

                namespace = AccelerateDefaultNamespace()
                namespace.config_file = temp_config_file
                namespace.num_processes = 1
                namespace.num_machines = session.get_world_size()
                namespace.machine_rank = session.get_world_rank()
                namespace.num_cpu_threads_per_process = (
                    session.get_trial_resources().bundles[-1].get("CPU", 1)
                )
                namespace.gpu_ids = None
                namespace.main_process_ip = master_addr
                namespace.main_process_port = master_port
                namespace.same_network = False

                device = get_device()
                if isinstance(device, list):
                    device = device[0]
                if device.type == "cpu":
                    os.environ["LOCAL_RANK"] = "-1"
                    namespace.use_cpu = True
                else:
                    namespace.use_cpu = False

                # Handle DeepSpeed config
                if isinstance(deepspeed_config_file_raw, dict):
                    namespace.deepspeed_config_file = deepspeed_config_file_raw
                elif deepspeed_config_file_raw:
                    deepspeed_config_file = os.path.join(
                        tempdir, "deepspeed_config.json"
                    )
                    with open(deepspeed_config_file, "w") as f:
                        f.write(deepspeed_config_file_raw)
                    namespace.deepspeed_config_file = deepspeed_config_file

                # Let Accelerate set all env vars
                launch_command(namespace)

                # Set our env vars again to override Accelerate
                os.environ["MASTER_ADDR"] = master_addr
                os.environ["MASTER_PORT"] = master_port
                _set_torch_distributed_env_vars()

                if device.type == "cpu":
                    os.environ["LOCAL_RANK"] = "-1"

                return train_loop_per_worker(*args, **kwargs)

        return _accelerate_train_loop_per_worker


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import time

link = "http://suninjuly.github.io/selects2.html"

def sum(a, b):
    return str(int(a) + int(b))

try:
    browser = webdriver.Chrome()
    browser.get(link)

    # Получаем из верстки переменные
    number_1 = browser.find_element(By.ID, 'num1')
    number_2 = browser.find_element(By.ID, 'num2')

    # Вычисляем сумму полученных переменных
    summary = sum(number_1.text, number_2.text)

    # Ищем в select полученное значение
    select = Select(browser.find_element(By.ID, "dropdown"))
    select.select_by_value(f"{summary}")

    button = browser.find_element(By.CLASS_NAME, "btn.btn-default")
    button.click()

finally:

    # Ожидаем, чтобы визуально оценить результаты прохождения скрипта
    time.sleep(10)
    # Закрываем браузер после всех манипуляций
    browser.quit()
# Не забываем оставить пустую строку в конце файла


class Solution:
    # @param grid, a list of lists of integers
    # @return an integer
    def minPathSum(self, grid):
        if not grid or len(grid) == 0:
            return 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if i == 0 and j > 0:
                    grid[i][j]+=grid[i][j-1]
                elif j == 0 and i > 0:
                    grid[i][j]+=grid[i-1][j]
                elif i > 0 and j > 0:
                    grid[i][j] += min(grid[i-1][j],grid[i][j-1])
        return grid[len(grid)-1][len(grid[0])-1]


from rest_framework import viewsets

from . import models
from .serializers import GenericDictTableSerializer

def dict_table_viewset_factory(dict_table_model):
    """A class factory for generating viewsets for dicttable based models

    This function acts as a class factory. It generates classes that derive
    from django-rest-framework's ``viewsets.ReadOnlyModelViewSet``.
    It returns a viewset class that can be used to generate API endpoints for
    the various models that are based on ``nfdcore.models.DictionaryTable``.

    The code used here is somewhat obscure, as it is based on meta-programming
    techniques. This approach was chosen in order to reduce the number of
    lines of code that would need to be written in order to generate viewsets
    for all of the existing dicttable models.

    The code itself just calls ``type()`` with the correct arguments in order
    to generate a class at runtime.

    Examples
    --------

    The following example defines the ``ReservationViewSet`` class:

    >>> ReservationViewSet = dict_table_viewset_factory(models.Reservation)

    Without the current function, the equivalent code would be:

    >>> Class ReservationViewSet(viewsets.ReadOnlyModelViewSet):
    ...     queryset = models.Reservation.objects.all()
    ...     serializer_class = GenericDictTableSerializer
    ...
    ...     def get_serializer(self, *args, **kwargs):
    ...         return self.serializer_class(
    ...             model=models.Reservation, *args, **kwargs)

    """

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(model=dict_table_model, *args, **kwargs)

    cls_name = "{}ViewSet".format(dict_table_model.__name__)
    cls_attrs = {
        "queryset": dict_table_model.objects.all(),
        "serializer_class": GenericDictTableSerializer,
        "get_serializer": get_serializer,
    }

    return type(
        cls_name,
        (viewsets.ReadOnlyModelViewSet,),
        cls_attrs
    )

_MODELS_TO_SERIALIZE = [
    models.AnimalLifestages,
    models.AquaticHabitatCategory,
    models.AquaticSampler,
    models.Aspect,
    models.BedrockAndOutcrops,
    models.CanopyCover,
    models.ChannelType,
    models.CMSensitivity,
    models.CmStatus,  # this is extended
    models.ConiferLifestages,
    models.DayTime,
    models.DiseasesAndAbnormalities,
    models.ElementType,
    models.FernLifestages,
    models.FloweringPlantLifestages,
    models.FungalAssociationType,
    models.FungusApparentSubstrate,
    models.Gender,
    models.GeneralHabitatCategory,
    models.GlacialDeposit,
    models.GlacialDepositPleistoceneAge,
    models.GroundSurface,
    models.GRank,
    models.HmfeiLocalAbundance,
    models.IucnRedListCategory,
    models.LakeMicrohabitat,
    models.LandscapePosition,
    models.LeapLandCover,
    models.LoticHabitatType,
    models.Marks,
    models.MoistureRegime,
    models.MossLifestages,
    models.MushroomGroup,
    models.MushroomGrowthForm,
    models.MushroomOdor,
    models.MushroomVerticalLocation,
    models.NaturalAreaCondition,
    models.NaturalAreaType,
    models.NRank,
    models.OccurrenceCategory,
    models.PlantCount,
    models.PondLakeType,
    models.PondLakeUse,
    models.Preservative,
    models.RecordOrigin,
    models.RecordingStation,
    models.RegionalFrequency,
    models.RegionalStatus,  # this is extended
    models.Repository,
    models.Reservation,
    models.Season,
    models.ShorelineType,
    models.SlimeMoldClass,  # this is extended
    models.SlimeMoldMedia,
    models.Slope,
    models.SRank,
    models.Storage,
    models.StreamDesignatedUse,
    models.TerrestrialSampler,
    models.TerrestrialStratum,
    models.UsfwsStatus,
    models.WaterFlowType,
    models.WaterSource,
    models.Watershed,
    models.WetlandConnectivity,
    models.WetlandHabitatFeature,
    models.WetlandLocation,
    models.WetlandType,
]

for cls_model in _MODELS_TO_SERIALIZE:
    serializer_cls = dict_table_viewset_factory(cls_model)
    # put serializer_cls in module's namespace so it can be easily accessed
    globals()[serializer_cls.__name__] = serializer_cls


#-*- coding:utf-8 -*-

import cv2
import os
import time
import numpy as np
import matplotlib.pyplot as plt
import imutils

'''
1. 辨识BIOS光标位置  两个方案：1. 颜色识别，2. 轮廓识别
'''

picPath = "C:\\Users\\Laurence_SZH\\Pictures\\Camera Roll\\201124183637.BMP"
fullPath = os.path.expanduser(picPath)
print(fullPath)

pic = cv2.imread(fullPath)
print(pic)
#pic2 = pic[:,:,[2,1,0]]
pic2 = cv2.cvtColor(pic, cv2.COLOR_BGR2RGB)
#plt.subplot(20, 20, 10)
#以下这段主要是show出我们读到的图片

#用plt.show的好处是可以读得到threshod的值
plt.imshow(pic2)
plt.title('BGR')
#plt.show()  # 用这个会一直显示
plt.ion()  #搭配plt.pause & plt.close()可以让窗口显示5秒就关闭
plt.pause(5)
#plt.waitforbuttonpress(4)
plt.close()  #关闭图像窗口

# 利用阀值_绘制长方形的BIOS光标轮廓
img_gray = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY)
# ret, thresh = cv2.threshold(img_gray, 16, 18, 0)
ret, thresh = cv2.threshold(img_gray, 33, 0, 0)
plt.imshow(img_gray)
plt.title('thresh')
plt.ion()
plt.pause(35)
plt.close()

#检测图像的连通区(输入为二值化图像)
threshold, contours, heirarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 绘制寻找到的轮廓线
img_contours = cv2.drawContours(pic, contours, -1, (255,255,255),3)

cv2.imshow('contours', img_contours)
cv2.waitKey(0) & 0xFF == ord('q')

# 测试一下那个阀值的参数更适合我们的BIOS介面
#import numpy as np
#from matplotlib import pyplot as plt

#img = cv2.imread(r'/Users/Documents/image01.jpg',0)   # 读入灰度图
ret,thresh1 = cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY)
ret,thresh2 = cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY_INV)
ret,thresh3 = cv2.threshold(img_gray,127,255,cv2.THRESH_TRUNC)
ret,thresh4 = cv2.threshold(img_gray,127,255,cv2.THRESH_TOZERO)
ret,thresh5 = cv2.threshold(img_gray,127,255,cv2.THRESH_TOZERO_INV)

titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [img_gray, thresh1, thresh2, thresh3, thresh4, thresh5]

for i in range(6):
    plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])

plt.show()


from curso import Curso
from aluno import Aluno
from disciplina import Disciplina
from desempenho import Desempenho

def testar():
	c = Curso('Info')
	a = Aluno('Joao','01/01/01')
	d = Disciplina('Loo', 4, c)
	e = Disciplina('ED', 4, c)
	f = Disciplina('TE', 4, c)
	a.matricular(c)
	d1 = Desempenho(a,d, 5,1)
	d2 = Desempenho(a,e, 6,2)
	d3 = Desempenho(a,f, 7,3)
	a.listar_desempenhos()
	a2 = Aluno('Maria','01/01/01')
	a2.matricular(c)
	a3 = Aluno('Jose','01/01/01')
	a3.matricular(c)
	d4 = Desempenho(a2,d, 4,3)
	d5 = Desempenho(a3,d, 7,0)
	d.listar_alunos()

if __name__ == "__main__":
    testar()


from ast import Store
from service.db_service import get_db_values, write_to_db
from store.user_store import UserStore
from utils import Transactions

def show_transaction_options():
    user = UserStore.get_user()
    while True:
        print("Login Successful")
        print("Transaction Options")
        print("1. ATM Withdrawal")
        print("2. Deposit")
        print("3. Transfer")
        print("4. Show All transactions")
        print("5. Show Top Customers")
        print("0. Quit")
        option = int(input("Kindly enter option: "))
        if option == 1:
            withdraw(user)
        elif option == 2:
            deposit(user)
        elif option == 3:
            transfer(user)
        elif option == 4:
            show_all_transactions(user)
        elif option == 5:
            show_top_customers()
        elif option == 0:
            exit()

def show_top_customers():
    no_of_customers = int(input("Enter how many number of top customers to fetch"))
    db_values = get_db_values()
    customers = db_values["users"]["data"]
    customers = sorted(customers, key=lambda d: d["balance"], reverse=True)[
        0:no_of_customers
    ]
    count = 1
    for customer in customers:
        print("Top Customers")
        print(f"{count} Name: {customer['name']}")
        print("-------------------------------------")
        count += 1

def withdraw(user, amount=None, transaction=True):
    if amount is None:
        amount = int(input("Enter the Amount to withdraw "))

    debit_amount = user["balance"] - amount
    if debit_amount < 1000:
        print("Insuffecient funds")
        return False
    user["balance"] = debit_amount
    print(debit_amount)
    print(user["balance"])

    db_values = get_db_values()
    for _user in db_values["users"]["data"]:
        if _user["customer_id"] == user["customer_id"]:
            _user["balance"] = user["balance"]
    if transaction:
        t = Transactions.WITHDRAW
        db_values = store_transaction(db_values, t.value, user, amount)
    print(db_values["users"]["data"])
    write_to_db(db_values)
    return True

def deposit(user, amount=None, transaction=True):
    if amount is None:
        amount = int(input("Enter the Amount to deposit "))

    credit_amount = user["balance"] + amount
    user["balance"] = credit_amount
    db_values = get_db_values()
    for _user in db_values["users"]["data"]:
        if _user["customer_id"] == user["customer_id"]:
            _user["balance"] = user["balance"]
    if transaction:
        t = Transactions.DEPOSIT
        db_values = store_transaction(db_values, t.value, user, amount)

    write_to_db(db_values)

def transfer(user):
    while True:
        account_number = input("Input Account number to transfer: ")
        if account_number == user["account_number"]:
            print("Cannot transfer to your own account")
            continue
        amount = int(input("Amount to transfer"))
        benefeciary = None
        db_values = get_db_values()
        for _user in db_values["users"]["data"]:
            if _user["account_number"] == account_number:
                benefeciary = _user
                break
        if benefeciary == None:
            print("Benefeciary not found. Try again")
            continue
        break

    can_withdraw = withdraw(user, amount, False)
    if not can_withdraw:
        print("Insuffecient funds")
        return
    deposit(benefeciary, amount, False)
    t = Transactions.TRANSFER
    db_values = get_db_values()
    db_values = store_transaction(db_values, t.value, user, amount)

    write_to_db(db_values)

def store_transaction(values, type, user, amount):
    last_id = values["transactions"]["last_transaction_id"]
    transaction_obj = {
        "id": last_id + 1,
        "type": type,
        "user_id": user["customer_id"],
        "amount": amount,
        "balance": user["balance"],
    }
    values["transactions"]["data"].append(transaction_obj)
    return values

def show_all_transactions(user):
    db_values = get_db_values()
    transactions = []
    for transaction in db_values["transactions"]["data"]:
        if transaction["user_id"] == user["customer_id"]:
            transactions.append(transaction)

    for transaction in transactions:
        print("Transactions")
        print(f"ID: {transaction['id']}")
        print(f"Type: {transaction['type']}")
        print(f"Amount: {transaction['amount']}")
        print(f"Balance: {transaction['balance']}")
        print("-------------------------------------")


from diff_match_patch import diff_match_patch
from django.db.models import (
    AutoField,
    BigAutoField,
    BigIntegerField,
    BinaryField,
    BooleanField,
    CharField,
    DateField,
    DateTimeField,
    DecimalField,
    DurationField,
    EmailField,
    FileField,
    FilePathField,
    FloatField,
    ForeignKey,
    ImageField,
    IntegerField,
    ManyToManyField,
    OneToOneField,
    PositiveIntegerField,
    PositiveSmallIntegerField,
    SmallIntegerField,
    TextField,
    URLField,
    UUIDField,
)

def get_field_diff(old_value, new_value):
    dmp = diff_match_patch()
    diffs = dmp.diff_main(old_value, new_value)
    dmp.diff_cleanupSemantic(diffs)
    return dmp.diff_prettyHtml(diffs)

def format_field_value(field, value):
    if isinstance(field, BooleanField):
        return "No" if not value else "Yes"
    elif isinstance(
        field,
        (
            DecimalField,
            FloatField,
            IntegerField,
            PositiveIntegerField,
            PositiveSmallIntegerField,
            SmallIntegerField,
            BigIntegerField,
            BinaryField,
        ),
    ):
        return str(value)
    elif isinstance(field, DateField):
        return value.strftime("%Y-%m-%d") if value else ""
    elif isinstance(field, (DateTimeField, DurationField)):
        return value.strftime("%Y-%m-%d %H:%M:%S") if value else ""
    elif isinstance(field, (EmailField, URLField, FilePathField, CharField, TextField, UUIDField)):
        return value
    elif isinstance(field, (ImageField, FileField)):
        return value.url if value else ""
    elif isinstance(field, (AutoField, BigAutoField)):
        return str(value)
    elif isinstance(field, (OneToOneField, ForeignKey)):
        return field.related_model.objects.filter(pk=value).first().__str__() if value else ""
    elif isinstance(field, ManyToManyField):
        return list(value.values_list("pk", flat=True)) if value else ""
    else:
        return ""


import bitcoin
import base58
from bitcoin import privtopub, pubkey_to_address
from klefki.crypto.ecdsa.secp256k1 import pubkey, random_privkey
from klefki.bitcoin import gen_key_pair
from klefki.bitcoin.address import gen_address_from_priv
from klefki.bitcoin.public import decode_pubkey, gen_pub_key
from klefki.bitcoin.private import encode_privkey, decode_privkey

def test_priv_encode():
    key = random_privkey()
    encoded = encode_privkey(key)
    ans = bitcoin.encode_privkey(key.value, 'wif_compressed')
    t1 = base58.b58decode(ans)
    t2 = base58.b58decode(encoded)
    assert t1 == t2
    assert encoded == ans

def test_key():
    priv, pub = gen_key_pair()
    assert pub == privtopub(priv)
    priv, pub = gen_key_pair()
    assert pub == privtopub(priv)

    priv, pub = gen_key_pair()
    assert pub == privtopub(priv)

    priv, pub = gen_key_pair()
    assert pub == privtopub(priv)

    priv, pub = gen_key_pair()
    assert pub == privtopub(priv)

def test_addr():
    key = random_privkey()
    pub = gen_pub_key(key)
    addr = gen_address_from_priv(key)
    assert addr == pubkey_to_address(pub)

    key = random_privkey()
    pub = gen_pub_key(key)
    addr = gen_address_from_priv(key)
    assert addr == pubkey_to_address(pub)

def test_decode_pub():
    key = random_privkey()
    ans = pubkey(key)
    ret = decode_pubkey(gen_pub_key(key))
    assert ans == ret

    key = random_privkey()
    ans = pubkey(key)
    ret = decode_pubkey(gen_pub_key(key))
    assert ans == ret

def test_decode_priv():
    key = random_privkey()
    res = decode_privkey(encode_privkey(key))
    assert res == key


from urllib.parse import urlsplit
from urllib.request import urlopen
from django.core.files.base import ContentFile
from django.conf import settings

if settings.DEBUG:
    import ssl
    ssl._create_default_https_context = ssl._create_unverified_context

def save_user_profile(backend, user, response, *args, **kwargs):
    if 'gender' in response:
        if response['gender'] == 'male':
            user.profile.gender = user.profile.MALE
        else:
            user.profile.gender = user.profile.FEMALЕ

    if 'image' in response and 'url' in response['image']:
        r = urlsplit(response['image']['url'])
        img_url = r._replace(query=None).geturl()
        content = None
        if img_url:
            with urlopen(img_url) as f:
                content = ContentFile(f.read())

        if content:
            img_name = user.username + '.jpg'
            user.profile.avatar.save(img_name, content, save=True)