from tradingapis.bitflyer_api import pybitflyer
import keysecret as ks
import time
import datetime
import predict
import configIO
import sys
import technical_fx_hilo2
import technical_fx_turtle
import math
import configIO

class AutoTrading:

    switch_in_hour = False # if true, will be waiting for inhour position change
    order_id = ''
    init_trade_amount_buy = 0.1
    init_trade_amount_sell = 0.1
    auto_decide = True

    # for trail order
    max_profit = 0
    loss_cut_line = -100
    acc_factor = -0.02

    # position amount control
    total_margin = 50000
    least_collateral = 15000
    useable_margin = 35000
    level = 3
    max_loss = 0.025

    # panic index
    init_panic_index = 35
    panic = True

    def __init__(self):
        print("Initializing API")
        self.bitflyer_api = pybitflyer.API(api_key=str(ks.bitflyer_api), api_secret=str(ks.bitflyer_secret))

    def decide_trade_amount(self, curp ,losscut):
        safe_trade = 0.1
        if self.auto_decide:
            while curp == 0.0:
                predict.print_and_write('curp == 0 try again')
                curp = self.get_current_price(30)
            max_trade = round(self.useable_margin * self.level / curp, 2)
            safe_trade = round(self.useable_margin * self.max_loss / losscut, 2)
            predict.print_and_write('Amount control, Max trade: %.2f, safe trade: %.2f' % (max_trade, safe_trade))
            if safe_trade > max_trade:
                predict.print_and_write('Use smaller')
                safe_trade = max_trade
            self.init_trade_amount_buy = safe_trade
            self.init_trade_amount_sell = safe_trade

        if self.panic:
            buy_panic_weight = -0.025
            buy_panic_bias = 1.5
            sell_panic_weight = 0.025
            sell_panic_bias = -0.25

            panic_factor_buy = self.init_panic_index * buy_panic_weight + buy_panic_bias
            if panic_factor_buy > 1:
                panic_factor_buy = 1
            elif panic_factor_buy < 0.25:
                panic_factor_buy = 0.25
            panic_factor_sell = self.init_panic_index * sell_panic_weight + sell_panic_bias
            if panic_factor_sell > 1:
                panic_factor_sell = 1
            elif panic_factor_sell < 0.25:
                panic_factor_sell = 0.25

            self.init_trade_amount_buy = round(safe_trade * panic_factor_buy,2)
            if self.init_trade_amount_buy < 0.01:
                self.init_trade_amount_buy = 0.01
            self.init_trade_amount_sell = round(safe_trade * panic_factor_sell,2)
            if self.init_trade_amount_sell < 0.01:
                self.init_trade_amount_sell = 0.01
            predict.print_and_write('Use panic index: %.0f, buy amount %.2f, sell amount %.2f'%(self.init_panic_index, self.init_trade_amount_buy, self.init_trade_amount_sell))

    def trade_market(self, type, amount, wprice = 10000):
        self.maintance_time()

        product = 'FX_BTC_JPY'
        print('trade bitflyer')
        expire_time = 575
        try_t = 0
        while try_t < 20:
            if type == 'BUY' or type == 'buy':
                order = self.bitflyer_api.sendchildorder(product_code=product, child_order_type='MARKET',
                    side='BUY', size= str(amount))
                data2csv.data2csv(
                    [time.strftime('%b:%d:%H:%M'), 'order', 'BUY_MARKET', 'amount', '%f' % float(amount)])
                predict.print_and_write('Buy market ' +str(amount))
            elif type == "SELL" or type == "sell":
                order = self.bitflyer_api.sendchildorder(product_code=product, child_order_type='MARKET',
                                                         side='SELL', size=str(amount))
                data2csv.data2csv(
                    [time.strftime('%b:%d:%H:%M'), 'order', 'SELL_MARKET', 'amount', '%f' % float(amount)])
                predict.print_and_write('Sell market ' +str(amount))
            else:
                print("error!")
            if 'child_order_acceptance_id' in order:
                time.sleep(2)
                execute_price = self.get_execute_order()
                if execute_price != 0:
                    if type == "SELL" or type == "sell":
                        slides = float(wprice) - float(execute_price)
                        predict.print_and_write('SELL : Wish price: %f, deal price: %f, slide : %f'%(wprice, execute_price, slides))
                    elif type == "BUY" or type == "buy":
                        slides = float(execute_price) - float(wprice)
                        predict.print_and_write('BUY : Wish price: %f, deal price: %f, slide : %f'%(wprice, execute_price, slides))
                return order
            else:
                try_t += 1
                print(order)
                print('Failed, try again')
                time.sleep(20)

    # deal with maintance time
    def maintance_time(self):
        while 1:
            cur_oclock = int(time.strftime('%H:')[0:-1])
            cur_min = int(time.strftime('%M:')[0:-1])
            if (cur_oclock == 4 and cur_min >= 0 and cur_min <= 12) or (cur_oclock == 3 and cur_min >= 58):
                predict.print_and_write('Server maintenance')
                time.sleep(60)
                continue
            else:
                return

    def get_execute_order(self):
        try:
            result = self.bitflyer_api.getexecutions(product_code = 'FX_BTC_JPY',count = 1)
            #print(result['price'])
            return(float(result[0]['price']))
        except Exception:
            return (0)

    # judge if the time stamp in this hour
    def bf_timejudge(self, timestring):
        cur_time = time.gmtime()
        #time.sleep(10)
        #cur_time2 = time.gmtime()
        a = time.mktime(timestring)
        b = time.mktime(cur_time)
        tdelta = b - a
        return(tdelta)

    def get_curhour(self):
        cur_hour = datetime.datetime.fromtimestamp(time.time() - time.time() % 3600 +10)
        return(cur_hour.timestamp())

    def judge_order(self, id):
        i = 20
        while i > 0:
            try:
                order = self.get_orderbyid(id)
                if order['parent_order_state'] == 'REJECTED':
                    predict.print_and_write('Order rejected')
                    return True
                else:
                    return False
            except Exception:
                time.sleep(5)
                print(Exception)
                print('Exception Try again')
                i -= 1
        predict.print_and_write('Try many times but no result, return False without confidence')
        return False

    def get_hilo(self):
        i = 0
        while i < 100:
            try:
                hilos = technical_fx_turtle.HILO()
                result = hilos.publish_current_hilo_price()
        # result = prediction.publish_current_limit_price(periods="1H")
                sell = float(result[1])
                buy = float(result[0])
                close = float(result[2])  # the close price of last hour
                high = float(result[3])
                low =float(result[4])
                quits = float(result[5])
                quitl = float(result[6])
                return([sell, buy, close, high, low, quits, quitl])
            except Exception:
                print(Exception)
                predict.print_and_write('Try to get hilo again')
                time.sleep(10)
                i+=1
                continue

    def get_ATR(self):
        i = 0
        while i < 100:
            try:
                atrs = technical_fx_hilo2.HILO()
                result = atrs.getATR()
                # result = prediction.publish_current_limit_price(periods="1H")
                return (result)
            except Exception:
                print(Exception)
                predict.print_and_write('Try to get atr again')
                time.sleep(10)
                i += 1
                continue

    def get_orders(self, status = ''):
        #order = self.quoinex_api.get_orders()
        #order = self.quoinex_api.get_orders(status, limit)
        #ACTIVE CANCELED
        product = 'FX_BTC_JPY'
        if status != '':
            order = self.bitflyer_api.getparentorders(product_code=product, parent_order_state=status)
        else:
            order = self.bitflyer_api.getparentorders(product_code=product, count=30)
        return (order)

    def get_orderbyid(self, id):
        product = 'FX_BTC_JPY'
        i = 20
        while i > 0:
            try:
            #order = self.bitflyer_api.getparentorder(product_code=product, parent_order_acceptance_id=id)
                orders = self.get_orders()
                for i in orders:
                    if i['parent_order_acceptance_id'] == id:
                        return (i)
                print('order not find')
                return({})
            except Exception:
                print('Server is fucked off ,try again')
                time.sleep(20)
                i -= 1
                continue
        print('Try too many times, failed')
        return({})

    def get_checkin_price(self):
        p = self.bitflyer_api.getpositions(product_code='FX_BTC_JPY')
        position0 = 0.0
        checkin_price = 0.0
        #time_diff = 0
        if isinstance(p, list):
            for i in p:
                #predict.print_and_write('check in price: %f' % (i['price']))
                if i['side'] == 'SELL':
                    position0 -= i['size']
                else:
                    position0 += i['size']

            for i in p:
                checkin_price += i['size']/abs(position0) * i['price']
            #predict.print_and_write('Check in price: %f, position: %f' % (checkin_price, position0))

            # for i in p:
            #     opentime = i['open_date']
            #     time_diff = self.bf_timejudge(opentime)
            #     break

        elif isinstance(p, dict) or len(p) == 0:
            predict.print_and_write('Position not exist')
        checkin_price = math.floor(checkin_price)
        return([checkin_price, position0])

    def get_current_price(self, number):
        d = 200
        while d > 0:
            try:
                trade_history = self.bitflyer_api.executions(product_code = 'FX_BTC_JPY', count = number)
                total_size = 0.0
                cur_price = 0.0
                for i in trade_history:
                    total_size += i['size']

                for i in trade_history:
                    cur_price += i['size']/total_size * i['price']

                return(math.floor(cur_price))
            except Exception:
                print('Get price error ,try again')
                time.sleep(10)
                d -= 1
                continue
        print('Try too many times, failed')
        return 0.0

    def detect_and_trade(self, direction, line, amount):
        price = self.get_current_price(30)
        print('Price: %5.0f, Line: %5.0f' % (price, line), end='\r')
        if direction == 'buy':
            if price > line and price != 0 :
                predict.print_and_write(price)
                order = self.trade_market('buy', amount, int(price))
                predict.print_and_write(order)
                return(True)
        elif direction == 'sell':
            if price < line and price != 0 :
                predict.print_and_write(price)
                order = self.trade_market('sell', amount, int(price))
                predict.print_and_write(order)
                return(True)
        return(False)

    def trade_hour_init(self, checkins, cur_price, hilo):
        # if we have a new position in this hour, initial position and return suggested position.

        position_suggest = checkins[1]

        if hilo[2] >= hilo[1] : # if close > hi
            #TODO
            trade_mount = self.init_trade_amount_buy - checkins[1]
            if trade_mount > 0.0:
                amount_str = '%.2f' % (trade_mount)
                self.trade_market('buy', amount_str, int(cur_price))
                predict.print_and_write('Switch to long')
                position_suggest = self.init_trade_amount_buy
                self.loss_cut_line = -100
                self.acc_factor = -0.02
                self.max_profit = 0
            # buy self.init + checkins[1]

        elif hilo[2] <= hilo[0] : # if close < lo
            # TODO
            # sell self.init + checkins[1]
            trade_mount = self.init_trade_amount_sell + checkins[1]
            if trade_mount > 0.0:
                amount_str = '%.2f' % (trade_mount)
                self.trade_market('sell', amount_str,int(cur_price) )
                predict.print_and_write('Switch to short')
                position_suggest = -self.init_trade_amount_sell
                self.loss_cut_line = -100
                self.acc_factor = -0.02
                self.max_profit = 0

        elif cur_price > hilo[0] and cur_price < hilo[1]:
            predict.print_and_write('Switch to middle')
            if checkins[1] < 0.0:
                trade_mount = '%.2f' % (abs(checkins[1]))
                self.trade_market('buy', trade_mount, int(cur_price))
                predict.print_and_write('Buy short back')
            elif checkins[1] > 0.0:
                trade_mount = '%.2f' % (abs(checkins[1]))
                self.trade_market('sell', trade_mount, int(cur_price))
                predict.print_and_write('Sell long back')
            position_suggest = 0
            self.loss_cut_line = -100
            self.acc_factor = -0.02
            self.max_profit = 0

        predict.print_and_write('Suggest position:%.3f'%(float(position_suggest)))
        return(position_suggest)

        # check the position
    def get_stop_acc_line(self, atr, checkins, cur_p):
        position = checkins[1]
        check_p = checkins[0]
        init_loss_cut_factor = 2.2
        trail_max_ratio = 0.24
        trail_ratio_acc = 0.02
        max_line = 0

        profit = 0
        if position > 0.0:
            profit = cur_p - check_p
            if self.loss_cut_line == -100:
                self.loss_cut_line = check_p - init_loss_cut_factor * atr
                predict.print_and_write(
                    'Init loss cut line: %.0f' % (
                        self.loss_cut_line))
        elif position < 0.0:
            profit = check_p - cur_p
            # init the loss cut line
            if self.loss_cut_line == -100:
                self.loss_cut_line = check_p + init_loss_cut_factor * atr
                predict.print_and_write(
                    'Init loss cut line: %.0f' % (
                        self.loss_cut_line))
        predict.print_and_write('Max profit in last hour: %.0f'%profit)

        if profit > self.max_profit:
            self.max_profit = profit
            self.acc_factor += trail_ratio_acc
            if self.acc_factor > trail_max_ratio:
                self.acc_factor = trail_max_ratio
            predict.print_and_write('Max profit updated: %.0f, acc_factor: %.3f'%(self.max_profit, self.acc_factor))

            if position > 0.0:
                max_line = check_p + self.max_profit
            elif position < 0.0:
                max_line = check_p - self.max_profit

            trail_loss_cut = abs(max_line - self.loss_cut_line) * (1 - self.acc_factor)

            if position > 0.0:
                new_loss_cut_line = max_line - trail_loss_cut
                if new_loss_cut_line > self.loss_cut_line:
                    predict.print_and_write(
                        'loss cut line updated: %.0f -> %.0f' % (self.loss_cut_line, new_loss_cut_line))
                    self.loss_cut_line = new_loss_cut_line
            elif position < 0.0:
                new_loss_cut_line = max_line + trail_loss_cut
                if new_loss_cut_line < self.loss_cut_line:
                    predict.print_and_write(
                        'loss cut line updated: %.0f -> %.0f' % (self.loss_cut_line, new_loss_cut_line))
                    self.loss_cut_line = new_loss_cut_line

        else:
            trail_loss_cut = init_loss_cut_factor * atr
            if position > 0.0:
                new_loss_cut_line = check_p - trail_loss_cut
                if new_loss_cut_line > self.loss_cut_line:
                    predict.print_and_write(
                        'Profit is less than 0, loss cut line:2.2 ATR %.0f -> %.0f' % (
                        self.loss_cut_line, new_loss_cut_line))
                    self.loss_cut_line = new_loss_cut_line
            elif position < 0.0:
                new_loss_cut_line = check_p + trail_loss_cut
                if new_loss_cut_line < self.loss_cut_line:
                    predict.print_and_write(
                        'Profit is less than 0, loss cut line:2.2 ATR %.0f -> %.0f' % (
                        self.loss_cut_line, new_loss_cut_line))
                    self.loss_cut_line = new_loss_cut_line

    # detect order in hour
    # record the inital state of position
    # if position changed
    # detect the profit
    # following profit ever 1 min, if profit is starting to reduce , quite (need a trial order)
    def trade_in_hour(self, initposition, starttime, hilo, atr):
        amount_stop = abs(float('%.2f' % (initposition)))
        tdelta = self.bf_timejudge(starttime)
        self.switch_in_hour = False
        enable_other_side = True
        switch2other_side = False
        print_onec = True
        trial_loss_cut = atr
        suggest_position = initposition

        switch_line = self.loss_cut_line
        print('quit_short ', hilo[5], 'quit_long ', hilo[6])
        if initposition > 0.0 and hilo[6] > self.loss_cut_line:
            predict.print_and_write('quit line is higher than stop line, use quit %.0f to quit'%(hilo[6]))
            switch_line = hilo[6]
        elif initposition < 0.0 and hilo[5] < self.loss_cut_line:
            predict.print_and_write('quit line is lower than stop line, use quit %.0f to quit'%(hilo[5]))
            switch_line = hilo[5]

        predict.print_and_write('hi: %.0f, lo: %.0f, close: %.0f, atr: %.0f, quit: %.0f' % (hilo[1], hilo[0], hilo[2], atr, switch_line))

        if initposition > 0.0:
        # if we have a positive position, detect a change to quit and switch
            tdelta = self.bf_timejudge(starttime)
            predict.print_and_write('Detecting a chance to switch short')
            while tdelta < 3600:
                direction = 'sell'
                if not self.switch_in_hour:
                # if not switch , detecting
                    self.switch_in_hour = self.detect_and_trade(direction, switch_line, amount_stop)
                else:
                # if switch
                    if print_onec:
                        predict.print_and_write('Switch in hour')
                        suggest_position = 0
                        self.loss_cut_line = -100
                        self.acc_factor = -0.02
                        self.max_profit = 0
                        checkins = self.judge_position(suggest_position)
                        print_onec = False
                    if (not switch2other_side) and enable_other_side:
                        switch2other_side = self.detect_and_trade(direction, hilo[0], self.init_trade_amount_sell)
                    elif switch2other_side and enable_other_side:
                        suggest_position = -self.init_trade_amount_sell
                        checkins = self.judge_position(suggest_position)
                        predict.print_and_write('switch to other side')
                        self.trial_order(checkins, trial_loss_cut, starttime)
                    # trade another direction:
                time.sleep(0.8)
                tdelta = self.bf_timejudge(starttime)

        elif initposition < 0.0:
            # if we have a positive position, detect a change to quit and switch
            tdelta = self.bf_timejudge(starttime)
            predict.print_and_write('Detecting a chance to switch long')
            while tdelta < 3600:
                direction = 'buy'

                if not self.switch_in_hour:
                    # if not switch , detecting
                    self.switch_in_hour = self.detect_and_trade(direction, switch_line, amount_stop)
                else:
                    # if switch
                    if print_onec:
                        predict.print_and_write('Switch in hour')
                        suggest_position = 0
                        self.loss_cut_line = -100
                        self.acc_factor = -0.02
                        self.max_profit = 0
                        checkins = self.judge_position(suggest_position)
                        print_onec = False
                    if not switch2other_side and enable_other_side:
                        switch2other_side = self.detect_and_trade(direction, hilo[1], self.init_trade_amount_buy)
                    elif switch2other_side and enable_other_side:
                        predict.print_and_write('switch to other side')
                        suggest_position = self.init_trade_amount_buy
                        checkins = self.judge_position(suggest_position)
                        self.trial_order(checkins, trial_loss_cut, starttime)

                    # trade another direction:
                time.sleep(0.8)
                tdelta = self.bf_timejudge(starttime)

        elif initposition == 0.0 and enable_other_side:
            # if we have a positive position, detect a change to quit and switch
            tdelta = self.bf_timejudge(starttime)
            predict.print_and_write('Detecting a chance to get in')
            switch_in_hourbuy = False
            switch_in_hoursell = False
            while tdelta < 3600:
                if not self.switch_in_hour:
                    # if not switch , detecting
                    switch_in_hoursell= self.detect_and_trade('sell', hilo[0], self.init_trade_amount_sell)
                    time.sleep(0.8)
                    switch_in_hourbuy = self.detect_and_trade('buy', hilo[1], self.init_trade_amount_buy)
                    self.switch_in_hour = switch_in_hourbuy or switch_in_hoursell
                elif switch_in_hourbuy:
                    predict.print_and_write('Bulid in hour long')
                    suggest_position = float(self.init_trade_amount_buy)
                    checkins = self.judge_position(suggest_position)
                    print_onec = False
                    self.trial_order(checkins, trial_loss_cut, starttime)
                    switch_in_hourbuy = False
                elif switch_in_hoursell:
                    predict.print_and_write('Bulid in hour short')
                    suggest_position = -float(self.init_trade_amount_sell)
                    checkins = self.judge_position(suggest_position)
                    print_onec = False
                    self.trial_order(checkins, trial_loss_cut, starttime)
                    switch_in_hourbuy = False
                time.sleep(0.8)
                tdelta = self.bf_timejudge(starttime)

    def trial_order(self, checkins, trial_loss_cut, starttime):
        # Trial order keep loss less than trial_loss_cut
        profit = 0
        max_profit = 0
        pre_profit = -trial_loss_cut
        atr = trial_loss_cut
        tdelta = self.bf_timejudge(starttime)
        startt= tdelta
        predict.print_and_write('Use a trial order')
        #predict.print_and_write('Current position: %f, price: %f' % (checkins[1], checkins[0]))
        while tdelta < 3600:
            cur_price = self.get_current_price(50)
            if checkins[1] > 0:
                profit = cur_price - checkins[0]
            elif checkins[1] < 0:
                profit = checkins[0] - cur_price
            if profit > max_profit:
                max_profit = profit
                if max_profit > atr * 0.5 and max_profit < atr:
                    trial_loss_cut = atr * 0.5
                elif max_profit >= atr and max_profit< atr * 2:
                    trial_loss_cut = atr
                elif max_profit >= atr * 2:
                    trial_loss_cut = max_profit /2
                if trial_loss_cut > 15000:
                    trial_loss_cut = 15000

            dt = tdelta- startt

            if profit < pre_profit:
                # quit
                if checkins[1] > 0.0:
                    trade_mount = '%.2f' % abs(checkins[1])
                    order = self.trade_market('sell', trade_mount, int(cur_price))
                    suggest_position = 0.0
                    checks = self.judge_position(suggest_position)
                    predict.print_and_write(order)
                elif checkins[1] < 0.0:
                    trade_mount = '%.2f' % abs(checkins[1])
                    order = self.trade_market('buy', trade_mount, int(cur_price))
                    suggest_position = 0.0
                    checks = self.judge_position(suggest_position)
                    predict.print_and_write(order)

                predict.print_and_write('Quit position ,profit: %.2f, time: %d'%(profit, dt))
                return

            elif profit >= pre_profit and profit > 0:
                temp_pre_profit = profit - trial_loss_cut
                if temp_pre_profit > pre_profit:
                    pre_profit = temp_pre_profit
            print('T: %d, P: %5.0f, MP: %5.0f, L: %5.0f' %(dt, profit, max_profit, pre_profit), end='\r')
            time.sleep(0.8)
            tdelta = self.bf_timejudge(starttime)
        predict.print_and_write('Time is over, quit, final profit: %5.0f'%(profit))

    # judge if it is order succeed
    def judge_position(self, suggest_position):
        t = 0
        while t < 100000:
            checkins = self.get_checkin_price()
            if abs(suggest_position - checkins[1]) < 0.01:
                predict.print_and_write('Suggest is same as real')
                return(checkins)
            t += 1
            predict.print_and_write(
                'Position is unusual, suggest: %.3f, real: %.3f , check again' % (suggest_position, checkins[1]))
            time.sleep(5)  # in 5s , we should obvious the position change.
            if (t % 100) == 0 and t > 99 :
                predict.print_and_write('Recorrect position')
                if suggest_position - checkins[1] > 0:
                    self.trade_market('buy', '%.2f'%(suggest_position - checkins[1]))
                elif suggest_position - checkins[1] < 0:
                    self.trade_market('sell', '%.2f'%(checkins[1] -suggest_position ))
        predict.print_and_write('Something is wrong, trade but not succeed')
        return(checkins)

    def judge_condition(self): # judge position at hour start.
        time.sleep(1)
        starttime = time.gmtime(self.get_curhour())
        checkins = self.get_checkin_price()
        suggest_position = checkins[1]
        predict.print_and_write('##################################################')
        cur_price = self.get_current_price(100)
        predict.print_and_write('Start a new hour: Current price: %f' % (cur_price))
        predict.print_and_write('Check in price: %.0f, position: %.2f' % (checkins[0], checkins[1]))
        hilo = self.get_hilo()
        time.sleep(3)
        atr = round(float(self.get_ATR()),0)
        self.decide_trade_amount(cur_price, atr * 2.2)

        # if keep a position and transfor in this hour. ckeck position again:
        if (checkins[1] != 0.0 and self.switch_in_hour) or checkins[1] == 0.0:
            if checkins[1] == 0.0:
                predict.print_and_write('No position exist, trade none position')
            else:
                predict.print_and_write('Trade with position %f and init position'%checkins[1])
            suggest_position = self.trade_hour_init(checkins, cur_price, hilo)
            #self.order_id = order['parent_order_acceptance_id']

            # we should verify the order is dealing or not here
            checkins = self.judge_position(suggest_position)
            #order = self.update_order(checkins, hilo)
        if checkins[1] != 0.0:
            if checkins[1] > 0.0:
                last_peak = hilo[3]
                self.get_stop_acc_line(atr, checkins, last_peak)
            else:
                last_peak = hilo[4]
                self.get_stop_acc_line(atr, checkins, last_peak)

        self.trade_in_hour(suggest_position, starttime, hilo, atr)
        # elif checkins[1] != 0.0 and not self.switch_in_hour:
        #     predict.print_and_write('Update order')
        #     order = self.update_order(checkins, hilo)
        #     self.order_id = order['parent_order_acceptance_id']

        # perform a stop order and detect

    def get_collateral(self):
        try:
            result = self.bitflyer_api.getcollateral(product_code = 'FX_BTC_JPY')
            self.total_margin = float(result['collateral'])
            self.useable_margin = self.total_margin - self.least_collateral
            print('Useable for trading: %.0f'%self.useable_margin)
            data2csv.data2csv(result)
            predict.print_and_write(result)
        except Exception:
            predict.print_and_write(Exception)

