from src.GameObject import GameObject
import colorama as clr
import sys

from src.TownHall import TownHall

def getWallIndex(x,y, walls):
    for wall in walls.wallsArray:
        if(wall.posX == x and wall.posY == y and wall.alive):
            return wall
    return None

def manhattanDistance(object1, object2):
    return abs(object1.posX - object2.posX) + abs(object1.posY - object2.posY)

class Archer(GameObject):
    def __init__(self, posX, posY, char, sizeX, sizeY, color, health):
        GameObject.__init__(self, posX, posY, char, sizeX, sizeY, color, health)
        self.vel = 1
        self.attackdamage = 1
        self.currentTarget = None
        self.attackWall = None
        self.attackTarget = False
        self.townHallPosition = None
        self.range = 8

    def moveAndAttack(self, walls, townHall, cannons, huts, screen, rageSpellActive, wizardTowers):
        # if attacking a wall then decrease wall's health
        if(self.attackWall != None):
            self.attackWall.health -= self.attackdamage
            if(self.attackWall.health <= self.attackWall.maxHealth*2/3):
                self.attackWall.color = clr.Fore.YELLOW
            if(self.attackWall.health <= self.attackWall.maxHealth/3):
                self.attackWall.color = clr.Fore.RED
            if(self.attackWall.health <= 0):
                self.attackWall.alive = False
                self.attackWall.color = clr.Fore.RESET
                # self.attackWall.char = ' '
                self.attackWall = None

        # if attacking target then decrease target's health
        elif(self.attackTarget):
            self.currentTarget.health -= self.attackdamage
            if(self.currentTarget.health <= self.currentTarget.maxHealth*2/3):
                self.currentTarget.color = clr.Fore.YELLOW
            if(self.currentTarget.health <= self.currentTarget.maxHealth/3):
                self.currentTarget.color = clr.Fore.RED
            if(self.currentTarget.health <= 0):
                self.currentTarget.alive = False
                self.currentTarget.color = clr.Fore.RESET
                self.currentTarget = None
                self.attackTarget = False

        # if not attacking then find nearest wall/hut/town hall according to manhattan distance or move towards target
        else:
            # if no target, then set current target to nearest wall/hut/town hall
            if(self.currentTarget == None or self.currentTarget.alive == False):
                # find nearest wall/hut/town hall according to manhattan distance
                minDistance = 99999
                for hut in huts.hutsArray:
                    if(hut.alive):
                        if(abs(self.posX - hut.posX) + abs(self.posY - hut.posY) < minDistance):
                            self.currentTarget = hut
                            minDistance = abs(self.posX - hut.posX) + abs(self.posY - hut.posY)

                for x in range(townHall.posX, townHall.posX + townHall.sizeX):
                    for y in range(townHall.posY, townHall.posY + townHall.sizeY):
                        if(townHall.alive):
                            if(abs(self.posX- x) + abs(self.posY - y) < minDistance):
                                self.currentTarget = townHall
                                self.townHallPosition = (x,y)
                                minDistance = abs(self.posX - x) + abs(self.posY - y)

                for cannon in cannons:
                    if(cannon.alive):
                        if(abs(self.posX - cannon.posX) + abs(self.posY - cannon.posY) < minDistance):
                            self.currentTarget = cannon
                            minDistance = abs(self.posX - cannon.posX) + abs(self.posY - cannon.posY)

                for wizardTower in wizardTowers:
                    if(wizardTower.alive):
                        if(abs(self.posX - wizardTower.posX) + abs(self.posY - wizardTower.posY) < minDistance):
                            self.currentTarget = wizardTower
                            minDistance = abs(self.posX - wizardTower.posX) + abs(self.posY - wizardTower.posY)
            # move towards target
            else:
                if(manhattanDistance(self, self.currentTarget) > self.range):
                    if(self.posX < self.currentTarget.posX):
                        for i in range(self.posX, self.currentTarget.posX):
                            if(getWallIndex(i, self.posY, walls) != None):
                                # self.posX = i - 1
                                self.attackWall = getWallIndex(i, self.posY, walls)
                                break
                        if(self.attackWall == None):
                            self.posX += self.vel
                    elif(self.posX > self.currentTarget.posX):
                        for i in range(self.posX, self.currentTarget.posX, -1):
                            if(getWallIndex(i, self.posY, walls) != None):
                                # self.posX = i + 1
                                self.attackWall = getWallIndex(i, self.posY, walls)
                                break
                        if(self.attackWall == None):
                            self.posX -= self.vel
                    elif(self.posY < self.currentTarget.posY):
                        for i in range(self.posY, self.currentTarget.posY-self.range):
                            if(getWallIndex(self.posX, i, walls) != None):
                                # self.posY = i - 1
                                self.attackWall = getWallIndex(self.posX, i, walls)
                                break
                        if(self.attackWall == None):
                            self.posY += self.vel
                    elif(self.posY > self.currentTarget.posY):
                        for i in range(self.posY-self.range, self.currentTarget.posY, -1):
                            if(getWallIndex(self.posX, i, walls) != None):
                                # self.posY = i + 1
                                self.attackWall = getWallIndex(self.posX, i, walls)
                                break
                        if(self.attackWall == None):
                            self.posY -= self.vel
                else:
                    self.attackTarget = True
            # else:
            #     self.currentTarget.health -= self.attackdamage
            #     if(self.currentTarget.health <= self.currentTarget.maxHealth*2/3):
            #         self.currentTarget.color = clr.Fore.YELLOW
            #     if(self.currentTarget.health <= self.currentTarget.maxHealth/3):
            #         self.currentTarget.color = clr.Fore.RED
            #     if(self.currentTarget.health <= 0):
            #         self.currentTarget.alive = False
            #         self.currentTarget.color = clr.Fore.RESET
            #         self.currentTarget = None


# Внешняя сортировка

from external_sorts import merge_sort
import os
import random

def write_seg(f_ind, alist):
    """
    Записывает отсортированный отрезок в файл с опредленным индексом
    """
    with open(f'fl{f_ind}.txt', 'a') as out_file:
        merge_sort(alist, 0, len(alist))
        print(*alist, file=out_file)

def segment_sort(path, m):
    """
    Открывает файл с исходгыми данными и разбивает их на отрезки по 30 элементов
    """
    file_ind = 0
    with open(path, 'r') as inp_file:
        arr = []
        num = inp_file.readline()
        while num:
            arr.append(int(num))

            if len(arr) == m:
                write_seg(file_ind % 3, arr)
                arr.clear()
                file_ind += 1

            num = inp_file.readline()

        if len(arr) > 0:
            write_seg(file_ind % 3, arr)

def my_any(arr):
    """
    Возвращает истину, когда слияние завершено, а ложь в противном случае
    """
    cnt_normal = 0
    cnt_None = 0
    for i in arr:
        if i is None:
            cnt_None += 1
        else:
            cnt_normal += 1
    if cnt_None == 3 or cnt_normal == 0:
        return False
    return True

def write(arr, ind):
    """
    Осуществляет слияние с помощью генераторов
    """
    with open(f"fl{ind}.txt" if ind != 6 else 'result.txt', 'a') as out_f:
        g = tuple((int(x) for x in y.split() if x != '\n') for y in arr if y)
        values = []

        for i in range(len(g)):
            try:
                values.append(g[i].__next__())
            except StopIteration:
                values.append(None)

        ind_min = None
        while my_any(values):
            try:
                min_v = min(x for x in values if x is not None)
                ind_min = values.index(min_v)
                out_f.write(f'{min_v} ')
                values[ind_min] = g[ind_min].__next__()
            except StopIteration:
                values[ind_min] = None

        if ind_min is not None:
            out_f.write('\n')

def check_str():
    """
    Проверка окончания внешней сортировки
    """
    lines = []
    for i in range(6):
        if os.path.exists(f"fl{i}.txt"):
            cnt = 0
            with open(f'fl{i}.txt', 'r') as curr_f:
                curr_line = curr_f.readline()
                while curr_line:
                    cnt += 1
                    if cnt > 1:
                        return False
                    lines.append(curr_line)
                    curr_line = curr_f.readline()
    write(lines, 6)
    return True

def merge():
    """
    Осуществляет внешнию сортировку
    """
    m = 3  # Режим считывания и записи
    while True:
        if check_str():
            break
        # открываем файлы для чтения
        with open(f"fl{(m + 3) % 6}.txt") as f0, open(f"fl{(m + 4) % 6}.txt") as f1, open(f"fl{(m + 5) % 6}.txt") as f2:
            lines = [
                f0.readline(),
                f1.readline(),
                f2.readline()
            ]
            f_ind = m

            while any(lines):
                write(lines, f_ind)
                f_ind = m + (f_ind + 1) % 3

                lines = [
                    f0.readline(),
                    f1.readline(),
                    f2.readline()
                ]

        for j in range(3, 6):
            f = open(f"fl{(m + j) % 6}.txt", 'w')
            f.close()

        m = 0 if m == 3 else 3

N = 55000  # Количество чисел в массиве

list_ = []  # создание рандомной последовательности
for i in range(N):
    list_.append(random.randint(-10000, 10000))

# Заполняем файл случайными числами
file = open("inp_2.txt", "w")
for line in list_:
    file.write(str(line) + '\n')
file.close()

# запуск внешней сортировки
segment_sort('inp_2.txt', 30)
merge()

9 практическая/lab 9.py


"""
Created on 21/12/2019

@author: Maurizio Ferrari Dacrema
"""

from Base.DataIO import DataIO
import os, shutil
import numpy as np

def run_evaluation_ablation(recommender_class, recommender_input_args,
                            evaluator_test,
                            input_folder_path,
                            result_folder_path,
                            map_mode):

    recommender_object = recommender_class(*recommender_input_args.CONSTRUCTOR_POSITIONAL_ARGS)
    file_name_input = recommender_object.RECOMMENDER_NAME + "_best_model_last"
    file_name_output = recommender_object.RECOMMENDER_NAME

    if os.path.exists(result_folder_path + file_name_output + "_metadata.zip"):
        return

    result_folder_path_temp = result_folder_path + "__temp_model/"

    # If directory does not exist, create
    if not os.path.exists(result_folder_path_temp):
        os.makedirs(result_folder_path_temp)

    recommender_object.load_model(input_folder_path, file_name_input)
    recommender_object.save_model(result_folder_path_temp, file_name_output)

    # Alter saved object to force in the desired map mode
    dataIO = DataIO(folder_path = result_folder_path_temp)
    data_dict = dataIO.load_data(file_name = file_name_output)

    data_dict["map_mode"] = map_mode
    dataIO.save_data(file_name = file_name_output, data_dict_to_save = data_dict)

    recommender_object = recommender_class(*recommender_input_args.CONSTRUCTOR_POSITIONAL_ARGS)
    recommender_object.load_model(result_folder_path_temp,
                                  file_name=file_name_output)

    results_dict, results_run_string = evaluator_test.evaluateRecommender(recommender_object)

    shutil.rmtree(result_folder_path_temp, ignore_errors=True)

    result_file = open(result_folder_path + file_name_output + ".txt", "w")
    result_file.write(results_run_string)
    result_file.close()

    results_dict = {"result_on_last": results_dict}

    dataIO = DataIO(folder_path = result_folder_path)
    dataIO.save_data(file_name = file_name_output + "_metadata",
                     data_dict_to_save = results_dict)


