import numpy as np
from scipy.stats import lomax
from BaseModel import *

class Lomax(Base):
    def __init__(self, k = None, lmb = None, ti = None, xi = None):
        if ti is not None:
            self.train_org = ti
            self.train_inorg = xi
            self.newtonRh()
        else:
            self.train = []
            self.test = []
            self.train_org = []
            self.train_inorg = []
            self.k = k
            self.lmb = lmb
        self.params = [self.k, self.lmb]

    def determine_params(self, k, lmb, params):
        return super(Lomax, self).determine_params(k, lmb, params)

    def pdf(self,t,k=None,lmb=None,params=None):
        [k,lmb] = self.determine_params(k,lmb,params)
        return lmb*k/(1+lmb*t)**(k+1)

    def cdf(self,t,k=None,lmb=None,params=None):
        [k,lmb] = self.determine_params(k,lmb,params)
        return 1-(1+lmb*t)**-k

    def survival(self,t,k=None,lmb=None, params = None):
        [k,lmb] = self.determine_params(k,lmb,params)
        return (1+lmb*t)**-k

    def logpdf(self,t,k,lmb):
        return np.log(k) + np.log(lmb) - (k+1)*np.log(1+lmb*t)

    def logsurvival(self,t,k,lmb):
        return -k*np.log(1+lmb*t)

    def loglik(self,t,x,k=0.5,lmb=0.3):
        return sum(self.logpdf(t,k,lmb)) +sum(self.logsurvival(x,k,lmb))

    def grad(self,t,x,k=0.5,lmb=0.3):
        n = len(t)
        m = len(x)
        delk = n/k - sum(np.log(1+lmb*t)) - sum(np.log(1+lmb*x))
        dellmb = n/lmb -(k+1) * sum(t/(1+lmb*t)) -k*sum(x/(1+lmb*x))
        return np.array([delk,dellmb])

    def numerical_grad(self,t,x,k=None,lmb=None):
        if k is None or lmb is None:
            k = self.k
            lmb = self.lmb
        eps = 1e-5
        delk = (self.loglik(t,x,k+eps,lmb) - self.loglik(t,x,k-eps,lmb))/2/eps
        dellmb = (self.loglik(t,x,k,lmb+eps) - self.loglik(t,x,k,lmb-eps))/2/eps
        return np.array([delk,dellmb])

    def hessian(self,t,x,k=0.5,lmb=0.3):
        n=len(t)
        delksq = -n/k**2
        dellmbsq = -n/lmb**2 + (k+1)*sum((t/(1+lmb*t))**2) + k*sum((x/(1+lmb*x))**2)
        delklmb = -sum(t/(1+lmb*t)) - sum(x/(1+lmb*x))
        hess = np.zeros([2,2])
        hess[0,0] = delksq
        hess[1,1] = dellmbsq
        hess[0,1] = hess[1,0] = delklmb
        return hess

    def numerical_hessian(self,t,x,k=0.5,lmb=0.3):
        eps = 1e-4
        delksq = (self.loglik(t,x,k+2*eps,lmb) + self.loglik(t,x,k-2*eps,lmb) - 2*self.loglik(t,x,k,lmb))/4/eps/eps
        dellmbsq = (self.loglik(t,x,k,lmb+2*eps) + self.loglik(t,x,k,lmb-2*eps) - 2*self.loglik(t,x,k,lmb))/4/eps/eps
        dellmbk = (self.loglik(t,x,k+eps,lmb+eps) + self.loglik(t,x,k-eps,lmb-eps) - self.loglik(t,x,k+eps,lmb-eps) - self.loglik(t,x,k-eps,lmb+eps))/4/eps/eps
        hess = np.zeros([2,2])
        hess[0,0] = delksq
        hess[1,1] = dellmbsq
        hess[0,1] = hess[1,0] = dellmbk
        return hess

    def gradient_descent(self,numIter=2001, params = np.array([.5,.3])):
        for i in range(numIter):
            lik = self.loglik(self.train_org,self.train_inorg,params[0],params[1])
            directn = self.grad(self.train_org,self.train_inorg,params[0],params[1])
            params2 = params
            for alp1 in [1e-8,1e-7,1e-5,1e-3,1e-2,.1]:
                params1 = params + alp1 * directn
                if(min(params1) > 0):
                    lik1 = self.loglik(self.train_org,self.train_inorg,params1[0],params1[1])
                    if(lik1 > lik and np.isfinite(lik1)):
                        lik = lik1
                        params2 = params1
            params = params2
            if i%100 == 0:
                print("Iteration " + str(i) + " ,objective function: " + str(lik) + " \nparams = " + str(params) + " \nGradient = " + str(directn))
                print("\n########\n")
        return params

    def newtonRh(self, numIter=101, params = np.array([.1,.1])):
        for i in range(numIter):
            directn = self.grad(self.train_org,self.train_inorg,params[0],params[1])
            if sum(abs(directn)) < 1e-5:
                print("\nIt took: " + str(i) + " Iterations.\n Gradients - " + str(directn))
                self.params = params
                [self.k, self.lmb] = params
                return params
            lik = self.loglik(self.train_org,self.train_inorg,params[0],params[1])
            step = np.linalg.solve(self.hessian(self.train_org,self.train_inorg,params[0],params[1]),directn)
            params = params - step
            if min(params) < 0:
                print("Drastic measures")
                params = params + step # undo the effect of taking the step.
                params2 = params
                for alp1 in [1e-8,1e-7,1e-5,1e-3,1e-2,.1,.5,1.0]:
                    params1 = params - alp1 * step
                    if(max(params1) > 0):
                        lik1 = self.loglik(self.train_org,self.train_inorg,params1[0],params1[1])
                        if(lik1 > lik and np.isfinite(lik1)):
                            lik = lik1
                            params2 = params1
                            scale = alp1
                params = params2
            if i % 10 == 0:
                print("Iteration " + str(i) + " ,objective function: " + str(lik) + " \nparams = " + str(params) + " \nGradient = " + str(directn) + "\n##\n\n")
        [self.k, self.lmb] = params
        self.params = params
        return params

    def optimalWaitThreshold(self, Cint, k=None, lmb=None):
        if k is None or lmb is None:
            k = self.k
            lmb = self.lmb
        return (Cint*k - 1/lmb)

    def expectedDT(self,tau,k,lmb,C_int):
        return 1/lmb/(k-1) - (1/lmb/(k-1) + tau*k/(k-1))*1/(1+lmb*tau)**k + (tau + C_int)*1/(1+lmb*tau)**k

    @staticmethod
    def expectedDT_s(tau,k,lmb,C_int):
        return 1/lmb/(k-1) - (1/lmb/(k-1) + tau*k/(k-1))*1/(1+lmb*tau)**k + (tau + C_int)*1/(1+lmb*tau)**k

    def expectedT(self,tau,k=None,lmb=None,params=None):
        [k,lmb] = self.determine_params(k,lmb,params)
        return (1/lmb/(k-1) - (1/lmb/(k-1) + tau*k/(k-1))*1/(1+lmb*tau)**k)/(1-1/(1+lmb*tau)**k)

    def samples(self, k=None, lmb=None, size = 1000, params = None):
        [k, lmb] = self.determine_params(k, lmb, params)
        return lomax.rvs(c=k, scale=(1 / lmb), size=size)

    @staticmethod
    def samples_s(k, lmb, size = 1000):
        return lomax.rvs(c=k, scale=(1 / lmb), size=size)

    def kappafn_k(self,t,x,lmb=0.1):
        n = len(t)
        return n/(sum(np.log(1+lmb*t)) + sum(np.log(1+lmb*x)))

    def kappafn_lmb(self,t,x,lmb=0.1):
        n = len(t)
        return (n/lmb - sum(t/(1+lmb*t)))/(sum(t/(1+lmb*t)) + sum(x/(1+lmb*x)))

    def bisection_fn(self,lmb=0.1):
        return self.kappafn_k(self.train_org,self.train_inorg,lmb) - self.kappafn_lmb(self.train_org,self.train_inorg,lmb)

    def bisection(self,a=1e-6,b=2000):
        n=1
        while n < 10000:
            c=(a+b)/2
            if self.bisection_fn(c) == 0 or (b-a)/2 < 1e-6:
                return c
            n=n+1
            if (self.bisection_fn(c) > 0) == (self.bisection_fn(a) > 0):
                a=c
            else:
                b=c


from datetime import datetime
from time import strptime
from django.db.models.signals import post_save
from django.dispatch import receiver
from bank.models import SavingPlan, BankAccountLog, ProcessedTransactionId, BankAccount, ScheduledTask
from bank.schedule import activate_plan_on, terminate_plan_on

def cal_rem_days(end_date):
    today = strptime(str(datetime.now().date()), '%Y-%m-%d').tm_yday
    ending_date = strptime(str(end_date), '%Y-%m-%d').tm_yday
    rem_days = ending_date-today
    if rem_days > 0:
        return False
    else:
        return True

def create_plan_engine(*args):
    schedule = ScheduledTask(account=args[0], activation_date=args[4], termination_date=args[5])
    schedule.save()
    if args[4] == args[6]:
        new_plan = SavingPlan(account_number=args[0], sender_account=args[1], plan_name=args[2],
                              deduction_amount=args[3], start_date=args[4], end_date=args[5],
                              status=True)
        new_plan.save()
        terminate_plan_on(args[5])
    else:
        new_plan = SavingPlan(account_number=args[0], sender_account=args[1], plan_name=args[2],
                              deduction_amount=args[3], start_date=args[4], end_date=args[5])
        new_plan.save()
        activate_plan_on(args[4])
        terminate_plan_on(args[5])