def sendamail(title ,str):
    address = 'phoenixflame11@rakuten.jp'  # change the reciver e-mail address to yours
    username = 'goozzfgle@gmail.com'
    paswd = 'googlebaidu1'

    mail_str = '%s %s' % (str, formatdate(None, True, None))
    sender = SendMail(address, username, paswd)
    msg = MIMEText(mail_str)
    msg['Subject'] = title
    msg['From'] = username
    msg['To'] = address
    msg['Date'] = formatdate()
    sender.send_email(address, msg.as_string())

if __name__ == '__main__':
    argvs = sys.argv
    argc = len(argvs)
    autoTrading = AutoTrading()

    if argc >= 2:
        cofile = sys.argv[1]
    else:
        cofile = 'order.ini'
        #tempcf = dict()
        #tempcf['stoploss'] = {'max_profit':autoTrading.max_profit,
        #                   'loss_cut_line':autoTrading.loss_cut_line,
        #                   'acc_factor':autoTrading.acc_factor}

        #cf.save_config_order(tempcf)
    cf = configIO.configIO(config_file=cofile)
    parameters = cf.read_config_order('stoploss')
    autoTrading.max_profit = parameters['max_profit']
    autoTrading.loss_cut_line = parameters['loss_cut_line']
    autoTrading.acc_factor = parameters['acc_factor']
    predict.print_and_write('config read')

    #tdelta = autoTrading.bf_timejudge('2018-05-21T14:35:44.713')
    try_times = 20
    while 1:
        if autoTrading.panic:
            p2 = cf.read_config_order('panic')
            autoTrading.init_panic_index = p2['init_panic_index']
            print('Panic read')

        autoTrading.get_collateral()
        autoTrading.judge_condition()
        tempcf = dict()
        tempcf['stoploss'] = {'max_profit':autoTrading.max_profit,
                           'loss_cut_line':autoTrading.loss_cut_line,
                           'acc_factor':autoTrading.acc_factor}
        predict.print_and_write('config saved')
        cf.save_config_order(tempcf)

    #tdelta = autoTrading.bf_timejudge('2018-05-21T14:35:44.713')
    # while try_times > 0:
    #     try:
    #         while 1:
    #             autoTrading.judge_condition()
    #             autoTrading.get_collateral()
    #     except Exception:
    #         print(Exception)
    #         sendamail('Exception', 'exception happend')
    #         predict.print_and_write('Exception happened, try again')
    #         predict.print_and_write('Last try times: %d'%try_times)
    #         try_times -= 1


