import json
import time

from BaseClass import ProtocolObject

class NetworkPlayer(ProtocolObject):
	def __init__(self, conn, addr):
		# Assigns self.buffer and self.conn
		super().__init__()
		self.conn = conn
		self.ip_address = addr[0]
		self.port = addr[1]

		self.nickname = None
		self.init = None
		self.waiting = 0
		self.game_player = None
		self.index = None

	def validate(self):
		# Called before player is assigned a lobby
		init = self.get_command()
		if init == "1":
			self.send_command("9")
			return True
		else:
			return False

	def get_nickname(self):
		# Called before player is assigned a lobby
		command = self.get_command()
		if command == "disconnected":
			# TODO
			raise Exception

		if not command:
			# If we didn't get anything
			return False, None
		else:
			command = json.loads(command)
			self.nickname = command["name"]
			return True, self.nickname

	def accept_name(self):
		to_send = json.dumps({"cf": True})
		self.send_command(to_send)

	def reject_name(self):
		to_send = json.dumps({"cf": False})
		self.send_command(to_send)

	def send_names(self, names, lobby_id):
		# Called once after a player has been added to a lobby
		to_send = json.dumps({"names": names, "id": lobby_id}, separators=(',', ':'))
		self.send_command(to_send)

	def update(self, time_left, no_of_players, new_players, lost_players, started):
		# Called once every few seconds while we're in the lobby
		# Send info to the client
		to_send = {}
		to_send["time"] = time_left
		to_send["players"] = no_of_players
		to_send["new"] = new_players
		to_send["lost"] = lost_players
		to_send["st"] = started

		to_send = json.dumps(to_send, separators=(',', ':'))

		self.send_command(to_send)
		self.waiting += 1

	def receive(self):
		# Called while we are in the lobby to check if the client is responding
		if self.waiting > 0:
			s = self.get_command()
			if s == "disconnected" or self.waiting > 5:
				return "disconnected"
			elif not s:
				return False
			s = json.loads(s)
			if s and (s["cf"] != 5):
				raise Exception("5 not returned from client")
			if s["cf"] == 5:
				self.waiting -= 1
				return True
		return False

	def start_game(self, index, names):
		self.index = index
		to_send = {"index": index, "names": names}
		to_send = json.dumps(to_send, separators=(',', ':'))
		self.send_command(to_send)

	def start_round(self, dice_list, dice_quantities):
		# Called at the beginning of each round to tell the client how many dice
		# there are, and what their dice are.
		# Convert a list of ints into a string
		to_send = {"i": "@", "dice": dice_list, "dice_q": dice_quantities}
		to_send = json.dumps(to_send, separators=(',', ':'))
		self.send_command(to_send)

	def send_current_player(self, player_no):
		# Tell every player who's turn it is
		to_send = {"i": "?", "player": player_no}
		to_send = json.dumps(to_send, separators=(',', ':'))
		self.send_command(to_send)

	def get_turn(self):
		# Called when it is this player's turn, so we wait until they respond
		while True:
			command = self.get_command()
			if command:
				if command == "disconnected":
					# TODO something
					print("Client " + self.nickname + " disconnected")
					exit()

				else:
					turn = json.loads(command)
					bid = turn["bid"]
					if bid == "dudo":
						return "dudo"
					bid = tuple(bid)
					print("Bid received from " + self.nickname + ": " + str(bid))
					return bid

	def send_turn(self, bid):
		# Called after a turn has happened, we are telling our player what
		# the turn was.
		to_send = {"i": "sendturn", "bid": bid}
		to_send = json.dumps(to_send, separators=(',', ':'))
		self.send_command(to_send)

	def send_dudo(self, player_no, is_out, all_dice):
		to_send = {"i": "senddudo", "player": player_no, "out": is_out, "alldice": all_dice}
		to_send = json.dumps(to_send, separators=(',', ':'))
		self.send_command(to_send)

	def send_player_out(self, player_no):
		to_send = {"i": "sendplayerout", "player": player_no}
		to_send = json.dumps(to_send, separators=(',', ':'))
		self.send_command(to_send)

	def end_game(self):
		# TODO
		to_send = {"i": "endgame"}
		to_send = json.dumps(to_send, separators=(',', ':'))
		self.send_command(to_send)


# -*- coding: utf-8 -*-
# test_app.settings
DEBUG = True
TEMPLATE_DEBUG = True

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'test_db'
    }
}

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

MIDDLEWARE_CLASSES = [
    # default django middleware
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
]

TEMPLATE_CONTEXT_PROCESSORS = [
    'django.contrib.messages.context_processors.messages',
    'django.contrib.auth.context_processors.auth',
]

STATIC_URL = "/static/"

SECRET_KEY = "secret"

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
    },
    'loggers': {
        '': {
            'handlers': ['console'],
            'propagate': True,
            'level': 'ERROR',
        },
        # 'django': {
        #     'handlers': ['console'],
        #     'propagate': True,
        #     'level': 'WARNING',
        # },
    }
}

ROOT_URLCONF = 'test_app.urls'

###################################################
try:
    import coverage
    import django_coverage
    INSTALLED_APPS += ('django_coverage',)
    # Specify a list of regular expressions of module paths to exclude
    # from the coverage analysis. Examples are ``'tests$'`` and ``'urls$'``.
    # This setting is optional.
    COVERAGE_MODULE_EXCLUDES = [
        'tests$',
        'settings$',
        'urls$',
        'locale$',
        'common.views.test',
        '__init__',
        'django',
        'migrations',
        'request_profiler.admin',
        'request_profiler.signals',
    ]
    COVERAGE_REPORT_HTML_OUTPUT_DIR = 'coverage/html'
    COVERAGE_USE_STDOUT = True
except ImportError:
    print(u"Missing coverage or django-coverage packages.")


# -*- coding: utf-8 -*-
###############################################################################
#                           "A BEER-WARE LICENSE"                             #
# ----------------------------------------------------------------------------#
# Feel free to do whatever you wish with this file. Since we most likey will  #
# never meet, buy a stranger a beer. Give credit to ALL named, unnamed, past, #
# present and future dev's of this & files like this. -Share the Knowledge!   #
###############################################################################

# Addon Name: Fuzzy Britches v3 Scrapers
# Addon id: script.module.fuzzybritchesv3scrapers
# Addon Provider: The Papaw

'''
Included with the Fuzzy Britches Add-on
'''

import re

from fuzzybritchesscrapers import parse_qs, urljoin, urlencode, quote_plus, unquote_plus
from fuzzybritchesscrapers.modules import cleantitle, client, debrid, source_utils

from fuzzybritchesscrapers import custom_base_link
custom_base = custom_base_link(__name__)

class source:
    def __init__(self):
        self.priority = 1
        self.language = ['en']
        self.domains = ['btscene.today']
        self.base_link = custom_base or 'http://btscene.nl'
        self.search_link = '/search?q=%s'
        self.aliases = []

    def movie(self, imdb, title, localtitle, aliases, year):
        try:
            self.aliases.extend(aliases)
            url = {'imdb': imdb, 'title': title, 'year': year}
            url = urlencode(url)
            return url
        except:
            return

    def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
        try:
            self.aliases.extend(aliases)
            url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year}
            url = urlencode(url)
            return url
        except:
            return

    def episode(self, url, imdb, tvdb, title, premiered, season, episode):
        try:
            if url is None:
                return
            url = parse_qs(url)
            url = dict([(i, url[i][0]) if url[i] else (i, '') for i in url])
            url['title'], url['premiered'], url['season'], url['episode'] = title, premiered, season, episode
            url = urlencode(url)
            return url
        except:
            return

    def sources(self, url, hostDict, hostprDict):
        sources = []
        try:
            if url is None:
                return sources
            if debrid.status() is False:
                return sources
            data = parse_qs(url)
            data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])

            title = data['tvshowtitle'] if 'tvshowtitle' in data else data['title']
            hdlr = 's%02de%02d' % (int(data['season']), int(data['episode'])) if 'tvshowtitle' in data else data['year']

            query = ' '.join((title, hdlr))
            query = re.sub('(\\\|/| -|:|;|\*|\?|"|\'|<|>|\|)', ' ', query)

            url = self.search_link % quote_plus(query)
            url = urljoin(self.base_link, url)

            r = client.request(url)
            posts = client.parseDOM(r, 'tr')
            for post in posts:
                try:
                    links = re.findall('a title="Download Torrent Magnet" href="(magnet:.+?)"', post, re.DOTALL)
                    try:
                        size = re.findall('((?:\d+\,\d+\.\d+|\d+\.\d+|\d+\,\d+|\d+)\s*(?:GiB|MiB|GB|MB))', post)[0]
                        dsize, isize = source_utils._size(size)
                    except:
                        dsize, isize = 0.0, ''
                    for link in links:
                        link_name = unquote_plus(link)

                        url = link_name.split('&tr=')[0]
                        if any(x in url for x in ['FRENCH', 'Ita', 'italian', 'TRUEFRENCH', '-lat-', 'Dublado']):
                            continue

                        name = cleantitle.get_title(url.split('&dn=')[1])
                        if not source_utils.is_match(name, title, hdlr, self.aliases):
                            continue

                        quality, info = source_utils.get_release_quality(name, url)
                        info.insert(0, isize)
                        info = ' | '.join(info)
                        sources.append({'source': 'Torrent', 'quality': quality, 'language': 'en', 'url': url, 'info': info,
                                        'direct': False, 'debridonly': True, 'size': dsize, 'name': name})
                except:
                    pass
            return sources
        except:
            return sources

    def resolve(self, url):
        return url


import pathlib
from itertools import product
from PIL import Image
from numpy import asarray

input_path = pathlib.Path(__file__).parent / "input.txt"

class GridIterator:
    def __init__(self):
        self.iterator = product(range(100), range(100))

    def __iter__(self):
        return self.iterator

print("first star:")
grid = [[0] * 100 for _ in range(100)]
with open(input_path, "r") as input_file:
    for row, line in enumerate(input_file):
        for column, number in enumerate(line.strip()):
            grid[column][row] = int(number)

print(grid[0])
total_danger = 0
EDGES = {0, 99}
for row, column in GridIterator():
    left = max(0, column - 1)
    right = min(99, column + 1)
    up = max(0, row - 1)
    down = min(99, row + 1)
    middle = grid[column][row]
    greaters = 0
    if row in EDGES:
        greaters += 1
    if column in EDGES:
        greaters += 1
    if grid[column][up] > middle:
        greaters += 1
    if grid[column][down] > middle:
        greaters += 1
    if grid[left][row] > middle:
        greaters += 1
    if grid[right][row] > middle:
        greaters += 1
    if greaters == 4:
        total_danger += middle + 1
print(f"total danger: {total_danger}")

print("second star:")
# turn the table into a binary grid; replace all 9s with high values,
# everything else with 0.
HIGH = 100000
for row, column in GridIterator():
    grid[column][row] = HIGH if grid[column][row] == 9 else 0

# "paint" in the areas with 2s, keeping count of how many cells
# were filled in per connected area.
def get_neighbors(column, row):
    retval = []
    if column > 0:
        retval.append((column - 1, row))
    if column < 99:
        retval.append((column + 1, row))
    if row > 0:
        retval.append((column, row - 1))
    if row < 99:
        retval.append((column, row + 1))
    return retval

paint = 1
stack = []

for row, column in GridIterator():
    if grid[column][row] != 0:
        continue
    stack.append((column, row))
    while len(stack) > 0:
        current_c, current_r = stack.pop()
        if grid[current_c][current_r] == 0:
            grid[current_c][current_r] = paint
            stack.extend(get_neighbors(current_c, current_r))
    paint += 1
    print(f" done painting {paint-1}")

# Grid is now painted in; time to see which color "won."
counts = {}