import sys
from datetime import datetime, timedelta
from unittest.mock import patch

import pytest
from django.utils import timezone
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST

from apps.core.models import Article, Board
from apps.core.models.board import NameType
from apps.core.models.communication_article import (
    CommunicationArticle,
    SchoolResponseStatus,
)
from apps.user.models import UserProfile
from ara.settings import ANSWER_PERIOD, MIN_TIME, SCHOOL_RESPONSE_VOTE_THRESHOLD

from .conftest import RequestSetting, TestCase, Utils

@pytest.fixture(scope="class")
def set_communication_board(request):
    request.cls.communication_board = Board.objects.create(
        slug="with-school",
        ko_name="학교와의 게시판 (테스트)",
        en_name="With School (Test)",
        is_school_communication=True,
        name_type=NameType.REALNAME,
        read_access_mask=0b11011110,
        write_access_mask=0b11011010,
    )

@pytest.fixture(scope="class")
def set_non_communication_board(request):
    request.cls.non_communication_board = Board.objects.create(
        slug="not with-school",
        ko_name="학교 아닌 게시판 (테스트)",
        en_name="Not With School (Test)",
        is_school_communication=False,
    )

@pytest.fixture(scope="class")
def set_article(request):
    # After defining set_communication_board
    request.cls.article = Article.objects.create(
        title="Communication Article Title",
        content="Communication Article Content",
        content_text="Communication Article Content Text",
        created_by=request.cls.user,
        parent_board=request.cls.communication_board,
        name_type=NameType.REALNAME,
    )

@pytest.fixture(scope="class")
def set_communication_article(request):
    # After defining set_article
    request.cls.communication_article = CommunicationArticle.objects.create(
        article=request.cls.article
    )

@pytest.mark.usefixtures(
    "set_user_client",
    "set_user_client2",
    "set_user_client3",
    "set_user_client4",
    "set_school_admin",
    "set_communication_board",
    "set_non_communication_board",
    "set_article",
    "set_communication_article",
)
class TestCommunicationArticle(TestCase, RequestSetting):
    # ======================================================================= #
    #                            Helper Functions                             #
    # ======================================================================= #

    def _get_communication_article_status(self, article):
        res = self.http_request(self.user, "get", f"articles/{article.id}")
        return res.data.get("communication_article_status")

    def _add_positive_votes(self, article, num):
        dummy_users = Utils.create_users(num)
        for user in dummy_users:
            self.http_request(user, "post", f"articles/{article.id}/vote_positive")

    def _add_admin_comment(self, article):
        comment_data = {
            "content": "Comment made in factory",
            "created_by": self.school_admin.id,
            "parent_article": article.id,
        }
        res = self.http_request(self.school_admin, "post", "comments", comment_data)
        assert res.data.get("created_by").get("profile").get("is_school_admin")

    # status를 가지는 communication_article 반환
    def _create_article_with_status(
        self, status=SchoolResponseStatus.BEFORE_UPVOTE_THRESHOLD
    ):
        article_title = f"Factory: Article Status {status} created at {timezone.now()}"
        article_data = {
            "title": article_title,
            "content": "Content made in factory",
            "content_text": "Content Text made in factory",
            "created_by": self.user.id,
            "parent_board": self.communication_board.id,
            "name_type": NameType.REALNAME.name,
        }
        res = self.http_request(self.user, "post", "articles", article_data)

        article = Article.objects.get(pk=res.data.get("id"))

        if status == SchoolResponseStatus.BEFORE_UPVOTE_THRESHOLD:
            pass
        elif status == SchoolResponseStatus.BEFORE_SCHOOL_CONFIRM:
            self._add_positive_votes(article, SCHOOL_RESPONSE_VOTE_THRESHOLD)
        elif status == SchoolResponseStatus.ANSWER_DONE:
            self._add_admin_comment(article)

        return article

    # ======================================================================= #
    #                              Creation Test                              #
    # ======================================================================= #

    # communication_article 생성 확인
    def test_create_communication_article(self):
        # 소통 게시물 생성
        article_title = "Article for test_create_communication_article"
        user_data = {
            "title": article_title,
            "content": "Content for test_create_communication_article",
            "content_text": "test_create_communication_article",
            "creted_by": self.user.id,
            "parent_board": self.communication_board.id,
            "name_type": NameType.REALNAME.name,
        }
        self.http_request(self.user, "post", "articles", user_data)

        article = Article.objects.get(title=article_title)

        # 소통 게시물이 생성될 때 communication_article이 함께 생성되는지 확인
        article_id = article.id
        communication_article = CommunicationArticle.objects.get(article_id=article_id)
        assert communication_article

        # 필드 default 값 확인
        min_time = MIN_TIME
        assert all(
            [
                communication_article.response_deadline == min_time,
                communication_article.answered_at == min_time,
                communication_article.school_response_status
                == SchoolResponseStatus.BEFORE_UPVOTE_THRESHOLD,
            ]
        )

    # 소통 게시물이 아닌 게시물에 communication_article 없는지 확인
    def test_non_communication_article(self):
        # 비소통 게시물 생성
        article_title = "Article for test_non_communication_article"
        user_data = {
            "title": article_title,
            "content": "Content for test_non_communication_article",
            "content_text": "test_non_communication_article",
            "creted_by": self.user.id,
            "parent_board": self.non_communication_board.id,
            "name_type": NameType.REGULAR.name,
        }
        self.http_request(self.user, "post", "articles", user_data)

        article_id = Article.objects.get(title=article_title).id
        communication_article = CommunicationArticle.objects.filter(
            article_id=article_id
        ).first()
        assert communication_article is None

    # ======================================================================= #
    #                    SchoolResponseStatus Update Test                     #
    # ======================================================================= #

    # 0 -> 1
    def test_BEFORE_UPVOTE_THRESHOLD_to_BEFORE_SCHOOL_CONFIRM(self):
        from_status = SchoolResponseStatus.BEFORE_UPVOTE_THRESHOLD
        to_status = SchoolResponseStatus.BEFORE_SCHOOL_CONFIRM

        article = self._create_article_with_status(from_status)
        assert self._get_communication_article_status(article) == from_status

        self._add_positive_votes(article, SCHOOL_RESPONSE_VOTE_THRESHOLD)
        assert self._get_communication_article_status(article) == to_status

    # 0 -> 2
    def test_BEFORE_UPVOTE_THRESHOLD_to_ANSWER_DONE(self):
        from_status = SchoolResponseStatus.BEFORE_UPVOTE_THRESHOLD
        to_status = SchoolResponseStatus.ANSWER_DONE

        article = self._create_article_with_status(from_status)
        assert self._get_communication_article_status(article) == from_status

        self._add_admin_comment(article)
        assert self._get_communication_article_status(article) == to_status

    # 1 -> 2
    def test_BEFORE_SCHOOL_CONFIRM_to_ANSWER_DONE(self):
        from_status = SchoolResponseStatus.BEFORE_SCHOOL_CONFIRM
        to_status = SchoolResponseStatus.ANSWER_DONE

        article = self._create_article_with_status(from_status)
        assert self._get_communication_article_status(article) == from_status

        self._add_admin_comment(article)
        assert self._get_communication_article_status(article) == to_status

    # 2 -> 1
    def test_ANSWER_DONE_to_BEFORE_SCHOOL_CONFIRM(self):
        status = SchoolResponseStatus.ANSWER_DONE

        article = self._create_article_with_status(status)
        assert self._get_communication_article_status(article) == status

        self._add_positive_votes(article, SCHOOL_RESPONSE_VOTE_THRESHOLD)
        assert self._get_communication_article_status(article) == status

    def test_days_left(self):
        status = SchoolResponseStatus.BEFORE_UPVOTE_THRESHOLD
        article = self._create_article_with_status(status)

        # days_left가 설정되기 전
        res = self.http_request(self.school_admin, "get", f"articles/{article.id}")
        assert res.data.get("days_left") == sys.maxsize
        #
        self._add_positive_votes(article, SCHOOL_RESPONSE_VOTE_THRESHOLD)
        res = self.http_request(self.school_admin, "get", f"articles/{article.id}")
        assert res.data.get("days_left") == ANSWER_PERIOD

    def test_days_left_in_local_timezone(self):
        status = SchoolResponseStatus.BEFORE_SCHOOL_CONFIRM
        article = self._create_article_with_status(status)

        today = timezone.localtime().replace(hour=23, minute=59, second=0)
        tomorrow = (timezone.localtime() + timedelta(days=1)).replace(
            hour=0, minute=1, second=0
        )

        # localtime 기준으로 오늘에서 내일로 넘어갈 때 D-day 변경되는지 확인
        with patch.object(timezone, "localtime", return_value=today):
            res = self.http_request(self.school_admin, "get", f"articles/{article.id}")
            assert res.data.get("days_left") == ANSWER_PERIOD

        with patch.object(timezone, "localtime", return_value=tomorrow):
            res = self.http_request(self.school_admin, "get", f"articles/{article.id}")
            assert res.data.get("days_left") == ANSWER_PERIOD - 1

    # ======================================================================= #
    #                          Ordering & Filtering                           #
    # ======================================================================= #

    # 좋아요 개수 내림차순 정렬 확인
    def test_descending_ordering_by_positive_vote_count(self):
        vote_counts = (0, 1, 2, 2, 3, 4)
        articles = [self._create_article_with_status() for _ in vote_counts]

        for vote_cnt, article in zip(vote_counts, articles):
            self._add_positive_votes(article, vote_cnt)

        res = self.http_request(
            self.user,
            "get",
            "articles",
            querystring="ordering=-positive_vote_count,-created_at",
        )
        assert res.status_code == HTTP_200_OK

        res_result = res.data.get("results")

        # 좋아요 개수 내림차순 정렬 확인
        res_positive_votes = [el.get("positive_vote_count") for el in res_result]
        assert res_positive_votes == sorted(res_positive_votes, reverse=True)

        # 좋아요 개수 같은 경우 최신 글이 앞에 있는지 확인
        res_vote_cnt_eq = [
            el.get("created_at")
            for el in res_result
            if el.get("positive_vote_count") == 2
        ]
        assert res_vote_cnt_eq == sorted(
            res_vote_cnt_eq,
            reverse=True,
            key=lambda date_str: datetime.fromisoformat(date_str),
        )

    # 좋아요 개수 오름차순 정렬 확인
    def test_ascending_ordering_by_positive_vote_count(self):
        vote_counts = (4, 3, 2, 2, 1, 0)
        articles = [self._create_article_with_status() for _ in vote_counts]

        for vote_cnt, article in zip(vote_counts, articles):
            self._add_positive_votes(article, vote_cnt)

        res = self.http_request(
            self.user,
            "get",
            "articles",
            querystring="ordering=positive_vote_count,-created_at",
        )
        assert res.status_code == HTTP_200_OK

        res_result = res.data.get("results")
        assert Article.objects.count() == len(res_result)

        # 좋아요 개수 오름차순 정렬 확인
        res_positive_votes = [el.get("positive_vote_count") for el in res_result]
        assert res_positive_votes == sorted(res_positive_votes)

        # 좋아요 개수 같은 경우 최신 글이 앞에 있는지 확인
        res_vote_cnt_eq = [
            el.get("created_at")
            for el in res_result
            if el.get("positive_vote_count") == 2
        ]
        assert res_vote_cnt_eq == sorted(
            res_vote_cnt_eq,
            reverse=True,
            key=lambda date_str: datetime.fromisoformat(date_str),
        )

    # 답변 진행 상황 필터링 확인
    def test_filtering_by_status(self):
        # 모든 status의 article 하나씩 생성
        for status in SchoolResponseStatus:
            self._create_article_with_status(status)

        # 답변 완료(status=3)
        res = self.http_request(
            self.user,
            "get",
            "articles",
            querystring=f"communication_article__school_response_status={SchoolResponseStatus.ANSWER_DONE}",
        )
        assert res.status_code == HTTP_200_OK
        res_status_set = {
            el.get("communication_article_status") for el in res.data.get("results")
        }
        assert res_status_set == {SchoolResponseStatus.ANSWER_DONE}

        # 답변 전(status<3)
        res = self.http_request(
            self.user,
            "get",
            "articles",
            querystring=f"communication_article__school_response_status__lt={SchoolResponseStatus.ANSWER_DONE}",
        )
        assert res.status_code == HTTP_200_OK
        res_status_set = {
            el.get("communication_article_status") for el in res.data.get("results")
        }
        assert res_status_set == {*SchoolResponseStatus} - {
            SchoolResponseStatus.ANSWER_DONE
        }

    # ======================================================================= #
    #                                Anonymous                                #
    # ======================================================================= #

    # 익명 게시물 작성 불가 확인
    def test_anonymous_article(self):
        article_title = "Anonymous article"
        article_data = {
            "title": article_title,
            "content": "Content of anonymous article",
            "content_text": "Content text of anonymous article",
            "created_by": self.user.id,
            "parent_board": self.communication_board.id,
            "name_type": NameType.ANONYMOUS.name,
        }
        result = self.http_request(self.user, "post", "articles", article_data)
        assert result.status_code == HTTP_400_BAD_REQUEST

    # 익명 댓글 작성 불가 확인
    def test_anonymous_comment(self):
        comment_data = {
            "content": "Anonymous comment",
            "created_by": self.user.id,
            "parent_article": self.article.id,
            "name_type": NameType.ANONYMOUS,
        }
        res = self.http_request(self.user, "post", "comments", comment_data).data
        assert res.get("name_type") == NameType.REALNAME

    # ======================================================================= #
    #                               School Admin                              #
    # ======================================================================= #

    # school_admin이 작성할 때 my_comment_profile REGULAR 확인
    def test_school_admin_my_comment_profile(self):
        res = self.http_request(
            self.school_admin, "get", f"articles/{self.article.id}"
        ).data

        assert res.get("my_comment_profile")["profile"]["is_school_admin"]
        assert (
            res.get("my_comment_profile")["profile"]["nickname"]
            == UserProfile.objects.get(user_id=self.school_admin.id).nickname
        )