import flarecast_engine as fc

flare_class_list = ('abovem', 'abovec',)
window_list = ('24',)
issuing_time_list = ('00', '06', '12', '18')
fh = 'withfh'

for it_list in flare_class_list:
    for it_issuing in issuing_time_list:
        for it_window in window_list:
            cfg_name = 'HybridLasso_' + it_list + '_' + it_window + '_0_' \
                       + it_issuing + '_Bmix_all_' + fh + '-train.json'
            cfg_name_test = 'HybridLasso_' + it_list + '_' + it_window + '_0_' \
                            + it_issuing + '_Bmix_all_' + fh + '-predict.json'

            # train
            fc_dataset = fc.access_db(cfg_name, offline=True)
            fc_dataset.load_dataset_creazione_pkl(offline=True)
            fc_dataset.feature_df.to_pickle('data/feature_Bmix_' + it_issuing +
                                            'h_20120914_20160430_clean.pkl')
            fc_dataset.label_df.to_pickle('data/label_' + it_list +
                                          '_Bmix_' + it_issuing +
                                          'h_20120914_20160430_clean.pkl')


import boto3
import json

profile = 'KlayersProdP38'
# profile = 'KlayersDev'

config = {'table_name': 'kl.Klayers-prodp38.db', 'region': 'us-east-2'}
# config = {'table_name': 'kl.Klayers-devp38.db', 'region': 'us-west-2'}
# config = {'table_name': 'kl.Klayers-defaultp38.db', 'region': 'ap-southeast-1'}

