from datetime import datetime, timedelta
import oandapy
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pickle
import sys
import os
import talib
sys.path.append('/Users/toshio/project/fx')
from config import token
from lib.indicator import ichimoku

class Preprocess:
    def __init__(self, res, df = None):
        self.res = res
        if df is None:
            self.df = self.res_to_df()
        else:
            self.df = df
        self.df = self.res_to_df()
        self.arr_ask, self.arr_bid, self.df_ask = self.prep_ohlcv()
        self.delta = self.prep_delta()
        self.sma = self.prep_sma()
        self.macd = self.prep_macd()
        self.rsi = self.prep_rsi()
        self.bband = self.prep_bband()
        self.adx = self.prep_adx()
        self.di = self.prep_di()
        self.sar = self.prep_sar()
        self.ichi = self.prep_ichi()
        self.data = self.prep_concat()

    def res_to_df(self):
        df = pd.DataFrame(self.res['candles'])
        df = df.drop(['complete'], axis = 1)
        df['time'] = df['time'].str[:-8]
        df['time'] = df['time'].str.replace('T',' ')
        times = [datetime.strptime(v, '%Y-%m-%d %H:%M:%S') for v in df['time']]
        df['time'] = times
        df = df.set_index('time',drop = True)
        return df

    def prep_ohlcv(self):
        df_ask = pd.DataFrame(columns = ['open', 'high', 'low', 'close', 'volume'])
        df_ask['open'] = self.df['openAsk']
        df_ask['high'] = self.df['highAsk']
        df_ask['low'] = self.df['lowAsk']
        df_ask['close'] = self.df['closeAsk']
        df_ask['volume'] = self.df['volume']
        arr_ask = np.array(df_ask)

        df_bid = pd.DataFrame(columns = ['open', 'high', 'low', 'close', 'volume'])
        df_bid['open'] = self.df['openBid']
        df_bid['high'] = self.df['highBid']
        df_bid['low'] = self.df['lowBid']
        df_bid['close'] = self.df['closeBid']
        df_bid['volume'] = self.df['volume']
        arr_bid = np.array(df_bid)
        return arr_ask, arr_bid, df_ask

    def prep_delta(self):
        delta = pd.DataFrame(index = self.df.index, columns = ['delta_close'])
        delta['delta_close'] = self.df_ask['close'].diff()
        return delta

    def prep_sma(self):
        sma = pd.DataFrame(index = self.df.index, columns = ['sma5', 'sma25', 'sma50', 'sma75'])
        sma['sma5'] = talib.SMA(self.arr_ask[:,3], timeperiod = 5)
        sma['sma25'] = talib.SMA(self.arr_ask[:,3], timeperiod = 25)
        sma['sma50'] = talib.SMA(self.arr_ask[:,3], timeperiod = 50)
        sma['sma75'] = talib.SMA(self.arr_ask[:,3], timeperiod = 75)
        return sma

    def prep_macd(self):
        macd = pd.DataFrame(index = self.df.index, columns = ['macd', 'macdsignal', 'macdhist'])
        macd['macd'] =  talib.MACD(self.arr_ask[:,3],fastperiod=12, slowperiod=26, signalperiod=9)[0]
        macd['macdsignal'] =  talib.MACD(self.arr_ask[:,3],fastperiod=12, slowperiod=26, signalperiod=9)[1]
        macd['macdhist'] =  talib.MACD(self.arr_ask[:,3],fastperiod=12, slowperiod=26, signalperiod=9)[2]
        return macd

    def prep_rsi(self):
        rsi = pd.DataFrame(index = self.df.index, columns = ['rsi'])
        rsi['rsi'] =  talib.RSI(self.arr_ask[:,3], timeperiod = 14)
        return rsi

    def prep_bband(self):
        bband = pd.DataFrame(index = self.df.index, columns = ['-3sigma', '-2sigma', '-1sigma', '+1sigma', '+2sigma', '+3sigma'])
        bband['+1sigma'] = talib.BBANDS(self.arr_ask[:,3], timeperiod=15, nbdevup=1, nbdevdn=1)[0]
        bband['-1sigma'] = talib.BBANDS(self.arr_ask[:,3], timeperiod=15, nbdevup=1, nbdevdn=1)[2]
        bband['+2sigma'] = talib.BBANDS(self.arr_ask[:,3], timeperiod=15, nbdevup=2, nbdevdn=2)[0]
        bband['-2sigma'] = talib.BBANDS(self.arr_ask[:,3], timeperiod=15, nbdevup=2, nbdevdn=2)[2]
        bband['+3sigma'] = talib.BBANDS(self.arr_ask[:,3], timeperiod=15, nbdevup=3, nbdevdn=3)[0]
        bband['-3sigma'] = talib.BBANDS(self.arr_ask[:,3], timeperiod=15, nbdevup=3, nbdevdn=3)[2]
        return bband

    def prep_adx(self):
        adx = pd.DataFrame(index = self.df.index, columns = ['adx'])
        adx['adx'] = talib.ADX(self.arr_ask[:,1], self.arr_ask[:,2], self.arr_ask[:,3], timeperiod =14)
        return adx

    def prep_di(self):
        di = pd.DataFrame(index = self.df.index, columns = ['+di', '-di'])
        di['+di'] = talib.PLUS_DI(self.arr_ask[:,1], self.arr_ask[:,2], self.arr_ask[:,3], timeperiod = 14)
        di['-di'] = talib.MINUS_DI(self.arr_ask[:,1], self.arr_ask[:,2], self.arr_ask[:,3], timeperiod = 14)
        return di

    def prep_sar(self):
        sar = pd.DataFrame(index = self.df.index, columns = ['sar'])
        sar['sar'] = talib.SAR(self.arr_ask[:,1], self.arr_ask[:,2], acceleration=0.05, maximum=0.2)
        return sar

    def prep_ichi(self):
        ichi = ichimoku(self.df_ask).drop('close', axis = 1)
        return ichi

    def prep_concat(self):
        adder = [self.delta, self.sma, self.macd, self.rsi, self.bband, self.adx, self.di, self.sar, self.ichi]
        data = self.df.join(adder)
        data = data.drop('chiko', axis = 1)
        data = data.dropna()
        return data

if __name__ == '__main__':
    gran = 'H1'
    look_back = 10
    oanda = oandapy.API(environment="practice", access_token=token)
    res = oanda.get_history(instrument="USD_JPY",granularity=gran, count = 77 + look_back)
    prep = Preprocess(res)
    data = prep.data

    with open('../intermediate_data/prep_data_{}.pickle'.format(gran), mode='wb') as f:
        pickle.dump(data, f)


import pandas as pd
import numpy as np

class Adj_Matrix(object): #class for adjacency matrix
    def __init__(self, size):
        self.matrix = np.zeros((size,size))
        self.size = size

    def get_weight(self, v_purchaser, v_user):
        return self.matrix[v_purchaser][v_user]

    def add_edge(self, v_purchaser, v_user, weight):
        curr_weight = self.get_weight(v_purchaser, v_user)
        self.matrix[v_purchaser][v_user] = weight + curr_weight

def parse_string(name_str):
    name_str = name_str.title()
    name_list = name_str.split(' ')
    return name_list[0]

def validate_name(name_dict, name_str):
    if name_str in name_dict:
        return True
    return False

def get_users(row):
    user_list = []
    for i in range(4, len(row)):
        if row[i] == 'x':
            user_list.append(data.columns[i])
    return user_list

#read excel data into data frame
#data = pd.read_excel("adj_exp.xlsx", sheet_name="new_sheet") # for testing within directory
data = pd.read_excel("/Users/nicksharpe/Library/CloudStorage/OneDrive-UniversityofFlorida/ResearchAssistant/Expenses.xlsx", sheet_name="Expenses") # for mac
#data = pd.read_excel("C:\\Users\\nshar\\OneDrive - University of Florida\\ResearchAssistant\\Expenses.xlsx", sheet_name="Expenses") # for windows

#create dictionary of names from column headers
name_dict = {}
for index, name in enumerate(data.columns[4:]):
    name = parse_string(name)
    name_dict[name] = index #number assigned will represent index in numpy array
    name_dict[index] = name