def saving_plan_engine(self, sender, amount):
    plans = SavingPlan.objects.all().filter(account_number=self, sender_account=sender)
    for plan in plans:
        if plan.status:
            if plan.deduction_amount >= float(str(amount)):
                log = BankAccountLog(receiver=self, sender=sender, saving_plan=plan.plan_name,
                                     amount=amount)
            else:
                log = BankAccountLog(receiver=self, sender=sender, saving_plan=plan.plan_name,
                                     amount=plan.deduction_amount)
            log.save()
        else:
            pass

def main_bank_engine(self):
    for log in self:
        log_receiver = int(str(log.receiver))
        account = BankAccount.objects.get(account_number=log_receiver)
        balance = account.account_balance
        processed_log = ProcessedTransactionId(account=account, processed_by_bank_account=log.transaction_id)
        processed_log.save()
        if log.saving_plan is None:
            balance += log.amount
            account.account_balance = str(balance)
        else:
            plan = SavingPlan.objects.get(plan_name=log.saving_plan)
            plan_balance = plan.current_balance
            plan_balance += log.amount
            plan.current_balance = str(plan_balance)
            plan.save()
            balance -= log.amount
            account.account_balance = str(balance)
        account.save()

@receiver(post_save, sender=BankAccountLog)
def bank_engine_caller(sender, **kwargs):
    logs = BankAccountLog.objects.all()
    processed_logs = ProcessedTransactionId.objects.all()
    if len(processed_logs) == 0:
        main_bank_engine(logs)
    else:
        for processed_log in processed_logs:
            logs = logs.exclude(transaction_id=processed_log.processed_by_bank_account)
        main_bank_engine(logs)


#Done by Carlos Amaral in 29/06/2020

"""
Write a function called make_album() that builds a dictionary
describing a music album. The function should take in an artist name and an
album title, and it should return a dictionary containing these two pieces of
information. Use the function to make three dictionaries representing different
albums. Print each return value to show that the dictionaries are storing the
album information correctly.
Use None to add an optional parameter to make_album() that allows you to
store the number of songs on an album. If the calling line includes a value for
the number of songs, add that value to the album’s dictionary. Make at least
one new function call that includes the number of songs on an album.
"""

#Album
#1st version
def make_album(artist_name, album_title):
    """Returns the name of the album and it's title."""
    album_discription = f"{artist_name}, {album_title}"
    return album_discription.title()

album = make_album('Cocteau Twins', 'Four Calendar Cafe')
album2 = make_album('Oasis', '(Whats the story) Morning Glory?')
album3 = make_album('Portishead', 'Dummy')
print(album)
print(album2)
print(album3)

print("\n")

def make_album(artist_name, album_title, songs_number):
    """Returns the name of the album and it's title."""
    album_discription = f"{artist_name}, {album_title}, {songs_number}"
    return album_discription.title()

album = make_album('Cocteau Twins', 'Four Calendar Cafe', '10')
album2 = make_album('Oasis', '(Whats the story) Morning Glory?', '12')
album3 = make_album('Portishead', 'Dummy', '11')
print(album)
print(album2)
print(album3)


import config
import telebot
#import put_new_words as load
#import common_function as api

bot = telebot.TeleBot(config.token)

@bot.message_handler(commands = ['help'])
def help(message):
	cid = message.chat.id
	cmd = ['/start - начать тренировку','/next - показать следующую карточку','/correct - исправить перевод','/today - показать все слова за сегодня','/load - загрузить еще карточек','/help - список команд', '/dev - написать разработчикам']
	v_text = 'Доступные команды: \n'+'\n'.join(cmd)
	bot.send_message(cid, v_text)

if __name__ == '__main__':
	bot.polling(none_stop=True, timeout=500)


from cement.core import controller
from lib.podi.rpc.player import pause_unpause_player, list_active_players

class PauseController(controller.CementBaseController):
    """
    Sends RPC calls to Kodi to pause playback of media items.
    """

    class Meta:
        """
        Defines metadata for use by the Cement framework.
        """

        label = 'pause'
        aliases = ['unpause']
        description = 'Pause/unpause the current media item'
        stacked_on = 'base'
        stacked_type = 'nested'

    @controller.expose(hide=True)
    def default(self):
        """
        Instructs Kodi to pause the current media item.
        """

        for player in self.app.send_rpc_request(list_active_players()):
            self.app.log.info("Pausing/unpausing {0}".format(player['type']))
            self.app.send_rpc_request(pause_unpause_player(player['playerid']))


from farcaster import Warpcast
from farcaster.models import Parent

from ditti.commands.text2img import Text2Img

class Thread:
    def __init__(self, fcc: Warpcast):
        self.fcc = fcc
        self.t2i = Text2Img()

    # Will break if a parent is deleted, but that's a problem for another day
    def start_thread(self, call_cast):
        if call_cast.parent_hash is None:
            thread_text = call_cast.text
            imgur_link = self.t2i.convert(
                thread_text, color="grey", image_file="hello.png"
            )
            final_t_cast = "@{0} requested this cast as an image: {1}".format(
                call_cast.author.username, imgur_link
            )
            parent = Parent(fid=call_cast.author.fid, hash=call_cast.hash)
            return final_t_cast, parent
        else:
            call_parent = self.fcc.get_cast(call_cast.parent_hash)
            author = call_parent.cast.author.username
            parent_hash = call_parent.cast.hash
            thread_text = ""
            if parent_hash is None:
                thread_text = f"{call_parent.cast.text}\n\n"
            last_parent_hash = parent_hash
            while parent_hash:
                parent_cast = self.fcc.get_cast(parent_hash)
                if parent_cast.cast.author.username == author:
                    thread_text = f"{parent_cast.cast.text}\n\n" + thread_text
                    last_parent_hash = parent_hash
                    parent_hash = parent_cast.cast.parent_hash or ""
                else:
                    break
            imgur_link = self.t2i.convert(
                thread_text, color="grey", image_file="hello.png"
            )
            final_t_cast = "@{0} requested this thread as an image: {1}".format(
                call_cast.author.username, imgur_link
            )
            parent_cast = self.fcc.get_cast(hash=last_parent_hash)
            parent = Parent(fid=parent_cast.cast.author.fid, hash=last_parent_hash)
            return final_t_cast, parent


from itertools import takewhile
from datetime import datetime
import os
import re

def _format_filename(filename):
    datetime_ = datetime.now()
    date = datetime_.strftime("%Y%m%d")
    time = datetime_.strftime("%H%M%S")
    datetime_ = "{}_{}".format(date, time)
    return filename.format(datetime_, datetime=datetime_, date=date, time=time)

class PatternFactory:
    """Transforms strings composed of * and ** to matches on strings with
    particular separator"""
    def __init__(self, separator):
        separator = re.escape(separator)
        self.substitutions = {"*":  r"[^{}]*".format(separator),
                              "**": r".*"}

    def _substitute(self, match):
        match = match.group()
        return self.substitutions.get(match, match)

    def create_regex(self, pattern):
        pattern = pattern.replace(".", r"\.")
        pattern = re.sub(r"\*+", self._substitute, pattern)
        return re.compile("^{}$".format(pattern))

_factory = PatternFactory("/")

def find_files(filename, base_dir=""):
    """Given a filename/dirname/pattern, returns matching files on the system"""
    if isinstance(filename, list):
        files = [find_files(file, base_dir=base_dir) for file in filename]
        files = sorted(set(sum(files, [])))
        return files
    if os.path.isdir(filename):
        filename = filename+"/**"
    sections = re.split(r"/+", filename)

    root = tuple(takewhile(lambda section: "*" not in section, sections[:-1]))
    pattern = sections[len(root):]
    recursive = len(pattern) > 1 or any("**" in p for p in pattern)

    pattern = "/".join(pattern)
    root = os.sep.join(root)
    _root = (root if root else ".") + os.sep
    if base_dir:
        _root = os.path.join(base_dir, _root)
    pattern = _factory.create_regex(pattern)

    lst = []
    prefix_length = len(_root)
    for dirpath, _dirnames, filenames in os.walk(_root, topdown=True,
                                                 followlinks=True):
        dirpath = dirpath[prefix_length:]
        for filename in filenames:
            path = os.path.join(dirpath, filename)
            complete_path = os.path.join(root, path)
            matchable_path = path.replace(os.sep, "/")
            match = pattern.match(matchable_path)
            if match is not None:
                lst.append(complete_path)
        if not recursive:
            break
    lst.sort()
    return lst


from __future__ import division

import six

import datetime
import os
import random
import shutil
import string
import tempfile
import subprocess
import sys

import requests

import verta
from verta import Client
from verta._internal_utils import _utils

import hypothesis
import pytest
from . import utils

RANDOM_SEED = 0
INPUT_LENGTH = 12  # length of iterable input fixture

DEFAULT_HOST = None
DEFAULT_PORT = None
DEFAULT_EMAIL = None
DEFAULT_DEV_KEY = None

# hypothesis on Jenkins is apparently too slow
hypothesis.settings.register_profile("default", suppress_health_check=[hypothesis.HealthCheck.too_slow])
hypothesis.settings.load_profile("default")

def pytest_addoption(parser):
    parser.addoption("--oss", action="store_true", help="run OSS-compatible tests")

def pytest_collection_modifyitems(config, items):
    if config.getoption("--oss"):
        skip_not_oss = pytest.mark.skip(reason="not available in OSS")
        for item in items:
            if 'not_oss' in item.keywords:
                item.add_marker(skip_not_oss)
    else:
        skip_oss = pytest.mark.skip(reason="only applicable to OSS")
        for item in items:
            if 'oss' in item.keywords:
                item.add_marker(skip_oss)

@pytest.fixture(scope='session')
def host():
    return os.environ.get("VERTA_HOST", DEFAULT_HOST)

@pytest.fixture(scope='session')
def port():
    return os.environ.get("VERTA_PORT", DEFAULT_PORT)

@pytest.fixture(scope='session')
def email():
    return os.environ.get("VERTA_EMAIL", DEFAULT_EMAIL)