import requests
from cardReader import CardReader

def admin(id):
    print("read in card id " + id)
    mode = input("what do you want to do? (addTokens, addTickets, charge, addUser, removeUser)")
    while mode not in ["addTokens", "addTickets", "charge", "addUser", "removeUser"]:
        mode = input("please enter a valid option (addTokens, addTickets, charge, addUser, removeUser)")
    if mode == "addTokens" or mode == "addTickets" or mode == "charge" or mode == "addUser":
        amount = input("Please enter an amount")
        name = ""
        try:
            amount = int(amount)
        except:
            print("Please enter a valid integer")
            return
        if mode == "addUser":
            name = input("Please enter a name")
        v = requests.get("https://arcade-52bs.onrender.com/" + mode, params={"id" : id, "amount" : amount, "name" : name})
        if v.text == "1":
            print("success")
        else:
            print("failure")
    elif mode == "removeUser":
        v = requests.get("https://arcade-52bs.onrender.com/removeUser", params={"id" : id})


# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
import argparse
import json
import os
from random import randint
from time import sleep

from azureml.core import Run

class Util:

    @staticmethod
    def str2bool(v):

        if v is None:
            return False
        if isinstance(v, bool):
            return v
        if v.lower() in ('yes', 'True', 'true', 't', 'y', '1'):
            return True
        elif v.lower() in ('no', 'False', 'false', 'f', 'n', '0'):
            return False
        else:
            raise argparse.ArgumentTypeError('Boolean value expected.')

parser = argparse.ArgumentParser("split")
parser.add_argument("--node_count", default=1, type=int, help="number of nodes")
parser.add_argument("--process_count_per_node", default=1, type=int, help="number of processes per node")
parser.add_argument("--retrain_failed_models", default=False, type=Util.str2bool, help="retrain failed models only")

args, _ = parser.parse_known_args()
many_models_train = None

# Whether or not this driver has been initialized
driver_initialized = False

def _get_automl_settings():
    with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'automl_settings.json')) as json_file:
        return json.load(json_file)

def _initialize_driver():
    print("Initializing driver")

    # Sleep this worker node for a random amount of time. This helps stagger new traffic over a
    # longer period of time so that service pods have time to auto-scale up.

    max_concurrent_runs = args.node_count * args.process_count_per_node
    traffic_ramp_up_period_in_seconds = min(max_concurrent_runs, 600)
    worker_sleep_time_in_seconds = randint(1, traffic_ramp_up_period_in_seconds)
    print("Traffic ramp up period: {} seconds".format(traffic_ramp_up_period_in_seconds))
    print("Sleeping this worker for {} seconds to stagger traffic ramp-up...".format(worker_sleep_time_in_seconds))
    sleep(worker_sleep_time_in_seconds)
    current_step_run = Run.get_context()
    from azureml.train.automl.runtime._many_models.many_models_train import \
        ManyModelsTrain
    global many_models_train
    many_models_train = ManyModelsTrain(current_step_run=current_step_run,
                                        automl_settings=_get_automl_settings(),
                                        process_count_per_node=args.process_count_per_node,
                                        retrain_failed_models=args.retrain_failed_models)
    print('many_models_train_driver._initialize_driver() done.')

def run(input_data):
    print("Invoking many_models_train_driver.run()")

    # Initiailze the driver when the first mini batch runs.
    # (This is done because the initialize call requires a sleep call to stagger new traffic ramp-up (refer to
    # the initialize method for more info). There can be a large time gap between calls to the PRS in-built init()
    # methods and the in-built run methods. For example, for large datasets, it seems possible for PRS to invoke
    # the init() methods of all workers, and then 15 minutes later, invoke the run methods of all workers. Given that,
    # the sleep call to stagger traffic ramp-up won't work as expected if invoked in the PRS in-built init() method.)
    global driver_initialized
    if not driver_initialized:
        _initialize_driver()
        driver_initialized = True

    global many_models_train
    return many_models_train.run(input_data)


import cv2 as cv
import mediapipe as mp

class poseDetector():
    def __init__(self, static_image_mode=False,
                 model_complexity=1,
                 smooth_landmarks=True,
                 enable_segmentation=False,
                 smooth_segmentation=True,
                 min_detection_confidence=0.5,
                 min_tracking_confidence=0.5):  # con - confidence

        self.static_image_mode = static_image_mode
        self.model_complexity = model_complexity
        self.smooth_landmarks = smooth_landmarks
        self.enable_segmentation = enable_segmentation
        self.smooth_segmentation = smooth_segmentation
        self.min_detection_confidence = min_detection_confidence
        self.min_tracking_confidence = min_tracking_confidence

        self.mpDraw = mp.solutions.drawing_utils
        self.mpPose = mp.solutions.pose
        self.pose = self.mpPose.Pose()

    def findPose(self, img, draw = True):

        imgRGB = cv.cvtColor(img, cv.COLOR_BGR2RGB)
        self.results = self.pose.process(imgRGB)

        if self.results.pose_landmarks:
           self.mpDraw.draw_landmarks(img, self.results.pose_landmarks, self.mpPose.POSE_CONNECTIONS)
        return img

    def findPosition(self, img, draw = True):
        lmList = []

        if self.results.pose_landmarks:

            for id, lm in enumerate(self.results.pose_landmarks.landmark):
                h, w, c = img.shape
                # find out the position of each landmark in the image,
                # given the ratio of those position in the picture
                # z is the depth, make it a positive integer, so it can be
                # compared more easily.
                cx, cy, cz = int(lm.x * w), int(lm.y * h), int(-lm.z * 100)
                lmList.append([id, cx, cy, cz])
                if draw:
                    cv.circle(img, (cx, cy), 15, (255, 0, 255), cv.FILLED)
        return lmList

def main():
    pTime = 0
    cTime = 0

    cap = cv.VideoCapture(0)
    # set the dimensions of live video
    cap.set(3, 640)
    cap.set(4, 480)
    detector = poseDetector()
    while True:
        success, img = cap.read()
        img = detector.findPose(img) #Get the model hands on the image

        lmList = detector.findPosition(img) #Collect all the positions
        if len(lmList) != 0:
            print(lmList[4])

        fps = 1 / (cTime - pTime)
        pTime = cTime

        cv.imshow("img", img)
        cv.waitKey(1)

# _name_ is a implicit variable whose value is set as __main__.
# If other files import this module, they will execute this main function first and then execute other codes
if __name__ == '__main__':
    main()


#!/usr/bin/python3