#create adj matrix graph and insert expenses into it
exp_g = Adj_Matrix(len(name_dict) // 2)

for index,row in data.iterrows():
    purchased_by = parse_string(row[2])
    user_list = get_users(row)
    if len(user_list) == 0:
        continue
    split_cost = row[3] / len(user_list)
    for user in user_list:
        user = parse_string(user)
        if user in name_dict:
            exp_g.add_edge(name_dict[purchased_by], name_dict[user], split_cost)
        else:
            print("Error: Name does not match: ", user)

#print out results
pmt_arr = []
for r in range(len(exp_g.matrix)):
    for c in range(len(exp_g.matrix)):
        amount = exp_g.get_weight(c,r) - exp_g.get_weight(r,c)
        if amount > 0:
            pmt_arr.append([name_dict[r], name_dict[c], amount])
for l in sorted(pmt_arr): print(l[0], ' -> ', l[1], ' ', l[2])


import os
import json
import pandas as pd

pd.set_option('display.max_columns', None)   # 显示完整的列
pd.set_option('display.max_rows', None)  # 显示完整的行
pd.set_option('display.expand_frame_repr', False)  # 设置不折叠数据
pd.set_option('display.max_colwidth', 100)

# 获取路径
rPath = os.getcwd()
dataPath = rPath + "\\dataSets"
# fileList = os.listdir(dataPath)
fr = open("weapon.json", 'r', encoding='utf-8')
weaponDict = json.load(fr)
fr.close()

# 对newapt.csv进行归并处理
with open("dataSets/ByWeapon.csv", 'r', encoding='utf-8-sig') as f1:
    data1 = pd.read_csv(f1)
data1 = data1.fillna("")
m1, n1 = data1.shape
flag_apt = "MESSAGETAP "
curr_apt = ""    # 当前组织名
eventList = []
eventDict = {}
for i in range(m1):
    curr_apt = data1.iloc[i][0]
    if curr_apt != flag_apt:
        # 如果当前的apt与上一个组织不同，则将eventList添加到aptDict中
        weaponDict[flag_apt]["Events"] = eventList
        eventList = []
        flag_apt = curr_apt
    eventDict["报告标题"] = data1.iloc[i][1]
    eventDict["披露时间"] = data1.iloc[i][2]
    eventDict["披露机构"] = data1.iloc[i][3]
    eventDict["攻击方法"] = data1.iloc[i][4]
    eventDict["报告摘要"] = data1.iloc[i][5]
    eventList.append(eventDict)
    eventDict = {}

with open("resOfweapon.json", "w", encoding='utf-8') as f:
    json.dump(weaponDict, f, ensure_ascii=False)


#!/usr/bin/python3
import time
import threading
import struct
import queue
import collections
import traceback
import random
import socket

from listener import *

def get_host_ip_addresses():
    return gethostbyname_ex(gethostname())[2]

class WriteBootProtocolPacket(object):

    message_type = 2 # 1 for client -> server 2 for server -> client
    hardware_type = 1
    hardware_address_length = 6
    hops = 0

    transaction_id = None

    seconds_elapsed = 0
    bootp_flags = 0 # unicast

    client_ip_address = '0.0.0.0'
    your_ip_address = '0.0.0.0'
    next_server_ip_address = '0.0.0.0'
    relay_agent_ip_address = '0.0.0.0'

    client_mac_address = None
    magic_cookie = '99.130.83.99'

    parameter_order = []

    def __init__(self, configuration):
        for i in range(256):
            names = ['option_{}'.format(i)]
            if i < len(options) and hasattr(configuration, options[i][0]):
                names.append(options[i][0])
            for name in names:
                if hasattr(configuration, name):
                    setattr(self, name, getattr(configuration, name))

    def to_bytes(self):
        result = bytearray(236)

        result[0] = self.message_type
        result[1] = self.hardware_type
        result[2] = self.hardware_address_length
        result[3] = self.hops

        result[4:8] = struct.pack('>I', self.transaction_id)

        result[ 8:10] = shortpack(self.seconds_elapsed)
        result[10:12] = shortpack(self.bootp_flags)

        result[12:16] = inet_aton(self.client_ip_address)
        result[16:20] = inet_aton(self.your_ip_address)
        result[20:24] = inet_aton(self.next_server_ip_address)
        result[24:28] = inet_aton(self.relay_agent_ip_address)

        result[28:28 + self.hardware_address_length] = macpack(self.client_mac_address)

        result += inet_aton(self.magic_cookie)

        if self.options:
            for option in self.options:
                value = self.get_option(option)
                #print(option, value)
                if value is None:
                    continue
                result += bytes([option, len(value)]) + value
        result += bytes([255])
        return bytes(result)

    def get_option(self, option):
        if option < len(options) and hasattr(self, options[option][0]):
            value = getattr(self, options[option][0])
        elif hasattr(self, 'option_{}'.format(option)):
            value = getattr(self, 'option_{}'.format(option))
        else:
            return None
        function = options[option][2]
        if function and value is not None:
            value = function(value)
        return value

    @property
    def options(self):
        done = list()
        # fulfill wishes
        if self.parameter_order:
            for option in self.parameter_order:
                if option < len(options) and hasattr(self, options[option][0]) or hasattr(self, 'option_{}'.format(option)):
                    # this may break with the specification because we must try to fulfill the wishes
                    if option not in done:
                        done.append(option)
        # add my stuff
        for option, o in enumerate(options):
            if o[0] and hasattr(self, o[0]):
                if option not in done:
                    done.append(option)
        for option in range(256):
            if hasattr(self, 'option_{}'.format(option)):
                if option not in done:
                    done.append(option)
        return done

    def __str__(self):
        return str(ReadBootProtocolPacket(self.to_bytes()))

class DelayWorker(object):

    def __init__(self):
        self.closed = False
        self.queue = queue.Queue()
        self.thread = threading.Thread(target = self._delay_response_thread)
        self.thread.start()

    def _delay_response_thread(self):
        while not self.closed:
            if self.closed:
                break
            try:
                p = self.queue.get(timeout=1)
                t, func, args, kw = p
                now = time.time()
                if now < t:
                    time.sleep(0.01)
                    self.queue.put(p)
                else:
                    func(*args, **kw)
            except queue.Empty:
                continue

    def do_after(self, seconds, func, args = (), kw = {}):
        self.queue.put((time.time() + seconds, func, args, kw))

    def close(self):
        self.closed = True

class Transaction(object):

    def __init__(self, server):
        self.server = server
        self.configuration = server.configuration
        self.packets = []
        self.done_time = time.time() + self.configuration.length_of_transaction
        self.done = False
        self.do_after = self.server.delay_worker.do_after

    def is_done(self):
        return self.done or self.done_time < time.time()

    def close(self):
        self.done = True

    def receive(self, packet):
        # packet from client <-> packet.message_type == 1
        if packet.message_type == 1 and packet.dhcp_message_type == 'DHCPDISCOVER':
            self.do_after(self.configuration.dhcp_offer_after_seconds,
                          self.received_dhcp_discover, (packet,), )
        elif packet.message_type == 1 and packet.dhcp_message_type == 'DHCPREQUEST':
            self.do_after(self.configuration.dhcp_acknowledge_after_seconds,
                          self.received_dhcp_request, (packet,), )
        elif packet.message_type == 1 and packet.dhcp_message_type == 'DHCPINFORM':
            self.received_dhcp_inform(packet)
        else:
            return False
        return True

    def received_dhcp_discover(self, discovery):
        if self.is_done(): return
        self.configuration.debug('discover:\n {}'.format(str(discovery).replace('\n', '\n\t')))
        self.send_offer(discovery)

    def send_offer(self, discovery):
        # https://tools.ietf.org/html/rfc2131
        offer = WriteBootProtocolPacket(self.configuration)
        offer.parameter_order = discovery.parameter_request_list
        mac = discovery.client_mac_address
        ip = offer.your_ip_address = self.server.get_ip_address(discovery)
        # offer.client_ip_address =
        offer.transaction_id = discovery.transaction_id
        # offer.next_server_ip_address =
        offer.relay_agent_ip_address = discovery.relay_agent_ip_address
        offer.client_mac_address = mac
        offer.client_ip_address = discovery.client_ip_address or '0.0.0.0'
        offer.bootp_flags = discovery.bootp_flags
        offer.dhcp_message_type = 'DHCPOFFER'
        offer.client_identifier = mac
        self.server.broadcast(offer)

    def received_dhcp_request(self, request):
        if self.is_done(): return
        self.server.client_has_chosen(request)
        self.acknowledge(request)
        self.close()

    def acknowledge(self, request):
        ack = WriteBootProtocolPacket(self.configuration)
        ack.parameter_order = request.parameter_request_list
        ack.transaction_id = request.transaction_id
        # ack.next_server_ip_address =
        ack.bootp_flags = request.bootp_flags
        ack.relay_agent_ip_address = request.relay_agent_ip_address
        mac = request.client_mac_address
        ack.client_mac_address = mac
        requested_ip_address = request.requested_ip_address
        ack.client_ip_address = request.client_ip_address or '0.0.0.0'
        ack.your_ip_address = self.server.get_ip_address(request)
        ack.dhcp_message_type = 'DHCPACK'
        self.server.broadcast(ack)

    def received_dhcp_inform(self, inform):
        self.close()
        self.server.client_has_chosen(inform)

class DHCPServerConfiguration(object):

    dhcp_offer_after_seconds = 10
    dhcp_acknowledge_after_seconds = 10
    length_of_transaction = 40

    bind_address = ''
    network = '192.168.173.0'
    broadcast_address = '255.255.255.255'
    subnet_mask = '255.255.255.0'
    router = None # list of ips
    # 1 day is 86400
    ip_address_lease_time = 300 # seconds
    domain_name_server = None # list of ips

    host_file = 'hosts.csv'

    debug = lambda *args, **kw: None

    def load(self, file):
        with open(file) as f:
            exec(f.read(), self.__dict__)

    def adjust_if_this_computer_is_a_router(self):
        ip_addresses = get_host_ip_addresses()
        for ip in reversed(ip_addresses):
            if ip.split('.')[-1] == '1':
                self.router = [ip]
                self.domain_name_server = [ip]
                self.network = '.'.join(ip.split('.')[:-1] + ['0'])
                self.broadcast_address = '.'.join(ip.split('.')[:-1] + ['255'])
                #self.ip_forwarding_enabled = True
                #self.non_local_source_routing_enabled = True
                #self.perform_mask_discovery = True

    def all_ip_addresses(self):
        ips = ip_addresses(self.network, self.subnet_mask)
        for i in range(5):
            next(ips)
        return ips

    def network_filter(self):
        return NETWORK(self.network, self.subnet_mask)

def ip_addresses(network, subnet_mask):
    import socket, struct
    subnet_mask = struct.unpack('>I', socket.inet_aton(subnet_mask))[0]
    network = struct.unpack('>I', socket.inet_aton(network))[0]
    network = network & subnet_mask
    start = network + 1
    end = (network | (~subnet_mask & 0xffffffff))
    return (socket.inet_ntoa(struct.pack('>I', i)) for i in range(start, end))

class ALL(object):
    def __eq__(self, other):
        return True
    def __repr__(self):
        return self.__class__.__name__
ALL = ALL()

class GREATER(object):
    def __init__(self, value):
        self.value = value
    def __eq__(self, other):
        return type(self.value)(other) > self.value

class NETWORK(object):
    def __init__(self, network, subnet_mask):
        self.subnet_mask = struct.unpack('>I', inet_aton(subnet_mask))[0]
        self.network = struct.unpack('>I', inet_aton(network))[0]
    def __eq__(self, other):
        ip = struct.unpack('>I', inet_aton(other))[0]
        return ip & self.subnet_mask == self.network and \
               ip - self.network and \
               ip - self.network != ~self.subnet_mask & 0xffffffff

class CASEINSENSITIVE(object):
    def __init__(self, s):
        self.s = s.lower()
    def __eq__(self, other):
        return self.s == other.lower()

class CSVDatabase(object):

    delimiter = ';'

    def __init__(self, file_name):
        self.file_name = file_name
        self.file('a').close() # create file

    def file(self, mode = 'r'):
        return open(self.file_name, mode)

    def get(self, pattern):
        pattern = list(pattern)
        return [line for line in self.all() if pattern == line]

    def add(self, line):
        with self.file('a') as f:
            f.write(self.delimiter.join(line) + '\n')

    def delete(self, pattern):
        lines = self.all()
        lines_to_delete = self.get(pattern)
        self.file('w').close() # empty file
        for line in lines:
            if line not in lines_to_delete:
                self.add(line)

    def all(self):
        with self.file() as f:
            return [list(line.strip().split(self.delimiter)) for line in f]

class Host(object):

    def __init__(self, mac, ip, hostname, last_used):
        self.mac = mac.upper()
        self.ip = ip
        self.hostname = hostname
        self.last_used = int(last_used)

    @classmethod
    def from_tuple(cls, line):
        mac, ip, hostname, last_used = line
        last_used = int(last_used)
        return cls(mac, ip, hostname, last_used)

    @classmethod
    def from_packet(cls, packet):
        return cls(packet.client_mac_address,
                   packet.requested_ip_address or packet.client_ip_address,
                   packet.host_name or '',
                   int(time.time()))

    @staticmethod
    def get_pattern(mac = ALL, ip = ALL, hostname = ALL, last_used = ALL):
        return [mac, ip, hostname, last_used]

    def to_tuple(self):
        return [self.mac, self.ip, self.hostname, str(int(self.last_used))]

    def to_pattern(self):
        return self.get_pattern(ip = self.ip, mac = self.mac)

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

    def __eq__(self, other):
        return self.to_tuple() == other.to_tuple()

    def has_valid_ip(self):
        return self.ip and self.ip != '0.0.0.0'

class HostDatabase(object):
    def __init__(self, file_name):
        self.db = CSVDatabase(file_name)

    def get(self, **kw):
        pattern = Host.get_pattern(**kw)
        return list(map(Host.from_tuple, self.db.get(pattern)))

    def add(self, host):
        self.db.add(host.to_tuple())

    def delete(self, host = None, **kw):
        if host is None:
            pattern = Host.get_pattern(**kw)
        else:
            pattern = host.to_pattern()
        self.db.delete(pattern)

    def all(self):
        return list(map(Host.from_tuple, self.db.all()))

    def replace(self, host):
        self.delete(host)
        self.add(host)

def sorted_hosts(hosts):
    hosts = list(hosts)
    hosts.sort(key = lambda host: (host.hostname.lower(), host.mac.lower(), host.ip.lower()))
    return hosts

class DHCPServer(object):

    def __init__(self, configuration = None):
        if configuration == None:
            configuration = DHCPServerConfiguration()
        self.configuration = configuration
        self.socket = socket(type = SOCK_DGRAM)
        self.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        self.socket.bind((self.configuration.bind_address, 67))
        self.delay_worker = DelayWorker()
        self.closed = False
        self.transactions = collections.defaultdict(lambda: Transaction(self)) # id: transaction
        self.hosts = HostDatabase(self.configuration.host_file)
        self.time_started = time.time()

    def close(self):
        self.socket.close()
        self.closed = True
        self.delay_worker.close()
        for transaction in list(self.transactions.values()):
            transaction.close()

    def update(self, timeout = 0):
        try:
            reads = select.select([self.socket], [], [], timeout)[0]
        except ValueError:
            # ValueError: file descriptor cannot be a negative integer (-1)
            return
        for socket in reads:
            try:
                packet = ReadBootProtocolPacket(*socket.recvfrom(4096))
            except OSError:
                # OSError: [WinError 10038] An operation was attempted on something that is not a socket
                pass
            else:
                self.received(packet)
        for transaction_id, transaction in list(self.transactions.items()):
            if transaction.is_done():
                transaction.close()
                self.transactions.pop(transaction_id)

    def received(self, packet):
        if not self.transactions[packet.transaction_id].receive(packet):
            self.configuration.debug('received:\n {}'.format(str(packet).replace('\n', '\n\t')))

    def client_has_chosen(self, packet):
        self.configuration.debug('client_has_chosen:\n {}'.format(str(packet).replace('\n', '\n\t')))
        host = Host.from_packet(packet)
        if not host.has_valid_ip():
            return
        self.hosts.replace(host)

    def is_valid_client_address(self, address):
        if address is None:
            return False
        a = address.split('.')
        s = self.configuration.subnet_mask.split('.')
        n = self.configuration.network.split('.')
        return all(s[i] == '0' or a[i] == n[i] for i in range(4))

    def get_ip_address(self, packet):
        mac_address = packet.client_mac_address
        requested_ip_address = packet.requested_ip_address
        known_hosts = self.hosts.get(mac = CASEINSENSITIVE(mac_address))
        assigned_addresses = set(host.ip for host in self.hosts.get())
        ip = None
        if known_hosts:
            # 1. choose known ip address
            for host in known_hosts:
                if self.is_valid_client_address(host.ip):
                    ip = host.ip
            print('known ip:', ip)
        if ip is None and self.is_valid_client_address(requested_ip_address) and ip not in assigned_addresses:
            # 2. choose valid requested ip address
            ip = requested_ip_address
            print('valid ip:', ip)
        if ip is None:
            # 3. choose new, free ip address
            chosen = False
            network_hosts = self.hosts.get(ip = self.configuration.network_filter())
            for ip in self.configuration.all_ip_addresses():
                if not any(host.ip == ip for host in network_hosts):
                    chosen = True
                    break
            if not chosen:
                # 4. reuse old valid ip address
                network_hosts.sort(key = lambda host: host.last_used)
                ip = network_hosts[0].ip
                assert self.is_valid_client_address(ip)
            print('new ip:', ip)
        if not any([host.ip == ip for host in known_hosts]):
            print('add', mac_address, ip, packet.host_name)
            self.hosts.replace(Host(mac_address, ip, packet.host_name or '', time.time()))
        return ip

    @property
    def server_identifiers(self):
        return get_host_ip_addresses()

    def broadcast(self, packet):
        self.configuration.debug('broadcasting:\n {}'.format(str(packet).replace('\n', '\n\t')))
        for addr in self.server_identifiers:
            broadcast_socket = socket(type = SOCK_DGRAM)
            broadcast_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
            broadcast_socket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
            packet.server_identifier = addr
            broadcast_socket.bind((addr, 67))
            try:
                data = packet.to_bytes()
                broadcast_socket.sendto(data, ('255.255.255.255', 68))
                broadcast_socket.sendto(data, (addr, 68))
            finally:
                broadcast_socket.close()

    def run(self):
        while not self.closed:
            try:
                self.update(1)
            except KeyboardInterrupt:
                break
            except:
                traceback.print_exc()

    def run_in_thread(self):
        thread = threading.Thread(target = self.run)
        thread.start()
        return thread

    def debug_clients(self):
        for line in self.ips.all():
            line = '\t'.join(line)
            if line:
                self.configuration.debug(line)

    def get_all_hosts(self):
        return sorted_hosts(self.hosts.get())

    def get_current_hosts(self):
        return sorted_hosts(self.hosts.get(last_used = GREATER(self.time_started)))

if __name__ == '__main__':
    configuration = DHCPServerConfiguration()
    configuration.debug = print
    configuration.adjust_if_this_computer_is_a_router()
    configuration.router #+= ['192.168.0.1']
    configuration.ip_address_lease_time = 60
    server = DHCPServer(configuration)
    for ip in server.configuration.all_ip_addresses():
        assert ip == server.configuration.network_filter()
    server.run()


# def add(a, b):
#     print('함수의 결과 :',a + b)
#
#
# add(3, 7)
#
#
# #  글로벌 함수   지역 변수와 글로벌 변수는 같은 이름의 지역 변수가 있을 경우 먼저 적용 된다.
# a = 10
# def func():
#     global a
#     a += 1
#     print(a)
#
# func()

def operator(a, b):
    add_var = a+b
    subtract_var = a - b
    multiply_var = a * b
    divide_var = a / b
    return add_var, subtract_var, multiply_var,divide_var # 반환된 순서에 따라 함수에 담을 수 있다.

a, b, c, d = operator(3, 7)

print(a, b, c, d)


#!/usr/bin/env python3

import sys
import math

from common import print_tour, read_input

def distance(city1, city2):
    return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)

##greedyのサンプルコードのこのsolveの中身を書き換えました
##greedyで求めた経路から交差をなくしていきgreedyよりは短い移動距離となる方法をとりました

def solve(cities):
    N = len(cities)

    dist = [[0] * N for i in range(N)]
    for i in range(N):
        for j in range(i, N):
            dist[i][j] = dist[j][i] = distance(cities[i], cities[j])

    current_city = 0
    unvisited_cities = set(range(1, N))
    tour = [current_city]

    while unvisited_cities:
        next_city = min(unvisited_cities,
                        key=lambda city: dist[current_city][city])
        unvisited_cities.remove(next_city)
        tour.append(next_city)
        current_city = next_city

    ##ここまではgreedyのサンプルコードと一緒です！

    ##ここからのコード：greedyで求めた経路tourは交差している箇所がいくつかあるのでその交差を解いて移動距離を減らします

    tour_after = []
    x=0
    while (x != 1):
        y = 0
        for i in range(len(tour)-1):
            ##最後、元の出発点に戻ってくる時の線も考えないといけないので、範囲をlen(tour)までに設定
            for j in range(i+1,len(tour)):
                if j  == len(tour) -1:
                        j = -1
                if (dist[tour[i]][tour[i + 1]] + dist[tour[j]][tour[j + 1]]) > (dist[tour[i]][tour[j]] + dist[tour[i + 1]][tour[j + 1]]):
                    ##連続する2点を2組とり、連続２点同士(iとi+1、jとj+1)で結ぶのとiとj、i+1とj+1で結ぶ場合の距離を比べ、短い方をたどってく（短い方がクロスがないから短い方を選択してたどっていけばクロスがなくなる）
                    if j == -1:
                        tour_before =  tour[:i+1]
                        tour_after = tour[i+1:]
                        for t in range(len(tour_after)):
                            tour_before.append(tour_after[-1-t])
                        tour = tour_before
                    else:
                        tour_before = tour[:i+1]
                        tour_after = tour[i+1:j+1]
                        for l in range(len(tour_after)):
                            tour_before.append(tour_after[-1-l])
                        for h in range(j+1,len(tour)):
                            tour_before.append(tour[h])
                        tour = tour_before
                    y += 1
        if y ==  0:##クロスがなくなったらwhile文から抜ける
            x = 1
    return tour

if __name__ == '__main__':
    assert len(sys.argv) > 1
    tour = solve(read_input(sys.argv[1]))
    print_tour(tour)
    ##output_csvを書き換えます
    with open('output_'+sys.argv[1].split('.')[0][-1]+'.csv', mode='w') as f:
        f.write('index\n')
        for t in tour:
            f.write(str(t)+'\n')


#!/usr/bin/env python3
"""
Program that tracks international space station (iss)
"""

import requests
import datetime

# website
URL="http://api.open-notify.org/iss-now.json"

def main():
    resp= requests.get(URL).json()
    print(resp, "\n\n")

    # gets latitude and longitude
    long= resp['iss_position']['longitude']
    lat= resp['iss_position']['latitude']
    ts= resp['timestamp']
    ts= datetime.datetime.fromtimestamp(ts)

    # displays current location with lat and long
    print(f"CURRENT LOCATION OF THE ISS:")
    print(f"Timestamp: {ts}")
    print(f"Lon: {long}")
    print(f"Lat: {lat}")

main()


class Solution:
    # @param {string} haystack
    # @param {string} needle
    # @return {integer}
    def strStr(self, haystack, needle):
        i = 0
        n = len(haystack)
        m = len(needle)
        if m<=0 and n == 0:
            return 0
        elif n<=0:
            return -1
        elif m <=0:
            return 0
        while(i < n-m+1):
            if haystack[i:i+m] == needle:
                    return i
            i+=1
        return -1


import numpy as np
import itertools
import cv2
import os
import re

