import numpy as np
from numpy.linalg import inv,svd
import math

class ML_ppca(object):

    def __init__(self,X,dim_q=2,sigma=1.0):
        """Initialization of the class ML_ppca for the Maximum Likelihood method
        Parameter
        ---------
        X: array-like (N,D)
            data points
        sigma: int
            covariance
        dim_q: int
            dimension of the latent space
        """

        self.X = X
        self.dim_q =dim_q
        self.prev_sigma = sigma

    def fit(self):
        """
        Method for fitting using the ML.
        Compute the mean of the obsvervable, the eigen values and the eigen vectors from the SVD decomposition,
        the weighting matrix W(D,q) that represent the mapping of the lating space to that of the principal subspace,
        the variance lost sigma in the projection over the dimension decreased.

        """

        D = self.X.shape[1]
        self.mu = np.mean(self.X,axis=0)[:,np.newaxis]
        [U,S,V] =  svd(self.X.T - self.mu)
        eig_val = S[:self.dim_q]**2
        self.W = U[:,:self.dim_q].dot(np.sqrt(np.diag(np.maximum(0,eig_val -self.prev_sigma))))
        self.sigma = 1.0/(D - self.dim_q) * np.sum(eig_val[self.dim_q:])

    def transfom(self):
        """
        Method for getting the latent space of the data points.
        Compute
        Return
        ------
        z: array-like (q,N)
            data points in the latent space
        """
        m = self.W.T.dot(self.W) + self.sigma * np.eye(self.W.shape[1])
        self.z = inv(m).dot(self.W.T).dot(self.X.T - self.mu)

        return self.z

    def infer_transform(self):
        """
        Method for getting the inference data points from the latent space to the original space
        Return
        ------
        x: array-like (D,N)
            inferred data points in the original space
        """

        x = self.W.dot(self.z) + self.mu

        return x

class EM_ppca(object):
    """
    Initialization of the class EM_ppca for the Expectation-Maximization algorithm
    Parameter
    ---------
    X: array-like (N,D)
        data points
    sigma: int
        covariance
    dim_q: int
        dimension of the latent space
    """
    def __init__(self,X,dim_q=2,sigma= 1.0,max_iter=40):
        """Initialization of the class ML_ppca for the Maximum Likelihood method
        Parameter
        ---------
        X: array-like (N,D)
          data points
        sigma: int
            covariance
        dim_q: int
            dimension of the latent space
        """
        self.X =X
        self.q = dim_q
        self.sigma = sigma
        self.max_iter = max_iter

    def ell(self,w,m,mu,norm=True):
        """
        Method for computing the expected log-likelihood during the E-step
        Parameter
        ---------
        :m array-like (q,q)
            matrix related to the covariance and the mapping latent space
        :mu array-like (D,1)
            mean for each observable
        :norm bool
            Normalilsation of the LL
        Return
        ------
        ll: float
            return the value of the expected LL
        """

        ll = 0.5 * self.X.shape[0] * self.X.shape[1] * np.log(2 * math.pi*self.sigma+1e-5)

        for i in range(self.X.shape[0]):
            x_scl_i = self.X[i][:,np.newaxis] - mu
            zi = inv(m).dot(w.T).dot(x_scl_i)

            ll += 0.5 * np.trace(self.sigma*inv(m) + zi.dot(zi.T))
            ll += (2*self.sigma+1e-5)**-1 * float(x_scl_i.T.dot(x_scl_i))
            ll -= (self.sigma+1e-5)**-1 * float(zi.T.dot(w.T).dot(x_scl_i))
            ll += (2*self.sigma)**-1 * np.trace((self.sigma*inv(m)+zi.dot(zi.T)).dot(w.T).dot(w))

        ll *= -1

        if norm == True:
            ll /= float(self.X.shape[0])

        return ll

    def fit(self):
        """
        Method for computing the M-step by maximization respect with W and sigma

        """
        self.W = np.random.rand(self.X.shape[1],self.q)
        m = self.W.T.dot(self.W) + self.sigma * np.eye(self.q)
        self.mu = np.mean(self.X,axis=0)[:,np.newaxis]
        S = self.X.shape[0]**-1 * (self.X.T - self.mu).dot((self.X.T - self.mu).T)
        ll = self.ell(self.W,m,self.mu)
        #print(float(ll))
        print("Iteration 0 : LL = {:.2f}".format(ll))
        for i in range(self.max_iter):
            W_new = S.dot(self.W).dot(inv(self.sigma * np.eye(self.q) + inv(m).dot(self.W.T).dot(S).dot(self.W)))
            sigma_new = self.X.shape[1]**-1 * np.trace(S-(S).dot(self.W).dot(inv(m)).dot(W_new.T))
            m = W_new.T.dot(W_new) + sigma_new * np.eye(self.q)
            self.sigma = sigma_new
            ll = self.ell(W_new,m,self.mu)
            self.W = W_new

            print("Iteration {} : LL = {:.2f}".format(i+1,ll))

    def transform(self):
        """
        Method for getting the latent space of the data points.
        Compute
        Return
        ------
        z: array-like (q,N)
            data points in the latent space
        """
        m = self.W.T.dot(self.W) + self.sigma * np.eye(self.W.shape[1])
        self.z = inv(m).dot(self.W.T).dot(self.X.T - self.mu)

        return self.z

    def infer_transform(self):
        """
        Method for getting the inference data points from the latent space to the original space
        Return
        ------
        x: array-like (D,N)
            inferred data points in the original space
        """

        x = self.W.dot(self.z) + self.mu

        return x

class BV_ppca(object):
    def __init__(self,q=2,sigma=1.0):
        self.q = q
        self.sigma = sigma

class MV_ppca(object):
    def __init__(self,q=2,sigma=1.0):
        self.q =q
        self.sigma = sigma


import glob
import logging
import os
import re
import shutil
import zstandard as zstd

from virt_backup.exceptions import CancelledError, ImageNotFoundError, ImageFoundError
from . import (
    _AbstractBackupPackager,
    _AbstractReadBackupPackager,
    _AbstractWriteBackupPackager,
    _opened_only,
    _closed_only,
)

class _AbstractBackupPackagerZSTD(_AbstractBackupPackager):
    _mode = ""

    def __init__(self, name, path, name_prefix, compression_lvl=0, threads=0):
        super().__init__(name)

        #: Directory path to store the archives in.
        self.path = path

        #: Each file from this package will be stored as one separated archive.
        #: Their name will be prefixed by prefix_name
        self.name_prefix = name_prefix

        #: zstd_params is used by the compressor.
        self.zstd_params = zstd.ZstdCompressionParameters.from_level(
            compression_lvl, threads=threads
        )

    @property
    def complete_path(self):
        return self.path

    def archive_path(self, name):
        """
        WARNING: it does not check that the archive actually exists,
        just returns the path it should have
        """
        return os.path.join(self.path, self._gen_archive_name(name))

    def _gen_archive_name(self, filename):
        return "{}_{}.zstd".format(self.name_prefix, filename)

    def open(self):
        if not os.path.isdir(self.path):
            os.makedirs(self.path)

        self.closed = False
        return self

    @_opened_only
    def close(self):
        self.closed = True

    @_opened_only
    def list(self):
        results = []
        pattern = re.compile(r"{}_(.*)\.zstd$".format(self.name_prefix))
        for i in glob.glob(os.path.join(self.complete_path, "*.zstd")):
            m = pattern.match(os.path.basename(i))
            if m:
                results.append(m.group(1))

        return results

class ReadBackupPackagerZSTD(_AbstractReadBackupPackager, _AbstractBackupPackagerZSTD):
    _mode = "r"

    @_opened_only
    def restore(self, name, target, stop_event=None):
        if name not in self.list():
            raise ImageNotFoundError(self.archive_path(name), self.complete_path)

        if not os.path.exists(target) and target.endswith("/"):
            os.makedirs(target)
        if os.path.isdir(target):
            target = os.path.join(target, name)
        if os.path.isfile(target):
            raise ImageFoundError(target)

        buffersize = 2**20
        dctx = zstd.ZstdDecompressor()
        try:
            with open(self.archive_path(name), "rb") as ifh, open(target, "xb") as ofh:
                with dctx.stream_reader(ifh) as reader:
                    while True:
                        if stop_event and stop_event.is_set():
                            raise CancelledError()

                        data = reader.read(buffersize)
                        if not data:
                            break

                        if stop_event and stop_event.is_set():
                            raise CancelledError()
                        ofh.write(data)
        except:
            if os.path.exists(target):
                os.remove(target)
            raise

        return target

class WriteBackupPackagerZSTD(
    _AbstractWriteBackupPackager, _AbstractBackupPackagerZSTD
):
    _mode = "x"

    @_opened_only
    def add(self, src, name=None, stop_event=None):
        name = name or os.path.basename(src)
        self.log(logging.DEBUG, "Add %s into %s", src, self.archive_path(name))

        cctx = zstd.ZstdCompressor(compression_params=self.zstd_params)
        try:
            with open(src, "rb") as ifh, open(self.archive_path(name), "wb") as ofh:
                with cctx.stream_writer(ofh) as writer:
                    while True:
                        if stop_event and stop_event.is_set():
                            raise CancelledError()

                        data = ifh.read(zstd.COMPRESSION_RECOMMENDED_INPUT_SIZE)
                        if not data:
                            break

                        if stop_event and stop_event.is_set():
                            raise CancelledError()
                        writer.write(data)
        except:
            if os.path.exists(self.archive_path(name)):
                os.remove(self.archive_path(name))
            raise

        return self.archive_path(name)

    @_opened_only
    def remove(self, name):
        if name not in self.list():
            raise ImageNotFoundError(self.archive_path(name), self.complete_path)

        os.remove(self.archive_path(name))

    @_closed_only
    def remove_package(self, stop_event=None):
        if not os.path.exists(self.complete_path):
            raise FileNotFoundError(self.complete_path)

        with self:
            files = self.list()

        for i in files:
            if stop_event and stop_event.is_set():
                raise CancelledError()
            os.remove(self.archive_path(i))


import numpy as np
import win32gui, win32ui, win32con
from multiprocessing import Process, Queue, Event

class WindowCapturer:
    """
    Class for capturing a window's screenshot and retrieving screen position.
    """

    BORDER_PIXELS = 8
    """
    int: The number of border pixels to exclude from the captured window.
    """

    TITLEBAR_PIXELS = 30
    """
    int: The number of title pixels to exclude from the captured window.
    """

    def __init__(self, window_name: str, frame_queue: Queue):
        """
        Initialize the WindowCapturer instance.

        :param window_name: The partial name of the window to capture.
                            It can even be a full name, but because the Terraria window name changes every time,
                            it's recommended to use the immutable part of it.
        :type: str

        :param frame_queue: The queue for the process to store frames
        :type: Queue

        :raises Exception: If the window isn't found.
        """

        # process properties
        self._process = None
        self._stop_event = Event()
        self._frame_queue = frame_queue

        self._hwnd = self.__get_hwnd_by_partial_name(window_name)
        if not self._hwnd:
            raise Exception('Window is not found: {}'.format(window_name))

        window_rect = win32gui.GetWindowRect(self._hwnd)
        self.width = window_rect[2] - window_rect[0]
        self.height = window_rect[3] - window_rect[1]

        # window width and height with cutting borders and a title
        self.width -= (self.BORDER_PIXELS * 2)
        self.height = self.height - self.TITLEBAR_PIXELS - self.BORDER_PIXELS
        self.cropped_x = self.BORDER_PIXELS
        self.cropped_y = self.TITLEBAR_PIXELS

        self.offset_x = window_rect[0] + self.cropped_x
        self.offset_y = window_rect[1] + self.cropped_y

    # Declaring process methods
    def start(self):
        """
        Start the capturing process.
        """

        self._process = Process(target=self._run)
        self._process.start()

    def stop(self):
        """
        Stop the capturing process.
        """

        self._stop_event.set()
        self._process.terminate()

    def _run(self):
        """
        Main capturing loop.
        """
        while not self._stop_event.is_set():
            screenshot = self.__get_screenshot()
            self._frame_queue.put(screenshot)

    def get_screen_position(self, position):
        """
        Translate a pixel position on a screenshot image to a pixel position on the screen.

        WARNING: if you move the window being captured after execution is started, this will
        return incorrect coordinates, because the window position is only calculated in
        the __init__ constructor.

        :param position: The pixel position on the screenshot image (x, y).
        :type position: tuple

        :return: The translated pixel position on the screen (x, y).
        :rtype: tuple
        """

        return position[0] + self.offset_x, position[1] + self.offset_y

    def __get_screenshot(self):
        """
        Capture the window's screenshot.

        :return: The captured screenshot as a NumPy array.
        :rtype: numpy.ndarray
        """

        # get the window data
        wDC = win32gui.GetWindowDC(self._hwnd)
        dcObj = win32ui.CreateDCFromHandle(wDC)
        cDC = dcObj.CreateCompatibleDC()
        data_bit_map = win32ui.CreateBitmap()
        data_bit_map.CreateCompatibleBitmap(dcObj, self.width, self.height)
        cDC.SelectObject(data_bit_map)
        cDC.BitBlt((0, 0), (self.width, self.height), dcObj, (self.cropped_x, self.cropped_y), win32con.SRCCOPY)

        # data_bit_map.SaveBitmapFile(cDC, 'debug.bmp')
        signed_ints_array = data_bit_map.GetBitmapBits(True)
        img = np.frombuffer(signed_ints_array, dtype='uint8')
        img.shape = (self.height, self.width, 4)

        # Free Resources
        dcObj.DeleteDC()
        cDC.DeleteDC()
        win32gui.ReleaseDC(self._hwnd, wDC)
        win32gui.DeleteObject(data_bit_map.GetHandle())

        # drop the alpha channel to cv.matchTemplate() not throw an error
        # maybe it will be deleted later
        img = img[..., :3]

        img = np.ascontiguousarray(img)

        return img

    @staticmethod
    def __get_hwnd_by_partial_name(partial_name):
        """
        Get the window handle by its partial name.

        :param partial_name (str): The partial name of the window.

        :return: int: The window handle (HWND) if found, None otherwise.
        """

        hwnds = []

        def callback(hwnd, hwnd_list):
            if partial_name.lower() in win32gui.GetWindowText(hwnd).lower():
                hwnd_list.append(hwnd)
            return True

        win32gui.EnumWindows(callback, hwnds)
        return hwnds[0] if hwnds else None


from django.conf import settings
from django.conf.urls.static import static
from django.contrib.sitemaps.views import sitemap
from django.urls import path, re_path

from upapp import views
from upapp import viewsAuth
from upapp.apis import blog, employer, lever, locations, project, sendEmail, storage, tag, teachable, training, user
from upapp.sitemaps import sitemaps

apiPath = 'api/v1/'

urlpatterns = [
    # Views
    path('', views.homepage, name='index'),
    path('admin/', views.admin, name='admin'),
    path('account-settings/<int:userId>/', views.accountSettings, name='accountSettings'),
    re_path('^blog/(?P<blogId>[0-9]+)?/?$', views.blog, name='blog'),
    path('candidate-board/', views.candidateBoard, name='candidateBoard'),
    re_path('^candidateDashboard/(?P<userId>[0-9]+)?/?$', views.candidateDashboard, name='candidateDashboard'),
    path('candidateOnboard/', views.candidateOnboard, name='candidateOnboard'),
    path('contact/', views.contact, name='contact'),
    path('courses/', views.courses, name='courses'),
    path('credits/', views.credits, name='credits'),
    re_path('^employerDashboard/(?P<employerId>[0-9]+)?/?$', views.employerDashboard, name='employerDashboard'),
    path('employers/', views.employers, name='employers'),
    path('errors/', views.errors, name='errors'),
    path('jobs/', views.jobs, name='jobs'),
    re_path('^job-posting/(?P<jobId>[0-9]+)/(?P<employerId>[0-9]+)?/?$', views.jobPosting, name='jobPosting'),
    path('login-page/', views.login, name='loginPage'),
    path('privacy/', views.privacy, name='privacy'),
    path('profile/<int:profileId>/', views.profile, name='profile'),
    path('project/<int:projectId>/', views.project, name='project'),
    re_path('^projects/$', views.projects, name='projects'),
    path('sign-up/', views.signUp, name='signUp'),
    re_path('^sign-up/employer/(?P<type>[a-z]+)?/?$', views.signUpEmployer, name='signUpEmployer'),
    path('terms-of-service/', views.termsOfService, name='termsOfService'),
    re_path('^user-project/(?P<userProjectId>[0-9]+)?/?$', views.userProject, name='userProject'),

    # Sales views
    path('mentor/', views.salesMentor, name="salesMentor"),

    # APIs
    re_path(apiPath + 'account-employer/(?P<employerId>[0-9]+)?/?$', employer.EmployerView.as_view()),
    re_path(apiPath + 'account-user/(?P<userId>[0-9]+)?/?$', user.UserView.as_view()),
    re_path(apiPath + 'blog/(?P<blogId>[0-9]+)?/?$', blog.BlogPostView.as_view()),
    re_path(apiPath + 'course/(?P<courseId>[0-9]+)?/?$', training.TrainingCourseView.as_view()),
    re_path(apiPath + 'job-posting/(?P<jobId>[0-9]+)?/?$', employer.JobPostingView.as_view()),
    re_path(apiPath + 'locations/$', locations.LocationView.as_view()),
    re_path(apiPath + 'organization/$', employer.OrganizationView.as_view()),
    re_path(apiPath + 'preferences/$', user.PreferencesView.as_view()),
    re_path(apiPath + 'project/(?P<projectId>[0-9]+)?/?$', project.ProjectView.as_view()),
    re_path(apiPath + 'project-role/(?P<roleId>[0-9]+)?/?$', project.RoleView.as_view()),
    re_path(apiPath + 'project-skill/(?P<skillId>[0-9]+)?/?$', project.SkillView.as_view()),
    re_path(apiPath + 'tag/$', tag.TagView.as_view()),
    re_path(apiPath + 'user-job-application/(?P<userJobApplicationId>[0-9]+)?/?$', user.UserJobApplicationView.as_view()),
    re_path(apiPath + 'user-job-rec/$', user.UserJobSuggestions.as_view()),
    re_path(apiPath + 'user-preferences/?$', user.UserPreferenceView.as_view()),
    re_path(apiPath + 'user-profile/$', user.UserProfileView.as_view()),
    re_path(apiPath + 'user-profile/content-item/$', user.UserProfileContentItemView.as_view()),
    re_path(apiPath + 'user-profile/section/$', user.UserProfileSectionView.as_view()),
    re_path(apiPath + 'user-profile/section/content-item/$', user.UserProfileSectionContentItemView.as_view()),
    re_path(apiPath + 'user-project/(?P<userProjectId>[0-9]+)?/?$', user.UserProjectView.as_view()),
    re_path(apiPath + 'user-project/status/?$', user.UserProjectStatusView.as_view()),
    re_path(apiPath + 'user-project-evaluation/$', employer.UserProjectEvaluationView.as_view()),
    re_path(apiPath + 'user-file/$', user.UserFileView.as_view()),
    re_path(apiPath + 'user-image/$', user.UserImageView.as_view()),
    re_path(apiPath + 'user-video/$', user.UserVideoView.as_view()),
    re_path(apiPath + 'waitlist/$', user.WaitlistView.as_view()),

    # Email
    path(apiPath + 'email/', sendEmail.EmailView.as_view()),

    # Authentication
    path(apiPath + 'login/', viewsAuth.LoginView.as_view()),
    path(apiPath + 'logout/', viewsAuth.LogoutView.as_view()),
    path(apiPath + 'setPassword/', viewsAuth.SetPasswordView.as_view()),
    re_path('password-reset-email/(?P<uidb64>[\S]+)?/(?P<token>[\S]+)?/$', viewsAuth.PasswordResetView.as_view(template_name='passwordReset.html'), name='passwordReset'),
    path(apiPath + 'password-reset-generate/', viewsAuth.PasswordResetGenerateView.as_view(), name='passwordResetSend'),
    path('password-reset-complete/', viewsAuth.LoginPageView.as_view(template_name='login.html'), name='password-reset-complete'),
    path('login/', viewsAuth.LoginPageView.as_view(template_name='login.html'), name='login'),

    # Lever
    re_path('^integrate/?$', lever.leverIntegrate, name='leverIntegrate'),

    re_path(f'^{apiPath}lever/logout/(?P<employerId>[0-9]+)?/?$', lever.LeverLogOut.as_view()),
    re_path(f'^{apiPath}lever/opportunities/(?P<employerId>[0-9]+)?/?$', lever.LeverOpportunities.as_view()),
    re_path(f'^{apiPath}lever/postings/(?P<employerId>[0-9]+)?/?$', lever.LeverPostings.as_view()),
    re_path(f'^{apiPath}lever/stages/(?P<employerId>[0-9]+)?/?$', lever.LeverStages.as_view()),
    re_path(f'^{apiPath}lever/users/(?P<employerId>[0-9]+)?/?$', lever.LeverUsers.as_view()),

    re_path(f'^{apiPath}lever/change/stage-change/(?P<employerId>[0-9]+)?/?$', lever.LeverChangeStage.as_view()),
    re_path(f'^{apiPath}lever/change/archive/(?P<employerId>[0-9]+)?/?$', lever.LeverArchive.as_view()),
    re_path(f'^{apiPath}lever/change/hire/(?P<employerId>[0-9]+)?/?$', lever.LeverHired.as_view()),
    re_path(f'^{apiPath}lever/change/delete/(?P<employerId>[0-9]+)?/?$', lever.LeverDeleted.as_view()),
    re_path(f'^{apiPath}lever/config/(?P<employerId>[0-9]+)?/?$', lever.LeverConfig.as_view()),

    # Teachable
    re_path(f'^{apiPath}teachable/enroll/?$', teachable.TeachableEnrolled.as_view()),
    re_path(f'^{apiPath}teachable/progress/?$', teachable.TeachableCourseProgress.as_view()),

    # Storage
    path(apiPath + 'user-storage/', storage.UserStorageView.as_view()),

    # Sitemap
    path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap')
]

if settings.USE_LOCAL:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


# -*- coding: utf-8 -*-
from drf_yasg.utils import swagger_auto_schema
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.views import APIView

from gcloud.contrib.function.models import FunctionTask
from gcloud.contrib.function.serializers import FunctionTaskClaimantTransferRequestSerializer, \
    FunctionTaskClaimantTransferResponse
from gcloud.core.api_adapter.user_role import is_user_role
from gcloud.iam_auth import IAMMeta

class FunctionTaskClaimantTransferView(APIView):

    @swagger_auto_schema(
        method="POST", operation_summary="职能转交", request_body=FunctionTaskClaimantTransferRequestSerializer,
        responses={200: FunctionTaskClaimantTransferResponse},
    )
    @action(methods=["POST"], detail=False)
    def post(self, request):
        # 获取用户名鉴权是否拥有职能化权限
        username = request.user.username
        if not is_user_role(username, IAMMeta.FUNCTION_VIEW_ACTION):
            return Response({"result": False, "message": "没有查看职能化任务权限"})

        # 获取请求参数并校验
        serializer = FunctionTaskClaimantTransferRequestSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 查询传进来的id职能化任务是否有效
        serializer_data = serializer.data
        function_task_query = FunctionTask.objects.filter(id=serializer_data["id"]).values("claimant")
        if not function_task_query.count():
            return Response({"result": False, "message": "该id查询不到职能化任务"})

        # 查询当前任务是否有认领人判断是否已认领,并且请求的用户是否是认领人
        claimant = function_task_query.first().get("claimant")
        if not claimant:
            return Response({"result": False, "message": "查询不到该职能化任务认领人"})
        elif claimant != username:
            return Response({"result": False, "message": "非该职能化任务认领人无法转交"})

        # 修改并返回结果
        FunctionTask.objects.filter(id=serializer_data["id"]).update(claimant=serializer_data["claimant"])
        return Response({"result": True, "data": None})


import os
import glob
import openpyxl
# 创建新的工作簿
new_workbook = openpyxl.Workbook()
new_sheet = new_workbook.active
# 遍历Ptest文件夹下的所有excel文件
for file_path in glob.glob("D:/Ptest/*.xlsx"):
    # 打开excel文件
    workbook = openpyxl.load_workbook(file_path)
    # 获取sheet1
    sheet = workbook["Sheet1"]
    # 获取A1和A2单元格的数据
    a1_data = sheet["A1"].value
    a2_data = sheet["A2"].value
    # 将数据添加到新的工作簿中
    new_sheet.append([a1_data, a2_data])
# 保存新的工作簿
new_workbook.save("D:/Ptest/summary.xlsx")


from django.urls import path

from .views import (
    ToDoItemsListView,
    ToDoItemCreateView,
    ToDoItemDeleteView,
    ToDoItemToggleView,
)

app_name = "todo-list"

urlpatterns = [
    path("", ToDoItemsListView.as_view(), name="items-list"),
    path("create/", ToDoItemCreateView.as_view(), name="create-item"),
    path("<int:pk>/confirm-delete/", ToDoItemDeleteView.as_view(), name="delete-item"),
    path("<int:pk>/toggle/", ToDoItemToggleView.as_view(), name="toggle-item"),
]


from Classes.Login import Login

import json
import time

# Instanciando massa de dados
with open('fixtures/MassaDeDados/LoginPessoal.json') as f:
  data = json.load(f)

Login.abrir_pagina()
Login.click_button_sign_in()
Login.preencher_email(data['email'])
Login.preencher_senha(data['senha'])
Login.click_button_register()
Login.validar_nome_usuario()


#6.4
import numpy as np
import matplotlib.pyplot as plt

t = 0.03
kappa = 1
L = 1
x = np.linspace(-1.5, 1.5, 100)

def TG(x, n, t, kappa):
    x0 = n*L
    output = np.empty(len(x))
    for i in range(len(x)):
        output[i] = exp(-((x[i]-x0)**2) / (4*kappa*t)) / (((2*kappa*t)**(1/2)) * (2*np.pi)**(1/2))
    return output

negone = -TG(x, -1, t, kappa)
zero = TG(x, 0, t, kappa)
one = -TG(x, 1, t, kappa)
yzero = np.zeros(100)

plt.figure(1)
plt.plot(x, yzero, ls='--')
plt.plot(x, zero)
plt.ylim([-2, 2])
plt.plot(x, negone+one, ls='--')
plt.xlabel('x/L')
plt.ylabel('T(x,t)')

plt.figure(2)
plt.vlines(-0.5, -3, 3, ls='--')
plt.vlines(0.5, -3, 3, ls='--')
plt.ylim([-2, 2])
plt.plot(x, zero+negone+one)


from dateutil import parser
import datetime
import random
import numpy as np

from torch.utils.data import DataLoader, Dataset

from constants import *
from .preprocessing import *
from utils import *

random.seed(448)

# Define column names
OHLC = ['Open', 'High', 'Low', 'Close']

def date_to_frac_minute(row):
    t = row.name
    return t.hour * 60 + t.minute / 1440

class SingleFXDatasetBase(Dataset):

    def __init__(self, days, logger, data_args):
        self.days = days
        self.logger = logger
        self.data_args = data_args

        self.api = CandleDataAPI.get_DataAPI(data_args.candle_interval)
        self.candle_interval = datetime.timedelta(seconds=data_args.candle_interval)

        index = 0
        self.day_index_range = []
        for d in self.days:
            day_index_start = index
            day_hour_start = DAY_HOUR_LOOKUP[d][0]
            day_hour_end = DAY_HOUR_LOOKUP[d][1]

            num_hours = day_hour_end - day_hour_start
            num_candles = int(num_hours * 3600 / data_args.candle_interval)
            index_range = (day_index_start, num_candles, d, day_hour_start)
            self.day_index_range.append(index_range)
            index += num_candles
        self.total_len = index

    def __len__(self):
        return self.total_len

    def _retry(self, message):
        self.logger.log_stdout(message, level=LOG_DEBUG)
        return self.getitem(random.randint(0, len(self) - 1))

    def getitem(self, index):

        day = None
        offset = None
        day_hour_start = None
        for day_range in self.day_index_range:
            if index >= day_range[0] and index < day_range[0] + day_range[1]:
                day = day_range[2]
                offset = index - day_range[0]
                day_hour_start = day_range[3]
                break

        day_datetime = parser.parse(day, dayfirst=False)
        start_timedelta = datetime.timedelta(hours=day_hour_start,
                                             seconds=offset * self.data_args.candle_interval,
                                             )
        slot_start = day_datetime + start_timedelta
        slot_end = slot_start + datetime.timedelta(seconds=self.data_args.num_candles * self.data_args.candle_interval)
        # self.data_args.num_candles

        if slot_start.day != slot_end.day:
            return self._retry(f'Index[{index}] ({slot_start}) is too close to the end')

        all_features = []
        all_targets = []
        pair = self.data_args.currency_pair
        for i in TRADING_LP:
            try:
                feature = self.api.get(pair=pair,
                                       lp_idx=i,
                                       start_time=slot_start,
                                       length=self.data_args.num_candles,
                                       verbose=self.logger.log_level <= LOG_DEBUG)
                target = self.api.get(pair=pair,
                                      lp_idx=i,
                                      start_time=slot_end,
                                      length=1,
                                      verbose=self.logger.log_level <= LOG_DEBUG)
            except IndexError:
                return self._retry(f'Index[{index}] ({slot_start}) is too close to the end')

            # ol skips keyword volume
            # Should be ['Close', 'High', 'Low', 'Open', 'Volume']
            # Note that this way we actually have no volume information
            sorted_keys = sorted(feature['candle_bids'].keys())
            for k in sorted_keys:
                if 'ol' not in k:
                    all_features.append(feature['candle_bids'][k])
                else:
                    all_features.append(feature['candle_bids'][k] / 1000000)
            for k in sorted_keys:
                if 'ol' not in k:
                    all_features.append(feature['candle_asks'][k])
                else:
                    all_features.append(feature['candle_asks'][k] / 1000000)

            assert len(target['candle_bids']['Close']) == 1

            target_data = (target['candle_bids']['Close'][0], target['candle_bids']['High'][0], target['candle_bids']['Low'][0],
                           target['candle_asks']['Close'][0], target['candle_asks']['High'][0], target['candle_asks']['Low'][0])
            all_targets.append(target_data)
            # all_targets.append(target['candle_asks']['Close'][0])

            assert len(all_features) == 2 * len(TRADING_LP) * 5 # close high low open volume

        # actual_target = np.mean(all_targets)

        return np.array(all_features), all_targets

class SingleFXDatasetRegression(SingleFXDatasetBase):

    def __init__(self, days, logger, data_args):
        super(SingleFXDatasetRegression, self).__init__(days, logger, data_args)

    def __getitem__(self, index):
        all_features, all_targets =  super().getitem(index)

        # Use mean of close as '1'
        cur_sum = 0
        for i in range(0, len(all_features), 5):
            cur_sum += all_features[i][-1]
        avg_last = cur_sum / len(range(0, len(all_features), 5))

        # For regressuion let's take the mean of close of bid and asks (num_lp * 2)
        cur_sum = 0
        for lp in range(len(all_targets)):
            cur_sum += all_targets[lp][0] + all_targets[lp][3]
        target = cur_sum / 2 / len(all_targets)

        all_features = all_features / avg_last
        target = target / avg_last
        return all_features, target

class SingleFXDatasetBinaryClassification(SingleFXDatasetBase):

    def __init__(self, days, logger, data_args):
        super(SingleFXDatasetBinaryClassification, self).__init__(days, logger, data_args)

    def __getitem__(self, index):
        all_features, all_targets = super().getitem(index)

        # Let's make binary classification be based on whether close of mean of bid and ask
        # if higher/lower than mean of close of bid and ask of last
        # tie = randomly high/low to avoid class bias

        # print(all_targets)
        cur_sum = 0
        for i in range(len(all_targets)):
            cur_sum += all_targets[i][0] + all_targets[i][3]
        future = cur_sum / 2 / len(all_targets)

        cur_sum = 0
        for i in range(0, len(all_features), 5):
            cur_sum += all_features[i][-1]
        last = cur_sum / len(range(0, len(all_features), 5))

        if future > last:
            target = 1
        elif last < future:
            target = 0
        else:
            target = random.random() > 0.5

        return all_features, target

def get_dataloaders(args):

    if args.misc_args.fast_debug:
        train_days, valid_days = convert_train_val_days(TRAIN_DAYS,
                                                        VALID_DAYS)
    else:
        train_days, valid_days = TRAIN_DAYS, VALID_DAYS

    # Cheat to get the dataset class
    dataset_class = globals()[ALL_SETTINGS[args.misc_args.exp_setting]['dataset']]

    # We should force dataset initialization to use the same parameters
    train_dataset = dataset_class(train_days, args.misc_args.logger, args.data_args)
    valid_dataset = dataset_class(valid_days, args.misc_args.logger, args.data_args)

    train_dataloader = DataLoader(train_dataset,
                                  batch_size=args.train_args.batch_size,
                                  shuffle=True,
                                  num_workers=args.data_args.num_workers)

    valid_dataloader = DataLoader(valid_dataset,
                                  batch_size=args.train_args.batch_size,
                                  shuffle=False,
                                  num_workers=args.data_args.num_workers)

    return train_dataloader, valid_dataloader


# -*- coding: utf-8 -*-
"""
**************************************************************************************
*                     Braille Dictionary (GRADE 1)
*                  ================================
*  This software is intended to convert english text into braille characters
*  MODULE: Braille_Dictionary_Grade_1
*  Filename: Braille_Dictionary_Grade_1.py
*  Version: 1.8.0
*  Date: March 14, 2019
*
*  Authors: Aditya Kumar Singh and Raj Kumar Bhagat
*  Team Name: Victorious Visionaries
*  Team Members: Aditya Kumar Singh, Raj Kumar Bhagat,
*                Ruphan S, Yash Patel
***************************************************************************************
"""

"""
---------------------------------------------------------------------------------------
                               INSTRUCTIONS
                             =================
    1. Braille is represented in form of 6 raised dots.
       Ex:-
              1-> o o <-4
              2-> o o <-5
              3-> o o <-6
        The dots are represented here with '0' whereas those numbers are dots
        refrence number.
    2. So 'a' is represented as 0 o  where '0' is raised dot and 'o' is normal dot.
                                o o
                                o o
    3. Now this can be numrically reffered as 1 since only raised dot is at position 1
       In the same way for 'b' we can say [1,2] since only these two dots are raised.

    4. Now here each braille character set is represented in a form of array[] with
       6 elements in it.

    5. And raised dot is represented by "1". and normal dots are represented with "0".

    6. Each element maps to braille character like this :
            [ 1, 2, 3, 4, 5, 6]
       So for 'a' we have [1, 0, 0, 0, 0, 0]

                              GRADE 1 BRAILLE
                        ==========================
    1. It is the the first grade in braille.

    2. It is basically contains one-to-one conversion of contractions.

    3. Individual cells cannot represent words or abbreviations in this grade of Braille.

    4. Characters invloved are a-z(with capatalization included), punctutators, numbers.

    5. For more visit "http://www.acb.org/tennessee/braille.html"

----------------------------------------------------------------------------------------
"""

import string                                   #For handling string methods like punctuation()

class Grade1:
    last_type_modifier=""                       #Variable to keep track of type of character last read
    braille_code=[]                             #List which will hold the braille code after conversion
    Dict = {                             #Dictionary for BRAILLE GRADE 1
        "_number": [0, 0, 1, 1, 1, 1],
        "_letter": [0, 0, 0, 0, 1, 1],
        "_caps": [0, 0, 0, 0, 0, 1],
        "_decimal": [0, 0, 0, 1, 0, 1],
        "_space": [0, 0, 0, 1, 0, 1],
        "a": [1, 0, 0, 0, 0, 0],
        "b": [1, 1, 0, 0, 0, 0],
        "c": [1, 0, 0, 1, 0, 0],
        "d": [1, 0, 0, 1, 1, 0],
        "e": [1, 0, 0, 0, 1, 0],
        "f": [1, 1, 0, 1, 0, 0],
        "g": [1, 1, 0, 1, 1, 0],
        "h": [1, 1, 0, 0, 1, 0],
        "i": [0, 1, 0, 1, 0, 0],
        "j": [0, 1, 0, 1, 1, 0],
        "k": [1, 0, 1, 0, 0, 0],
        "l": [1, 1, 1, 0, 0, 0],
        "m": [1, 0, 1, 1, 0, 0],
        "n": [1, 0, 1, 1, 1, 0],
        "o": [1, 0, 1, 0, 1, 0],
        "p": [1, 1, 1, 1, 0, 0],
        "q": [1, 1, 1, 1, 1, 0],
        "r": [1, 1, 1, 0, 1, 0],
        "s": [0, 1, 1, 1, 0, 0],
        "t": [0, 1, 1, 1, 1, 0],
        "u": [1, 0, 1, 0, 0, 1],
        "v": [1, 1, 1, 0, 0, 1],
        "x": [1, 0, 1, 1, 0, 1],
        "y": [1, 0, 1, 1, 1, 1],
        "z": [1, 0, 1, 0, 1, 1],
        "w": [0, 1, 0, 1, 1, 1],
        "1": [1, 0, 0, 0, 0, 0],
        "2": [1, 1, 0, 0, 0, 0],
        "3": [1, 0, 0, 1, 0, 0],
        "4": [1, 0, 0, 1, 1, 0],
        "5": [1, 0, 0, 0, 1, 0],
        "6": [1, 1, 0, 1, 0, 0],
        "7": [1, 1, 0, 1, 1, 0],
        "8": [1, 1, 0, 0, 1, 0],
        "9": [0, 1, 0, 1, 0, 0],
        "0": [0, 1, 0, 1, 1, 0],
        ",": [0, 1, 0, 0, 0, 0],
        ";": [0, 1, 1, 0, 0, 0],
        ":": [0, 1, 0, 0, 1, 0],
        ".": [0, 1, 0, 0, 1, 1],
        "!": [0, 1, 1, 0, 1, 0],
        "()": [0, 1, 1, 0, 1, 1],
        "\"?": [0, 1, 1, 0, 0, 1],
        "*": [0, 0, 1, 0, 1, 0],
        "\"": [0, 0, 1, 0, 1, 1],
        }
    """
    Constructor Function
    """
    def __init__(self):
        self.last_type_modifier=False
        braille_code=[]

    """
    This Function prints all the characters defined in all the dictionaries
    present in its parent class
    """
    def show_all(self):
        print("Grade 1.... \n")
        for i,j in self.Dict.items():
            print(i+"->")
            for n,k in enumerate(self.Dict[i][:3]):
                print(k,self.Dict[i][n+3])
            print("\n")

    """
    This Function prints a particular character in its braille form.
    NOTE: The character should belong to Grade 1.
    """
    def print_braille1(self,char):
        if(char.isupper()):
            char=char.lower()
        if char in self.Dict:
            for n,i in enumerate(self.Dict[char][:3]):
                print(i,self.Dict[char][n+3])
            print("..")

    """
    This function encodes the given english word into Braille
    """
    def decode_grade1(self,word):
        """
          In this function if you want to print the current character which is being
          processed in tis braille form then, uncomment the lines which have print in it.
          Ex: 'print(i)' and 'self.print_braille1("_letter")'
          NOTE: This is helpfull in case of debugging but it also decrease the processing time.
          So better once checked keep those lines in comments.
        """
        #Checking for firstrun
        if(self.last_type_modifier==False):
            if(word[0].isalpha()):
               if(word[0].islower()):
                   self.last_type_modifier="lower"
                   #self.print_braille1("_letter")
                   #self.braille_code.append(self.Dict["_letter"])
               elif(word[0].isupper()):
                   self.last_type_modifier="upper"
            elif(word[0].isnumeric()):
                self.last_type_modifier="num"
                #self.print_braille1("_number")
                self.braille_code.append(self.Dict["_number"])
        m = -1                                  #Variable holding index position for the string word
        while(m<len(word)-1):
            #Update the iterating variable
            m+=1
            #Extracting the character at index m in string word
            i=word[m]
            #Checking for type change
            if(i.islower() and (self.last_type_modifier!="lower")):
                if(self.last_type_modifier=="upper"):
                    self.last_type_modifier="lower"
                else:
                    self.last_type_modifier="lower"
                    #self.print_braille1("_letter")
                    self.braille_code.append(self.Dict["_letter"])

            elif(i.isnumeric() and (self.last_type_modifier!="num")):
                self.last_type_modifier="num"
                #self.print_braille1("_number")
                self.braille_code.append(self.Dict["_number"])
            elif(i.isupper()):
                self.last_type_modifier="upper"
                final_index=len(word)
                if(final_index==1):
                    self.braille_code.append(self.Dict["_caps"])
                    if i.lower() in self.Dict:
                        self.braille_code.append(self.Dict[i.lower()])
                    else:
                        self.braille_code.append([0, 0, 0, 0, 0, 0])
                    return
                flag=0
                while(final_index!=(m+1)):
                    if(word[m:final_index].isupper() and word[m:final_index].isalpha()):
                        #print(word[m:final_index])
                        flag=1
                        #self.print_braille1("_caps")
                        #self.print_braille1("_caps")
                        self.braille_code.append(self.Dict["_caps"])
                        self.braille_code.append(self.Dict["_caps"])
                        for j in word[m:final_index]:
                            #print(j)
                            #self.print_braille1(j)
                            if j.lower() in self.Dict:
                                self.braille_code.append(self.Dict[j.lower()])
                            else:
                                self.braille_code.append([0, 0, 0, 0, 0, 0])

                        break
                    final_index-=1
                m=final_index-1
                if(final_index==len(word)):
                    return
                else:
                    if((not word[m+1].isnumeric()) and flag==1):
                        #self.print_braille1("_caps")
                        #self.print_braille1("_caps")
                        self.braille_code.append(self.Dict["_caps"])
                        self.braille_code.append(self.Dict["_caps"])
                    if(not flag):
                        #self.print_braille1("_caps")
                        self.braille_code.append(self.Dict["_caps"])
                        #print(i)
                        #self.print_braille1(i)
                        if i.lower() in self.Dict:
                            self.braille_code.append(self.Dict[i.lower()])
                        else:
                            self.braille_code.append([0, 0, 0, 0, 0, 0])
                    continue
            elif(i in string.punctuation):
                char=""
                if(i=='(' or i==')'):
                    char="()"
                elif(i=='?'):
                    char="\"?"
                elif(i=='.'):
                    if(m==len(word)-1):
                        char=i
                    else:
                        char="_decimal"
                else:
                    char=i
                if char in self.Dict:
                    self.braille_code.append(self.Dict[char])
                else:
                    self.braille_code.append([0, 0, 0, 0, 0, 0])
                continue
            """Printing the current character"""
            #print(i)
            #self.print_braille1(i)
            self.braille_code.append(self.Dict[i])

    """
    This functions start encoding into braille
    """
    def encode_braille(self,word):
        self.braille_code=[]
        self.decode_grade1(word)
        code=self.braille_code
        return code

"""
    This function prints the converted braille on the screen.
"""
def print_braille(braille):
    #print(braille)
    _len=len(braille)
    for i in range(0,3):
        m=""
        for x in braille:
            m+=str(x[i])+str(x[i+3])
            m+=" "
        print(m)

braille=Grade1()           #Object created

"""
test="asdfghAQWWWopiuytrew"

brl=braille.encode_braille(test)
print("Given word: " + test)
print("Braille converted text: ")
print_braille(brl)
"""


class Solution:
    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        #perform an inorder traversal
        #return the kth smallest value from the list created
        res = []
        def inorder(root): #left root right
            if root:
                inorder(root.left)
                res.append(root.val)
                inorder(root.right)
        inorder(root)
        return res[k-1]


from setuptools import find_packages, setup

VERSION = "0.0.4"

with open("README.md", "r") as readme:
    long_description = readme.read()

setup(
    name="burrowkv",
    version=VERSION,
    description="key-value store",
    packages=find_packages(),
    long_description=long_description,
    long_description_content_type="text/markdown",
    author="Yusuf",
    author_email="contact@yusuf.im",
    url="https://github.com/iunary/burrowkv",
    license="MIT",
    install_requires=[],
    keywords=["key value store", "kv", "key-value"],
    classifiers=[
        "Programming Language :: Python :: 3",
        "Operating System :: OS Independent",
    ],
    python_requires=">=3.8",
)


__author__ = 'Tony Beltramelli - 07/11/2015'
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from math import sqrt

def detect_peaks(signal, threshold=0.5):
	""" Performs peak detection on three steps: root mean square, peak to
	average ratios and first order logic.
	threshold used to discard peaks too small """
	# compute root mean square
	root_mean_square = sqrt(np.sum(np.square(signal) / len(signal)))
	# compute peak to average ratios
	ratios = np.array([pow(x / root_mean_square, 2) for x in signal])
	# apply first order logic
	peaks = (ratios > np.roll(ratios, 1)) & (ratios > np.roll(ratios, -1)) & (ratios > threshold)
	# optional: return peak indices
	peak_indexes = []
	for i in range(0, len(peaks)):
		if peaks[i]:
			peak_indexes.append(i)
	return peak_indexes


# run rpi detection code here
# preferably running interrupts
# need some way to preserve state
# maybe a class would be nice

import RPi.GPIO as GPIO
import time
import tempfile

print("Setting up RPi code")

GPIO.setmode(GPIO.BOARD)

# potential divider
GPIO.setup(22, GPIO.OUT)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

# status LED
GPIO.setup(32, GPIO.OUT)

GPIO.output(22, 1)

class LPD:
    running = False
    start_time = 0
    stop_time = 0
    pulses = 0
    pulse_times = []

    @staticmethod
    def start():
        LPD.running = True
        LPD.start_time = time.perf_counter()
        LPD.pulses = 0
        LPD.pulse_times = []
        GPIO.output(32, 1)

    @staticmethod
    def stop():
        GPIO.output(32, 0)
        LPD.running = False
        LPD.stop_time = time.perf_counter()
        file = tempfile.NamedTemporaryFile(delete=False)
        filename = file.name
        file.close()
        with open(filename, "w") as file:
            for t in LPD.pulse_times:
                file.write("{}\r\n".format(t))

        return filename

    @staticmethod
    def running_for():
        return time.perf_counter() - LPD.start_time

    @staticmethod
    def running_for_hms():
        t = LPD.running_for()
        h, m = divmod(t, 3600)
        m, s = divmod(m, 60)
        return int(h), int(m), s

    @staticmethod
    def light_pulse_callback(call):
        if LPD.running and GPIO.input(12):
            dt = time.perf_counter() - LPD.start_time
            LPD.pulse_times.append(dt)
            LPD.pulses += 1
            # print("Pulsing")

GPIO.add_event_detect(12, GPIO.RISING, bouncetime=10)
GPIO.add_event_callback(12, LPD.light_pulse_callback)


"""N = int(input())

dp = [[0]*3 for _ in range(N+1)]

dp[1]=[1,1,1]

for i in range(2,N+1) :
    dp[i][0] = sum(dp[i-1])%9901
    dp[i][1] = (dp[i-1][0]+dp[i-1][2])%9901
    dp[i][2] = (dp[i-1][0]+dp[i-1][1])%9901

#메모리 사용량이 많음
# 1.각 부분을 나눠줘서 해결한다
# 2. ->변수를 사용해서 우벼ㅑㄴ에서 한번에 연산후 튜플로 좌변 대입(메모리소모,속도빠름)
ans = sum(dp[N])
print(ans%9901)
"""

# 2. ->변수를 사용해서 우벼ㅑㄴ에서 한번에 연산후 튜플로 좌변 대입(메모리소모,속도빠름)
N = int(input())

n0 = n1 = n2 = 1
for i in range(1, N):
    n0, n1, n2 = (n0+n1+n2)%9901, (n0+n2)%9901, (n0+n1)%9901
ans = n0+n1+n2
print(ans%9901)


import sqlite3
import os
from flask import current_app

class SQliteConnection(object):
    """automatic open and close"""
    def __init__(self):
        self.conn = None
        self.curr = None
        #OBS! using current_app.config prevents the user from accessing
        #two different projects in the same browser session - they need
        #To open a new browser session (private window) for each project
        self.config = current_app.config

    def __enter__(self):
        print(f"Opening connection to {self.config['path_db_file']}")
        self.conn = sqlite3.connect(self.config["path_db_file"])
        self.curr = self.conn.cursor()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Closing connection")
        if exc_tb is None or "Aborted by KeyboardInterrupt" in str(exc_val):
            print("Comitting")
            self.conn.commit()
        else:
            self.conn.rollback()
        self.conn.close()


from time import sleep
from discord.ext import commands, tasks
from datetime import datetime
import discord
import yaml
from lol_manager import getMatch, searchMatch, getUsername, isPlaying, getRemainingTime, filterData

client = commands.Bot(command_prefix='!')

channel = None
discord_key = ''
curMatchId = ''

class emojis():
    IRON = 999136386856800307
    BRONZE = 999136386856800307
    SILVER = 999136388328992808
    GOLD = 999136393504772217
    PLATINUM = 999136397371912202
    DIAMOND = 999136392296812604
    MASTER = 999136390916882572
    GRANDMASTER = 999136398743449781
    CHALLENGER = 999136400425365634
    BLUE = ':blue_circle:'
    RED = ':red_circle:'
    FAILED = 999405999091880077
    PASSED = 999406000736043008
    NO_BACKGROUND = 999802179005194300

    def getEmoji(elo):
        if elo == 'IRON':
            return emojis.IRON
        elif elo == 'BRONZE':
            return emojis.BRONZE
        elif elo == 'SILVER':
            return emojis.SILVER
        elif elo == 'GOLD':
            return emojis.GOLD
        elif elo == 'PLATINUM':
            return emojis.PLATINUM
        elif elo == 'DIAMOND':
            return emojis.DIAMOND
        elif elo == 'MASTER':
            return emojis.MASTER
        elif elo == 'GRANDMASTER':
            return emojis.GRANDMASTER
        elif elo == 'CHALLENGER':
            return emojis.CHALLENGER

with open('config.yml', 'r') as f:
    discord_key = yaml.safe_load(f)['discord_key']

with open('cache.yml', 'r') as f:
    cache = yaml.safe_load(f)
    if cache != None and cache.get('Gameid') != None:
        curMatchId = cache.get('Gameid')

def getChannelId():
    with open('config.yml') as f:
        config = yaml.safe_load(f)
        if config != None:
            if config.get('channel_id') != None:
                return config.get('channel_id')

@client.event
async def on_ready():
    print(f'Logged in as:  {client.user.name} - {client.user.id}')
    global channel
    channel = client.get_channel(getChannelId())
    print(f"Channel id found in config ({channel.id})")
    matchFindLoop.start()
    await client.change_presence(activity=discord.Game(f"partida de {getUsername()}"))

@client.command(aliases=['set_channel'])
async def setChannel(ctx):
    channel = ctx.channel.id
    with open('config.yml', 'w') as f:
        config = {'channel_id': channel}
        yaml.dump(config, f)

@tasks.loop(seconds=60)
async def matchFindLoop():
    global channel
    global curMatchId
    if(isPlaying()):
        match = await searchMatch()

        gameId = match['Gameid']
        matchTime = match['Time']
        remainingTime = getRemainingTime(matchTime)

        if(gameId == curMatchId):
            sleep(remainingTime)
            return

        date = datetime.now()
        print(f"Match found at: {datetime.strftime(date, '%H:%M:%S')}")

        gameId, gameType, matchTime, gameMinutes, gameSeconds, names, champions, elos = filterData(
            match, client, emojis)

        curMatchId = gameId

        embed = discord.Embed(title='Partida encontrada',
                              description=f"{gameType} {gameMinutes:02d}:{gameSeconds:02d}", color=0xf50000)
        embed.add_field(name='Nome', value=names, inline=True)
        embed.add_field(name='Champion', value=champions, inline=True)
        embed.add_field(name='Elo', value=elos, inline=True)
        embed.set_footer(text=f"ID: {gameId}")

        await channel.send(embed=embed)

        sleep(remainingTime)
    else:
        print('No match found... Waiting 60 seconds for searching again')

client.run(discord_key)


from flask import Flask
from flask import request

import datetime
import pickle
import urllib.request

urllib.request.urlretrieve("https://github.com/arthursl12/Cloud_TP2/raw/main/trained_model.sk", "trained_model.sk")
urllib.request.urlretrieve("https://github.com/arthursl12/Cloud_TP2/raw/main/last_updated.date", "last_updated.date")

app = Flask(__name__)
app.model = pickle.load(open("trained_model.sk", "rb"))
app.last_updated = pickle.load(open("last_updated.date", "rb"))

@app.route("/")
def hello_world():
    return "
Hello, World!
"

@app.route("/api/american", methods=["POST"])
def american_process():
    # Get input JSON
    text = request.get_json(force=False)['text']

    # Predict using the model
    result = app.model.predict([text])[0]
    print(result)

    # Convert datetime to ISO string
    date_string = datetime.datetime.strftime(
        app.last_updated, '%Y-%m-%dT%H:%M:%S%z'
    )

    # Send a dict response (Flask will convert to JSON
    return {
        "is_american": int(result),
        "version": "1.7",
        "model_date": date_string,
    }


# -*- coding: utf-8 -*-
"""
Created on Thu Jul 19 10:45:24 2018

@author: shen1994
"""

import os
import cv2
import tensorflow as tf
import numpy as np

if __name__ == "__main__":

    os.environ['CUDA_VISIBLE_DEVICES'] = '0'

    output_graph_def = tf.GraphDef()
    output_graph_def.ParseFromString(open("model/pico_FaceProper_model.pb", "rb").read())
    tensors = tf.import_graph_def(output_graph_def, name="")
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    opt = sess.graph.get_operations()
    input_x = sess.graph.get_tensor_by_name("proper_input:0")
    gender_y = sess.graph.get_tensor_by_name("pred_gender/Softmax:0")
    age_y = sess.graph.get_tensor_by_name("pred_age/Softmax:0")

    image_path = "timg.jpg"
    image_size = 128
    o_image = cv2.imread(image_path, 1)
    image = cv2.resize(o_image, (image_size, image_size))
    image = image.astype('float32')

    gender_list, age_list = sess.run([gender_y, age_y], \
                           feed_dict={input_x: [image]})

    g_gender_list = np.arange(0, 2).reshape(2,)
    g_age_list = np.arange(0, 101).reshape(101,)

    gender = gender_list.dot(g_gender_list)[0]
    age = age_list.dot(g_age_list)[0]

    cv2.namedWindow("test")

    while(True):
        age_text = 'Age: %.2f' % age
        gender_text = 'Gender: %.2f' % gender
        cv2.putText(o_image, age_text, (130, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.60, (0,255,0), 2)
        cv2.putText(o_image, gender_text, (0, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.60, (0,255,0), 2)

        cv2.imwrite("DeepFaceProper-female.jpg", o_image)
        break

        cv2.imshow("test", o_image)
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break


bl_info = {
    "name": "Export: Reign Model-XML Format",
    "author": "Andrew and Philip Witte <zezba9000@gmail.com>",
    "blender": (2, 66, 0),
    "location": "File > Import-Export",
    "description": "Export RMX: Mesh, Material, Textures, & Animation.",
    "warning": "",
    "wiki_url": "http://www.reign-studios.com/",
    "tracker_url": "",
    "support": 'OFFICIAL',
    "category": "Import-Export"}

if "bpy" in locals():
    import imp

    if "export_rmx" in locals():
        imp.reload(export_rmx)

import bpy

from bpy.props import (BoolProperty,
                       FloatProperty,
                       StringProperty,
                       EnumProperty,
                       )
from bpy_extras.io_utils import (ExportHelper,
                                 path_reference_mode,
                                 axis_conversion,
                                 )

class ExportRMX(bpy.types.Operator, ExportHelper):
    """Save a Reign Model-XML File"""

    bl_idname = "export_scene.rmx"
    bl_label = 'Export RMX'
    bl_options = {'PRESET'}

    filename_ext = ".rmx"
    filter_glob = StringProperty(
            default="*.rmx",
            options={'HIDDEN'},
            )

    path_mode = path_reference_mode
    check_extension = True

    def execute(self, context):
        from . import export_rmx

        keywords = self.as_keywords(ignore=("check_existing", "filter_glob"))

        return export_rmx.save(self, context, **keywords)

def menu_func_export(self, context):
    self.layout.operator(ExportRMX.bl_idname, text="Reign (.rmx)")

def register():
    bpy.utils.register_module(__name__)
    bpy.types.INFO_MT_file_export.append(menu_func_export)

def unregister():
    bpy.utils.unregister_module(__name__)
    bpy.types.INFO_MT_file_export.remove(menu_func_export)

if __name__ == "__main__":
    register()


import pygame
import time
import pytmx
from pytmx import TiledImageLayer
from pytmx import TiledObjectGroup
from pytmx import TiledTileLayer
from pytmx import TiledMap

pygame.init()
size = width, height = 1366, 768
from pytmx import TiledObjectGroup

#screen = pygame.display.set_mode(size,pygame.FULLSCREEN)
screen = pygame.display.set_mode(size)
tiled_map = pytmx.load_pygame('image\\Tilemap\\t1.tmx')
print(tiled_map.get_tile_gid(0, 0, 0))
print(tiled_map.get_tile_properties_by_gid(1))

for layer in tiled_map.visible_layers:
    print(layer)
    if isinstance(layer, TiledTileLayer):
        print("TiledTileLayer")
        print(TiledMap)
        for t in layer.iter_data():
            if (t[2] != 0):
                print(tiled_map.get_tile_properties_by_gid(t[2]))
                screen.blit(tiled_map.get_tile_image_by_gid(t[2]), (t[0]*16, t[1]*16))
                print(t)
    elif isinstance(layer, TiledObjectGroup):
        print("TiledObjectGroup")
    elif isinstance(layer, TiledImageLayer):
        print("TiledImageLayer")

pygame.display.flip()

while True:
    time.sleep(1)


from PySide6.QtGui import *
from PySide6.QtCore import *
from PySide6.QtWidgets import *
import PySide6.QtNetwork, socket, resources, os, zipfile, datetime, random, base64
from werkzeug.serving import make_server, BaseWSGIServer
from flask import Flask, send_file, request, render_template

TITLE = "File Server"

class QSwitch(QAbstractButton):
    def __init__(
        self,
        parent=None,
        track_radius=10,
        thumb_radius=8,
        thumb_offset=4,
        useOffset=True,
        text_margin=4,
    ):
        super().__init__(parent=parent)
        self.setCheckable(True)
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        self.text_margin = text_margin
        self._track_radius = track_radius
        self._thumb_radius = thumb_radius
        self._thumb_offset = thumb_offset
        self._useOffset = useOffset
        self._offset = self._thumb_offset

        palette = self.palette()
        if self._thumb_radius > self._track_radius:
            self._track_color = {
                True: palette.highlight(),
                False: palette.dark(),
            }
            self._thumb_color = {
                True: palette.highlight(),
                False: palette.light(),
            }
            self._text_color = {
                True: palette.highlightedText().color(),
                False: palette.dark().color(),
            }
            self._thumb_text = {
                True: "",
                False: "",
            }
            self._track_opacity = 0.5
        else:
            self._thumb_color = {
                True: palette.highlightedText(),
                False: palette.light(),
            }
            self._track_color = {
                True: palette.highlight(),
                False: palette.dark(),
            }
            self._text_color = {
                True: palette.highlight().color(),
                False: palette.dark().color(),
            }
            self._thumb_text = {
                True: "✔",
                False: "✕",
            }
            self._thumb_text = {
                True: "1",
                False: "0",
            }
            self._track_opacity = 1

    @Property(int)
    def offset(self):
        return self._offset

    @offset.setter
    def offset(self, value):
        self._offset = value
        self.update()

    @property
    def thumb_radius(self):
        if self._useOffset:
            return self.height() - self._thumb_offset * 2
        else:
            return self._thumb_radius

    @property
    def thumb_y_offset(self):
        if self._useOffset:
            return self._thumb_offset
        else:
            return (self.height() - self._thumb_radius) / 2

    @property
    def next_offset(self):
        if self.isChecked():
            return self.width() - self.thumb_radius - self.thumb_x_offset
        else:
            return self.thumb_x_offset

    @property
    def thumb_x_offset(self):
        if self._useOffset:
            return self._thumb_offset
        else:
            return (self.height() - self._thumb_radius) / 2

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self.update()

    def paintEvent(self, event):  # pylint: disable=invalid-name, unused-argument
        p = QPainter(self)
        p.setRenderHint(QPainter.Antialiasing, True)
        p.setPen(Qt.NoPen)
        track_opacity = self._track_opacity
        thumb_opacity = 1.0
        text_opacity = 1.0

        if self.isEnabled():
            track_brush = self._track_color[self.isChecked()]
            thumb_brush = self._thumb_color[self.isChecked()]
            text_color = self._text_color[self.isChecked()]
        else:
            track_opacity *= 0.8
            track_brush = self.palette().shadow()
            thumb_brush = self.palette().mid()
            text_color = self.palette().shadow().color()

        # drawing the track
        p.setBrush(track_brush)
        p.setOpacity(track_opacity)
        p.drawRoundedRect(
            0,
            0,
            self.width(),
            self.height(),
            self._track_radius,
            self._track_radius,
        )

        # drawing the thumb
        p.setBrush(thumb_brush)
        p.setOpacity(thumb_opacity)
        p.drawEllipse(
            self.offset,
            self.thumb_y_offset,
            self.thumb_radius,
            self.thumb_radius,
        )

        # drawing the thumb
        p.setPen(text_color)
        p.setOpacity(text_opacity)
        font = p.font()
        font.setPixelSize(int(0.8 * self.thumb_radius))
        p.setFont(font)
        p.drawText(
            QRectF(
                self.offset,
                self.thumb_y_offset,
                self.thumb_radius,
                self.thumb_radius,
            ),
            Qt.AlignCenter,
            self._thumb_text[self.isChecked()],
        )

    def mouseReleaseEvent(self, event):  # pylint: disable=invalid-name
        super().mouseReleaseEvent(event)
        if event.button() == Qt.LeftButton:
            anim = QPropertyAnimation(self, b"offset", self)
            anim.setDuration(120)
            anim.setStartValue(self.offset)
            anim.setEndValue(self.next_offset)
            anim.start()

    def enterEvent(self, event):  # pylint: disable=invalid-name
        self.setCursor(Qt.PointingHandCursor)
        super().enterEvent(event)

class QToggle(QSwitch):
    ...

class Thread(QThread):
    def __init__(self, run) -> None:
        super().__init__()
        self._run = run

    def run(self):
        self._run()

class Label(QLabel):
    ...

class Server:
    def get_size(self, file: str) -> str:
        size = os.path.getsize(file)
        order = 0
        while size >= self.BYTE and order < len(self.UNITS):
            order += 1
            size /= self.BYTE
        return f"{size:.1f} {self.UNITS[order]}"

    def get_dfs(self, folder: str) -> str:
        dirs = []
        files = []

        for df in os.listdir(folder):
            p = os.path.join(folder, df)

            ls = [
                f"?path={self.encode(os.path.abspath(p))}&rand={random.randint(0, 2000)}",
                df,
                self.get_size(p),
                datetime.datetime.fromtimestamp(os.path.getmtime(p)).strftime(
                    "%d/%m/%Y %I:%M:%S %p"
                ),
            ]
            master = None
            if os.path.isdir(p):
                master = dirs
            elif os.path.isfile(p):
                master = files

            if master != None:
                master.append(ls)

        dirs.sort()
        files.sort()
        return dirs, files

    def encode(self, path: str):
        return base64.b64encode(path.encode()).decode()

    def decode(self, path: str):
        return base64.b64decode(path.encode()).decode()

    def get_request_path(self):
        path = request.args.get("path")
        return self.escape(self.decode(path)), path

    def base(self, path):
        return os.path.basename(path)

    def __init__(self):
        self.BYTE = 1024
        self.UNITS = [
            "B",
            "KB",
            "MB",
            "GB",
            "TB",
        ]
        self._path: str = ""

        self.flask_app = Flask(TITLE)
        self.flask_app.add_url_rule("/", view_func=self.home)
        self.flask_app.add_url_rule("/folder", view_func=self.folder)
        self.flask_app.add_url_rule("/file", view_func=self.file)

    def home(self):
        return self.folder(self._path)

    def folder(self, folder=""):
        dirname = self.escape(os.path.dirname(self._path))

        if not folder:
            folder, _ = self.get_request_path()
            if self.escape(self._path) not in folder:
                return "Path not found!"

        dirs, files = self.get_dfs(folder)
        is_root = folder == self._path

        parent = ""
        current = f"?path={self.encode(folder)}&rand={random.randint(0, 2000)}"
        if is_root:
            index = self.base(folder)
        else:
            index = self.escape(folder).replace(dirname, "")
            parent = f"?path={self.encode(os.path.dirname(folder))}&rand={random.randint(0, 2000)}"

        return render_template(
            "file_server.html",
            dirs=dirs,
            files=files,
            is_root=is_root,
            parent=parent,
            current=current,
            index=index,
        )

    def file(self):
        file, _ = self.get_request_path()
        if self.escape(self._path) not in file:
            return "Path not found!"
        return send_file(file)

    def escape(self, path: str):
        return path.replace(os.path.sep, "/")

class Window(Server, QWidget):
    def __init__(self):
        QWidget.__init__(self)
        Server.__init__(self)

        self.setWindowFlag(Qt.WindowStaysOnTopHint)
        self.setWindowTitle(TITLE)

        self.flask_app.add_url_rule("/download", view_func=self.download)
        self.flask_app.add_url_rule("/served", view_func=self.served)

        self._port: int = 7767
        self.count = 0

        self._server: BaseWSGIServer = None

        lay = QVBoxLayout(self)

        form = QFormLayout()
        form.setFormAlignment(Qt.AlignCenter)
        lay.addLayout(form)

        l = QHBoxLayout()
        self.server_ip = Label()
        self.server_ip.setMaximumWidth(100)
        l.addWidget(self.server_ip)
        l.addStretch()
        self.counter = Label(f"{self.count} Downloads")
        self.counter.setAlignment(Qt.AlignCenter)
        self.counter.setMaximumWidth(100)
        l.addWidget(self.counter)
        form.addRow(Label("Server IP : "), l)
        self.ip_timer = self.startTimer(1000)

        l = QHBoxLayout()
        self.server_port = QLineEdit()
        self.server_port.setValidator(QIntValidator())
        self.server_port.setMaximumWidth(100)
        l.addWidget(self.server_port)
        l.addStretch()
        self.url = Label()
        self.url.setTextInteractionFlags(Qt.TextSelectableByMouse)
        l.addWidget(self.url)
        form.addRow(Label("Server PORT : "), l)

        self.isFolder = QSwitch()
        self.isFolder.toggled.connect(self.switch_icon)
        form.addRow(Label("Path is Folder ? "), self.isFolder)

        l = QHBoxLayout()
        self.path = Label()
        self.path.setMinimumWidth(300)
        l.addWidget(self.path)
        self.icons = [QIcon("static/file"), QIcon("static/folder")]
        self.icon_texts = ["Browse File", "Browse Folder"]
        self.browse_btn = QPushButton(self.icons[0], self.icon_texts[0])
        self.browse_btn.clicked.connect(self.browse)
        l.addWidget(self.browse_btn)
        form.addRow(Label("Path to Serve : "), l)

        self.serve = QSwitch()
        self.serve.clicked.connect(self.server)
        form.addRow(Label("Serve ? "), self.serve)

        self._thread_ = None

        # self.t = QTimer()
        # self.t.singleShot(200, lambda: self.isFolder.setChecked(True))

        self.show()

    def timerEvent(self, event: QTimerEvent):
        timerId = event.timerId()
        if timerId == self.ip_timer:
            self.server_ip.setText(self.ip)

    @property
    def datetime(self) -> str:
        return datetime.datetime.now().strftime("%A %d/%m/%Y %I/%M/%S %p")

    def home(self):
        if os.path.isfile(self._path):
            path = os.path.basename(self._path)
            return f"""

Home Page @ {self.datetime}

Download {path}

Download Latest {path}

                """
        return super().home()

    def download(self):
        path, _ = self.get_request_path()
        if os.path.isdir(path):
            path = self.zip(path, True)

        self.count += 1
        self.counter.setText(f"{self.count} Downloads")
        return send_file(path, as_attachment=True, attachment_filename=self.base(path))

    def served(self):
        latest = request.args.get("latest", 0, bool)
        path = self._path

        if os.path.isdir(self._path):
            path = self.zip(self._path, latest)

        if path:
            basename = os.path.basename(path)
            self.count += 1
            self.counter.setText(f"{self.count} Downloads")
            return send_file(path, attachment_filename=basename, as_attachment=True)
        return "No file is served"

    def server(self):
        if self.serve.isChecked():
            if self._path:
                self._port = int(self.server_port.text() or self._port)
                self.server_port.setText(str(self._port))
                self.url.setText(f"http://{self.ip}:{self._port}")
                self.server_port.setDisabled(True)

                self._server = make_server(self.ip, self._port, self.flask_app)

                self.ctx = self.flask_app.app_context()
                self.ctx.push()

                self._thread_ = Thread(self.serve_forever)
                self._thread_.start()

            else:
                QMessageBox.critical(
                    self, "No path to serve", "Select a path to serve first!"
                )
                self.serve.setChecked(False)

        else:
            if self._server:
                self._server.shutdown_signal = True
                self.server_port.setEnabled(True)
                self._server = None

    def serve_forever(self):
        self._server.serve_forever()

    def switch_icon(self, toggled):
        self.browse_btn.setIcon(self.icons[toggled])
        self.browse_btn.setText(self.icon_texts[toggled])

    def browse(self):
        path = ""
        if self.isFolder.isChecked():
            path = QFileDialog.getExistingDirectory(
                self, "Select a folder to zip and serve?"
            )
        else:
            path = QFileDialog.getOpenFileName(self, "Select a file serve?")
        if path:

            self.count = 0
            if isinstance(path, tuple):
                path = path[0]

            self._path = path
            self.path.setText(os.path.basename(path))
            self.path.setToolTip(path)

    @property
    def ip(self):
        ip_, localhost = None, None
        for ip in PySide6.QtNetwork.QNetworkInterface().allAddresses():
            if ip.protocol() == ip.IPv4Protocol:
                _ip = ip.toString()
                if ip.isLoopback():
                    localhost = _ip
                else:
                    ip_ = _ip
        return ip_ or localhost

    @property
    def _ip(self):
        return socket.gethostbyname(socket.gethostname())

    def zip(self, folder: str, latest=False) -> str:
        zipFileName = folder + ".zip"
        if os.path.isfile(zipFileName) and not latest:
            return zipFileName
        print(f"Zipping {folder}")

        # Create zip file
        with zipfile.ZipFile(
            zipFileName, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9
        ) as zipFile:
            if os.path.isdir(folder):
                for root, dirs, files in os.walk(folder):
                    if os.path.basename(root) == "__pycache__":
                        continue

                    for file in files:
                        filename = os.path.join(root, file)
                        arc = root.replace(folder, os.path.basename(folder))
                        arcname = os.path.join(arc, file)
                        zipFile.write(filename, arcname, zipfile.ZIP_DEFLATED)
            else:
                zipFile.write(folder, zipFileName, zipfile.ZIP_DEFLATED)
        return zipFileName

class App(QApplication):
    def close_win(self):
        if self.win._server:
            self.win._server.shutdown_signal = True
        self.quit()

    def __init__(self):
        super().__init__()

        self.win = Window()
        self.win.destroyed.connect(self.close_win)

        self.setStyleSheet(
            """
         QWidget {
            font-family: Times New Roman;
         }
        QLineEdit, QLabel {
            padding: 4px;
            padding-top: 2px;
            padding-bottom: 2px;
            border: 0px outset white;
            border-radius: 10px;
            background-color: #27384b;
            color: #fafafa;
            font-size: 16px;
            min-height: 1.5em;
        }
        Label {
            min-width: 6.5em;
        }
        QLineEdit:hover {
            border: 1px solid #1d87c5;
            color: #fafafa;
        }
        QLineEdit:focus {
            border: 1px solid #166594;
        }
        QLineEdit:selected {
            background-color: #1d87c5;
            color: #17222d;
        }
        QPushButton {
            border-style: outset;
            border-width: 2px;
            border-radius: 10px;
            border-color: black;
            font: bold 14px;
            padding: 2px;
            min-height: 1.5em;
            max-width: 7.5em;
        }
        QPushButton:hover {
            background-color: red;
            color: white;
        }
        QPushButton:pressed, QPushButton:checked {
            background-color: green;
            color: white;
        }
        QSwitch {
            min-width: 5em;
            min-height: 2em;
        }
        """
        )

app = App()
app.exec()


import numpy as np
import pandas as pd

from flask import Flask, send_from_directory
from flask import Flask
import json

app = Flask(__name__, static_url_path='', static_folder='my-app/build')

@app.route('/')
def index():
    return send_from_directory(app.static_folder, 'index.html')

@app.route('/data_energy')
def data_energy():
	data = pd.read_csv("WorldRenewableEnergy.csv")
	features = data.columns
	return {
		'features': features.tolist(),
		'data': data.to_dict(orient='records')
	}

if __name__ == '__main__':
	app.debug = True
	app.run(port=5002)


import os
import sqlite3

DATA_PATH = "/app/bookstore_db"

CREATE_TABLE = """CREATE TABLE IF NOT EXISTS books
                        (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, author TEXT NOT NULL)"""

def connect():
    conn = sqlite3.connect(os.path.join(DATA_PATH, 'bookstore.db'))
    conn.row_factory = sqlite3.Row
    return conn

def init_db():
    if not os.path.exists(DATA_PATH):
        os.mkdir(DATA_PATH)

    conn = connect()

    cur = conn.cursor()
    cur.execute(CREATE_TABLE)

    add_sample_records(cur)

    conn.commit()
    conn.close()
    print('Initialized the database.')

def is_empty(cur):
    cur.execute('select * from books;')
    return len(cur.fetchall()) == 0

def add_sample_records(cur):
    if is_empty(cur):
        cur.execute("INSERT INTO books (title, author) VALUES (?, ?)",
                    ('Continuous Delivery', 'Dave Farley & Jez Humble'))
        cur.execute("INSERT INTO books (title, author) VALUES (?, ?)",
                    ('CD Pipelines', 'Dave Farley'))
        cur.execute("INSERT INTO books (title, author) VALUES (?, ?)",
                    ('Modern Software Engineering', 'Dave Farley'))


# n=8
n = int(input())
l = list(map(int,input().split()))
d={}
# l = [1,1,2,2,3,2,5]
for i in range(1,len(l)+1):
    u,v= i+1,l[i-1]
    if v not in d:
        d[v] = [u]
    else:
        d[v].append(u)

def dfs(d,root,n,l,v):
    if root in v:
        return False
    else:
        v.add(root)
    if root == n:
        return True
    if root in d:
        for i in d[root]:
            a=dfs(d,i,n,l,v)
            if a is True:
                l.append(i)
                return  True
    return False

l=[]
a=dfs(d,1,n,l,set())
if a:
    l.append(1)
print(*l[::-1])
# 1 1 2 2 3 2 5
# 2 3 4 5 6 7 8
# 1:[2,3]


'''
Created on Sep 8, 2012

@author: anuvrat
'''

from fractions import Fraction
import math

l = []
for d in range( 7, 1000000 ):
    print( d )
    digits = int( math.log10( d ) ) + 1
    bb = 10 ** digits
    aa = int( 3 * bb / 7 )
    begin = int( ( ( aa - 1 ) / bb ) * d )
    end = int( ( ( aa + 1 ) / bb ) * d )
    l.extend( [Fraction( k / d ).limit_denominator() for k in range( begin, end + 2 )] )
    l = list( set( l ) )
    l.sort()
    idx = l.index( Fraction( 3, 7 ) )
    l = l[idx - 1 : idx + 1]
    print( l )

l = list( set( l ) )
l.sort()

print( l[l.index( Fraction( 3 , 7 ) ) - 1] )


from os.path import exists
from argparse import ArgumentParser
import time

from joblib import delayed, Parallel
import torch
import torch.nn.functional as F

# project imports
from setup import *
from database.data_loader import DataLoader
from scripts import config_dev as configFile
from src.algorithm import *
from src.utils import algorithm_utils, deformation_utils as def_utils, io_utils, image_utils, results_utils
from database import read_demo_info
from src import models, layers

device = 'cpu'#'cuda:0'
labels_to_write = ['Thalamus', 'Lateral-Ventricle', 'Hippocampus', 'Amygdala', 'Caudate', 'Pallidum', 'Putamen', 'Accumbens', 'Inf-Lat-Ventricle']
keep_labels = ['Right-' + l for l in labels_to_write] + ['Left-' + l for l in labels_to_write]
UNIQUE_LABELS = np.asarray([0] + [lab for labstr, lab in LABEL_DICT.items() if labstr in keep_labels], dtype=np.uint8)
# UNIQUE_LABELS = np.array([  0,   2,   3,   4,   5,   7,   8,  10,  11,  12,  13,  14,  15,
#         16,  17,  18,  24,  26,  28,  30,  31,  41,  42,  43,  44,  46,
#         47,  49,  50,  51,  52,  53,  54,  58,  60,  62,  63,  77,  80,
#         85, 251, 252, 253, 254, 255], dtype=np.uint8)

class FS_Lin(results_utils.LabelFusion):

    def compute_p_label(self, timepoints, image_list, svf_list, age_list, tp, subject, parameter_dict, regnet_model):
    # def compute_p_label(self, timepoints, image_list, age_list, tp, subject):

        interp_func = layers.SpatialInterpolation(padding_mode='zeros').to(device)

        results_dir_sbj = subject.results_dirs.get_dir('linear_st')
        p_data = {t_var: {sp_var: np.zeros(tp.image_shape + (len(timepoints),), dtype='float32') for sp_var in spatial_variance} for t_var in temp_variance}
        p_label = {t_var: {sp_var: np.zeros(tp.image_shape + (len(UNIQUE_LABELS),), dtype='float32') for sp_var in spatial_variance} for t_var in temp_variance}
        ref_shape = image_list[tp.id].shape

        ii = np.arange(0, ref_shape[0], dtype='int32')
        jj = np.arange(0, ref_shape[1], dtype='int32')
        kk = np.arange(0, ref_shape[2], dtype='int32')

        II, JJ, KK = np.meshgrid(ii, jj, kk, indexing='ij')

        voxMosaic_orig = np.concatenate((II.reshape(-1, 1), JJ.reshape(-1, 1), KK.reshape(-1, 1), np.ones((int(np.prod(ref_shape[:3])), 1), dtype='int32')), axis=1).T
        rasMosaic_orig = np.dot(tp.vox2ras0, voxMosaic_orig).astype('float32')

        del voxMosaic_orig, ii, jj, kk, II, JJ, KK

        for it_tp_flo, tp_flo in enumerate(timepoints):
            fileparts = tp_flo.id.split('_')
            filepath = join(FS_DIR, fileparts[0] + '_' + fileparts[1] + '_' + str(int(fileparts[4])) + '_' + fileparts[5] + '_' + fileparts[6] + '.cross.aseg.mgz')
            proxyseg = nib.load(filepath)

            cog = tp_flo.get_cog()
            affine_matrix = read_affine_matrix(join(results_dir_sbj, tp_flo.id + '.aff'), full=True)
            affine_matrix[:3, 3] += cog
            vox2ras0_fs = np.dot(np.linalg.inv(affine_matrix), proxyseg.affine).astype('float32')

            if tp_flo.id == tp.id:
                for t_var in temp_variance:
                    for s_var in spatial_variance:
                        p_data[t_var][s_var][..., it_tp_flo] = 1

                rasMosaic_targ = rasMosaic_orig.copy()
                voxMosaic_targ = np.matmul(np.linalg.inv(vox2ras0_fs), rasMosaic_targ).astype('float32')#np.dot(np.linalg.inv(vox2ras0_fs), np.dotnp.dot(tp.vox2ras0, voxMosaic_targ))
                voxMosaic_targ = voxMosaic_targ[:3]

                del rasMosaic_targ

            else:

                rasMosaic_targ = rasMosaic_orig.copy()
                voxMosaic_targ = np.matmul(np.linalg.inv(tp_flo.vox2ras0), rasMosaic_targ).astype('float32')
                voxMosaic_targ = voxMosaic_targ[:3]

                voxMosaic_targ = voxMosaic_targ.reshape((1,3) + ref_shape)
                voxMosaic_targ = torch.from_numpy(voxMosaic_targ).float().to(device)

                im = torch.from_numpy(image_list[tp_flo.id][np.newaxis, np.newaxis]).float().to(device)
                im_resampled = interp_func(im, voxMosaic_targ)
                im_resampled = im_resampled[0, 0].cpu().detach().numpy()

                del voxMosaic_targ

                mean_im_2 = (im_resampled - image_list[tp.id]) ** 2

                del im_resampled

                mean_age_2 = (age_list[tp_flo.id] - age_list[tp.id]) ** 2
                for t_var in temp_variance:
                    for s_var in spatial_variance:
                        p_data[t_var][s_var][..., it_tp_flo] = np.exp(-0.5 / s_var * mean_im_2) \
                                                             * np.exp(-0.5 / t_var * mean_age_2)

                voxMosaic_targ = np.matmul(np.linalg.inv(vox2ras0_fs), rasMosaic_targ).astype('float32')
                voxMosaic_targ = voxMosaic_targ[:3]

                del rasMosaic_targ

            voxMosaic_targ = voxMosaic_targ.reshape((3,) + ref_shape)
            voxMosaic_targ_torch = voxMosaic_targ.copy()
            voxMosaic_targ_torch = torch.from_numpy(voxMosaic_targ_torch[np.newaxis]).float().to(device)

            del voxMosaic_targ

            seg = np.asarray(proxyseg.dataobj)
            seg_onehot = image_utils.one_hot_encoding(seg, categories=UNIQUE_LABELS).astype('float32')

            del seg

            seg_onehot = torch.from_numpy(seg_onehot[np.newaxis]).float().to(device)
            seg_resampled = interp_func(seg_onehot, voxMosaic_targ_torch)

            del seg_onehot, voxMosaic_targ_torch

            seg_resampled = np.transpose(seg_resampled[0].cpu().detach().numpy(), (1, 2, 3, 0))

            for t_var in temp_variance:
                for s_var in spatial_variance:
                    p_label[t_var][s_var] += p_data[t_var][s_var][..., it_tp_flo, np.newaxis] * seg_resampled

            del seg_resampled

        for t_var in temp_variance:
            for s_var in spatial_variance:
                p_label[t_var][s_var] = p_label[t_var][s_var] / np.sum(p_data[t_var][s_var], axis=-1, keepdims=True)

        return p_label

# def write_volume_results(volume_dict, filepath, fieldnames=None, attach_overwrite='a'):
#     if fieldnames is None:
#         fieldnames = ['TID'] + list(LABEL_DICT.keys())
#
#     with open(filepath, attach_overwrite) as csvfile:
#         csvwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
#         if attach_overwrite == 'w':
#             csvwriter.writeheader()
#         csvwriter.writerows(volume_dict)
#
# def get_vols_post(post):
#     n_labels = post.shape[-1]
#     vols = {}
#     for l in range(n_labels):
#         mask_l = post[..., l]
#         mask_l[post[..., l] < 0.05] = 0
#         vols[l] = np.sum(mask_l)
#
#     return vols
#
#
# def label_fusion(subject):
#     print('Subject: ' + str(subject.id))
#     timepoints = subject.timepoints
#     results_dir_sbj = subject.results_dirs.get_dir('longitudinal_segmentation_st_freesurfer') + '_AFF'
#
#     last_dir = join(results_dir_sbj, str(temp_variance[-1]) + '_' + str(spatial_variance[1]))
#     timepoints_to_run = timepoints[0:1]#list(filter(lambda x: not exists(join(last_dir, x.id + '.nii.gz')), timepoints))
#     attach_overwrite = 'a' if exists(join(last_dir, 'vols_st.txt')) else 'w'
#
#
#     # if not timepoints_to_run:
#     #     print('Subject: ' + str(subject.id) + '. DONE')
#     #     return
#
#     print('  o Reading the input files')
#     image_list = {}
#     age_list = {}
#     for tp in timepoints:
#         # Age
#         age_list[tp.id] = float(demo_dict[subject.id][tp.id]['AGE'])
#
#         # Data
#         seg = tp.load_seg()
#         image = tp.load_data()
#
#         # Normalize image
#         wm_mask = (seg == 2) | (seg == 41)
#         m = np.mean(image[wm_mask])
#         image = 110 * image / m
#         image_list[tp.id] = image
#
#         del image, seg, wm_mask
#
#     # Model
#
#     print('  o Computing the segmentation')
#     st_vols = {t_var: {sp_var: [] for sp_var in spatial_variance} for t_var in temp_variance}
#     for tp in timepoints_to_run:
#         print('        - Timepoint ' + tp.id, end=':', flush=True)
#
#         t_0 = time.time()
#         p_label_dict = compute_p_label(timepoints, image_list, age_list, tp, subject)
#         t_1 = time.time()
#         print(str(t_1-t_0) + ' seconds.')
#
#         proxy = nib.load(tp.init_path['resample'])
#         for t_var in temp_variance:
#             for s_var in spatial_variance:
#                 if not exists(join(results_dir_sbj, str(t_var) + '_' + str(s_var))):
#                     os.makedirs(join(results_dir_sbj, str(t_var) + '_' + str(s_var)))
#
#                 p_label = p_label_dict[t_var][s_var]
#                 p_label[np.isnan(p_label)] = 0
#                 mask = np.sum(p_label, axis=-1) > 0.5
#                 fake_vol = np.argmax(p_label, axis=-1).astype('uint16')
#                 true_vol = np.zeros_like(fake_vol)
#                 for it_ul, ul in enumerate(UNIQUE_LABELS): true_vol[fake_vol == it_ul] = ul
#                 true_vol = true_vol * mask
#
#                 img = nib.Nifti1Image(p_label, proxy.affine)
#                 nib.save(img, join(results_dir_sbj, str(t_var) + '_' + str(s_var), tp.id + '.post.nii.gz'))
#
#                 img = nib.Nifti1Image(true_vol, proxy.affine)
#                 nib.save(img, join(results_dir_sbj, str(t_var) + '_' + str(s_var), tp.id + '.nii.gz'))
#
#                 vols = get_vols_post(p_label)
#                 st_vols_dict = {k: vols[[it_ul for it_ul, ul in enumerate(UNIQUE_LABELS) if ul == val][0]] for k, val in LABEL_DICT.items() if val in UNIQUE_LABELS}
#                 st_vols_dict['TID'] = tp.id
#                 st_vols[t_var][s_var].append(st_vols_dict)
#
#                 del p_label, fake_vol, true_vol, mask
#
#         del p_label_dict
#
#     fieldnames = ['TID'] + list(LABEL_DICT.keys())
#     for t_var in temp_variance:
#         for s_var in spatial_variance:
#             write_volume_results(st_vols[t_var][s_var], join(results_dir_sbj, str(t_var) + '_' + str(s_var), 'vols_st.txt'),
#                                  fieldnames=fieldnames, attach_overwrite=attach_overwrite)
#
#     print('Subject: ' + str(subject.id) + '. DONE')
#

print('\n\n\n\n\n')
print('# -------------------------------------------- #')
print('# Running the longitudinal segmentation script #')
print('# -------------------------------------------- #')
print('\n\n')

#####################
# Global parameters #
#####################

parameter_dict_MRI = configFile.REGISTRATION_DIR
REScmd = NIFTY_REG_DIR + 'reg-apps' + '/reg_resample'
TRANSFORMcmd = NIFTY_REG_DIR + 'reg-apps' + '/reg_transform'

# Parameters
arg_parser = ArgumentParser(description='Computes the prediction of certain models')
arg_parser.add_argument('--subjects', default=None, nargs='+')
arg_parser.add_argument('--num_cores', default=1, type=int)
arg_parser.add_argument('--reg_algorithm', default='bidir', choices=['standard', 'bidir', 'niftyreg'])

arguments = arg_parser.parse_args()
initial_subject_list = arguments.subjects
num_cores = arguments.num_cores
reg_algorithm = arguments.reg_algorithm

FS_DIR = '/home/acasamitjana/Results/Registration/BrainAging/miriad_Eugenio/longitudinal'

##############
# Processing #
##############

demo_dict = read_demo_info(demo_fields=['AGE'])
data_loader = DataLoader(sid_list=initial_subject_list, linear=True)
parameter_dict = configFile.get_config_dict(data_loader.image_shape)

subject_list = data_loader.subject_list
subject_list = list(filter(lambda x: x.id in demo_dict.keys(), subject_list))

print('[LONGITUDINAL SEGMENTATION] Start processing.')
spatial_variance = [3**2, 5**2, 7**2, 9**2] # in grayscale
temp_variance = [100000]#[1/4, 1/2, 1, 2] #in years^2

segmenter = FS_Lin(demo_dict=demo_dict, parameter_dict=parameter_dict, reg_algorithm=reg_algorithm, device=device,
                   long_seg_algo='freesurfer_lineal', temp_variance=temp_variance, spatial_variance=spatial_variance)

if num_cores == 1:
    for subject in subject_list:
        segmenter.label_fusion(subject)

elif len(subject_list) == 1:
    segmenter.label_fusion(subject_list[0])

else:
    results = Parallel(n_jobs=num_cores)(delayed(segmenter.label_fusion)(subject) for subject in subject_list)


import random
import os

exit = False

while not exit:
    rand_num = random.randint(1,100)

    level = int(input('''
1. Easy
2. Hard
Choose level: '''))

    lives = 0

    if level == 1:
        lives = 10
    else:
        lives = 5

    game_over = False
    while lives != 0 and game_over != True:

        guess_num = int(input("Guess the number between (0-100): "))

        if guess_num == rand_num:
            print(f"Your Right, The number is {guess_num}")
            game_over = True
        elif guess_num < rand_num:
            print(f"The number is bigger than {guess_num}")
            lives -= 1
            print(f"you have {lives} lives left")

        elif guess_num > rand_num:
            print(f"The number is smaller than {guess_num}")
            lives -= 1
            print(f"you have {lives} lives left")

        if lives == 0:
            print("Game Over")
            game_over = True

    play_again = int(input("""
1. Play Again
2. Exit
Enter the Choice: """))
    if play_again == 1:
        os.system('clear')
        continue
    else:
        print("Exiting....")
        exit = True


#mic Programming Python implementation of Min Cost Path
# problem
#def searchIndex(i,j,base):

def Initialize(cost, Si, Sj, Gi, Gj,obstacle):
    #Si,Sj are the coordinates of startswith
    #Gi,Gj are the coordinates of Goal
    R = len(cost)
    C = len(cost[0])
    path = []
    #parameter check
    if (Si >= R) or (Gi >= R) or \
       (Sj >= C) or (Gj >= C):
            print("parametet error")
            exit()
    #initialize tc ： total cost table
    tc = [[obstacle for x in range(C)] for x in range(R)]#set the cost of unreachable point equal to obstacle
    tc[Si][Sj] = cost[Si][Sj]
    #initialize path: path in line with total cost
    path = [[[] for x in range(C)] for x in range(R)]
    #path[0][0] = [0,0]
    return R,C, tc, path

def LookAround(cost, tc, path, x,y,R,C,obstacle):
    #return a batter next hop if exist
    #return None if can not find better one
    if cost[x][y] == obstacle: #we dont care the path to obstacle
        return None
    advise = None
    #look up
    if (x-1) >= 0:
        #print("look up")
        if tc[x][y] > tc[x-1][y] + cost[x][y]:
            #prevent from loop
            if [x,y] not in path[x-1][y]:
                path[x][y] = path[x-1][y].copy()
                path[x][y].append([x-1,y])
                tc[x][y] = tc[x-1][y] + cost[x][y]
                advise = [x-1,y]
    #look down
    if (x+1) < R:
        #print("look down")
        if tc[x][y] > tc[x+1][y] + cost[x][y]:
            #prevent from loop
            if [x,y] not in path[x+1][y]:
                path[x][y] = path[x+1][y].copy()
                path[x][y].append([x+1,y])
                tc[x][y] = tc[x+1][y] + cost[x][y]
                advise = [x+1,y]
    #look left
    if (y-1) >= 0:
        #print("look left")
        if tc[x][y] > tc[x][y-1] + cost[x][y]:
            #prevent from loop
            if [x,y] not in path[x][y-1]:
                path[x][y] = path[x][y-1].copy()
                path[x][y].append([x,y-1])
                tc[x][y] = tc[x][y-1] + cost[x][y]
                advise = [x,y-1]

    #look right
    if (y+1) < C:
        #print("look right")
        if tc[x][y] > tc[x][y+1] + cost[x][y]:
            #prevent from loop
            if [x,y] not in path[x][y+1]:
                path[x][y] = path[x][y+1].copy()
                path[x][y].append([x,y+1])
                tc[x][y] = tc[x][y+1] + cost[x][y]
                advise = [x,y+1]

    return advise

def search(cost, Si, Sj, Gi, Gj,obstacle):
    R,C, tc, path = Initialize(cost, Si, Sj, Gi, Gj,obstacle)
    #searching util no update
    update = True
    advise = None
    cnt = 0
    while(update == True):
        update = False
        i = 0
        j = 0
        while(i < R):
            j = 0
            while(j < C):
                advise = LookAround(cost, tc, path, i,j,R,C,obstacle)
                if advise != None:
                    update = True
                j += 1
            i += 1
        cnt += 1
        #print(cnt)
    print("After " + str(cnt)+" times loop")
    #print(path)
    path[Gi][Gj].append([Gi,Gj])
    print(tc)
    print(path[Gi][Gj])
    return path[Gi][Gj]

def run(position, Tcost):
    print("start searching path")
    R = position[0][0]
    C = position[0][1]
    si = position[1][0]
    sj = position[1][1]
    gi = position[2][0]
    gj = position[2][1]
    #print(Tcost[0])
    ob = Tcost[0][2]
    maze = [[1 for x in range(C)] for x in range(R)]
    maze[si][sj] = 0
    for item in Tcost:
        maze[item[0]][item[1]] = ob
    path = search(maze, si, sj, gi, gj, ob)
    path = path[::-1]
    resp = str(path)
    step = len(path)
    resp = "200 ok {'steps': " + str(step) + ", 'path': [" + resp + "]}"
    print(resp)
    return resp
#inspired by:
#https://www.geeksforgeeks.org/min-cost-path-dp-6/


__author__ = 'Jacob Davis'

from extensions.interactions import base

class LogicProof(base.BaseInteraction):
    """Interaction for entering logic proofs."""

    name = 'Logic Proof'
    category = 'Mathematics'
    description = (
        'Allows learners to write proofs for simple logical statements.')
    display_mode = base.DISPLAY_MODE_SUPPLEMENTAL
    _dependency_ids = ['logic_proof', 'codemirror']
    _handlers = [{
        'name': 'submit', 'obj_type': 'CheckedProof'}]

    _customization_arg_specs = [{
        'name': 'question',
        'description': 'Question to ask.',
        'schema': {
            'type': 'custom',
            'obj_type': 'LogicQuestion',
        },
        'default_value': {
            'assumptions': [{
                'top_kind_name': 'variable',
                'top_operator_name': 'p',
                'arguments': [],
                'dummies': []
            }],
            'results': [{
                'top_kind_name': 'variable',
                'top_operator_name': 'p',
                'arguments': [],
                'dummies': []
            }],
            'default_proof_string': ''
        },
    }]