@pytest.fixture(scope='session')
def dev_key():
    return os.environ.get("VERTA_DEV_KEY", DEFAULT_DEV_KEY)

@pytest.fixture(scope='session')
def email_2():
    # For collaboration tests
    return os.environ.get("VERTA_EMAIL_2")

@pytest.fixture(scope='session')
def dev_key_2():
    # For collaboration tests
    return os.environ.get("VERTA_DEV_KEY_2")

@pytest.fixture
def seed():
    return RANDOM_SEED

@pytest.fixture
def nones():
    return [None]*INPUT_LENGTH

@pytest.fixture
def bools(seed):
    random.seed(seed)
    return [bool(random.randint(0, 1)) for _ in range(INPUT_LENGTH)]

@pytest.fixture
def floats(seed):
    random.seed(seed)
    return [random.uniform(-3**2, 3**3) for _ in range(INPUT_LENGTH)]

@pytest.fixture
def ints(seed):
    random.seed(seed)
    return [random.randint(-3**4, 3**5) for _ in range(INPUT_LENGTH)]

@pytest.fixture
def strs(seed):
    """no duplicates"""
    random.seed(seed)
    gen_str = lambda: ''.join(random.choice(string.ascii_letters) for _ in range(INPUT_LENGTH))
    result = set()
    while len(result) < INPUT_LENGTH:
        single_str = gen_str()
        while single_str in result:
            single_str = gen_str()
        else:
            result.add(single_str)
    return list(result)

@pytest.fixture
def flat_lists(seed, nones, bools, floats, ints, strs):
    random.seed(seed)
    values = (nones, bools, floats, ints, strs)
    return [
        [
            values[random.choice(range(len(values)))][i]
            for i in range(INPUT_LENGTH)
        ]
        for _ in range(INPUT_LENGTH)
    ]

@pytest.fixture
def flat_dicts(seed, nones, bools, floats, ints, strs):
    random.seed(seed)
    values = (nones, bools, floats, ints, strs)
    return [
        {
            strs[i]: values[random.choice(range(len(values)))][i]
            for i in range(INPUT_LENGTH)
        }
        for _ in range(INPUT_LENGTH)
    ]

@pytest.fixture
def nested_lists(seed, nones, bools, floats, ints, strs):
    random.seed(seed)
    values = (nones, bools, floats, ints, strs)
    flat_values = [value for type_values in values for value in type_values]
    def gen_value(p=1):
        if random.random() < p:
            return [
                gen_value(p/2)
                for _ in range(random.choice(range(4)))
            ]
        else:
            return random.choice(flat_values)
    return [
        [
            gen_value()
            for _ in range(random.choice(range(3))+1)
        ]
        for _ in range(INPUT_LENGTH)
    ]

@pytest.fixture
def nested_dicts(seed, nones, bools, floats, ints, strs):
    random.seed(seed)
    values = (nones, bools, floats, ints, strs)
    flat_values = [value for type_values in values for value in type_values]
    def gen_value(p=1):
        if random.random() < p:
            return {
                key: gen_value(p/2)
                for key, _ in zip(strs, range(random.choice(range(4))))
            }
        else:
            return random.choice(flat_values)
    return [
        {
            key: gen_value()
            for key, _ in zip(strs, range(random.choice(range(3))+1))
        }
        for _ in range(INPUT_LENGTH)
    ]

@pytest.fixture
def scalar_values(nones, bools, floats, ints, strs):
    return [type_values[0]
            for type_values in (nones, bools, floats, ints, strs)]

@pytest.fixture
def collection_values(flat_lists, flat_dicts, nested_lists, nested_dicts):
    return [type_values[0]
            for type_values in (flat_lists, flat_dicts, nested_lists, nested_dicts)]

@pytest.fixture
def all_values(scalar_values, collection_values):
    return scalar_values + collection_values

@pytest.fixture(scope='session')
def output_path():
    dirpath = ".outputs"
    while len(dirpath) < 1024:
        try:  # avoid name collisions
            os.mkdir(dirpath)
        except OSError:
            dirpath += '_'
        else:
            yield os.path.join(dirpath, "{}")
            break
    else:
        raise RuntimeError("dirpath length exceeded 1024")
    shutil.rmtree(dirpath)

@pytest.fixture
def dir_and_files(strs, tmp_path):
    """
    Creates nested directory of empty files.

    Returns
    -------
    dirpath : str
    filepaths : set of str

    """
    filepaths = {
        os.path.join(strs[0], strs[1], strs[2]),
        os.path.join(strs[0], strs[1], strs[3]),
        os.path.join(strs[0], strs[2]),
        os.path.join(strs[0], strs[4]),
        os.path.join(strs[2]),
        os.path.join(strs[5]),
    }

    for filepath in filepaths:
        p = tmp_path / filepath
        p.parent.mkdir(parents=True, exist_ok=True)
        p.touch()

    return str(tmp_path), filepaths

@pytest.fixture
def tempdir_root():
    return os.environ.get("TEMPDIR_ROOT")

@pytest.fixture
def in_tempdir(tempdir_root):
    """Moves test to execute inside a temporary directory."""
    dirpath = tempfile.mkdtemp(dir=tempdir_root)
    try:
        with utils.chdir(dirpath):
            yield dirpath
    finally:
        shutil.rmtree(dirpath)

@pytest.fixture
def client(host, port, email, dev_key):
    print("[TEST LOG] test setup begun {} UTC".format(datetime.datetime.utcnow()))
    client = Client(host, port, email, dev_key, debug=True)

    yield client

    proj = client._ctx.proj
    if proj is not None:
        proj.delete()

    print("[TEST LOG] test teardown completed {} UTC".format(datetime.datetime.utcnow()))

@pytest.fixture
def client_2(host, port, email_2, dev_key_2):
    """For collaboration tests."""
    if not (email_2 and dev_key_2):
        pytest.skip("second account credentials not present")
    print("[TEST LOG] test setup begun {} UTC".format(datetime.datetime.utcnow()))

    client = Client(host, port, email_2, dev_key_2, debug=True)

    yield client

    print("[TEST LOG] test teardown completed {} UTC".format(datetime.datetime.utcnow()))

@pytest.fixture
def experiment_run(client):
    proj = client.set_project()
    print("[TEST LOG] Project ID is {}".format(proj.id))
    client.set_experiment()
    run = client.set_experiment_run()
    print("[TEST LOG] Run ID is {}".format(run.id))

    return run

@pytest.fixture
def model_for_deployment(strs):
    np = pytest.importorskip("numpy")
    pd = pytest.importorskip("pandas")
    sklearn = pytest.importorskip("sklearn")
    from sklearn import linear_model

    num_rows, num_cols = 36, 6

    data = pd.DataFrame(np.tile(np.arange(num_rows).reshape(-1, 1),
                                num_cols),
                        columns=strs[:num_cols])
    X_train = data.iloc[:,:-1]  # pylint: disable=bad-whitespace
    y_train = data.iloc[:, -1]

    return {
        'model': sklearn.linear_model.LogisticRegression(),
        'model_api': verta.utils.ModelAPI(X_train, y_train),
        'requirements': six.StringIO("scikit-learn=={}".format(sklearn.__version__)),
        'train_features': X_train,
        'train_targets': y_train,
    }

@pytest.fixture
def repository(client):
    name = _utils.generate_default_name()
    repo = client.get_or_create_repository(name)

    yield repo

    repo.delete()

@pytest.fixture
def commit(repository):
    commit = repository.get_commit()

    yield commit

@pytest.fixture
def created_datasets(client):
    """Container to track and clean up Datasets created during tests."""
    created_datasets = []

    yield created_datasets

    datasets_conn = {}  # prevent duplication
    for dataset in created_datasets:
        datasets_conn[dataset.id] = dataset._conn

    for dataset_id in datasets_conn:
        utils.delete_datasets([dataset_id], datasets_conn[dataset_id])

@pytest.fixture
def registered_model(client):
    model = client.get_or_create_registered_model()
    yield model
    model.delete()

@pytest.fixture
def created_registered_models():
    """Container to track and clean up `RegisteredModel`s created during tests."""
    to_delete = []

    yield to_delete

    for registered_model in to_delete:
        registered_model.delete()

@pytest.fixture
def model_version(registered_model):
    yield registered_model.get_or_create_version()

@pytest.fixture
def created_endpoints():
    to_delete = []

    yield to_delete

    for endpoint in to_delete:
        endpoint.delete()

@pytest.fixture
def endpoint(client, created_endpoints):
    path = _utils.generate_default_name()
    endpoint = client.create_endpoint(path)
    created_endpoints.append(endpoint)

    yield endpoint

@pytest.fixture
def created_endpoints():
    to_delete = []

    yield to_delete

    for endpoint in to_delete:
        endpoint.delete()

@pytest.fixture
def organization(client):
    workspace_name = _utils.generate_default_name()
    org = client._create_organization(workspace_name)

    yield org

    org.delete()

@pytest.fixture
def requirements_file():
    with tempfile.NamedTemporaryFile('w+') as tempf:
        # create requirements file from pip freeze
        pip_freeze = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
        pip_freeze = six.ensure_str(pip_freeze)
        tempf.write(pip_freeze)
        tempf.flush()  # flush object buffer
        os.fsync(tempf.fileno())  # flush OS buffer
        tempf.seek(0)

        yield tempf


class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        for _ in range(k % len(nums)):
            elem = nums.pop()
            nums.insert(0, elem)

# reverse the first n - k elements
# reverse the rest of them
# reverse the entire array
class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        end = len(nums) - 1
        k = k % len(nums)
        self.reverse(nums, 0, end - k)
        self.reverse(nums, end - k + 1, end)
        self.reverse(nums, 0, end)
        return nums

    def reverse(self, nums, start, end):
        while start < end:
            nums[start], nums[end] = nums[end], nums[start]
            start += 1
            end -= 1


# https://atcoder.jp/contests/ABC279/tasks/abc279_e
# # def input(): return sys.stdin.readline().rstrip()
# # input = sys.stdin.readline
# from numba import njit
# from functools import lru_cache

# import sys
# input = sys.stdin.buffer.readline
# sys.setrecursionlimit(10 ** 7)

class UnionFind():
    """ Union-Find木の実装（ランクあり） """
    def __init__(self, n):
        self.n = n
        self.parent = [-1]*(n+1)    # parent 親 マイナスだったら根で、絶対値が集合の数
        self.rank   = [0]*(n+1)     # rank 深さ

    def root(self, x):
        """ 木の根を求める """
        if self.parent[x] < 0:      # xが根
            return x
        else:
            self.parent[x] = self.root(self.parent[x])  # 経路圧縮
            return self.parent[x]

    def unite(self, x, y):
        """ xとyの属する集合を併合 """
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return 0
        elif self.rank[x] > self.rank[y]:
            self.parent[x] += self.parent[y]
            self.parent[y] = x
        else:
            self.parent[y] += self.parent[x]
            self.parent[x] = y
            if self.rank[x] == self.rank[y]:
                self.rank[y] += 1

    def isSame(self, x, y):
        """ xとyが同じ集合に属するか否か """
        return self.root(x) == self.root(y) or x==y

    def size(self, x):
        """ xと同じ集合に属する数 """
        return -self.parent[self.root(x)]

N, Q = map(int, input().split())
box = dict(zip(range(N), range(N)))
roots = dict(zip(range(N), range(N)))
# print(box)
uf = UnionFind(N+Q)
now = N
for i in range(Q):
    query = input()
    # print(query)
    if query[0]=='1':
        t, x, y = map(int, query.split())
        if box[y-1]==-1:
            continue
        elif box[x-1]==-1:
            rt = box[y-1]
        else:
            uf.unite(box[y-1], box[x-1])
            rt = uf.root(box[x-1])
        box[x-1] = rt
        roots[rt] = x-1
        box[y-1] = -1
    elif query[0]=='2':
        t, x = map(int, query.split())
        uf.unite(now, box[x-1])
        rt = uf.root(now)
        box[x-1] = rt
        roots[rt] = x-1
        now += 1
        # print(now, rt)
    else:
        t, x = map(int, query.split())
        rt = uf.root(x-1)
        # print(x-1, rt, box, roots)
        print(roots[rt]+1)
    # print(now, box)

# S = input()
# N = int(input())
# N, K = map(int, input().split())
# A = list(map(int, (input().split())))
# A = [[int(i) for i in input().split()] for _ in range(N)]

# import sys
# it = map(int, sys.stdin.buffer.read().split())
# N = next(it)

# @njit('(i8,i8[::1],i4[::1])', cache=True)
# def main():
#     @lru_cache(None)
#     def dfs():
#         return
#     return

# main()


import cv2
from PIL import Image # Pillow
from numpy import asarray
import dlib

# https://pyimagesearch.com/2021/04/19/face-detection-with-dlib-hog-and-cnn/
# Thư viện dlib được cho là một trong những gói được sử dụng nhiều nhất để nhận dạng khuôn mặt.
# Một gói Python được đặt tên thích hợp face_recognition kết hợp các chức năng nhận dạng khuôn
# mặt của dlib thành một API đơn giản, dễ sử dụng.

def convert_and_trim_bb(image, rect):
    # extract the starting and ending (x, y)-coordinates of the
    # bounding box
    startX = rect.left()
    startY = rect.top()
    endX = rect.right()
    endY = rect.bottom()
    # ensure the bounding box coordinates fall within the spatial
    # dimensions of the image
    startX = max(0, startX)
    startY = max(0, startY)
    endX = min(endX, image.shape[1])
    endY = min(endY, image.shape[0])
    # compute the width and height of the bounding box
    w = endX - startX
    h = endY - startY
    # return our bounding box coordinates
    return (startX, startY, w, h)

# load dlib's HOG + Linear SVM face detector
print("[INFO] loading HOG + Linear SVM face detector...")
detector = dlib.get_frontal_face_detector()

# file = "./dataset/TRAIN_VN_500p_6_8i/1020/1.png"
file = "./face_test/Unknow/psg_team_1.jpg"

# tải hình ảnh
# image = Image.open(file)
# # chuyển đổi sang RGB, nếu cần
# image = image.convert('RGB')
# # chuyển đổi sang array
# pixels = asarray(image)

# rects = detector(pixels)
# print(rects)

# boxes = [convert_and_trim_bb(pixels, r) for r in rects]
# # loop over the bounding boxes
# for (x, y, w, h) in boxes:
# 	# draw the bounding box on our image
# 	cv2.rectangle(pixels, (x, y), (x + w, y + h), (255, 0, 0), 2)
# # show the output image
# cv2.imshow("Output", pixels)
# cv2.waitKey(0)


import mosek
import numpy
import sys

from mosek.fusion   import *
from portfolio_data import *

def MarkowitzWithTransactionsCost(n,mu,GT,x0,w,gamma,f,g):
    # Upper bound on the traded amount
    w0 = w+sum(x0)
    u = n*[w0]

    with Model("Markowitz portfolio with transaction costs") as M:
        x = M.variable("x", n, Domain.greaterThan(0.0))
        z = M.variable("z", n, Domain.unbounded())
        y = M.variable("y", n, Domain.binary())

        #  Maximize expected return
        M.objective('obj', ObjectiveSense.Maximize, Expr.dot(mu,x))

        # Invest amount + transactions costs = initial wealth
        M.constraint('budget', Expr.add([ Expr.sum(x), Expr.dot(f,y),Expr.dot(g,z)] ), Domain.equalsTo(w0))

        # Imposes a bound on the risk
        M.constraint('risk', Expr.vstack( gamma,Expr.mul(GT,x)), Domain.inQCone())

        # z >= |x-x0|
        M.constraint('buy', Expr.sub(z,Expr.sub(x,x0)),Domain.greaterThan(0.0))
        M.constraint('sell', Expr.sub(z,Expr.sub(x0,x)),Domain.greaterThan(0.0))

        # Constraints for turning y off and on. z-diag(u)*y<=0 i.e. z_j <= u_j*y_j
        M.constraint('y_on_off', Expr.sub(z,Expr.mulElm(u,y)), Domain.lessThan(0.0))

        # Integer optimization problems can be very hard to solve so limiting the
        # maximum amount of time is a valuable safe guard
        M.setSolverParam('mioMaxTime', 180.0)
        M.solve()

        print('Expected return: %.4e Std. deviation: %.4e Transactions cost: %.4e' % \
              (numpy.dot(mu,x.level()),gamma,numpy.dot(f,y.level())+numpy.dot(g,z.level())))

if __name__ == '__main__':
    f = n*[0.01]
    g = n*[0.001]
    MarkowitzWithTransactionsCost(n,mu,GT,x0,w,gamma,f,g)


from string import Template
import datetime

def stringify_user(user):
    return u"%s %s" % (user['name'], user['surname'])
class Writer(object):
    def __init__(self, filename):
        self.handle = open(filename, "w")

    def start(self, user):
        html = u'''<!html >

                  <title>Sarakste ar $user</title>
                  <meta http-equiv="Content-Type" value="text/html; charset=utf-8" />

$user

                '''
        self.user = stringify_user(user)
        html = Template(html).substitute(user = self.user)
        self.handle.write(html.encode("utf-8"))
    def write(self, message,):
        html = u'''
$type $user

$time

$subject

$text
'''
        if message['type'] == 'inbox':
            type = u'no'
            message['user'] = stringify_user(message['user'])
        else:
            type = u'kam'
            message['user'] = self.user
        html = Template(html).substitute(user = message['user'],
                                        time = datetime.datetime.fromtimestamp(int(message['timestamp'])).isoformat(),
                                        subject = message['title'],
                                        text = message['text'],
                                        type = type)

        self.handle.write(html.encode("utf-8"))
    def end(self):
        html = ''''''
        self.handle.write(html)
        self.handle.close()


#!/usr/bin/env python

import pygame
import os
from rational import rational
from random import choice

pygame.init()

#For Compiling
def resource_path(relative_path):
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

#Basic Information
CAPTION = "Physical pi calculator"
ICON = resource_path("icon.png")
WIDTH = 640
HEIGHT = 360
TARGET_FRAME_RATE = 144
MAGNIFYING_RATE = 60

#Colors
BLACK   = (  0,   0,   0)
RED     = (255,   0,   0)
GREEN   = (  0, 255,   0)
BLUE    = (  0,   0, 255)
YELLOW  = (255, 255,   0)
MAGENTA = (255,   0, 255)
CYAN    = (  0, 255, 255)
WHITE   = (255, 255, 255)

#Extended Colors
LIGHT_GRAY  = (240, 240, 240)
LIGHT_GREEN = (144, 238, 144)
DARK_GRAY   = (120, 120, 120)

#Preset
RUNNING = True
WINDOW = pygame.display
WINDOW.set_caption(CAPTION)
WINDOW.set_icon(pygame.image.load(ICON))
SCREEN = WINDOW.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)

#Global Variables
FLOOR_HEIGHT = HEIGHT // 4
WALL_THICKNESS = 80
PAUSED = True
STATUS = "Simulate"
TEXT_BOX_INFO = {"Size": "", "Mass": "", "Position": "", "Velocity": "", "Color": ""}
ERROR_MESSAGE_TIMER = 0
PAUSE_BUTTON_FLAG = True
ERROR_MESSAGE = ""
CLICKED_TEXT_BUTTON = None
SPEED = 1

COLLISION = 0
COLLISION_TIMER = rational(0)
PAST_COLLIDE = 0
PRED_COLLIDER = None

collider = []

#Classes
class box():
    def __init__(self, length: rational, mass: rational, position: rational, velocity: rational, color: tuple):
        self.length = length
        self.mass = mass
        self.position = position
        self.velocity = velocity
        self.color = color
    def __repr__(self):
        return "Box{%skg, %sm, %sm/s, Color: %s}" % (mass, position, velocity, color)
    def info(self):
        return (self.length, self.mass, self.position, self.velocity, self.color)
    def update(self, colider: list):
        pass
    def render(self):
        pygame.draw.rect(SCREEN, self.color, [float(WALL_THICKNESS + self.position * MAGNIFYING_RATE), float(HEIGHT - FLOOR_HEIGHT - self.length * MAGNIFYING_RATE), float(self.length * MAGNIFYING_RATE), float(self.length * MAGNIFYING_RATE)])
    def copy(self):
        return box(self.length, self.mass, self.position, self.velocity, self.color)

#Functions
def print_text(text = "", pos = (0, 0), center_align = False, font = None, font_size = 18, color = BLACK, alpha = 255):
    split_text = list(text.split("\n"))
    font = pygame.font.SysFont(font, font_size)
    for i in range(len(split_text)):
        txt = font.render(split_text[i], True, color)
        txt.set_alpha(alpha)
        if center_align:
            rect = txt.get_rect()
            rect.center = (pos[0], pos[1] + (2 * i - len(split_text) + 1) * font_size // 2)
            SCREEN.blit(txt, rect)
        else:
            SCREEN.blit(txt, (pos[0], pos[1] + font_size * i))

def FLOOR_relocation():
    global FLOOR_HEIGHT
    FLOOR_HEIGHT = HEIGHT // 4

def render_restart_button():
    pygame.draw.rect(SCREEN, RED, [WALL_THICKNESS // 8, WALL_THICKNESS // 8, WALL_THICKNESS * 3 // 4, WALL_THICKNESS * 3 // 8], 0, WALL_THICKNESS * 3 // 24)
    print_text("RS", (WALL_THICKNESS // 2, WALL_THICKNESS * 5 // 16), True, None, 24, WHITE)

def restart_button_clicked():
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()[0]
    if click and WALL_THICKNESS // 8 <= mouse[0] < WALL_THICKNESS * 7 // 8 and WALL_THICKNESS // 8 <= mouse[1] < WALL_THICKNESS // 2:
        return True
    return False

def render_pause_button():
    if PAUSED:
        bgcolor = LIGHT_GREEN
        fgcolor = BLACK
        text = "RUN"
    else:
        bgcolor = MAGENTA
        fgcolor = WHITE
        text = "PAUSE"
    pygame.draw.rect(SCREEN, bgcolor, [WALL_THICKNESS // 8, WALL_THICKNESS * 5 // 8, WALL_THICKNESS * 3 // 4, WALL_THICKNESS * 3 // 8], 0, WALL_THICKNESS * 3 // 24)
    print_text(text, (WALL_THICKNESS // 2, WALL_THICKNESS * 13 // 16), True, None, 18, fgcolor)

def pause_button_clicked():
    global PAUSE_BUTTON_FLAG
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()[0]
    if click and WALL_THICKNESS // 8 <= mouse[0] < WALL_THICKNESS * 7 // 8 and WALL_THICKNESS * 5 // 8 <= mouse[1] < WALL_THICKNESS:
        if PAUSE_BUTTON_FLAG == True:
            PAUSE_BUTTON_FLAG = False
            return True
        return False
    PAUSE_BUTTON_FLAG = True
    return False

def render_collision_counter():
    print_text("Collisions: %d" % COLLISION, (WALL_THICKNESS * 9 // 8, WALL_THICKNESS // 8), False, None, 24)

def render_pause_ui():
    if not PAUSED:
        return
    print_text("Paused", (WIDTH - 64, WALL_THICKNESS // 8), False, None, 24)

def collider_update():
    global COLLISION, COLLISION_TIMER, PRED_COLLIDER, PAST_COLLIDE, collider
    while COLLISION_TIMER < rational(1, TARGET_FRAME_RATE): #While there is not-processed collision in the current frame
        if PRED_COLLIDER != None: #if it is valid collision
            #Move to the collision
            for i in collider:
                i.position += i.velocity * PAST_COLLIDE
            #Collision with the wall
            if PRED_COLLIDER[0] == "Wall":
                PRED_COLLIDER[1].velocity = -PRED_COLLIDER[1].velocity
            #Collision between colliders
            else:
                c1 = PRED_COLLIDER[0]
                c2 = PRED_COLLIDER[1]
                m1 = c1.mass
                m2 = c2.mass
                v1 = c1.velocity
                v2 = c2.velocity
                c1.velocity = (v1 * (m1 - m2) + 2 * m2 * v2) / (m1 + m2)
                c2.velocity = (v2 * (m2 - m1) + 2 * m1 * v1) / (m2 + m1)
            COLLISION += 1
        #Next collision prediction
        NCT = rational("inf") #Next Collision Time
        PRED_COLLIDER = None
        for i in collider:
            if i.velocity < 0:
                CCT = i.position / abs(i.velocity) #Current Collision Time
                if CCT < NCT:
                    NCT = CCT
                    PRED_COLLIDER = ["Wall", i]
            for j in collider:
                L, R = sorted([i, j], key = lambda x: x.position)
                if R.velocity < L.velocity:
                    CCT = (R.position - L.position - L.length) / (L.velocity - R.velocity)
                    if CCT < NCT:
                        NCT = CCT
                        PRED_COLLIDER = [L, R]
        #End of prediction
        PAST_COLLIDE = NCT
        COLLISION_TIMER += NCT
    if COLLISION_TIMER == rational("inf"):
        for i in collider:
            i.position += i.velocity * rational(1, TARGET_FRAME_RATE)
    else:
        MOV_TIME = rational(1, TARGET_FRAME_RATE) - (COLLISION_TIMER - PAST_COLLIDE)
        for i in collider:
            i.position += i.velocity * MOV_TIME
        COLLISION_TIMER -= rational(1, TARGET_FRAME_RATE)
        PAST_COLLIDE = COLLISION_TIMER

def render_size_input_box():
    pygame.draw.rect(SCREEN, WHITE, [WIDTH * 2 // 5, HEIGHT * 7 // 24, WIDTH * 7 // 20, 24])

def size_button_clicked():
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()[0]
    if click and WIDTH * 2 // 5 <= mouse[0] < WIDTH * 3 // 4 and HEIGHT * 7 // 24 <= mouse[1] < HEIGHT * 7 // 24 + 24:
        return True
    return False

def render_mass_input_box():
    pygame.draw.rect(SCREEN, WHITE, [WIDTH * 2 // 5, HEIGHT * 9 // 24, WIDTH * 7 // 20, 24])

def mass_button_clicked():
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()[0]
    if click and WIDTH * 2 // 5 <= mouse[0] < WIDTH * 3 // 4 and HEIGHT * 9 // 24 <= mouse[1] < HEIGHT * 9 // 24 + 24:
        return True
    return False

def render_position_input_box():
    pygame.draw.rect(SCREEN, WHITE, [WIDTH * 2 // 5, HEIGHT * 11 // 24, WIDTH * 7 // 20, 24])

def position_button_clicked():
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()[0]
    if click and WIDTH * 2 // 5 <= mouse[0] < WIDTH * 3 // 4 and HEIGHT * 11 // 24 <= mouse[1] < HEIGHT * 11 // 24 + 24:
        return True
    return False

def render_velocity_input_box():
    pygame.draw.rect(SCREEN, WHITE, [WIDTH * 2 // 5, HEIGHT * 13 // 24, WIDTH * 7 // 20, 24])

def velocity_button_clicked():
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()[0]
    if click and WIDTH * 2 // 5 <= mouse[0] < WIDTH * 3 // 4 and HEIGHT * 13 // 24 <= mouse[1] < HEIGHT * 13 // 24 + 24:
        return True
    return False

def render_color_input_box():
    pygame.draw.rect(SCREEN, WHITE, [WIDTH * 2 // 5, HEIGHT * 15 // 24, WIDTH * 7 // 20, 24])

def color_button_clicked():
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()[0]
    if click and WIDTH * 2 // 5 <= mouse[0] < WIDTH * 3 // 4 and HEIGHT * 15 // 24 <= mouse[1] < HEIGHT * 15 // 24 + 24:
        return True
    return False

def render_add_button():
    pygame.draw.rect(SCREEN, RED, [WIDTH * 7 // 24, HEIGHT * 19 // 24, WIDTH // 6, HEIGHT // 12], 0, HEIGHT // 30)
    print_text("ADD", (WIDTH * 3 // 8, HEIGHT * 5 // 6), True, None, 24, WHITE)

def add_button_clicked():
    global PAUSE_BUTTON_FLAG
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()[0]
    if click and WIDTH * 7 // 24 <= mouse[0] < WIDTH * 11 // 24 and HEIGHT * 19 // 24 <= mouse[1] < HEIGHT * 21 // 24:
        if PAUSE_BUTTON_FLAG == True:
            PAUSE_BUTTON_FLAG = False
            return True
        return False
    PAUSE_BUTTON_FLAG = True
    return False

def render_done_button():
    pygame.draw.rect(SCREEN, GREEN, [WIDTH * 13 // 24, HEIGHT * 19 // 24, WIDTH // 6, HEIGHT // 12], 0, HEIGHT // 30)
    print_text("DONE", (WIDTH * 5 // 8, HEIGHT * 5 // 6), True, None, 24, BLACK)

def done_button_clicked():
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()[0]
    if click and WIDTH * 13 // 24 <= mouse[0] < WIDTH * 17 // 24 and HEIGHT * 19 // 24 <= mouse[1] < HEIGHT * 21 // 24:
        return True
    return False

def render_speed_ui():
    print_text("Speed: x%s" % SPEED, (WALL_THICKNESS * 9 // 8, WALL_THICKNESS // 8 + 18), False, None, 24)

def render_version_ui():
    print_text("Version: A1.00", (WIDTH - 50, HEIGHT - 14), True, None, 18, WHITE)

#Main Code
collider.append(box(length = rational(1), mass = rational(1), position = rational(2), velocity = rational(0), color = RED))
collider.append(box(length = rational(1), mass = rational(1), position = rational(5), velocity = rational(-1), color = BLUE))

#Main Loop
while RUNNING:
    pygame.time.Clock().tick(TARGET_FRAME_RATE)

    #Simulating
    if STATUS == "Simulate":
        #Render Background, Floor and Wall
        SCREEN.fill(LIGHT_GRAY)
        pygame.draw.rect(SCREEN, BLACK, [0, HEIGHT - FLOOR_HEIGHT, WIDTH, FLOOR_HEIGHT])
        pygame.draw.rect(SCREEN, BLACK, [0, 0, WALL_THICKNESS, HEIGHT])

        #Render Colliders
        for i in collider:
            i.render()

        #Render UIs
        render_restart_button()
        render_pause_button()
        render_collision_counter()
        render_pause_ui()
        #render_speed_ui()
        render_version_ui()

        #Update Collider Status
        if not PAUSED:
            collider_update()

        #Interrupt
        if restart_button_clicked():
            STATUS = "Reset"
            collider = []
            TEXT_BOX_INFO = {"Size": "", "Mass": "", "Position": "", "Velocity": "", "Color": ""}
            COLLISION = 0
            COLLISION_TIMER = rational(0)
            PRED_COLLIDER = None
            SPEED = 1
        if pause_button_clicked():
            if PAUSED:
                PAUSED = False
            else:
                PAUSED = True

    #New Experiment Setting
    if STATUS == "Reset":
        #Render Background and Input Textbox
        SCREEN.fill(DARK_GRAY)
        print_text("Add new collider", (WIDTH // 2, HEIGHT // 6), True, None, 36, WHITE)
        print_text("Size    : ", (WIDTH // 4, HEIGHT * 7 // 24), False, None, 24, WHITE)
        print_text("Mass    : ", (WIDTH // 4, HEIGHT * 9 // 24), False, None, 24, WHITE)
        print_text("Position: ", (WIDTH // 4, HEIGHT * 11 // 24), False, None, 24, WHITE)
        print_text("Velocity: ", (WIDTH // 4, HEIGHT * 13 // 24), False, None, 24, WHITE)
        print_text("Color   : ", (WIDTH // 4, HEIGHT * 15 // 24), False, None, 24, WHITE)
        render_size_input_box()
        render_mass_input_box()
        render_position_input_box()
        render_velocity_input_box()
        render_color_input_box()
        render_add_button()
        render_done_button()
        print_text(TEXT_BOX_INFO["Size"], (WIDTH * 2 // 5 + 4, HEIGHT * 7 // 24 + 4), False, None, 24, BLACK)
        print_text(TEXT_BOX_INFO["Mass"], (WIDTH * 2 // 5 + 4, HEIGHT * 9 // 24 + 4), False, None, 24, BLACK)
        print_text(TEXT_BOX_INFO["Position"], (WIDTH * 2 // 5 + 4, HEIGHT * 11 // 24 + 4), False, None, 24, BLACK)
        print_text(TEXT_BOX_INFO["Velocity"], (WIDTH * 2 // 5 + 4, HEIGHT * 13 // 24 + 4), False, None, 24, BLACK)
        print_text(TEXT_BOX_INFO["Color"], (WIDTH * 2 // 5 + 4, HEIGHT * 15 // 24 + 4), False, None, 24, BLACK)

        #Interrupt
        if add_button_clicked():
            try:
                if TEXT_BOX_INFO["Color"] != "":
                    exec("color = %s" % TEXT_BOX_INFO["Color"].upper())
                else:
                    color = choice([RED, GREEN, BLUE, YELLOW, MAGENTA, CYAN, LIGHT_GREEN])
                sz = float(TEXT_BOX_INFO["Size"])
                ms = float(TEXT_BOX_INFO["Mass"])
                ps = float(TEXT_BOX_INFO["Position"])
                vc = float(TEXT_BOX_INFO["Velocity"])
                collider.append(box(sz, ms, ps, vc, color))
                ERROR_MESSAGE_TIMER = TARGET_FRAME_RATE * 2
                ERROR_MESSAGE = "Collider added successfully"
                TEXT_BOX_INFO = {"Size": "", "Mass": "", "Position": "", "Velocity": "", "Color": ""}
            except:
                ERROR_MESSAGE_TIMER = TARGET_FRAME_RATE * 2
                ERROR_MESSAGE = "Some of inputs are missing or wrong!"
            CLICKED_TEXT_BUTTON = None

        if done_button_clicked():
            STATUS = "Simulate"
            PAUSED = True
            ERROR_MESSAGE_TIMER = 0
            CLICKED_TEXT_BUTTON = None
        if size_button_clicked():
            CLICKED_TEXT_BUTTON = "Size"
            TEXT_BOX_INFO["Size"] = ""
        if mass_button_clicked():
            CLICKED_TEXT_BUTTON = "Mass"
            TEXT_BOX_INFO["Mass"] = ""
        if position_button_clicked():
            CLICKED_TEXT_BUTTON = "Position"
            TEXT_BOX_INFO["Position"] = ""
        if velocity_button_clicked():
            CLICKED_TEXT_BUTTON = "Velocity"
            TEXT_BOX_INFO["Velocity"] = ""
        if color_button_clicked():
            CLICKED_TEXT_BUTTON = "Color"
            TEXT_BOX_INFO["Color"] = ""
        if CLICKED_TEXT_BUTTON != None:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_BACKSPACE:
                        if TEXT_BOX_INFO[CLICKED_TEXT_BUTTON] != "":
                            TEXT_BOX_INFO[CLICKED_TEXT_BUTTON] = TEXT_BOX_INFO[CLICKED_TEXT_BUTTON][:-1]
                    elif event.key == pygame.K_TAB:
                        if CLICKED_TEXT_BUTTON == "Size":
                            CLICKED_TEXT_BUTTON = "Mass"
                            TEXT_BOX_INFO["Mass"] = ""
                        elif CLICKED_TEXT_BUTTON == "Mass":
                            CLICKED_TEXT_BUTTON = "Position"
                            TEXT_BOX_INFO["Position"] = ""
                        elif CLICKED_TEXT_BUTTON == "Position":
                            CLICKED_TEXT_BUTTON = "Velocity"
                            CLICKED_TEXT_BUTTON = "Velocity"
                        elif CLICKED_TEXT_BUTTON == "Velocity":
                            CLICKED_TEXT_BUTTON = "Color"
                            TEXT_BOX_INFO["Color"] = ""
                    elif event.key in [pygame.K_RETURN, pygame.K_KP_ENTER]:
                        try:
                            if TEXT_BOX_INFO["Color"] != "":
                                exec("color = %s" % TEXT_BOX_INFO["Color"].upper())
                            else:
                                color = choice([RED, GREEN, BLUE, YELLOW, MAGENTA, CYAN, LIGHT_GREEN])
                            sz = float(TEXT_BOX_INFO["Size"])
                            ms = float(TEXT_BOX_INFO["Mass"])
                            ps = float(TEXT_BOX_INFO["Position"])
                            vc = float(TEXT_BOX_INFO["Velocity"])
                            collider.append(box(sz, ms, ps, vc, color))
                            ERROR_MESSAGE_TIMER = TARGET_FRAME_RATE * 2
                            ERROR_MESSAGE = "Collider added successfully"
                            TEXT_BOX_INFO = {"Size": "", "Mass": "", "Position": "", "Velocity": "", "Color": ""}
                            CLICKED_TEXT_BUTTON = "Size"
                        except:
                            ERROR_MESSAGE_TIMER = TARGET_FRAME_RATE * 2
                            ERROR_MESSAGE = "Some of inputs are missing or wrong!"
                    else:
                        TEXT_BOX_INFO[CLICKED_TEXT_BUTTON] += event.unicode
        #Error Message
        if 0 < ERROR_MESSAGE_TIMER:
            print_text(ERROR_MESSAGE, (WIDTH // 2, HEIGHT * 3 / 4), True, None, 18, WHITE, 255 * ERROR_MESSAGE_TIMER // TARGET_FRAME_RATE)
            ERROR_MESSAGE_TIMER -= 1

    #Refresh Screen
    pygame.display.update()

    #Event Processing
    for event in pygame.event.get():

        #Quit Button Action
        if event.type == pygame.QUIT:
            pygame.display.quit()
            RUNNING = False

        #Update Size
        elif event.type == pygame.VIDEORESIZE:
            WIDTH = event.w
            HEIGHT = event.h
            FLOOR_relocation()


import serial
import Simple485

SERIALPORT = "COM13"
BAUDRATE = 9600
ADDR = b'\x1b'

ser = serial.Serial()
ser.port = SERIALPORT
ser.baudrate = BAUDRATE

try:
  ser.open()
except serial.SerialException as e:
  print('Could not open serial port {}: {}\n'.format(ser.name, e))
  exit(1)

rs485 = Simple485.Simple485(ser, ADDR)

while 1:
  try:
    rs485.loop()
    while rs485.received() > 0:
      m = rs485.read()
      src = m[0]
      ln = m[1]
      msg = m[2]
      print("Received " + str(ln) + " from " + str(src))
      print(msg)
      rs485.send(src, "ACQ")
  except KeyboardInterrupt:
    print("\nClosing")
    ser.close()
    exit(0)


#!/usr/bin/env python3
import os
import time
import cv2
import pickle
import face_recognition
import numpy

# last n seconds to use for fps calc
FPS_WINDOW = 60

# if true, use face_recognition.face_distance to determin known faces
USE_FACE_DISTANCE = os.getenv('USE_FACE_DISTANCE') == '1' or False

if USE_FACE_DISTANCE:
    print('Using face_distance to determine known faces')

class FpsStats(object):
    def __init__(self):
        self.start()

    # can call start after init, or pause and start for more accuracy
    def start(self):
        self.started_at = time.time()
        self.total_frames = 0
        self.floating_frames_count = 0
        self.floating_started_at = time.time()
        self.last_floating_fps = 0

    def increment(self):
        self.total_frames += 1
        self.floating_frames_count += 1

        fps_time = time.time() - self.floating_started_at
        if fps_time > FPS_WINDOW:
            self.last_floating_fps = self.floating_frames_count / fps_time
            self.floating_started_at = time.time()
            self.floating_frames_count = 0
            print(f"fps: {self.last_floating_fps}")

    def stats(self):
        now = time.time()
        total_time = now - self.started_at
        return {
            "totalFramesRead": self.total_frames,
            "totalTime": total_time,
            "overallFps": self.total_frames / total_time,
            "fpsStartedAt": self.floating_started_at,
            "floatingFps": self.last_floating_fps
        }

print('initializing VideoCapture')
camera = cv2.VideoCapture(0)  # , apiPreference=cv2.CAP_V4L2)
if not camera.isOpened():
    raise RuntimeError('Could not start camera.')

camera.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

encodings_data = pickle.loads(
    open("data/encodings.pickle", "rb").read(), encoding='latin1')
print(f"loaded {len(encodings_data['encodings'])} encodings")

fps_stats = FpsStats()

try:
    while True:
        _, img = camera.read()
        if img is None:
            print(
                "The camera has not read data, please check whether the camera can be used normally.")
            print(
                "Use the command: 'raspistill -t 1000 -o image.jpg' to check whether the camera can be used correctly.")
            break

        fps_stats.increment()

        new_faces = face_recognition.face_locations(img)
        num_new_faces = len(new_faces)
        print(f"found {num_new_faces} faces")

        names = []
        if num_new_faces > 0:
            encodings = face_recognition.face_encodings(img, new_faces)
            for encoding in encodings:
                if USE_FACE_DISTANCE:
                    face_distances = face_recognition.face_distance(
                        encodings_data["encodings"], encoding)
                    best_match_index = numpy.argmin(face_distances)
                    if face_distances[best_match_index] < 0.65:
                        names.append(encodings_data["names"][best_match_index])
                else:
                    matches = face_recognition.compare_faces(
                        encodings_data["encodings"], encoding)
                    # check to see if we have found a match
                    if True in matches:
                        matched_indexes = [
                            i for (i, b) in enumerate(matches) if b]
                        counts = {}

                        for i in matched_indexes:
                            name = encodings_data["names"][i]
                            counts[name] = counts.get(name, 0) + 1

                        # determine the recognized face with the largest number of votes
                        names.append(max(counts, key=counts.get))

        print(f"recognized {len(names)} faces")
except KeyboardInterrupt:
    pass

print('')
print(fps_stats.stats())


import configparser
import logging
import os
import subprocess

from .. import GameData
from ..build import (PackagingTask)
from ..paths import DATADIR
from ..util import (mkdir_p)

logger = logging.getLogger(__name__)

def install_data(from_, to):
    subprocess.check_call(['cp', '--reflink=auto', from_, to])

class ScummvmGameData(GameData):
    def __init__(self, shortname, data):
        super(ScummvmGameData, self).__init__(shortname, data)

        self.wikibase = 'http://wiki.scummvm.org/index.php/'
        assert self.wiki

        if 'gameid' in self.data:
            self.gameid = self.data['gameid']
            assert self.gameid != shortname, 'extraneous gameid for ' + shortname
            self.aliases.add(self.gameid)
        else:
            self.gameid = shortname

        if self.engine is None:
            self.engine = 'scummvm'
        if self.genre is None:
            self.genre = 'Adventure'

    def _populate_package(self, package, d):
        super(ScummvmGameData, self)._populate_package(package, d)
        package.gameid = d.get('gameid')

    def construct_task(self, **kwargs):
        return ScummvmTask(self, **kwargs)

class ScummvmTask(PackagingTask):
    def iter_extra_paths(self, packages):
        super(ScummvmTask, self).iter_extra_paths(packages)

        gameids = set()
        for p in packages:
            gameid = p.gameid or self.game.gameid
            if gameid == 'agi-fanmade':
                continue
            gameids.add(gameid.split('-')[0])
        if not gameids:
            return

        # http://wiki.scummvm.org/index.php/User_Manual/Configuring_ScummVM
        # https://github.com/scummvm/scummvm/pull/656
        for rcfile in (os.path.join(os.environ.get('XDG_DATA_HOME',
                                    os.path.expanduser('~/.local/share')),
                                              'scummvm/scummvm.ini'),
                       os.path.expanduser('~/.scummvmrc')):
            if os.path.isfile(rcfile):
                break
        else:
            return

        config = configparser.ConfigParser(strict=False)
        config.read(rcfile, encoding='utf-8')
        for section in config.sections():
            for gameid in gameids:
                if section.split('-')[0] == gameid:
                    if 'path' not in config[section]:
                        # invalid .scummvmrc
                        continue
                    path = config[section]['path']
                    if os.path.isdir(path):
                        yield path

    def fill_extra_files(self, package, destdir):
        super(ScummvmTask, self).fill_extra_files(package, destdir)
        if package.type == 'expansion' and not package.gameid:
            return

        icon = package.name
        for from_ in (self.locate_steam_icon(package),
                      os.path.join(DATADIR, package.name + '.png'),
                      os.path.join(DATADIR, self.game.shortname + '.png'),
                      os.path.join('/usr/share/pixmaps', icon + '.png'),
                      os.path.join(DATADIR,
                          self.game.shortname.strip('1234567890') + '.png')):
            if from_ and os.path.exists(from_):
                pixdir = os.path.join(destdir, 'usr/share/pixmaps')
                mkdir_p(pixdir)
                install_data(from_, os.path.join(pixdir, '%s.png' % icon))
                break
        else:
            icon = 'scummvm'

        from_ = os.path.splitext(from_)[0] + '.svgz'
        if os.path.exists(from_):
            svgdir = os.path.join(destdir, 'usr/share/icons/hicolor/scalable/apps')
            mkdir_p(svgdir)
            install_data(from_, os.path.join(svgdir, '%s.svgz' % icon))

        appdir = os.path.join(destdir, 'usr/share/applications')
        mkdir_p(appdir)

        desktop = configparser.RawConfigParser()
        desktop.optionxform = lambda option: option
        desktop['Desktop Entry'] = {}
        entry = desktop['Desktop Entry']
        entry['Name'] = package.longname or self.game.longname
        entry['GenericName'] = self.game.genre + ' Game'
        entry['TryExec'] = 'scummvm'
        entry['Icon'] = icon
        entry['Terminal'] = 'false'
        entry['Type'] = 'Application'
        entry['Categories'] = 'Game;%sGame;' % self.game.genre.replace(' ','')
        gameid = package.gameid or self.game.gameid
        install_to = self.packaging.substitute(package.install_to,
                                               package.name)
        if len(package.langs) == 1:
            entry['Exec'] = 'scummvm -p %s %s' % (
                    os.path.join('/', install_to), gameid)
            self.packaging.override_lintian(destdir, package.name,
                    'desktop-command-not-in-package',
                    'usr/share/applications/%s.desktop %s'
                     % (package.name, 'scummvm'))
        else:
            pgm = package.name[0:len(package.name)-len('-data')]
            entry['Exec'] = pgm
            bindir = self.packaging.substitute(self.packaging.BINDIR, package.name)
            bindir = os.path.join(destdir, bindir.strip('/'))
            assert bindir.startswith(destdir + '/'), (bindir, destdir)
            mkdir_p(bindir)
            path = os.path.join(bindir, pgm)
            if 'en' not in package.langs:
                package.langs.append('en')
            with open(path, 'w') as f:
                f.write('#!/bin/sh\n')
                f.write('GAME_LANG=$(\n')
                f.write("echo $LANGUAGE $LANG en | tr ': ' '\\n' | cut -c1-2 | while read lang\n")
                f.write('do\n')
                for lang in package.langs:
                    f.write('[ "$lang" = "%s" ] && echo $lang && break\n' % lang)
                f.write('done\n')
                f.write(')\n')
                f.write('if [ "$GAME_LANG" = "en" ]; then\n')
                f.write('  exec scummvm -p %s %s\n' % (
                    os.path.join('/', install_to), gameid))
                f.write('else\n')
                f.write('  exec scummvm -q $GAME_LANG -p %s %s\n' % (
                    os.path.join('/', install_to), gameid))
                f.write('fi\n')
            os.chmod(path, 0o755)

        with open(os.path.join(appdir, '%s.desktop' % package.name),
                  'w', encoding='utf-8') as output:
             desktop.write(output, space_around_delimiters=False)

GAME_DATA_SUBCLASS = ScummvmGameData


#!/usr/bin/env python3
import re, sys
import subprocess as sp
sectre = re.compile("(.*) \((.+)\)")
args = " ".join(sys.argv[1:])
cmd = 'onsub --nocolor --verbose 3 ' + args + ' "{remote} {sep} {wcrev}"'
try: result = sp.check_output(cmd, shell=True, stderr=sp.DEVNULL).decode()
except sp.CalledProcessError as exc: result = []
sections = {}
folder = section = repo = None
for line in result.splitlines():
    line = line.strip()
    if len(line) == 0 or line == "<<< RESULTS >>>": continue
    if folder and repo:
        rev = line
        sections.setdefault(section, []).append((folder, repo, rev))
        folder = section = repo = None
        continue
    if folder:
        repo = line
        continue
    mm = sectre.match(line)
    if mm and len(mm.groups()) == 2:
        folder = mm.group(1)
        section = mm.group(2)
        pass
    continue
for section, folderrepos in sorted(sections.items()):
    print("{section} = [".format(section=section))
    for folder, repo, rev in sorted(folderrepos):
        print('\t("{folder}", "{repo}", "{rev}"),'.format(folder=folder, repo=repo, rev=rev))
        continue
    print("]")
    continue


import torch
import torch.nn as nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
use_cuda = torch.cuda.is_available()

class VGG16(nn.Module):
    def __init__(self, num_classes=10):
        super(VGG16, self).__init__()
        self.features = nn.Sequential(
            # 1
            nn.Conv2d(3, 64, kernel_size=3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(True),
            # 2
            nn.Conv2d(64, 64, kernel_size=3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(True),
            nn.MaxPool2d(kernel_size=2, stride=2),
            # 3
            nn.Conv2d(64, 128, kernel_size=3, padding=1),
            nn.BatchNorm2d(128),
            nn.ReLU(True),
            # 4
            nn.Conv2d(128, 128, kernel_size=3, padding=1),
            nn.BatchNorm2d(128),
            nn.ReLU(True),
            nn.MaxPool2d(kernel_size=2, stride=2),
            # 5
            nn.Conv2d(128, 256, kernel_size=3, padding=1),
            nn.BatchNorm2d(256),
            nn.ReLU(True),
            # 6
            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.BatchNorm2d(256),
            nn.ReLU(True),
            # 7
            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.BatchNorm2d(256),
            nn.ReLU(True),
            nn.MaxPool2d(kernel_size=2, stride=2),
            # 8
            nn.Conv2d(256, 512, kernel_size=3, padding=1),
            nn.BatchNorm2d(512),
            nn.ReLU(True),
            # 9
            nn.Conv2d(512, 512, kernel_size=3, padding=1),
            nn.BatchNorm2d(512),
            nn.ReLU(True),
            # 10
            nn.Conv2d(512, 512, kernel_size=3, padding=1),
            nn.BatchNorm2d(512),
            nn.ReLU(True),
            nn.MaxPool2d(kernel_size=2, stride=2),
            # 11
            nn.Conv2d(512, 512, kernel_size=3, padding=1),
            nn.BatchNorm2d(512),
            nn.ReLU(True),
            # 12
            nn.Conv2d(512, 512, kernel_size=3, padding=1),
            nn.BatchNorm2d(512),
            nn.ReLU(True),
            # 13
            nn.Conv2d(512, 512, kernel_size=3, padding=1),
            nn.BatchNorm2d(512),
            nn.ReLU(True),
            nn.MaxPool2d(kernel_size=2, stride=2),
            nn.AvgPool2d(kernel_size=1, stride=1),
        )
        self.classifier = nn.Sequential(
            # 14
            nn.Linear(512, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            # 15
            nn.Linear(4096, 4096),
            nn.ReLU(True),
            nn.Dropout(),
            # 16
            nn.Linear(4096, num_classes),
        )
        # self.classifier = nn.Linear(512, 10)

    def forward(self, x):
        out = self.features(x)
        #        print(out.shape)
        out = out.view(out.size(0), -1)
        #        print(out.shape)
        out = self.classifier(out)
        #        print(out.shape)
        return out
def stu():
    model=VGG16()
    if use_cuda:
        model.cuda()
    return model


import pandas as pd
import networkx as nx
import numpy as np

# FUNÇÃO: Inserir dado em DF_final

def insert(DF_final, row):
    insert_loc = DF_final.index.max()

    if np.isnan(insert_loc):
        DF_final.loc[0] = row
    else:
        DF_final.loc[insert_loc + 1] = row

    return DF_final

# FUNÇÃO: Converte a matriz em dados antes de inserir no DF_final

def save_in_df(DF_final, movimentos_, A_, P_, Global_, Alerta_, Classes_, Trib_, g, PG_df):
    for i in range(len(movimentos_.index)):
        # print(x.iat[i,0],"->",x.iat[i,1],":",g.number_of_edges(x.iat[i,0],x.iat[i,1]))
        insert(DF_final, [
            movimentos_.iat[i, 0],
            movimentos_.iat[i, 1],
            g.number_of_edges(movimentos_.iat[i, 0], movimentos_.iat[i, 1]),
            P_.at[movimentos_.iat[i, 0], movimentos_.iat[i, 1]],
            Alerta_,
            PG_df.at[movimentos_.iat[i, 0], movimentos_.iat[i, 1]],
            Classes_,
            Trib_
        ])

    return DF_final

def aplicar(processos):
    DF_final = pd.DataFrame(columns=['mov_origem', 'mov_destino', 'ocorrencias',
                                     'prob', 'alerta', 'prob_Nac', 'classe_processual', 'siglaTribunal'])

    df = processos.dropna(subset=['movimentos'])

    classes_escolhidas = [1116, 7, 159, 283]
    tribunais = ['TJSP', 'TJPR', 'TJRJ', 'TJBA', 'TJSC', 'TJES', 'TJPE', 'TJGO', 'TJRO', 'TJAM', 'TJAL', 'TJMG', 'TJMT',
                 'TJCE', 'TJRN', 'TJTO', 'TJPB', 'TJDFT', 'TJPA', 'TJMS', 'TJSE', 'TJAC', 'TJPI', 'TJRS', 'TJMA', 'TJRR', 'TJAP']

    for classe_escolhida in classes_escolhidas:
        df_classe = df[(df.classe_processual == classe_escolhida)]
        g_nacional = nx.MultiDiGraph()

        count2 = 0
        for row in df_classe.index:  # Percorre todas a linhas do df
            # captura os movimentos e transforma em uma lista (vetor)
            mov2 = df.iloc[row]['movimentos'].split(",")
            # percorre a lista de movimentos para gerar os Nós
            for st2 in range(0, len(mov2)-1):
                origem2 = mov2[st2]
                destino2 = mov2[st2+1]
                if destino2 != None:  # eliminas processos com somente um movimento
                    # adicionamos as transições (arestas)
                    g_nacional.add_edge(origem2, destino2)
            count2 = count2+1

        print(classe_escolhida, " GLOBAL analisado!")
        # 2)MATRIZ DE TRANSIÇÃO UNITÁRIA
        AG = nx.to_numpy_matrix(g_nacional)
        ndg = g_nacional.nodes()
        AG_df = pd.DataFrame(AG, index=ndg, columns=ndg)
        # 2)MATRIZ DE PROBABILIDADE
        PG = AG/AG.sum(axis=1)
        PG_df = pd.DataFrame(PG, index=ndg, columns=ndg)

        for tribunal in tribunais:
            df_tribunal = df_classe[(df_classe.siglaTribunal == tribunal)]

            # MultiDiGraph - Gráfos direcionados com auto-loops e arestas paralelas
            g = nx.MultiDiGraph()

            count = 0
            for row in df_tribunal.index:  # Percorre todas a linhas do df
                # captura os movimentos e transforma em uma lista (vetor)
                mov = df.iloc[row]['movimentos'].split(",")
                # percorre a lista de movimentos para gerar os Nós
                # com base da origem -> destivo
                for st in range(0, len(mov)-1):
                    origem = mov[st]
                    destino = mov[st+1]
                    if destino != None:  # eliminas processos com somente um movimento
                        # print(count,":",origem,"-->",destino)
                        # adicionamos as transições (arestas)
                        g.add_edge(origem, destino)
                        # MELHORAR: add_path([0,1,2,3,4,5,6,7,8,9]) https://networkx.github.io/documentation/networkx-1.11/reference/classes.multidigraph.html
                count = count+1
            print(classe_escolhida, ":", tribunal, " analisado!")

            movimentos = pd.DataFrame(g.edges()).drop_duplicates()

            # 2)MATRIZ DE TRANSIÇÃO UNITÁRIA
            A = nx.to_numpy_matrix(g)
            nd = g.nodes()
            A_df = pd.DataFrame(A, index=nd, columns=nd)
            # print(A_df)
            # 2)MATRIZ DE PROBABILIDADE
            P = A/A.sum(axis=1)
            P_df = pd.DataFrame(P, index=nd, columns=nd)
            # print(P_df)

            # 2)MATRIZ DE ESCALA
            P = A/A.sum(axis=1)
            P_df = pd.DataFrame(P, index=nd, columns=nd)
            # print(P_df)

            # Salva no DF_final
            save_in_df(DF_final, movimentos, A_df, P_df, PG_df,
                       'xxx', classe_escolhida, tribunal, g, PG_df)

    DF_final['alerta'] = DF_final['prob'] - DF_final['prob_Nac']
    DF_final['alerta'] = DF_final['alerta'] / DF_final['prob_Nac']
    DF_final['alerta'] = DF_final['alerta'].abs()

    DF_final = DF_final[(DF_final['alerta'] > 10.34)]

    DF_final = DF_final.sort_values('alerta', ascending=False)

    return DF_final


import colors
import json
import os
import tf
from args import parse_args

def find_project_root(path=None):
  path = path if path else os.getcwd()

  if os.path.isfile(os.path.join(path, '.tfconfig')):
    return path
  else:
    new_path = os.path.dirname(path)
    if new_path == path:
      return None

    return find_project_root(os.path.dirname(path))

def load_config():
  project_root = find_project_root()

  if not project_root:
    return None

  config = None

  with open(os.path.join(project_root, '.tfconfig')) as config_file:
    try:
      config = json.load(config_file)
      config['project_root'] = project_root
    except ValueError as e:
      # print(e)
      pass

  return config

def main():

  args = parse_args()

  wrapper = tf.TF(
    args.stack,
    args.environment,
    tfargs=args.tfargs,
    config=load_config()
  )

  wrapper.build_path()
  wrapper.validate_paths()

  colors.print_heading('========> Configuring state backend')
  wrapper.configure()

  # Always make sure we have the modules
  colors.print_heading('========> Updating the modules')
  wrapper.execute_tf_command('get', include_tfargs=False)

  colors.print_heading("========> Exucuting terraform {0}".format(args.command))
  wrapper.execute_tf_command(args.command)