session = boto3.session.Session(profile_name=profile, region_name=config['region'])
dynamodb = session.resource('dynamodb')
table = dynamodb.Table(config['table_name'])

items = list()
with open('output.json', 'r') as migration_file:
    for line in migration_file.readlines():
        items.append(json.loads(line))

with table.batch_writer() as batch:
    for k, item in enumerate(items):
        batch.put_item(Item=item)
        if k % 10 == 0:
            print(f"Written {k}/{len(items)} to {config['table_name']}")

print("Done")


import asyncio
import time

async def fun1():
    print("func1")
    await asyncio.sleep(3)
    print("fun1")
    return 'fun1--result'

async def fun2():
    print("func2")
    await asyncio.sleep(2)
    print("fun2")
    return 'fun2--result'

async def fun3():
    print("func3")
    await asyncio.sleep(1)
    print("fun3")
    return 'fun3--result'

async def main():
    task = [
        asyncio.create_task(fun1()),
        asyncio.create_task(fun2()),
        asyncio.create_task(fun3())
    ]
    await asyncio.wait(task)

if __name__ == '__main__':
    start = time.time()
    loop = asyncio.get_event_loop()
    # task1 = loop.create_task(fun1())
    # task2 = loop.create_task(fun2())
    # task3 = loop.create_task(fun3())
    loop.run_until_complete(main())
    # asyncio.run(main())
    # asyncio.run(asyncio.wait([fun1(), fun2(), fun3()])) # 同时执行多个任务
    end = time.time()
    print(end - start)


import random
random.seed(42)

lines = open('hot_wiki5m_all_triples.txt').readlines()
random.shuffle(lines)
div_split = [
    483142,
    59071,
    50000,
] # data from FB15K Train,Valid,Test
div_split = [int(unit/sum(div_split)*len(lines)) for unit in div_split]
split_point = [div_split[0],div_split[0]+div_split[1]]
with open('train.txt','w') as f:
    f.writelines([line for line in lines[:split_point[0]]])
with open('valid.txt','w') as f:
    f.writelines([line for line in lines[split_point[0]:split_point[1]]])
with open('test.txt','w') as f:
    f.writelines([line for line in lines[split_point[1]:]])


import argparse

parser = argparse.ArgumentParser()

parser.add_argument("values", nargs='*')
parser.add_argument("--sort", action="store_true")

args = parser.parse_args()

lst = args.values

d = dict()

for string in lst:
    key, val = string.split('=')
    d[key] = val

keys = list(d.keys())
if args.sort:
    keys.sort()

for key in keys:
    print(f"Key: {key} Value: {d[key]}")


import skimage
from skimage import io, measure
from sklearn import cluster
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math

parrots = io.imread('parrots.jpg')
parrots_float = skimage.img_as_float(parrots)
x, y, z = parrots_float.shape
obj_feat_matrix = parrots_float.reshape(x * y, z)

for j in range(5, 20):

    km = cluster.KMeans(random_state=241, n_clusters=j)
    km.fit(obj_feat_matrix)

    df = pd.DataFrame(obj_feat_matrix, columns=list('RGB'))
    df['Cluster'] = km.predict(df)

    df_mean_groups = df.groupby('Cluster').mean()
    df_median_groups = df.groupby('Cluster').median()
    df_mean = df.copy()
    for i in range(j):
        df_mean.ix[df_mean['Cluster'] == i, [0, 1, 2]] = df_mean_groups.ix[i].tolist()

    df_median = df.copy()
    for i in range(j):
        df_median.ix[df_median['Cluster'] == i, [0, 1, 2]] = df_median_groups.ix[i].tolist()

    MSE = 0

    MSE_mean = ((df.ix[:, 0:3] - df_mean.ix[:, 0:3]) ** 2).mean()
    MSE_mean = sum(MSE_mean) / 3
    PSNR_mean = 10 * math.log(pow(1, 2) / MSE_mean, 10)
    print("PSNR mean:", PSNR_mean, "j:", j)

    MSE_median = ((df.ix[:, 0:3] - df_median.ix[:, 0:3]) ** 2).median()
    MSE_median = sum(MSE_median) / 3
    PSNR_median = 10 * math.log(pow(1, 2) / MSE_median, 10)
    print("PSNR median:", PSNR_median, "j:", j)

    print()


from sense_hat import SenseHat
from time import sleep
from time import time

##################################### INTERFACE

def new_message_ui(caracters,symbols):
	"""
	demande a l'utilisateur de crer un nouveau message
	pre: caracers la liste de tout les caracteres possibles
		 symbols la liste des "images" pour le menu de confirmation
	post: un string contenant le message en clair
	"""
	#creation variables
	sense = SenseHat()
	sense.low_light = True
	new_message = ["0"]
	index = 0
	push2 = 0
	sense.show_letter(new_message[index])
	returned = False

	while index >= 0:
		caracter = new_message[index]
		for event in sense.stick.get_events():
			if returned == False:
				if event.action == "pressed":
					#suprimer le dernier caractere
					if event.direction == "middle":
						if len(new_message) > 1:
							if push2 == 1:
								new_message = new_message[:-1]
								index = len(new_message)-1
								push2 = 0
							else:
								push2 = 1

					#choisir le caractere
					elif event.direction == "up":
						push2 = 0
						new_message[index] = caracters[up_index(caracter,caracters)]
					elif event.direction == "down":
						push2 = 0
						new_message[index] = caracters[down_index(caracter,caracters)]

					#se deplacer dans le message
					elif event.direction == "left":
						push2 = 0
						if index == 0: index = 1
						index -= 1
					elif event.direction == "right":
						push2 = 0
						if index == len(new_message)-1:
							new_message.append("0")
							index += 1
						else:
							index += 1

				#fin ecriture
				elif event.action == "held":
					if event.direction == "middle":
						message = end_menu(new_message,symbols)
						returned = True
						returned_time = time()
						if message != None:
							return message
			else:
				if time() - returned_time > 0.1:
					returned = False

			sense.show_letter(new_message[index])

def end_menu(new_message,symbols):
	sense = SenseHat()
	string_message = ""
	for i in new_message:
		string_message += i
	sense.show_message(string_message)

	#demande de confirmation
	selected = 0
	sense.set_pixels(symbols[selected])
	selected = menu(symbols)
	if selected == 0:
		return string_message

def menu(menu_options):
	"""
	afiche un menu a l'ecran
	pre: menu_options la liste des "images" pour chaque option du menu
	post: l'index du choix fait dans le menu
	"""
	sense = SenseHat()
	sense.low_light = True
	menu_index = 0

	sense.set_pixels(menu_options[menu_index])
	while menu_index >= -10:
		for event in sense.stick.get_events():
			if event.action == "pressed":
				if event.direction == "middle":
					return menu_index
				elif event.direction == "up":
					menu_index += 1
					if menu_index == len(menu_options): menu_index = 0
					sense.set_pixels(menu_options[menu_index])
				elif event.direction == "down":
					if menu_index == 0: menu_index = len(menu_options)
					menu_index -= 1
					sense.set_pixels(menu_options[menu_index])

################ MANIPULATION INDEX ###################

def get_index(caracter,caracters):
	"""
	donne le numro d index de caracter dans la liste caracters
	"""
	for i,j in enumerate(caracters):
		if j == caracter:
			return i

def up_index(caracter,caracters):
	"""
	renvoie le numero suivant dans la liste caracters (boucle)
	"""
	new = get_index(caracter,caracters)
	if new == len(caracters)-1:
		return 0
	else:
		return new+1

def down_index(caracter,caracters):
	"""
	renvoie le numero precedent dans la liste caracters (boucle)
	"""
	new = get_index(caracter,caracters)
	if new == 0:
		return len(caracters)-1
	else:
		return new-1


import pygame, sys
from pygame.locals import *

def key_down_events(event, player, sprite_animation, setting, camera, enemy, menu):
    if event.key == K_RIGHT:
        player.x_change = setting.player_speed
        player.right = True
        sprite_animation.stop_left = False
    elif event.key == K_LEFT:
        player.x_change = -setting.player_speed
        player.left = True
        sprite_animation.stop_left = True
    elif event.key == K_UP:
        menu.up_arrow = True
        player.y_change = setting.jump_speed
        player.jump = True
    elif event.key == K_DOWN:
        menu.down_arrow = True
    elif event.key == K_RETURN:
        if menu.menu_select_rect.y != menu.credits_rect.centery - 2:
            setting.start_game = True

    elif event.key == K_q:
        pygame.quit()
        sys.exit()

def key_up_events(event, player, sprite_animation, menu):
     if event.key == K_RIGHT:
        player.right = False
        if player.left == False:
            player.x_change = 0
     elif event.key == K_LEFT:
        player.left = False
        if player.right == False:
            player.x_change = 0
     elif event.key == K_UP:
        player.jump = False
        menu.up_arrow = False
     elif event.key == K_DOWN:
        menu.down_arrow = False

def game_events(player, sprite_animation, setting, camera, enemy, menu):
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            key_down_events(event, player, sprite_animation, setting, camera, enemy, menu)
        elif event.type == KEYUP:
            key_up_events(event, player, sprite_animation, menu)

