import RPi.GPIO as GPIO
import board
import digitalio
import adafruit_dht
import psutil
import mh_z19
import time
from mcp3008 import MCP3008

#################################################################################################
# Global variables storing the references to the different sensors that are connected to the Pi #
#################################################################################################

# DHT11 sensors for measuring temperature and humidity
# Referenced using the CircuitPython board scheme in order to use the sensor objects produced by the Adafruit library
DHT_External  = adafruit_dht.DHT11(board.D25, use_pulseio = False)
DHT_Internal1 =	adafruit_dht.DHT11(board.D23, use_pulseio = False)
DHT_Internal2 = adafruit_dht.DHT11(board.D24, use_pulseio = False)

Light_Sensing = 14

Fans = 17
Water_Valve = 27
Lights = 22

# Variables representing the states of the fans and LED lamp | 1 = on, 0 = off
Light_state = 0
Fan_state = 0

# ADC channels for analogue sensors
ADC = MCP3008()
Light_Channel =	0
Soil_Moisture =	1

##################################################################################
# Dictionary storing threshold values to activate/ deactivate relevent actuators #
##################################################################################

Threshold = {
	"Light_Threshold":		512,
	"Moisture_Threshold":	512,
	"Humidity_Threshold":	70.0,
	"Temp_Threshold":		24.0}

class hardware_interface:

	def __init__(self):
		self.Light_state = 0
		self.Fan_state = 0
		print("Hardware interface is initialized")

	##############################
	# Initializing the GPIO pins #
	##############################

	def initialize_GPIO(self):
		GPIO.setmode(GPIO.BCM)
		GPIO.setwarnings(False)

		# Pin responsible for detecting the lighting control signal
		GPIO.setup(Light_Sensing, GPIO.IN)
		# Pins responsible for the control signals used for the relays
		GPIO.setup(Fans, GPIO.OUT, initial = GPIO.LOW) # Fans
		GPIO.setup(Water_Valve, GPIO.OUT, initial = GPIO.LOW) # Water valve
		GPIO.setup(Lights, GPIO.OUT, initial = GPIO.LOW) # LED Lamp

	#######################################################
	# Methods that read the data of the different sensors #
	#######################################################

	#########################################
	# DHT11 Temperature and Humidity Sensor #
	#########################################

	# Note on DHT sensors:
	# DHT sensors have a tendency to cause a runtime errors on linux-based systems when retrieving sensor data
	# So, a 'try/ raise logic' needs to be used to retrieve the sensor data again after 2 seconds

	# Gets the measured temperature from outside the greenhouse
	def get_external_temp(self):
		external_temp = 0

		while external_temp == 0:
			try:
				external_temp = DHT_External.temperature
			except RuntimeError as error:
				time.sleep(2.0)
				continue
			except Exception as error:
				DHT_External.exit()
				raise error

		return float(external_temp)

	# Gets the measured temperatures of the 2 sensors from inside the greenhouse
	# Then returns the averaged result from the 2 sensors
	def get_internal_temp(self):
		temp1 = 0
		temp2 = 0

		while temp1 == 0:
			try:
				temp1 = DHT_Internal1.temperature
			except RuntimeError as error:
				time.sleep(2.0)
				continue
			except Exception as error:
				DHT_Internal1.exit()
				raise error

		while temp2 == 0:
			try:
				temp2 = DHT_Internal2.temperature
			except RuntimeError as error:
				time.sleep(2.0)
				continue
			except Exception as error:
				DHT_Internal2.exit()
				raise error

		return round((temp1 + temp2)/2, 2)

	# Gets the measured humidity from the 2 sensors inside the greenhouse
	# Then returns the averaged result from the 2 sensors
	def get_humidity(self):
		hum1 = 0
		hum2 = 0

		while hum1 == 0:
			try:
				hum1 = DHT_Internal1.humidity
			except RuntimeError as error:
				time.sleep(2.0)
				continue
			except Exception as error:
				DHT_Internal1.exit()
				raise error

		while hum2 == 0:
			try:
				hum2 = DHT_Internal2.humidity
			except RuntimeError as error:
				time.sleep(2.0)
				continue
			except Exception as error:
				DHT_Internal2.exit()
				raise error

		return round((hum1 + hum2)/2, 2)

	#####################
	# MH-Z19 CO2 Sensor #
	#####################

	# Gets the measured CO2 concentration inside the greenhouse
	# The value returned is in PPM (parts per million)
	def get_CO2(self):
		co2 = mh_z19.read_from_pwm(gpio = 12, range = 2000)
		return co2['co2']

	##################################
	# Light Dependent Resistor (LDR) #
	##################################

	# Broke the ADC now using the LDR as a switch using a potentiometer as a 'digital signal'
	# Sensitivity is adjusted with the pot
	# When the ambient lighting is sufficient the input pin will have read a high voltage
	# The input pin will read a low voltage when it's too dark
	def get_light_reading(self):
		if GPIO.input(Light_Sensing) == GPIO.LOW: # Lighting is low
			return 1
		elif GPIO.input(Light_Sensing) == GPIO.HIGH: # Lighting is high enough
			return 0

		# Gets the light reading from the LDR
		# The sensor data is read from the ADC 10 times then averaged to avoid inaccurate readings
		#Deprecated code as the ADC broke
		# light = 0

		# for i in range(10):
			# light += ADC.read(channel = Light_Channel)

		# return light/10

	########################################
	# Velleman VMA303 Soil Moisture Sensor #
	########################################

	# Gets the soil moisture reading
	# The sensor data is read from the ADC 10 times then averaged to avoid inaccurate readings
	def get_soil_moisture(self):
		moisture = 0

		for i in range(10):
			moisture += ADC.read(channel = Soil_Moisture)

		return moisture/10

	###################################################
	# Methods that activate/ deactivate the actuators #
	###################################################

	############
	# LED Lamp #
	############

	def turn_light_on(self):
		GPIO.output(Lights, GPIO.HIGH)
		self.set_lighting_state(1)

	def turn_light_off(self):
		GPIO.output(Lights, GPIO.LOW)
		self.set_lighting_state(0)

	def set_lighting_state(self, state):
		if state == 1:
			self.Light_state = 1
		else:
			self.Light_state = 0

	def get_lighting_state(self):
		return self.Light_state

	################################
	# Normally Open Solenoid Valve #
	################################

	def water_plant(self):
		GPIO.output(Water_Valve, GPIO.HIGH)
		time.sleep(3)
		GPIO.output(Water_Valve, GPIO.LOW)

	#############################
	# Intake and Extractor Fans #
	#############################

	def turn_fans_on(self):
		GPIO.output(Fans, GPIO.HIGH)
		self.set_fan_state(1)

	def turn_fans_off(self):
		GPIO.output(Fans, GPIO.LOW)
		self.set_fan_state(0)

	def set_fan_state(self, state):
		if state == 1:
			self.Fan_state = 1
		else:
			self.Fan_state = 0

	def get_fan_state(self):
		return self.Fan_state

	###################################################
	# Methods that control the greenhouse environment #
	###################################################

	############
	# Lighting #
	############

	# Turns the light on if the ambient light is too low AND if the internal temperature isn't too high
	# Or turns the light off if the ambient light is good enough OR if the internal temperature is too high
	def light_control(self):
		light_reading = self.get_light_reading()
		internal_temp = self.get_internal_temp()

		if light_reading == 1 and internal_temp <= (Threshold["Temp_Threshold"] + 2):
			self.turn_light_on()
		elif light_reading == 0 or internal_temp > (Threshold["Temp_Threshold"] + 2):
			self.turn_light_off()
		# ADC broke
		# if light_reading <= Threshold["Light_Threshold"] and internal_temp <= (Threshold["Temp_Threshold"] + 5):
			# self.turn_light_on()
		# elif light_reading > Threshold["Light_Threshold"] or internal_temp > (Threshold["Temp_Threshold"] + 5):
			# self.turn_light_off()

	############
	# Watering #
	############

	# If the soil isn't wet enough, then the water valve is opened to water the plant
	def water_control(self):
		moisture_reading = self.get_soil_moisture()

		if moisture_reading >= Threshold["Moisture_Threshold"]:
			self.water_plant()

	# Unfortunetly the valve doesn't work due to the water pressure being too low to initialize itself

	###############
	# Ventilation #
	###############

	# Turns the fans on if the relative humidity is high enough to cause the water vapour to condense
	# Also turns the fans on if the internal temperature is too high
	def ventilation(self):
		humidity = self.get_humidity()
		internal_temp = self.get_internal_temp()
		external_temp = self.get_external_temp()

		if humidity >= Threshold["Humidity_Threshold"]:
			self.turn_fans_on()
		elif internal_temp >= Threshold["Temp_Threshold"] and internal_temp > external_temp:
			self.turn_fans_on()
		else:
			self.turn_fans_off()


# isEven.py
# Program prompts the reader for number
# and indicates if the number is even or odd

# Author: Rebecca Feeley

number = int(input("enter an integer: "))

if (number % 2) == 0:
    print (f"{number} is an even number.")

else:
    print (f"{number} is an odd number.")


#!/usr/bin/env python3

import argparse
from textwrap import wrap

parser = argparse.ArgumentParser(add_help=True)
parser.add_argument("-c", "--create", type=int, nargs="?",
help="create pattern of x length")
parser.add_argument("-o", "--offset", type=str, nargs="?",
help="find offset of x character series")
parser.add_argument("-py", help="output in prettified python format",
action="store_true")
parser.add_argument("-cpp", help="output in prettified c/c++ format",
action="store_true")

args = parser.parse_args()
size = args.create
offset = args.offset
py = args.py
cpp = args.cpp

primaries = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z']

secondaries = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9']

tertiaries = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',
'3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z']

def pattern_create(size):

    string = ''

    for x in primaries:
        for y in secondaries:
            for z in tertiaries:
                addition = (x + y + z)
                string += addition

    return(string[:size])

def pattern_offset(offset):

    offset_len = len(offset)
    new_offset = ''
    new_offset = offset[-2:]
    counter = -2
    while len(new_offset) < offset_len:
        new_offset += offset[counter - 2:counter]
        counter = counter - 2

    offset = bytes.fromhex(new_offset).decode('utf-8')

    string = ''

    for x in primaries:
        for y in secondaries:
            for z in tertiaries:
                addition = (x + y + z)
                string += addition

    if offset in string:
        result = len(string.split(offset)[0])
        print("Exact offset found at position: {}".format(str(result)))

    else:
        print("Characters not found in string.")

def python(result):

    output = 'pattern = (\'' + result + '\')'
    list = wrap(output,78)
    for x in list:
        if x == list[0]:
            x += "\'"
            print(x)
        elif x == list[-1]:
            x = '\'' + x
            print(x)
        else:
            print('\'' + x + '\'')

def seeplusplus(result):

    header = "char pattern[] = "
    output = result + "\";"
    list = wrap(output,78)
    print(header)
    for x in list:
        if x == list[-1]:
            x = '\"' + x
            print(x)
        else:
            print('\"' + x + '\"')

if size:
    result = pattern_create(size)
    if py:
        python(result)
    elif cpp:
        seeplusplus(result)
    else:
        print(result)

elif offset:
    pattern_offset(offset)

else:
    parser.print_help()


# calculate school grades
math= float(input("Enter a number your grade for math:\n"))
history= float(input("Enter a number your grade for history:\n"))
reading= float(input("Enter a number your grade for reading:\n"))
science= float(input("Enter a number your grade for science:\n"))
media= float(input("Enter a number your grade for media:\n"))

sum=math+history+reading+science+media
average_grade= sum/5

if average_grade > 90:
    print("Execllent job your grade is: A")
elif  average_grade >80:
    print("Great job your overall grade is: B")
elif    average_grade > 70:
    print( "keep working your overall grade is:D")
elif average_grade > 60:
    print("Keep pushing your overall grade is: C")
else:
    print("you can do better push hard it is possible your grade is :E")