for row, column in GridIterator():
    val = grid[column][row]
    if val != HIGH:
        counts[val] = counts.get(val, 0) + 1

paints = counts.keys()
cell_count = counts.values()
sorted_counts = [
    (paint_, count)
    for (paint_, count) in sorted(
        zip(paints, cell_count), key=lambda x: x[1], reverse=True
    )
]
print(f"Top three: {sorted_counts[0]}, {sorted_counts[1]}, {sorted_counts[2]}.")
print(
    f"Product of top three: {sorted_counts[0][1] * sorted_counts[1][1] * sorted_counts[2][1]}"
)

# Silly extra thing that is really not needed but scratch
# it, I'm doing it anyway.
output_image = Image.new("HSV", (100, 100))
editable_image = asarray(output_image)
for row, column in GridIterator():
    val = grid[column][row]
    if val != HIGH:
        hue = (val / paint) * 255
        editable_image[column, row] = (hue, 250, 250)
output_path = pathlib.Path(__file__).parent / "out.png"
Image.fromarray(editable_image, mode="HSV").convert(mode="RGB").save(output_path)


import shutil
import os
import glob
from utilities.Logger import Logger

class ExploitableGdbPlugin:
    #If you wrote the gdb output to a different directory than where the input crash file lived,
    #I'm sorry, you can not use this class
    classifications = ["EXPLOITABLE", "PROBABLY_EXPLOITABLE", "PROBABLY_NOT_EXPLOITABLE", "UNKNOWN" ]

    def __init__(self, config, search_dir, output_dir=None):
        self.config = config
        self.search_dir = search_dir
        #output directory will be just the same place where the input file is if output_dir is None
        self.output_dir = output_dir

    @staticmethod
    def get_classifications():
        return ExploitableGdbPlugin.classifications

    def divide_by_exploitability(self, function=shutil.move):
        if self.output_dir is not None and not os.path.exists(self.output_dir):
            os.mkdir(self.output_dir)
        for path, _, files in os.walk(self.search_dir):
            for filename in files:
                if filename.endswith(self.config.run_extension):
                    continue
                filepath = os.path.join(path, filename)
                gdb_out_filepath = filepath+self.config.get_gdb_exploitable_file_extension()
                if os.path.exists(gdb_out_filepath):
                    file_content = file(gdb_out_filepath, "rb").read()
                    out_dir_main = self.output_dir
                    if out_dir_main is None:
                        out_dir_main = path
                    out_dir = os.path.join(out_dir_main, "UNCATEGORIZED") + os.path.sep
                    for classification in self.classifications:
                        if self._get_search_string_for_classification(classification) in file_content:
                            out_dir = os.path.join(out_dir_main, classification) + os.path.sep
                            break
                    if not os.path.exists(out_dir):
                        os.mkdir(out_dir)
                    Logger.debug("Moving", filepath+"* to", out_dir, debug_level=4)
                    for file_all_extensions in glob.glob(filepath+"*"):
                        function(file_all_extensions, out_dir)
                else:
                    Logger.warning("Seems like there is no gdb output file %s, can not find exploitability" % gdb_out_filepath)

    def _get_search_string_for_classification(self, classification):
        return "Exploitability Classification: "+classification


# Create a program that reads the length and width of a farmer’s field from the user in
# feet. Display the area of the field in acres.
# Hint: There are 43,560 square feet in an acre.

def feet(length, width):
    area = length * width
    area_acre = area / 43560

    return area_acre

print(feet(50,50))


from collections import Counter
import matplotlib.pyplot as plt
import numpy as np
import os
import torch
import torchvision.transforms as transform
from torch.utils.data import Dataset
from tqdm import tqdm
from PIL import Image

#shape1: h: 256, w: 320
#shape2: h:224, w:224

SUIM_CLASSES = ('background',
                'Human',
               'Robot',
               'Fish',
               'Reef',
               'Wreck')

NUM_CLASSES = len(SUIM_CLASSES)

class PascalVOCDataset(Dataset):

    def __init__(self, img_dir, mask_dir, image_shape=(224, 224), n_channels=3, transform=None):
        #self.images = open(list_file, "rt").read().split("\n")[:-1]

        self.imgshape = image_shape
        self.n_channels = n_channels
        self.img_extension = ".jpg"
        self.mask_extension = ".bmp"

        self.image_root_dir = img_dir
        self.mask_root_dir = mask_dir
        self.transform = transform

        #self.counts = self.__compute_class_probability()

    def __len__(self):
        return len(os.listdir(self.image_root_dir))

    def __getitem__(self, index):
        image_name = os.listdir(self.image_root_dir)[index]
        name = image_name.split('.')[0]
        image_path = os.path.join(self.image_root_dir, name + self.img_extension)
        mask_path = os.path.join(self.mask_root_dir, name + self.mask_extension)

        image = self.load_image(path=image_path)
        gt_mask = self.load_mask(path=mask_path)

        data = {
                    'image': torch.FloatTensor(image),
                    'mask' : torch.LongTensor(gt_mask)
                    }

        return data

    def load_image(self, path=None):
        raw_image = Image.open(path)
        raw_image = raw_image.resize((224, 224))
        raw_image = transform.Grayscale(3)(raw_image)
        imx_t = np.array(raw_image, dtype=np.float32)/255.0

        # print(imx_t.shape)
        return imx_t

    def load_mask(self, path=None):
        raw_image = Image.open(path)
        raw_image = raw_image.resize((224, 224))
        raw_image = np.array(raw_image)
        raw_image = raw_image/255.0
        raw_image[raw_image > 0.5] = 1
        raw_image[raw_image <= 0.5] = 0
        mask = []
        mask.append(self.getDiffMask(raw_image))
        # import ipdb;ipdb.set_trace()
        imx_t = np.array(mask).squeeze()
        # print(imx_t.shape)
        # border
        #imx_t[imx_t==255] = len(VOC_CLASSES)

        return imx_t

    def getDiffMask(self, mask):
        imw, imh = mask.shape[0], mask.shape[1]

        #################
        # softmax
        #################
        background = np.ones((imw, imh))
        Human1 = np.zeros((imw, imh))
        Robot1 = np.zeros((imw, imh))
        Fish1 = np.zeros((imw, imh))
        Reef1 = np.zeros((imw, imh))
        Wreck1 = np.zeros((imw, imh))

        mask_idx = np.where((mask[:,:,0] == 0) & (mask[:,:,1] == 0) & (mask[:,:,2] == 1))
        Human1[mask_idx] = 1
        background[mask_idx] = 0

        mask_idx = np.where((mask[:,:,0] == 1) & (mask[:,:,1] == 0) & (mask[:,:,2] == 0))
        Robot1[mask_idx] = 1
        background[mask_idx] = 0

        mask_idx = np.where((mask[:,:,0] == 1) & (mask[:,:,1] == 1) & (mask[:,:,2] == 0))
        Fish1[mask_idx] = 1
        background[mask_idx] = 0

        mask_idx = np.where((mask[:,:,0] == 1) & (mask[:,:,1] == 0) & (mask[:,:,2] == 1))
        Reef1[mask_idx] = 1
        background[mask_idx] = 0

        mask_idx = np.where((mask[:,:,0] == 0) & (mask[:,:,1] == 1) & (mask[:,:,2] == 1))
        Wreck1[mask_idx] = 1
        background[mask_idx] = 0

        return np.stack((background, Robot1, Fish1, Human1, Reef1, Wreck1), -1)

        '''
        #################
        # Sigmoid
        #################
        Human = np.zeros((imw, imh))
        Robot = np.zeros((imw, imh))
        Fish = np.zeros((imw, imh))
        Reef = np.zeros((imw, imh))
        Wreck = np.zeros((imw, imh))

        mask_idx = np.where((mask[:,:,0] == 0) & (mask[:,:,1] == 0) & (mask[:,:,2] == 1))
        Human[mask_idx] = 1

        mask_idx = np.where((mask[:,:,0] == 1) & (mask[:,:,1] == 0) & (mask[:,:,2] == 0))
        Robot[mask_idx] = 1

        mask_idx = np.where((mask[:,:,0] == 1) & (mask[:,:,1] == 1) & (mask[:,:,2] == 0))
        Fish[mask_idx] = 1

        mask_idx = np.where((mask[:,:,0] == 1) & (mask[:,:,1] == 0) & (mask[:,:,2] == 1))
        Reef[mask_idx] = 1

        mask_idx = np.where((mask[:,:,0] == 0) & (mask[:,:,1] == 1) & (mask[:,:,2] == 1))
        Wreck[mask_idx] = 1

        return np.stack(( Robot, Fish, Human, Reef, Wreck), -1)
        '''
if __name__ == "__main__":
    img_dir = './train_val/images'
    mask_dir = './train_val/masks'

    objects_dataset = PascalVOCDataset(img_dir=img_dir,
                                       mask_dir=mask_dir)

    #print(objects_dataset.get_class_probability())

    sample = objects_dataset[519]
    image, mask = sample['image'], sample['mask']

    #image.transpose_(0, 2)

    fig = plt.figure()

    a = fig.add_subplot(1,2,1)
    plt.imshow(image)
    print(image.shape)
    a = fig.add_subplot(1,2,2)
    print(mask.shape)
    mask.transpose_(0,2)
    mask.transpose_(0,1)
    plt.imshow(mask[:,:,:, 0])
    #fig.savefig('test_0.png')
    plt.show()

    # 0: robot
    # 1: fish
    # 2: human
    # 3: reef
    # 4: wreck


import random
import time
print("""
*********************
sayı tahmin etme oyunu

*********************

1 ile 40 arasındaki sayıyı tahmin etme

""")
rastgele_sayı = random.randint(1,40)

while True:
    tahmin_hakkı=7
    tahmin = int(input("Tahmininiz: "))

    if(tahmin < rastgele_sayı):
        print("Bilgiler Sorgulanıyor...")
        time.sleep(2)

        print("Daha yüksek bir sayı söyleyiniz...")

    elif(tahmin > rastgele_sayı):
         print("Bilgiler Sorgulanıyor...")
         time.sleep(2)

         print("Daha düşük bir sayı söyleyiniz...")

         tahmin_hakkı -= 1
    else:
        print("Bililer Sorgulanıyor...")

        time.sleep(2)
        print("Tebrikler Sayınız", rastgele_sayı)
        break

    if(tahmin_hakkı ==0):
        print("Tahmin hakkınız Bitti...")
        print("Sayınız...", rastgele_sayı)


import keras
import keras.backend as K
from keras.layers import (
    Input,
    Conv2D,
    GaussianNoise,
    DepthwiseConv2D,
    ZeroPadding2D,
    Add
)

from keras.models import Model

from .layers import _normalization, _activation, _downsizing, _se_block

def Conv2D_same(x, filters, strides=1, kernel_size=3, rate=1):
    if strides == 1:
        return Conv2D(filters, (kernel_size, kernel_size),
                      strides=(strides, strides),
                      padding='same',
                      use_bias=False,
                      dilation_rate=(rate, rate))(x)

    else:
        kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1)
        pad_total = kernel_size_effective - 1
        pad_beg = pad_total // 2
        pad_end = pad_total - pad_beg
        x = ZeroPadding2D((pad_beg, pad_end))(x)
        return Conv2D(filters, (kernel_size, kernel_size),
                      strides=(strides, strides),
                      padding='valid', use_bias=False,
                      dilation_rate=(rate, rate))(x)