def update_screen(player, sprite_animation, setting, camera, enemy, menu, tile_map, death, moving_objects, coin):
    if setting.start_game:
        if enemy.collide_enemy == False: # make player visible, not dead
                player.update()
                sprite_animation.update()
        moving_objects.update()
        camera.update_camera(sprite_animation, enemy)
        tile_map.blit_map(camera, player)
        enemy.update()
        death.update()
        coin.update(camera)
    if setting.start_game == False:
        menu.update()
        reset_game(setting, camera, player, sprite_animation, enemy, moving_objects, tile_map, coin)

"""reset back to initial values"""
def reset_game(setting, camera, player, sprite_animation, enemy, moving_objects, tile_map, coin):
    setting.start_game = False
    sprite_animation.stop_left = False
    enemy.collide_enemy = False
    player.collide_box_item = False
    camera.camera_position = 0
    player.rect.x = 400
    player.rect.bottom = 750
    moving_objects.rect.x = 2000 # Asteroid 1
    moving_objects.rect_2.x = 4000 # Asteroid
    tile_map.tile_map_level[2][30] = setting.box_item
    tile_map.tile_map_level[4][17] = setting.box_item
    tile_map.tile_map_level[10][27] = setting.box_item
    tile_map.tile_map_level[10][43] = setting.box_item
    coin.coin1 = True
    coin.coin2 = True
    coin.coin3 = True
    coin.coin4 = True
    coin.coins_collected = 0
    tile_map.show_coin1 = False
    tile_map.show_coin2 = False
    tile_map.show_coin3 = False
    tile_map.show_coin4 = False


import os
import numpy as np
import matplotlib.pyplot as plt

from collections import defaultdict
from decimal import Decimal

dir_reports = os.path.dirname(os.path.realpath(__file__)) + '/reports'
dir_charts = os.path.dirname(os.path.realpath(__file__)) + '/charts'

sellers = defaultdict(list)
trust = defaultdict(list)
reputation = defaultdict(list)
image = defaultdict(list)
knowhow = defaultdict(list)
availability = defaultdict(list)
canceledSales = 0
abortedSales = 0

# Functions

def showDict(dict):
    '''
        This function shows the dictionary on the screen
    '''
    for key in dict.keys():
        for element in dict[key]:
            print(element)

def trustChart():
    '''
        This function creates a line chart that shows the thust that the buyers has in the sellers
    '''
    for buyer in trust.keys():

        sellersOf = defaultdict(list)
        plt.subplots()

        for data in trust[buyer]:
            seller = data[0]
            product = data[1]
            time = data[2]
            value = data[3]

            key = seller + "-" + product
            sellersOf[key].append((time, value))

        for seller in sellersOf.keys():
            times = []
            values = []

            for data in sellersOf[seller]:
                times.append(data[0])
                values.append(round(data[1], 2))

            plt.plot(times, values, label=seller)
            plt.xticks(range(times[0], times[len(times) - 1] + 1, 2))

        plt.title('Trust variation')
        plt.xlabel('Interactions')
        plt.ylabel('Trust values')
        plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
        plt.subplots_adjust(left=0.14, right=0.686)
        plt.savefig(dir_charts + '/' + buyer + '_trust.png')

def impressionChart(chartType):
    '''
        This function creates a line chart that shows the reputation, image or knowhow of the sellers
        @param chartType: type of chart to be shown
    '''
    fileName = None
    chartTitle = None
    yLabel = None
    impressions = None

    if chartType == 0:
        fileName = '_reputation.png'
        chartTitle = 'Reputation variation'
        yLabel = 'Reputation values'
        impressions = reputation
    elif chartType == 1:
        fileName = '_image.png'
        chartTitle = 'Image variation'
        yLabel = 'Image values'
        impressions = image
    else:
        fileName = '_knowhow.png'
        chartTitle = 'Knowhow variation'
        yLabel = 'Knowhow values'
        impressions = knowhow

    for buyer in impressions.keys():

        sellersOf = defaultdict(list)

        for data in impressions[buyer]:
            seller = data[0]
            product = data[1]
            time = data[2]

            for criterion in data[3]:
                cName = criterion[0]
                cValue = criterion[1]

                key = seller + "-" + product + "-" + cName
                sellersOf[key].append((time, cValue))

        products = defaultdict(list)

        for seller in sellersOf.keys():
            key = seller.split("-")[0] + "-" + seller.split("-")[1]
            criterion = seller.split("-")[2]
            products[key].append((criterion, sellersOf[seller]))

        for product in products.keys():
            plt.subplots()

            for data in products[product]:
                criterion = data[0]
                series = data[1]

                times = []
                values = []

                for serie in series:
                    times.append(serie[0])
                    values.append(round(serie[1],2))

                plt.plot(times, values, label=criterion)
                plt.xticks(range(times[0], times[len(times) - 1] + 1, 2))

            plt.title(chartTitle + ": " + product)
            plt.xlabel('Interactions')
            plt.ylabel(yLabel)
            plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
            plt.subplots_adjust(left=0.114, right=0.755)
            plt.savefig(dir_charts + '/' + buyer + '_' + product + fileName)

def availabilityChart():
    '''
        This function creates a line chart that shows the availability of the sellers
    '''
    for buyer in availability.keys():

        sellersOf = defaultdict(list)
        plt.subplots()

        for data in availability[buyer]:
            seller = data[0]
            product = data[1]
            time = data[2]
            value = data[3]

            key = seller + "-" + product
            sellersOf[key].append((time, value))

        for seller in sellersOf.keys():
            times = []
            values = []

            for data in sellersOf[seller]:
                times.append(data[0])
                values.append(round(data[1], 2))

            plt.plot(times, values, label=seller)
            plt.xticks(range(times[0], times[len(times) - 1] + 1, 2))

        plt.title('Availability variation')
        plt.xlabel('Interactions')
        plt.ylabel('Availability values')
        plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
        plt.subplots_adjust(left=0.14, right=0.686)
        plt.savefig(dir_charts + '/' + buyer + '_availability.png')

def salesChart():
    '''
        This function creates a stacked chart about the amount of made sales
    '''
    seriesNames = []
    seriesValues = []
    p = []
    N = 1
    y = 0
    ind = np.arange(N)
    width = 0.35

    for seller in sellers.keys():
        seriesNames.append(seller)
        seriesValues.append(sellers[seller][0])

    seriesNames.append('Canceled')
    seriesValues.append(canceledSales)

    seriesNames.append('Aborted')
    seriesValues.append(abortedSales)

    for value in seriesValues:
        if y == 0:
            p.append(plt.bar(ind, value, width))
            y = y + value
        else:
            p.append(plt.bar(ind, value, width, bottom = y))
            y = y + value

    plt.ylabel('Number of sales')
    plt.xlabel('Kind of sales')
    plt.title('Sales Report')
    plt.xticks([])
    plt.yticks(np.arange(0, y, 5))
    plt.legend(p, seriesNames, bbox_to_anchor=(1.05, 1), loc='upper left')
    plt.subplots_adjust(left=0.4, right=0.61)
    plt.savefig(dir_charts + '/sales.png')

# Main

for entry in os.listdir(dir_reports):
    if os.path.isfile(os.path.join(dir_reports, entry)):
        agent = entry.split("_")[0]
        suffix = entry.split("_")[1]

        inputFile = open(dir_reports + "/" + entry, 'r')

        for line in inputFile:
            time = int(line.split(";")[0])
            content = line.split(";")[1]

            if suffix == 'base.txt':
                if 'buyer' in agent:
                    if content.split(":")[0][1:] == 'canceled_sales':
                        canceledSales = canceledSales + int(content.split(":")[1][:-2])
                    elif content.split(":")[0][1:] == 'aborted_sales':
                        abortedSales = abortedSales + int(content.split(":")[1][:-2])
                else:
                    if content.split(":")[0][1:] == 'made_sales':
                        sellers[agent].append(int(content.split(":")[1][:-2]))

            elif suffix == 'trust.txt':
                seller = content.split(",")[0][6:]
                product = content.split(",")[1]
                value = Decimal(content.split(",")[2][:-2])
                trust[agent].append((seller, product, time, value))

            elif suffix == 'reputation.txt' or suffix == 'image.txt' or suffix == 'knowhow.txt':
                seller = content.split(",")[1]
                product = content.split(",")[3]
                c1 = content.split(",")[4][2:-1]
                c2 = content.split(",")[5][1:-1]
                c3 = content.split(",")[6][1:-2]
                v1 = Decimal(content.split(",")[7][1:])
                v2 = Decimal(content.split(",")[8])
                v3 = Decimal(content.split(",")[9][:-3])

                if suffix == 'reputation.txt':
                    reputation[agent].append((seller, product, time, [(c1, v1), (c2, v2), (c3, v3)]))
                elif suffix == 'image.txt':
                    image[agent].append((seller, product, time, [(c1, v1), (c2, v2), (c3, v3)]))
                else:
                    knowhow[agent].append((seller, product, time, [(c1, v1), (c2, v2), (c3, v3)]))

            elif suffix == 'availability.txt':
                seller = content.split(",")[0][-8:]
                product = content.split(",")[1]
                request = int(content.split(",")[2])
                helping = int(content.split(",")[3][:-2])
                value = helping / request

                availability[agent].append((seller, product, time, value))

        inputFile.close()

salesChart()
trustChart()
availabilityChart()
impressionChart(0)
impressionChart(1)
impressionChart(2)


# Task 15
# Creating a fun game using Pygame.

# Importing the game library with required functions for the program.
# Importing random numbers function.
import pygame
import random

# Getting everything started by initiating the pygame modules.
pygame.init()

# Setting the height and width of the screen.
screen_width = 1100
screen_height = 700