__author__ = 'mark'
# StarbaseMini Staribus/Starinet Client for the British Astronomical Association Staribus Protocol
# Copyright (C) 2015  Mark Horn
#
# This file is part of StarbaseMini.
#
# StarbaseMini is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# StarbaseMini is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with StarbaseMini.  If not, see <http://www.gnu.org/licenses/>.

import numpy as np
import logging

class DataStore(object):
    def __init__(self):

        # The raw data as returned from the controller in whatever format that might be, StaribusBlocks only at
        # present.  WARNING - the data store in RawDataBlocks will be in reverse e.g if we have block 0000 - 000A
        # index 0 of the list will be 000A whereas index 9 will be 0000

        self.RawDataBlocks = []

        # A simple condition so we know if RawDataBlocks has data True we have data False we haven't

        self.RawDataBlocksAvailable = False

        # The raw csv data

        self.RawDataCsv = []

        # Data that has been translated from whatever format the controller has provided,
        # StaribusBlocks only at present.  Make sure this ends up np.array

        self.RawData = []

        # Data that has been passed through one of the filters. Make sure this ends up np.array

        self.ProcessedData = []

        # A simple condition so we know if RawDataCsv has data True we have data False we haven't

        self.RawDataCsvAvailable = False

        # Where the data came from either CSV file or Controller

        self.DataSource = None

        # A simple condition so we know if the RawData has been saved, true is saved, false isn't saved.

        self.RawDataSaved = False

        # A simple condition so we know if the ProcessedData has been saved, true is saved, false isn't saved

        self.ProcessedDataSaved = False # False if ProcessedData hasn't been saved, or True if it has

        # Observation Note Changed.

        self.ObservationNotesChanged = False

        # Channel count of current data.

        self.channel_count = 0

        # Controller data block parser this is set from the instrument_datatranslator_class_loader

        self.block_parser = None

    def print_state(self):

        print("Data source : %s" % str(self.DataSource))
        print("\nRaw data blocks length : %s" % str(len(self.RawDataBlocks)))
        print("Raw data blocks : %s" % str(self.RawDataBlocks))
        print("Raw data blocks available : %s" % str(self.RawDataBlocksAvailable))
        print("\nRaw data csv blocks : %s" % str(self.RawDataCsv))
        print("Raw data csv available : %s" % str(self.RawDataCsvAvailable))
        print("Raw data : %s" % str(self.RawData))
        print("Raw data saved : %s" % str(self.RawDataSaved))
        print("\nProcessed data length : %s" % str(len(self.ProcessedData)))
        print("Processed data saved : %s" % str(self.ProcessedDataSaved))
        print("\nChannel count : %s" % self.channel_count)

    def data_state(self):

        logger = logging.getLogger('datastore.DataStore.data_state')

        if len(self.RawData) != 0 and self.RawDataSaved is False and self.DataSource == 'Controller' and \
           len(self.ProcessedData) != 0 and self.ProcessedDataSaved is False:

            logger.debug("We have both Raw and Processed Data but it isn't saved yet.")

            return False, "You have unsaved raw and processed data."

        elif len(self.ProcessedData) != 0 and self.ProcessedDataSaved is False:

            logger.debug("We have Processed Data but it isn't saved yet.")

            return False, "You have unsaved processed data."

        elif len(self.RawData) != 0 and self.RawDataSaved is False and self.DataSource == 'Controller':

            logger.debug("We have RawData but it isn't saved yet.")

            return False, "You have unsaved raw data."

        elif len(self.RawData) != 0 and self.RawDataSaved is False and self.ObservationNotesChanged is True:

            logger.debug("Unsaved Metadata.")

            return False, "You have unsaved metadata."

        elif self.ObservationNotesChanged is True:

            logger.debug("Unsaved Metadata.")

            return False, "You have unsaved metadata."

        else:

            logger.debug("We appear to have a clean data store.")

            return True, "Data store ready to accept data."

    def default_state(self):

        ''' Return True if all settings are reset to default other returns False'''

        if len(self.RawData) != 0 or len(self.ProcessedData) != 0 or self.DataSource is not None or \
           len(self.RawDataBlocks) != 0 or self.RawDataSaved is not False or self.ProcessedDataSaved is not False \
            or self.RawDataBlocksAvailable is not False or self.RawDataCsvAvailable \
                is not False or self.ObservationNotesChanged is not False:

            return False

        else:

            return True

    def clear_processed(self):

        # This only time this should be called is from the filters so we can process processed data more than once.

        del self.ProcessedData  # Delete instead of clear as we could have a numpy array.

        self.ProcessedData = []  # Recreate deleted variable.

    def clear(self):

        ''' Set all attributes back to default state.'''

        self.RawDataBlocks.clear()

        self.RawDataCsv.clear()

        del self.RawData  # Delete instead of clear as we could have a numpy array.

        self.RawData = [] # Recreate deleted variable.

        del self.ProcessedData # Delete instead of clear as we could have a numpy array.

        self.ProcessedData = [] # Recreate deleted variable.

        self.RawDataBlocksAvailable = False

        self.RawDataCsvAvailable = False

        self.DataSource = None

        self.RawDataSaved = False

        self.ProcessedDataSaved = False

        self.ObservationNotesChanged = False

        self.channel_count = 0

    def create_arrays(self):

        logger = logging.getLogger('datastore.DataStore.create_arrays')

        # Here we create the numpy arrays based on the shape of the data presented.

        # CSV Data ..

        if self.DataSource == 'CSV':

            self.RawData = np.array(self.RawDataCsv)

            self.RawDataCsvAvailable = True

            return True

        elif self.DataSource == 'Controller':

            # Parse Blocks

            # clear any data held in translator

            self.block_parser.clear()

            if self.block_parser.block_parser(self):

                logger.debug('We appeared to parse block')

                self.RawData = np.array(self.block_parser.parsed_data_list)

                return True

            else:

                return False


from time import time
from os import chdir, path
from sys import argv
start = time()

# changing current working directory to the directory of executed file
chdir(path.abspath(path.dirname(argv[0])))

# You need Problem018-triangle.txt file in the same directory
file = open('Problem018-triangle.txt')

data = [line.replace("\n", "").replace(" ", ",").split(",") for line in file.readlines()] # this line converts the file into a list of lists

data = [[int(elements) for elements in first_list] for first_list in data]     # returns int version of a list strings
data.reverse()

for row_counter, row in enumerate(data):
    if len(row) == 1:
        break
    for index, item in enumerate(row):
        if index+1 == len(row):
            break
        data[row_counter+1][index] += max(item,row[index+1])
file.close()
print("the maximum sum of a path from top to bottom is:",data[-1][-1])

print("it took {} seconds".format(time() - start))


# solution
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

# animate plots?
animate=True # True / False

# define tank model
def tank(Level,time,c,valve):
    rho = 1000.0 # water density (kg/m^3)
    A = 1.0      # tank area (m^2)
    # calculate derivative of the Level
    dLevel_dt = (c/(rho*A)) * valve
    return dLevel_dt

# time span for the simulation for 10 sec, every 0.1 sec
ts = np.linspace(0,10,101)

# valve operation
c = 50.0          # valve coefficient (kg/s / %open)
u = np.zeros(101) # u = valve % open

# level initial condition
Level0 = 0

# initial valve position
valve = 0

# for storing the results
z = np.zeros(101)
es = np.zeros(101)
sps = np.zeros(101)

# TO DO: what is the value for ubias?
ubias = 0

# TO DO: decide on a tuning value for Kc
Kc = 50.0

# TO DO: record the desired level (set point)
SP = 10

plt.figure(1,figsize=(12,5))
if animate:
    plt.ion()
    plt.show()
    make_gif = True
    try:
        import imageio  # required to make gif animation
    except:
        print('install imageio with "pip install imageio" to make gif')
        make_gif=False
    if make_gif:
        try:
            import os
            images = []
            os.mkdir('./frames')
        except:
            print('Figure directory failed')
            make_gif=False

# simulate with ODEINT
for i in range(100):
    # calculate the error
    error = SP - Level0

    # TO DO: put P-only controller here
    valve = ubias + Kc * error
    valve = max(0,valve)
    valve = min(100,valve)

    u[i+1] = valve   # store the valve position
    es[i+1] = error  # store the error
    y = odeint(tank,Level0,[0,0.1],args=(c,valve))
    Level0 = y[-1] # take the last point
    z[i+1] = Level0 # store the level for plotting
    sps[i+1] = SP

    if animate:
        # update plot
        plt.clf()
        plt.subplot(3,1,1)
        plt.plot(ts[0:i+1],z[0:i+1],'r-',linewidth=3,label='level PV')
        plt.plot(ts[0:i+1],sps[0:i+1],'k:',linewidth=3,label='level SP')
        plt.ylabel('Tank Level')
        plt.legend(loc='best')
        plt.subplot(3,1,2)
        plt.plot(ts[0:i+1],u[0:i+1],'b--',linewidth=3,label='valve')
        plt.ylabel('Valve')
        plt.legend(loc='best')
        plt.subplot(3,1,3)
        plt.plot(ts[0:i+1],es[0:i+1],'g-',linewidth=3,label='error')
        plt.ylabel('Error = SP-PV')
        plt.xlabel('Time (sec)')
        plt.legend(loc='best')
        filename='./frames/frame_'+str(1000+i)+'.png'
        plt.savefig(filename)
        if make_gif:
            images.append(imageio.imread(filename))
        plt.pause(0.1)

if not animate:
    # plot results
    plt.subplot(3,1,1)
    plt.plot(ts,z,'r-',linewidth=3,label='level PV')
    plt.plot(ts,sps,'k:',linewidth=3,label='level SP')
    plt.ylabel('Tank Level')
    plt.legend(loc='best')
    plt.subplot(3,1,2)
    plt.plot(ts,u,'b--',linewidth=3,label='valve')
    plt.ylabel('Valve')
    plt.legend(loc='best')
    plt.subplot(3,1,3)
    plt.plot(ts,es,'g-',linewidth=3,label='error')
    plt.ylabel('Error = SP-PV')
    plt.xlabel('Time (sec)')
    plt.legend(loc='best')
    plt.show()
else:
    # create animated GIF
    if make_gif:
        imageio.mimsave('animate.gif', images)


def or_sum(nums, x):
    temp = []
    res = 0
    for each in nums:
        if each % x == 0:
            temp.append(each)
    for each in temp:
        res = res | each
    return res

if __name__ == '__main__':
    n = int(input())
    for i in range(n):
        x = int(input().split()[-1])
        nums = [int(j) for j in input().split()]
        print(or_sum(nums, x))


import sys
import torch
from torchinfo import summary

sys.path.insert(0, '../')
import constants
from models.diffusion.denoising_diffusion import Unet, GaussianDiffusion, Trainer

if __name__ == "__main__":

    model = Unet(
        dim = constants.DIM, # 256
        dim_mults = constants.DIM_MULTS,
        channels = constants.CHANNELS
    )

    diffusion = GaussianDiffusion(
        denoise_fn = model,
        image_size = 512,
        n_mels = constants.NUM_CHANNELS,
        n_samples = constants.TARGET_SAMPLES,
        channels = constants.CHANNELS,
        timesteps = constants.TIMESTEPS,   # number of steps
        loss_type = constants.LOSS_TYPE    # L1 or L2

    )

    summary(diffusion, input_size=(constants.BATCH_SIZE, 1, 128, 1024))

    # trainer = Trainer(
    #     diffusion,
    #     constants.TRAIN_DATA,
    #     constants.SAMPLE_RATE,
    #     constants.TARGET_SAMPLES,
    #     constants.DEVICE,
    #     train_batch_size = constants.BATCH_SIZE,
    #     train_num_steps = constants.TRAIN_STEPS,
    #     gradient_accumulate_every = constants.GRADIENT_ACCUMULATION,
    #     save_and_sample_every = constants.SAVE_SAMPLES_EVERY
    # )

    # trainer.train()


#!/usr/bin/env python
# coding: utf-8
# %% [markdown]
# ### App File

# %%
import gradio as gr
import cv2
import tensorflow as tf

def predict_input_image(img):

    '''To predict Diabetic Retinopathy images'''

    model = tf.keras.models.load_model(r"/Users/Sarmita Majumdar/Desktop/SMit_App/model00000002-0.9092040061950684.h5")
    Retina_classes:str = ['DR', 'No_DR']
    img_resize = img.reshape(-1,224,224,3)
    prediction:float=model.predict(img_resize)[0]
    return {Retina_classes[i]: float(prediction[i]) for i in range(2)}

def  GUI():

    '''1. Gradio - Graphical user interface development tool and easy to access anyone

    2. Instead of using HTML/ CSS/ JS -> I am using Gradio'''

    # Input shape represent by Gradio
    image = gr.inputs.Image(shape=(224,224))

    # Number of Classes using by Gradio
    label = gr.outputs.Label(num_top_classes=2)

    # All are in one place to serve Browser!
    gr.Interface(fn=predict_input_image, inputs=image, outputs=label,interpretation='default').launch(debug='True', share=True)

GUI()

# %%

# %%


0#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 16 16:28:13 2022

@author: astahl3
"""
import re
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
import os
import pathlib
import math

####################################################
######## ENTER DESIRED NUMERICAL VARIABLES #########
####################################################

# 0 = display name
# 1 = pattern match for log file (copy-paste entire process_0.log line up until the desired number)
var_01 =  ['loop time (sec)',               r' - Loop time  \(mpi   time\):.*?([0-9.-]+)']
var_02 =  ['fastest particle (level 0)',    r'   ->Fastest particle \(int\) in Level 0:.*?([0-9.-]+)']
var_03 =  ['fastest particle (level 1)',    r'   ->Fastest particle \(int\) in Level 1:.*?([0-9.-]+)']
var_04 =  ['fastest particle (level 2)',    r'   ->Fastest particle \(int\) in Level 2:.*?([0-9.-]+)']
var_05 =  ['fastest particle (level 3)',    r'   ->Fastest particle \(int\) in Level 3:.*?([0-9.-]+)']

variables  =    [
                var_01,
                #var_02,
                #var_03,
                #var_04,
                #var_05,
                ]
####################################################
############## ENTER PATH TO LOG FILE ##############
####################################################

#log_path = '/home/astahl3/aikef_output/Juno/Juno_n10_r0_dt10/bin/process_0.log'
#log_path = '/home/astahl3/aikef_output/Juno/Juno_n10_r1_dt10_Duling/bin/process_0.log'
#log_path = '/home/astahl3/aikef_output/Juno/Juno_n14_r3_dtplus/bin/process_0.log'
log_path = '/home/astahl3/aikef_output/Juno/Juno_n12_r1_dt10/bin/process_0.log'
#log_path = '/data1/astahl/aikef_output/G2/G2_master_r0/bin/process_0.log'
#log_path = '/home/astahl3/aikef_output/Juno/Juno_n10_r1_dt10_D2/bin/process_0.log'

####################################################
########## EXTRACT BASIC INFO ABOUT RUNS ###########
####################################################
TL_per_run = []
dt_per_run = []
TL_save = []
TL_save.append(0)
run_count = 1
TL_temp = 0
total_lines = 0
cnt = 0

###### Saving basic info about number of runs, timesteps of each run in log file, starting save position
with open(log_path) as log_file:
    pattern_match_dt = re.compile(r' dt = .*?([0-9.-]+)')
    pattern_match_time = re.compile(r' STATISTICS OF TL .*?([0-9.-]+)')
    pattern_match_save = re.compile(r' Continuing at TL .*?([0-9.-]+)')

    for line in log_file:
        total_lines = total_lines + 1 # keep count of total number of lines read
        cnt = cnt + 1 # dummy counter for print statements
        match_dt = pattern_match_dt.match(line) # extract the AIKEF timestep "dt" used in current run
        match_time = pattern_match_time.match(line) # extract timestep n
        match_save = pattern_match_save.match(line) # extract timestep for restart from state

        if match_time:
            TL_temp = match_time.group(1) # save most recent timestep in current run

        # If true, this means new run is starting
        # Save the final timestep "TL" of previous run
        # Save the AIKEF timestep "dt" used in current run
        if match_dt:
            dt_per_run.append(match_dt.group(1)) # extract dt used for current run
            TL_per_run.append(TL_temp) # save the associated (i.e., max timestep of prior run)
        if match_save:
            TL_save.append(match_save.group(1))
            run_count = run_count + 1

        if cnt == 100000:
            print(total_lines, 'lines scanned during run counter')
            cnt = 0

    TL_per_run.append(TL_temp) # store total number of timesteps achieved in each run
    TL_per_run.pop(0) # remove first entry as it doesn't corresond to any run

TL_save = np.float_(TL_save)
TL_save = np.int_(TL_save)
TL_per_run = np.float_(TL_per_run)
TL_per_run = np.int_(TL_per_run)

###### Print summary of each run included in the log file
print('\n')
for k in range(0,run_count):
    TL_per_run[k] = TL_per_run[k] - TL_save[k]
    print('run #', k+1, 'used dt =', dt_per_run[k], 'totalling ', TL_per_run[k], 'timesteps')

print('\n')
print('TOTAL LINES IN LOG FILE: ', total_lines, '\n')

####################################################
########### STRINGS TO MATCH IN LOG FILE ###########
####################################################

    ##############################################################################################
    # Extracts the number (as a float) appearing after a particular line                         #
    # The string of the line must be copied exactly, including leading spaces, from              #
    # start of line until some point before the desired numerical value                          #
    # Use backslash before parenthesis, e.g.:                                                    #
    #    if desired line is:  "   -> vel (int) in level 0 = " (wihthout the quotes)              #
    #    enter this in  re.compile():  "    -> vel \(int\) in level 0 = " (without the quotes)   #
    ##############################################################################################

pattern_start = re.compile(variables[0][1])

###### Save the desired variable or value at each timestep
save_var = []
with open(log_path) as log_file:
    k = 0
    cnt = 0
    for line in log_file:
        match_var = pattern_start.match(line)
        if match_var:
            #print('match.group(1)')
            save_var.append(match_var.group(1))
            #print(match.group(1))
            #result.append(match.group(1))
            k = k + 1
            cnt = cnt + 1
        if k == 500:
            print(cnt, ' timesteps completed during variable extraction')
            k = 0

###### PLOT ALL TIMESTEPS ######
var_plot = np.float_(save_var)
fig, ax = plt.subplots(1,1,sharex=True)
plt.subplots_adjust(hspace = 0.05)
ax.plot(np.linspace(1,cnt,cnt,endpoint=True),var_plot)
ax.set_yticks(np.round(np.linspace(1,np.max(var_plot),10,endpoint=True)))
ax.set_ylabel('maximum normalized v')
ax.set_xlabel('timestep')
ax.set_title('all timesteps')
#plt.savefig('/home/astahl3/plots/Juno_n10_r1_dt10_Duling_vel.png')

###### MAKE PLOTS FOR EACH RUN ######

for k in range(0,run_count):
    fig, ax = plt.subplots(1,1,sharex=True)
    plt.subplots_adjust(hspace = 0.05)
    temp_plot = var_plot[TL_save[k]:TL_save[k]+TL_per_run[k]:1]
    ax.plot(np.linspace(TL_save[k],TL_per_run[k],TL_per_run[k],endpoint=True),temp_plot)
    ax.set_title('run # '+str(k+1))
    ax.set_xlabel('timestep')
    ax.set_ylabel(variables[0][0])

###### PLOT TIMESTEPS LAST RUN ONLY ######
#TL_per_run = np.float_(TL_per_run)
#num_runs = len(TL_per_run)
#TL_last_end = np.sum(TL_per_run)
#TL_last_start = np.sum(TL_per_run[0:num_runs-1])
#steps = round(TL_last_end)-round(TL_last_start)
#var_last_plot = var_plot[round(TL_last_start):steps:1]

#fig, ax = plt.subplots(1,1,sharex=True)
#plt.subplots_adjust(hspace = 0.05)
#ax.plot(np.linspace(1,steps,steps,endpoint=True),var_last_plot)
#ax.set_yticks(np.round(np.linspace(1,np.max(var_plot),10,endpoint=True)))
#ax.set_ylabel(variables[0][0])
#ax.set_xlabel('timestep')


from PySide2.QtCore import QObject, Slot
import chardet

class FileUtil(QObject):
    @Slot(str, result='QVariant')
    def readFile(self, file_path):
        print(file_path)
        # the_file = open(file_path, 'r', encoding ='utf-8')
        the_file = open(file_path, 'rb')
        data_byte = the_file.read()
        result = chardet.detect(data_byte)
        the_file.close()
        the_encoding = result.get('encoding')
        the_file = open(file_path, 'r', encoding=the_encoding)
        data_text = the_file.read()
        return data_text


import matplotlib.pyplot as plt
import pandas as pd

mc_connect_no_entity = pd.read_csv("MC/connect_no_entity/network/rtt/TCP_123-57-84-206.csv")
mc_connect_no_entity = mc_connect_no_entity.loc[:,["sample_rtt"]]

mc_connect_entity = pd.read_csv("MC/connect_many_entity/network/rtt/TCP_123-57-84-206.csv")
mc_connect_entity = mc_connect_entity.loc[:, ["sample_rtt"]]

mc_stand_no_entity = pd.read_csv("MC/stand_still_no_entity/network/rtt/TCP_123-57-84-206.csv")
mc_stand_no_entity = mc_stand_no_entity.loc[:, ["sample_rtt"]]

mc_stand_entity = pd.read_csv("MC/stand_still_many_entity/network/rtt/TCP_123-57-84-206.csv")
mc_stand_entity = mc_stand_entity.loc[:, ["sample_rtt"]]

plt.figure(figsize=(16, 9))  # 设置画布的尺寸
plt.title('Minecraft Computation Burden with RTT', fontsize=40)  # 标题，并设定字号大小
labels = 'Connection', 'General'  # 图例

# vert=False:水平箱线图；showmeans=True：显示均值
plt.boxplot([mc_connect_no_entity["sample_rtt"],
             mc_stand_no_entity["sample_rtt"]],
            labels=labels, showmeans=True,
            positions=[0.6, 2.6],
            patch_artist = True, boxprops = {'color':'orangered','facecolor':'red'})

plt.boxplot([mc_connect_entity["sample_rtt"],
             mc_stand_entity["sample_rtt"]],
            labels=labels, showmeans=True,
            positions=[1.2, 3.2],
            patch_artist = True, boxprops = {'color':'orangered','facecolor':'blue'})

plt.xticks(fontsize=30)
plt.yticks(fontsize=25)

plt.ylabel("RTT(ms)", fontsize=40)
plt.show()


lines = []
while True:
    try:
        lines.append(input())
    except:
        break
first=list(lines.pop(0).split(" "))
n=int(first[0])
m=int(first[1])
str=lines.pop(0)
max=0
if len(str)==4:
    print(1)
    print(2)
else:
    print(str)
    print(lines)


def to_int_list(l, split):
    l = l.split(split)
    l = all_to_int(l)
    return l

def all_to_int(x):
    while "null" in x:
        x.remove("null")
    for i in range(len(x)):
        x[i] = int(x[i])
    return x

num = int(input())
nums = to_int_list(input(), " ")
nums.sort()
min = max = 0
big = nums[num-1]
small = nums[0]
mid = nums[num//2]
res = "YES"
if mid == big or mid == small:
    res = "NO"
for i in nums:
    if i == small:
        min += 1
    elif i == big:
        max += 1
    elif i != mid:
        res = "NO"
        break
if big == small:
    res = "YES"
print(res)


import random
def start():
    mat = []
    for i in range(4):
        mat.append([0]*4)
    return mat

def add_new(mat):

    r = random.randint(0,3)
    c = random.randint(0,3)
    while mat[r][c] != 0:
        r = random.randint(0,3)
        c = random.randint(0,3)
    mat[r][c] = 2

def reverse(mat):
    new_mat = []
    for i in range(4):
        new_mat.append([])
        for j in range(4):
            new_mat[i].append(mat[i][4-j-1])
    return new_mat

def transpose(mat):
    new_mat = []
    for i in range(4):
        new_mat.append([])
        for j in range(4):
            new_mat[i].append(mat[j][i])
    return new_mat

def merge(mat):
    change = False
    for i in range(4):
        for j in range(3):
            if mat[i][j] == mat[i][j+1] and mat[i][j]!=0:
                mat[i][j] = mat[i][j]*2
                mat[i][j+1] = 0
                change = True
    return mat,change

def compress(mat):
    new = []
    change = False
    for i in range(4):
        new.append([0]*4)

    for i in range(4):
        pos = 0
        for j in range(4):
            if mat[i][j] != 0:
                new[i][pos] = mat[i][j]
                if j!=pos:
                    change = True
                pos += 1
    return new,change

def move_up(grid):
    transpose_grid = transpose(grid)
    new_grid,changed1 = compress(transpose_grid)
    new_grid,changed2 = merge(new_grid)
    changed = changed1 or changed2
    new_grid,temp = compress(new_grid)
    final_grid = transpose(new_grid)
    return final_grid,changed

def move_down(grid):
    transpose_grid = transpose(grid)
    reverse_grid = reverse(transpose_grid)
    new_grid,changed1 = compress(reverse_grid)
    new_grid,changed2 = merge(new_grid)
    changed = changed1 or changed2
    new_grid,temp = compress(new_grid)
    final_grid_reverse = reverse(new_grid)
    final_grid = transpose(final_grid_reverse)
    return final_grid,changed

def move_right(grid):
    reverse_grid = reverse(grid)
    new_grid,changed1 = compress(reverse_grid)
    new_grid,changed2 = merge(new_grid)
    changed = changed1 or changed2
    new_grid,temp = compress(new_grid)
    final_grid = reverse(new_grid)
    return final_grid,changed

def move_left(grid):
    new_grid,changed1 = compress(grid)
    new_grid,changed2 = merge(new_grid)
    changed = changed1 or changed2
    final_grid,temp = compress(new_grid)
    return final_grid,changed

def state(mat):
    for i in range(4):
        for j in range(4):
            if mat[i][j] == 2048:
                return 'WON'

    for i in range(4):
        for j in range(4):
            if mat[i][j] == 0:
                return 'Game not over'

    for i in range(3):
        for j in range(3):
            if mat[i][j] == mat[i+1][j] or mat[i][j] == mat[i][j+1]:
                return 'Game not over'

    for j in range(3):
        if mat[3][j] == mat[3][j+1]:
            return 'Game not over'

    for i in range(3):
        if mat[i][3] == mat[i+1][3]:
            return 'Game not over'

    return 'LOST'


#####################################################################
#
#  This script will count the number of times a domain
#  appears as an entry and will report the top 50
#  domains by count sorted by procentage growth over the last
#  30 days.
#
#  This script assumes that the tables in the database
#  are populated and exist.
#
#  If they do not exist, run setup.py.  That will create
#  and populate the tables with data.
#
#  The script will not reprocess the entire mailing table
#  unless it detects a change.  A change is detected with the
#  process.check_table_updated() function that returns +1 if
#  items have been added to the mailing table, 0 if nothing
#  has changed and -1 if items have been removed (refer to
#  the read me and commented sections for notes and assumptions).
#
#  You can force the script to re-process the entire mailing table
#  by deleting the file defined by process.COUNTS_FILE or by
#  changing the number in that file to soemthing lower than the
#  number of entries in the mailing table.
#
#####################################################################

import python_mysql as pysql
import conf
import process
import setup

# open connection.
print ('Connecting to DB...')
con = pysql.mysql_connect(conf.SERVER_CONF)

# Create counting table if it doesn't exist just in case.
print ('Creating counts table just in case...')
pysql.mysql_create_table(con, setup.COUNT_TABLE)

# Check to see if the table has been updated, and thus
# we either need to start from the previous saved count or from the beginning.
print ('Processing mailing table (this could take awhile)...')
table_update_state =  process.check_table_updated(con, setup.MAILING_TABLE_NAME,
        process.COUNTS_FILE)
if table_update_state == 1:
    # start processing from SAVED_ROW_COUNT offset.
    process.process_n_address(con, setup.MAILING_TABLE_NAME,
            setup.COUNT_TABLE_NAME, conf.PROCESS_N, process.SAVED_ROW_COUNT)
elif table_update_state == 0: # do nothing
    pass
else:
    # re-process from the beginning.
    process.process_n_address(con, setup.MAILING_TABLE_NAME,
            setup.COUNT_TABLE_NAME, conf.PROCESS_N)

# update the new count.
print ('Updating new count...')
new_count = pysql.mysql_count_rows(con, setup.MAILING_TABLE_NAME)
process.update_count(new_count)

# print report of top 50 by count sorted by growth in the past 30 days.
process.print_top50(con, setup.COUNT_TABLE_NAME)

print ('Closing connectoin')
pysql.mysql_disconnect(con)


#! python3
# prime_number.py

import math

def is_prime_number(x):
    if x < 2: return False
    elif x == 2: return True
    elif x%2 == 0: return False

    sqrt_upper_bound = math.floor(math.sqrt(x))+1
    for i in range(3, sqrt_upper_bound, 2):
        if x % i == 0:
            return False

    return True

n = int(input())
prime_num = 0
for i in range(n):
    x = int(input())
    if is_prime_number(x):
        prime_num += 1

print(prime_num)


from scipy.io import loadmat
import numpy as np
import os

from skimage.color import gray2rgb
from skimage.io import imsave
import skimage.morphology as morph
from sys import argv, exit

if len(argv) < 2:
    print('Usage: python parse.py <data_dir> [-v]')
    exit(0)

SHOW_PLOTS = False

if len(argv) == 3:
    if argv[2] != '-v':
        print('Unknown flag', argv[2])
        exit(0)
    SHOW_PLOTS = True

img_index = 0

import matplotlib.pyplot as plt

data_dir = os.path.normpath(argv[1]) + '/'
seg_filename_mask = data_dir + 'manual_seg/manual_seg_32points_pat{}.mat'
img_filename_mask = data_dir + 'mrimages/sol_yxzt_pat{}.mat'

input_dir = data_dir + 'input/'
if not os.path.exists(input_dir):
    os.mkdir(input_dir)
output_dir = data_dir + 'output/'
if not os.path.exists(output_dir):
    os.mkdir(output_dir)
bbox_dir = data_dir + 'bbox/'
if not os.path.exists(bbox_dir):
    os.mkdir(bbox_dir)

batch_filename = 'batch_{}.npy'

def save_batch(batch):
    '''
    print(i.shape)
    print(o.shape)
    print(i[0])
    print(o[0])
    '''
    np.save((input_dir + batch_filename).format(batch_count), batch[0])
    np.save((output_dir + batch_filename).format(batch_count), batch[1])
    np.save((bbox_dir + batch_filename).format(batch_count), batch[2])

def fill_poly(poly_y, poly_x, shape):
    bbox = np.zeros((4), dtype=np.int32)
    bbox[0] = np.min(poly_y)
    bbox[1] = np.min(poly_x)
    bbox[2] = np.max(poly_y)
    bbox[3] = np.max(poly_x)

    mask = np.zeros(shape, dtype = np.bool_)
    mask[poly_y.astype(np.int), poly_x.astype(np.int)] = True
    mask = morph.convex_hull_image(mask).astype(np.int8)
    return mask, bbox

max_bbox = [0, 0]

count = 0
batch_count = 0
i = 1
while True:
    cur_batch = [None, None, None]
    seg_filename = seg_filename_mask.format(i)
    img_filename = img_filename_mask.format(i)
    i += 1

    print(seg_filename)
    if not os.path.isfile(seg_filename):
        break

    slices = loadmat(img_filename)['sol_yxzt']
    segmentations = loadmat(seg_filename)['manual_seg_32points']

    for z in range(slices.shape[2]):
        for t in range(slices.shape[3]):

            slice = slices[:, :, z, t]
            segmentation = segmentations[z, t]

            if segmentation.shape[0] > 1:
                segm = np.zeros((2, 33, 2))
                segm[0] = segmentation[:33, :]
                segm[0, 32] = segm[0, 0]

                segm[1] = segmentation[32:, :]
                segm[1, 0] = segm[1, -1]

                mask1, _ = fill_poly(segm[0, :, 1], segm[0, :, 0], slice.shape[:2])
                mask2, bbox = fill_poly(segm[1, :, 1], segm[1, :, 0], slice.shape[:2])
                mask = mask1 + mask2
                count += 1

                max_bbox = [max(max_bbox[0], bbox[2] - bbox[0]),
                            max(max_bbox[1], bbox[3] - bbox[1])]

                if cur_batch[0] is None:
                    cur_batch[0] = np.array([slice], dtype=np.float16)
                    cur_batch[1] = np.array([mask], dtype=np.int8)
                    cur_batch[2] = np.array([bbox], dtype=np.int32)
                else:
                    cur_batch[0] = np.append(cur_batch[0], [slice], axis=0)
                    cur_batch[1] = np.append(cur_batch[1], [mask], axis=0)
                    cur_batch[2] = np.append(cur_batch[2], [bbox], axis=0)
                '''
                if count % batch_size == 0:
                    save_batch(cur_batch[1], cur_batch[0])
                    cur_batch = [None, None]
                    batch_count += 1
                '''

                plt.imsave('{}images/img_{}.png'.format(data_dir, img_index), slice, cmap='gray')

                np.save('{}mask1/img_{}'.format(data_dir, img_index), mask1)
                np.save('{}mask2/img_{}'.format(data_dir, img_index), mask2)
                #plt.imsave('{}mask1/img_{}.png'.format(data_dir, img_index), mask1, cmap='gray')
                #plt.imsave('{}mask2/img_{}.png'.format(data_dir, img_index), mask2, cmap='gray')
                img_index += 1
                if SHOW_PLOTS:
                    plt.subplot(121)
                    plt.plot(segm[0, :, 0], segm[0, :, 1])
                    plt.plot(segm[1, :, 0], segm[1, :, 1])
                    plt.imshow(slice, cmap='gray')

                    plt.subplot(122)
                    plt.imshow(mask, cmap='gray', interpolation='None')

                    mngr = plt.get_current_fig_manager()
                    # to put it into the upper left corner for example:
                    mngr.window.setGeometry(100,100, 1000, 800)

                    plt.show()

    save_batch(cur_batch)
    batch_count += 1

    print('count:', count)
print('max_bbox:', max_bbox)
'''
if cur_batch[0] is not None:
    np.save(batch_filename.format(batch_count), cur_batch)
    cur_batch = None
'''


import pandas as pd
import numpy as np

from collections import defaultdict
from sklearn import model_selection
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.ensemble import ExtraTreesClassifier, RandomForestRegressor, AdaBoostRegressor
from sklearn.model_selection import KFold

def Venue_Changes(teamA,teamB,venue):   #venue is changed to 1 for teamA, -1 for teamB and 0 for no team.
	d = defaultdict(list)
	country=''
	with open ('stadium/stadiums', 'r') as f:
	    lines = f.read().splitlines()
	    length=len(lines)
	    i=0
	    while i<length:
	        line = lines[i]
	        if line == '$':
	        	country=lines[i+1]
	        	i+=1
	        else:
	        	d[country].append(line)
	        	i+=1

	if venue in (d[teamA]):
		return 1
	if venue in (d[teamB]):
		return -1
	return 0

def Toss_Changes(teamA,teamB,Toss):
	if Toss == teamA:
		return 1
	return 0

def Toss_Decision_Changes(Toss,Toss_Decision):
	if ( ((Toss == 1) & (Toss_Decision == 'bat')) | ((Toss == 0) & (Toss_Decision == 'field')) ):
		return 1
	return 0

def Win_Prob_Of_TeamA(df,teamA,teamB):

	playOffAandB=df[((df['TeamA']==teamA)&(df['TeamB']==teamB) | (df['TeamA']==teamB)&(df['TeamB']==teamA))]
	playOffAandB = playOffAandB.sort_values(by = 'Date', ascending=[0])
	# playOffAandB = playOffAandB.head(10)

	Awin=playOffAandB[(playOffAandB['Winner']==1)]
	a=len(Awin)
	p=len(playOffAandB)

	if p==0:
		return 0
	return a/p

def Win_prob_on_venue(df1,venue,Toss_Decision):

	prevMatches = df1[(df1['Venue']==venue)]
	prevMatches = prevMatches.sort_values(by = 'Date', ascending=[0])
	# prevMatches = prevMatches.head(10)

	#print prevMatches

	if Toss_Decision == 1:
		Awin = prevMatches[(prevMatches['Toss_Decision'] == prevMatches['Winner'])]
	else:
		Awin = prevMatches[(prevMatches['Toss_Decision'] != prevMatches['Winner'])]

	#print Awin
	a=len(Awin)
	p=len(prevMatches)

	if p==0:
		return 0
	return a/p

def strength_based_on_batBowl_avg(df,TeamA,TeamB):
	playOffAandB=df[((df['TeamA']==TeamA)&(df['TeamB']==TeamB) | (df['TeamA']==TeamB)&(df['TeamB']==TeamA))]
	playOffAandB = playOffAandB.sort_values(by = 'Date', ascending=[0])
	playOffAandB = playOffAandB["Strength"].iloc[0]

	return playOffAandB

def pastPerformance(df1,teamA,teamB,bat_avg):
	prevA = df1[((df1['TeamA']==teamA) | (df1['TeamB']==teamA))]
	prevA = prevA.sort_values(by = 'Date', ascending=[0])
	prevA = prevA.head(10)

	form_A = 0
	cntA = 0
	for index, row in prevA.iterrows():
		name = str(row['MatchID'])+'.csv'#"657643" #657645
		df=pd.read_csv("Dataset/PlayerInfo/"+name)
		df['Bat_Avg'] = df['Bat_Avg'].replace('-', bat_avg)
		total_A = 0
		cntA = cntA + 1
		team_list=df[(df['Country']==teamA)]
		for index1, row1 in team_list.iterrows():
			total_A=total_A+float(row1['Bat_Avg'])
		form_A = form_A + total_A/11

	prevB = df1[((df1['TeamA']==teamB) | (df1['TeamB']==teamB))]
	prevB = prevB.sort_values(by = 'Date', ascending=[0])
	prevB = prevB.head(10)

	form_B = 0
	cntB = 0
	for index, row in prevB.iterrows():
		name = str(row['MatchID'])+'.csv'#"657643" #657645
		df=pd.read_csv("Dataset/PlayerInfo/"+name)
		df['Bat_Avg'] = df['Bat_Avg'].replace('-', bat_avg)
		total_B = 0
		cntB = cntB + 1
		team_list=df[(df['Country']==teamB)]
		for index1, row1 in team_list.iterrows():
			total_B=total_B+float(row1['Bat_Avg'])
		form_B = form_B + total_B/11

	# print form_A, form_B, df1.loc[i, 'MatchID']
	if cntA == 0:
		cntA = 1
		formA = bat_avg
	if cntB == 0:
		cntB = 1
		formB = bat_avg

	return form_A/cntA - form_B/cntB

def testPredicit(df1,testData,TeamA,TeamB):
	df1 = df1[((df1['TeamA']==TeamA)&(df1['TeamB']==TeamB) | (df1['TeamA']==TeamB)&(df1['TeamB']==TeamA))]
	predictors = ['Toss', 'Toss_Decision','Venue', 'HTH', 'WinningPerDes','Strength','latest_form']
	alg = LogisticRegression(random_state=1)
	df = df1[['Toss', 'Toss_Decision', 'Venue', 'HTH', 'WinningPerDes', 'Strength','latest_form','Winner']]
	train_predictors = (df[predictors])
	train_target = df["Winner"]
	alg.fit(train_predictors, train_target)
	test_predictions = alg.predict(testData)
	return test_predictions[0]

# main Function

def startPrediction(teamA_input,teamB_input,venue_input,toss_input,tossDecision_input):

	df = pd.read_csv('OutputOfAll.csv')

	if teamB_input < teamA_input:
		teamB_input,teamA_input = teamA_input,teamB_input

	TeamA = teamA_input
	TeamB = teamB_input
	Toss = toss_input
	Toss_Decision = tossDecision_input
	Venue = venue_input

	Venue = Venue_Changes(TeamA,TeamB,Venue)
	Toss = Toss_Changes(TeamA,TeamB,Toss)
	Toss_Decision = Toss_Decision_Changes(Toss,Toss_Decision)

	HTH = Win_Prob_Of_TeamA(df,TeamA,TeamB)

	WinningPerDes = Win_prob_on_venue(df,Venue,Toss_Decision)

	bat_avg = 22.6046511628
	bowl_avg = 29.7670682731

	Strength = strength_based_on_batBowl_avg(df,TeamA,TeamB)

	latest_form = pastPerformance(df,TeamA,TeamB,bat_avg)

	print ("teamA : " +  TeamA)
	print (" ")
	print ("teamB :"  + TeamB)
	print(" ")
	print ( "winning probability of TeamA based on previous matches : " + str(HTH))
	print (" ")
	print ( "winning probability of Team batting first : " + str(WinningPerDes))
	print(" ")
	print ("Team A Performance - Team B Performance : " + str(latest_form))
	print(" ")
	print ("Performance is calculated based on team's batting average")
	print(" ")
	dict = {'Toss':Toss, 'Toss_Decision':Toss_Decision, 'Venue':Venue, 'HTH':HTH, 'WinningPerDes':WinningPerDes, 'Strength':Strength , 'latest_form':latest_form}

	testData = pd.DataFrame(dict,index = ["result"])

	if testPredicit(df,testData,TeamA,TeamB) == 1:
		return teamA_input
	return teamB_input


from mc.tools.EnhancedMenu import Menu
from PyQt5.Qt import QKeySequence
from PyQt5.Qt import QIcon
from PyQt5.Qt import QAction
from mc.common.globalvars import gVar
from .BookmarksTools import BookmarksTools
from .BookmarkItem import BookmarkItem

class BookmarksMenu(Menu):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._window = None  # QPointer<BrowserWindow>
        self._changed = True
        self._init()

        bookmarks = gVar.app.bookmarks()
        bookmarks.bookmarkAdded.connect(self._bookmarksChanged)
        bookmarks.bookmarkRemoved.connect(self._bookmarksChanged)
        bookmarks.bookmarkChanged.connect(self._bookmarksChanged)

    def setMainWindow(self, window):
        '''
        @param: window BrowserWindow
        '''
        self._window = window

    # private Q_SLOTS:
    def _bookmarkPage(self):
        if self._window:
            self._window.bookmarkPage()

    def _bookmarkAllTabs(self):
        if self._window:
            BookmarksTools.bookmarkAllTabsDialog(self._window, self._window.tabWidget())

    def _showBookmarksManager(self):
        print('-----> here', self._window)
        if self._window:
            gVar.app.browsingLibrary().showBookmarks(self._window)

    def _bookmarksChanged(self):
        self._changed = True

    def _aboutToShow(self):
        if self._changed:
            self._refresh()
            self._changed = False

    def _menuAboutToShow(self):
        menu = self.sender()
        assert(isinstance(menu, Menu))

        for action in menu.actions():
            item = action.data()
            if isinstance(item, BookmarkItem) and item.type() == BookmarkItem.Url and action.icon().isNull():
                action.setIcon(item.icon())

    def _menuMiddleClicked(self, menu):
        '''
        @param: menu Menu
        '''
        item = menu.menuAction().data()
        assert(isinstance(item, BookmarkItem))
        self._openFolder(item)

    def _bookmarkActivated(self):
        action = self.sender()
        if isinstance(action, QAction):
            item = action.data()
            assert(isinstance(item, BookmarkItem))
            self._openBookmark(item)

    def _bookmarkCtrlActivated(self):
        action = self.sender()
        if isinstance(action, QAction):
            item = action.data()
            assert(isinstance(item, BookmarkItem))
            self._openBookmarkInNewTab(item)

    def _bookmarkShiftActivated(self):
        action = self.sender()
        if isinstance(action, QAction):
            item = action.data()
            assert(isinstance(item, BookmarkItem))
            self._openBookmarkInNewWindow(item)

    def _openFolder(self, item):
        '''
        @param: item BookmarkItem
        '''
        assert(item.isFolder())

        if self._window:
            BookmarksTools.openFolderInTabs(self._window, item)

    def _openBookmark(self, item):
        '''
        @param: item BookmarkItem
        '''
        assert(item.isUrl())

        if self._window:
            BookmarksTools.openBookmark(self._window, item)

    def _openBookmarkInNewTab(self, item):
        '''
        @param: item BookmarkItem
        '''
        assert(item.isUrl())

        if self._window:
            BookmarksTools.openBookmarkInNewTab(self._window, item)

    def _openBookmarkInNewWindow(self, item):
        '''
        @param: item BookmarkItem
        '''
        assert(item.isUrl())

        if self._window:
            BookmarksTools.openBookmarkInNewWindow(self._window, item)

    # private:
    def _init(self):
        self.setTitle('&Bookmarks')

        act = self.addAction('Bookmark &This Page', self._bookmarkPage)
        act.setShortcut(QKeySequence('Ctrl+D'))
        self.addAction('Bookmark &All Tabs', self._bookmarkAllTabs)
        act = self.addAction(QIcon.fromTheme('bookmarks-organize'),
            'Organize &Bookmarks')
        # NOTE: if use self.addAction(icon, label, self._showBookmarksManager)
        # will cause connection random invalid, so here connect triggered
        # separately.
        act.triggered.connect(self._showBookmarksManager)
        act.setShortcut(QKeySequence('Ctrl+Shift+O'))
        self.addSeparator()

        self.aboutToShow.connect(self._aboutToShow)
        self.aboutToShow.connect(self._menuAboutToShow)
        self.menuMiddleClicked.connect(self._menuMiddleClicked)

    def _refresh(self):
        while len(self.actions()) > 4:
            act = self.actions()[4]
            if act.menu():
                act.menu().clear()
            self.removeAction(act)
            del act

        BookmarksTools.addActionToMenu(self, self, gVar.app.bookmarks().toolbarFolder())
        self.addSeparator()

        for child in gVar.app.bookmarks().menuFolder().children():
            BookmarksTools.addActionToMenu(self, self, child)

        self.addSeparator()
        BookmarksTools.addActionToMenu(self, self, gVar.app.bookmarks().unsortedFolder())


import asyncio
import datetime
import json
import os
import signal
import sys
from collections import deque
from time import time
from enum import Enum

import numpy as np

import telegram_bot
import websockets

from jitted import round_, calc_diff, calc_ema, calc_cost, iter_entries, iter_long_closes, \
    iter_shrt_closes, round_dynamic

def get_keys():
    return ['inverse', 'do_long', 'do_shrt', 'qty_step', 'price_step', 'min_qty', 'min_cost',
            'contract_multiplier', 'ddown_factor', 'qty_pct', 'leverage', 'n_close_orders',
            'grid_spacing', 'pos_margin_grid_coeff', 'volatility_grid_coeff',
            'volatility_qty_coeff', 'min_markup', 'markup_range', 'ema_span', 'ema_spread',
            'stop_loss_liq_diff', 'stop_loss_pos_pct']

def sort_dict_keys(d):
    if type(d) == list:
        return [sort_dict_keys(e) for e in d]
    if type(d) != dict:
        return d
    return {key: sort_dict_keys(d[key]) for key in sorted(d)}

def flatten_dict(d, parent_key='', sep='_'):
    items = []
    for k, v in d.items():
        new_key = parent_key + sep + k if parent_key else k
        if type(v) == dict:
            items.extend(flatten_dict(v, new_key, sep=sep).items())
        else:
            items.append((new_key, v))
    return dict(items)

def make_get_filepath(filepath: str) -> str:
    '''
    if not is path, creates dir and subdirs for path, returns path
    '''
    dirpath = os.path.dirname(filepath) if filepath[-1] != '/' else filepath
    if not os.path.isdir(dirpath):
        os.makedirs(dirpath)
    return filepath

def load_key_secret(exchange: str, user: str) -> (str, str):
    try:
        keyfile = json.load(open('api-keys.json'))
        # Checks that the user exists, and it is for the correct exchange
        if user in keyfile and keyfile[user]["exchange"] == exchange:

            # If we need to get the `market` key:
            # market = keyfile[user]["market"]
            # print("The Market Type is " + str(market))

            keyList = [str(keyfile[user]["key"]), str(keyfile[user]["secret"])]

            return keyList
        elif user not in keyfile or keyfile[user]["exchange"] != exchange:
            print("Looks like the keys aren't configured yet, or you entered the wrong username!")
    except FileNotFoundError:
        print("File Not Found!")
        raise Exception('API KeyFile Missing!')

def print_(args, r=False, n=False):
    line = ts_to_date(time())[:19] + '  '
    str_args = '{} ' * len(args)
    line += str_args.format(*args)
    if n:
        print('\n' + line, end=' ')
    elif r:
        print('\r' + line, end=' ')
    else:
        print(line)
    return line

def ts_to_date(timestamp: float) -> str:
    return str(datetime.datetime.fromtimestamp(timestamp)).replace(' ', 'T')

def filter_orders(actual_orders: [dict],
                  ideal_orders: [dict],
                  keys: [str] = ['symbol', 'side', 'qty', 'price']) -> ([dict], [dict]):
    # returns (orders_to_delete, orders_to_create)

    if not actual_orders:
        return [], ideal_orders
    if not ideal_orders:
        return actual_orders, []
    actual_orders = actual_orders.copy()
    orders_to_create = []
    ideal_orders_cropped = [{k: o[k] for k in keys} for o in ideal_orders]
    actual_orders_cropped = [{k: o[k] for k in keys} for o in actual_orders]
    for ioc, io in zip(ideal_orders_cropped, ideal_orders):
        matches = [(aoc, ao) for aoc, ao in zip(actual_orders_cropped, actual_orders) if aoc == ioc]
        if matches:
            actual_orders.remove(matches[0][1])
            actual_orders_cropped.remove(matches[0][0])
        else:
            orders_to_create.append(io)
    return actual_orders, orders_to_create

def flatten(lst: list) -> list:
    return [y for x in lst for y in x]

class Bot:
    def __init__(self, user: str, config: dict, telegram = None):
        self.config = config
        self.user = user
        self.telegram = telegram

        for key in config:
            setattr(self, key, config[key])

        self.ema_span = int(round(self.ema_span))
        self.ema_alpha = 2 / (self.ema_span + 1)
        self.ema_alpha_ = 1 - self.ema_alpha

        self.ts_locked = {'cancel_orders': 0, 'decide': 0, 'update_open_orders': 0,
                          'update_position': 0, 'print': 0, 'create_orders': 0}
        self.ts_released = {k: 1 for k in self.ts_locked}

        self.position = {}
        self.open_orders = []
        self.highest_bid = 0.0
        self.lowest_ask = 9.9e9
        self.price = 0
        self.ob = [0.0, 0.0]
        self.ema = 0.0

        self.n_open_orders_limit = 8
        self.last_price_diff_limit = 0.15
        self.n_orders_per_execution = 4

        self.hedge_mode = True
        self.contract_multiplier = self.config['contract_multiplier'] = 1.0

        self.log_filepath = make_get_filepath(f"logs/{self.exchange}/{config['config_name']}.log")

        self.key, self.secret = load_key_secret(config['exchange'], user)

        self.log_level = 0

        self.stop_websocket = False
        self.process_websocket_ticks = True

    def set_config(self, config):
        config['ema_span'] = int(round(config['ema_span']))
        self.config = config
        for key in config:
            setattr(self, key, config[key])
            if key in self.xk:
                self.xk[key] = config[key]

    def set_config_value(self, key, value):
        self.config[key] = value
        setattr(self, key, self.config[key])

    async def _init(self):
        self.xk = {k: float(self.config[k]) for k in get_keys()}

    def dump_log(self, data) -> None:
        if self.config['logging_level'] > 0:
            with open(self.log_filepath, 'a') as f:
                f.write(json.dumps({**{'log_timestamp': time()}, **data}) + '\n')

    async def update_open_orders(self) -> None:
        if self.ts_locked['update_open_orders'] > self.ts_released['update_open_orders']:
            return
        try:
            open_orders = await self.fetch_open_orders()
            self.highest_bid, self.lowest_ask = 0.0, 9.9e9
            for o in open_orders:
                if o['side'] == 'buy':
                    self.highest_bid = max(self.highest_bid, o['price'])
                elif o['side'] == 'sell':
                    self.lowest_ask = min(self.lowest_ask, o['price'])
            if self.open_orders != open_orders:
                self.dump_log({'log_type': 'open_orders', 'data': open_orders})
            self.open_orders = open_orders
            self.ts_released['update_open_orders'] = time()
        except Exception as e:
            print('error with update open orders', e)

    async def update_position(self) -> None:
        # also updates open orders
        if self.ts_locked['update_position'] > self.ts_released['update_position']:
            return
        self.ts_locked['update_position'] = time()
        try:
            position, _ = await asyncio.gather(self.fetch_position(),
                                               self.update_open_orders())
            position['used_margin'] = \
                ((calc_cost(position['long']['size'], position['long']['price'],
                            self.xk['inverse'], self.xk['contract_multiplier'])
                  if position['long']['price'] else 0.0) +
                 (calc_cost(position['shrt']['size'], position['shrt']['price'],
                            self.xk['inverse'], self.xk['contract_multiplier'])
                  if position['shrt']['price'] else 0.0)) / self.leverage
            position['available_margin'] = (position['equity'] - position['used_margin']) * 0.9
            position['long']['liq_diff'] = calc_diff(position['long']['liquidation_price'], self.price)
            position['shrt']['liq_diff'] = calc_diff(position['shrt']['liquidation_price'], self.price)
            if self.position != position:
                self.dump_log({'log_type': 'position', 'data': position})
            self.position = position
            self.ts_released['update_position'] = time()
        except Exception as e:
            print('error with update position', e)

    async def create_orders(self, orders_to_create: [dict]) -> dict:
        if not orders_to_create:
            return
        if self.ts_locked['create_orders'] > self.ts_released['create_orders']:
            return
        self.ts_locked['create_orders'] = time()
        creations = []
        for oc in sorted(orders_to_create, key=lambda x: x['qty']):
            try:
                creations.append((oc, asyncio.create_task(self.execute_order(oc))))
            except Exception as e:
                print_(['error creating order a', oc, e], n=True)
        created_orders = []
        for oc, c in creations:
            try:
                o = await c
                created_orders.append(o)
                if 'side' in o:
                    print_([' created order', o['symbol'], o['side'], o['position_side'], o['qty'],
                            o['price']], n=True)
                else:
                    print_(['error creating order b', o, oc], n=True)
                self.dump_log({'log_type': 'create_order', 'data': o})
            except Exception as e:
                print_(['error creating order c', oc, c.exception(), e], n=True)
                self.dump_log({'log_type': 'create_order', 'data': {'result': str(c.exception()),
                                                                    'error': repr(e), 'data': oc}})
        self.ts_released['create_orders'] = time()
        return created_orders

    async def cancel_orders(self, orders_to_cancel: [dict]) -> [dict]:
        if not orders_to_cancel:
            return
        if self.ts_locked['cancel_orders'] > self.ts_released['cancel_orders']:
            return
        self.ts_locked['cancel_orders'] = time()
        deletions = []
        for oc in orders_to_cancel:
            try:
                deletions.append((oc,
                                  asyncio.create_task(self.execute_cancellation(oc))))
            except Exception as e:
                print_(['error cancelling order a', oc, e])
        canceled_orders = []
        for oc, c in deletions:
            try:
                o = await c
                canceled_orders.append(o)
                if 'side' in o:
                    print_(['cancelled order', o['symbol'], o['side'], o['position_side'], o['qty'],
                            o['price']], n=True)
                else:
                    print_(['error cancelling order', o], n=True)
                self.dump_log({'log_type': 'cancel_order', 'data': o})
            except Exception as e:
                print_(['error cancelling order b', oc, c.exception(), e], n=True)
                self.dump_log({'log_type': 'cancel_order', 'data': {'result': str(c.exception()),
                                                                    'error': repr(e), 'data': oc}})
        self.ts_released['cancel_orders'] = time()
        return canceled_orders

    def stop(self) -> None:
        self.stop_websocket = True

    def pause(self) -> None:
        self.process_websocket_ticks = False

    def resume(self) -> None:
        self.process_websocket_ticks = True

    def calc_orders(self):
        balance = self.position['wallet_balance'] * 0.9
        long_psize = self.position['long']['size']
        long_pprice = self.position['long']['price']
        shrt_psize = self.position['shrt']['size']
        shrt_pprice = self.position['shrt']['price']

        if self.hedge_mode:
            do_long = self.do_long or long_psize != 0.0
            do_shrt = self.do_shrt or shrt_psize != 0.0
        else:
            no_pos = long_psize == 0.0 and shrt_psize == 0.0
            do_long = (no_pos and self.do_long) or long_psize != 0.0
            do_shrt = (no_pos and self.do_shrt) or shrt_psize != 0.0

        self.xk['do_long'] = do_long
        self.xk['do_shrt'] = do_shrt

        liq_price = self.position['long']['liquidation_price'] if long_psize > abs(shrt_psize) \
            else self.position['shrt']['liquidation_price']

        long_entry_orders, shrt_entry_orders, long_close_orders, shrt_close_orders = [], [], [], []
        stop_loss_close = False

        for tpl in iter_entries(balance, long_psize, long_pprice, shrt_psize, shrt_pprice,
                                liq_price, self.ob[0], self.ob[1], self.ema, self.price,
                                self.volatility, **self.xk):
            if (len(long_entry_orders) >= self.n_open_orders_limit and
                len(shrt_entry_orders) >= self.n_open_orders_limit) or \
                    calc_diff(tpl[1], self.price) > self.last_price_diff_limit:
                break
            if tpl[4] == 'stop_loss_shrt_close':
                shrt_close_orders.append({'side': 'buy', 'position_side': 'shrt', 'qty': abs(tpl[0]),
                                          'price': tpl[1], 'type': 'limit', 'reduce_only': True,
                                          'custom_id': tpl[4]})
                shrt_psize = tpl[2]
                stop_loss_close = True
            elif tpl[4] == 'stop_loss_long_close':
                long_close_orders.append({'side': 'sell', 'position_side': 'long', 'qty': abs(tpl[0]),
                                          'price': tpl[1], 'type': 'limit', 'reduce_only': True,
                                          'custom_id': tpl[4]})
                long_psize = tpl[2]
                stop_loss_close = True
            elif tpl[0] > 0.0:
                long_entry_orders.append({'side': 'buy', 'position_side': 'long', 'qty': tpl[0],
                                          'price': tpl[1], 'type': 'limit', 'reduce_only': False,
                                          'custom_id': tpl[4]})
            else:
                shrt_entry_orders.append({'side': 'sell', 'position_side': 'shrt', 'qty': abs(tpl[0]),
                                          'price': tpl[1], 'type': 'limit', 'reduce_only': False,
                                          'custom_id': tpl[4]})

        for ask_qty, ask_price, _ in iter_long_closes(balance, long_psize, long_pprice, self.ob[1],
                                                      **self.xk):
            if len(long_close_orders) >= self.n_open_orders_limit or \
                    calc_diff(ask_price, self.price) > self.last_price_diff_limit or \
                    stop_loss_close:
                break
            long_close_orders.append({'side': 'sell', 'position_side': 'long', 'qty': abs(ask_qty),
                                      'price': float(ask_price), 'type': 'limit',
                                      'reduce_only': True, 'custom_id': 'close'})

        for bid_qty, bid_price, _ in iter_shrt_closes(balance, shrt_psize, shrt_pprice, self.ob[0],
                                                      **self.xk):
            if len(shrt_close_orders) >= self.n_open_orders_limit or \
                    calc_diff(bid_price, self.price) > self.last_price_diff_limit or \
                    stop_loss_close:
                break
            shrt_close_orders.append({'side': 'buy', 'position_side': 'shrt', 'qty': abs(bid_qty),
                                      'price': float(bid_price), 'type': 'limit',
                                      'reduce_only': True, 'custom_id': 'close'})
        return long_entry_orders + shrt_entry_orders + long_close_orders + shrt_close_orders

    async def cancel_and_create(self):
        await asyncio.sleep(0.005)
        await self.update_position()
        await asyncio.sleep(0.005)
        if any([self.ts_locked[k_] > self.ts_released[k_]
                for k_ in [x for x in self.ts_locked if x != 'decide']]):
            return
        to_cancel, to_create = filter_orders(self.open_orders,
                                             self.calc_orders(),
                                             keys=['side', 'position_side', 'qty', 'price'])
        to_cancel = sorted(to_cancel, key=lambda x: calc_diff(x['price'], self.price))
        to_create = sorted(to_create, key=lambda x: calc_diff(x['price'], self.price))
        results = []
        if to_cancel:
            results.append(asyncio.create_task(self.cancel_orders(to_cancel[:self.n_orders_per_execution])))
            await asyncio.sleep(0.005)  # sleep 5 ms between sending cancellations and creations
        if to_create:
            results.append(await self.create_orders(to_create[:self.n_orders_per_execution]))
        await asyncio.sleep(0.005)
        await self.update_position()
        if any(results):
            print()
        return results

    async def decide(self):
        if self.price <= self.highest_bid:
            self.ts_locked['decide'] = time()
            print_(['bid maybe taken'], n=True)
            await self.cancel_and_create()
            self.ts_released['decide'] = time()
            return
        if self.price >= self.lowest_ask:
            self.ts_locked['decide'] = time()
            print_(['ask maybe taken'], n=True)
            await self.cancel_and_create()
            self.ts_released['decide'] = time()
            return
        if time() - self.ts_locked['decide'] > 5:
            self.ts_locked['decide'] = time()
            await self.cancel_and_create()
            self.ts_released['decide'] = time()
            return
        if time() - self.ts_released['print'] >= 0.5:
            self.ts_released['print'] = time()
            line = f"{self.symbol} "
            line += f"long {self.position['long']['size']} @ "
            line += f"{round_(self.position['long']['price'], self.price_step)} "
            long_closes = sorted([o for o in self.open_orders if o['side'] == 'sell'
                                  and o['position_side'] == 'long'], key=lambda x: x['price'])
            long_entries = sorted([o for o in self.open_orders if o['side'] == 'buy'
                                   and o['position_side'] == 'long'], key=lambda x: x['price'])
            line += f"close @ {long_closes[0]['price'] if long_closes else 0.0} "
            line += f"enter @ {long_entries[-1]['price'] if long_entries else 0.0} "
            line += f"|| shrt {self.position['shrt']['size']} @ "
            line += f"{round_(self.position['shrt']['price'], self.price_step)} "
            shrt_closes = sorted([o for o in self.open_orders if o['side'] == 'buy'
                                  and (o['position_side'] == 'shrt' or
                                       (o['position_side'] == 'both' and
                                        self.position['shrt']['size'] != 0.0))],
                                 key=lambda x: x['price'])
            shrt_entries = sorted([o for o in self.open_orders if o['side'] == 'sell'
                                   and (o['position_side'] == 'shrt' or
                                        (o['position_side'] == 'both' and
                                         self.position['shrt']['size'] != 0.0))],
                                  key=lambda x: x['price'])
            line += f"close @ {shrt_closes[-1]['price'] if shrt_closes else 0.0} "
            line += f"enter @ {shrt_entries[0]['price'] if shrt_entries else 0.0} "
            if self.position['long']['size'] > abs(self.position['shrt']['size']):
                liq_price = self.position['long']['liquidation_price']
                sl_trigger_price = round_(liq_price / (1 - self.stop_loss_liq_diff), self.price_step)
            else:
                liq_price = self.position['shrt']['liquidation_price']
                sl_trigger_price = round_(liq_price / (1 + self.stop_loss_liq_diff), self.price_step)
            line += f"|| last {self.price} liq {round_dynamic(liq_price, 3)} "
            line += f"sl trig {round_dynamic(sl_trigger_price, 3)} "
            line += f"ema {round_dynamic(self.ema, 3)} "
            line += f"bal {round_dynamic(self.position['wallet_balance'], 3)} "
            line += f"equity {round_dynamic(self.position['equity'], 3)} "
            line += f"v. {round_dynamic(self.volatility, 3)} "
            print_([line], r=True)

    def flush_stuck_locks(self, timeout: float = 4.0) -> None:
        now = time()
        for key in self.ts_locked:
            if self.ts_locked[key] > self.ts_released[key]:
                if now - self.ts_locked[key] > timeout:
                    print('flushing', key)
                    self.ts_released[key] = now

    async def fetch_compressed_ticks(self):

        def drop_consecutive_same_prices(ticks_):
            compressed_ = [ticks_[0]]
            for i in range(1, len(ticks_)):
                if ticks_[i]['price'] != compressed_[-1]['price']:
                    compressed_.append(ticks_[i])
            return compressed_

        ticks_unabridged = await self.fetch_ticks(do_print=False)
        ticks_per_fetch = len(ticks_unabridged)
        ticks = drop_consecutive_same_prices(ticks_unabridged)
        if self.exchange == 'bybit' and self.market_type == 'linear_perpetual':
            print('\nwarning:  bybit linear usdt symbols only allows fetching most recent 1000 ticks')
            return ticks
        delay_between_fetches = 0.55
        print()
        while True:
            print(f'\rfetching ticks... {len(ticks)} of {self.ema_span} ', end= ' ')
            sts = time()
            new_ticks = await self.fetch_ticks(from_id=ticks[0]['trade_id'] - ticks_per_fetch,
                                               do_print=False)
            wait_for = max(0.0, delay_between_fetches - (time() - sts))
            ticks = drop_consecutive_same_prices(sorted(new_ticks + ticks,
                                                        key=lambda x: x['trade_id']))
            if len(ticks) > self.ema_span:
                break
            await asyncio.sleep(wait_for)
        new_ticks = await self.fetch_ticks(do_print=False)
        return drop_consecutive_same_prices(sorted(ticks + new_ticks, key=lambda x: x['trade_id']))

    async def init_indicators(self):
        ticks = await self.fetch_compressed_ticks()
        ema = ticks[0]['price']
        self.tick_prices_deque = deque(maxlen=self.ema_span)
        for tick in ticks:
            self.tick_prices_deque.append(tick['price'])
            ema = ema * self.ema_alpha_ + tick['price'] * self.ema_alpha
        if len(self.tick_prices_deque) < self.ema_span:
            print('\nwarning: insufficient ticks fetched, filling deque with duplicate ticks...')
            print('ema and volatility will be inaccurate until deque is filled with websocket ticks')
            while len(self.tick_prices_deque) < self.ema_span:
                self.tick_prices_deque.extend([t['price'] for t in ticks])
        self.ema = ema
        self.sum_prices = sum(self.tick_prices_deque)
        self.sum_prices_squared = sum([e ** 2 for e in self.tick_prices_deque])
        self.price_std = np.sqrt((self.sum_prices_squared / len(self.tick_prices_deque) -
                                 ((self.sum_prices / len(self.tick_prices_deque)) ** 2)))
        self.volatility = self.price_std / self.ema
        print('\ndebug len ticks, prices deque, ema_span')
        print(len(ticks), len(self.tick_prices_deque), self.ema_span)

    def update_indicators(self, ticks: dict):
        for tick in ticks:
            if tick['is_buyer_maker']:
                self.ob[0] = tick['price']
            else:
                self.ob[1] = tick['price']
            self.ema = calc_ema(self.ema_alpha, self.ema_alpha_, self.ema, tick['price'])
            self.sum_prices -= self.tick_prices_deque[0]
            self.sum_prices_squared -= self.tick_prices_deque[0] ** 2
            self.tick_prices_deque.append(tick['price'])
            self.sum_prices += self.tick_prices_deque[-1]
            self.sum_prices_squared += self.tick_prices_deque[-1] ** 2
        self.price_std = np.sqrt((self.sum_prices_squared / len(self.tick_prices_deque) -
                                 ((self.sum_prices / len(self.tick_prices_deque)) ** 2)))
        self.price = ticks[-1]['price']
        self.volatility = self.price_std / self.ema

    async def start_websocket(self) -> None:
        self.stop_websocket = False
        self.process_websocket_ticks = True
        print_([self.endpoints['websocket']])
        await self.update_position()
        await self.init_exchange_config()
        await self.init_indicators()
        k = 1
        async with websockets.connect(self.endpoints['websocket']) as ws:
            await self.subscribe_ws(ws)
            async for msg in ws:
                if msg is None:
                    continue
                try:
                    ticks = self.standardize_websocket_ticks(json.loads(msg))
                    if self.process_websocket_ticks:
                        if ticks:
                            self.update_indicators(ticks)
                        if self.ts_locked['decide'] < self.ts_released['decide']:
                            asyncio.create_task(self.decide())
                    if k % 10 == 0:
                        self.flush_stuck_locks()
                        k = 1
                    if self.stop_websocket:
                        if self.telegram is not None:
                            self.telegram.send_msg("<pre>Bot stopped</pre>")
                        break
                    k += 1

                except Exception as e:
                    if 'success' not in msg:
                        print('error in websocket', e, msg)

async def start_bot(bot):
    await bot.start_websocket()

async def create_binance_bot(user: str, config: str):
    from binance import BinanceBot
    bot = BinanceBot(user, config)
    await bot._init()
    return bot

async def create_bybit_bot(user: str, config: str):
    from bybit import Bybit
    bot = Bybit(user, config)
    await bot._init()
    return bot

async def _start_telegram(account: dict, bot: Bot):
    telegram = telegram_bot.Telegram(token=account['telegram']['token'],
                                     chat_id=account['telegram']['chat_id'],
                                     bot=bot,
                                     loop=asyncio.get_event_loop())
    telegram.log_start()
    return telegram

async def main() -> None:
    try:
        accounts = json.load(open('api-keys.json'))
    except Exception as e:
        print(e, 'failed to load api-keys.json file')
        return
    if sys.argv[1] in accounts:
        account = accounts[sys.argv[1]]
    else:
        print('unrecognized account name', sys.argv[1])
        return
    try:
        config = json.load(open(sys.argv[3]))
    except Exception as e:
        print(e, 'failed to load config', sys.argv[3])
        return
    config['exchange'] = account['exchange']
    config['symbol'] = sys.argv[2]

    if account['exchange'] == 'binance':
        bot = await create_binance_bot(sys.argv[1], config)
    elif account['exchange'] == 'bybit':
        bot = await create_bybit_bot(sys.argv[1], config)
    else:
        raise Exception('unknown exchange', account['exchange'])
    print('using config')
    print(json.dumps(config, indent=4))

    if 'telegram' in account and account['telegram']['enabled']:
        telegram = await _start_telegram(account=account, bot=bot)
        signal.signal(signal.SIGINT, telegram.exit)
    await start_bot(bot)

if __name__ == '__main__':
    asyncio.run(main())


from subprocess import call
import sys

files = open("upload.txt", "r").read().split('\n')

for f in files:
  print(f)
  call(["git", "add", f])
  call(["git", "commit", "-m", "update file: " + f])
  call(["git", "push", "origin", "master"])


T = int(input())

for tc in range(1, T + 1):
    print(f'#{tc}', end=" ")
    N = int(input())
    numbers = list(map(int, input().split()))
    total = []

    for n1 in range(N):
        for n2 in range(n1, N):
            if n1 != n2:
                total.append(numbers[n1] * numbers[n2])

    danzo = []

    for num in total:
        is_danzo = True
        target = num

        while target > 0:
            back = target % 10
            target = target // 10
            front = target % 10

            if front > back:
                is_danzo = False
                break

        if is_danzo:
            danzo.append(num)

    if danzo:
        print(max(danzo))
    else:
        print(-1)

SWEA/D3/6190. 정곤이의 단조 증가하는 수/정곤이의 단조 증가하는 수.py

정곤이의 단조 증가하는 수.py


import time

import pytest

from docker import Client
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

def pytest_addoption(parser):
    parser.addoption(
        '--browser',
        action='store',
        default='firefox',
        help='browser used to run the tests')

@pytest.fixture(scope='module')
def browser(request):
    return request.config.getoption("--browser")

@pytest.fixture(scope='module')
def driver(request, browser):
    """ Fixture for selenium Webdriver using docker
    """
    if browser == 'firefox':
        browser_image = 'selenium/standalone-firefox'
        browser_dc = DesiredCapabilities.FIREFOX
    elif browser == 'chrome':
        browser_image = 'selenium/standalone-chrome'
        browser_dc= DesiredCapabilities.CHROME

    cli = Client(version='auto', tls=False)

    port_conf = cli.create_host_config(
        publish_all_ports=True, port_bindings={4444: ('127.0.0.1',)})

    container = cli.create_container(
        image=browser_image, ports=[4444], detach=True, host_config=port_conf)

    cli.start(container.get('Id'))
    request.addfinalizer(lambda: cli.stop(container.get('Id')))

    port_info = cli.port(container['Id'], 4444)[0]

    selenium_host = 'http://{}:{}/wd/hub'.format(
        port_info['HostIp'], port_info['HostPort'])

    timeout = time.time() + 10
    success = 'connect to {}'.format(selenium_host)

    for output in cli.logs(container['Id'], stream=True):
        if success in output or time.time() > timeout:
            break
        else:
            time.sleep(1)

    driver = webdriver.Remote(
        command_executor=selenium_host, desired_capabilities=browser_dc)

    return driver


from django.test import TestCase
from todo.models import TableTodo
from django.db.utils import IntegrityError

class TodoTest(TestCase):

    def setUp(self):
        self.todo_task = TableTodo(
            # task_id = 1
            task_name = 'Bird Watching',
            # task_status = 'not_started',
            # task_description 'Finish youtube 2 hr bird watching video'
            # created_on = ''_
            # finished_on = ''
        )
        self.todo_task.save()

    def test_create_task(self):
        self.assertIsInstance(self.todo_task, TableTodo)
        self.assertEquals(self.todo_task.task_name, 'Bird Watching')

    def test_create_nonunique_task(self):
        with self.assertRaises(IntegrityError):
            new_task = TableTodo(task_name = 'Bird Watching')
            new_task.save()

    def test_read_task(self):
        saved_task = TableTodo.objects.all()
        self.assertEquals(saved_task[0].task_name, 'Bird Watching')

    def test_update_status_completed(self):
        self.todo_task.task_status = 'completed'
        self.todo_task.save()

        saved_task = TableTodo.objects.first()
        self.assertIsNotNone(saved_task.finished_on, f'Date finished not found, actual: {saved_task.finished_on}')

    def test_delete_task(self):
        new_task = TableTodo(task_name='Delete me please')
        new_task.save()

        tasks = TableTodo.objects.all()
        self.assertEqual(tasks.count(), 2, msg='New task for delete test not added')

        new_task.delete()

        tasks = TableTodo.objects.all()
        self.assertEqual(tasks.count(), 1, msg='Task not deleted')


ip_address = input("Enter an IP address: ")

octets = ip_address.split(".")

binary_octets = []
for octet in octets:
    binary_octet = bin(int(octet))[2:].zfill(8)
    binary_octets.append(binary_octet)

subnet_mask = "255.255.255.0"
prefix = sum([bin(int(i)).count("1") for i in subnet_mask.split(".")])

#reversed_subnet_mask = subnet_mask[::-1]
#binary_ver_list = []
#for n in reversed_subnet_mask.split("."):
    #binary_ver = bin(int(n))[2:].zfill(8)
    #binary_ver_list.append(binary_ver)
#count=0
#for j in binary_ver_list:
    #while j!=1:
        #count=count+1
    #if j==1:
        #break

print("IP Address:", ip_address)
print("Binary Octets:", binary_octets)
print("Subnet Mask:", subnet_mask)
print("Prefix:", prefix)
#print("Host Number: ", count)


import tensorflow_datasets as tfds
import tensorflow as tf

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

def load_ds():
    examples, meta = tfds.load('ted_hrlr_translate/pt_to_en', with_info=True)
    print(examples)
    print(meta)

    train_ds, val_ds = examples['train'], examples['validation']
    print(train_ds)
    print(val_ds)

    for a in train_ds.take(2):
        print(a['pt'])
        print(a['en'])

def train():
    ds = load_ds()

if __name__ == "__main__":
    train()


from dash import dcc, html
import dash_bootstrap_components as dbc

from app import app

cameron_yap = dbc.Card([
    dbc.CardImg(src='assets/cameron_yap_cropped.jpg'),
    dbc.CardBody([
        html.H4(
            html.A('Cameron Yap', href='https://www.linkedin.com/in/cameron-yap-9b8234119'),
            style={'text-align': 'center'})
    ])
])

emily_christiansen = dbc.Card([
    dbc.CardImg(src='assets/emily_christiansen.jpeg'),
    dbc.CardBody([
        html.H4(
            html.A('Emily Christiansen', href='https://www.linkedin.com/in/emily-christiansen-65a644117/'),
            style={'text-align': 'center'})
    ])
])

madeleine_thompson = dbc.Card([
    dbc.CardImg(src='assets/madeleine_thompson.png'),
    dbc.CardBody([
        html.H4(html.A('Madeleine Thompson', href='https://www.linkedin.com/in/madeleine-jane-thompson/'),
        style={'text-align': 'center'})
    ])
])

stefan_lin = dbc.Card([
    dbc.CardImg(src='assets/stefan_lin_cropped.jpeg'),
    dbc.CardBody([
        html.H4(
            html.A('Stefan Lin', href='https://www.linkedin.com/in/stefanemoses'),
            style={'text-align': 'center'})
    ])
])

layout = html.Div([
    # Header container
    dbc.Container([
        dbc.Row([
            dbc.Col(html.H1('Predicting House Prices'))
        ]),
        dbc.Row([
            dbc.Col(html.Div(
                'Cameron Yap, Emily Christiansen, Madeleine Thompson, and Stefan Lin'))
        ]),
        html.Br()
    ]),

    # Content container
    dbc.Container([
        dbc.Row([
            dbc.Col(html.H3('About our project'))
        ]),
        dbc.Row([
            dbc.Col(html.Div("""
            We have developed predictive models to accurately forecast rent prices and analyze local rent level trends in relation to environmental quality metrics in Los Angeles County. This tool will serve as a predictive reference and could prove to be advantageous for a company to gain an informational edge over all other housing agencies. Our tool could also encourage state or local governments to pay attention to environmental trends in order to support the housing market in Los Angeles County.
            """))
        ]),

        html.Br(),
        dbc.Row([
            dbc.Col(html.H3("What's in this tool?"))
        ]),
        dbc.Row([
            dbc.Col(html.Div("""
            For all your rental needs, we have incorporated socio-environmental factors into our prediction model. What are your main concerns when renting a home? Do you worry about the surrounding socio-environmental issues such as safety, education, oil wells, air quality, and water pollution that can impact you and your partner, children and beloved furry friends? Our tool takes in your specific needs and concerns and helps you find the best locations and predicted price for your next rented home!
            """))
        ]),

        html.Br(),
        dbc.Row([
            dbc.Col(html.H3('About us'))
        ]),
        dbc.Row([
            dbc.Col(html.Div("""
            Index Zero is a data analytics consulting team at the University of Southern California. Our members are Cameron Yap, Emily Christiansen, Madeleine Thompson, and Stefan Lin. We are experts in technical data analytics and want to help you, residential renters, to find your next home in Los Angeles County.
            """))
        ]),
        html.Br(),
        dbc.Row([
            dbc.Col(cameron_yap),
            dbc.Col(emily_christiansen),
            dbc.Col(madeleine_thompson),
            dbc.Col(stefan_lin),
        ])
    ])
])


from copy import deepcopy
import import_ipynb
import numpy as np
import tsaug
import h5py
import EMGImg
import math
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt

colors=list(mcolors.TABLEAU_COLORS.keys()) #颜色变化
# 按动作次数将手势分割（数据，手势类别，通道数）

def segment(data, dataclass, channel):
    data = np.array(data)
    Datalist = []
    for j in range(1, dataclass + 1):
        num = 0
        while (num < 6):
            for i in range(data.shape[0]):
                if data[i, channel] == j:  # alldata最后一维存储标签
                    start = i
                    break
            for k in range(start, data.shape[0]):
                if data[k, channel] == 0:
                    end = k
                    break
                if k == len(data) - 1:
                    end = data.shape[0]
                    break

            print(start, end)
            num = num + 1
            emg = (deepcopy(data[start:end, 0:channel]))
            label = (deepcopy(data[start:end, channel]))
            myemg = EMGImg.EMG(emg, label)
            Datalist.append(myemg)  # 用append将每次动作分割为单独的元素,保存了emg数据和标签
            for m in range(start, end):
                data[m, channel] = 100
    return Datalist  # 返回数据为list类型，保存不同长度的数据

'''该函数在输入二维数组时会将各个通道随机打乱，破坏了不同电极采样的同步性，故设定随机种子，单个通道依次打乱'''
def OneenhanceEMG(data):
    newdata =tsaug.TimeWarp(n_speed_change=1, max_speed_ratio=2, seed=123).augment(data)
#     enhancedata =np.hstack((data, newdata))
    return data, newdata

for j in range(1, 2):
    h5 = h5py.File('F:/DB2/filter/DB2_s' + str(j) + 'filter.h5', 'r')
    alldata = h5['alldata']
    seglist = segment(alldata, 2, 12)
    timedata=seglist[0].data
    data=[]
    newdata=[]
    for k in range(12):
            datasample, newdatasample =OneenhanceEMG(timedata[:,k])
            data.append(datasample)
            newdata.append(newdatasample)
    data=np.array(data)
    newdata=np.array(data)
    plt.figure(figsize=(20,8))
    for i in range(12):
        plt.subplot(12,1,i+1)
        plt.plot(data[:,i],color=mcolors.TABLEAU_COLORS[colors[int(math.fabs(i-2))]])
    #         plt.xticks([])  #去掉x轴
        plt.axis('off')
    plt.show()

# for j in range(1, 2):
#     h5 = h5py.File('F:/DB2/filter/DB2_s' + str(j) + 'filter.h5', 'r')
#     alldata = h5['alldata']
#     seglist = segment(alldata,2, 12)
#     timedata=seglist[0].data
#
#     data, newdata =enhanceEMG((timedata))
#
#
#     plt.figure(figsize=(20,8))
#     for i in range(12):
#         plt.subplot(12,1,i+1)
#         plt.plot(data[:,i],color=mcolors.TABLEAU_COLORS[colors[int(math.fabs(i-2))]])
#         #         plt.xticks([])  #去掉x轴
#         plt.axis('off')
#     plt.show()


# Question 11: Write a code to extract each digit from an integer
# , in the reverse order

def reverseOrder(num):
    while num > 0:
        reverseNum = num % 10
        num = num // 10
        print(reverseNum, end = ' ')

reverseOrder(12345)


from django.db import models
from django.contrib.auth.models import User
from product.models import Package

class Ship(models.Model):

    product = models.ForeignKey(Package, default=None, on_delete=models.CASCADE)
    driver = models.ForeignKey(User, default=None, on_delete=models.CASCADE)
    shipping_id = models.AutoField(primary_key=True)
    shipping_datetime = models.DateTimeField(auto_now=True)
    delivered_datetime = models.DateTimeField(null=True)
    delivered = models.BooleanField(default=True)

    def __str__(self):
        return str(self.shipping_id)

class Drop(models.Model):

    drop_id = models.AutoField(primary_key=True)
    drop_code = models.CharField(max_length=8)
    region = models.CharField(max_length=200)
    city = models.CharField(max_length=200)
    drop_datetime = models.DateTimeField(auto_now=True)
    manager = models.CharField(max_length=200)

    def __str__(self):
        return str(self.drop_id)