def SeparableConvBlock(x, filters, kernel_size=3, strides=1, rate=1, activation='relu', norm='bn', last_activation=False):
    '''
    Separable Convolution Block used in MobileNet and Xception
    '''
    if strides == 1:
        padding = 'same'
    else:
        kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1)
        pad_total = kernel_size_effective - 1
        pad_beg = pad_total // 2
        pad_end = pad_total - pad_beg
        x = ZeroPadding2D((pad_beg, pad_end))(x)
        padding='valid'

    if not last_activation:
        x = _activation(x, activation=activation)

    # Depwise Convolution
    x = DepthwiseConv2D((3, 3), strides=(strides, strides), use_bias=False, padding=padding,
                        dilation_rate=(rate, rate))(x)
    x = _normalization(x, norm=norm)
    x = _activation(x, activation=activation)

    # Pointwise Convolution
    x = Conv2D(filters, (1, 1), use_bias=False, padding='same')(x)
    x = _normalization(x, norm=norm)
    if last_activation:
        x = _activation(x, activation=activation)

    return x

def xception_block(inputs, filters, strides, rate=1, mode='conv', activation='relu', norm='bn', is_seblock=False, last_activation=False):
    '''
    Xception Block in DeepLabv3+
    '''

    x = inputs
    for i in range(3):
        x = SeparableConvBlock(x, filters[i],
                               strides=strides if i == 2 else 1,
                               rate=rate,
                               activation=activation,
                               norm=norm,
                               last_activation=last_activation)

        if i == 1:
            skip = x

    if is_seblock:
        x = _se_block(x, filters=filters[2])
    if mode == 'conv':
        residual = Conv2D_same(inputs, filters[1], kernel_size=1, strides=strides)
        residual = _normalization(residual, norm=norm)
        x = Add()([x, residual])
    elif mode == 'sum':
        x = Add()([x, inputs])

    return x, skip

def Xception_modified(
    input_shape=(256, 256, 1),
    norm='bn',
    activation='relu',
    downsizing='pooling',
    divide=1.,
    is_seblock=False,
    **kwargs):

    img_input = Input(shape=input_shape)

    # Entry flow
    c1 = GaussianNoise(0.1)(img_input)
    c1 = Conv2D(int(32/divide), (3, 3), strides=(2, 2), use_bias=False, padding='same')(c1)
    c1 = _normalization(c1, norm=norm)
    c1 = _activation(c1, activation=activation)
    c1 = Conv2D_same(c1, int(64/divide), kernel_size=3, strides=1)
    c1 = _normalization(c1, norm=norm)
    c1 = _activation(c1, activation=activation)

    c2, c2_out = xception_block(c1, [int(128/divide), int(128/divide), int(128/divide)], 2, 1, mode='conv', activation=activation, norm=norm, is_seblock=is_seblock)
    c3, c3_out = xception_block(c2, [int(256/divide), int(256/divide), int(256/divide)], 2, 1, mode='conv', activation=activation, norm=norm, is_seblock=is_seblock)
    c4, c4_out = xception_block(c3, [int(728/divide), int(728/divide), int(728/divide)], 2, 1, mode='conv', activation=activation, norm=norm, is_seblock=is_seblock)

    # Middle flow
    c5 = c4
    for i in range(8):
        c5, _ = xception_block(c5, [int(728/divide), int(728/divide), int(728/divide)], 1, 1, mode='sum', activation=activation, norm=norm, is_seblock=is_seblock)

    # Exit flow
    c5, c5_out = xception_block(c5, [int(728/divide), int(1024/divide), int(1024/divide)], 2, 1, mode='conv', activation=activation, norm=norm, is_seblock=is_seblock)
    c6, _ = xception_block(c5, [int(1536/divide), int(1536/divide), int(2048/divide)], 1, 2, mode='none', activation=activation, norm=norm, is_seblock=False, last_activation=True)

    model = Model([img_input], [c2_out, c3_out, c4_out, c5_out, c6], name='xception_modified')

    return model

if __name__ == "__main__":
    model = Xception_modified(input_shape=(256, 256, 1))
    model.summary()


# Pandas Python module is used in this file.
#   Licence: BSD-3-Clause License
#   Link: https://github.com/pandas-dev/pandas

import pandas as pd
from ._base_metric import BaseMetric
from ._cycle_metric import CycleMetric

class TransitionMetric(BaseMetric):
    """
    Class that contains metrics connected with edges.

    Parameters
    ----------
    data_holder : DataHolder
        Object that contains the event log and the names of its necessary columns.

    time_unit : {'s'/'second', 'm'/'minute', 'h'/'hour', 'd'/'day', 'w'/'week'}, default='day'
        Calculate time in needed format.

    Attributes
    ----------
    _data_holder : DataHolder
        Object that contains the event log and the names of its necessary columns.

    _group_column : str
        Column used for grouping the data.

    _group_data: pandas.GroupBy object
        Object that contains pandas.GroupBy data grouping by _group_column.

    _user_column : str
        Column of users in event log.

    metrics: pd.DataFrame
        DataFrame contain all metrics that can be calculated

    _unique_edges: pd.Series
        Contain all edges of event log
    """

    def __init__(self, data_holder, time_unit='day', cycle_length=2):
        super().__init__(data_holder, time_unit)
        self._cycle_metric = CycleMetric(data_holder, cycle_length)
        self._group_column = data_holder.activity_column
        _edge_data = data_holder.data[
            [data_holder.id_column, data_holder.activity_column, data_holder.duration_column]].copy()
        if self._user_column:
            _edge_data.loc[:, self._user_column] = data_holder.data[self._user_column]

        if data_holder.start_timestamp_column is not None and data_holder.end_timestamp_column is None:
            start_activity_col = _edge_data[data_holder.activity_column]
            end_activity_col = _edge_data[data_holder.activity_column].shift(-1)
            start_id_col = _edge_data[data_holder.id_column]
            end_id_col = _edge_data[data_holder.id_column].shift(-1)
        else:
            start_activity_col = _edge_data[data_holder.activity_column].shift(1)
            end_activity_col = _edge_data[data_holder.activity_column]
            start_id_col = _edge_data[data_holder.id_column].shift(1)
            end_id_col = _edge_data[data_holder.id_column]

        _edge_data.loc[:, data_holder.activity_column] = tuple(start_activity_col + "-->" + end_activity_col)
        id_mask = start_id_col != end_id_col
        _edge_data.drop(_edge_data[id_mask].index, axis=0, inplace=True)
        self._edge_data = _edge_data
        self._unique_edges = _edge_data[self._group_column].unique()
        self._group_data = _edge_data.groupby(self._group_column)

    def apply(self, std=False):
        """
        Calculate all metrics:
        total_count: frequency of edge
        total_duration: total time duration of grouped objects
        min_duration: min time duration of grouped objects
        max_duration: max time duration of grouped objects
        mean_duration: mean time duration of grouped objects
        median_duration: median time duration of grouped objects
        variance_duration: variance of time duration of grouped objects
        std_duration: std of time duration of grouped objects
        """
        if self.metrics is None:
            self.metrics = self._group_data.agg({self._data_holder.id_column: set}).reset_index() \
                .rename(columns={self._data_holder.activity_column: 'transitions',
                                 self._data_holder.id_column: 'unique_ids'})
            self.metrics['total_count'] = self._group_data[self._group_column].count().values
            self._calculate_time_metrics(self.metrics, self._group_data, std)
            self.metrics['transitions'] = self.metrics['transitions'].apply(lambda x: self._split_tuple(x))
        return self.metrics.sort_values('total_count', ascending=False).reset_index(drop=True)

    def calculate_time_metrics(self, std=False):
        """
        Calculate time metrics
        """
        metrics_df = super().calculate_time_metrics(std=std)
        metrics_df[self._data_holder.activity_column] = metrics_df[self._data_holder.activity_column].apply(
            lambda x: self._split_tuple(x))
        return metrics_df

    def count(self):
        """
        Count how many was edge
        """
        res = self._group_data[self._group_column].count()
        res.index = [self._split_tuple(x) for x in res.index]
        return res

    def nunique_users(self):
        res = self._group_data[self._user_column].nunique()
        res.index = [self._split_tuple(x) for x in res.index]
        return res

    def sum_time(self):
        res = super().sum_time()
        res.index = [self._split_tuple(x) for x in res.index]
        return res

    def mean_time(self):
        res = super().mean_time()
        res.index = [self._split_tuple(x) for x in res.index]
        return res

    def median_time(self):
        res = super().median_time()
        res.index = [self._split_tuple(x) for x in res.index]
        return res

    def max_time(self):
        res = super().max_time()
        res.index = [self._split_tuple(x) for x in res.index]
        return res

    def min_time(self):
        res = super().min_time()
        res.index = [self._split_tuple(x) for x in res.index]
        return res

    @staticmethod
    def _split_tuple(x):
        """
        Split edges and transform edge from Activity1->Activity2 to tuple(Activity1,Activity2)
        """
        return tuple(x.split("-->"))

    def cycle(self):
        return self._cycle_metric.find()[1]


import math
import copy
import os

import rclpy
from rclpy.node import Node

from std_msgs.msg import String
from geometry_msgs.msg import PoseStamped
import mavros_msgs.msg, mavros_msgs.srv

class RateLimiter():
    def __init__(self,min_period,clock):
        self.min_period = rclpy.duration.Duration(seconds=min_period)
        self.clock = clock
        self.time_of_last = None

    def call(self,func):
        if self.time_of_last is None:
            self.time_of_last = self.clock.now()
            time_since_last = self.min_period
        else:
            time_since_last = self.clock.now() - self.time_of_last

        if time_since_last > self.min_period:
            func()

class DemoController(Node):

    def __init__(self):
        super().__init__('demo_controller')
        self.logger = self.get_logger()

        # if target_name is None or target_name == '':
        #     self.declare_parameter('target', '')
        #     target_name = self.get_parameter('target').get_parameter_value().string_value

        self.logger.info(f'Controller namespace is {self.get_namespace()}')

        self.start_mission_subscriber = self.create_subscription(
            String,
            '/mission_start',
            self.mission_start_callback,
            1)

        self.emergency_stop_subscriber = self.create_subscription(
            String,
            '/emergency_stop',
            self.emergency_stop_callback,
            1)

        self.position_subscriber = self.create_subscription(
            PoseStamped,
            f'mavros/local_position/pose',
            self.position_callback,
            1)

        self.state_subscriber = self.create_subscription(
            mavros_msgs.msg.State,
            f'mavros/state',
            self.state_callback,
            1)

        self.setpoint_publisher = self.create_publisher(
            PoseStamped,
            f'mavros/setpoint_position/local',
            1)

        self.offboard_rate_limiter = RateLimiter(1,self.get_clock())
        self.offboard_client = self.create_client(
            mavros_msgs.srv.SetMode,
            f'mavros/set_mode')

        self.arm_rate_limiter = RateLimiter(1,self.get_clock())
        self.arming_client = self.create_client(
            mavros_msgs.srv.CommandBool,
            f'mavros/cmd/arming')

        self.command_rate_limiter = RateLimiter(1, self.get_clock())
        self.command_client = self.create_client(
            mavros_msgs.srv.CommandLong,
            f'mavros/cmd/command'
        )

        self.takeoff_offset = 0
        self.land_offset = None
        self.flight_height = 5.0

        self.controller_command = 'Init'

        self.state = 'Init'

        timer_period = 0.02
        self.timer = self.create_timer(timer_period, self.timer_callback)

        self.vehicle_position = PoseStamped()
        self.vehicle_state = mavros_msgs.msg.State()

        self.initial_position = None
        self.flight_start_time = None
        self.flight_duration = rclpy.duration.Duration(seconds=10.0)

        self.land_start_time = None
        self.land_duration_before_estop = rclpy.duration.Duration(seconds=60.0)

        self.angle = 0

    def mission_start_callback(self, msg):
        self.controller_command = "Run"
        self.logger.info('\033[92m' + 'MISSION START RECEIVED: ' + str(msg) + '\033[0m')

    def emergency_stop_callback(self, msg):
        self.controller_command = "eStop"
        self.logger.warn('\033[91m' + 'EMERGENCY: ESTOP PRESS RECEIVED' + '\033[0m')

    def position_callback(self,msg):
        self.vehicle_position = msg

    def state_callback(self,msg):
        self.vehicle_state = msg

    def timer_callback(self):

        if self.state == 'DEAD':
            self.logger.info('Drone in Dead State, Switch Off or Restart Controller')
            self.timer.cancel()
            self.destroy_node()

        if self.controller_command == 'eStop':
            # Currently will just land and disarm
            self.eSTOP()
            self.state = 'DEAD'

        if self.state == 'Init':
            if self.initial_position == None and self.vehicle_position != None:
                self.initial_position = copy.deepcopy(self.vehicle_position)
                self.logger.info("Got initial position: ({},{},{})".format(
                    self.initial_position.pose.position.x,
                    self.initial_position.pose.position.y,
                    self.initial_position.pose.position.z
                    ))
                self.logger.info("Initialisation Confirmed, Going to ModeSwitch")
                self.state = 'ModeSwitch'

        if self.state == 'ModeSwitch':
            if self.vehicle_state.mode != "OFFBOARD":
                modeSetCall = mavros_msgs.srv.SetMode.Request()
                modeSetCall.custom_mode = "OFFBOARD"
                self.offboard_rate_limiter.call(lambda: self.offboard_client.call_async(modeSetCall))
            else:
                self.logger.info("Mode Switch Confirmed, Waiting for Mission Start, Before Arming")
                self.state = 'Arming'

        if self.state == 'Disarming':
            if self.vehicle_state.armed == True:
                armingCall = mavros_msgs.srv.CommandBool.Request()
                armingCall.value = False
                self.arm_rate_limiter.call(lambda: self.arming_client.call_async(armingCall))
            else:
                self.logger.info("Disarm Completed")
                self.state = 'DEAD'

        setpoint_msg = None
        if self.initial_position != None:
            setpoint_msg = PoseStamped()
            setpoint_msg.header.stamp = self.get_clock().now().to_msg()
            setpoint_msg.pose = copy.deepcopy(self.initial_position.pose)

        if self.state == 'Land':
            if self.land_offset is None:
                self.land_offset = self.vehicle_position.pose.position.z
                self.land_start_time = self.get_clock().now()
            elif self.land_offset > -10:
                self.land_offset -= 0.01
                setpoint_msg.pose.position.z += self.land_offset
            elif self.get_clock().now() - self.land_start_time > self.land_duration_before_estop:
                self.eSTOP()
                self.logger.info('Exceeded Time Required To Land eSTOP activated')
                self.state = 'DEAD'
            else:
                self.state = 'Disarming'
                self.logger.info('Landing Confirmed, Going to Disarming')

        if self.controller_command == 'Run':
            if self.state == 'Arming':
                if self.vehicle_state.armed != True:
                    armingCall = mavros_msgs.srv.CommandBool.Request()
                    armingCall.value = True
                    self.arm_rate_limiter.call(lambda: self.arming_client.call_async(armingCall))
                else:
                    self.state = 'Takeoff'
                    self.logger.info("Arm Completed, Going to Takeoff")

            if self.state == 'Takeoff':
                if self.takeoff_offset < self.flight_height:
                    self.takeoff_offset += 0.05
                    setpoint_msg.pose.position.z += self.takeoff_offset
                else:
                    setpoint_msg.pose.position.z += self.takeoff_offset
                    # Wait for takeoff to be complete
                    if self.vehicle_position.pose.position.z > self.flight_height * 0.95:
                        self.logger.info("Takeoff Confirmed, Going to Flight")
                        self.state = 'Flight'

            if self.state == 'Flight':
                if self.flight_start_time is None:
                    self.flight_start_time = self.get_clock().now()
                elif self.get_clock().now() - self.flight_start_time > self.flight_duration:
                    self.logger.info("Flight Completed, Going for Landing")
                    self.state = 'Land'
                else:
                    radius = 1.0
                    self.angle = (self.angle + 0.005) % (2*math.pi)
                    setpoint_msg.pose.position.x = radius * math.cos(self.angle)
                    setpoint_msg.pose.position.y = radius * math.sin(self.angle)
                    setpoint_msg.pose.position.z = self.flight_height

        if setpoint_msg != None:
            self.setpoint_publisher.publish(setpoint_msg)

    def eSTOP(self):
        # eStop achieved by sending ARM command (400)
        # with param2 set to 21196
        # see: https://github.com/PX4/PX4-Autopilot/issues/14465#issuecomment-603265985
        commandCall = mavros_msgs.srv.CommandLong.Request()
        commandCall.broadcast = False
        commandCall.command = 400
        commandCall.param1 = 0.0
        commandCall.param2 = 21196.0
        commandCall.param3 = 0.0
        commandCall.param4 = 0.0
        commandCall.param5 = 0.0
        commandCall.param6 = 0.0
        commandCall.param7 = 0.0
        self.command_rate_limiter.call(lambda: self.command_client.call_async(commandCall))
        self.logger.warn('\033[91m' + 'EMERGENCY: KILL SIGNAL SENT' + '\033[0m')

def main(args=None):
    rclpy.init(args=args)

    demo_controller = DemoController()
    demo_controller.get_logger().info('STARTING DEMO CONTROLLER NOW!')

    try:
        rclpy.spin(demo_controller)
    except rclpy.handle.InvalidHandle as e:
        # Raised by node destroying itself.
        demo_controller.get_logger().info('demo_controller exited')
    else:
        demo_controller.destroy_node()

    rclpy.shutdown()

if __name__ == "__main__":
    main()


import sys
from direct.showbase import DirectObject
from direct.showbase.ShowBase import NodePath
from panda3d.core import *

class Picker(DirectObject.DirectObject):
    def __init__(self, base_object, select, unselect):
        DirectObject.DirectObject.__init__(self)
        self._camNode = base_object.camNode
        self._render = base_object.render
        self._mwn = base_object.mouseWatcherNode

        self.picker = CollisionTraverser()
        self.queue = CollisionHandlerQueue()
        self.pickerNode = CollisionNode('mouseRay')
        self.pickerNP = base_object.cam.attachNewNode(self.pickerNode)

        self.pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)
        self.picker.addCollider(self.pickerNP, self.queue)

        # this holds the object that has been picked
        self.selected = None
        self.overlined = None
        self.picked_pos = None
        self.picked_normal = None
        self.select_func = select
        self.unselect_func = unselect

        self._mouse_X = 0.
        self._mouse_Y = 0.

        self.accept('mouse1', self.left_click)
        # self.accept('mouse3', self.right_click)

        self.pickable_objects = dict()
        base_object.taskMgr.add(self.mouse_move, 'mouse_move')

    def make_pickable(self, obj):
        obj.set_tag('pickable', 'true')

    def get_selected_object(self):
        return self.selected

    def get_selected_pos(self):
        return self.picked_pos

    def get_selected_normal(self):
        return self.picked_normal

    def get_object(self):
        self.pickerRay.setFromLens(self._camNode, self._mwn.getMouse())
        self.picker.traverse(self._render)
        if self.queue.getNumEntries() > 0:
            self.queue.sortEntries()
            for element in self.queue.getEntries():
                shallow_element = element.getIntoNodePath()
                while not shallow_element.get_tag('pickable') == 'true':
                    shallow_element = shallow_element.get_parent()
                    if shallow_element == self._render:
                        return None
                self.picked_pos = element.getSurfacePoint(shallow_element)
                self.picked_normal = element.getSurfaceNormal(shallow_element)
                return shallow_element

    def _select(self, event_name):
        element = self.get_object()
        if element is None and self.selected is not None:
            self.unselect_func(self.selected)
            self.selected = None
        elif element is not None and element != self.selected:
            self.unselect_func(self.selected)
            self.selected = element
            self.select_func(event_name, self.selected, self.picked_pos, self.picked_normal)

    def _overline(self):
        element = self.get_object()
        if element is None and self.overlined is not None:
            self.overlined.hide_bounds()
            self.overlined = None
        elif element is not None and element != self.overlined:
            if self.overlined is not None:
                self.overlined.hide_bounds()
            self.overlined = element
            self.overlined.show_tight_bounds()

    def left_click(self):
        self._select('left_click')

    def _mouse_moved(self):
        mpos = self._mwn.getMouse()
        if mpos.getX() != self._mouse_X or mpos.getY() != self._mouse_Y:
            self._mouse_X = mpos.getX()
            self._mouse_Y = mpos.getY()
            return True
        return False

    def mouse_move(self, task):
        if self._mwn.hasMouse() and self._mouse_moved():
            self._overline()
        return task.cont


import logging

import hou
from marshmallow import Schema, ValidationError, fields

from .util import calcHash

class Hypnotic:
    def __init__(self, hipFile, schema=None):
        self.hipFile = hipFile
        self.hipFileHash = None
        self.controls = None
        self.out = None

        self._loadHip(self.hipFile)

        if schema:
            self.controlSchema = schema
        else:
            self._generateSchema()

    def _generateSchema(self):
        """
        Scan the control node to generate a validation schema for incoming data.
        """
        if self.controls:
            parms = self.controls.parms()
        else:
            logging.error("No control node in object. Is the hip file initialized?")
            return

        schemaDict = {}
        for parm in parms:
            value = parm.eval()
            if isinstance(value, str):
                schemaDict[parm.name()] = fields.String(required=False)
            elif isinstance(value, int):
                schemaDict[parm.name()] = fields.Integer(required=False)
            elif isinstance(value, float):
                schemaDict[parm.name()] = fields.Float(required=False)
            else:
                logging.info(f"Skipping parameter {parm.name()} of unrecognized type")

        self.controlSchema = Schema.from_dict(schemaDict)

    def _loadHip(self, file=None, hash=None):
        """
        Reload the hip file definition, or switch to a new one.
        Veify changes with hash if provided.
        """

        logging.info("Reloading the hip file")
        # Calculate the new files hash
        if file:
            newHash = calcHash(file)
        else:
            newHash = calcHash(self.hipFile)

        # if a hash has been provided to verify the new file, make sure they match
        if hash:
            if hash != newHash:
                logging.error("New file hash does not match provided one")
                return

        # If we are loading a new file and not reloading one in the same place update
        # our file name
        if file:
            self.hipFile = file

        # Actually load the file and save the hash to the object
        hou.hipFile.load(self.hipFile)
        self.controls = hou.node("/obj/CONTROLS")
        self.out = hou.node("/out/OUT")
        self.out_gl = hou.node("/out/OUT_GL")
        self.out_uv = hou.node("/out/OUT_UV")
        self.hipFileHash = newHash

    def _detectChanges(self):
        """
        Detects changes in the hip file during runtime.
        """
        md5_hash = calcHash(self.hipFile)

        return not md5_hash == self.hipFileHash

    def _reloadIfChanged(self):
        """
        Re-imports the hip file if it has been changed externally since it was loaded.
        """
        if self._detectChanges():
            self._loadHip()

    def _validateControls(self, controls):
        """
        Ensure passed parameters will fit in the control node
        """

        try:
            self.controlSchema.load(controls)
            return True
        except ValidationError as err:
            logging.error(f"Controls did not pass Hypnotic validation.\n{err.messages}")
            return False

    def _writeControls(self, controls):
        """
        Write the parameters from a json request into the control node.
        """
        self._reloadIfChanged()
        controlsAreValid = self._validateControls(controls)
        if controlsAreValid:
            self.controls.setParms(controls)
        else:
            logging.error("Could not write controls. Reason: Invalid controls")

    def exportPrintFile(self, controls):
        """
        Export an obj file from the provided parameters.
        """
        self._writeControls(controls)

        outPath = f"$HIP/out/print/{self.hipFile.split('/')[-1].split('.')[0]}/out.obj"
        self.out.setParms({"sopoutput": outPath})

        self.out.render()

    def exportPreviewFile(self, controls):
        """
        Export a .glb file from the provided parameters.
        """
        self._writeControls(controls)

        outPath = f"$HIP/out/gl/{self.hipFile.split('/')[-1].split('.')[0]}/out.glb"
        self.out.setParms({"file": outPath})

        self.out_gl.render()