if __name__ == "__main__":
    from calculator_1 import add, sub, mul, div
    import sys
    if len(sys.argv) - 1 != 3:
        print("Usage: ./100-my_calculator.py <a> <operator> <b>")
        sys.exit(1)

    option = {"+": add, "-": sub, "*": mul, "/": div}

    if sys.argv[2] not in option:
        print("Unknown operator. Available operators: +, -, * and /")
        sys.exit(1)

    a = int(sys.argv[1])
    b = int(sys.argv[3])
    operator = sys.argv[2]
    if operator == "/":
        if b == 0:
            print("Error: Cannot divide by zero")
            sys.exit(1)
    result = option[operator](a, b)
    print("{} {} {} = {}".format(a, operator, b, result))


# -*- coding: utf-8 -*-
# __author__ = 'shijin'
import web
import json
import os
import unittest
import datetime
from mainapp.models.mongo.denovo_rna_v2 import DenovoRnaV2
from mbio.api.to_file.denovo_rna_v2 import *
from mainapp.libs.signature import check_sig
from mainapp.controllers.project.denovo_rna_v2_controller import DenovoRnaV2Controller

class GenesetDeleteAction(DenovoRnaV2Controller):
    def __init__(self):
        super(GenesetDeleteAction, self).__init__(instant=True)

    @check_sig
    def POST(self):
        data = web.input()
        #print data
        default_argu = ['geneset_id', "task_id"]
        for argu in default_argu:
            if not hasattr(data, argu):
                var = []
                var.append(argu)
                info = {'success': False, 'info': "Lack argument: %s" % (argu), "code": 'C1601101', "variables": var}
                return json.dumps(info)
        #print(data.geneset_id)
        if self.denovo_rna_v2.delete_geneset(data.geneset_id, data.task_id):
            task_info = {"success": True, "info": "任务运行成功."}
            task_info['content'] = {
                'ids': {
                    'id': "",
                    'name': ""
                    }}
            return json.dumps(task_info)
        else:
            task_info = {"success": False, "info": "任务运行失败.", "code": 'C1601102', "variables": ''}
            return json.dumps(task_info)

class TestFunction(unittest.TestCase):
    """
    This is test for the tool. Just run this script to do test.
    """
    def test_this(self):
        cmd = 'python /mnt/ilustre/users/sanger-dev/biocluster/bin/webapitest.py '
        cmd += 'post '
        cmd += "-fr no "
        cmd += '-c {} '.format("client03")
        cmd += "i/denovo_rna_v2/geneset_delete "
        cmd += "-b http://192.168.12.102:9090 "
        args = dict(
            task_id="denovo_rna_v2",
            task_type="1",
            # submit_location="GenesetVenn",
            geneset_ids="5a35da8ba4e1af38e6fb83d7",
        )
        arg_names, arg_values = args.keys(), args.values()
        cmd += '-n "{}" -d "{}" '.format(";".join(arg_names), ";".join(arg_values))
        print(cmd)
        os.system(cmd)

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


# [2016-12-09] Challenge #294 [Hard] Rack management 3
# https://www.reddit.com/r/dailyprogrammer/comments/5hcd0x/20161209_challenge_294_hard_rack_management_3/

import copy, random, timeit

original_row = "sd?zeioao?mluvepesceinfxt?wyiru?ie?giator?t??nuefje?l?odndrotpewlgoobiinysagacaqski?aeh?rbhaervtnl?m"
words = [[line.strip(), 0] for line in open("enable1.txt") if len(line.strip()) < 11]
letters = "abcdefghijklmnopqsrtuvwxyz"
scores = [1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10]
practice = False
test = [6,0,0,5,5,3,6,6,5,0,6,7,1,2,1]
iteration = 0
tilescores = dict(zip("abcdefghijklmnopqrstuvwxyz?", [1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10,0]))
char_freq = {'a': 22, 'c': 15, 'b': 9, 'e': 25, 'd': 16, 'g': 13, 'f': 7, 'i': 23, 'h': 10, 'k': 6, 'j': 1, 'm': 11, 'l': 17, 'o': 19, 'n': 20, 'q': 0, 'p': 12, 's': 24, 'r': 21, 'u': 14, 't': 18, 'w': 5, 'v': 4, 'y': 8, 'x': 2, 'z': 3}

def calcScore(word):
  return sum(j * tilescores[char] for j, char in enumerate(word, 1))

def sortWord(word):
  word = "".join([p[0] for p in sorted([[letter, char_freq[letter]] for letter in word], key=lambda x: x[1])])
  return word

def bestWord(hand):
  cutoff = 10
  bestword = ["", 0, ""]
  perm_unknown = hand.count("?")
  for word in words:
    unknown = perm_unknown
    temp_hand = hand[:]
    score_word = word[0][:]
    yes = True
    for index, letter in enumerate(word[2]):
      if letter in temp_hand:
        temp_hand = temp_hand.replace(letter, "", 1)
      elif unknown > 0:
        # score_word = score_word[:index] + "?" + score_word[index + 1:]
        score_word = score_word.replace(letter, '?', 1)
        unknown -= 1
      else:
        yes = False
        break
    if yes:
      if cutoff < 0:
        break
      else:
        cutoff -= 1
      # print(word)
      temp_score = calcScore(score_word)
      if temp_score > bestword[1]:
        bestword = [word[0], temp_score, score_word]
        # bestword.append(score_word)
  return bestword

def randomHand(hand, row, order=False):
  global iteration
  # print("hand", hand)

  if not practice:
    stealLeft = random.randint(0, 10 - len(hand))
  else:
    stealLeft = test[iteration]

  if order and len(order) > iteration:
    stealLeft = order[iteration]

  iteration += 1

  if stealLeft > len(row):
    stealLeft = len(row)
  # print("stealLeft", stealLeft)
  hand += row[0:stealLeft]
  row = row[stealLeft:]
  stealRight = 10 - len(hand)
  # print("stealRight", stealRight)
  if stealRight > len(row):
    stealRight = len(row)
  if stealRight > 0:
    hand += row[-stealRight:]
    row = row[:-stealRight]
  return [stealLeft, hand, row, bestWord(hand)]

currentArray = [0]
currentBest = [0, 0]
currentAttempt = 0

def updateSeq(score):
  global currentAttempt, currentBest, currentArray
  currentAttempt += 1
  if score > currentBest[1]:
    currentBest = [currentArray[-1], score]
  if currentAttempt == 100:
    currentAttempt = 0
    if currentArray[-1] == 9:
      currentArray[-1] = currentBest[0]
      print("Moving Down, Best Seq: ", currentArray)
      currentArray.append(0)
    else:
      currentArray[-1] += 1

def attackRow():
  global iteration
  currentAttack = []
  iteration = 0
  hand = ""
  totalScore = 0
  row = original_row[:]
  empty = False
  while len(row) > 0 or not empty:
    left, hand, row, bestword = randomHand(hand, row, currentArray)
    # print("row", row)
    # print("handpick", left, hand)
    # print("bestword", bestword)
    try:
      currentAttack.append(str(left) + " " + bestword[2] + " " + bestword[0])
    except:
      print("Error!")
      print(left, bestword)
      currentAttack.append((left, bestword))
    if bestword[2] == "":
      empty = True
    totalScore += bestword[1]
    for letter in bestword[2]:
      hand = hand.replace(letter, "", 1)
  currentAttack.append("Hand: " + str(hand) + " | Row: " + str(row))
  updateSeq(totalScore)
  return [totalScore, currentAttack]

if __name__ == "__main__":
  for index, item in enumerate(words):
    words[index][1] = calcScore(item[0])
    words[index].append(sortWord(item[0]))
  words = sorted(words, key=lambda x: x[1], reverse=True)
  best = [0, ""]
  mainCounter = 0
  start = timeit.default_timer()
  while 1:
    results = attackRow()
    if results[0] > best[0]:
    # if 1 == 1:
      best = results
      for sentence in results[1]:
        print(sentence)
      print("Total Score: " + str(results[0]))
    mainCounter += 1
    if mainCounter > 9:
      print(timeit.default_timer() - start)
      start = timeit.default_timer()
      mainCounter = 0


#!/usr/bin/env python3

import os
import sys
import tempfile

import unittest
from unittest import mock
from CIME.utils import indent_string, run_and_log_case_status, \
    import_from_file

from . import utils

class TestIndentStr(unittest.TestCase):
    """Test the indent_string function.

    """

    def test_indent_string_singleline(self):
        """Test the indent_string function with a single-line string

        """
        mystr = 'foo'
        result = indent_string(mystr, 4)
        expected = '    foo'
        self.assertEqual(expected, result)

    def test_indent_string_multiline(self):
        """Test the indent_string function with a multi-line string

        """
        mystr = """hello
hi
goodbye
"""
        result = indent_string(mystr, 2)
        expected = """  hello
  hi
  goodbye
"""
        self.assertEqual(expected, result)

class MockTime(object):
    def __init__(self):
        self._old = None

    def __enter__(self):
        self._old = getattr(sys.modules["time"], "strftime")
        setattr(sys.modules["time"], "strftime", lambda *args: "00:00:00 ")

    def __exit__(self, *args, **kwargs):
        setattr(sys.modules["time"], "strftime", self._old)

def match_all_lines(data, lines):
    for line in data:
        for i, x in enumerate(lines):
            if x == line:
                lines.pop(i)

                continue

        if len(lines) == 0:
            return True, []

    return False, lines