data  = open("workspace/data/nv12_3840x2160.yuv", "rb").read()
array = np.frombuffer(data, np.uint8, len(data)).reshape(2160 * 3 // 2, 3840)
nv12_base_image = cv2.cvtColor(array, cv2.COLOR_YUV2BGR_NV12)

data  = open("workspace/data/yuyv_3840x2160_yuyv422.yuv", "rb").read()
array = np.frombuffer(data, np.uint8, len(data)).reshape(2160, 3840, 2)
yuyv_base_image = cv2.cvtColor(array, cv2.COLOR_YUV2BGR_YUYV)

def get_cv_image(iwidth, iheight, owidth, oheight, interp, format):

    base = nv12_base_image
    if format == "YUYV":
        base = yuyv_base_image

    interpolations = {"nearest": cv2.INTER_NEAREST, "bilinear": cv2.INTER_LINEAR}
    return cv2.resize(base[:iheight, :iwidth], (owidth, oheight), interpolation=interpolations[interp])

def load_tensor(file):

    data = open(file, "rb").read()
    magic_number, w, h, c, b, layout, dtype_idx = np.frombuffer(data, np.uint32, 7, 0)

    assert magic_number == 0xAABBCCEF, "Invalid tensor file"

    dtype_list = [None,np.uint8,np.float32,np.float16]
    dtype      = dtype_list[dtype_idx]
    array      = np.frombuffer(data, dtype, w * h * c * b, 28)

    if layout in [3, 4, 5, 6, 7, 8, 9, 10]:
        array = array.reshape(b, h, w, c)
    elif layout in [1, 2]:
        array = array.reshape(b, c, h, w)
    return array, layout

def save_tensor_to_image(tensor, layout, file):

    if layout in [3, 4]:
        image = tensor.astype(np.uint8)
    elif layout in [5, 6, 7, 8, 9, 10]:
        image = tensor[..., :3].astype(np.uint8)
    else:
        image = tensor[:3].transpose(1, 2, 0).astype(np.uint8)

    if layout in [1, 3, 5, 7, 9]:
        image = image[..., ::-1]

    cv2.imwrite(file, image)
    return image

def fformat(fmt, vars):
    for name in re.findall("{([\S]*?)}", fmt):
        fmt = fmt.replace("{" + name + "}", str(vars[name]))
    return fmt

input_sizes  = [[3840, 2160], [2160, 1440]]
output_sizes = [[1920, 1280], [1080, 720]]
input_batch    = 1
formats = "BL,PL,YUYV".split(",")
interps = "nearest,bilinear".split(",")
dtypes  = "uint8,float32,float16".split(",")
layouts = "NCHW16_BGR,NCHW16_RGB,NCHW32_BGR,NCHW32_RGB,NCHW4_BGR,NCHW4_RGB,NCHW_BGR,NCHW_RGB,NHWC_BGR,NHWC_RGB".split(",")

for (input_width, input_height), (output_width, output_height), format, interp, dtype, layout in itertools.product(input_sizes, output_sizes, formats, interps, dtypes, layouts):

    file = fformat("workspace/{format}-{interp}-{dtype}-{layout}-{input_width}x{input_height}x{input_batch}-{output_width}x{output_height}.binary", locals())
    cmd  = fformat("./yuvtorgb --input={input_width}x{input_height}x{input_batch}/{format} \
            --output={output_width}x{output_height}/{dtype}/{layout} --interp={interp} \
            --save={file}", locals())

    with os.popen(cmd) as p:
        # perf = float(re.findall("performance: ([0-9.]+) us", p.readlines()[0])[0])
        pass

    image, int_layout = load_tensor(file)
    for i in range(image.shape[0]):
        prefix = fformat("{format}-{interp}-{dtype}-{layout}-{input_width}x{input_height}x{input_batch}-{output_width}x{output_height}", locals())
        output_image = save_tensor_to_image(image[i], int_layout, fformat("workspace/{prefix}.png", locals()))

        oheight, owidth = output_image.shape[:2]
        cv_base = get_cv_image(input_width, input_height, owidth, oheight, interp, format)
        diff    = (np.abs(cv_base.astype(int) - output_image.astype(int))).astype(np.uint8)

        diff_sum  = np.sum(diff)
        diff_mean = np.mean(diff)
        diff_max  = np.max(diff)
        diff_std  = np.std(diff)
        print(fformat("{interp}: {input_width}x{input_height}x{input_batch}/{format} to {output_width}x{output_height}/{dtype}/{layout}, diff sum = {diff_sum}, avg = {diff_mean}, max = {diff_max}, std = {diff_std}", locals()))

        if np.sum(diff) != 0:
            diff = (diff * 255).astype(np.uint8)
            cv2.imwrite(fformat("workspace/{prefix}-diff.png", locals()), diff)
            cv2.imwrite(fformat("workspace/{prefix}-cv.png", locals()), cv_base)


from urllib.request import urlopen

url = "https://www.gutenberg.org/cache/epub/64317/pg64317.txt"
local_name = "The_Great_Gatsby.txt"

def save_locally(local_name,url):
    """
    Save the book locally, so we can use it faster and no need to load every time
    :return: None
   """
    with open(local_name, "w") as local_fp:
        with urlopen(url) as fp:
            for line in fp:
                line = line.decode('utf-8-sig').replace("\n", "")
                local_fp.write(line)

save_locally("Alice’s Adventures in Wonderland","https://www.gutenberg.org/files/11/11-0.txt")
save_locally("A Tale of Two Cities","https://www.gutenberg.org/files/98/98-0.txt")

punctuation = ",;!.?-()"
def get_unique_words(local_name):

    unique_words = {}
    word_count = 0
    with open(local_name) as fp:
        for line in fp:
            # remove punctuation
            for p in punctuation:
                line = line.replace(p, " ")
            line = line.lower()
            # get the words:
            for word in line.split():
                unique_words[word] = unique_words.get(word, 0) + 1
                word_count += 1
    return unique_words,word_count

unique_words, word_count = get_unique_words(local_name)

def get_7_charachters(local_nam):

    unique_words7 = []
    for word in unique_words.keys():
        if len(word) >= 7:
            unique_words7.append(word)
    return unique_words7

unique_words7 = get_7_charachters(local_name)

def get_rank(B1,B2):
    rank = []
    if B1 > B2:
        rank.append("more")
    else:
        rank.append("less")
    return rank

UniquewordsB1, wordcountB1 = get_unique_words("The_Great_Gatsby.txt")
More_7 = get_7_charachters("The_Great_Gatsby.txt")
More_7B1 = len(More_7)
lenuniquewordsB1 = len(UniquewordsB1.keys())
unique_ratioB1 =lenuniquewordsB1/wordcountB1
print(lenuniquewordsB1, wordcountB1, unique_ratioB1)

UniquewordsB2, wordcountB2 = get_unique_words("A Tale of Two Cities")
More_72 = get_7_charachters("A Tale of Two Cities")
More_7B2 = len(More_72)
lenunqiuewordsB2 = len(UniquewordsB2.keys())
unique_ratioB2 =  lenunqiuewordsB2/ wordcountB2
print(lenunqiuewordsB2, wordcountB2, unique_ratioB2)

print(f" Author of Book 1 has a vocabulary of {lenuniquewordsB1} words, whereas author of book 2 has a vocabulary of {lenunqiuewordsB2} words\n"
      f" Therefore, the Author of Book 1 has {get_rank(lenuniquewordsB1,lenunqiuewordsB2)} vocabulary than author of book 2\n"
      f" Book 1 has {More_7B1} unique words with more than 7 characters whereas book 2 has {More_7B2}\n"
      f" Therefore, Book 1 has {get_rank(More_7B1,More_7B2)} unique words than book 2\n"
      f" The ratio between distinct words and total number of words in book 1 is {round(unique_ratioB1,4)} whereas {round(unique_ratioB2,4)} in book 2.")


import json

class DataHandler:
    def __init__(self):
        self.AllDataArray = []
        self.dataHeaders = []
        self.missingData = []
        self.lowerTimeLimitForTrends = 0
        self.higherTimeLimitForTrends = 0
        self.trendStatistics = {"acceleration" : {}, "velocity": {}, "spatial_data": {}, "time_data": []}

    def initTrendStats(self):
        labels = ["acceleration", "velocity"]
        sublabels = ["max","Q1", "Q2", "Q3", "std","mean"]
        for label in labels:
            for sublabel in sublabels:
                self.trendStatistics[label][sublabel] = {"data": [], "mean": {}}

    def checkAndGetMissingData(self, headersStr):
        toremove = "listresult"
        LEN = len(toremove)
        headersStr = headersStr[LEN:]
        headersList = headersStr.split(",")

        missingData = []

        for header in headersList:
            if not header in self.dataHeaders:
                missingData.append(header)

        self.missingData = missingData
        return missingData.count != 0

    def updateMissingData(self, header):
        try:
            indx = self.missingData.index(header)
            del self.missingData[indx]
            if not header in self.dataHeaders:
                self.dataHeaders.append(header)
        except:
            print("Index not found on missing data")

    def newDataHandle(self, dataStr):
        toremove = "dataresultMS"
        LEN = len(toremove)
        dataStr = dataStr[LEN:]
        data = json.loads(dataStr)
        self.AllDataArray.append(data)
        self.updateMissingData(data["time"])

    def getDataByMs(self, stringMS):
        result = next((item for item in self.AllDataArray if item["time"] == stringMS), None)
        return result

    def getOldestAndNewestDataDates(self):
        if len(self.AllDataArray) != 0:
            oldest = self.AllDataArray[0]["time"]
            newest = self.AllDataArray[0]["time"]
            for item in self.AllDataArray:
                if item["time"] > newest:
                    newest = item["time"]
                if item["time"] < oldest:
                    oldest = item["time"]

        return oldest, newest

    def getDataBetweenDates(self):
        lower = self.lowerTimeLimitForTrends
        higher = self.higherTimeLimitForTrends

        array = self.AllDataArray

        result = []

        for item in array:
            time = item["time"]
            time = time.replace(",",".")
            time = float(time)
            if time > lower and time < higher:
                result.append(item)

        return result

    def setTrendStatistics(self):
        trendTimeData = self.getDataBetweenDates()
        self.initTrendStats()

        cat_labels = ["acceleration", "velocity"]
        sublabels = ["max","Q1", "Q2", "Q3", "std","mean"]

        for item in trendTimeData:
            stats = item["statistics"]
            time = item["time"]
            self.trendStatistics["time_data"].append(time)
            for c_label in cat_labels:
                head_data = stats[c_label]
                for label in sublabels:
                    value = head_data[label]
                    self.trendStatistics[c_label][label]["data"].append(value)

        for label in cat_labels:
            for sublabel in sublabels:
                valueArray = self.trendStatistics[label][sublabel]["data"]
                count = 0
                total = 0
                for value in valueArray:
                    count = count + 1
                    total = total + value

                if count == 0:
                    self.trendStatistics[label][sublabel]["mean"] = -9999999
                else:
                    self.trendStatistics[label][sublabel]["mean"] = total/count


#!/usr/bin/python3
# encoding: utf-8
'''
@author: matthew hsw
@contact: murdockhou@gmail.com
@software: pycharm
@file: dataset.py
@time: 2019/7/24 下午2:25
@desc:
'''

import tensorflow as tf
import numpy as np
import random
import json
import cv2
import os
import math
from config.spm_config import spm_config as params
from utils.utils import clip, gaussian_radius, prepare_bbox, read_json, prepare_kps
from utils.data_aug import data_aug
from encoder.spm import SingleStageLabel
from pycocotools.coco import COCO

def get_dataset(num_gpus = 1, mode = 'train'):
    assert mode in ['train', 'test']

    if mode == 'train':
        json_file = params['train_json_file']
        img_path  = params['train_img_path']
    else:
        json_file = params['test_json_file']
        img_path  = params['test_img_path']

    coco = COCO(json_file)
    cat_ids = coco.getCatIds(catNms=['person'])
    img_ids = coco.getImgIds(catIds=cat_ids)

    def parser_func(img_id):
        if type(img_id) != int:
            img_id = int(img_id.numpy())
            assert type(img_id) == int

        img_info = coco.loadImgs(img_id)[0]
        ann_ids  = coco.getAnnIds(img_id, cat_ids)
        annos    = coco.loadAnns(ann_ids)

        spm = SingleStageLabel(img_info, img_path, annos)
        img, center_map, center_mask, kps_offset, kps_weight = spm(params['height'], params['width'], params['scale'], params['num_joints'])

        return img, center_map, center_mask, kps_offset, kps_weight

    def tf_parser_func(img_id):
        [img, center_map, center_mask, kps_offset, kps_weight] = tf.py_function(
            func=parser_func, inp=[img_id], Tout=[tf.float32, tf.float32, tf.float32, tf.float32, tf.float32]
        )

        img.set_shape([params['height'], params['width'], 3])
        center_map.set_shape([params['height']//params['scale'], params['width']//params['scale'], 1])
        center_mask.set_shape([params['height']//params['scale'], params['width']//params['scale'], 1])
        kps_offset.set_shape([params['height']//params['scale'], params['width']//params['scale'], params['num_joints']*2])
        kps_weight.set_shape([params['height']//params['scale'], params['width']//params['scale'], params['num_joints']*2])

        return img, center_map, center_mask, kps_offset, kps_weight

    if mode == 'train':
        random.shuffle(img_ids)
    dataset = tf.data.Dataset.from_tensor_slices(img_ids)
    dataset = dataset.map(tf_parser_func, num_parallel_calls=tf.data.experimental.AUTOTUNE)
    dataset = dataset.batch(params['batch_size'] * num_gpus, drop_remainder=True).repeat(1)
    dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)

    return dataset


import maya.cmds as cmds
import maya.api.OpenMaya as om2

def matrix_connect(driver, target):
    """connects driver to target"s offsetParentMatrix with offset! """
    # offset could be directly calculated with matrix math
    # without using a temp node
    cmds.shadingNode("multMatrix", n = "tempMM", asUtility = True)
    cmds.connectAttr(f"{target}.worldMatrix[0]", "tempMM.matrixIn[0]")
    cmds.connectAttr(f"{driver}.worldInverseMatrix[0]", "tempMM.matrixIn[1]")
    offset = cmds.getAttr("tempMM.matrixSum")
    cmds.delete("tempMM")
    # parent
    parent = cmds.listRelatives(target, p=True)[0]
    ending = str(driver).split("_")[-1]
    # connect
    name = str(driver).replace(ending, "driverMatrix_MM")
    dm = cmds.shadingNode("multMatrix", n=name, au=True)

    cmds.setAttr(f"{dm}.matrixIn[0]", offset, type="matrix") # offset
    cmds.connectAttr(f"{driver}.worldMatrix[0]", f"{dm}.matrixIn[1]")
    cmds.connectAttr(f"{parent}.worldInverseMatrix[0]", f"{dm}.matrixIn[2]")
    cmds.connectAttr(f"{dm}.matrixSum", f"{target}.offsetParentMatrix")
    cmds.xform(
        target, translation=[0, 0, 0], rotation=[0, 0, 0], scale=[1, 1, 1])

def zero_transforms(nodes):
    """
    transfers local matrix to offset parent matrix
    leaving nodes with zeroed channels
    (maintains jointOrients for joints)
    """
    objects = [nodes] if isinstance(nodes, str) else nodes
    for obj in objects:
        if cmds.nodeType(obj) == "joint":
            # get .matrix from a temp node without rotation
            # since JNTs have 0 rot after orientation
            parent = cmds.listRelatives(obj, parent=True)[0]
            temp_grp = cmds.group(n="temp_GRP", p=parent, em=True)
            cmds.matchTransform(temp_grp, obj, position=True)
            offset = cmds.getAttr(f"{temp_grp}.matrix")
            cmds.setAttr(f"{obj}.offsetParentMatrix", offset, typ="matrix")
            cmds.setAttr(f"{obj}.translate", 0,0,0)
            cmds.delete(temp_grp)
        else:
            # direct matrix muliplication with OpenMaya
            parent = cmds.listRelatives(obj, parent=True)[0]
            invparent_mtx = om2.MMatrix(
                cmds.getAttr(f"{parent}.worldInverseMatrix[0]"))
            objworld_mtx = om2.MMatrix(
                cmds.getAttr(f"{obj}.worldMatrix[0]"))
            offsetparent_mtx = objworld_mtx * invparent_mtx
            cmds.setAttr(
                f"{obj}.offsetParentMatrix", offsetparent_mtx, type="matrix")
            cmds.setAttr(f"{obj}.translate", 0,0,0)
            cmds.setAttr(f"{obj}.rotate", 0,0,0)

def get_distance(obj1, obj2):
    temp = cmds.shadingNode("distanceBetween", asUtility=True, n="tempDist")
    cmds.connectAttr(f"{obj1}.worldMatrix[0]", "tempDist.inMatrix1")
    cmds.connectAttr(f"{obj2}.worldMatrix[0]", "tempDist.inMatrix2")
    distance = cmds.getAttr("tempDist.distance")
    cmds.delete(temp)
    return distance

def attr_separator(targets):
    objects = [targets] if isinstance(targets, str) else targets
    for obj in objects:
        cmds.addAttr(
            obj,
            longName = "separator",
            niceName = "____________",
            attributeType = "enum",
            enumName = "____:")
        cmds.setAttr(
            f"{obj}.separator",
            e = True,
            channelBox = True,
            keyable = False,
            lock = True)

def insert_scaleInvJoint(controls):
    """ add invisible jnt to invert scale into a ctrl chain hierarchy """
    objects = [controls] if isinstance(controls, str) else controls
    for obj in objects:
        childCtrl = cmds.listRelatives(
            obj, children = True, type = "transform")[0]
        name = obj.replace("_CTRL", "_sclInv_JNT")
        rotateOrder = cmds.getAttr(f"{obj}.ro")
        cmds.select(cl=True)
        sclJoint = cmds.joint(n=name)
        cmds.setAttr(f"{sclJoint}.ro", rotateOrder)
        cmds.matchTransform(sclJoint, childCtrl, position = True)
        cmds.matchTransform(sclJoint, obj, rotation = True)
        cmds.parent(sclJoint, obj)
        cmds.parent(childCtrl, sclJoint)
        cmds.connectAttr(f"{obj}.scale", f"{sclJoint}.inverseScale")
        cmds.setAttr(f"{sclJoint}.drawStyle", 2) # 2 = None / Invisible

def buffer_grp(target, new_suffix="buffer_GRP"):
    """ creates a buffer group as a parent"""
    suffix = target.split("_")[-1]
    name = target.replace(f"{suffix}", new_suffix)
    parent = cmds.listRelatives(target, parent = True)
    buff_grp = cmds.group(
        n = name, parent = target, empty =True, relative = True)
    cmds.parent(buff_grp, parent)
    cmds.parent(target, buff_grp)
    return buff_grp

def connect_transforms(driver, driven, t=True, r=True, s=True):
    if t == True:
        cmds.connectAttr(f"{driver}.translate", f"{driven}.translate")
    if r == True:
        cmds.connectAttr(f"{driver}.rotate", f"{driven}.rotate")
    if s == True:
        cmds.connectAttr(f"{driver}.scale", f"{driven}.scale")

if __name__ == "__main__":

    loc = cmds.spaceLocator(n="test_LOC", r=True)[0]
    buffer_grp(loc)

    pass


import logging
import sys

def setup_logger(name: str, log_file: str, level=logging.INFO) -> logging.Logger:
    """Function setup as many loggers as you want"""

    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

    file_handler = logging.FileHandler(log_file)
    file_handler.setFormatter(formatter)

    stream_handler = logging.StreamHandler(sys.stdout)
    stream_handler.setFormatter(formatter)

    logger_instance = logging.getLogger(name)
    logger_instance.setLevel(level)
    logger_instance.addHandler(file_handler)
    logger_instance.addHandler(stream_handler)  # Add StreamHandler

    return logger_instance

def close_logger(logger_instance: logging.Logger):
    """Closes the handlers of the provided logger instance."""
    for handler in logger_instance.handlers:
        handler.close()
        logger_instance.removeHandler(handler)

# Setup your logger
my_logger = setup_logger('my_logger', 'first_logfile.log')

def main():
    # your main code here
    # perhaps some logging
    my_logger.info("Starting program...")

    try:
        # your program logic here
        # perhaps some logging
        my_logger.info("Running some task...")
    except Exception:
        # log the exception and then re-raise
        my_logger.exception("An error occurred!")
        raise
    finally:
        # We're done with logging at this point, so close the logger.
        close_logger(my_logger)

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
from django.shortcuts import render,redirect
from SGMGU.models import *
from SGMGU.forms import *
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .utiles import *
from django.http import HttpResponse,Http404
from django.db.models import Q
from django.db import models

# para buscar entre las entidades
@login_required
@permission_required(['administrador', 'especialista'])
def buscar_entidades(request):
    if request.method == "POST":
        texto = request.POST['texto_entidad'].lower()

        entidades = Entidad.objects.filter(e_nombre__icontains=texto)
    else:
        entidades = []
    entidades = paginar(request, entidades)
    context = {'entidades': entidades, 'paginas': crear_lista_pages(entidades), 'busqueda': True,
               'texto': request.POST['texto_entidad']}
    return render(request, "Entidades/gestion_entidades.html", context)

# para imprimir en la tabla las entidades

@login_required
@permission_required(['administrador', 'especialista'])
def gestion_entidades(request):
    entidades = Entidad.objects.all()
    entidades = paginar(request, entidades)
    context = {'entidades': entidades, 'paginas': crear_lista_pages(entidades)}
    return render(request, "Entidades/gestion_entidades.html", context)

# aqui registro una entidad
def registrar_entidad(request):
    if request.method == 'POST':
        form=EntidadForm(request.POST)
        if form.is_valid():
            form.save()
            messages.add_message(request, messages.SUCCESS, "La entidad se ha registrado con éxito.")
            return redirect('/entidades')
    else:
        form = EntidadForm()
    context = {'form':form}
    return render(request, "entidades/form_entidad.html", context)

# para modificar una entidad:

@login_required
@permission_required(['administrador','especialista'])
def modificar_entidad(request,id_entidad):
    entidad=Entidad.objects.get(id_codigo_entidad=id_entidad)
    if request.method == 'POST':
        form=EntidadForm(request.POST,instance=entidad)
        if form.is_valid():
            form.save()
            messages.add_message(request, messages.SUCCESS, "La entidad se ha modificado con éxito.")
            return redirect('/entidades')
    else:
        form = EntidadForm(instance=entidad)
    # Creamos el contexto
    context = {'form':form,'nombre_accion':'Modificar'}
    # Y mostramos los datos
    return render(request, "entidades/form_entidad.html", context)

# eliminar una entidad

@login_required
@permission_required(['administrador','especialista'])
def eliminar_entidad(request,id_entidad):
    entidad = Entidad.objects.get(id_codigo_entidad=id_entidad)
    entidad.estado = False
    entidad.save()
    messages.add_message(request, messages.SUCCESS, "La entidad ha sido desactivada con éxito.")
    return redirect('/entidades')


import os
import pandas as pd
import numpy as np
import faiss
import umap
from tqdm import tqdm
from gensim.models import Word2Vec
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
from evaluate import rec_eval

def load_data(file_path):
    data = pd.read_table('../dataset/ml-1m/ratings.dat', sep='::', names = ['userID','itemID','Rating','Zip-code'])
    movies = pd.read_table('../dataset/ml-1m/movies.dat',sep='::',names=['MovieID','Title','Genres'],encoding='ISO-8859-1')
    movies['content'] = movies['Title'] + '__' + movies['Genres']
    #
    tra_data, val_data = train_test_split(data, test_size=0.2)
    users_train = tra_data['userID'].unique().tolist()
    users_valid = val_data['userID'].unique().tolist()

    """训练集"""
    # 存储消费者的购买历史
    train_users = {}
    train_corpus = []
    # 用 itemID 填充列表
    for i in tqdm(users_train):
        temp = tra_data[tra_data["userID"] == i]["itemID"].tolist()
        train_users[i] = temp
        train_corpus.append(temp)
    """验证集"""
    # 存储消费者的购买历史
    valid_users = {}
    valid_corpus = []
    # 用商品代码填充列表
    for i in tqdm(users_valid):
        temp = val_data[val_data["userID"] == i]["itemID"].tolist()
        valid_users[i] = temp
        valid_corpus.append(temp)
    """建立商品字典"""
    items_dict = movies.groupby('MovieID')['content'].apply(list).to_dict()

    return train_users, train_corpus, valid_users, valid_corpus, items_dict

def visualize_emb(X):
    cluster_embedding = umap.UMAP(n_neighbors=30, min_dist=0.0,
    n_components=2, random_state=42).fit_transform(X)
    plt.figure(figsize=(10,9))
    plt.scatter(cluster_embedding[:, 0], cluster_embedding[:, 1], s=3, cmap='Spectral')
    plt.show()

def users_similarity(user_emb):
    pass

if __name__ == "__main__":
    train_users, train_corpus, valid_users, valid_corpus, items_dict = load_data('../dataset/ml-1m')
    # train_users: {user1:[item1,item2,...],user2:[item2,item5,...],...}
    # train_corpus: [[item1,item2,...],[item2,item5,...],...]
    # 训练word2vec模型
    print('开始训练word2vec...')
    model = Word2Vec(window = 10, sg = 1, hs = 0, negative = 10, alpha=0.03, min_alpha=0.0007, seed = 14)
    model.build_vocab(train_corpus, progress_per=200)
    model.train(train_corpus, total_examples = model.corpus_count, epochs=10, report_delay=1)
    model.init_sims(replace=True)
    # 打印模型
    print(model)
    # 提取向量
    X = model.wv[model.wv.key_to_index.keys()]
    # 可视化
    #visualize_emb(X)

    def similar_products(v, n = 10):
        """
        返回最相似的n个物品
        """
        # 为输入向量提取最相似的商品
        ms = model.wv.similar_by_vector(v, topn= n+1)[1:]
        # 提取相似产品的名称和相似度评分
        new_ms = []
        for j in ms:
            pair = (items_dict[j[0]][0], j[1])
            new_ms.append(pair)
        return new_ms

    def similar_products_idx(v, n = 10):
        """
        返回最相似的n个物品
        """
        # 为输入向量提取最相似的商品
        ms = model.wv.similar_by_vector(v, topn= n+1)[1:]
        return ms

    def aggregate_vectors(products):
        """
        返回购买记录的平均向量
        """
        product_vec = []
        for i in products:
            try:
                product_vec.append(model.wv[i])
            except KeyError:
                continue
            return np.mean(product_vec, axis=0)

    #=====================UserCF 推荐=======================#
    TopK = 100
    TopN = 10

    # 对train_user重建索引, 求用户向量, 求重索引的new_train_users, 只需要一次循环就能做完
    # 已有 train_users  # train_users: {user1:[item1,item2,...], user2:[item3,item4,...],...}
    count = 0
    MAP = dict()   # 对train_user重建索引,从0开始   MAP: {userID:faiss_idx, ...}
    usersVec = []  # 求用户向量, 即对看过的所有电影的向量求均值
    new_train_users = {}    # new_train_users: {faiss_idx1:[item1,item2,...],faiss_idx2:[item3,item4,...],...}
    for user,items in train_users.items():
        MAP[user] = count
        new_train_users[count] = items
        usersVec.append(aggregate_vectors(train_corpus[count]))
        count += 1
    del train_users

    # 对valid_users的userid按MAP重索引,得到new_valid_users: {faiss_idx1:[item1,item2,...],faiss_idx2:[item3,item4,...],...}
    new_valid_users = {}
    for user,items in valid_users.items():
        if user not in new_train_users:
            continue
        new_valid_users[MAP[user]] = items
    del valid_users

    # 建立用户向量索引库
    import faiss
    usersVec = np.array(usersVec)
    faiss.normalize_L2(usersVec)   # 这是inplace操作 (计算余弦相似度,先正则化,再计算内积)
    index = faiss.IndexFlatIP(100)
    index.add(usersVec)

    # 找TopK相似用户
    D, I = index.search(usersVec[list(new_valid_users.keys())], TopK+1) # TopK要+1,因为底下计算相似度会计算自身一次
    similar_users_idxs = I
    similar_users = {}  # similar_users: {faiss_idx1:{faiss_idx2:score,faiss_idx4:score,...},faiss_idx2:{...},...}
    for idx,val_user in enumerate(new_valid_users):
        similar_users[val_user] = dict()
        for iidx,s_user in enumerate(similar_users_idxs[idx]):
            similar_users[val_user][s_user] = D[idx][iidx]

    # 推荐TopN相似商品
    print('开始生成推荐列表...')
    rec_dict = {}
    rel_dict = new_valid_users
    for val_user in tqdm(new_valid_users):   # new_valid_users: {faiss_idx1:[item1,item2,...],faiss_idx2:[item3,item4,...],...}
        rec_dict[val_user] = dict()
        for user in similar_users[val_user]:
            for item in new_train_users[user]:
                if item not in new_train_users[val_user]:
                    if item not in rec_dict[val_user]:
                        rec_dict[val_user][item]=0
                    rec_dict[val_user][item] += similar_users[val_user][user]
    # rec_dict: {faiss_idx1:{item2:score,item4:score,...},faiss_idx2:{...},...}
    # 先选出每个user的TopN "item-score" 对，再提出item到最后的推荐列表, 变换后的rec_dict: {faiss_idx1:[item2,item4,...],faiss_idx2:[item3,item4,...],...}
    rec_dict = {k: sorted(v.items(), key=lambda x: x[1], reverse=True)[:TopN] for k, v in rec_dict.items()}
    rec_dict = {k: list([x[0] for x in v]) for k, v in rec_dict.items()}

    # evaluate
    rec_eval(rec_dict,rel_dict,new_train_users)


import torch

class Private(torch.nn.Module):
    def __init__(self, args):
        super(Private, self).__init__()

        self.ncha,self.size,_=args.inputsize
        self.taskcla=args.taskcla
        self.latent_dim = args.latent_dim
        self.num_tasks = args.ntasks
        self.nhid = args.units
        self.device = args.device

        self.task_out = torch.nn.ModuleList()
        for _ in range(self.num_tasks):
            self.linear = torch.nn.Sequential()
            self.linear.add_module('linear', torch.nn.Linear(self.ncha*self.size*self.size, self.latent_dim))
            self.linear.add_module('relu', torch.nn.ReLU(inplace=True))
            self.task_out.append(self.linear)

    def forward(self, x_p, task_id):
        x_p = x_p.view(x_p.size(0), -1)
        return self.task_out[task_id].forward(x_p)

class Shared(torch.nn.Module):

    def __init__(self,args):
        super(Shared, self).__init__()

        ncha,self.size,_=args.inputsize
        self.taskcla=args.taskcla
        self.latent_dim = args.latent_dim
        self.nhid = args.units
        self.nlayers = args.nlayers

        self.relu=torch.nn.ReLU()
        self.drop=torch.nn.Dropout(0.2)
        self.fc1=torch.nn.Linear(ncha*self.size*self.size, self.nhid)

        if self.nlayers == 3:
            self.fc2 = torch.nn.Linear(self.nhid, self.nhid)
            self.fc3=torch.nn.Linear(self.nhid,self.latent_dim)
        else:
            self.fc2 = torch.nn.Linear(self.nhid,self.latent_dim)

    def forward(self, x_s):

        h = x_s.view(x_s.size(0), -1)
        h = self.drop(self.relu(self.fc1(h)))
        h = self.drop(self.relu(self.fc2(h)))
        if self.nlayers == 3:
            h = self.drop(self.relu(self.fc3(h)))

        return h

class Net(torch.nn.Module):

    def __init__(self, args):
        super(Net, self).__init__()
        ncha,size,_=args.inputsize
        self.taskcla=args.taskcla
        self.latent_dim = args.latent_dim
        self.num_tasks = args.ntasks
        self.device = args.device

        if args.experiment == 'mnist5':
            self.hidden1 = 28
            self.hidden2 = 14
        elif args.experiment == 'pmnist':
            self.hidden1 = 28
            self.hidden2 = 28

        self.samples = args.samples

        self.shared = Shared(args)
        self.private = Private(args)

        self.head = torch.nn.ModuleList()
        for i in range(self.num_tasks):
            self.head.append(
                torch.nn.Sequential(
                    torch.nn.Linear(2 * self.latent_dim, self.hidden1),
                    torch.nn.ReLU(inplace=True),
                    torch.nn.Dropout(),
                    torch.nn.Linear(self.hidden1, self.hidden2),
                    torch.nn.ReLU(inplace=True),
                    torch.nn.Linear(self.hidden2, self.taskcla[i][1])
                ))

    def forward(self,x_s, x_p, tt, task_id):

        h_s = x_s.view(x_s.size(0), -1)
        h_p = x_s.view(x_p.size(0), -1)

        x_s = self.shared(h_s)
        x_p = self.private(h_p, task_id)

        x = torch.cat([x_p, x_s], dim=1)

        return torch.stack([self.head[tt[i]].forward(x[i]) for i in range(x.size(0))])

    def get_encoded_ftrs(self, x_s, x_p, task_id):
        return self.shared(x_s), self.private(x_p, task_id)

    def print_model_size(self):
        count_P = sum(p.numel() for p in self.private.parameters() if p.requires_grad)
        count_S = sum(p.numel() for p in self.shared.parameters() if p.requires_grad)
        count_H = sum(p.numel() for p in self.head.parameters() if p.requires_grad)

        print('Num parameters in S       = %s ' % (self.pretty_print(count_S)))
        print('Num parameters in P       = %s,  per task = %s ' % (self.pretty_print(count_P),self.pretty_print(count_P/self.num_tasks)))
        print('Num parameters in p       = %s,  per task = %s ' % (self.pretty_print(count_H),self.pretty_print(count_H/self.num_tasks)))
        print('Num parameters in P+p     = %s ' % self.pretty_print(count_P+count_H))
        print('-------------------------->   Total architecture size: %s parameters (%sB)' % (self.pretty_print(count_S + count_P + count_H),
                                                                    self.pretty_print(4*(count_S + count_P + count_H))))

    def pretty_print(self, num):
        magnitude=0
        while abs(num) >= 1000:
            magnitude+=1
            num/=1000.0
        return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])


#为了测试上面这个服务器，编写一个客户端程序
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#建立连接
s.connect(('localhost',9999))
#接收欢迎消息
print(s.recv(1024).decode('utf-8'))
for data in [b'Michael',b'Tracy',b'Sarah']:
    s.send(data)  #发送数据
    print(s.recv(1024).decode('utf-8'))
s.send(b'exit')
s.close()

'''
小结
用TCP协议进行Socket编程在Python中十分简单，对于客户端，要主动连接服务器的IP和指定端口，对于服务器，要首先监听指定端口，
然后，对每一个新的连接，创建一个线程或进程来处理。通常，服务器程序会无限运行下去。
同一个端口，被一个Socket绑定了以后，就不能被别的Socket绑定了。
'''


import random

from customexceptions import OutOfCardsException
import deck
from hand import Hand

class Shoe:
    """a shoe is composed of one or more decks of cards"""
    def __init__(self, deck_count):
        self.deck_count = deck_count
        self.cards = []
        self.build_shoe()
        self.shuffle()

    def build_shoe(self):
        """build shoe from multiple decks of cards"""
        for i in range(self.deck_count):
            self.cards.extend(deck.build_deck())

    def shuffle(self):
        """shuffle all cards in shoe"""
        random.shuffle(self.cards)

    def deal_hand(self):
        '''deal a hand of two cards'''
        try:
            hand = Hand()
            for i in range(2):
                hand.add_card(self.cards[0])
                self.cards.pop(0)
            return hand
        except IndexError:
            raise OutOfCardsException

    def hit(self, hand):
        '''deal a card for a hit'''
        try:
            hand.add_card(self.cards[0])
            self.cards.pop(0)
        except IndexError:
            raise OutOfCardsException


#!echo not intended for execution
# -*- coding: UTF_8 -*-

# ///////////////////////////////////////////////////////////////////////////////////
# YIANG (v2.0)
# [locked.py]
# (c) 2008-2011 Yiang Development Team
#
# HIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ///////////////////////////////////////////////////////////////////////////////////

# PySFML
import sf

# My own stuff
from stubs import *

class FloatingNotification:

    def __init__(self,alpha_scale=1.0):
        self.alpha_scale = alpha_scale

    def DrawNotification(self,text=_('(no text specified)'),scale=1.0):
        scale = max(0,min(1,scale*self.alpha_scale))

        r,g,b = self.color.r,self.color.g,self.color.b
        fg = sf.Color(r//4,g//4,b//4,int(0xff*scale))
        bg = sf.Color(r//2,g//2,b//2,int(0xff*scale))

        pos = list(self.level.ToCameraDeviceCoordinates((self.pos[0]+self.dim[0]/2,self.pos[1]+self.dim[1]/2)))
        pos[0] = max(240,pos[0])
        bb = pos[0]-200,pos[1]+5,pos[0],pos[1]+19
        shape = sf.Shape()
        shape.AddPoint(bb[0], bb[1],fg,bg )
        shape.AddPoint(bb[2], bb[1],fg,bg )
        shape.AddPoint(bb[2], bb[3],fg,bg )
        shape.AddPoint(bb[0], bb[3],fg,bg )

        shape.SetOutlineWidth(2)
        shape.EnableFill(True)
        shape.EnableOutline(True)
        Renderer.app.Draw(shape)

        rsize = 8
        text = sf.String(text,Font=FontCache.get(rsize),Size=rsize)
        text.SetPosition(bb[0]+10,bb[1]+3)
        text.SetColor(sf.Color(0xff,0xff,0xff,int(0xd0*scale)))
        Renderer.app.Draw(text)


import datetime

from django.urls import reverse

import pytest
from rest_framework import status

from notifier.models import Event
from notifier.tests.factories import EventFactory
from users.models import User
from users.tests.factories import UserFactory

@pytest.mark.django_db()
def test_read_event_list(client, token_headers):
    EventFactory()
    EventFactory()
    url = reverse("event-list")
    r = client.get(url)
    assert r.status_code == status.HTTP_401_UNAUTHORIZED
    r = client.get(url, **token_headers)
    assert r.status_code == status.HTTP_405_METHOD_NOT_ALLOWED

@pytest.mark.django_db()
def test_read_event_detail(client, token_headers):
    u = User.objects.get()
    event = EventFactory(user=u)
    url = reverse("event-detail", args=[event.id])
    r = client.get(url)
    assert r.status_code == status.HTTP_401_UNAUTHORIZED
    r = client.get(url, **token_headers)
    assert r.status_code == status.HTTP_200_OK
    assert r.data["id"] == event.id

@pytest.mark.django_db()
def test_create_event(client, token_headers):
    u = User.objects.get()
    url = reverse("event-list")
    date = datetime.date(1994, 1, 24)
    data = {
        "name": "JJ Reddick",
        "annual_date": {"year": date.year, "month": date.month, "day": date.day},
        "type": "Birthday",
    }
    r = client.post(url, data=data, content_type="application/json", **token_headers)
    assert r.status_code == status.HTTP_201_CREATED
    assert r.data["name"] == data["name"]
    assert r.data["user"] == u.id

@pytest.mark.django_db()
def test_update_event(client, token_headers):
    u = User.objects.get()
    event = EventFactory(user=u)
    url = reverse("event-detail", args=[event.id])

    name = "Something else"
    date = datetime.date(1994, 1, 1)
    _type = Event.EventType.OTHER
    assert event.name != name
    assert event.annual_date != date
    assert event.type != _type

    data = {
        "name": name,
        "annual_date": {"year": date.year, "month": date.month, "day": date.day},
        "type": _type.value,
    }
    r = client.patch(url, data=data, content_type="application/json", **token_headers)
    assert r.status_code == status.HTTP_200_OK
    assert r.data["name"] == name
    assert r.data["type"] == _type.value
    assert r.data["user"] == u.id

    event.refresh_from_db()
    assert event.name == name
    assert event.annual_date == date
    assert event.type == _type

@pytest.mark.django_db()
def test_delete_event(client, token_headers):
    u = User.objects.get()
    event = EventFactory(user=u)
    url = reverse("event-detail", args=[event.id])
    r = client.delete(url, **token_headers, content_type="application/json")
    assert r.status_code == status.HTTP_204_NO_CONTENT
    assert r.data is None
    assert not u.events.exists()

@pytest.mark.django_db()
def test_user_cant_read_or_delete_event_of_another_user(client, token_headers):
    _ = User.objects.get()
    u = UserFactory()
    u_event = EventFactory(user=u)
    url = reverse("event-detail", args=[u_event.id])
    r = client.get(url, **token_headers)  # token belongs to _
    assert r.status_code == status.HTTP_403_FORBIDDEN
    r = client.delete(url, **token_headers)  # token belongs to _
    assert r.status_code == status.HTTP_403_FORBIDDEN


import argparse
from pathlib import Path
from typing import List

import numpy as np
import pandas as pd
from pandas.core.frame import DataFrame

def main(args: argparse.Namespace):
    SEED = 42
    np.random.seed(SEED)
    df: DataFrame = pd.read_csv(args.csv_path)
    train_ratio = args.ratio[0]
    val_ratio = args.ratio[0] + args.ratio[1]
    train, validate, test = np.split(
        df.sample(frac=1, random_state=SEED), [int(train_ratio * len(df)), int(val_ratio * len(df))]
    )
    res_paths: List[Path] = [args.res_dir / f"{split}.csv" for split in ("train", "valid", "test")]
    for _df, res_path in zip([train, validate, test], res_paths):
        print(f"Save to {res_path}")
        _df.to_csv(res_path, index=False)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Split csv into trian,val,test")
    parser.add_argument("csv_path", type=Path, help="Path to csv to split.")
    parser.add_argument(
        "ratio",
        type=lambda x: list(map(float, x.split(","))),
        default="0.8,0.1,0.1",
        help="Split ratio separeted by , (e.g. 0.8,0.1,0.1)",
    )
    parser.add_argument("res_dir", type=Path, help="Path to directory in which save result")
    args = parser.parse_args()
    main(args)


from itertools import combinations
import sys
N,M = map(int,sys.stdin.readline().split())
graph =[]
for _ in range(N):
    graph.append(list(map(int,sys.stdin.readline().split())))

# 1,2 위치 세기
onecount=[]
twocount =[]
for i in range(N):
    for j in range(M):
        if graph[i][j]==0:
            onecount.append([i,j])
        if graph[i][j]==2:
            twocount.append([i,j])
# [[0, 1], [0, 2], [0, 3], [0, 6], [1, 0], [1, 1],...
# 3개를 조합을 해서 사용할 것
# -> from itertools import combinations
combin =list(combinations(onecount,3))

# [([0, 0], [0, 1], [0, 2]),    ([0, 0], [0, 1], [0, 3])....]

def bfs(a,b):
    Q = [[a,b]]
    visit =[] # 시간초과를 막기위해 만듬 ->
    dy = [0,0,1,-1]
    dx = [1,-1,0,0]
    while Q:
        s = Q.pop(0)
        newgraph[s[0]][s[1]] = 3
        for i in range(4):
            ny = s[0] + dy[i]
            nx = s[1] + dx[i]
            if nx<0 or ny<0 or nx>=M or ny>=N:
                continue
            if newgraph[ny][nx]==0:
                if [ny,nx] not in visit:
                    newgraph[s[0]][s[1]]=3
                    Q.append([ny,nx])
                    visit.append([ny,nx])

result =[]
for comb in combin:

    # newgraph= copy.deepcopy(graph)
    newgraph=[]
    for i in range(N):
        newgraph.append(graph[i][:])

    for i in range(3):
        newgraph[comb[i][0]][comb[i][1]]=1

    for i in twocount:
        bfs(i[0],i[1])

    count= sum(i.count(0) for i in newgraph)
    result.append(count)

print(result)
print(max(result))


def palindrome(a):

    if a!=0:
        result=""
        if len(a)!=0 and len(a)!=1 :
            if a[0]==a[-1]:
                return palindrome(a[1:-1])
            else:
                result="no"
        elif len(a)==0:
            result="yes"
        else:
            result="yes"
        return result

while True:
    a=input()
    if a=="0":
        break

    print(palindrome(a))


#!/usr/bin/env python
########################################################################
# File :   dirac-admin-lfn-replicas
# Author : Stuart Paterson
########################################################################
"""
    Show replicas for a (set of) LFNs
"""
__RCSID__ = "$Id$"
__VERSION__ = "$Revision: 86918 $"

from LHCbDIRAC.DataManagementSystem.Client.DMScript import DMScript, Script

if __name__ == "__main__":

  dmScript = DMScript()
  dmScript.registerFileSwitches()
  Script.registerSwitch('a', "All", "  Also show inactive replicas")
  Script.registerSwitch('', 'DiskOnly', '  Show only disk replicas')
  Script.registerSwitch('', 'PreferDisk', "  If disk replica, don't show tape replicas")
  Script.registerSwitch('', 'ForJobs', '  Select only replicas that can be used for jobs')

  Script.setUsageMessage('\n'.join([__doc__,
                                    'Usage:',
                                    '  %s [option|cfgfile] [<LFN>] [<LFN>...]' % Script.scriptName, ]))

  Script.parseCommandLine(ignoreErrors=False)

  from LHCbDIRAC.DataManagementSystem.Client.ScriptExecutors import executeLfnReplicas
  from DIRAC import exit
  exit(executeLfnReplicas(dmScript))


from eth_typing import ChecksumAddress, HexStr
from hexbytes import HexBytes
from uniswap.EtherClient.web3_client import EtherClient
from uniswap.v3.models import UncheckedTrade
from web3.types import TxReceipt

from .base import BaseContract

class SwapRouter02(BaseContract):
    """
    SwapRouter02 contract wrapper.
    Please refer official documentation:
    https://docs.uniswap.org/contracts/v2/reference/smart-contracts/router-02

    Parameters
    ----------
    client : EtherClient
        EtherClient Client
    address : ChecksumAddress
        Address of the ERC20 token smart contract
    abi_path : str
        Path to json file with ABI of the contract. By default is
        `../utils/abis/swap_router_02.abi.json`
    """

    def __init__(
        self,
        client: EtherClient,
        address: ChecksumAddress,
        abi_path: str = "../utils/abis/swap_router_02.abi.json",
    ):
        super().__init__(client.w3, address, abi_path)
        self.client = client
        self._data = None

    def _get_data(self):
        raise NotImplementedError

    @property
    def data(self):
        """NotImplementedError"""
        if self._data is None:
            self._data = self._get_data()
        return self._data

    def decode_multicall(self, payload: HexStr) -> list:
        """
        Decode provided payload with multicall data for the array of inputs.

        Parameters
        ----------
        payload : HexStr
            Encoded smart contract call.

        Returns
        -------
        list of tuples of function objects and decoded input parameters
        """
        function_name, data = self.contract.decode_function_input(payload)
        assert (
            function_name != "<Function multicall(bytes[])>"
        ), f"Not a multicall (function_name = {function_name})"
        data = data.get("data")
        return [self.contract.decode_function_input(i) for i in data]

    def swapExactTokensForTokens(
        self,
        unchecked_trade: UncheckedTrade,
        to,
        slippage: float = 0.01,
        wait=False,
    ) -> HexBytes | TxReceipt:
        """
        Run swapExactTokensForTokens from Uniswap router 2.
        It will sell Token0 for Token1.
        Please refer official documentation:
        https://docs.uniswap.org/contracts/v2/reference/smart-contracts/router-02#swapexacttokensfortokens

        Parameters
        ----------
        unchecked_trade : UncheckedTrade
            UnChecked trade from `uni.quoter.get_trade`.
        to : ChecksumAddress
            Address of recipient wallet.
        slippage : float
            [Optional]. By default 1%. Slippage in absolute value. i.e. 50% == 0.5,
            0.1% = 0.001, 5% == 0.05
        wait : bool
            [Optional]. If true, execution will be locked until transaction not been
            verified by blockchain.
            By default is False.

        Returns
        -------
        HexBytes | TxReceipt
        """
        function_call = self.functions.swapExactTokensForTokens(
            unchecked_trade.raw.inputAmount,
            int(unchecked_trade.raw.outputAmount * (1 - slippage)),
            unchecked_trade.raw.route,
            to,
        )
        transaction = function_call.build_transaction(
            {
                "chainId": self.client.chain_id,
                "from": self.client.address,
                "nonce": self.w3.eth.get_transaction_count(self.client.address),
            }
        )
        private_key = self.w3.eth.account.decrypt(
            self.client._keyfile_json, self.client._wallet_pass
        )
        signed_tx = self.client.w3.eth.account.sign_transaction(
            transaction, private_key
        )
        tx_hash = self.w3.eth.send_raw_transaction(signed_tx.rawTransaction)
        if wait:
            return self.w3.eth.wait_for_transaction_receipt(tx_hash)
        return tx_hash


import requests
from bs4 import BeautifulSoup
import time

url = "https://rhccc.ca/?p=".strip()

with open("./index.txt", "w", encoding="utf-8") as f:

    for i in range(0, 10_000):
    # for i in [734]:
        result = requests.get(url+str(i))

        if result.status_code == 404:
            f.write(f"{i}: 404 not found.")
            print(f"nothing found at p={i}")
        elif result.status_code == 200:
            src = result.content
            soup = BeautifulSoup(src, "lxml")

            title = soup.find("meta", property="og:title")
            description = soup.find("meta", property="og:description")
            site_url = soup.find("meta", property="og:url")

            pub_time = soup.find("meta", property="article:published_time")
            auth = soup.find("meta", property="twitter:data1")

            f.write("Searching at ?p={i}...\n\n")
            f.write(f"Found url at: {site_url['content']}\n" if site_url else "Found URL, but somehow did not!\n")
            f.write(f"Title: {title['content']}\n" if title else "No title!\n")
            f.write(f"Desc: {description['content']}\n" if description else "No desc!\n")
            f.write(f"Pub. date: {pub_time['content']}\n" if pub_time else "No pub date!\n")
            f.write(f"Author: {title['content']}\n" if auth else "No author!\n")
            f.write("\n\n")

            print(f"Found something at p={i}")

        time.sleep(1)


from __future__ import annotations
import numpy as np
from utils import Point

class NewtonPolynom:
    x_list: list[float]
    y_list: list[float]

    def __init__(self, points: list[Point]):
        self.x_list = [p.x for p in points]
        self.y_list = [p.y for p in points]

    def solve(self, x: float) -> Point:
        a = self.make_diff_table()
        n = len(self.x_list) - 1  # Degree of polynomial
        p = a[n]

        for k in range(1, n + 1):
            p = a[n - k] + (x - self.x_list[n - k]) * p

        return Point(x, p)

    def make_diff_table(self) -> np.ndarray[float]:
        m = len(self.x_list)

        x = np.copy(self.x_list)
        a = np.copy(self.y_list)
        for k in range(1, m):
            a[k:m] = (a[k:m] - a[k - 1]) / (x[k:m] - x[k - 1])

        return a


from enum import Enum
from typing import Optional, Union, Tuple, Type

import numpy as np
from gym import Env
from gym.core import ObsType, ActType
from gym.spaces import MultiDiscrete, Discrete

from src.models.action_definitions import *
from src.models.fly_spatial_parameters import FlySpatialParameters
from src.models.goals import GoalZone
from src.models.integrator_senses import IntegratorSensor
from src.models.odor_plumes import * #PLUME_VIDEO_X_BOUNDS, PLUME_VIDEO_Y_BOUNDS
from src.models.odor_senses import *
from src.models.reward_schemes import *
from src.models.wind_directions import WindDirections

class PlumeMotionNavigationEnvironment(Env):
    """
    This is structured like the OpenAI Gym Environments, with reset and step actions.
    When it is initialized, it takes a bunch of parameters that define how rewards are
    calculated, what the odor plume is, what the agent senses (odor features).
    Actual instances of this class are composed in motion_environment_factory.py
    This class specifies the reset and step actions that are needed for openAI gym.
    The 'render' method is part of Gym environments but isn't implemented yet.
    """

    def __init__(self,
                 rng,
                 config,
                 wind_directions: WindDirections,
                 fly_spatial_parameters: FlySpatialParameters,
                 odor_features: OdorFeatures,
                 odor_plume: OdorPlumeFromMovie,
                 reward_flag: RewardSchemeEnum,
                 action_enum: Union[Type[WalkActionEnum], Type[WalkStopActionEnum]] = WalkActionEnum,  # default is
                 # consistent with original design
                 action_class=WalkDisplacements,
                 ):
        self.prior_frame = None
        self.wind_directions = wind_directions  # given as input
        self.fly_spatial_parameters = fly_spatial_parameters  # given as input
        self.odor_features = odor_features
        self.odor_plume = odor_plume  # given as input
        self.reward_flag = reward_flag  # given as input, member of reward_enum tells how reward works
        self.observation_space = MultiDiscrete([2, 3, 3])  # This should go in the factory?
        self.action_space = Discrete(len(action_enum))
        self.action_enum = action_enum
        self.action_class: DisplacementActionClass = action_class
        self.source_radius = config['GOAL_RADIUS_MM']
        self.current_trial_walk_displacement = np.array([0, 0])
        self.rng = rng
        self.config = config
        self.max_frames = config['STOP_FRAME']
        # self.render_fig = plt.figure()
        # self.render_ax = self.render_fig.add_subplot(111)

    def reset(
            self,
            *,
            return_info: bool = False,
            options: Optional[dict] = None,
    ) -> Union[ObsType, Tuple[ObsType, dict]]:
        """
        Reinitialize the plume and the agent. Return the agent's initial observation.
        """
        #rng: np.random.Generator = np.random.default_rng(seed)
        # Step 1: get odor frame
        try:
            self.odor_plume.reset(flip=options['flip'], rng = self.rng)
        except TypeError:
            self.odor_plume.reset()

        self.prior_frame = self.odor_plume.get_previous_frame()
        odor_on = self.odor_plume.frame > self.config['CONCENTRATION_THRESHOLD']
        odor_on_indices = np.transpose(odor_on.nonzero())

        # Step 2: Initialize fly position
        try:
            x_random_bounds = options['randomization_x_bounds']
            y_random_bounds = options['randomization_y_bounds']

            valid_locations = odor_on_indices*self.config['MM_PER_PX']

            self.fly_spatial_parameters.randomize_position(rng=self.rng,
                                                           x_bounds=x_random_bounds,
                                                           y_bounds=y_random_bounds,
                                                           valid_locations=valid_locations)
        except TypeError:
            print('Got no randomization bounds')

            min_x = self.config['MIN_RESET_X_MM']
            max_x = self.config['MAX_RESET_X_MM']

            x_bounds = np.array([min_x, max_x])

            min_y = self.config['MIN_RESET_Y_MM']
            max_y = self.config['MAX_RESET_Y_MM']

            y_bounds = np.array([min_y, max_y])

            self.fly_spatial_parameters.randomize_position(rng=self.rng, x_bounds = x_bounds, y_bounds = y_bounds)

        #except KeyError:
        #    print("No bounds on randomizing fly position; using defaults")
        #   self.fly_spatial_parameters.randomize_position(rng=self.rng)

        #self.fly_spatial_parameters.randomize_orientation(rng=self.rng)

        # Smell
        self.odor_features.clear()
        self.odor_features.update(config = self.config, sensor_location=self.fly_spatial_parameters.position,
                                  odor_plume_frame=self.odor_plume.frame,
                                  prior_odor_plume_frame=self.prior_frame)

        return self.odor_features.discretize_features(config = self.config)  # Change to a method that is implemented in all feature types

    def step(self, action: ActType) -> Tuple[ObsType, float, bool, dict]:
        """
        Advance the environment, based on an action selected by the agent.
        Return the next observation, the reward, a boolean indicating whether
        the trial is over, and a dictionary of any additional info that might be needed
        """
        # Translate action level (i.e., integer denoting action) into a spatial displacement
        walk_action = self.action_enum(action)
        walk_displacement = self.walk_functions[walk_action]

        self.current_trial_walk_displacement = walk_displacement  # This can be removed

        # Update fly position using calculated action displacement
        self.fly_spatial_parameters.update_position(walk_displacement)

        # Advance odor plume
        self.prior_frame = self.odor_plume.frame

        self.odor_plume.advance(rng = self.rng)

        # Sniff
        self.odor_features.update(sensor_location=self.fly_spatial_parameters.position,
                                  odor_plume_frame=self.odor_plume.frame,
                                  prior_odor_plume_frame=self.prior_frame, config = self.config)

        reward = self.reward # this should be calculate_reward() method

        if self.odor_plume.frame_number >= self.max_frames:
            done = True
        else:
            done = False

        # add a punishment to discourage always walking upwind
        if self.fly_spatial_parameters.position[0] < self.config['WALL_MIN_X_MM']:
            reward = -10
            done = True
        elif self.fly_spatial_parameters.position[0] > self.config['WALL_MAX_X_MM']:
            reward = -10
            done = True
        elif self.fly_spatial_parameters.position[1]<self.config['WALL_MIN_Y_MM']:
            reward = -10
            done = True
        elif self.fly_spatial_parameters.position[1] > self.config['WALL_MAX_Y_MM']:
            reward = -10
            done = True

        if self.fly_spatial_parameters.distance(distance_from=self.odor_plume.source_location) <= self.source_radius:
            done = True

        # observation, reward, done, info
        return self.odor_features.discretize_features(config = self.config), \
            reward, \
            done, \
            {'concentration': self.odor_features.concentration,
             'motion_speed': self.odor_features.motion_speed,
             'gradient': self.odor_features.gradient}

    def render(self, mode="human"):
        """
        This is a method of openAI Gym Environments; but it's not yet implemented
        """
        assert mode in ["human", "rgb_array"], "Invalid mode: must be \'human\' or \'rgb_array\'"

    @property
    def walk_functions(self) -> dict[Enum, np.ndarray]:
        actions = self.action_class(wind_params=self.wind_directions, config = self.config)
        walk_functions = actions.walk_displacements
        return walk_functions

    @property
    def reward(self) -> float:  # This conditional thing should probably be selected at the model factory
        if self.reward_flag is RewardSchemeEnum.SIMPLE_ODOR_FEATURES:
            reward_scheme: RewardScheme = SimpleOdorFeatureRewardScheme(odor_features=self.odor_features)
        elif self.reward_flag is RewardSchemeEnum.GOAL_ZONE:
            reward_scheme: RewardScheme = GoalZoneRewardScheme(goal_zone=GoalZone(self.config),
                                                               test_position=self.fly_spatial_parameters.position)
        elif self.reward_flag is RewardSchemeEnum.Y_MAX:
            reward_scheme: RewardScheme = YMaxRewardScheme(y_displacement=self.current_trial_walk_displacement[1])
        else:
            reward_scheme: RewardScheme = NiragRewardScheme(odor_features=self.odor_features)
        return reward_scheme.get_reward()


import logging
import sys

# from tanapol.argparse import args

logger = logging.getLogger('tanapol')
log_format = logging.Formatter('[%(levelname)s] %(message)s')
logger.setLevel(logging.DEBUG)

stream_handler = logging.StreamHandler(stream=sys.stdout)
stream_handler.setFormatter(log_format)
# verbosity = min(2, args.v)
verbosity = 2
stream_handler.setLevel(logging.WARNING - logging.DEBUG * verbosity)
logger.addHandler(stream_handler)

def handle_exception(exc_type, exc_value, exc_traceback, **kwargs):
    logger.error("Uncaught exception",
                 exc_info=(exc_type, exc_value, exc_traceback))
    sys.__excepthook__(exc_type, exc_value, exc_traceback, **kwargs)

sys.excepthook = handle_exception


import os  # 環境変数取得のため
import slack  # SlackAPIの使用
import json  # json形式で保存
import pandas as pd  # csv形式で保存

def rename_channels(client):
    lst = pd.read_csv("data.csv").values.tolist()

    for item in lst:
        print(item)
        id=item[0]
        name=item[1]
        channels = client.conversations_rename(channel=id, name=name)

if __name__ == '__main__':
    cli = slack.WebClient(token=os.environ['SLACK_API_TOKEN'])
    channels = rename_channels(cli)


class PinLayout:

	def __init__(self, type_, title_ , subTitle_, primaryColor, backGroundColor_, body_, tinyIcon_):
			self.type 				= type_
			self.title 				= title_
			self.subtitle			= subTitle_
			self.primaryColor 	    = primaryColor
			self.backgroundColor    = backGroundColor_
			self.body 	     	    = body_
			self.tinyIcon           = tinyIcon_


# Read all file names which have csv/xlsx extension in the current folder
# Remove extra characters at the end of the second '-'

import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
existing_files = []
for f in files:
	# print(f.index('.'))
	dot_index = f.index('.')
	if(f[dot_index+1:] in ['xlsx','csv']):
		if('-' in f[2:]):
			dash_index = f.index('-',2)
			if(dash_index<5):
				if(f[:dash_index]+'.'+f[dot_index+1:] not in existing_files):
					os.rename(f,f[:dash_index]+'.'+f[dot_index+1:])
					existing_files.append(f[:dash_index]+'.'+f[dot_index+1:])
				else:
					os.rename(f,f[:dash_index]+'new.'+f[dot_index+1:])
					existing_files.append(f[:dash_index]+'new.'+f[dot_index+1:])

files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
	print(f)


def warshall_floyd(d,n):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d

def main():
    n, x = map(int, input().split())
    x -= 1
    h = list(map(int, input().split()))
    edge = [[] for _ in range(n)]
    for _ in range(n-1):
        a, b = map(int, input().split())
        a -= 1
        b -= 1
        edge[a].append(b)
        edge[b].append(a)

    def dfs(now, pre):
        cost = 0
        for v in edge[now]:
            if v == pre:
                continue
            cost_last = dfs(v, now)
            if cost_last > 0 or h[v] == 1:
                cost += cost_last + 2

        return cost

    ans = dfs(x, -1)
    print(ans)

if __name__ == "__main__":
    main()


#User function Template for python3
from collections import defaultdict
from typing import List
from queue import Queue
class Solution:
    #Function to return Breadth First Traversal of given graph.
    def bfsOfGraph(self, V: int, adj: List[List[int]]) -> List[int]:
        # code here
        res=[0]
        graph=defaultdict(list)
        for i in range(V):
            if adj[i]!=[]:
                graph[i]=adj[i]
        q=[0]
        visited={0}
        while q:
            newq=[]
            while q:
                node=q.pop(0)
                if node in graph:
                    for x in graph[node]:
                        if x not in visited:
                            visited.add(x)
                            newq.append(x)
            q=newq
            if len(newq)!=0:
                res+=newq
        return res


import os
import cv2
import numpy as np

from common.nparray_intpla import NparrayIntpla

def resize_all_img(path, out_path, dim=(128, 128)):
    names = os.listdir(path)
    for name in names:
        img = cv2.imread(os.path.join(path, name))
        ret = cv2.resize(img, dim, interpolation=cv2.INTER_CUBIC)
        cv2.imwrite(os.path.join(out_path, name), ret)
    return

def resize_all_np(path, out_path, dim=(128, 128)):
    names = os.listdir(path)
    for name in names:
        arr = np.load(os.path.join(path, name))
        arr = NparrayIntpla.clip_array(arr)
        arr = NparrayIntpla.resize2d(arr, dim)
        arr = np.expand_dims(arr, axis=2)
        np.save(os.path.join(out_path, name), arr)
    return

def remove_suffix(filename):
    dot_char = '.'
    filenames = filename.split(dot_char)
    prefixname = ''
    for i in range(len(filenames) - 1):
        if i != 0:
            prefixname += dot_char
        prefixname += filenames[i]
    return prefixname

def to_numpy_name(filename):
    prefixname = remove_suffix(filename)
    return prefixname + '.npy'