# Creating the screen with a 2 item sequence as specified by width and height dimensions.
screen = pygame.display.set_mode((screen_width,screen_height))

# Creating the player, enemies and prize characters.
# I created my own character images using paint.
# Assigning images to them from this folder.
player = pygame.image.load("myplayer.png")
enemy_1 = pygame.image.load("bolt.png")
enemy_2 = pygame.image.load("robot.png")
enemy_3 = pygame.image.load("bomb.png")
prize = pygame.image.load("starprize.png")

# Getting the height and width of the character images.
# This enables boundary detection.
player_height = player.get_height()
player_width = player.get_width()
enemy_1_height = enemy_1.get_height()
enemy_1_width = enemy_1.get_width()
enemy_2_height = enemy_2.get_height()
enemy_2_width = enemy_2.get_width()
enemy_3_height = enemy_3.get_height()
enemy_3_width = enemy_3.get_width()
prize_height = prize.get_height()
prize_width = prize.get_width()

# Setting x and y values for the player position.
player_X = 100
player_Y = 50

# Setting the x and y positions for the enemy characters.
enemy_1X = 900
enemy_1Y = 20
enemy_2X = 50
enemy_2Y = 700
enemy_3X = 400
enemy_3Y = 25

# Setting the x and y characters for the prize object.
prize_X = 900
prize_Y = 700

# Setting Boolean values for the up, down, left and right keys.
keyUp= False
keyDown = False
keyLeft = False
keyRight = False

# Creating the game loop.
while 1:

    screen.fill(0) # Clearing the screen.

    # Drawing character images to the screen at specified x and y positions.
    screen.blit(player, (player_X, player_Y))
    screen.blit(enemy_1, (enemy_1X, enemy_1Y))
    screen.blit(enemy_2, (enemy_2X, enemy_2Y))
    screen.blit(enemy_3, (enemy_3X, enemy_3Y))
    screen.blit(prize, (prize_X, prize_Y))

    # Updating the screen.
    pygame.display.flip()

    # Creating a loop for events in the game.
    for event in pygame.event.get():

        # Checking if the user exits the game and closing the program safely.
        if event.type == pygame.QUIT:
            pygame.quit()
            exit(0)

        # Checking if the user presses a key down.
        if event.type == pygame.KEYDOWN:

            # Testing if the key pressed is the up, down, left or right key.
            # Setting previously assigned Boolean values to true.
            if event.key == pygame.K_UP:
                keyUp = True
            if event.key == pygame.K_DOWN:
                keyDown = True
            if event.key == pygame.K_LEFT:
                keyLeft = True
            if event.key == pygame.K_RIGHT:
                keyRight = True

        # Checking if the user releases a key.
        if event.type == pygame.KEYUP:

            # Testing if the key released is up, down, left or right.
            # Setting Boolean values back to False.
            if event.key == pygame.K_UP:
                keyUp = False
            if event.key == pygame.K_DOWN:
                keyDown = False
            if event.key == pygame.K_LEFT:
                keyLeft = False
            if event.key == pygame.K_RIGHT:
                keyRight = False

    # Setting movement values for the player character if the up, down, left or right keys are pressed.
    if keyUp == True:
        if player_Y > 0 :  # Ensuring the player does not move out the top of the screen.
            player_Y -= 1
    if keyDown == True:
        if player_Y < screen_height - player_height:  # Ensuring the player does not move beyond the screen bottom.
            player_Y += 1
    if keyLeft == True:
        if player_X > 0:  #  Ensuring the player does not move beyond the left side of the screen.
            player_X -= 1
    if keyRight == True:
        if player_X < screen_width - player_width:  # Ensuring the player does not move beyond the right side of the screen.
            player_X += 1

    # Creating bounding boxes for all character images.
    # This will enable actions to occur when the player collides with an enemy or the prize.
    playerBox = pygame.Rect(player.get_rect())
    enemy_1Box = pygame.Rect(enemy_1.get_rect())
    enemy_2Box = pygame.Rect(enemy_2.get_rect())
    enemy_3Box = pygame.Rect(enemy_3.get_rect())
    prizeBox = pygame.Rect(prize.get_rect())

    # Updating playerBox position to characters' x and y positions.
    playerBox.top = player_X
    playerBox.left = player_Y
    enemy_1Box.top = enemy_1X
    enemy_1Box.left = enemy_1Y
    enemy_2Box.top = enemy_2X
    enemy_2Box.left = enemy_2Y
    enemy_3Box.top = enemy_3X
    enemy_3Box.left = enemy_3Y
    prizeBox.top = prize_X
    prizeBox.left = prize_Y

    # Testing collision of the player box with enemy boxes.
    if playerBox.colliderect(enemy_1Box) or playerBox.colliderect(enemy_2Box) or playerBox.colliderect(enemy_3Box):

        # Display losing status to the user.
        print("You lose")

        # Quitting the game and exiting the window.
        pygame.quit()
        exit(0)

    if playerBox.colliderect(prizeBox):

        # Display winning status to the user.
        print("You win")

        # Quitting the game and exiting the window.
        pygame.quit()
        exit(0)

    # If the prize exits the window before the user reaches it, they lose the game.
    if prize_Y < 0 - prize_width:

        # Displaying loser status.
        print("You lose")

        # Quitting the game and exiting the window.
        pygame.quit()
        exit(0)

    # Making the enemy and prize characters approach the player.
    enemy_1X -= 0.15
    enemy_3Y += 0.3
    enemy_2Y -= 0.1
    prize_Y -= 0.15


from arcade.gui.widgets import UIDummy, UIBorder

def test_wrap_with_default_border():
    # GIVEN
    widget = UIDummy()

    # WHEN
    with_border = widget.with_border()

    # THEN
    assert isinstance(with_border, UIBorder)
    assert with_border.rect == (-2, -2, 104, 104)

def test_wrap_with_extra_wide_border():
    # GIVEN
    border_width = 10
    widget = UIDummy()

    # WHEN
    with_border = widget.with_border(width=border_width)

    # THEN
    assert isinstance(with_border, UIBorder)
    assert with_border.rect == (-border_width, -border_width, 100 + 2 * border_width, 100 + 2 * border_width)


import os
import sys
import json
from glob import glob
import ast
import csv

import mylib

pathInput = "data/input/"
#inputTsv = pathInput + "citationNet_v3_" + "_".join(mylib.sectors).replace("/","") + ".json"
inputTsv = pathInput + "_".join(mylib.sectors).replace("/","") + "_withNames_scopusId_editedAddedMissingScopusId.tsv"

pathOutput = "data/output/"
pathAbstracts = pathOutput + "abstracts/"+ ("_".join(mylib.sectors)).replace("/", "") + "/"
fileCitingNet = pathOutput + "citingNet_" + ("_".join(mylib.sectors)).replace("/", "") + ".json"
codePrefix = "2-s2.0-"
fileDoiEidMap = pathOutput + "doiEidMap_" + ("_".join(mylib.sectors)).replace("/", "") + ".json"
eidToAuthorsFile = pathOutput + "eidToAuthors_" + ("_".join(mylib.sectors)).replace("/", "") + ".json"

outputTsv = pathOutput + "adjacencyMatrix_" + ("_".join(mylib.sectors)).replace("/", "") + ".tsv"

class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

def computeCitedNetwork(path):
	documentSet = set()
	contents = glob(path + '*.json')
	contents.sort()
	# get set of eids from the input list of dois
	for filename_withPath in contents:
		with open(filename_withPath) as json_file:
			data = json.load(json_file)
			try:
				citing = data['abstracts-retrieval-response']['coredata']['eid']
				documentSet.add(citing)
			except:
				print ('*** EID ERROR: ' + filename_withPath + " ***")

	# create the dictionary of cited papers (with empty lists of citing papers)
	citingCitedDict = dict()
	for citing in documentSet:
		citingCitedDict[citing] = []

	for filename_withPath in contents:
		with open(filename_withPath) as json_file:
			data = json.load(json_file)
			try:
				citing = data['abstracts-retrieval-response']['coredata']['eid']
				biblio = data['abstracts-retrieval-response']['item']['bibrecord']['tail']['bibliography']
				numRefs = int(biblio['@refcount'])
				for ref in biblio['reference']: #range(numRefs):
					temp = ref['ref-info']['refd-itemidlist']['itemid']
					#print (filename_withPath)
					if type(temp) is not list:
						idtype = temp['@idtype']
						code = temp['$']
						cited = codePrefix + code
						if cited in documentSet:
							citingCitedDict[citing].append(cited)
					else:
						for el in temp:
							idtype = el['@idtype']
							code = el['$']
							cited = codePrefix + code
							if idtype == 'SGR':
								if cited in documentSet:
									citingCitedDict[citing].append(cited)
			except:
				print ('*** BIBLIOGRAPHY ERROR: ' + filename_withPath + " ***")

	return citingCitedDict

def getEidToAuthors(tsv, doiEidMap):
	eidToAuthors = dict()
	with open(tsv, newline='') as csvfile:
		spamreader = csv.DictReader(csvfile, delimiter='\t')
		for row in spamreader:
			authorId = row['SCOPUS ID']
			citingDois = ast.literal_eval(row['DOIS ESISTENTI'])
			for citingDoi in citingDois:
				try:
					citingEid = doiEidMap["doi-to-eid"][citingDoi]
					if citingEid in eidToAuthors:
						temp = eidToAuthors[citingEid]
						if authorId not in temp:
							temp.append(authorId)
							eidToAuthors[citingEid] = temp
					else:
						eidToAuthors[citingEid] = [authorId]
				except:
					continue
	return eidToAuthors