#coding:utf-8
import unittest
import requests
from common.logger import Log
from common.mysql_pub import MysqlUtil
from config import readConfig

class Maintain_siteinfo(unittest.TestCase):
    u'''
    站长站点信息接口
    '''
    log = Log()
    mysqlutil = MysqlUtil()
    log.info("---站长站点信息接口测试---")

    def siteinfo(self,userCode):
        '''一个参数：
        登录用户code（工号）：userCode
        '''

        ip = readConfig.ip
        i_port = readConfig.i_port

        url = "http://" + ip + ":" + i_port + "/backend/capacity/maintain/siteInfo"
        header = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",
            "X-Requested-With": "XMLHttpRequest",
            "Connection": "keep-alive"
                 }
        par = {"userCode":userCode}
        r = requests.get(url,params=par)
        result = r.json()
        self.log.info("---站长站点信息接口响应：%s"%result)

        sql = "SELECT CODE FROM cap_courier WHERE CODE IS NOT NULL AND CODE <> '' GROUP BY CODE;"
        userCodes = self.mysqlutil.mysql_getrows(sql)
        s_userCodes = userCodes.__str__()
        if userCode in s_userCodes and userCode != '':
            self.assertEqual(result["code"], '0000')
            self.assertEqual(result["msg"], '接口正常')
            sql1 = "SELECT co.org_name FROM cap_organization co LEFT JOIN cap_courier cc ON co.`org_code` = cc.`org_code` WHERE cc.code = '%s';"%userCode
            orgname = self.mysqlutil.mysql_getrows(sql1)[0][0]
            self.assertEqual(result["data"]["orgName"],orgname)
        elif userCode == '':
            self.assertEqual(result["code"], '0025')
            self.assertEqual(result["msg"], '参数不能为空')
            self.assertEqual(result["data"], {})
        elif userCode != '' and userCode not in s_userCodes:
            self.assertEqual(result["code"], '0000')
            self.assertEqual(result["msg"], '接口正常')
            self.assertEqual(result["data"], None)

    def test_siteinfo1(self):
        u'''测试站长站点信息接口：请求参数正确'''
        self.log.info("---1.请求参数正确：start!---")
        userCode = 'CB00006447'
        self.siteinfo(userCode)
        self.log.info("---pass---")
        self.log.info("")

    def test_siteinfo2(self):
        u'''测试站长站点信息接口：登录用户code（工号）不存在'''
        self.log.info("---2.userCode传入不存在：start!---")
        userCode = 'abc'
        self.siteinfo(userCode)
        self.log.info("---pass---")
        self.log.info("")

    def test_siteinfo3(self):
        u'''测试站长站点信息接口：userCode传入为空'''
        self.log.info("---3.userCode传入为空：start!---")
        userCode = ''
        self.siteinfo(userCode)
        self.log.info("---pass---")
        self.log.info("")

    if __name__ == "__main__":
        unittest.main()


import tkinter as tk
from tkinter import ttk
from tkinter import messagebox as msg
from tkinter import simpledialog
import random
import numpy as np
from scipy.stats import maxwell

#상수 또는 처음에 결정하는 값
delta_t=0.01 #(시뮬레이션 기준)스텝 사이 시간 간격(s)
M=0.01       #실제 분자량(kg/mol)
R=8.314      #기체 상수(J/mol K)

modestr=''
class simboard:
    def __init__(self, frame):
        self.c1=tk.Canvas(frame, relief='solid', bg='white')
        self.c1.pack_propagate(False)
        self.c1.pack(fill='both', expand=tk.YES)
        self.c1['width']=600
        self.c1['height']=300

    def unpack(self, frame):
        frame.pack_forget()

    def const_vol_sim(self):    #T,P,W를 표시함
        self.num=particle_num.get()
        self.V=amountvolume.get()
        self.size=particle_size.get()
        self.n=self.num/100
        Mol.set(self.n)
        #화면에 표시하는 값
        temper_value.set(2*amountheat.get()/(3*self.n*R))#온도(K)
        pressure_value.set(0)          #압력(atm)
        work_value.set(0)          #기체가 한 일(J) (등적 과정이므로 항상 0)

        #프로그램 내부에서 사용하는 값
        self.v_rms=np.sqrt(3*R*temper_value.get()/M) #분자의 rms 속력
        self.m=self.n*M/self.num   #입자 질량(kg)
        #각 입자의 위치, 속도 저장
        self.p=[]
        self.pad=5
        self.c_width ,self.c_height=600, 300
        self.v_width, self.v_height=self.c_width/10*self.V, self.c_height
        self.c1.create_rectangle(self.v_width, 0, self.v_width+15, self.v_height, fill='black')
        self.c1.create_rectangle(self.v_width+15, self.v_height/2-7.5, 2000, self.v_height/2+7.5, fill='black')
        for i in range(self.num):
            #x1,y1은 입자의 왼쪽 위 좌표, x2,y2는 입자의 오른쪽 아래 좌표
            x1,y1=self.v_width*(random.random()*0.8+0.1),self.v_height*(random.random()*0.8+0.1)
            x2,y2=x1+self.size,y1+self.size
            r1=self.c1.create_oval(x1,y1,x2,y2,fill='black')
            #속도 벡터의 구면 좌표(theta, phi)
            theta=random.random()*np.pi
            phi=random.random()*2*np.pi
            #실제 속도, m/s단위
            vel=maxwell.rvs()/np.sqrt(3)*self.v_rms
            vel_x=vel *np.sin(theta) *np.cos(phi)
            vel_y=vel *np.cos(theta)
            #delta_t(1스텝)동안 이동하는 pixel 수  #1m = 2339.214pixel
            v_x=vel_x*2339.214/1000/100
            v_y=vel_y*2339.214/1000/100
            self.p.append([x1,y1,x2,y2,r1,v_x,v_y])
        self.press=[]
        def particleMove():
            temper_value.set(2*amountheat.get()/(3*self.n*R))#온도(K)
            self.v_rms=np.sqrt(3*R*temper_value.get()/M) #분자의 rms 속력
            for i in range(self.num):
                #실제 속도, m/s단위
                vel=maxwell.rvs()/np.sqrt(3)*self.v_rms
                vel_x=vel *np.sin(theta) *np.cos(phi)
                vel_y=vel *np.cos(theta)
                #delta_t(1스텝)동안 이동하는 pixel 수  #1m = 2339.214pixel
                v_x=vel_x*2339.214/1000/100
                v_y=vel_y*2339.214/1000/100
                self.p[i][5]=self.p[i][5]/abs(self.p[i][5])*v_x
                self.p[i][6]=self.p[i][6]/abs(self.p[i][6])*v_y
            imp=0
            for i in range(self.num):
                #x1 범위 제한, 왼쪽 벽과 탄성 충돌
                if self.p[i][0]<=self.p[i][5]+self.pad:
                    self.p[i][5]=abs(self.p[i][5])
                #x2 범위 제한, 오른쪽 벽(피스톤)과 탄성 충돌
                if self.p[i][2]>=self.v_width-self.p[i][5]+self.pad:
                    self.p[i][5]=-abs(self.p[i][5])
                    #피스톤에 가해지는 충격량(kg m/s)
                    imp+=self.m*2*abs(self.p[i][5])/(2339.214/1000/100)
                #y1 범위 제한, 위쪽 벽과 탄성 충돌
                if self.p[i][1]<=self.p[i][6]+self.pad:
                    self.p[i][6]=abs(self.p[i][6])
                #y2 범위 제한, 아래쪽 벽과 탄성 충돌
                if self.p[i][3]>=self.v_height-self.p[i][6]+self.pad:
                    self.p[i][6]=-abs(self.p[i][6])
                self.c1.move(self.p[i][4], self.p[i][5], self.p[i][6])
                self.p[i][0]+=self.p[i][5]
                self.p[i][2]+=self.p[i][5]
                self.p[i][1]+=self.p[i][6]
                self.p[i][3]+=self.p[i][6]
                #피스톤을 뚫고 나간 입자(버그)는 다시 안으로 집어넣음
                if self.p[i][0]>=self.v_width+10 or self.p[i][0]<=-20:
                    x_new=self.v_width*(random.random()*0.8+0.1)
                    self.c1.move(self.p[i][4], x_new-self.p[i][0], 0)
                    self.p[i][0]=x_new
                    self.p[i][2]=self.p[i][0]+self.size
            self.press.append(imp)
            imp=0
            if len(self.press)==100:
                #충격량과 압력 사이 비례 상수
                k=0.02924018*0.01*0.001*101325 /1.5 #0.02924018 = 피스톤 단면적(m^2)
                #압력 계산(10스텝 평균 압력)
                pressure_value.set(sum(self.press)/100/k)
                self.press=[]
            self.c1.after(int(delta_t*1000), particleMove)
        particleMove()

    def const_tmp_sim(self):    #V,W를 표시함
        self.V=amountvolume.get()
        self.T=temper_value.get()
        self.num=particle_num.get()
        self.size=particle_size.get()
        self.n=self.num/100
        Mol.set(self.n)

        #화면에 표시하는 값
        amountvolume.set(0)          #부피(L)
        work_value.set(0)          #기체가 한 일(J)

        #프로그램 내부에서 사용하는 값
        self.v_rms=np.sqrt(3*R*self.T/M) #분자의 rms 속력
        m=self.n*M/self.num   #입자 질량(kg)
        self.pad=5
        self.c_width ,self.c_height=600, 300
        self.v_width, self.v_height=self.c_width/10*self.V, self.c_height
        self.piston=self.c1.create_rectangle(self.v_width, 0, self.v_width+15, self.v_height, fill='black')
        self.rod=self.c1.create_rectangle(self.v_width+15, self.v_height/2-7.5, 2000, self.v_height/2+7.5, fill='black')
        #각 입자의 위치, 속도 저장
        self.p=[]
        for i in range(self.num):
            #x1,y1은 입자의 왼쪽 위 좌표, x2,y2는 입자의 오른쪽 아래 좌표
            x1,y1=self.v_width*(random.random()*0.8+0.1),self.v_height*(random.random()*0.8+0.1)
            x2,y2=x1+self.size,y1+self.size
            r1=self.c1.create_oval(x1,y1,x2,y2,fill='black')
            #속도 벡터의 구면 좌표(theta, phi)
            theta=random.random()*np.pi
            phi=random.random()*2*np.pi
            #실제 속도, m/s단위
            vel=maxwell.rvs()/np.sqrt(3)*self.v_rms
            vel_x=vel *np.sin(theta) *np.cos(phi)
            vel_y=vel *np.cos(theta)
            #delta_t(1스텝)동안 이동하는 pixel 수  #1m = 2339.214pixel
            v_x=vel_x*2339.214/1000/100
            v_y=vel_y*2339.214/1000/100
            self.p.append([x1,y1,x2,y2,r1,v_x,v_y])

        #충격량과 압력 사이 비례 상수
        k=0.02924018*0.01*0.001*101325  #0.02924018 = 피스톤 단면적(m^2)

        def pistonMove(imp):
            delta_x=(imp-pressure_value.get()*k)*5
            self.v_width+=delta_x
            if delta_x<0:
                work_value.set(work_value.get()+pressure_value.get()*(delta_x/800*10)*101.325)
            else:
                work_value.set(work_value.get()+(imp/k-pressure_value.get())*(delta_x/800*10)*101.325)
            self.c1.move(self.piston, delta_x, 0)
            self.c1.move(self.rod, delta_x, 0)

        def particleMove():
            imp=0
            for i in range(self.num):
                #x1 범위 제한, 왼쪽 벽과 탄성 충돌
                if self.p[i][0]<=self.p[i][5]+self.pad:
                    self.p[i][5]=abs(self.p[i][5])
                #x2 범위 제한, 오른쪽 벽(피스톤)과 탄성 충돌
                if self.p[i][2]>=self.v_width-self.p[i][5]+self.pad:
                    self.p[i][5]=-abs(self.p[i][5])
                    #피스톤에 가해지는 충격량(kg m/s)
                    imp+=m*2*abs(self.p[i][5])/(2339.214/1000/100)
                #y1 범위 제한, 위쪽 벽과 탄성 충돌
                if self.p[i][1]<=self.p[i][6]+self.pad:
                    self.p[i][6]=abs(self.p[i][6])
                #y2 범위 제한, 아래쪽 벽과 탄성 충돌
                if self.p[i][3]>=self.v_height-self.p[i][6]+self.pad:
                    self.p[i][6]=-abs(self.p[i][6])
                self.c1.move(self.p[i][4], self.p[i][5], self.p[i][6])
                self.p[i][0]+=self.p[i][5]
                self.p[i][2]+=self.p[i][5]
                self.p[i][1]+=self.p[i][6]
                self.p[i][3]+=self.p[i][6]
                #피스톤을 뚫고 나간 입자(버그)는 다시 안으로 집어넣음
                if self.p[i][0]>=self.v_width+10 or self.p[i][0]<=-20:
                    x_new=self.v_width*(random.random()*0.8+0.1)
                    self.c1.move(self.p[i][4], x_new-self.p[i][0], 0)
                    self.p[i][0]=x_new
                    self.p[i][2]=self.p[i][0]+self.size

            self.c1.after(int(delta_t*1000), particleMove)
            amountvolume.set(self.v_width/800*10)   #기체의 부피(L)계산
            pistonMove(imp)
        particleMove()

    def const_pressure_sim(self):
        self.num=particle_num.get()
        self.P=pressure_value.get()
        self.size=particle_size.get()
        self.n=self.num/100
        Mol.set(self.n)

        #화면에 표시하는 값
        temper_value.set(2*amountheat.get()/(5*self.n*R))#온도(K)
        work_value.set(0)          #기체가 한 일(J) (등적 과정이므로 항상 0)
        self.P=pressure_value.get()
        pressure_label.configure(text='부피')
        pressure_entry.configure(textvariable=amountvolume)
        pressure_label2.configure(text='L')

        #프로그램 내부에서 사용하는 값
        self.v_rms=np.sqrt(3*R*temper_value.get()/M) #분자의 rms 속력
        self.m=self.n*M/self.num   #입자 질량(kg)

        self.my_w = tk.Tk()
        self.my_w.title('등압 과정')
        self.c_width,self.c_height=600,300
        self.v_width,self.v_height=self.c_width-100,self.c_height
        self.piston = self.c1.create_rectangle(self.v_width, 0, self.v_width+15, self.v_height, fill='black')
        self.rod = self.c1.create_rectangle(self.v_width+15, self.v_height/2-7.5, 2000, self.v_height/2+7.5, fill='black')

        #각 입자의 위치, 속도 저장
        self.p=[]
        self.pad=5
        for i in range(self.num):
            #x1,y1은 입자의 왼쪽 위 좌표, x2,y2는 입자의 오른쪽 아래 좌표
            x1,y1=self.v_width*(random.random()*0.8+0.1),self.v_height*(random.random()*0.8+0.1)
            x2,y2=x1+self.size,y1+self.size
            r1=self.c1.create_oval(x1,y1,x2,y2,fill='black')
            #속도 벡터의 구면 좌표(theta, phi)
            theta=random.random()*np.pi
            phi=random.random()*2*np.pi
            #실제 속도, m/s단위
            vel=maxwell.rvs()/np.sqrt(3)*self.v_rms
            vel_x=vel *np.sin(theta) *np.cos(phi)
            vel_y=vel *np.cos(theta)
            #delta_t(1스텝)동안 이동하는 pixel 수  #1m = 2339.214pixel
            v_x=vel_x*2339.214/1000/100
            v_y=vel_y*2339.214/1000/100
            self.p.append([x1,y1,x2,y2,r1,v_x,v_y])

        #충격량과 압력 사이 비례 상수
        k=0.02924018*0.01*0.001*101325 #0.02924018 = 피스톤 단면적(m^2)

        def pistonMove(imp):
            delta_x=(imp-self.P*k)*10
            self.v_width+=delta_x
            work_value.set(work_value.get()+self.P*(delta_x/800*10)*101.325)
            self.c1.move(self.piston, delta_x, 0)
            self.c1.move(self.rod, delta_x, 0)

        def particleMove():
            temper_value.set(2*amountheat.get()/(5*self.n*R))#온도(K)
            self.v_rms=np.sqrt(3*R*temper_value.get()/M) #분자의 rms 속력
            for i in range(self.num):
                #실제 속도, m/s단위
                vel=maxwell.rvs()/np.sqrt(3)*self.v_rms
                vel_x=vel *np.sin(theta) *np.cos(phi)
                vel_y=vel *np.cos(theta)
                #delta_t(1스텝)동안 이동하는 pixel 수  #1m = 2339.214pixel
                v_x=vel_x*2339.214/1000/100
                v_y=vel_y*2339.214/1000/100
                self.p[i][5]=self.p[i][5]/abs(self.p[i][5])*v_x
                self.p[i][6]=self.p[i][6]/abs(self.p[i][6])*v_y
            imp=0
            for i in range(self.num):
                #x1 범위 제한, 왼쪽 벽과 탄성 충돌
                if self.p[i][0]<=self.p[i][5]+self.pad:
                    self.p[i][5]=abs(self.p[i][5])
                #x2 범위 제한, 오른쪽 벽(피스톤)과 탄성 충돌
                if self.p[i][2]>=self.v_width-self.p[i][5]+self.pad:
                    self.p[i][5]=-abs(self.p[i][5])
                    #피스톤에 가해지는 충격량(kg m/s)
                    imp+=self.m*2*abs(self.p[i][5])/(2339.214/1000/100)
                #y1 범위 제한, 위쪽 벽과 탄성 충돌
                if self.p[i][1]<=self.p[i][6]+self.pad:
                    self.p[i][6]=abs(self.p[i][6])
                #y2 범위 제한, 아래쪽 벽과 탄성 충돌
                if self.p[i][3]>=self.v_height-self.p[i][6]+self.pad:
                    self.p[i][6]=-abs(self.p[i][6])
                self.c1.move(self.p[i][4], self.p[i][5], self.p[i][6])
                self.p[i][0]+=self.p[i][5]
                self.p[i][2]+=self.p[i][5]
                self.p[i][1]+=self.p[i][6]
                self.p[i][3]+=self.p[i][6]
                #피스톤을 뚫고 나간 입자(버그)는 다시 안으로 집어넣음
                if self.p[i][0]>=self.v_width+10 or self.p[i][0]<=-20:
                    x_new=self.v_width*(random.random()*0.8+0.1)
                    self.c1.move(self.p[i][4], x_new-self.p[i][0], 0)
                    self.p[i][0]=x_new
                    self.p[i][2]=self.p[i][0]+self.size
            self.c1.after(int(delta_t*1000), particleMove)
            amountvolume.set(self.v_width/800*10)
            pistonMove(imp)

        particleMove()

    def simulation_start(self):
        global modestr
        #mode: 0: 등적, 1: 등압, 2: 등온, 3: 단열
        mode=simtype.get()
        if mode==0:
            modestr='등적과정(부피 일정)'
            amountvolume.set(const_volume.get())
            self.const_vol_sim()
            amountvolume_slider['state']='disabled'
        if mode==1:
            modestr='등압과정(압력 일정)'
            pressure_value.set(const_pressure.get())
            self.const_pressure_sim()
        if mode==2:
            temper_value.set(const_temp.get())
            modestr='등온과정(온도 일정, 압력 조절)'
            self.const_tmp_sim()
            amountheat_slider['state']='disabled'
        whatmodeisit.set(modestr)

def simulation_type():
    if sim is not None:
        sim.disabled = True
    menuwindow.deiconify()       # 새 게임 대화상자를 화면에 표시, 게임판 비활성화

sim=None

def quitmenu():
    if sim is not None:
        sim.disabled = False
    menuwindow.withdraw()

def quitmain():
    if msg.askokcancel('열역학 시뮬레이터', '프로그램을 종료하시겠습니까?'):
        mainwindow.destroy()        # 게임종료 대화상자를 표시, 게임종료

def simuStart(frame):
    num=simpledialog.askinteger("particle_num", "입자의 개수를 입력하세요")
    particle_num.set(num)
    ss=simpledialog.askinteger("particle_size", "입자의 크기를 입력하세요(5~30)")
    particle_size.set(ss)
    menuwindow.withdraw()
    global sim
    if sim is not None:
        sim.unpack(mainFrame)
    sim= simboard(frame)
    sim.disabled = False
    sim.simulation_start()

# root
mainwindow = tk.Tk()
# mainwindow.geometry('430x200')
mainwindow.title('main')
mainwindow.geometry('1000x500+100+100')

menuwindow=tk.Toplevel(mainwindow)
menuwindow.wm_attributes("-topmost", 1)      # 새 게임 대화상자 윈도우를 생성, 초기설정
menuwindow.geometry('+100+100')
menuwindow.protocol("WM_DELETE_WINDOW", quitmenu)       # 창 닫기 버튼 클릭 시 quitGame 함수 호출

# 열역학 과정 선택 대화상자의 GUI 구성
title_frm=tk.Frame(menuwindow)
title_frm.grid(row=0, column=0, columnspan=4)
levelLabel = tk.Label(title_frm, text='열역학 과정의 종류를 선택해주세요!')
levelLabel.pack(fill='both')

# 라디오 버튼 생성
radio_frame=tk.Frame(menuwindow)
radio_frame.grid(row=1, column=0)
simtype = tk.IntVar()
isovolumetric = tk.Radiobutton(radio_frame, text='등적과정', variable=simtype, value=0)
isobaric = tk.Radiobutton(radio_frame, text='등압과정', variable=simtype, value=1)
isothermal = tk.Radiobutton(radio_frame, text='등온과정', variable=simtype, value=2)

# 라디오 버튼 배치
isovolumetric.grid(row=0, padx=15)
isobaric.grid(row=1, padx=15)
isothermal.grid(row=2, padx=15)

const_frm=tk.Frame(menuwindow)
const_frm.grid(row=1, column=1, columnspan=3)
# 위젯 클릭시 등장할 entry
const_volume=tk.IntVar(const_frm)
isovolumetric_label1=tk.Label(const_frm, text='부피:')
isovolumetric_label1.grid(row=0, column=0)
isovolumetric_entry=tk.Entry(const_frm, textvariable=const_volume)
isovolumetric_entry.grid(row=0, column=1)
isovolumetric_label2=tk.Label(const_frm, text='L')
isovolumetric_label2.grid(row=0, column=2)

const_pressure=tk.IntVar()
isobaric_label1=tk.Label(const_frm, text='압력:')
isobaric_label1.grid(row=1, column=0)
isobaric_entry=tk.Entry(const_frm, textvariable=const_pressure)
isobaric_entry.grid(row=1, column=1)
isobaric_label2=tk.Label(const_frm, text='atm')
isobaric_label2.grid(row=1, column=2)

const_temp=tk.IntVar()
isothermal_label1=tk.Label(const_frm, text='온도:')
isothermal_label1.grid(row=2, column=0)
isothermal_entry=tk.Entry(const_frm, textvariable=const_temp)
isothermal_entry.grid(row=2, column=1)
isothermal_label2=tk.Label(const_frm, text='K')
isothermal_label2.grid(row=2, column=2)
bin_label=tk.Label(const_frm)
bin_label.grid(row=3, column=0, columnspan=3)

btn_frame=tk.Frame(menuwindow)
btn_frame.grid(row=2, column=0, columnspan=4)
mainFrame=tk.Frame(mainwindow)
startBtn = tk.Button(btn_frame, text='확인', command=(lambda: simuStart(frm_canvas)))
startBtn.pack(fill='both')

#mainwindow 위젯 배치

mainFrame.grid_propagate(False)     # 게임이 들어갈 mainFrame 생성
whatmodeisit=tk.StringVar()
particle_num=tk.IntVar()
particle_size=tk.IntVar()
particle_size.set(20)
amountheat=tk.IntVar()
amountheat.set(6000)
amountvolume=tk.IntVar()
temper_value=tk.IntVar()
pressure_value=tk.IntVar()
work_value=tk.IntVar()
Mol=tk.IntVar()
#Mol.set(mol)

frm1=tk.Frame(mainwindow)
frm2=tk.Frame(mainwindow)
frm3=tk.Frame(mainwindow)
frm4=tk.Frame(mainwindow)
frm5=tk.Frame(mainwindow)
frm6=tk.Frame(mainwindow)
frm_canvas=tk.Frame(mainwindow)
frm1.grid(row=0, column=0, rowspan=2, columnspan=2)
frm2.grid(row=0, column=2, rowspan=2, columnspan=2)
frm3.grid(row=0, column=4, rowspan=2, columnspan=3)
frm4.grid(row=3, column=0, rowspan=1, columnspan=7)
frm5.grid(row=4, column=0, rowspan=1, columnspan=5)
frm6.grid(row=4, column=5, rowspan=7, columnspan=3)
frm_canvas.grid(row=5, column=0, rowspan=6, columnspan=4)

#frm1
particle_num_label=tk.Label(frm1, text='입자 수: ')
particle_num_entry=tk.Entry(frm1, textvariable=particle_num)
particle_num_label.grid(row=0, column=0)
particle_num_entry.grid(row=0, column=1)
whatmode=tk.Label(frm1, textvariable=whatmodeisit)
whatmode.grid(row=1, column=0, columnspan=2)

#frm2
particle_size_label=tk.Label(frm2, text='입자 크기: ')
particle_size_slider = ttk.Scale(frm2, from_=10, to=50, orient='horizontal', variable=particle_size, length=100, state='disabled') ####################
newSimBtn=tk.Button(frm2, text='새로운 시뮬레이션', command=simulation_type)
particle_size_label.grid(row=0, column=0)
particle_size_slider.grid(row=0, column=1)
newSimBtn.grid(row=1, column=0, columnspan=2)

#frm3
def resetwork():
    work_value.set(0)
actual_mol_label=tk.Label(frm3, text='실제 몰 수: ')
actual_mol_entry=tk.Entry(frm3, textvariable=Mol)
actual_mol_label2=tk.Label(frm3, text='mol')
resetwork_button=tk.Button(frm3, text='기체가 한 일 초기화', command=resetwork)
quitGameBtn = tk.Button(frm3, text=' X ', command=quitmain, foreground='red')
actual_mol_label.grid(row=0, column=0)
actual_mol_entry.grid(row=0, column=1)
actual_mol_label2.grid(row=0, column=3)
resetwork_button.grid(row=1, column=0, columnspan=2)
quitGameBtn.grid(row=1, column=3)

#frm4
amountheat_label=tk.Label(frm4, text='가한 열')
amountheat_slider = ttk.Scale(frm4, from_=100, to=30000, orient='horizontal', variable=amountheat, length=500) ####################
amountheat_label.grid(row=0, column=0)
amountheat_slider.grid(row=0, column=1)

#frm5
amountvolume_label=tk.Label(frm5, text='부피')
amountvolume_slider = ttk.Scale(frm5, from_=1, to=10, orient='horizontal', variable=amountvolume, length=300) ####################
amountvolume_label.grid(row=0, column=0, sticky='w')
amountvolume_slider.grid(row=0, column=1, sticky='w')

#frm6
temper_label=tk.Label(frm6, text='온도:')
temper_entry=tk.Entry(frm6, textvariable=temper_value)
temper_label2=tk.Label(frm6, text='K')
pressure_label=tk.Label(frm6, text='압력:')
pressure_entry=tk.Entry(frm6, textvariable=pressure_value)
pressure_label2=tk.Label(frm6, text='atm')
work_label=tk.Label(frm6, text='한 일:')
work_entry=tk.Entry(frm6, textvariable=work_value)
work_label2=tk.Label(frm6, text='J')
temper_label.grid(row=0,column=0)
temper_entry.grid(row=0,column=1)
temper_label2.grid(row=0,column=2)
pressure_label.grid(row=1,column=0)
pressure_entry.grid(row=1,column=1)
pressure_label2.grid(row=1,column=2)
work_label.grid(row=2,column=0)
work_entry.grid(row=2,column=1)
work_label2.grid(row=2,column=2)

mainwindow.mainloop()


import time

import cairocffi as cairo

from cairotft import linuxfb
from cairotft import transitions

class Marquee():

    """A text marquee widget."""

    def __init__(self, display_object, text,
                 font_face, font_size,
                 text_color,
                 pos_x, pos_y, width, height,
                 background_color=(1, 1, 1, 1),
                 step=1,
                 interval_time=0.05,
                 transition=transitions.LinearTransition.ease_in,
                 smooth=False):
        """Initialisation of the Marquee.

        :param display_object: the Display class instanciation.
        :type display_object: :class:`cairotft.tft.TftDisplay`
        :param str text: the text to display.
        :param font_face: the font face used for the text
        :type font_face: :class:`cairocffi.ToyFontFace`
        :param tuple text_color: a tuple of 4 float representing the rgba
            value of the text color.
        :param int font_size: the size of the font.
        :param int pos_x: x coordinates of the text box (top left corner)
        :param int pos_y: y coordinates of the text box (top left corner)
        :param int width: the width of the text box
        :param int height: the height of the text box
        :param tuple background_color: a tuple of 4 float representing the
            rgba value of the background color to repaint the icon.
        :param int step: number of unit we skip at each frame. (X chars if
            smooth is False, X pixels if smooth is True)
        :param float interval_time: the time in s between two frames

        TODO: instead of repainting with a color, save the background or paint
              in order: from bottom to top.
        """
        self._stop = False
        self._showing = False
        self._pos = 0
        self.display_object = display_object
        self.text = text
        self.full_text = self.text + "   " + self.text
        self._shrinked_text = text
        self.font_face = font_face
        self.font_size = font_size
        self.text_color = text_color
        self.background_color = background_color
        self._old_text_color = text_color
        self._old_background_color = background_color
        self.pos_x = pos_x
        self.pos_y = pos_y
        self.width = width
        self.height = height
        self.step = step
        self.smooth = smooth
        self.max_offset = len(self.text) + 3
        self.interval_time = interval_time
        self.transition = transition
        self._transition_time = None
        self._first_time = None
        self._should_scroll = False  # if False, text does not scroll

    def _smooth_init_buffer(self, ctx):
        """Initialise the buffer used in smooth text."""
        # in smooth case, we need to instanciate specific buffers
        # at first, determine the width and height we need:
        ctx.set_font_size(self.font_size)
        ctx.set_font_face(self.font_face)
        (_, _, small_text_width, _,
         x_advance_text, _) = ctx.text_extents(self.text + "   ")
        self.smooth_text_width = int(x_advance_text)
        self.max_offset = self.smooth_text_width

        (_, y_bearing,
         width, height,
         x_advance, _) = ctx.text_extents(self.full_text)
        self.smooth_full_height = int(height)
        self.smooth_full_width = int(max(x_advance, width))
        self.smooth_pos_y = int(-y_bearing)
        stride = cairo.ImageSurface.format_stride_for_width(
            self.display_object.cairo_format, int(x_advance))
        textbuffer = linuxfb.memory_buffer(
            int(stride * self.smooth_full_height))
        self.smooth_textsurf = cairo.ImageSurface(
            format=self.display_object.cairo_format,
            width=self.smooth_full_width,
            height=self.smooth_full_height,
            data=textbuffer,
            stride=stride)
        # if the text does not fit inside the target box, we will scrool it
        if small_text_width > self.width:
            self._should_scroll = True
            self._transition_time = (self.interval_time *
                                     self.smooth_text_width / self.step)

        # creates the context for this memory surface and draw the text
        self.smooth_text_ctx = cairo.Context(self.smooth_textsurf)
        self._smooth_draw_text()

    def _smooth_draw_text(self):
        """draw the text in the smooth text buffer.

        This is not display, only drawed in the smooth buffer.
        """
        # background
        self.smooth_text_ctx.set_source_rgba(*self.background_color)
        self.smooth_text_ctx.rectangle(0,
                                       0,
                                       self.smooth_full_width,
                                       self.smooth_full_height)
        self.smooth_text_ctx.fill()
        # text
        self.smooth_text_ctx.set_font_size(self.font_size)
        self.smooth_text_ctx.set_font_face(self.font_face)
        self.smooth_text_ctx.set_source_rgba(*self.text_color)
        self.smooth_text_ctx.move_to(0, self.smooth_pos_y)
        if self._should_scroll:
            self.smooth_text_ctx.show_text(self.full_text)
        else:
            self.smooth_text_ctx.show_text(self.text)

    def _shrink_text(self, ctx):
        """based on the font size, calculate the width of the text.

        And eventually shrink the name if too long.
        """
        # same font face here than the one displayed.
        if self._pos > 0:
            new_text = (self.full_text)[self._pos:]
        else:
            new_text = self.text[self._pos:]
        while True:
            (_, _, _, _, x_advance, _) = ctx.text_extents(new_text)
            if x_advance > self.width:
                new_text = new_text[:-1]  # + '…'
            else:
                break
        self._shrinked_text = new_text
        if self._shrinked_text != self.text:
            self._should_scroll = True
            self._transition_time = (self.interval_time *
                                     len(self.text + "   ") / self.step)

    def change_color(self, color):
        """Change the text color.

        :param tuple color: a tuple of 4 float representing the
            rgba value of the text color.
        """
        self._old_text_color = self.text_color
        self.text_color = color
        if self.smooth and self._showing:
            self._smooth_draw_text()

    def change_background(self, background_color):
        """Change the background color.

        :param tuple background_color: a tuple of 4 float representing the
            rgba value of the background color to repaint the icon.
        """
        self._old_background_color = self.background_color
        self.background_color = background_color
        if self.smooth and self._showing:
            self._smooth_draw_text()

    def color_changed(self):
        """Return True is either text_color or background_color has changed.

        (since last paint)
        """
        if (self._old_text_color != self.text_color or
                self._old_background_color != self.background_color):
            return True

    def show(self, ctx, no_loop=False):
        """Show the text."""
        if not self._stop and self._showing:
            # here at each frame, move the text and display it.
            if (self.color_changed or self._should_scroll) and not self.smooth:
                # erase the text box
                ctx.set_source_rgba(*self.background_color)
                ctx.rectangle(self.pos_x, self.pos_y, self.width, self.height)
                ctx.fill()

                # display text
                ctx.set_source_rgba(*self.text_color)
                ctx.set_font_size(self.font_size)
                ctx.set_font_face(self.font_face)

                self._shrink_text(ctx)
                ctx.move_to(
                    self.pos_x,
                    (self.pos_y +
                     (self.height - self.font_size) / 2 +
                     self.font_size) - 2)
                ctx.show_text(self._shrinked_text)
                self.display_object.blit()
            elif (self.color_changed or self._should_scroll) and self.smooth:
                # erase the text box
                ctx.set_source_rgba(*self.background_color)
                ctx.rectangle(self.pos_x, self.pos_y, self.width, self.height)
                ctx.fill()
                ctx.set_source_surface(
                    self.smooth_textsurf.create_for_rectangle(
                        self._pos, 0, self.width, self.smooth_full_height),
                    self.pos_x,
                    (self.pos_y +
                     (self.height - self.smooth_full_height) / 2) + 1)
                ctx.paint()
                self.display_object.blit()

            if self._should_scroll:  # only cycle when text is too long.
                now = time.time()
                if self._first_time is not None:
                    transition_offset = self.transition(
                        (now - self._first_time) /
                        self._transition_time)
                else:
                    transition_offset = self.transition(0)
                    self._first_time = now
                self._pos = int(self.max_offset * transition_offset)
                if (now - self._first_time) > self._transition_time:
                    self._first_time = now  # recycle
                    self._pos = int(self.max_offset * self.transition(0))

            self._old_text_color = self.text_color
            self._old_background_color = self.background_color

            if not no_loop:
                if self.display_object.fps is not None:
                    interval_time = max(self.interval_time,
                                        1 / self.display_object.fps)
                else:
                    interval_time = self.interval_time
                self.display_object.loop.call_later(
                    interval_time, self.show, ctx)

    def start(self, ctx):
        """Start showing the marquee."""
        if not self._showing:
            self._showing = True
            self._stop = False
            self._first_time = None
            if self.smooth:
                self._smooth_init_buffer(ctx)
            else:
                self._shrink_text(ctx)

            self.display_object.loop.call_soon(
                self.show, ctx)

    def stop(self):
        """stop showing the marquee."""
        self._stop = True
        self._showing = False
        self._first_time = None


#!/usr/bin/env python
import os
import sys
import textwrap

import matplotlib.pyplot as plt
import pandas as pd
import scipy.cluster.hierarchy as shc
from Bio import SeqIO, Phylo
from Bio.SeqUtils.ProtParam import ProteinAnalysis
from ete3 import Tree, NodeStyle, TreeStyle, TextFace, CircleFace, faces, AttrFace

from phylofisher import help_formatter

def distance_matrix2tree(Z, names):
    """Return tree representation for distance matrix"""
    n = Z.shape[0] + 1
    i2n = [0] * (2 * n - 1)
    t = Tree()
    for i, (idx1, idx2, dist, sample_count) in enumerate(Z):
        idx1, idx2 = int(idx1), int(idx2)
        # create Tree object for tips / leaves
        if idx1 < n:
            i2n[idx1] = Tree(name=names[idx1])
        if idx2 < n:
            i2n[idx2] = Tree(name=names[idx2])
        # create new node
        t = Tree()
        # normalise distance
        dist1 = dist - i2n[idx1].get_farthest_leaf()[1]
        dist2 = dist - i2n[idx2].get_farthest_leaf()[1]
        # add children
        t.add_child(i2n[idx1], dist=dist1)
        t.add_child(i2n[idx2], dist=dist2)
        # store
        i2n[n + i] = t
    return t

def aa_comp_calc():
    peptides = ['A', 'G', 'P', 'S', 'T', 'C', 'F', 'W', 'Y', 'H', 'R', 'K', 'M', 'I', 'L', 'V', 'N', 'D', 'E', 'Q']
    if not os.path.isdir(args.output):
        os.mkdir(args.output)
    with open(args.input, 'r') as infile, open(f'{args.output}/aa_comp.tsv', 'w') as outfile:
        outfile.write('Taxon\t' + '\t'.join(peptides) + '\n')

        # Reads in input file
        for record in SeqIO.parse(infile, format=args.in_format):
            outfile.write(f'{record.id}\t')
            analysed_seq = ProteinAnalysis(str(record.seq))
            count_dict = analysed_seq.count_amino_acids()
            length = len(str(record.seq).replace("-", "").replace("X", "").replace("*", ""))
            out_str = ''

            # Loops through peptides and checks to see if it is in count_dict
            for pep in peptides:
                if pep in count_dict.keys():
                    out_str += f'{float(count_dict[pep]) / length}\t'
                else:
                    out_str += '0\t'

            outfile.write(out_str.strip() + '\n')

def parse_tree_colors():
    color_dict = {}
    tree_color_dict = {}
    meta_dict = {}

    with open(tree_colors, 'r') as infile:
        infile.readline()
        for line in infile:
            s_line = line.strip().split('\t')
            tree_color_dict[s_line[0]] = s_line[1]

    with open(metadata, 'r') as infile:
        infile.readline()
        for line in infile:
            s_line = line.strip().split('\t')
            meta_dict[s_line[0]] = s_line[2:4]

        if args.chimeras:
            with open(args.chimeras, 'r') as infile:
                for line in infile:
                    line = line.strip()
                    split_line = line.split('\t')
                    meta_dict[split_line[0]] = split_line[1:3]

    for k, v in meta_dict.items():
        if k in tree_color_dict.keys():
            color_dict[k] = tree_color_dict[k]
        elif v[0] in tree_color_dict.keys():
            color_dict[k] = tree_color_dict[v[0]]
        elif v[1] in tree_color_dict.keys():
            color_dict[k] = tree_color_dict[v[1]]
        else:
            sys.exit(f'{k} is not in the tree_color.tsv')

    return color_dict, tree_color_dict, meta_dict

def mylayout(node):
    # Internal Node formatting
    nstyle = NodeStyle()
    nstyle["size"] = 0
    nstyle["vt_line_width"] = 2
    nstyle["hz_line_width"] = 2

    if node.is_leaf():
        circle_face = CircleFace(10, color_dict[node.name], style='circle')
        faces.add_face_to_node(circle_face, node, position="branch-right", column=0)

        text_face = TextFace(meta_dict[node.name][0])
        text_face.fgcolor = color_dict[node.name]
        faces.add_face_to_node(text_face, node, position="branch-right", column=1)

        node.set_style(nstyle)

    elif node.is_root():
        node.dist = 0
        node.set_style(nstyle)

    else:
        node.set_style(nstyle)

def make_plot():
    df = pd.read_csv(f'{args.output}/aa_comp.tsv', sep="\t")
    df = df.set_index('Taxon')

    z = shc.linkage(df, method='ward')
    t = distance_matrix2tree(z, df.index.values)
    t.write(outfile=f'{args.output}/distance_matrix.tre')

    # Basic tree style
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.mode = "c"
    ts.show_scale = False
    ts.layout_fn = mylayout
    # PDF rendering
    t.render(f'{args.output}/aa_comp_calculator.pdf', w=183, units="mm", tree_style=ts)

if __name__ == '__main__':
    description = 'Calculates amino acid composition of the supplied super matrix'
    parser, optional, required = help_formatter.initialize_argparse(name='aa_comp_calculator.py',
                                                                    desc=description,
                                                                    usage='aa_comp_calculator.py '
                                                                          '[OPTIONS] -i <matrix>')

    required.add_argument('-i', '--input', required=True, type=str, metavar='matrix',
                          help=textwrap.dedent("""\
                          Path to input matrix for analysis.
                          """))
    required.add_argument('-d', '--database', type=str, metavar='<db_dir>', required=True,
                          help=textwrap.dedent("""\
                          Path to database directory.
                          """))

    optional.add_argument('--chimeras', type=str, metavar='chimera_info.tsv',
                          help=textwrap.dedent("""\
                          A .tsv containing a Unique ID, higher taxonomy, and lower taxonomy for each chimera within the input matrix.

                          Example:
                            Chimera_ID 1\tHigher_Tax\tLower_Tax
                            Chimera_ID 2\tHigher_Tax\tLower_Tax
                          """))
    optional.add_argument('-if', '--in_format', metavar='<format>', type=str, default='fasta',
                          help=textwrap.dedent("""\
                          Format of input matrix.
                          Options: fasta, nexus, phylip (names truncated at 10 characters),
                          Default: fasta
                          """))

    args = help_formatter.get_args(parser, optional, required, pre_suf=False, inp_dir=False)

    dfo = os.path.abspath(args.database)

    tree_colors = f'{dfo}/tree_colors.tsv'
    metadata = f'{dfo}/metadata.tsv'

    color_dict, tree_color_dict, meta_dict = parse_tree_colors()

    aa_comp_calc()
    make_plot()


from backend import logger, constants
import requests
import json

enabled = False
api = ""
host = ""

def initialize():
    try:
        payload = {'ApiKey': api}
        request = requests.get(host+constants.OMBI_SYSTEM_STATUS, params=payload)
        if(request.status_code is not 200):
            raise Exception()
    except:
        logger.error(__name__, "Could not create a connection to Ombi: Please check config.ini")
        exit()


liste = [i for i in range(1,101) if i % 2 == 0]
print(liste)

# ya da

liste = list(range(1,101))
liste1 = []
for i in liste:
    if(i % 2 == 0):
        liste1.append(i)
print(liste1)

Kurs/Kurs Ödevleri/Çift sayıları ayrı listeye atma.py


from dataclasses import dataclass
from datetime import datetime
from typing import List

from interfaces import IObservable, IObserver

class RocketShip(IObservable):

    def __init__(self, name) -> None:
        self.name: str = name
        self.__has_launched : bool = False
        self.__observers : List[IObserver] = []

    @property
    def has_launched(self) -> bool:
        return self.__has_launched

    @has_launched.setter
    def has_launched(self, value : bool) -> None:
        self.__has_launched = value
        self.notify_observers()

    def add_observer(self, observer: IObserver) -> None:

        if observer not in self.__observers:
            self.__observers.append(observer)

    def remove_observer(self, observer: IObserver) -> None:

        if observer in self.observers:
            self.__observers.remove(observer)

    def notify_observers(self) -> None:
        for observer in self.__observers:
            observer.update()

@dataclass
class NasaScientist(IObserver):

    name: str
    rocket : RocketShip

    def update(self) -> None:
        if(self.rocket.has_launched == True):
            print(f"This is {self.name}. Inform that {self.rocket.name} has been launched.")

@dataclass
class NewsReporter(IObserver):

    name: str
    journal_name: str
    rocket : RocketShip

    def update(self) -> None:
        if(self.rocket.has_launched == True):
            print(
                f"This is {self.name} from the {self.journal_name} journal.",
                f"We passed the last night on the Nasa station and we are finally able that the {self.rocket.name} rocketship",
                f"has been launched at {datetime.now()}. \n The launching was a success!."
            )

if __name__ == '__main__':

    rocket = RocketShip('kepler')

    scientist = NasaScientist('Steven Shulz', rocket)
    reporter = NewsReporter('Emmily Gray', 'The Washington Post', rocket)

    rocket.add_observer(scientist)
    rocket.add_observer(reporter)

    rocket.has_launched = True


import os

dir_name = "C:/Users/catha/Downloads"
test = os.listdir(dir_name)

def deleteFiles():
    userPrint = "Enter following commands to delete file types:\nppt(x)\nzip\nrar\nexe\ndoc(x)\n"
    userInput = input(userPrint + "\n")
    if userInput == "ppt":
        for item in test:
            if item.endswith(".pptx") or item.endswith(".ppt"):
                os.remove(os.path.join(dir_name, item))
    elif userInput == "zip":
        for item in test:
            if item.endswith(".zip"):
                os.remove(os.path.join(dir_name, item))

    elif userInput == "rar":
        for item in test:
            if item.endswith(".rar"):
                os.remove(os.path.join(dir_name, item))

    elif userInput == "exe":
        for item in test:
            if item.endswith(".exe"):
                os.remove(os.path.join(dir_name, item))

    elif userInput == "docx":
        for item in test:
            if item.endswith(".docx") or item.endswith(".doc"):
                os.remove(os.path.join(dir_name, item))

    else:
        print("Incorrect Input")
        deleteFiles()

deleteFiles()