class TestUtils(unittest.TestCase):
    def setUp(self):
        self.base_func = lambda *args: None

        #pylint: disable=unused-argument
        def _error_func(*args):
            raise Exception("Something went wrong")

        self.error_func = _error_func

    def assertMatchAllLines(self, tempdir, test_lines):
        with open(os.path.join(tempdir, "CaseStatus")) as fd:
            data = fd.readlines()

        result, missing = match_all_lines(data, test_lines)

        error = []

        if len(missing) != 0:
            error.extend(["Missing Lines", ""])
            error.extend([x.rstrip("\n") for x in missing])
            error.extend(["", "Tempfile contents", ""])
            error.extend([x.rstrip("\n") for x in data])

        self.assertTrue(result, msg="\n".join(error))

    def test_import_from_file(self):
        with tempfile.NamedTemporaryFile() as fd:
            fd.writelines([
                b"def test():\n",
                b"  return 'value'",
            ])

            fd.flush()

            module = import_from_file("test.py", fd.name)

            assert module.test() == "value"

    def test_run_and_log_case_status(self):
        test_lines = [
            "00:00:00 default starting \n",
            "00:00:00 default success \n",
        ]

        with utils.TemporaryDirectory() as tempdir, MockTime():
            run_and_log_case_status(self.base_func, "default",
                                    caseroot=tempdir)

            self.assertMatchAllLines(tempdir, test_lines)

    def test_run_and_log_case_status_case_submit_on_batch(self):
        test_lines = [
            "00:00:00 case.submit starting \n",
            "00:00:00 case.submit success \n",
        ]

        with utils.TemporaryDirectory() as tempdir, MockTime():
            run_and_log_case_status(self.base_func, "case.submit",
                                    caseroot=tempdir, is_batch=True)

            self.assertMatchAllLines(tempdir, test_lines)

    def test_run_and_log_case_status_case_submit_no_batch(self):
        test_lines = [
            "00:00:00 case.submit starting \n",
            "00:00:00 case.submit success \n",
        ]

        with utils.TemporaryDirectory() as tempdir, MockTime():
            run_and_log_case_status(self.base_func, "case.submit",
                                    caseroot=tempdir, is_batch=False)

            self.assertMatchAllLines(tempdir, test_lines)

    def test_run_and_log_case_status_case_submit_error_on_batch(self):
        test_lines = [
            "00:00:00 case.submit starting \n",
            "00:00:00 case.submit error \n",
            "Something went wrong\n",
        ]

        with utils.TemporaryDirectory() as tempdir, MockTime():
            with self.assertRaises(Exception):
                run_and_log_case_status(self.error_func, "case.submit",
                                        caseroot=tempdir, is_batch=True)

            self.assertMatchAllLines(tempdir, test_lines)

    def test_run_and_log_case_status_custom_msg(self):
        test_lines = [
            "00:00:00 default starting starting extra\n",
            "00:00:00 default success success extra\n",
        ]

        starting_func = mock.MagicMock(return_value="starting extra")
        success_func = mock.MagicMock(return_value="success extra")

        def normal_func():
            return "data"

        with utils.TemporaryDirectory() as tempdir, MockTime():
            run_and_log_case_status(normal_func, "default",
                                    custom_starting_msg_functor=starting_func,
                                    custom_success_msg_functor=success_func,
                                    caseroot=tempdir)

            self.assertMatchAllLines(tempdir, test_lines)

        starting_func.assert_called_with()
        success_func.assert_called_with("data")

    def test_run_and_log_case_status_custom_msg_error_on_batch(self):
        test_lines = [
            "00:00:00 default starting starting extra\n",
            "00:00:00 default success success extra\n",
        ]

        starting_func = mock.MagicMock(return_value="starting extra")
        success_func = mock.MagicMock(return_value="success extra")

        def error_func():
            raise Exception("Error")

        with utils.TemporaryDirectory() as tempdir, MockTime(), \
                self.assertRaises(Exception):
            run_and_log_case_status(error_func, "default",
                                    custom_starting_msg_functor=starting_func,
                                    custom_success_msg_functor=success_func,
                                    caseroot=tempdir)

            self.assertMatchAllLines(tempdir, test_lines)

        starting_func.assert_called_with()
        success_func.assert_not_called()

    def test_run_and_log_case_status_error(self):
        test_lines = [
            "00:00:00 default starting \n",
            "00:00:00 default error \n",
            "Something went wrong\n",
        ]

        with utils.TemporaryDirectory() as tempdir, MockTime():
            with self.assertRaises(Exception):
                run_and_log_case_status(self.error_func, "default",
                                        caseroot=tempdir)

            self.assertMatchAllLines(tempdir, test_lines)

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


"""文字列基礎
正規表現に一致する部分文字列の登場回数をカウントする方法
(正規表現モジュール reを使用する場合)

[説明ページ]
https://tech.nkhn37.net/python-substring-count/#findall
"""
import re

text = "PythonPythonPythonプロジェクトPythonプロジェクトPython"

# reを使って部分文字列をカウントする
ptrn = re.compile("Python")
result = ptrn.findall(text)
print(len(result))

# 重複のない出現回数をカウントするので注意
ptrn = re.compile("PythonPython")
result = ptrn.findall(text)
print(len(result))


import numpy as np
import pandas as pd

from sklearn.model_selection import train_test_split
from knn import KNN

if __name__ == '__main__':
    # Load hc_dataset dataset
    hc_dataset = pd.read_csv('HC_Body_Temperature.txt', sep="\s+", header=None, names=["x", "label", "y"], dtype=float)
    hc_dataset.loc[hc_dataset['label'] > 1, 'label'] = -1

    iterations = 100
    clf = KNN(k={1, 3, 5, 7, 9})

    data = [[1, 0, 0, 0], [3, 0, 0, 0], [5, 0, 0, 0], [7, 0, 0, 0], [9, 0, 0, 0]]
    avg_true_errs = pd.DataFrame(data, columns=['K_value', 'l_1', 'l_2', 'l_inf'])
    avg_emp_errs = pd.DataFrame(data, columns=['K_value', 'l_1', 'l_2', 'l_inf'])
    for _ in range(iterations):
        x_train, x_test, y_train, y_test = train_test_split(hc_dataset[['x', 'y']], hc_dataset['label'], test_size=0.5)

        clf.fit(np.array(x_train[['x', 'y']]), np.array(y_train))
        predictions_test = clf.predict(np.array(x_test[['x', 'y']]), np.array(y_test))
        predictions_train = clf.predict(np.array(x_train[['x', 'y']]), np.array(y_train))

        avg_true_errs[['l_1', 'l_2', 'l_inf']] += predictions_test[['l_1', 'l_2', 'l_inf']]
        avg_emp_errs[['l_1', 'l_2', 'l_inf']] += predictions_train[['l_1', 'l_2', 'l_inf']]

    avg_true_errs[['l_1', 'l_2', 'l_inf']] /= iterations
    avg_emp_errs[['l_1', 'l_2', 'l_inf']] /= iterations

    print("----------- true_err -----------")
    print(avg_true_errs)
    print("----------- emp_err -----------")
    print(avg_emp_errs)


import tweepy
from balkanicagenerator import *

saveLocation = 'result.jpg'

def saveImage():
    img = pasteMan()
    phrase = getPhrase()
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("segoesc.ttf", 25)
    draw.text((150,10), convertToFit(phrase), font=font, fill=(0,0,0,0))

    img.save(saveLocation)

# uploads the image to twitter with a random status from text file
# fill up manually CONSUMER_KEY, CONSUMER_SECRET etc.
def uploadImage():
    status = getPhrase()

    CONSUMER_KEY = 'key'
    CONSUMER_SECRET = 'secret'
    ACCESS_KEY = 'token'
    ACCESS_SECRET = 'secret'
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.secure = True
    auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
    api = tweepy.API(auth)
    fn = os.path.abspath(saveLocation)
    api.update_with_media(fn, status=status)

def deleteImage():
    os.remove(saveLocation)

if __name__ == '__main__':
    saveImage()
    uploadImage()
    deleteImage()


# -- coding: utf-8 --**
# train the Run EV-Gait-3DGraph model

import numpy as np
import torch
import torch.nn.functional as F
import torch_geometric.transforms as T
from torch_geometric.data import DataLoader
import argparse
import pdb
from tqdm import tqdm
import os
import torchvision
import torch.distributed as dist

import logging
import sys
sys.path.append("..")
from config import Config
from models.dual_model import Net as dual_model
from datasets.img_voxel_dataset import EV_Gait_3DGraph_Dataset as dual_dataset
from datasets.spatial_transforms import *
from datasets.temporal_transforms import *