def getAuthorIdsList(tsv):
	authorIdsSet = set()
	with open(tsv, newline='') as csvfile:
		spamreader = csv.DictReader(csvfile, delimiter='\t')
		for row in spamreader:
			authorId = row['SCOPUS ID']
			authorIdsSet.add(authorId)
	authorIdsList = list(authorIdsSet)
	authorIdsList.sort()
	return authorIdsList

def getAdjacencyMatrix(tsv, authorIdsList, doiEidMap, citingCitedDict, eidToAuthors):

	# initialize empty map (dict of dict)
	matrix = AutoVivification()
	for authorId1 in authorIdsList:
		for authorId2 in authorIdsList:
			matrix[authorId1][authorId2] = 0

	with open(tsv, newline='') as csvfile:
		authorsAnalyzed = set()
		spamreader = csv.DictReader(csvfile, delimiter='\t')
		for row in spamreader:
			citingAuthor = row['SCOPUS ID']
			if citingAuthor in authorsAnalyzed:
				continue
			authorsAnalyzed.add(citingAuthor)
			citingDois = ast.literal_eval(row['DOIS ESISTENTI'])
			for citingDoi in citingDois:
				try:
					citingEid = doiEidMap["doi-to-eid"][citingDoi]
					for citedEid in citingCitedDict[citingEid]:
						citedAuthors = eidToAuthors[citedEid]
						for citedAuthor in citedAuthors:
							temp = matrix[citingAuthor][citedAuthor]
							#print (temp)
							temp += 1
							matrix[citingAuthor][citedAuthor] = temp
				except:
					continue
	return matrix

#Save Adjacency Matrix to TSV file
def saveMatrixToFile(tsv, matrix, authorList):
	res = "\tCV-" + "\tCV-".join(authorList) + "\n"
	for authorIdCiting in authorList:
		line = list()
		for authorIdCited in authorList:
			line.append(str(matrix[authorIdCiting][authorIdCited]))
		res += "CV-" + authorIdCiting + "\t" + "\t".join(line) + "\n"
	text_file = open(tsv, "w")
	text_file.write(res)
	text_file.close()

# load doiEid map from file
with open(fileDoiEidMap) as json_file:
	doiEidMap = json.load(json_file)

eidToAuthors = getEidToAuthors(inputTsv, doiEidMap)

with open(eidToAuthorsFile, 'w') as fp:
	json.dump(eidToAuthors, fp, indent=4)

# compute citing network (eid-citing -> list-eids-cited) using abstracts (i.e. json files)
citingCitedDict = computeCitedNetwork(pathAbstracts)

# save the citing network (eid-citing -> list-eids-cited) to file
with open(fileCitingNet, 'w') as fp:
	json.dump(citingCitedDict, fp, indent=4)

# load the citing network (eid-citing -> list-eids-cited) from file
#with open(fileCitingNet) as json_file:
#	citingCitedDict = json.load(json_file)

authorIdsList = getAuthorIdsList(inputTsv)

adjacencyMatrix = getAdjacencyMatrix(inputTsv, authorIdsList, doiEidMap, citingCitedDict, eidToAuthors)

saveMatrixToFile(outputTsv, adjacencyMatrix, authorIdsList)

'''
with open(inputTsv) as json_file:
	data = json.load(json_file)
	# get author ids
	authorIds = list()
	for authorId in data:
		authorIds.append("cv-" +authorId)

	# initialize empty map (dict of dict)
	matrix = AutoVivification()
	for authorId1 in authorIds:
		for authorId2 in authorIds:
			matrix[authorId1][authorId2] = 0
			print (matrix[authorId1][authorId2])

	for citing in citingCitedDict:
		for cited in citingCitedDict[citing]:
			temp = matrix[citing][cited]
			print (temp)
			matrix[citing][cited] = temp + 1

	res = "\t" + "\t".join(authorIds) + "\n"
	for authorIdCiting in authorIds:
		res += authorIdauthorIdCiting
		for authorIdCited in authorIds:
			res += matrix[authorIdCiting][authorIdCited]
		res += "\n"

	print (res)

	citingMap = dict()
	for authorCited in data:
		for idCv in data[authorCited]:
			for pub in data[authorCited][idCv]["pubs"]:
				cited = pub["cited"]["doi"]
				citing = pub["citing"]["doi"]
				authorsCiting = pub["citing"]["authors"]

				for authorCitingDict in authorsCiting:
					authorCiting = authorCitingDict["authorId"]
					temp = dict()
					if authorCiting in citingMap:
						temp = citingMap[authorCited]
'''

'''
		c1	c2	...	cn
	c1
	c2
	...
	cn
'''


from cv2 import cv2 as cv

img = cv.imread('Photos/cat.jpg')
cv.imshow('Cat', img)

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Gray', gray)

# Simple Thresholding
threshold, thresh = cv.threshold(gray, 150, 255, cv.THRESH_BINARY)
cv.imshow('Simple Thresholded', thresh)

threshold, thresh_inv = cv.threshold(gray, 150, 255, cv.THRESH_BINARY_INV)
cv.imshow('Simple Thresholded Inverse', thresh_inv)

# Adapting Thresholding
adaptive_thresh = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 3)
cv.imshow('Adaptive Thresholding', adaptive_thresh)

cv.waitKey(0)


"""
Ch. 4.1: Route Between Nodes
Given a directed graph, design an algorithm to find out whether there is a route
between nodes.
"""
dg = {} # a directed graph

def is_path(graph, starting_node, ending_node):
    starting_node.visited = True
    for n in starting_node.neighbor:
        if n == ending_node:
            return True
        if not n.visited:
            if is_path(graph, neighbor, ending_node):
                return True
    return False

def is_path(graph, starting_node, ending_node):
    q = [starting_node]
    while True:
        if q == []:
            return False
        focus = q.pop()
        focus.visited = True
        for n in focus.neighbor:
            if not n.visited:
                q.append(focus, 0)
            if n == ending_node:
                return True

"""
Ch. 4.4: Check Balanced
Implement a function to check if a binary tree is balanced.
For this question, a balanced tree is defined as a tree where the heights of the
two subtrees of any node never differ by more than one.
"""

def check_balanced(root):
    if not root:
        return (0, True)
    else:
        lh, lb = check_balanced(root.left)
        rh, rb = check_balanced(root.right)
        return (max(lh, rh) + 1, False)


def swap():
    file1 = input("What is the name of file one?")
    file2 = input("What is the name of file two?")

    with open(file1, 'r') as a:
        data_a = a.read()
    with open(file2, 'r') as b:
        data_b = b.read()
    with open(file1, 'w') as a:
        a.write(data_b)
    with open(file2, 'w') as b:
        b.write(data_a)
        print("Completed! The content in ", file1, "was successfully switched with the content in ",file2,"." )
swap()


from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View

from .forms import UploadCameraImageForm
from .models import Camera, CameraImage

class Homepage(View):
    template_name = "pages/home.html"

    def get(self, request):
        try:
            cameras = Camera.objects.exclude(slug='ccf')
        except Camera.DoesNotExist:
            raise Http404("No cameras available.")

        return render(request, self.template_name, {
            'cameras': cameras,
            'camera': cameras[0],
        })

class ViewCamera(View):
    template_name = "pages/camera.html"

    def get(self, request, camera_slug):
        try:
            camera = Camera.objects.get(slug=camera_slug)
        except Camera.DoesNotExist:
            raise Http404("Camera does not exist")

        return render(request, self.template_name, {
            'camera': camera,
            'cameras': [camera, ],
            'single': True,
        })

@method_decorator(csrf_exempt, name='dispatch')
class UploadCameraImage(View):
    def post(self, request, secret):
        form = UploadCameraImageForm(request.POST, request.FILES)

        if form.is_valid():
            camera = None
            try:
                camera = Camera.objects.get(secret=secret)
            except Camera.DoesNotExist:
                pass

            if not camera:
                try:
                    camera = Camera.objects.get(ftp_username=secret)
                except Camera.DoesNotExist:
                    pass

            if not camera:
                raise Http404("Camera does not exist")

            image = CameraImage.objects.create(
                camera=camera,
                image=request.FILES['image'],
            )

            return HttpResponse('ok: #{}'.format(image.id))
        else:
            print(form.errors)
            raise Http404("Invalid image")

class GetCameraImage(View):
    def get(self, request, camera_id, width, height):
        try:
            camera = Camera.objects.get(id=camera_id)
        except Camera.DoesNotExist:
            return JsonResponse({'error': "Camera does not exist"})

        if not camera.current_image:
            return JsonResponse({'error': "No camera image (image not set)"})

        return JsonResponse(camera.current_image.get_sized_image(width, height))


from queue import Queue
from time import sleep
G = {}

letters = 'abcdefgh'
numbers = '12345678'

for w in letters:
    for h in numbers:
        G[''.join((w, h))] = set()

for x in G:
    for y in G:
        if abs((ord(x[0]) - ord(y[0])) * (ord(x[1]) - ord(y[1]))) == 2:
            G[x].add(y)
            G[y].add(x)

def calc_pathes(G, start, end):
    pathes = {v:None for v in G}
    parent = {x:None for x in G}
    used = set()
    q = Queue()
    q.put(start)
    pathes[start] = [start]
    while not q.empty():
        vertex = q.get()
        used.add(vertex)
        for neighbor in G[vertex]:
            if neighbor not in used:
                q.put(neighbor)
                parent[neighbor] = vertex
                pathes[neighbor] = pathes[vertex].copy()
                pathes[neighbor].append(neighbor)
                if neighbor == end:
                    break

    return pathes

