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

"""
Beta MA No.1

信号1 趋势中
信号2 大周期接近均线
信号3 小周期影线和成交量达到要求

"""
import json

from ..okx.AccountAndTradeApi import AccountAndTradeApi
from ...models import AccountInfo, Strategy, PlaceAlgo
import pandas as pd

import time
from ..basetrade.basetrade import BaseTrade

import re

class NewInstId(BaseTrade):
    def __init__(self, api_key=None, secret_key=None, passphrase=None, use_server_time=False, flag='1', **kwargs):
        super().__init__(api_key, secret_key, passphrase, use_server_time, flag, logfile=kwargs.get('logfile', None))
        self.df = None
        self.df_3mins = None
        self.stop_loss = 0
        self.flag = flag
        self.instId = kwargs.get('instId')
        self.slTriggerPx = kwargs.get('slTriggerPx')
        self.tpTriggerPx = kwargs.get('tpTriggerPx')
        self.sz = kwargs.get('sz')

        self.trader = kwargs.get('trader')
        self.accountinfo_obj = kwargs.get('accountinfo')
        self.strategy_obj = self.init_strategy(kwargs.get('strategy_obj'))
        self.all_accountinfo_data_list = None
        self.orderinfo_obj = None
        self.side_type = {"buy": "long", "sell": "short"}
        self.side = "buy"
        self.posSide = 'long'
        self.lever = "1"
        self.last_price = ''
        self.availPos = None
        self.avgpx = None
        self.signal_info_dict = {}

    def init_strategy(self, strategy_obj):
        strategy_obj.instid = self.instId
        strategy_obj.save()
        return strategy_obj

    def start_my_trade(self):
        self.all_accountinfo_data_list = self.set_initialization_account_all_by_newinstid(self.strategy_obj.accountinfo,
                                                                             self.strategy_obj.name,
                                                                             self.strategy_obj.instid,
                                                                             lever="1",
                                                                             )
        if not self.all_accountinfo_data_list:
            self.log.info('no account info data')
            return
        if self.strategy_obj.status < 5:
            self.track_trading_status(1)

        self.ready_order()

        for accountinfo in self.all_accountinfo_data_list:
            obj = accountinfo['obj']
            obj.status = 0
            obj.save()

    def ready_order(self):
        para = {
            "instId": self.instId,
            "tdMode": self.tdMode,
            "ccy": 'USDT',
            'side': "buy",
            'ordType': 'market',
            'px': '',
        }
        place_order_code = False
        place_order_error_code = False
        placc_algo_order_info_list = []
        for accountinfo in self.all_accountinfo_data_list:
            orderinfo_dict = {}
            obj = accountinfo['obj']
            obj_api = accountinfo['obj_api']
            orderinfo_dict['lever'] = self.lever
            para['sz'] = self.sz
            orderinfo_dict.update(para)
            while True:
                result = obj_api.tradeAPI.place_order(**para)
                ordId, sCode, sMsg = self.check_order_result_data(result, 'ordId')
                print(sMsg)
                if "Instrument ID doesn't exist" != sMsg:
                    break

            if sCode == "0":
                accountinfo['status'] = 2
                place_order_code = True
                # 获取持仓信息
                # self.get_order_details(self.instId, ordId)
                self.has_order = self.get_positions(instType='MARGIN')
                self.order_times += 1
                print('%s 开仓成功！！！！！！' % obj.account_text)
                self.log.info('%s 开仓成功！！！！！！' % obj.account_text)
                # self.track_trading_status(5)

                if self.order_lst:
                    self.avgpx = float(self.order_lst[0].get('avgPx'))
                    self.availPos = float(self.order_lst[0].get('availPos'))    # 可平仓数量，
                    orderinfo_dict['order_ctime'] = self.timestamp_to_date(self.order_lst[0].get('cTime'))
                    orderinfo_dict['order_utime'] = self.timestamp_to_date(self.order_lst[0].get('uTime'))
                else:
                    result = self.marketAPI.get_ticker(self.instId)
                    for data in result.get('data'):
                        self.last_price = data.get("last")
                    self.avgpx = self.last_price

                orderinfo_dict['ordId'] = ordId
                orderinfo_dict['avgPx'] = self.avgpx

                # 设置止损止盈
                algo_para = self.set_place_algo_order_oco(obj_api, self.sz)
                algo_para['orderid'] = ordId
                algo_para['accountinfo_id'] = obj.id
                algo_para['instid'] = self.instId
                placc_algo_order_info_list.append(algo_para)
                orderinfo_dict.update(algo_para)
                orderinfo_dict['posside'] = self.posSide
                orderinfo_dict['side'] = self.side
                self.has_order = True
            else:
                place_order_error_code = True
                # self.track_trading_status(-1)
                msg = '%s 账户异常！！！开仓失败！！！！！！' % obj.account_text
                accountinfo['status'] = -1
                accountinfo['msg'] = msg
                self.log.error(msg)
                self.has_order = False
            accountinfo['orderinfo'] = orderinfo_dict

        if place_order_code:
            self.has_order = True
            self.track_trading_status(5)
            # 发消息提示
            # self.send_msg_to_me(self.trader)
        if place_order_error_code:
            self.track_trading_status(6)

        # 保存订单信息
        for accountinfo in self.all_accountinfo_data_list:
            orderinfo_dict = accountinfo['orderinfo']
            orderinfo_dict['strategyid'] = self.strategy_obj.id
            accountinfo_obj = accountinfo['obj']

            # 保存订单信
            orderinfo_obj = self.set_trading_orderinfo(accountinfo_obj, **orderinfo_dict)
            accountinfo['orderinfo_obj'] = orderinfo_obj

            # 保存账户状态
            accountinfo_obj.status = accountinfo['status']
            accountinfo_obj.save()

        # 保存策略信息
        self.signal_info_dict['posSide'] = self.posSide
        self.signal_info_dict['instId'] = self.instId
        self.signal_info_dict['side'] = self.side
        self.signal_info_dict['avgPx'] = self.avgpx
        self.signal_info_dict['stop_loss_price'] = self.slTriggerPx
        self.set_strategy_info(self.signal_info_dict)

        # 保存委托订单信息
        for item in placc_algo_order_info_list:
            new_dict = {}
            for i, j in item.items():
                # 把key转小写
                new_dict[i.lower()] = j
            algo = PlaceAlgo(**new_dict, strategyid=self.strategy_obj.id)
            try:
                algo.save()
            except Exception as e:
                print(e)

    def track_trading_status(self, status=0, update_status=True):
        strategy_obj = Strategy.objects.get(pk=self.strategy_obj.id)
        if strategy_obj.status in (0, -2):
            self.log.info('已强行停止策略')
            raise Exception('已强行停止策略')
        if update_status:
            self.strategy_obj.status = status
            self.strategy_obj.save()
            self.log.info('更新运行状态--%s--' % status)

    def set_strategy_info(self, data):
        signalinfo = self.strategy_obj.signalinfo
        if signalinfo:
            try:
                signalinfo = json.loads(signalinfo)
            except Exception as e:
                pass
                # self.log.info(e)
                # self.log.info(signalinfo)
            if isinstance(signalinfo, list):
                signalinfo.append(data)
            else:
                signalinfo = [data]
        else:
            signalinfo = [data]
        self.strategy_obj.signalinfo = signalinfo
        self.strategy_obj.save()

    def set_place_algo_order_oco(self, obj_api, sz):
        side = 'sell'
        self.tpTriggerPx = float(self.avgpx) * float(self.tpTriggerPx) if self.tpTriggerPx else float(self.avgpx) * 5
        self.slTriggerPx = float(self.avgpx) * float(self.slTriggerPx) if self.slTriggerPx else float(self.avgpx) * 0.7
        price_para = {
            "tpTriggerPx": self.tpTriggerPx,
            "tpOrdPx": "-1",
            "slTriggerPx": self.slTriggerPx,
            "slOrdPx": "-1"
        }
        try:
            result = obj_api.tradeAPI.place_algo_order(self.instId, self.tdMode, side, ordType=self.ordType,
                                                       sz=self.availPos, **price_para, ccy='USDT',
                                                       tpTriggerPxType='last', slTriggerPxType='last')
        except Exception as e:
            self.log.error("委托单错误")
            self.log.error(e)
            return
        algoId, sCode, msg = self.check_order_result_data(result, "algoId")
        if sCode == "0":
            # 事件执行结果的code，0代表成功
            status = 1
            self.log.info("止损止盈设置成功 市价委托")
            try:
                result = obj_api.tradeAPI.order_algos_list(ordType=self.ordType, algoId=algoId, instType='SWAP')
                price_para['algo_ctime'] = self.timestamp_to_date(result.get('data')[0].get('cTime'))
            except Exception as e:
                self.log.error(e)
        else:
            # 可能是止损设置错误
            status = -1
            msg = "止损止盈设置错误，，，%s, 止损：%s, 止盈：%s, 现价：%s" % (
                msg, self.slTriggerPx, self.tpTriggerPx, self.last_price)
            self.log.error(msg)

        price_para['algoid'] = algoId
        price_para['posside'] = self.posSide
        price_para['side'] = side
        price_para['sz'] = sz
        price_para['scode'] = sCode
        price_para['smsg'] = msg
        price_para['status'] = status
        return price_para

    def set_initialization_account_all_by_newinstid(self, all_accountinfo, strategy_name, instid, interval=0.2, lever='50',
                                       mgnMode='cross'):
        # 初始化状态， 设置倍数， 账户状态。
        all_accountinfo_obj = AccountInfo.objects.filter(pk__in=all_accountinfo)
        all_accountinfo_data_list = []
        for obj in all_accountinfo_obj:
            if interval:
                time.sleep(interval)
            accountinfo_data = {}
            try:
                obj_api = AccountAndTradeApi(obj.api_key, obj.secret_key, obj.passphrase, False, obj.flag)
                # try:
                #     result = self.accountAPI.set_leverage(instId=self.instId, lever=lever, mgnMode=mgnMode)
                #     result = self.accountAPI.get_position_mode('long_short_mode')
                # except Exception as e:
                #     print(e)
                #     print('初始化账户 error')
                balance = obj_api.get_my_balance('availEq')
                obj.balance = float(balance)
                if obj.init_balance == -1:
                    obj.init_balance = float(balance)
                obj.strategy_name = strategy_name
                obj.status = 1
                accountinfo_data['id'] = obj.id
                accountinfo_data['name'] = obj.account_text
                accountinfo_data['balance'] = balance
                accountinfo_data['obj'] = obj
                accountinfo_data['obj_api'] = obj_api
                all_accountinfo_data_list.append(accountinfo_data)
            except Exception as e:
                obj.status = -1
                self.log.error('set_initialization_account_all error')
                self.log.error(e)
            obj.save()
        return all_accountinfo_data_list


t = input()
s = input()
res = False;
for i in range(len(t)):
    if t[i] != s[0] and t[i] != '?':
        continue
    ss = True;
    j = 1
    k = i + 1
    while j < len(s):
        if k != len(t) and (t[k] == s[j] or t[k] == '?'):
            j+=1
            k+=1
            continue
        ss = False
        break
    if ss == False:
        continue
    res = True
    break
if res:
    print("YES")
else:
    print("NO")


'''Напишите программу, которая определит позицию
второго вхождения строки в списке либо сообщит, что её нет.
Пример:
список: ["qwe", "asd", "zxc", "qwe", "ertqwe"], ищем: "qwe", ответ: 3
список: ["йцу", "фыв", "ячс", "цук", "йцукен", "йцу"], ищем: "йцу", ответ: 5
список: ["йцу", "фыв", "ячс", "цук", "йцукен"], ищем: "йцу", ответ: -1
список: ["123", "234", 123, "567"], ищем: "123", ответ: -1
список: [], ищем: "123", ответ: -1 '''

list = ["qwe", "asd", "abs", "qwe", "ertqwe"]
text = input("Введите элемент списка на проверку ")
count = list.count(text)
try:
    indexFirst = list.index(text)
except:
    print("Данный элемент не находится в списке")
indexSecond = 0
for i in list:
    if text in list:
        if count >= 2:
            indexSecond = list.index(text,indexFirst+1,len(list)-1)
            print(f"Индекс второго вхождения равен {indexSecond}")
            break
        else:
            print('-1')
            break
    else:
        print('-1')
        break


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

import discord
from discord import Forbidden
#from discord.ext import commands
import random
from botkey import Key
import sys
import logging
import time
from discord import HTTPException
from discord import utils
from discord import DMChannel
from recruitDb import DbApi

logging.basicConfig(level=logging.INFO)

client = discord.Client()

prefix = Key().prefix()

db = DbApi()

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

@client.event
async def on_message(message):

    # we do not want the bot to reply to itself
    if message.author == client.user or 'recruitment' not in message.channel.name:
        return

    if message.content.startswith(prefix+'add'):
        await addTerm(message)

    if message.content.startswith(prefix+'remove'):
        await removeTerm(message)

    if message.content.startswith(prefix+'list'):
        await list(message)

async def addTerm(message):
    db.addTerm(message.content[4+len(prefix):])

async def removeTerm(message):
    db.removeTerm(message.content[7+len(prefix):])

async def list(message):
    msg = db.listTermsString()
    await message.channel.send('```List of terms currently being searched for:\n{0}```'.format(msg))

client.run(Key().value())


'''
client.py
@author Jason Lin

Client for simplified Google File System implementation. Handles creating, reading,
writing, and deleting files.
'''
from xmlrpc.client import ServerProxy

import random
import time

class Client():
    def __init__(self, chunk_size=64000, master_url='http://localhost:9000', \
            cache_timeout=60, debug=False):
        random.seed(0)
        self.debug = debug
        self.chunk_size = chunk_size
        self.master_proxy = ServerProxy(master_url)
        # read_cache: (filename,chunk_idx) -> [chunk_id,[replica urls],time]
        # used for caching the replica urls of a given file and chunk index when reading
        self.read_cache = {}
        self.read_cache_timeout_secs = cache_timeout
        # primary_cache: (filename,chunk_idx) -> [chunk_id,primary,[replica urls]]
        # used for caching the primary of a given file and chunk index when writing
        self.primary_cache = {}

    '''
    create:
    Tell the master to create a file in GFS with the given filename.

    @param filename(string): desired filename to create
    @return string: result message
    '''
    def create(self, filename):
        return self.master_proxy.create(filename)

    '''
    delete:
    Delete cached entries for filename, then tell the master to delete the file
    with the given filename from GFS.

    @param filename(string): desired filename to delete
    @return string: result message
    '''
    def delete(self, filename):
        to_delete = []
        for f, chunk_idx in self.primary_cache:
            if f == filename:
                to_delete.append((f, chunk_idx))
        for tup in to_delete:
            del self.primary_cache[tup]
        return self.master_proxy.delete(filename)

    '''
    read:
    Read amount bytes from thespecified filename, starting at a given offset.
    Splits the amount into different chunks if the read overlaps chunks.

    @param filename(string): desired filename to read
    @param byte_offset(int): offset within file to start reading from
    @param amount(int): number of bytes to read starting from byte_offset
    @return string: bytes read from filename, or 'file not found'
    '''
    def read(self, filename, byte_offset, amount):
        chunk_idx = byte_offset // self.chunk_size
        chunk_offset = byte_offset % self.chunk_size

        total_to_read = amount
        amount_to_read_in_chunk = min(self.chunk_size - chunk_offset, total_to_read)
        s = ''
        while total_to_read > 0:
            # locate replica urls of chunk
            should_contact_master = True
            if (filename, chunk_idx) in self.read_cache:
                res = self.read_cache[(filename, chunk_idx)]
                original_cache_time = res[2]
                if time.time() <= original_cache_time + self.read_cache_timeout_secs:
                    #refresh original cache time
                    self.read_cache[(filename, chunk_idx)][2] = time.time()
                    should_contact_master = False

            if should_contact_master:
                res = self.master_proxy.read(filename, chunk_idx)
                if res == 'file not found' or res == 'requested chunk idx out of range':
                    return res
                res.append(time.time())
                self.read_cache[(filename,chunk_idx)] = res
            chunk_id = res[0]
            replica_urls = res[1]

            # pick random replica to read from
            while len(replica_urls) > 0:
                replica_url = random.choice(replica_urls)
                chunkserver_proxy = ServerProxy(replica_url)
                try:
                    read_res = chunkserver_proxy.read( \
                            chunk_id, chunk_offset, amount_to_read_in_chunk)
                    if read_res == None:
                        if self.debug:
                            print('invalid checksum found in replica, trying another')
                        replica_urls.remove(replica_url)
                        continue
                    s += read_res
                    break
                except Exception as e:
                    if self.debug:
                        print('exception reading from replica:', e)
                    replica_urls.remove(replica_url)
            if len(replica_urls) == 0:
                return 'no replicas remaining for chunk'

            total_to_read -= amount_to_read_in_chunk
            amount_to_read_in_chunk = min(self.chunk_size, total_to_read)
            chunk_idx += 1
            chunk_offset = 0
        return s

    '''
    write:
    Writes the given data to the desired file. The client specifies the byte_offset,
    which must be the last byte written so far in the file.
    Splits writes that overlap chunks into multiple writes.

    @param filename(string): desired filename to write
    @param data(string): data to write to file
    @param byte_offset(int): offset within file that corresponds to the last byte written
    @return int: offset within file that the data was actually written to.
    This may differ from the provided byte_offset when there are multiple concurrent writers
    to the same file.
    '''
    def write(self, filename, data, byte_offset):
        chunk_idx = byte_offset // self.chunk_size
        first_chunk_idx = chunk_idx
        chunk_offset = byte_offset % self.chunk_size

        data_idx = 0
        total_to_write = len(data)
        amount_to_write_in_chunk = min(self.chunk_size - chunk_offset, total_to_write)

        backoff_secs = 1
        offset_written_at = None
        while total_to_write > 0:
            if chunk_idx != first_chunk_idx:
                # if this isn't the first chunk, create another chunk
                self.create(filename)
            data_piece = data[data_idx:data_idx+amount_to_write_in_chunk]
            res = self.write_helper(filename, data_piece, chunk_idx)
            if type(res) != int:
                if res == 'file not found':
                    return res
                # error, wait for exponential backoff and retry
                print(res, 'for ' + filename + ', backing off and retrying in ' \
                        + str(backoff_secs) + ' seconds')
                time.sleep(backoff_secs)
                backoff_secs *= 2
            else:
                if chunk_idx == first_chunk_idx:
                    offset_written_at = res
                chunk_idx += 1
                data_idx += amount_to_write_in_chunk
                total_to_write -= amount_to_write_in_chunk
                amount_to_write_in_chunk = min(self.chunk_size, total_to_write)
        return offset_written_at

    '''
    write_helper:
    Helper method to handle sending data to replicas as well as actually applying the
    mutations to those replicas. Handles lease management and requesting new primaries
    if the current primary is down or the lease has expired.

    @param filename(string): desired filename to write
    @param data(string): data to write to file
    @param chunk_idx(int): chunk index of file to write to
    @return int: offset within file that the data was actually written to.
    '''
    def write_helper(self, filename, data, chunk_idx):
        # locate primary and replica urls
        if (filename, chunk_idx) in self.primary_cache:
            res = self.primary_cache[(filename,chunk_idx)]
            if self.debug:
                print('using from primary cache:', res)
        else:
            res = self.master_proxy.get_primary(filename, chunk_idx, False)
            if res == 'file not found':
                return res
            self.primary_cache[(filename,chunk_idx)] = res
            if self.debug:
                print('asked master for primary:', res)
        chunk_id = res[0]
        primary = res[1]
        replica_urls = res[2]

        # send data to first replica, which sends data to all other replicas
        while len(replica_urls) > 0:
            replica_url = replica_urls[0]
            chunkserver_proxy = ServerProxy(replica_url)
            try:
                send_res = chunkserver_proxy.send_data(chunk_id, data, 1, replica_urls)
            except:
                if self.debug:
                    print('exception when sending data to', replica_url)
                send_res = 'chunkserver failure_' + replica_url
            # if any replica failed, reselect primary and replicas
            if send_res != 'success':
                if self.debug:
                    print('replica failed when sending data, asking for primary again')
                    print('res=', send_res)
                if send_res == 'timed out':
                    time.sleep(2)
                    continue
                failed_url = send_res[send_res.rfind('_')+1:]
                self.master_proxy.remove_chunkserver(failed_url)
                new_lease_res = self.master_proxy.get_primary(filename, chunk_idx, True)
                self.primary_cache[(filename, chunk_idx)] = new_lease_res
                chunk_id = new_lease_res[0]
                primary = new_lease_res[1]
                replica_urls = new_lease_res[2]
            else:
                break
        if len(replica_urls) == 0:
            return 'no remaining replicas'

        # tell the primary to apply mutations to all secondary replicas
        while True:
            primary_proxy = ServerProxy(primary)
            secondary_urls = replica_urls[:]
            secondary_urls.remove(primary)
            # to simplify state machine, assume that primary doesn't fail between selecting
            # it a few lines above and here
            mutation_res = primary_proxy.apply_mutations( \
                    chunk_id, secondary_urls, primary, [])

            # if lease expired, reselect primary and replicas
            if mutation_res == 'not primary':
                if self.debug:
                    print('lease expired, asking for primary again')
                new_lease_res = self.master_proxy.get_primary(filename, chunk_idx, True)
                old_urls = replica_urls[:]
                self.primary_cache[(filename, chunk_idx)] = new_lease_res
                chunk_id = new_lease_res[0]
                primary = new_lease_res[1]
                replica_urls = new_lease_res[2]

                # resend data if the replicas changed
                send_again_urls = [url for url in replica_urls if url not in old_urls]
                if len(send_again_urls) > 0:
                    if self.debug:
                        print('sending data to new replicas')
                    resend_proxy = ServerProxy(send_again_urls[0])
                    resend_proxy.send_data(chunk_id, data, 1, send_again_urls)
                continue

            # find offset of written data in mutation_res
            offset_within_chunk = mutation_res[data]
            written_offset = (chunk_idx * self.chunk_size) + offset_within_chunk
            return written_offset


#https://leetcode.com/problems/count-square-submatrices-with-all-ones/
#Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
#
#Example 1:
#Input: matrix =
#[
#  [0,1,1,1],
#  [1,1,1,1],
#  [0,1,1,1]
#]
#Output: 15
#Explanation:
#There are 10 squares of side 1.
#There are 4 squares of side 2.
#There is  1 square of side 3.
#Total number of squares = 10 + 4 + 1 = 15.
#Example 2:
#Input: matrix =
#[
#  [1,0,1],
#  [1,1,0],
#  [1,1,0]
#]
#Output: 7
#Explanation:
#There are 6 squares of side 1.
#There is 1 square of side 2.
#Total number of squares = 6 + 1 = 7.
#
#Constraints:
#	1 <= arr.length <= 300
#	1 <= arr[0].length <= 300
#	0 <= arr[i][j] <= 1
class Solution(object):
    def countSquares(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: int
        """
        # Approach 1: Dynamic Programming
        # Time Complexity: O(N^2)
        # Space Complexity: O(N^2)
        # Runtime: 676 ms, faster than 84.85% of Python online submissions for Count Square Submatrices with All Ones.
        # Memory Usage: 16.4 MB, less than 100.00% of Python online submissions for Count Square Submatrices with All Ones.
        ans = 0
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                if i and j and matrix[i][j]:
                    matrix[i][j] = min(matrix[i - 1][j], matrix[i][j - 1], matrix[i - 1][j - 1]) + 1
                ans += matrix[i][j]
        return ans


import pytest
import numpy as np

from gym.vector.tests.utils import make_env

from gym.vector.async_vector_env import AsyncVectorEnv
from gym.vector.sync_vector_env import SyncVectorEnv

@pytest.mark.parametrize('shared_memory', [True, False])
def test_vector_env_equal(shared_memory):
    env_fns = [make_env('CubeCrash-v0', i) for i in range(4)]
    num_steps = 100
    try:
        async_env = AsyncVectorEnv(env_fns, shared_memory=shared_memory)
        sync_env = SyncVectorEnv(env_fns)

        async_env.seed(0)
        sync_env.seed(0)

        assert async_env.num_envs == sync_env.num_envs
        assert async_env.observation_space == sync_env.observation_space
        assert async_env.single_observation_space == sync_env.single_observation_space
        assert async_env.action_space == sync_env.action_space
        assert async_env.single_action_space == sync_env.single_action_space

        async_observations = async_env.reset()
        sync_observations = sync_env.reset()
        assert np.all(async_observations == sync_observations)

        for _ in range(num_steps):
            actions = async_env.action_space.sample()
            assert actions in sync_env.action_space

            async_observations, async_rewards, async_dones, _ = async_env.step(actions)
            sync_observations, sync_rewards, sync_dones, _ = sync_env.step(actions)

            assert np.all(async_observations == sync_observations)
            assert np.all(async_rewards == sync_rewards)
            assert np.all(async_dones == sync_dones)

    finally:
        async_env.close()
        sync_env.close()


# August 18, 2020
# Edit Distance: find the minimum # of ops required to convert word1 to word2 (insert, substitute, delete)

# Bottom up approach:
# Levenshtein Distance Algorithm
# - Create 2d dp array len(word1)+1 x len(word2)+1
# - Fill the elements in the 1st row and column with their own respective index
# - Iterate through remaining rows and cols, and if chars don't match in the two words take the min of the up, left, and
#   up-left cell + 1
# - if the chars match, take the copy the up-left cell into the current cell
# - return the bottom right cell value

# If converting from row word (vertical) to col word (horzontal)
#   diagonal = substitute
#   vertical = delete from row word
#   horizontal = insert into row word
# Else if converting from col word (horizontal) to row word (vertical)
#   diagonal = substitute
#   vertical = insert into col word
#   horizontal = delete into col word
def minDistance(self, word1: str, word2: str) -> int:
    # initialize 2d dp array
    dp2d = []
    for row in range(len(word2) + 1):
        dp2d.append([0] * (len(word1) + 1))

    for col in range(1, len(word1) + 1):
        dp2d[0][col] = col

    for row in range(1, len(word2) + 1):
        dp2d[row][0] = row

    for row in range(1, len(word2) + 1):
        for col in range(1, len(word1) + 1):
            if word1[col-1] != word2[row-1]:
                dp2d[row][col] = min(dp2d[row-1][col], dp2d[row-1][col-1], dp2d[row][col-1]) + 1
            else:
                dp2d[row][col] = dp2d[row-1][col-1]

    return dp2d[-1][-1]


import torch
from .mode import Mode

def err2gt(err, mode:Mode=Mode.JOINTS):
  gt = torch.zeros(mode.get_num_layers(), dtype=torch.float32)
  if mode == Mode.JOINTS:
    for (i, e) in enumerate(err):
      gt[int(i*4 + e)] = 1
  else:
    for i in range(0, len(gt), 2):
      if err[i//2] == 0:
        gt[i] = 1
      else:
        gt[i+1] = 1

  return gt

def errs2gts(errs, mode:Mode=Mode.JOINTS):
  num_error_labels = mode.get_num_error_label()

  gts = torch.zeros(len(errs), len(errs[0]) * num_error_labels, dtype=torch.float32)
  for (i, err) in enumerate(errs):
    gts[i] = err2gt(err, mode)
  return gts

def gt2err(gt, mode:Mode=Mode.JOINTS):
  num_error_labels = mode.get_num_error_label()

  err = torch.zeros(len(gt) // num_error_labels, dtype=torch.float32)
  confidence = torch.zeros(len(gt) // num_error_labels, dtype=torch.float32)

  for i in range(0, len(gt), num_error_labels):
    e = gt[i:i + num_error_labels]
    probs = torch.nn.functional.softmax(e, dim=0)
    conf, classes = torch.max(probs, 0)

    confidence[i // num_error_labels] = conf
    err[i // num_error_labels] = classes

  return err, confidence

def gts2errs(gts, mode:Mode=Mode.JOINTS):
  num_error_labels = mode.get_num_error_label()

  errs = torch.zeros(len(gts), len(gts[0]) // num_error_labels, dtype=torch.float32)
  confidences = torch.zeros(len(gts), len(gts[0]) // num_error_labels, dtype=torch.float32)
  for (i, gt) in enumerate(gts):
    errs[i], confidences[i] = gt2err(gt, mode)

  return errs, confidences


import unittest

from datastructures_and_algorithms.stack import Stack
from datastructures_and_algorithms.exceptions.StackEmptyException import StackEmptyException

class TestStack(unittest.TestCase):

    def test_can_push_and_pop_in_right_order(self):

        my_stack = Stack()
        my_stack.push(1)
        my_stack.push(2)

        pop1 = my_stack.pop()
        pop2 = my_stack.pop()

        self.assertEqual(2, pop1, "first pop did not have the expected value")
        self.assertEqual(1, pop2, "second pop did not have the expected value")

    def test_can_peek_in_right_order(self):

        my_stack = Stack()
        my_stack.push(1)
        my_stack.push(2)

        peek1 = my_stack.peek()
        peek2 = my_stack.peek()

        self.assertEqual(2, peek1, "first peek did not have the expected value")
        self.assertEqual(2, peek2, "second peek did not have the expected value")

    def test_len_correctly_counts(self):

        my_stack = Stack()
        my_stack.push(1)
        my_stack.push(2)
        my_stack.push(3)
        my_stack.push(4)

        length = len(my_stack)

        self.assertEqual(4, length, "The length count works")

    def test_can_count_empty_stack(self):

        my_empty_stack = Stack()
        empty_len = len(my_empty_stack)
        self.assertEqual(0, empty_len, "The length count is all messed (empty test)")

    def test_will_raise_exception_on_empty_stack(self):

        empty = Stack()
        self.assertRaises(StackEmptyException, empty.pop)
        self.assertRaises(StackEmptyException, empty.peek)

    def test_reverse_function(self):

        my_stack = Stack()
        my_stack.push(1)
        my_stack.push(2)
        my_stack.push(3)

        reversed(my_stack)

        pop1 = my_stack.pop()
        pop2 = my_stack.pop()
        pop3 = my_stack.pop()

        self.assertEqual(1, pop1, "The Reverse Function is broken")
        self.assertEqual(2, pop2, "The Reverse Function is broken")
        self.assertEqual(3, pop3, "The Reverse Function is broken")


trip_price = float(input())
puzzles_number = int(input())
talking_dolls_number = int(input())
teddy_bears_number = int(input())
minions_number = int(input())
trucks_number = int(input())

puzzle_price = 2.60
talking_doll_price = 3
teddy_bear_price = 4.10
minion_price = 8.20
truck_price = 2
amount = puzzles_number * puzzle_price + talking_dolls_number * talking_doll_price \
               + teddy_bears_number * teddy_bear_price + minions_number * minion_price + \
               trucks_number * truck_price
number_of_toys = puzzles_number + talking_dolls_number + teddy_bears_number + minions_number + trucks_number

if number_of_toys >= 50:
    discount = amount * 25 / 100
    amount = amount - discount

rent = amount * 10 / 100
profit = amount - rent

if profit >= trip_price:
    print(f"Yes! {profit - trip_price:.2f} lv left.")
else:
    print(f"Not enough money! {trip_price - profit:.2f} lv needed.")

Programming basics with Python/02. Conditional statements/Exercises/toys_store.py


# coding=utf-8
# 代码文件：chapter20/ch20.6.1.py

import threading
import time

# 创建条件变量对象
condition = threading.Condition()

class Stack:
    def __init__(self):
        # 堆栈指针初始值为0
        self.pointer = 0
        # 堆栈有5个数字的空间
        self.data = [-1, -1, -1, -1, -1]

    # 压栈方法
    def push(self, c):
        global condition
        condition.acquire()
        # 堆栈已满，不能压栈
        while self.pointer == len(self.data):
            # 等待其它线程把数据出栈
            condition.wait()
        # 通知其他线程把数据出栈
        condition.notify()
        # 数据压栈
        self.data[self.pointer] = c
        # 指针向上移动
        self.pointer += 1
        condition.release()

    # 出栈方法
    def pop(self):
        global condition
        condition.acquire()
        # 堆栈无数据，不能出栈
        while self.pointer == 0:
            # 等待其他线程把数据压栈
            condition.wait()
        # 通知其他线程压栈
        condition.notify()
        # 指针向下移动
        self.pointer -= 1
        data = self.data[self.pointer]
        condition.release()
        # 数据出栈
        return data

# 创建堆栈Stack对象
stack = Stack()

# 生产者线程体函数
def producer_thread_body():
    global stack  # 声明为全局变量
    # 产生10个数字
    for i in range(0, 10):
        # 把数字压栈
        stack.push(i)
        # 打印数字
        print('生产：{0}'.format(i))
        # 每产生一个数字线程就睡眠
        time.sleep(1)

# 消费者线程体函数
def consumer_thread_body():
    global stack  # 声明为全局变量
    # 从堆栈中读取数字
    for i in range(0, 10):
        # 从堆栈中读取数字
        x = stack.pop()
        # 打印数字
        print('消费：{0}'.format(x))
        # 每消费一个数字线程就睡眠
        time.sleep(1)

# 主函数
def main():
    # 创建生产者线程对象producer
    producer = threading.Thread(target=producer_thread_body)
    # 启动生产者线程
    producer.start()
    # 创建消费者线程对象consumer
    consumer = threading.Thread(target=consumer_thread_body)
    # 启动消费者线程
    consumer.start()

if __name__ == '__main__':
    main()


from config import CONFIG
from config import TOKEN, MODE, HEROKU_APP_NAME, PORT
from dialog_manager import LANGUAGES, MAIN_MENU, ANSWERS, SECOND_LEVEL

import logging

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, \
    CallbackQueryHandler
from telegram import ParseMode, InlineKeyboardButton, InlineKeyboardMarkup

logging.basicConfig(format=('%(asctime)s - %(name)s - '
                            '%(levelname)s - %(message)s'),
                    level=logging.INFO)
logger = logging.getLogger()

language = {}

def add_handlers(updater):
    """
    This function adds handlers for start and message_processing functions.
    :param updater: an Updater object
    :return: None
    """
    updater.dispatcher.add_handler(CommandHandler('start', start))
    updater.dispatcher.add_handler(CommandHandler('help', help))
    updater.dispatcher.add_handler(MessageHandler(Filters.all,
                                                  message_processing))
    updater.dispatcher.add_handler(CallbackQueryHandler(button))

def start(update, context):
    """
    Function sends reply every time the Bot receives message with
    /start command.
    :return: None
    """

    keyboard = []
    for item in LANGUAGES:
        keyboard.append([InlineKeyboardButton(item, callback_data=item)])

    reply_markup = InlineKeyboardMarkup(keyboard)

    start_text = (ANSWERS['greeting'] + '\n\n' +
                  ANSWERS['ru_greeting'])
    context.bot.send_message(parse_mode=ParseMode.MARKDOWN,
                             chat_id=update.effective_chat.id,
                             text=start_text, reply_markup=reply_markup)

def button(update, context):
    query = update.callback_query

    logger.info(f'Query {query.data} for '
                f'{update.effective_user.name} at '
                f'{update.effective_message.date}')

    keyboard = []

    if query.data in LANGUAGES:
        language[update.effective_user.name] = query.data
        for item in LANGUAGES[query.data]:
            keyboard.append([InlineKeyboardButton(item,
                                                  callback_data=item)])

    elif query.data in MAIN_MENU:
        for item in MAIN_MENU[query.data]:
            keyboard.append([InlineKeyboardButton(item,
                                                  callback_data=item)])

    elif query.data in SECOND_LEVEL:
        for item in SECOND_LEVEL[query.data]:
            keyboard.append([InlineKeyboardButton(item,
                                                  callback_data=item[:5])])

    elif query.data in ANSWERS:
        if language[update.effective_user.name] == 'English':
            back_text = 'Back to main menu'
        else:
            back_text = 'Назад в главное меню'

        keyboard = [[InlineKeyboardButton(back_text, callback_data=
        language[update.effective_user.name])]]
        reply_markup = InlineKeyboardMarkup(keyboard)

        context.bot.send_message(parse_mode=ParseMode.MARKDOWN,
                                 chat_id=update.effective_chat.id,
                                 text=ANSWERS[query.data],
                                 reply_markup=reply_markup,
                                 disable_web_page_preview=True)
        return 1

    else:
        if language[update.effective_user.name] == 'Русский':
            error_text = ANSWERS['ru_default']
        else:
            error_text = ANSWERS['default']

        context.bot.send_message(parse_mode=ParseMode.MARKDOWN,
                                 chat_id=update.effective_chat.id,
                                 text=error_text)
        return 1

    reply_markup = InlineKeyboardMarkup(keyboard)

    if language[update.effective_user.name] == 'Русский':
        intro_text = 'Выберите вопрос:'
    else:
        intro_text = 'Choose the question:'

    context.bot.send_message(parse_mode=ParseMode.MARKDOWN,
                             chat_id=update.effective_chat.id,
                             reply_markup=reply_markup,
                             text=intro_text)

def help(update, context):
    if language[update.effective_user.name] == 'Русский':
        help_text = 'Напиши /start для входа в меню.'
    else:
        help_text = 'Use /start command for FAQ.'
    context.bot.send_message(parse_mode=ParseMode.MARKDOWN,
                             chat_id=update.effective_chat.id,
                             text=help_text)

def message_processing(update, context):
    """
    Function saves voice messages in wav format with simple rate 16MHz and
    photos if a face is detected there. All path store in database `bot`.
    :return: None
    """

    logger.info(f'Waiting for message_processing function for '
                f'{update.effective_user.name} at '
                f'{update.effective_message.date}')

    if language == 'Русский':
        answer_text = ANSWERS['ru_default']
    else:
        answer_text = ANSWERS['default']

    context.bot.send_message(parse_mode=ParseMode.MARKDOWN,
                             chat_id=update.effective_chat.id,
                             text=answer_text)

    logger.info(f'Answer ready for {update.effective_user.name} '
                f'at {update.effective_message.date}')

if MODE == 'prod_heroku':
    def run():
        updater = Updater(TOKEN, use_context=True)
        updater.start_webhook(listen='0.0.0.0',
                              port=PORT,
                              url_path=TOKEN)
        add_handlers(updater)
        updater.bot.set_webhook(
            f'https://{HEROKU_APP_NAME}.herokuapp.com/{TOKEN}')

elif MODE == 'prod':
    def run():
        REQUEST_KWARGS = CONFIG['DEFAULT_REQUEST_KWARGS']
        updater = Updater(TOKEN,
                          request_kwargs=REQUEST_KWARGS,
                          use_context=True)
        add_handlers(updater)
        updater.start_polling()

elif MODE == 'dev':
    def run():
        # experiments here
        REQUEST_KWARGS = CONFIG['DEFAULT_REQUEST_KWARGS']
        updater = Updater(TOKEN,
                          request_kwargs=REQUEST_KWARGS,
                          use_context=True)
        add_handlers(updater)
        updater.start_polling()
else:
    logger.error('No MODE specified')
    exit(1)

if __name__ == '__main__':
    logger.info('Bot starting')
    run()


def play(n, sourse, receiver, storage):
    """
    The function of moving n disks in the Tower of Hanoi puzzle.
    Function arguments:
    The first argument n is an integer, the number of disks in the pyramid.
    source, receiver, storage - any type.
    The second argument is sourse, the rod from which we shift the disks.
    The third argument is the receiver, the rod on which we shift the disks.
    The fourth argument is storage, the pivot on which we shift n-1 disks
    for temporary storage in the process of general work.
    """
    assert n > -1, "Number of disks 'n' must be greater -1"
    if n <= 0:
        return
    play(n-1, sourse, storage, receiver)
    print("Диск ", n, " : ", sourse, " --> ", receiver)
    play(n-1, storage, receiver, sourse)

play(10, 'a', 'b', 'c')


from tkinter import *
from tkinter import messagebox

root = Tk()

def box():
    response = messagebox.askquestion('Do you really agree?', 'Really, REALLY AGREE?')
    Label(root, text=response)
    if response == "yes":
        m = messagebox.showinfo('FINE', 'FINE MAN')
        Label(root, text=m)
    while response == "no":
        r = messagebox.askquestion('Agreement', 'But now?')
        Label(root, text=r)
        if r == "yes":
            m = messagebox.showinfo('FINE', 'FINE MAN')
            Label(root, text=m)
            break

btn = Button(root, text='If agree CLICK!', command=box).pack()

root.mainloop()


import copy
import numpy as np

class mesh:
    def __init__(self, which):
        """
        Strictly follows the g,z,y,x convention for cartesian mesh

        units:
        g: MeV
        dimensions: cm
        """

        self.supported_which = ['orcs', 'shift']
        if which not in self.supported_which:
            raise ValueError('Format %s not supported. Supported formats are: [%s]' %','.join(self.supported_which))

        self.dims = ['g', 'z', 'y', 'x']
        # standardized data format for no confusion
        # i hope.
        self.meta_dict = {}
        for dim in self.dims:
            self.meta_dict['n%s' %dim] = 0
            self.meta_dict['mesh_%s' %dim] = []
        self.arr = np.zeros((1,1,1,1))
        self.re = np.zeros_like(self.arr)
        self.particle_type = ''

    def get_shape(self):
        """
        Returns the shape tuple with number of mesh groups (g,z,y,x)
        """
        self.check_meta_dict()
        self.shape = (self.meta_dict['ng'], self.meta_dict['nz'],
                      self.meta_dict['ny'], self.meta_dict['nx'])
        # for convenience
        self.shape3d = self.shape[1:]
        # get them as attributes too
        for k,v in self.meta_dict.items():
            setattr(self, k, v)

        return self.shape

    def get_num_vals_from_mesh(self):
        for i in self.dims:
            mesh = self.meta_dict['mesh_%s' %i]
            assert(len(mesh) != 0)
            self.meta_dict['n%s' %i] = len(mesh) - 1

    def get_mesh_volumes(self):
        self.check_meta_dict()
        vol_arr = np.zeros(self.arr.shape[1:])
        diff_dict = {}
        for dim in self.dims[1:]:
            diff_dict[dim] = np.diff(self.meta_dict['mesh_%s' %dim])
        # take a slice
        for zindx in range(vol_arr.shape[0]):
            vol_arr[zindx, :, :] = diff_dict['z'][zindx] * np.multiply(diff_dict['x'], diff_dict['y'])
        self.vol_arr = vol_arr
        return vol_arr

    def check_meta_dict(self):
        for dim in self.dims:
            assert(self.meta_dict['n%s' %dim] != 0)
            assert(len(self.meta_dict['mesh_%s' %dim]) != 0)
            assert(len(self.meta_dict['mesh_%s' %dim]) == self.meta_dict['n'+dim]+1)
        assert(self.particle_type in ['n', 'p'])

    def check_value_shapes(self):
        # check if initialized:
        assert(self.arr.shape != (1,1,1,1))
        self.check_meta_dict()

        for indx, val in enumerate(self.dims):
            assert(self.arr.shape[indx] == self.meta_dict['n%s' %val])

        for i in self.dims[1:]:
            assert(len(self.meta_dict['mesh_%s' %i]) == self.meta_dict['n%s' %i]+1)

        return True

    def export_vtk(self, outfile_path, title='', group_collapse=True):
        """
        Brute force way to write a vtk file
        """

        f = open(outfile_path, 'w')
        f.write('# vtk DataFile Version 2.0\n')
        if title:
            f.write(title + '\n')
        else:
            title = 'mesh'
            f.write('%s Mesh data \n' %(outfile_path.replace('.vtk', '')))
        f.write('ASCII\n')
        f.write('DATASET UNSTRUCTURED_GRID\n')

        # now points
        num_points = 1
        for dim in self.dims[1:]:
            num_points = num_points * len(self.meta_dict['mesh_'+dim])
        print('Writing %s Points..' %int(num_points))
        f.write('POINTS %s double\n' %int(num_points))
        # list all them points
        # increase x first, then y then z
        point_indx_arr = np.zeros((len(self.meta_dict['mesh_x'])+1,
                                     len(self.meta_dict['mesh_y'])+1,
                                     len(self.meta_dict['mesh_z'])+1,
                                     ))
        point_list = []
        counter = 0
        for zindx, zval in enumerate(self.meta_dict['mesh_z']):
            for yindx, yval in enumerate(self.meta_dict['mesh_y']):
                for xindx, xval in enumerate(self.meta_dict['mesh_x']):
                    point = [xval, yval, zval]
                    point_list.append(point)
                    f.write(' '.join([str(q) for q in point]) + '\n')
                    point_indx_arr[xindx, yindx, zindx] = int(counter)
                    counter += 1

        # now cells
        num_cells = 1
        for dim in self.dims[1:]:
            num_cells = num_cells * self.meta_dict['n'+dim]
        print('Writing %s Cells..' %int(num_cells))
        # multiplied by nine because
        # there's 9 values in a line?? #!
        f.write('CELLS %s %s\n' %(int(num_cells), int(num_cells*9)))
        # for each mesh cell
        # shorter
        mx = self.meta_dict['mesh_x']
        my = self.meta_dict['mesh_y']
        mz = self.meta_dict['mesh_z']
        for zindx_, zval in enumerate(mz[:-1]):
            for yindx_, yval in enumerate(my[:-1]):
                for xindx_, xval in enumerate(mx[:-1]):
                    ref_point = [xval, yval, zval]
                    # get all points to make that cell
                    # move +x, +y, -x, -y+z, +x, +y, -x
                    xindx = copy.deepcopy(xindx_)
                    yindx = copy.deepcopy(yindx_)
                    zindx = copy.deepcopy(zindx_)
                    points = [point_indx_arr[xindx, yindx, zindx]]
                    xindx += 1
                    points.append(point_indx_arr[xindx, yindx, zindx])
                    yindx += 1
                    points.append(point_indx_arr[xindx, yindx, zindx])
                    xindx -= 1
                    points.append(point_indx_arr[xindx, yindx, zindx])
                    yindx -= 1
                    zindx += 1
                    points.append(point_indx_arr[xindx, yindx, zindx])
                    xindx += 1
                    points.append(point_indx_arr[xindx, yindx, zindx])
                    yindx += 1
                    points.append(point_indx_arr[xindx, yindx, zindx])
                    xindx -= 1
                    points.append(point_indx_arr[xindx, yindx, zindx])
                    f.write('8 ' + ' '.join([str(int(q)) for q in points]) + '\n')

        # cell values
        print('Writing %s Cell Data' %(int(num_cells)))
        f.write('CELL_TYPES %s\n' %(int(num_cells)))
        for i in range(int(num_cells)):
            f.write('12\n')
        f.write('CELL_DATA %s\n' %(int(num_cells)))
        collapsed_arr = np.sum(self.arr, axis=0)
        f.write('SCALARS %s_total double 1\n' %title)
        f.write('LOOKUP_TABLE default\n')
        for zindx_, zval in enumerate(mz[:-1]):
            for yindx_, yval in enumerate(my[:-1]):
                for xindx_, xval in enumerate(mx[:-1]):
                    val = collapsed_arr[zindx_, yindx_, xindx_]
                    f.write(str(val) + '\n')

        # write them energy-dependent ones
        if not group_collapse:
            for g in range(self.arr.shape[0]):
                print('Writing energy group %s/%s' %(g, self.arr.shape[0]))
                f.write('SCALARS %s_g_%s double 1\n' %(title,g))
                f.write('LOOKUP_TABLE default\n')
                for zindx_, zval in enumerate(mz[:-1]):
                    for yindx_, yval in enumerate(my[:-1]):
                        for xindx_, xval in enumerate(mx[:-1]):
                            val = self.arr[g, zindx_, yindx_, xindx_]
                            f.write(str(val) + '\n')

        print('Finished writing vtk file at %s' %outfile_path)

    def compare_arrs(self, l1, l2):
        # flatten just in case
        l1 = np.array(l1).flatten()
        l2 = np.array(l2).flatten()
        if len(l1) != len(l2):
            return False
        for indx, val in enumerate(l1):
            if val != l2[indx]:
                return False

        return True

    def compare(self, mesh_data_):
        for k in self.meta_dict.keys():
            assert(self.compare_arrs(self.meta_dict[k], mesh_data_.meta_dict[k]))
        assert(self.compare_arrs(self.arr, mesh_data_.arr))
        return True


BASIC_PARAMETERS_WORKSHEET_NAME = 'basic_parameters'
MIDI_POS_NAME = 'midi_pos'
DG_PROBS_NAME = 'group_probs'
NUDGE_AMT_NAME = 'nudge_amt'

import ast
import copy
import json
import random
from time import gmtime, strftime

import numpy as np
import pandas as pd
from midiutil import MIDIFile

class ChanceEntry:
    attributes = ['prob_hit', 'min_vol', 'max_vol', 'duration']

    def __init__(self):
        self.prob_hit = 0
        self.min_vol = 0
        self.max_vol = 0
        self.duration = 1

class BasicParameters:

    def __init__(self):
        self.map_worksheet_name = None
        self.hits_worksheet_name = None
        self.measures = None
        self.beats = None
        self.pulses = None
        pass

    # Example of json_data:
    # '{"map_worksheet_name": "midi_map", "hits_worksheet_name": "hits", "measures": 1, "beats": 4, "pulses": 4}'
    def from_json(self, json_data):
        # This is, by far, the most Python magic thing I've ever done.  The dictionary merge isn't all that big of
        # a deal, but loading back into the __dict__ attribute is.  This monkey-patches the JSON elements in as class
        # attributes (properties).  It avoids a bunch of boilerplate logic at the risk of (dramatically) reducing
        # readability.  Not sure if this is Pythonic; might be better served using the *args, **kwargs style packing.
        # It sure feels super dangerous
        self.__dict__ = {**self.__dict__, **json.loads(json_data)}

    def from_worksheet(self, path, sheet_name='basic_parameters'):
        _ = pd.read_excel(path, sheet_name)
        self.from_json(list(_.to_dict().keys())[0])

    @property
    def pulse_length(self):
        return 1 / self.pulses

    @property
    def pulses_per_measure(self):
        return self.beats * self.pulses

    @property
    def pulse_keys(self):
        # Pulse markers in the measure
        return [i / self.pulses for i in range(self.pulses_per_measure)]

def default_midi_map():
    # Maps Rock 32 Pad DW Live drum kit
    _ = {
        'g1': {MIDI_POS_NAME: [36, 37], DG_PROBS_NAME: [0.5, 0.5], NUDGE_AMT_NAME: 1},
        'g2': {MIDI_POS_NAME: [40, 41, 42, 43], DG_PROBS_NAME: [0.55, 0.25, 0.1, 0.1], NUDGE_AMT_NAME: 3},
        'g3': {MIDI_POS_NAME: [44, 45, 46, 47], DG_PROBS_NAME: [0.6, 0.2, 0.1, 0.1], NUDGE_AMT_NAME: 1},
        'g4': {MIDI_POS_NAME: [48, 49], DG_PROBS_NAME: [0.5, 0.5], NUDGE_AMT_NAME: 2}
    }
    return pd.DataFrame.from_dict(_, orient='index')

class ConfigFileGenerator:

    def __init__(self, config):
        self.config = config

    def write_file(self, path):
        writer = pd.ExcelWriter(path, engine='xlsxwriter')

        # Add the high level parms to the first cell of a known worksheet
        pd.DataFrame().to_excel(writer, startrow=4, startcol=0, sheet_name=BASIC_PARAMETERS_WORKSHEET_NAME)
        worksheet = writer.sheets[BASIC_PARAMETERS_WORKSHEET_NAME]
        worksheet.write(0, 0, json.dumps(self.config.__dict__))

        # Add the drum group definitions
        default_midi_map().to_excel(writer, sheet_name=self.config.map_worksheet_name)

        # Add the empty hits
        self.default_drum_hits().to_excel(writer, sheet_name=self.config.hits_worksheet_name)

        writer.save()
        writer.close()
        print('Created ' + path)

    def default_drum_hits(self):
        # Create a set of drum group names
        drum_groups = ['g' + str(i) for i in range(1, 5)]

        # Expand for all groups for all attributes
        column_headers = [dg + '_' + a for dg in drum_groups for a in ChanceEntry.attributes]

        # Add the pulse keys for the first column
        hits = pd.DataFrame(index=self.config.pulse_keys)

        # Add all the attribute columns
        hits = pd.concat([hits, pd.DataFrame(columns=column_headers)])

        # Default empty values to 0 and return
        return hits.fillna(0)

class MIDINote:

    def __init__(self, pitch=0, start=0, duration=0, volume=0, track=0, channel=0):
        self.track = track
        self.channel = channel
        self.pitch = pitch
        self.start = start
        self.duration = duration
        self.volume = volume

class DrumGroup:

    def __init__(self):
        self.midi_pitches = []
        self.midi_probs = []
        self.nudge_amt = 0

class MIDIFileGenerator:

    def __init__(self):
        self.config = BasicParameters()
        self.drum_groups = {}
        self.drum_probs = None

    def do(self, path):
        self.config.from_worksheet(path)
        self.read_data(path)
        # _ = self.generate_midi_notes()
        _ = self.generate_midi_notes_2()
        self.write_midi_file(_)

    def read_data(self, path):
        # Read data from the midi map worksheet
        _ = pd.read_excel(path, sheet_name=self.config.map_worksheet_name, index_col=0)
        for drum_group_name in _.index:
            # Load the data into a DrumGroup dictionary
            dg = DrumGroup()
            dg.midi_pitches = ast.literal_eval(_[MIDI_POS_NAME][drum_group_name])
            dg.midi_probs = ast.literal_eval(_[DG_PROBS_NAME][drum_group_name])
            dg.nudge_amt = _[NUDGE_AMT_NAME][drum_group_name]
            self.drum_groups[drum_group_name] = dg

        # Read data from the probability matrix, as it were
        _ = pd.read_excel(path, sheet_name=self.config.hits_worksheet_name, index_col=0).fillna(0)
        # Load the data into a dictionary of ChanceEntries
        self.drum_probs = {drum_group_name + str(r): ChanceEntry()
                           for drum_group_name in self.drum_groups.keys() for r in list(_.index)}
        for index, row in _.iterrows():
            for drum_group_name in self.drum_groups.keys():

                # Reference to the specific chance entry object
                entry = self.drum_probs.get(drum_group_name + str(row.name))

                for a in ChanceEntry.attributes:
                    # Set the attribute value
                    setattr(entry, a, row[drum_group_name + '_' + a])

    def generate_midi_notes_2(self):
        _ = {}
        for i in range(0, 2):
            _ = {**_, **(self.generate_midi_notes_2a(i * 4))}
        return _

    def generate_midi_notes_2a(self, base_measure):
        first_measure = self.build_measure_precursor(base_measure)
        _ = copy.deepcopy(first_measure)

        for i in range(1, 4):
            _ = {**_, **(self.duplicate(first_measure, i))}

        last_measure = self.build_measure_precursor(base_measure)
        self._shift_timing(last_measure, 4)
        _ = {**_, **last_measure}

        return _

    def build_measure_precursor(self, measure_number):
        all_notes = {}

        for drum_group_name, drum_group in self.drum_groups.items():
            notes = self.build_measure_for_dg(measure_number, drum_group_name, drum_group)

            if len(notes) > 0:
                # Drum group, measure number, and pulse key
                group_key = drum_group_name + '_m' + str(1)
                all_notes[group_key] = notes

        return all_notes

    def duplicate(self, notes, shift_amount):
        new_notes = copy.deepcopy(notes)
        new_notes = {k + '_s' + str(shift_amount): v for k, v in new_notes.items()}
        self._shift_timing(new_notes, shift_amount)
        return new_notes

    def _shift_timing(self, notes, shift_amount):
        for nl in notes.values():
            for n in nl:
                n.start = n.start + ((shift_amount - 1) * self.config.beats)

    def generate_midi_notes(self):
        all_notes = {}

        # TODO Generate and hold a pattern?  Let other drums revolve around a fixed point
        for measure in range(self.config.measures):

            for drum_group_name, drum_group in self.drum_groups.items():
                notes = self.build_measure_for_dg(measure, drum_group_name, drum_group)

                if len(notes) > 0:
                    # Drum group, measure number, and pulse key
                    group_key = drum_group_name + '_m' + str(measure)
                    all_notes[group_key] = notes

        return all_notes

    def build_measure_for_dg(self, measure_number, drum_group_name, drum_group):
        notes = []

        for pulse in self.config.pulse_keys:
            chance_key = drum_group_name + str(pulse)
            drum_chance = self.drum_probs.get(chance_key)

            if random.random() <= drum_chance.prob_hit:
                notes.append(self.build_note(drum_group, drum_chance, measure_number, pulse))

        return notes

    def build_note(self, drum_group, drum_chance, measure_number, pulse):
        n = MIDINote()
        n.pitch = self.choose_pitch(drum_group)
        measure_adjusted_pulse = pulse + (measure_number * self.config.beats)
        n.start = self.generate_start_time(drum_group, measure_adjusted_pulse, laidback=False)
        n.duration = self.generate_duration(drum_chance, measure_adjusted_pulse, n.start)
        n.volume = self.choose_volume(drum_chance)
        return n

    def choose_pitch(self, drum_group):
        # Choose which drum from set of drum groups based on stated probabilities
        pitch_pos = np.random.choice(np.arange(0, len(drum_group.midi_probs)), p=drum_group.midi_probs)
        return drum_group.midi_pitches[pitch_pos]

    def generate_start_time(self, drum_group, measure_adjusted_pulse, laidback):
        # Nudge off the grid, but can't be negative after the nudge
        return max(measure_adjusted_pulse + self.nudge(drum_group.nudge_amt, laidback), 0)

    def generate_duration(self, drum_chance, measure_adjusted_pulse, start):
        # Cap the length so that it doesn't run into the next measure
        return min(drum_chance.duration * self.config.pulse_length,
                   (measure_adjusted_pulse + self.config.pulse_length) - start)

    def choose_volume(self, drum_chance):
        # Range bound random volume
        return random.randint(drum_chance.min_vol, drum_chance.max_vol)

    def write_midi_file(self, notes):
        now = gmtime()
        midi_content = MIDIFile(1)
        midi_content.addTrackName(0, 0, strftime("%#m/%d %H:%M:%S", now))

        # filtered_notes = {k: notes[k] for k in notes.keys() if any(xk in k for xk in ['g2', 'g3', 'g4'])}
        filtered_notes = notes
        [[midi_content.addNote(n.track, n.channel, n.pitch, n.start, n.duration, n.volume) for n in v]
         for v in filtered_notes.values()]

        with open('c:/temp/' + strftime("%Y%m%d %H%M%S", now) + '.mid', "wb+") as _:
            midi_content.writeFile(_)
            _.close()

    def nudge(self, time=0, laidback=False):
        return 0 if time == 0 else random.randrange((0 if laidback else -1 * time), time) * 0.01


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

from odoo import models, fields, api, _
import logging
import time
from odoo.exceptions import UserError

_logger = logging.getLogger(__name__)

class AccountTaxInvoiceWizard(models.TransientModel):
    _name = 'account.tax.invoice.wizard'
    _description = 'the way to make tax invoice'

    tax_invoice_no = fields.Char('Tax invoice no', required=True)
    partner_id = fields.Many2one('res.partner', 'Partner')
    invoice_line_ids = fields.Many2many('account.invoice.line', string='Invoice line')
    tax_invoice_method = fields.Selection([
        ('all', 'All'),
        ('part_amount', 'Part-amount'),
        ('part_percent', 'Part-rate'),
    ], required=True)
    tax_invoice_number = fields.Float('Tax invoice number')

    @api.model
    def default_get(self, fields_list):
        res = super(AccountTaxInvoiceWizard, self).default_get(fields_list)
        if self.env.context.get('active_ids'):
            current_model_name = self.env.context.get('current_model_name')
            invoice_model_name = self.env.context.get('invoice_model_name')
            if not current_model_name:
                if invoice_model_name == 'account.invoice.line':
                    invoice_line_ids = self.env['account.invoice.line'].browse(self.env.context.get('active_ids'))
                else:
                    invoice_ids = self.env['account.invoice'].browse(self.env.context.get('active_ids'))
                    invoice_line_ids = invoice_ids.mapped('invoice_line_ids')

            if current_model_name and current_model_name == 'verify.batch.reconciliation':
                ve_batch_re_ids = self.env['verify.batch.reconciliation'].browse(self.env.context.get('active_ids'))
                invoice_line_ids = ve_batch_re_ids.mapped('invoice_line_ids')

            partner_id = invoice_line_ids.mapped('partner_id')
            invoice_line_ids = invoice_line_ids.filtered(lambda x: x.tax_invoice_amount != x.price_unit)
            res.update({
                'invoice_line_ids': [(6, 0, invoice_line_ids.ids)],
                'partner_id': partner_id[0].id if partner_id else invoice_line_ids.mapped('invoice_id').mapped('partner_id')[0].id if invoice_line_ids.mapped('invoice_id').mapped('partner_id') else False
            })
        _logger.info({
            'res': res
        })
        return res

    # 解析数据
    def _parse_account_tax_invoice_data(self):
        data = {
            'partner_id': self.partner_id.id,
            'partner_shipping_id': self.partner_id.id,
            'user_id': self.env.user.id,
            'tax_invoice_no': self.tax_invoice_no
        }
        return data

    # 数据行的数据
    def _parse_account_tax_invoice_line_data(self, tax_invoice_method, tax_invoice_number, invoice_line_ids):
        line_data = []
        for line_id in invoice_line_ids:
            # 获取金额数据
            amount = getattr(self, '_compute_invoice_amount_{type_name}'.format(
                type_name=tax_invoice_method
            ))(line_id, tax_invoice_number, invoice_line_ids)
            line_data.append((0, 0, {
                'product_id': line_id.product_id.id,
                'name': line_id.product_id.name,
                'quantity': 1,
                'uom_id': line_id.product_id.uom_id.id,
                'price_unit': amount,
                'account_id': line_id.account_id.id,
                'invoice_line_id': line_id.id
            }))
        return line_data

    # 全部
    def _compute_invoice_amount_all(self, line_id, tax_invoice_number, invoice_line_ids):
        left_amount = line_id.price_unit - line_id.tax_invoice_amount
        line_id.write({
            'tax_invoice_amount': line_id.price_unit,
            # 'tax_invoice_state': tax_invoice_state
        })
        return round(float(left_amount) * 1000, -1) / 1000

    # 部分-金额
    def _compute_invoice_amount_part_amount(self, line_id, tax_invoice_number, invoice_line_ids):
        left_amount = line_id.price_unit - line_id.tax_invoice_amount
        if left_amount > tax_invoice_number / len(invoice_line_ids):
            line_id.write({
                'tax_invoice_amount': line_id.tax_invoice_amount + round(
                    float(tax_invoice_number / len(invoice_line_ids) * 1000), -1) / 1000
            })
            return round(float(tax_invoice_number / len(invoice_line_ids) * 1000), -1) / 1000
        else:
            line_id.write({
                'tax_invoice_amount': line_id.price_unit
            })
            return left_amount

    # 部分-比率
    def _compute_invoice_amount_part_percent(self, line_id, tax_invoice_number, invoice_line_ids):
        res = (line_id.price_unit - line_id.tax_invoice_amount) * (tax_invoice_number / 100)
        line_id.write({
            'tax_invoice_amount': line_id.tax_invoice_amount + round(float(res * 1000), -1) / 1000
        })
        return round(float(res * 1000), -1) / 1000

    def create_account_tax_invoice(self):
        try:
            self._judge_invoice_no()

            data = self._parse_account_tax_invoice_data()
            line_data = self._parse_account_tax_invoice_line_data(self.tax_invoice_method, self.tax_invoice_number,
                                                                  self.invoice_line_ids)

            data.update({
                'invoice_line_ids': line_data
            })
            tax_invoice_obj = self.env['account.tax.invoice']
            res = tax_invoice_obj.create(data)

            # 计算一次预开票
            self.invoice_line_ids._compute_pre_billing()

            self._create_invoice_no(res)
        except Exception as e:
            self._cr.rollback()
            raise UserError(e)

    # 创建发票批次号
    def _create_invoice_no(self, res):
        invoice_no_obj = self.env['invoice.no.tax.invoice']
        tax_invoice_line_ids = res.mapped('invoice_line_ids')
        invoice_line_ids = self.invoice_line_ids

        partner_ids = res.mapped('partner_id').ids
        partner_ids = list(set(partner_ids))
        if len(partner_ids) > 1:
            raise UserWarning('You must select same partner.')

        invoice_id = invoice_no_obj.search([('name', '=', self.tax_invoice_no)])

        # 搜索到就修改更新，没有找到才创建
        if invoice_id:
            # Update
            invoice_id.write({
                'invoice_line_ids': [(4, line_id.id) for line_id in invoice_line_ids],
                'tax_invoice_line_ids': [(4, line_id.id) for line_id in tax_invoice_line_ids]
            })
        else:
            # Create
            invoice_no_obj.create({
                'name': self.tax_invoice_no,
                'partner_id': partner_ids[0] if partner_ids else False,
                'invoice_line_ids': [(6, 0, invoice_line_ids.ids)],
                'tax_invoice_line_ids': [(6, 0, tax_invoice_line_ids.ids)] if tax_invoice_line_ids else False
            })

    # 如果结算清单已经存在发票批次号，就不能使用新的批次号
    def _judge_invoice_no(self):
        res = self.env['invoice.no.tax.invoice'].search([
            ('tax_invoice_line_ids.invoice_line_id', 'in', self.invoice_line_ids.ids)
        ])

        if not res:
            return True

        # 理论上这样的记录不能超过1
        if len(res) > 1:
            raise UserError(_('You can\'t create multi different invoice no tax invoice with same invoice'))

        if res.name != self.tax_invoice_no:
            raise UserError(_('There are already exist tax invoice, you must use the same tax invoice no!'))


from collections import UserDict

class AddressBook(UserDict):
    def add_record(self, record):
        self.data[record.name.value] = record

class Record:
    def __init__(self, name, phone = None) -> None:
        self.name = name
        self.phones = []
        self.phones.append(phone)

    def add_phone(self, phone):
        self.phones.append(phone)
        return 'Done!'

    def del_phone(self, phone):
        for p in self.phones:
            if p.value == phone.value:
                self.phones = filter(lambda x: x != p, self.phones)
            return 'Done!'
        return "This phone doesn't exist in this contact."

    def edit_phone (self, phone, new_phone):
        for p in self.phones:
            if p.value == phone.value:
                p.value = new_phone.value
            return 'Done!'
        return "This phone doesn't exist in this contact."

class Field:
    def __init__(self, value):
        self.value = value

class Name(Field):
    pass

class Phone(Field):
    pass

def main():
    phone_book = AddressBook()
    while True:
        user_command = input('>>>')
        if user_command == '.':
            break
        elif user_command.lower() == 'hello':
            print(greeting())
        elif user_command.lower() in ("good bye", "close", "exit"):
            print(good_buy())
            break
        elif user_command.lower().startswith('add '):
            print(add(user_command, phone_book))
        elif user_command.lower().startswith('change '):
            print(change(user_command, phone_book))
        elif user_command.lower() == 'show all':
            print(show_all(phone_book))
        elif user_command.lower().startswith('phone '):
            print(phone(user_command, phone_book))
        elif user_command.lower().startswith('delate '):
            print(delate(user_command, phone_book))

def input_error(func):
    def inner(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except KeyError:
            return 'This name do not exist in your phone book!'
        except ValueError:
            return 'Please enter a phone number.'
        except IndexError:
            return 'Give me name and phone please.'
    return inner

def greeting():
    return 'How can I help you?'

def good_buy():
    return 'Good buy!'

def show_all(phones):
    result = ''
    for k, v in phones.items():
        all_phones = ''
        for p in v.phones:
            all_phones += str(p.value) + ', '
        result = result + f'{k} : {all_phones[:-2]}\n'
    return result[:-1]

@input_error
def add(user_command, phone_book):
    command = user_command.split(' ')
    if len(command) != 3:
        raise IndexError()
    name = Name(command[1])
    phone_number = Phone(int(command[2]))
    if name.value in phone_book.keys():
        rec = phone_book[name.value]
        rec.add_phone(phone_number)
        return 'Done!'
    rec = Record(name, phone_number)
    phone_book.add_record(rec)
    return 'Done!'

@input_error
def change(user_command, phone_book):
    command = user_command.split(' ')
    if len(command) != 4:
        raise IndexError()
    name = Name(command[1])
    phone_number = Phone(int(command[2]))
    new_phone = Phone(int(command[3]))
    if name.value not in phone_book.keys():
        raise KeyError()
    phone_book[name.value].edit_phone(phone_number, new_phone)
    return 'Done!'

@input_error
def delate(user_command, phone_book):
    command = user_command.split(' ')
    if len(command) != 3:
        raise IndexError()
    name = Name(command[1])
    phone_number = Phone(int(command[2]))
    if name.value not in phone_book.keys():
        raise KeyError()
    return phone_book[name.value].del_phone(phone_number)

@input_error
def phone(user_command, phone_book):
    command = user_command.split(' ')
    if len(command) != 2:
        raise KeyError()
    name = Name(command[1])
    all_phones = ''
    for p in phone_book[name.value].phones:
            all_phones += str(p.value) + ', '
    return (all_phones[:-2])

if __name__ == "__main__":
    main()


import pyttsx3
import datetime
import speech_recognition as sr
import webbrowser as wb
import os
tuesday=pyttsx3.init()
voice=tuesday.getProperty('voices')
tuesday.setProperty('voice', voice[1].id)

def speak(audio):
    print("Tuesday:"+ audio)
    tuesday.say(audio)
    tuesday.runAndWait()

def time():
    time=datetime.datetime.now().strftime("%I: %M: %p")
    speak(time)

def welcome():
    hour=datetime.datetime.now().hour
    if hour >= 6 and hour <= 12:
        speak("Good Morning sir")
    elif hour > 12 and hour <= 18:
        speak("Good Afternoon sir" )
    else:
        speak("Good Night Sir")
    speak("How can I help you")
def command():
    r=sr.Recognizer()

    with sr.Microphone() as source:
        r.pause_threshold= 1
        audio = r.listen(source)

        try:
            said=r.recognize_google(audio,language="en")
            print("Mr. Hoang "+ said)

        except Exception as e:
            print("Exception:" + str(e))
    return said

if __name__== "__main__":
    welcome()

    while True:
        said= command().lower()
        speak(said)
        if "google" in said :
            speak("What shoud I search boss?")
            search=command().lower()
            url=f"https://www.google.com/search?q={search}"
            wb.get().open(url)
            speak(f"Here is your {search} on google")
        if "Youtube" in said :
            speak("What shoud I search boss?")
            search=command().lower()
            url=f"https://www.youtube.com//search?q={search}"
            wb.get().open(url)
            speak(f"Here is your {search} on youtube")
        elif "open video" in said:
            meme=r"C:\Users\hoang\Videos\Captures\meme.mp4"
            os.startfile(meme)
        elif "sing" in said:
            sofa=r"C:\Users\hoang\Videos\Captures\sofa.mp3"
            os.startfile(sofa)
        elif "time" in said:
            time()
        elif "quit" in said:
            speak("Tuesday is quitting sir.Goodbye boss")
            quit()


def solve():
    c = 0  # c(current) 현재 값을 0으로 둔다 0에서 시작하기 때문
    cnt = 0  # 0에서 1로 또는 1에서 0으로 몇번 바뀌는지 cnt로 센다
    for i in range(len(arr)):  # i가 0이라고 가정할 때
        if arr[i] != c:  # 문자열의 첫번째 값이 0이 아니면
            c = not c  # c를 1로 바꾸고
            cnt += 1  # 카운트한다
    return cnt  # 몇번 카운트 했는지 반환한다

T = int(input())
for tc in range(1, T + 1):
    arr = list(map(int, input()))  # 숫자로 이루어진 리스트를 만든다
    ans = solve()
    print(f'#{tc} {ans}')

0301/원재의 메모리 복구하기.py

원재의 메모리 복구하기.py


import numpy as np
import matplotlib.pyplot as plt
import tools as tools
import time
start_time = time.time()

filein = '../core-softened-phase-diagram/CSA/temp-0.01/lambda_0.25/run/lammps_temp_0.01_press_6.5.snap'

r = tools.read_in_trajectory(filein, 4000, 100)

L1 = 1.1*np.absolute(np.max(r[:,:,0]) - np.min(r[:,:,0]))
L2 = 1.1*np.absolute(np.max(r[:,:,1]) - np.min(r[:,:,1]))
L3 = 0.0
rdf, r = tools.rdf_monomer_to_monomer(r[:,:,0],r[:,:,1],L1,L2)

sex, csum, r_s2 = tools.excess_entropy_from_rdf(rdf,r)
r_s2 = r_s2[r_s2>0]
csum = csum[csum>0]

rho = (0.5 * 4000) / (L1 * L2)

print(csum)
print(r_s2)
print("--- %s seconds ---" % (time.time() - start_time))

plt.figure()
#plt.ylim(0,12)
data = np.genfromtxt("../core-softened-phase-diagram/CSA/temp-0.01/lambda_0.25/ex_entropy/press_6.5_cumsex.dat")
plt.plot(r_s2,csum)
plt.plot(data[:,0],data[:,1],color="red")
#plt.yscale('log')
plt.show()


from common.base_utils.comm_utils import create_bankcard
from common.business_func.applet_func import Applet_func
from common.business_func.namelist import NameList
from common.business_func.mem_information_manag_func import Member_information_management_func
from common.login.web_login import Web_Login
from common.login.applet_login import Applet_Login
from common.venv.var import *
from common.base_utils.comm_param import *
from common.business_func.orders import Order

# 配置项
n = 1 # 录名单数量
entborrows = ['协和小时工1']  # 企业
ents = ['昆山协和']  # 标准企业
interviewdt = '2020-07-01' # 面试日期
OrderDt = '2020-07-01' # 订单报价日期
BeginDt = '2020-07-01' # 订单生效开始日期
repairclockdt = '2020-07-01' # 补卡开始日期
agentnames = ['殷海涛供应商'] #供应商列表
username_name = '13340000001'
username_order = '15995627659'
username_mem = '15995627659'
username_advance = '15995627659'
bankname = '兴业银行'
SettleBeginDate='2020-07-01'
SettleEndDate = '2020-07-01'
workdate = '2020-07-01' # 入职日期

login = Web_Login()

login.login(username_name)

name_manage = NameList(login)

# 录名单

mobiles = []
membernames = []
idcardnums = []
nameids = []
for i in range(n):
    mobile = create_phone()
    idnum = create_IDCard()
    name = create_name()
    name_manage.add_name_pq(entbrorrowname=entborrows[0],InterviewDate=interviewdt,FromSpName=agentnames[0],name=name)
    mobiles.append(mobile)
    membernames.append(name)
    idcardnums.append(idnum)
    nameids.append(name_manage.newnameid_pq)
    print(i)
# 建订单
order_manage = Order(login)
order_manage.create_order_pq(ReceiverType=2,entbrorrowname=entborrows[0],OrderDt=OrderDt,BeginDt=OrderDt,PriceUnit=1)
order_manage.Judge_Order(auditsts=2,orderid=order_manage.orderid)
order_manage.publishOrderToSupplier(agentname=agentnames[0])

# 名单绑订单
name_manage.bind_order(orderid=order_manage.orderid,namelist=nameids)

# 上传身份证
workcardnos = []
for i in range(n):
    applogin = Applet_Login()
    applogin.applogin(tenantype=2, phone=mobiles[i])
    member = Applet_func(applogin)
    mem_manage = Member_information_management_func(login)

    member.upload_idcard(fakeridcardpicture)
    # 审核身份证
    mem_manage.audit_idcard(idcardnum=idcardnums[i],rname=membernames[i],phone=mobiles[i])

    # 上传银行卡
    member.upload_bankcard(bankname=bankname,bankCardFile=fakerbankcardpicture)
    # 审核银行卡
    bankcardnum = create_bankcard()
    mem_manage.audit_bankcard(bankcardnum=bankcardnum,bankname=bankname,phone=mobiles[i])

    # 上传工牌
    member.upload_workcard(entname=ents[0],workCardFile=workCardpicture)
    # 审核工牌
    workcardno = create_workcardno()
    mem_manage.audit_workcard(entshortname=ents[0],workcardno=workcardno,phone=mobiles[i])
    # workcardnos.append(workcardno)


from flask import request, jsonify, Blueprint
from marshmallow import Schema, fields, ValidationError, validate

def UserModelBlueprint(database):

    UserModel = Blueprint('UserModel',__name__)

    class TimeRange(Schema):
        StartTime = fields.Time(required=True)
        EndTime = fields.Time(required=True)

    # Payload Schema for Store Initial Model API
    class StoreInitialModelSchema(Schema):
        UserId = fields.Integer(required=True)
        WorkingHours = fields.Nested(TimeRange(), required=True)
        BreakTime = fields.Nested(TimeRange(), required=True)
        TimePreference = fields.String(validate=validate.OneOf(['morning', 'afternoon', 'evening']), required=True)
        WeatherPreference = fields.String(validate=validate.OneOf(['sunny','rainy','none','any']), required=True)

    @UserModel.route("/store-initial-model", methods=["POST"])
    def StoreInitialModel():
        # Unmarshal Payload
        request_data = request.json

        try:
            result = StoreInitialModelSchema().load(request_data)
            result["WorkingHours"]["StartTime"] = result["WorkingHours"]["StartTime"].isoformat()
            result["WorkingHours"]["EndTime"] = result["WorkingHours"]["EndTime"].isoformat()
            result["BreakTime"]["StartTime"] = result["BreakTime"]["StartTime"].isoformat()
            result["BreakTime"]["EndTime"] = result["BreakTime"]["EndTime"].isoformat()
        except ValidationError as err:
            return jsonify(err.messages), 400

        try:
            database["userModel"].insert_one(result)
            return jsonify({"message": "Success"}), 200
        except Exception as e:
            return jsonify({"main_message": "Something went wrong!!", "detail_message": str(e)}), 400

    # Update Model Schema Payload
    class UpdateModelSchema(Schema):
        UserId = fields.Integer(required=True)
        WorkingHours = fields.Nested(TimeRange(), required=False)
        BreakTime = fields.Nested(TimeRange(), required=False)
        TimePreference = fields.String(validate=validate.OneOf(['morning', 'afternoon', 'evening']), required=False)
        WeatherPreference = fields.String(validate=validate.OneOf(['sunny', 'none']), required=False)

    @UserModel.route("/update-model", methods=["POST"])
    def UpdateModel():
        # Unmarshal Payload
        request_data = request.json

        try:
            result = UpdateModelSchema().load(request_data)
            if "WorkingHours" in result:
                result["WorkingHours"]["StartTime"] = result["WorkingHours"]["StartTime"].isoformat()
            if "WorkingHours" in result:
                result["WorkingHours"]["EndTime"] = result["WorkingHours"]["EndTime"].isoformat()
            if "BreakTime" in result:
                result["BreakTime"]["StartTime"] = result["BreakTime"]["StartTime"].isoformat()
            if "BreakTime" in result:
                result["BreakTime"]["EndTime"] = result["BreakTime"]["EndTime"].isoformat()
            UserId = result["UserId"]
            del result["UserId"]
        except ValidationError as err:
            return jsonify(err.messages), 400

        try:
            resp = database["userModel"].update_one(
                { 'UserId': UserId }, { '$set': result }
            )

            if resp.matched_count > 0:
                return jsonify({"message": "Success"}), 200
            else:
                return jsonify({"main_message": "Something went wrong!!", "detail_message": "The user does not exist"}), 400

        except Exception as e:
            return jsonify({"main_message": "Something went wrong!!", "detail_message": str(e)}), 400

    return UserModel


# 이코테 다이나믹 프로그래밍
# 개미 전사

# 정수 N을 입력 받기
n=int(input())
# 모든 식량 정보 입력 받기
lst=list(map(int,input().split()))

# 앞서 계산된 결과를 저장하기 위한 DP 테이블 초기화
d=[0]*100
# 다이나믹 프로그래밍 진행 (BottomUP)
d[0]=lst[0]
d[1]=lst[1]

for i in range(2,n):
    d[i]=max(d[i-1],d[i-2]+lst[i])

# 계산된 결과 출력
print(d[n-1])

이것이_취업을_위한_코딩테스트다_나동빈/DynamicProgramming/개미전사.py


from prime import sieve
from math import sqrt, ceil
from itertools import count, combinations
from functools import reduce

maximum = 1000000
primes_list = tuple(sieve(maximum))
primes_set = set(primes_list)

def factorize(n):
    factors = []
    for prime in primes_list:
        if prime > n:
            return factors

        while n % prime == 0:
            factors.append(prime)
            n = n//prime

def dividors(factors):
    s = set()
    factors.append(1)
    mul = lambda a,b: a*b
    for r in range(1, len(factors)+1):
        for c in combinations(factors, r):
            s.add(reduce(mul, c))
    return s

def minmax(a,b):
    if a > b:
        return b,a
    else:
        return a,b

def solutions(n):
    n2 = n*n
    s = set()
    factors = factorize(n)
    factors = factors+factors
    for t in dividors(factors):
        x = n + t
        y = n2//t + n
        s.add(minmax(x,y))
    return s

for n in range(4,20):
    s = solutions(n)
    print(n, len(s))


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the sockMerchant function below.
def sockMerchant(n, ar):
    import collections

    c = collections.Counter(ar)
    num = 0
    for elem in c.values():
        if elem != 1:
                num += elem // 2
    return num

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    ar = list(map(int, input().rstrip().split()))

    result = sockMerchant(n, ar)

    fptr.write(str(result) + '\n')

    fptr.close()


def smart_unicode(s, encoding='utf-8', errors='strict'):
    if isinstance(s, unicode):
        return s

    try:
        if not isinstance(s, basestring,):
            if hasattr(s, '__unicode__'):
                s = unicode(s)
            else:
                try:
                    s = unicode(str(s), encoding, errors)
                except UnicodeEncodeError:
                    s = ' '.join([smart_unicode(arg, encoding, errors) for arg in s])
        elif not isinstance(s, unicode):
            s = s.decode(encoding, errors)

    except UnicodeDecodeError:
        s = ' '.join([smart_unicode(arg, encoding, errors) for arg in s])

    return s

def smart_str(s, encoding='utf-8', errors='strict'):
    if not isinstance(s, basestring):
        try:
            return str(s)
        except UnicodeEncodeError:
            if isinstance(s, Exception):
                return ' '.join([smart_str(arg, encoding, errors) for arg in s])
            return unicode(s).encode(encoding, errors)

    elif isinstance(s, unicode):
        return s.encode(encoding, errors)
    elif s and encoding != 'utf-8':
        return s.decode('utf-8', errors).encode(encoding, errors)
    else:
        return s