if __name__ == '__main__':
    # pdb.set_trace()
    if not os.path.exists(Config.log_dir):
        os.makedirs(Config.log_dir)

    if not os.path.exists(Config.model_dir):
        os.makedirs(Config.model_dir)

    parser = argparse.ArgumentParser()
    # parser.add_argument("--cuda", default="0", help="The GPU ID")
    parser.add_argument("--epoch", default=150, type=int, help="The GPU ID")
    parser.add_argument("--batch_size", default=8, type=int, help="batch size")
    parser.add_argument("--num_works", default=16, type=int)
    parser.add_argument("--clip_len", default=8, type=int)
    parser.add_argument('--base_model', default='resnet50', type=str)
    parser.add_argument('--local_rank', default=-1, type=int,
                    help='node rank for distributed training')

    args = parser.parse_args()
    torch.multiprocessing.set_sharing_strategy('file_system')
    torch.backends.cudnn.benchmark = False
    # logging.basicConfig(filename=Config.graph_train_log_path, level=logging.DEBUG)
    dist.init_process_group(backend='nccl')
    args.nprocs = torch.cuda.device_count()
    # model = model_dataset[args.type]["model"]()
    model = dual_model(

    dim = 768,
    num_heads = 4,
    mlp_ratio=4.,
    qkv_bias=False,
    clip_len = args.clip_len,
    drop=0.,
    attn_drop=0.,
    init_values=1e-5,
    drop_path=0.
)

    torch.cuda.set_device(args.local_rank)
    model.cuda(args.local_rank)
    model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],find_unused_parameters=True)
    # ,find_unused_parameters=True

    optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

    input_mean=[.485, .456, .406]
    input_std=[.229, .224, .225]
    normalize = GroupNormalize(input_mean, input_std)

    scales = [1, .875, .75, .66]
    trans_train  = torchvision.transforms.Compose([
                            GroupScale(256),
                            GroupMultiScaleCrop(224, scales),
                            Stack(roll=(args.base_model in ['BNInception', 'InceptionV3'])),
                            ToTorchFormatTensor(div=(args.base_model not in ['BNInception', 'InceptionV3'])),
                            normalize
                            ])
    temporal_transform_train = torchvision.transforms.Compose([
                                        TemporalUniformCrop_train(args.clip_len)
                                        ])
    trans_test  = torchvision.transforms.Compose([
                            GroupScale(256),
                            GroupCenterCrop(224),
                            Stack(roll=(args.base_model in ['BNInception', 'InceptionV3'])),
                            ToTorchFormatTensor(div=(args.base_model not in ['BNInception', 'InceptionV3'])),
                            normalize
                            ])
    temporal_transform_test = torchvision.transforms.Compose([
                                        TemporalUniformCrop_val(args.clip_len)
                                    ])
    train_data_aug = T.Compose([T.Cartesian(cat=False), T.RandomScale([0.96, 1]), T.RandomTranslate(0.001)])

    dataset_factory = dual_dataset
    train_dataset = dataset_factory(
        Config.Nmnist_root_dir, mode='train',split='dir',transform=train_data_aug,spatial_transform=trans_train,
         temporal_transform = temporal_transform_train
    )
    num_samples = len(train_dataset)

    train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
    train_loader = DataLoader(train_dataset, batch_size=args.batch_size, sampler=train_sampler, num_workers=args.num_works, pin_memory=True, drop_last=True)

    test_data_aug = T.Compose([T.Cartesian(cat=False), T.RandomScale([0.999, 1])])
    test_dataset = dataset_factory(
        Config.Nmnist_root_dir, mode='test',split='dir',transform=test_data_aug,
        spatial_transform=trans_test, temporal_transform = temporal_transform_test
    )

    test_sampler = torch.utils.data.distributed.DistributedSampler(test_dataset)
    test_loader = DataLoader(test_dataset, batch_size=args.batch_size, sampler=test_sampler,num_workers=args.num_works, pin_memory=True)

    # train

    for epoch in range(1, args.epoch+1):
        model.train()

        if epoch == 60:
            for param_group in optimizer.param_groups:
                param_group["lr"] = 0.0001
        if epoch == 110:
            for param_group in optimizer.param_groups:
                param_group["lr"] = 0.00001

        correct = 0
        total = 0
        total_loss = 0
        train_sampler.set_epoch(epoch)
        # train_loader = DataLoader(train_dataset, batch_size=args.batch_size, sampler=train_sampler, num_workers=args.num_works, pin_memory=True, drop_last=True)
        with tqdm(total=num_samples, desc=f'Epoch {epoch}/{args.epoch}', unit='sample') as pbar:
            for batch in train_loader:

                optimizer.zero_grad()

                label = batch[0].cuda(args.local_rank,non_blocking=True)
                data_voxel = batch[1].cuda(args.local_rank,non_blocking=True)
                data_frame = batch[2].cuda(args.local_rank,non_blocking=True)
                end_point = model(data_voxel)
                # pdb.set_trace()
                loss = F.nll_loss(end_point, label)
                pred = end_point.max(1)[1]
                total += len(label)
                correct += pred.eq(label).sum()
                total_loss += float(loss)
                loss.backward()
                optimizer.step()
                pbar.set_postfix(**{'loss (batch)': loss.item()})
                pbar.update(len(label))
        if dist.get_rank() == 0:
            # logging.info("epoch: {}, train acc is {}, loss is {}".format(epoch, float(correct) / total,total_loss/len(train_loader)))
            print("epoch: {}, train acc is {},loss is {}".format(epoch, float(correct) / total,total_loss/len(train_loader)))
        if epoch % 10==0:
            model.eval()
            correct_t = 0
            total_t = 0
            with torch.no_grad():
                for index,batch in enumerate(tqdm(test_loader)):
                    label = batch[0].cuda(args.local_rank,non_blocking=True)
                    data_voxel = batch[1].cuda(args.local_rank,non_blocking=True)
                    data_frame = batch[2].cuda(args.local_rank,non_blocking=True)
                    end_point = model(data_voxel)
                    pred_t = end_point.max(1)[1]
                    total_t += len(label)
                    correct_t += pred_t.eq(label).sum().item()

                if dist.get_rank() == 0:
                    # logging.info("test acc is {}".format(float(correct_t) / total_t))
                    print("test acc is {}".format(float(correct_t) / total_t))

        # accuracy of each epoch
        if dist.get_rank() == 0 and  epoch %10==0:
            torch.save(model.module.state_dict(), os.path.join(Config.model_dir, 'NMnist_{}_{}_add_neck.pkl'.format(args.type,epoch)))
    # test
    model.eval()
    correct = 0
    total = 0
    with torch.no_grad():
        for index,batch in enumerate(tqdm(test_loader)):
            label = batch[0].cuda(args.local_rank,non_blocking=True)
            data_voxel = batch[1].cuda(args.local_rank,non_blocking=True)
            data_frame = batch[2].cuda(args.local_rank,non_blocking=True)
            end_point = model(data_voxel)
            pred = end_point.max(1)[1]
            total += len(label)
            correct += pred.eq(label).sum().item()

        # logging.info("test acc is {}".format(float(correct) / total))
        if dist.get_rank() == 0:
            print("test acc is {}".format(float(correct) / total))
            torch.save(model.module.state_dict(), os.path.join(Config.model_dir, 'NMnist_{}_{}_add_neck.pkl'.format(args.type,epoch)))
        # torch.save(model.state_dict(), Config.gcn_model_name.format(epoch))


from pydicom import dcmread
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import os
from tkinter import filedialog
import tkinter

#用户界面参量：维度号码，通道类型、输入路径、输出路径
#word内提醒医生必须选中dicom文件，其他格式不行#必须确认导入导出文件夹标准化（输入只有dicom，输出只有空文件夹），重新生成的话必须手动删除文件夹内容或者新建文件夹（不搞一键删除）

#可持续优化：图像通道不是RGB而是BGR/GBR的问题#注意uniT8的精度#内存目前最大占用1g

#parameters that need to be set at beginning

#set by programmer-----------------------------!
MAX_STANDARD=255
MIN_STANDARD=0

Channel_Mode=1#1 or 3 symbolizes one channel or RGB channel
Main_Dimens=0#0/1/2 means which 2-dimens is front
address=''              #change path    always remember add a
save_address=''             #change path
print("Welcome to Dicom-Transformer.")
#def is_dicom_file(filename):
#    '''
#       判断某文件是否是dicom格式的文件
#    :param filename: dicom文件的路径
#    :return:
#    '''
#    file_stream = open(filename, 'rb')
#    file_stream.seek(128)
#    data = file_stream.read(4)
#    file_stream.close()
#    if data == b'DICM':
#        return True
#    return False

def DICOM_to_PNG(address,save_address):
    print('All Dicom file names: ',os.listdir(address))
    all_data_name=os.listdir(address)
    print('Total DICOM Files:',len(all_data_name))

    for i in range(len(all_data_name)):
        path=address+all_data_name[i]
        ds=dcmread(path)
        print(f'Dealing with file {all_data_name[i]}.')
        print(ds.PatientName)
        print(ds.Manufacturer)
        print(ds.InstitutionName)
        print(f'{all_data_name[i]} got shape {ds.pixel_array.shape}, its dimensions is {ds.pixel_array.ndim}, the type of matrix is {type(ds.pixel_array)}.')#numpy.ndarray type
        ds.pixel_array_uint8=(ds.pixel_array).astype(np.uint8)#faster  uinT8  precision problem
        print('MAX PIXEL VALUE:',np.max(ds.pixel_array_uint8), '  MIN PIXEL VALUE:',np.min(ds.pixel_array_uint8))

        print('Image processing...')
        if np.max(ds.pixel_array_uint8)>MAX_STANDARD or np.min(ds.pixel_array_uint8)<MIN_STANDARD:
            ds_nor=((ds.pixel_array_uint8/np.max(ds.pixel_array_uint8))*MAX_STANDARD).astype('uint8')
        else:
            ds_nor=ds.pixel_array_uint8

        if Channel_Mode == 1:#grey
            ds_nor_3dimens=ds_nor[:,:,:,0]
            for j in range(ds_nor_3dimens.shape[Main_Dimens]):#循环对每一层转换，名字加个层数号
                if Main_Dimens==0:
                    ds_nor_layer=ds_nor_3dimens[j,:,:]

                    save_name=save_address+all_data_name[i]+'_'+str(j)+'.png'

                    im=Image.fromarray(ds_nor_layer)
                    im.save(save_name)
                if Main_Dimens==1:
                    ds_nor_layer=ds_nor_3dimens[:,j,:]

                    save_name=save_address+all_data_name[i]+'_'+str(j)+'.png'

                    im=Image.fromarray(ds_nor_layer)
                    im.save(save_name)
                if Main_Dimens==2:
                    ds_nor_layer=ds_nor_3dimens[:,:,j]

                    save_name=save_address+all_data_name[i]+'_'+str(j)+'.png'

                    im=Image.fromarray(ds_nor_layer)
                    im.save(save_name)
        else:#RGB
            #ds_nor
            for j in range(ds_nor.shape[Main_Dimens]):#循环对每一层转换，名字加个层数号
                if Main_Dimens==0:
                    ds_nor_layer=ds_nor[j,:,:,:]

                    save_name=save_address+all_data_name[i]+'_'+str(j)+'.png'

                    im=Image.fromarray(ds_nor_layer,mode='RGB')#mode='RGB'
                    im.save(save_name)
                if Main_Dimens==1:
                    ds_nor_layer=ds_nor[:,j,:,:]

                    save_name=save_address+all_data_name[i]+'_'+str(j)+'.png'

                    im=Image.fromarray(ds_nor_layer,mode='RGB')#mode='RGB'
                    im.save(save_name)
                if Main_Dimens==2:
                    ds_nor_layer=ds_nor[:,:,j,:]

                    save_name=save_address+all_data_name[i]+'_'+str(j)+'.png'

                    im=Image.fromarray(ds_nor_layer,mode='RGB')#mode='RGB'
                    im.save(save_name)
        print(f'{all_data_name[i]} done.\n\n')

def get_input_info():
    global Channel_Mode,Main_Dimens
    #Channel_Mode=channel_list.get(ANCHOR)
    if Channel_variable.get()==1:
        Channel_Mode=int(1)
    if Channel_variable.get()==3:
        Channel_Mode=int(3)

    if Dimens_variable.get()==0:
        Main_Dimens=int(0)
    if Dimens_variable.get()==1:
        Main_Dimens=int(1)
    if Dimens_variable.get()==2:
        Main_Dimens=int(2)
    #Main_Dimens=dimens_list.get(ANCHOR)
    print(Channel_Mode," mode, ",Main_Dimens," is dimension feature.")
    win.destroy()

def directory_in():
    # get a directory path by user
    global address
    address=filedialog.askdirectory(initialdir=r"C:",
                                    title="Select Dicom Input Folder Directory:")
    print("Your input folder path is: ",address)
    input_path=tkinter.Label(win,text=address,font=('italic 14'))
    input_path.grid(row=0,column=2)

def directory_out():
    # get a directory path by user
    global save_address
    save_address=filedialog.askdirectory(initialdir=r"C:",
                                    title="Select Dicom Output Folder Directory:")
    print("Your output folder path is: ",save_address)
    output_path=tkinter.Label(win,text=save_address,font=('italic 14'))
    output_path.grid(row=1,column=2)

#if __name__ == '__main__':
win = tkinter.Tk()
win.title("Dicom to PNG converter (written by bb)")
win.geometry("600x200+200+50")#change size----------------------------------!

Channel_variable=tkinter.IntVar()
Channel_variable.set(2)
Dimens_variable=tkinter.IntVar()
Dimens_variable.set(4)

input_path_label = tkinter.Label(win,
                      text="Input Dicom Files path:     ",
                      font=("italic 14", 10),
                      justify="left",
                      anchor="center")
input_path_label.grid(row=0,column=0)
dialog_btn1 = tkinter.Button(win, text='Select Folder', command = directory_in)
dialog_btn1.grid(row=0,column=1)

output_path_label = tkinter.Label(win,
                      text="Output Dicom Files path:     ",
                      font=("italic 14", 10),
                      justify="left",
                      anchor="center")
output_path_label.grid(row=1,column=0)
dialog_btn2 = tkinter.Button(win, text='Select Folder', command = directory_out)
dialog_btn2.grid(row=1,column=1)

#channel_list = tkinter.Listbox(win)
#channel_list.grid(row=2,column=1)
#channel_list.insert(1, 'Grey')
#channel_list.insert(3, 'RGB')
#dimens_list = tkinter.Listbox(win)
#dimens_list.grid(row=2,column=2)
#dimens_list.insert(0, '1')
#dimens_list.insert(1, '2')
#dimens_list.insert(2, '3')
channel_label = tkinter.Label(win,
                      text="Channel Type:",
                      font=("italic 14", 10),
                      justify="left",
                      anchor="center")
channel_label.grid(row=2,column=0)
channel_entry1=tkinter.Radiobutton(win, text="Grey", variable=Channel_variable, value=1)
channel_entry2=tkinter.Radiobutton(win, text="RGB", variable=Channel_variable, value=3)
channel_entry1.grid(row=2,column=1)
channel_entry2.grid(row=2,column=2)

dimens_label = tkinter.Label(win,
                      text="Dimension Type:",
                      font=("italic 14", 10),
                      justify="left",
                      anchor="center")
dimens_label.grid(row=3,column=0)
dimens_entry1=tkinter.Radiobutton(win, text="1", variable=Dimens_variable, value=0)
dimens_entry2=tkinter.Radiobutton(win, text="2", variable=Dimens_variable, value=1)
dimens_entry3=tkinter.Radiobutton(win, text="3", variable=Dimens_variable, value=2)
dimens_entry1.grid(row=3,column=1)
dimens_entry2.grid(row=3,column=2)
dimens_entry3.grid(row=3,column=3)

button = tkinter.Button(win, text="Confirm", command=get_input_info)
button.grid(row=5,column=1)
win.mainloop()
if address != "" and save_address != "":
    print("Path directing...")
    DICOM_to_PNG(address+'/',save_address+'/')
    print("All Converted.")
    os.system ("pause")
else:
    print("Incorrect folder path, program ends. Please restart the program and select the legal path.")
    os.system ("pause")


#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os

def cmd_get_dbg():
  return eval(input("q - quit\nr - restart\n"))

def main():
    server.my_serv.start()
    try:
        while True:
            c = input("q - quit\nr - restart\n")
            if c:
              print(c)
            if c == "q":
                break;
            if c == "r":
                server.my_serv.restart()
    except KeyboardInterrupt:
        print("\nKeyboardInterrupt")
        pass

def __log(fmt, data):
    print(fmt % data)

if __name__ == "__main__":
  mac = os.getenv('TIVIBG_MAC', False)
  if not mac:
    sys.exit('TIVIBG_MAC is not set\nTIVIBG_MAC=aa:bb:cc:dd:ee:ff %s' % (sys.argv[0]))
  import server
  server.log_cb = __log
  server.my_serv = server.serv(host=os.uname()[1])

  main()

  del server.my_serv


# coding=utf-8
import sys
import threading

import Pyro4
import Pyro4.naming

from plot import Ploter

with Pyro4.core.Daemon() as daemon:
  class NameServer(threading.Thread):
    def __init__(self, hostname, hmac=None):
      super(NameServer, self).__init__()
      self.setDaemon(True)
      self.hostname = hostname
      self.hmac = hmac
      self.started = threading.Event()

    def run(self):
      self.uri, self.ns_daemon, self.bc_server = Pyro4.naming.startNS(self.hostname, hmac=self.hmac)
      self.started.set()
      if self.bc_server:
        self.bc_server.runInThread()
      self.ns_daemon.requestLoop()

  def startNameServer(host, hmac=None):
    ns = NameServer(host, hmac=hmac)
    ns.start()
    ns.started.wait()
    return ns

  startNameServer("localhost")
  ns = Pyro4.naming.locateNS()

  obj = Ploter()
  uri = daemon.register(obj)
  ns.register("space.shouqianshi.utils.ploter", uri)

  print("server started")

  daemon.requestLoop()


from hypothesis import given
from hypothesis.strategies import text, integers, lists

from pymonet.utils import \
    identity,\
    increase,\
    compose,\
    eq,\
    pipe,\
    curried_map as map,\
    curried_filter as filter,\
    find

@given(text(), integers())
def test_identity_should_return_first_argument(text, integer):
    assert identity(text) is text
    assert identity(integer) is integer

@given(integers())
def test_compose_should_applied_function_on_value_and_return_it_result(integer):
    assert compose(integer, increase) == integer + 1
    assert compose(integer, increase, increase) == integer + 2
    assert compose(integer, increase, increase, increase) == integer + 3

@given(integers())
def test_compose_should_appield_functions_from_last_to_first(integer):
    assert compose(integer, increase, lambda value: value * 2) == (integer * 2) + 1

@given(text())
def test_eq(text):
    assert eq(text, text)
    assert eq(text)(text)

def test_compose_with_collections():
    def is_odd(value): return value % 2 == 0

    assert compose(
        list(range(10)),
        map(increase),
        filter(is_odd)
    ) == [1, 3, 5, 7, 9]

    assert compose(
        list(range(10)),
        filter(is_odd),
        map(increase)
    ) == [2, 4, 6, 8, 10]

@given(integers())
def test_pipe_should_appield_functions_from_first_to_last(integer):
    assert pipe(integer, increase, lambda value: value * 2) == (integer + 1) * 2

@given(
    lists(elements=integers(), min_size=1, max_size=1000, unique=True),
    integers()
)
def test_find_should_return_none_when_item_is_not_in_collection_otherwise_should_return_item(lst, integer):
    lst_copy = []
    lst_copy.extend(lst)
    lst_copy.append(integer)

    assert find(lst_copy, eq(integer)) == integer
    assert find(lst[1:], eq(lst[0])) is None


#!/usr/bin/python3

# 类定义
class people:
    # 定义基本属性
    name = ''
    age = 0
    # 定义私有属性，私有属性在类外部无法直接访问
    __weight = 0
    # 定制构造方法
    def __init__(self, n, a, w):
        self.name = n
        self.age = a
        self.__weight = w

    def speak(self):
        print("%s say I am %d years old" %(self.name, self.age))

p = people('Runoob', 10, 30)
p.speak()


import torch
import torch.nn as nn
import math

from typing import Optional

class PointWiseLinear(nn.Module):
    """
        Point-wise linear layer.
        This module computes a a separate linear projection for each point in the input.
    """
    def __init__(self,
                  in_features: int,
                   out_features: int,
                     num_points: int,
                       bias: Optional[bool] = True,
                          ) -> None:
        super(PointWiseLinear, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.num_points = num_points
        self.weight = nn.Parameter(torch.Tensor(num_points, out_features, in_features))
        if bias:
            self.bias = nn.Parameter(torch.Tensor(num_points, out_features))
        else:
            self.bias = None
        self.reset_parameters()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
            Forward function for the point-wise linear layer.

            Arguments:
                x (torch.Tensor): batched input tensor. Additional dimensions are squeezed and reshaped. [batch_size,..., num_points, in_features]
        """
        shape = x.shape
        x = x.view(-1, self.num_points, self.in_features)
        x = torch.einsum('njk,bnk->bnj', self.weight, x)
        if self.bias is not None:
            x = x + self.bias.unsqueeze(0)
        x = x.reshape(*shape[:-1], self.out_features)
        return x

    def reset_parameters(self) -> None:
        # Setting a=sqrt(5) in kaiming_uniform is the same as initializing with
        # uniform(-1/sqrt(in_features), 1/sqrt(in_features)). For details, see
        # https://github.com/pytorch/pytorch/issues/57109
        nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
        if self.bias is not None:
            fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight)
            bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
            nn.init.uniform_(self.bias, -bound, bound)

    def extra_repr(self) -> str:
        return f'in_features={self.in_features}, out_features={self.out_features}, num_points={self.num_points} bias={self.bias is not None}'


import numpy as np
import random

def sort_doors():
	lista = ['goat', 'goat', 'car']
	random.shuffle(lista) #Se desorganiza la lista
	return lista

def choose_door():
	return int(np.random.choice(3,1)) #Se escoje un numero al azar entre 0 y 2

def reveal_door(lista, choice):
	for i in range(len(lista)):
		if(i != choice):
			if lista[i] == 'goat':
				lista[i] = "GOAT_MONTY"
				break
	return lista

def finish_game(lista, choice, change):
	if not change:
		return lista[choice]
	else:
		for i in range(len(lista)):
			if i!=choice and lista[i]!='GOAT_MONTY':
				return lista[i] #Se escoge la opcion diferente

cambia = 0
no_cambia = 0
#Escenario en el que cambia de seleccion
for i in range(100):
	lista_t = sort_doors()
	puerta = choose_door()
	lista_t = reveal_door(lista_t, puerta)
	ans = finish_game(lista_t, puerta, True)
	if ans == 'car':
		cambia += 1

#Escenario en el que no cambia
for i in range(100):
	lista_f = sort_doors()
	puerta = choose_door()
	lista_f = reveal_door(lista_t, puerta)
	ans = finish_game(lista_t, puerta, False)
	if ans == 'car':
		no_cambia += 1

print("La probabilidad de obtener el premio cuando no hubo cambio es: "+ str(no_cambia/100.0))
print("La probabilidad de obtener el premio cuando si hubo cambio es: "+ str(cambia/100.0))


class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        ans = []
        for index, i in enumerate(nums):
            if index + 2 >= len(nums):
                break
            if index >= 1 and i == nums[index - 1]:
                continue

            left, right = index + 1, len(nums) - 1
            while left < right:
                if nums[left] + nums[right] == -i:
                    ans.append([i, nums[left], nums[right]])
                    while left < right and nums[left + 1] == nums[left]:
                        left += 1
                    left += 1
                elif nums[left] + nums[right] < -i:
                    left += 1
                else:
                    right -= 1

        return ans


from management.product_handler import get_product_by_id

def calculate_tab(account):
    products_consumed = []
    for i, product in enumerate(account):
        product_consumed = get_product_by_id(product["_id"])
        product_consumed["amount"] = account[i]["amount"]
        products_consumed.append(product_consumed)
    prices = sum([product["price"] * product["amount"] for product in products_consumed])
    subtotal = {

        "subtotal": f"${round(prices, 2)}"

    }
    return subtotal


def print_edge(temp_matrix, left_up_x, left_up_y, right_down_x, right_down_y):
    if left_up_x == right_down_x:
        for i in range(left_up_y, right_down_y + 1):
            print(temp_matrix[left_up_x][i], end=' ')
    elif left_up_y == right_down_y:
        for i in range(left_up_x, right_down_x):
            print(temp_matrix[i][left_up_y], end=' ')
    else:
        cur_x = left_up_x
        cur_y = left_up_y
        while cur_y != right_down_y:
            print(temp_matrix[left_up_x][cur_y], end=' ')
            cur_y += 1
        while cur_x != right_down_x:
            print(temp_matrix[cur_x][right_down_y], end=' ')
            cur_x += 1
        while cur_y != left_up_y:
            print(temp_matrix[right_down_x][cur_y], end=' ')
            cur_y -= 1
        while cur_x != left_up_x:
            print(temp_matrix[cur_x][left_up_y], end=' ')
            cur_x -= 1

def spiral_prider_print(input_matrix):
    left_up_x = 0
    left_up_y = 0
    right_down_x = len(input_matrix[0]) - 1
    right_down_y = len(input_matrix) - 1
    while left_up_x <= right_down_x and left_up_y < right_down_y:
        print_edge(input_matrix, left_up_x, left_up_y, right_down_x, right_down_y)
        left_up_x += 1
        left_up_y += 1
        right_down_x -= 1
        right_down_y -= 1

if __name__ == '__main__':
    matrix = [[1,  2,  3,  4],
              [5,  6,  7,  8],
              [9,  10, 11, 12],
              [13, 14, 15, 16]]
    spiral_prider_print(matrix)

算法与数据结构之美/宏观调度/Spiral prider print matrix/code.py


import os
import sys
from datetime import datetime,timedelta
from proc_satellite_class import Satellite_Process

class Estimate(Satellite_Process):

    def __init__(self):
        super().__init__()
        self.zmin_refs = None
        self.zmax_refs = None
        self.zstp_refs = None
        self.zmin_nrefs = None
        self.zmax_nrefs = None
        self.zstp_nrefs = None
        self.zmin_inds = None
        self.zmax_inds = None
        self.zstp_inds = None
        self.ax1_zmin = None
        self.ax1_zmax = None
        self.ax1_zstp = None
        self._freeze()

    def run(self):
        # Start process
        super().run()

        # Check files/folders
        start_dtim = datetime.strptime(self.start_date,self.date_fmt)
        end_dtim = datetime.strptime(self.end_date,self.date_fmt)
        first_dtim = datetime.strptime(self.first_date,self.date_fmt)
        last_dtim = datetime.strptime(self.last_date,self.date_fmt)
        if not os.path.exists(self.values['gis_fnam']):
            raise IOError('{}: error, no such file >>> {}'.format(self.proc_name,self.values['gis_fnam']))
        if not os.path.exists(self.values['event_fnam']):
            raise IOError('{}: error, no such file >>> {}'.format(self.proc_name,self.values['event_fnam']))
        if not os.path.exists(self.values['pm_fnam']):
            raise IOError('{}: error, no such file >>> {}'.format(self.proc_name,self.values['pm_fnam']))
        trg_bnam = '{:%Y%m%d}_{:%Y%m%d}'.format(start_dtim,end_dtim)
        wrk_dir = os.path.join(self.s2_analysis,self.proc_name)
        if not os.path.exists(wrk_dir):
            os.makedirs(wrk_dir)
        if not os.path.isdir(wrk_dir):
            raise ValueError('{}: error, no such folder >>> {}'.format(self.proc_name,wrk_dir))

        # Select data
        if 'Specific' in self.values['data_select']:
            spec_dtim = datetime.strptime(self.values['spec_date'],self.date_fmt)
            ystr = '{:%Y}'.format(spec_dtim)
            if 'Non-interpolated' in self.values['data_select']:
                if self.values['atcor_flag']:
                    spec_fnam = os.path.join(self.s2_data,'atcor',ystr,'{:%Y%m%d}_atcor.npz'.format(spec_dtim))
                    spec_gnam = os.path.join(self.s2_data,'atcor',ystr,'{:%Y%m%d}_factor.npz'.format(spec_dtim))
                else:
                    spec_fnam = os.path.join(self.s2_data,'parcel',ystr,'{:%Y%m%d}_parcel.npz'.format(spec_dtim))
            else:
                spec_fnam = os.path.join(self.s2_data,'interp',ystr,'{:%Y%m%d}_interp.npz'.format(spec_dtim))
            if not os.path.exists(spec_fnam):
                raise IOError('Error, no such file >>> {}'.format(spec_fnam))
            ax1_title = '{}: {:%Y%m%d}'.format(self.values['data_select'],spec_dtim)
        else:
            select_csv = os.path.join(wrk_dir,'{}_select.csv'.format(trg_bnam))
            select_shp = os.path.join(wrk_dir,'{}_select.shp'.format(trg_bnam))
            select_pdf = os.path.join(wrk_dir,'{}_select.pdf'.format(trg_bnam))
            command = self.python_path
            command += ' "{}"'.format(os.path.join(self.scr_dir,'sentinel2_select_data.py'))
            command += ' --shp_fnam "{}"'.format(self.values['gis_fnam'])
            command += ' --phenology "{}"'.format(self.values['event_fnam'])
            if 'Age' in self.values['data_select']:
                command += ' --param Age'
                command += ' --offset {}'.format(self.values['age_value'])
                ax1_title = '{}: {:.1f}'.format(self.values['data_select'],self.values['age_value'])
            elif 'Harvesting' in self.values['data_select']:
                command += ' --param harvest_d'
                command += ' --offset {}'.format(self.values['harvest_value'])
                ax1_title = '{}: {:.1f}'.format(self.values['data_select'],self.values['harvest_value'])
            elif 'Assessment' in self.values['data_select']:
                command += ' --param assess_d'
                command += ' --offset {}'.format(self.values['assess_value'])
                ax1_title = '{}: {:.1f}'.format(self.values['data_select'],self.values['assess_value'])
            elif 'Heading' in self.values['data_select']:
                command += ' --param head_d'
                command += ' --offset {}'.format(self.values['head_value'])
                ax1_title = '{}: {:.1f}'.format(self.values['data_select'],self.values['head_value'])
            elif 'Peak' in self.values['data_select']:
                command += ' --param peak_d'
                command += ' --offset {}'.format(self.values['peak_value'])
                ax1_title = '{}: {:.1f}'.format(self.values['data_select'],self.values['peak_value'])
            elif 'Planting' in self.values['data_select']:
                command += ' --param plant_d'
                command += ' --offset {}'.format(self.values['plant_value'])
                ax1_title = '{}: {:.1f}'.format(self.values['data_select'],self.values['plant_value'])
            else:
                raise ValueError('{}: error, unknown data selection >>> {}'.format(self.proc_name,self.values['data_select']))
            command += ' --inpdir "{}"'.format(os.path.join(self.s2_data,'interp'))
            command += ' --tendir "{}"'.format(os.path.join(self.s2_data,'tentative_interp'))
            command += ' --out_csv "{}"'.format(select_csv)
            command += ' --out_shp "{}"'.format(select_shp)
            command += ' --fignam "{}"'.format(select_pdf)
            for value in self.zmin_refs:
                command += ' --ax1_zmin="{}"'.format(value)
            for value in self.zmin_nrefs:
                command += ' --ax1_zmin="{}"'.format(value)
            for value in self.zmin_inds:
                command += ' --ax1_zmin="{}"'.format(value)
            for value in self.zmax_refs:
                command += ' --ax1_zmax="{}"'.format(value)
            for value in self.zmax_nrefs:
                command += ' --ax1_zmax="{}"'.format(value)
            for value in self.zmax_inds:
                command += ' --ax1_zmax="{}"'.format(value)
            for value in self.zstp_refs:
                command += ' --ax1_zstp="{}"'.format(value)
            for value in self.zstp_nrefs:
                command += ' --ax1_zstp="{}"'.format(value)
            for value in self.zstp_inds:
                command += ' --ax1_zstp="{}"'.format(value)
            command += ' --ax1_title "{}"'.format(ax1_title)
            command += ' --use_index'
            command += ' --debug'
            command += ' --batch'
            self.run_command(command,message='<<< Select data >>>')

        # Estimate plot-mean
        estimate_csv = os.path.join(wrk_dir,'{}_estimate.csv'.format(trg_bnam))
        estimate_shp = os.path.join(wrk_dir,'{}_estimate.shp'.format(trg_bnam))
        estimate_pdf = os.path.join(wrk_dir,'{}_estimate.pdf'.format(trg_bnam))
        command = self.python_path
        command += ' "{}"'.format(os.path.join(self.scr_dir,'sentinel2_score_estimate.py'))
        command += ' --form_fnam "{}"'.format(self.values['pm_fnam'])
        command += ' --inp_shp "{}"'.format(self.values['gis_fnam'])
        if 'Specific' in self.values['data_select']:
            command += ' --inp_fnam "{}"'.format(spec_fnam)
            if 'Non-interpolated' in self.values['data_select']:
                command += ' --cr_band {}'.format(self.values['cloud_band'])
                list_labels = [s.split()[0] for s in self.list_labels['cloud_thr']]
                ithr = list_labels.index('Reflectance')
                command += ' --cthr {}'.format(self.values['cloud_thr'][ithr])
                if self.values['atcor_flag']:
                    command += ' --fact_fnam "{}"'.format(spec_gnam)
                    ithr = list_labels.index('Correlation')
                    command += ' --rthr {}'.format(self.values['cloud_thr'][ithr])
        else:
            command += ' --inp_csv "{}"'.format(select_csv)
        command += ' --out_shp "{}"'.format(estimate_shp)
        command += ' --out_csv "{}"'.format(estimate_csv)
        for param,flag in zip(self.list_labels['y_params'],self.values['y_params']):
            if flag:
                command += ' --y_param {}'.format(param)
                command += ' --y_number {}'.format(self.values['pm_number'])
        command += ' --fignam "{}"'.format(estimate_pdf)
        for value,flag in zip(self.ax1_zmin,self.values['y_params']):
            if flag:
                command += ' --ax1_zmin="{}"'.format(value)
        for value,flag in zip(self.ax1_zmax,self.values['y_params']):
            if flag:
                command += ' --ax1_zmax="{}"'.format(value)
        for value,flag in zip(self.ax1_zstp,self.values['y_params']):
            if flag:
                command += ' --ax1_zstp="{}"'.format(value)
        command += ' --ax1_title "{}"'.format(ax1_title)
        command += ' --use_index'
        command += ' --debug'
        command += ' --batch'
        self.run_command(command,message='<<< Estimate plot-mean >>>')

        # Finish process
        super().finish()
        return