def table_print(data):
    print('\033[0;0H\033[48:2:127:127:255m\033[0J', sep='')

    for i in range(8):
        print('\033[48:2:127:127:255m ', chr(ord('8') - i), end=' ', sep='')
        for j in range(8):
            if (i + j) % 2:
                print('\033[48:2:255:255:255m\033[30m', end='   ')
            else:
                print('\033[48:2:0:0:0m\033[38m', end='   ')
        print('\033[0m')

    print('\033[48:2:127:127:255m   ', '  '.join(map(chr, range(97, 105))), end='', sep='')

    for n, e in enumerate(data):
        i, j = ord(e[0]) - ord('a'), ord(e[1]) - ord('1')
        print('\033[{};{}H'.format(9 - j, 5 + 3 * i), end='')
        if (i + j) % 2:
            print('\033[1;48:2:0:0:0;38:2:255:255:255m', n, sep='')
        else:
            print('\033[1;48:2:255:255:255;38:2:0:0:0m', n, sep='')

    print('\033[11;0H\033[0m\033[0J', data)

start, end = input().split()
pathes = calc_pathes(G, start, end)
table_print(pathes[end])


import numpy as np

__all__ = ['imretype', 'imgrids']

def imretype(im, dtype):
    im = np.array(im)

    if im.dtype in ['float', 'float16', 'float32', 'float64']:
        im = im.astype(np.float)
    elif im.dtype == 'uint8':
        im = im.astype(np.float) / 255.
    elif im.dtype == 'uint16':
        im = im.astype(np.float) / 65535.
    else:
        raise NotImplementedError('unsupported source dtype: {0}'.format(im.dtype))

    assert np.min(im) >= 0 and np.max(im) <= 1

    if dtype in ['float', 'float16', 'float32', 'float64']:
        im = im.astype(dtype)
    elif dtype == 'uint8':
        im = (im * 255.).astype(dtype)
    elif dtype == 'uint16':
        im = (im * 65535.).astype(dtype)
    else:
        raise NotImplementedError('unsupported target dtype: {0}'.format(dtype))

    return im

def imgrids(objs, num_columns):
    grids = []
    for k in range(num_columns):
        grids.append(np.concatenate(objs[k::num_columns], axis = 0))
    return np.concatenate(grids, axis = 1)


# LeetCode: Problem 162
# Jonathan Kosasih

#A peak element is an element that is greater than its neighbors.
#
#Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
#
#The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
#
#You may imagine that nums[-1] = nums[n] = -∞.
#
#Example 1:
#Input: nums = [1,2,3,1]
#Output: 2
#Explanation: 3 is a peak element and your function should return the index number 2.
#
#Example 2:
#Input: nums = [1,2,1,3,5,6,4]
#Output: 1 or 5
#Explanation: Your function can return either index number 1 where the peak element is 2,
#             or index number 5 where the peak element is 6.
#------------------------------------------------------------------
class Solution(object):
    # iterative binary search
    def findPeakElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l = 0
        r = len(nums)-1
        while l<r:
            p = (l+r) // 2
            if(nums[p]<nums[p+1]):
                l = p+1
            else:
                r = p
        return l

sol = Solution()
example = [1,2,1,3,5,6,4]
print(str(sol.findPeakElement(example)))


import pandas as pd
import rdkit
from rdkit import Chem
from rdkit.Chem import AllChem
import argparse

#Define the src and target for torchtext to process
def run_smiles_generator(smiles):
    fp = []
    fpz = ""
    for i in range(256):
        fpz += '0'

    for i in range(len(smiles)):
        m = Chem.MolFromSmiles(smiles[i])
        try:
            fp1 = AllChem.GetMorganFingerprintAsBitVect(m, 2, nBits=256)
            fp1 = fp1.ToBitString()
            fp.append(fp1)
        except:
            fp.append(fpz)

    data = []
    for i in range(len(smiles)):
        t = []
        for j in range(len(fp[i])):
            t.append(fp[i][j])
        data.append(t)

    f1 = pd.DataFrame(data)
    st = 'MFP_'
    for i in range(256):
        col = st + str(i)
        f1=f1.rename(columns = {i:col})

    return(f1)

if __name__=='__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--input", help = "input filename")
    parser.add_argument("--output", help = "output filename")
    args = parser.parse_args()

    print('Inputfile:',args.input)
    print('Outputfile:',args.output)

    #Read input file containing uniprot_id, protein sequence, inchikey, smiles, pchembl value
    input_df = pd.read_csv("../data/"+args.input,header='infer')
    all_sequences = input_df['canonical_smiles'].values.tolist()

    #Pass the file to Autoencoder and get latent space dataframe
    ls_df = run_smiles_generator(all_sequences)

    #Write output
    ls_df.to_csv("../data/"+args.output,index=False)
    print("Morgan fingerprints generation done")


from wagtail.core.fields import StreamField, StreamValue
from graphene.types import Scalar

from graphene_django.converter import convert_django_field

class GenericStreamFieldType(Scalar):
    @staticmethod
    def serialize(stream_value: StreamValue):
        block = stream_value.stream_block
        return block.get_api_representation(stream_value)

@convert_django_field.register(StreamField)
def convert_stream_field(field: StreamField, registry=None):
    return GenericStreamFieldType(description=field.help_text,
                                  required=not field.null)


import os
import PIL.Image as Image

# array = []
# for i in range(1, 10):
#     array.append(10 - i)
# array.sort(lambda(lhs, rhs): return lhs-rhs)
# print(array)

allSize = 0

def PrintImgSize(imgPath):
    if not os.path.exists(imgPath):
        print("not found => " + imgPath)
        return
    global allSize
    imgData = Image.open(imgPath)
    # print(imgData.size)
    print(imgPath, imgData.size[0], imgData.size[1])
    allSize = allSize + imgData.size[0] * imgData.size[1]
    imgData.close()

def Load(resName, sex, direction, action):
    respath = "E:\\lycq\\resource\\assets\\movie\\body\\" + ("body" + resName + "_" + sex + "_" + direction + action) + ".png"
    PrintImgSize(respath)

def Load2(resName):
    for sex in range(0, 2):
        for dir in range(0, 5):
            Load(resName, str(sex), str(dir), "a")
            Load(resName, str(sex), str(dir), "c")
            Load(resName, str(sex), str(dir), "r")
            Load(resName, str(sex), str(dir), "s")

# Load2("000")
# Load2("001")
# Load2("002")
# for i in range(1, 13):
#     Load2(str(100 + i))

# for i in range(1, 13):
#     Load2(str(200 + i))

# for i in range(1, 13):
#     Load2(str(300 + i))

# def LoadHero(type, resName, direction, action):
#     respath = "E:\\lycq\\resource\\assets\\movie\\" + type + "\\" + (type + resName + "_" + direction + action) + ".png"
#     PrintImgSize(respath)

# def LoadHero2(type, resName):
#         for dir in range(0, 5):
#             LoadHero(type, resName, str(dir), "a")
#             LoadHero(type, resName, str(dir), "c")
#             LoadHero(type, resName, str(dir), "r")
#             LoadHero(type, resName, str(dir), "s")

# for i in range(1, 10):
#     LoadHero2("hero", str(1000 + i))

# for i in range(1, 10):
#     LoadHero2("monster", str(10000 + i))

def GetAllImgPath(fileDir):
    imgList = []
    # for fileName in os.listdir(fileDir):
    for fileDir, sub, fileList in os.walk(fileDir):
        for fileName in fileList:
            if fileName.endswith("png") or fileName.endswith(".jpg"):
                imgList.append(os.path.join(fileDir, fileName))

    # print(os.walk(fileDir))
        # if fileName.endswith("png"):
        #     imgList.append(os.path.join(fileDir, fileName))
    return imgList

def PrintSize(dir):
    for path in GetAllImgPath(dir):
        PrintImgSize(path)

PrintSize("E:\\lycq\\resource\\assets\\movie\\body")
# PrintSize("E:\\lycq\\resource\\assets\\movie\\weapon")
# PrintSize("E:\\lycq\\resource\\assets\\movie\\wing")
# PrintSize("E:\\lycq\\resource\\temp_out_movie\\wing")
# PrintSize("F:\\game\\release\\~213\\resource\\assets\\atlas2_ui")
# PrintSize("E:\\lycq\\resource\\temp_out_movie\\body")

print(allSize * 1)

# 29 541 516


import os

PATH = "image/"
def rename():
    """
    the function renames the images in output/image folder
    """
    for count, file_name in enumerate(os.listdir(PATH)):
        dst = "output" + str(count) + ".jpg"
        src = PATH + file_name
        dst = PATH + dst

        os.rename(src, dst)

# if __name__ == '__main__':
#     rename()


# coding: utf-8

# In[1]:

import numpy as np
import matplotlib.pyplot as plt

#Genera muestra dados los números y su probabilidad

def sample_1(N):
    A = np.random.choice(a=[-10,-5,3,9],p=[0.1,0.4,0.2,0.3],size=N)
    return A

# Genera muestra que sigue distribución exponencial

def sample_2(N):
    A = np.random.exponential(scale=0.5,size=N)
    return A

# Retorna un array con las M medias de los datos dadas la función de muestreo

def get_mean(sampling_fun,N,M):
    sol = np.zeros(M)
    for i in range(M):
        A = sampling_fun(N)
        mean = np.mean(A)
        sol[i] = mean
    return sol

# Crea 6 archivos de texto con datos de 10000 medias para ambas distribuciones con N=10,100,1000

M = 10000
N = [10,100,1000]

for i in range(len(N)):
    A = get_mean(sample_1,N[i],M)
    B = get_mean(sample_2,N[i],M)

    s1 = 'sample_1_'+str(N[i])+'.txt'
    s2 = 'sample_2_'+str(N[i])+'.txt'

    np.savetxt(fname=s1,X=A)
    np.savetxt(fname=s2,X=B)

# In[ ]: