import json

import pytest

from autoprotocol import Container, Protocol, Well, WellGroup
from autoprotocol.harness import (
    Manifest,
    ProtocolInfo,
    get_protocol_preview,
    seal_on_store,
)
from autoprotocol.unit import Unit

class TestManifest(object):
    @pytest.fixture(autouse=True)
    def setUp(self):
        self.protocol = Protocol()

    def test_empty(self):
        protocol_info = ProtocolInfo({"name": "Test Empty", "inputs": {}})
        parsed = protocol_info.parse(self.protocol, {"refs": {}, "parameters": {}})
        assert {} == parsed

    def test_basic_types(self):
        protocol_info = ProtocolInfo(
            {
                "name": "Test Basic Types",
                "inputs": {
                    "bool": "bool",
                    "string": "string",
                    "integer": "integer",
                    "decimal": "decimal",
                },
            }
        )
        parsed = protocol_info.parse(
            self.protocol,
            {
                "refs": {},
                "parameters": {
                    "bool": True,
                    "string": "test",
                    "integer": 3,
                    "decimal": 2.1,
                },
            },
        )
        assert {"bool": True, "string": "test", "integer": 3, "decimal": 2.1} == parsed
        with pytest.raises(RuntimeError):
            parsed = protocol_info.parse(
                self.protocol,
                {
                    "refs": {},
                    "parameters": {
                        "bool": True,
                        "string": "test",
                        "integer": "hi",
                        "decimal": 2.1,
                    },
                },
            )
        with pytest.raises(RuntimeError):
            parsed = protocol_info.parse(
                self.protocol,
                {
                    "refs": {},
                    "parameters": {
                        "bool": True,
                        "string": "test",
                        "integer": "3",
                        "decimal": "hi",
                    },
                },
            )

    def test_unit_types(self):
        protocol_info = ProtocolInfo(
            {
                "name": "Test Basic Types",
                "inputs": {
                    "volume": "volume",
                    "time": "time",
                    "temperature": "temperature",
                },
            }
        )
        parsed = protocol_info.parse(
            self.protocol,
            {
                "refs": {},
                "parameters": {
                    "volume": "3:microliter",
                    "time": "30:second",
                    "temperature": "25:celsius",
                },
            },
        )
        assert {
            "volume": Unit.fromstring("3:microliter"),
            "time": Unit.fromstring("30:second"),
            "temperature": Unit.fromstring("25:celsius"),
        } == parsed
        with pytest.raises(RuntimeError):
            parsed = protocol_info.parse(
                self.protocol,
                {
                    "refs": {},
                    "parameters": {
                        "volume": 3,
                        "time": "30:second",
                        "temperature": "25:celsius",
                    },
                },
            )
            parsed = protocol_info.parse(
                self.protocol,
                {
                    "refs": {},
                    "parameters": {
                        "volume": "3:microliter",
                        "time": "hello",
                        "temperature": "25:celsius",
                    },
                },
            )
            parsed = protocol_info.parse(
                self.protocol,
                {
                    "refs": {},
                    "parameters": {
                        "volume": "3:microliter",
                        "time": "30:second",
                        "temperature": 25,
                    },
                },
            )

    def test_group(self):
        protocol_info = ProtocolInfo(
            {
                "name": "Test Basic Types",
                "inputs": {
                    "group_test": {"type": "group", "inputs": {"test": "aliquot"}}
                },
            }
        )
        parsed = protocol_info.parse(
            self.protocol,
            {
                "refs": {
                    "ct1test": {"id": "ct1test", "type": "96-pcr", "discard": True}
                },
                "parameters": {"group_test": {"test": "ct1test/0"}},
            },
        )
        assert isinstance(parsed["group_test"], dict)
        assert "test" in parsed["group_test"]
        assert isinstance(parsed["group_test"]["test"], Well)
        with pytest.raises(RuntimeError):
            protocol_info1 = ProtocolInfo(
                {
                    "name": "Test Errors",
                    "inputs": {
                        "group": {
                            "type": "group",
                            "inputs": {
                                "bool": "bool",
                                "aliquot": "aliquot",
                                "aliquot+": "aliquot+",
                            },
                        }
                    },
                }
            )
            protocol_info1.parse(
                self.protocol, {"refs": {}, "parameters": {"group": ["hello"]}}
            )
        with pytest.raises(RuntimeError):
            protocol_info2 = ProtocolInfo(
                {"name": "Test Errors", "inputs": {"group": {"type": "group"}}}
            )
            protocol_info2.parse(
                self.protocol,
                {
                    "refs": {},
                    "parameters": {
                        "group": {
                            "bool": True,
                            "aliquot": "dummy/0",
                            "aliquot+": ["dummy/0"],
                        }
                    },
                },
            )

    def test_multigroup(self):
        protocol_info = ProtocolInfo(
            {
                "name": "Test Basic Types",
                "inputs": {
                    "group_test": {"type": "group+", "inputs": {"test": "aliquot"}}
                },
            }
        )
        parsed = protocol_info.parse(
            self.protocol,
            {
                "refs": {
                    "ct1test": {"id": "ct1test", "type": "96-pcr", "discard": True}
                },
                "parameters": {
                    "group_test": [{"test": "ct1test/0"}, {"test": "ct1test/1"}]
                },
            },
        )
        assert isinstance(parsed["group_test"], list)
        assert 2 == len(parsed["group_test"])
        assert "test" in parsed["group_test"][0]
        assert isinstance(parsed["group_test"][0]["test"], Well)
        assert "test" in parsed["group_test"][1]
        assert isinstance(parsed["group_test"][1]["test"], Well)
        assert 1 == parsed["group_test"][1]["test"].index

        # pragma pylint: disable=duplicate-key
        with pytest.raises(RuntimeError):
            parsed = protocol_info.parse(
                self.protocol,
                {
                    "refs": {
                        "ct1test": {"id": "ct1test", "type": "96-pcr", "discard": True}
                    },
                    "parameters": {
                        "group_test": {"test": "ct1test/0", "test": "ct1test/1"}
                    },
                },
            )
            protocol_info = ProtocolInfo(
                {
                    "name": "Test Basic Types",
                    "inputs": {"group_test": {"type": "group+"}},
                }
            )
            parsed = protocol_info.parse(
                self.protocol,
                {
                    "refs": {
                        "ct1test": {"id": "ct1test", "type": "96-pcr", "discard": True}
                    },
                    "parameters": {
                        "group_test": [{"test": "ct1test/0"}, {"test": "ct1test/1"}]
                    },
                },
            )
        # pragma pylint: enable=duplicate-key

    def test_group_choice(self):
        protocol_info = ProtocolInfo(
            {
                "name": "Test Basic Types",
                "inputs": {
                    "group_test": {
                        "type": "group-choice",
                        "options": [
                            {"value": "a", "inputs": {"test": "aliquot"}},
                            {"value": "b"},
                        ],
                    }
                },
            }
        )
        parsed = protocol_info.parse(
            self.protocol,
            {
                "refs": {
                    "ct1test": {"id": "ct1test", "type": "96-pcr", "discard": True}
                },
                "parameters": {
                    "group_test": {
                        "value": "a",
                        "inputs": {"a": {"test": "ct1test/0"}, "b": {}},
                    }
                },
            },
        )
        assert isinstance(parsed["group_test"], dict)
        assert "a" == parsed["group_test"]["value"]
        assert "a" in parsed["group_test"]["inputs"]
        assert "b" not in parsed["group_test"]["inputs"]
        assert isinstance(parsed["group_test"]["inputs"]["a"]["test"], Well)
        with pytest.raises(RuntimeError):
            parsed = protocol_info.parse(
                self.protocol,
                {
                    "refs": {
                        "ct1test": {"id": "ct1test", "type": "96-pcr", "discard": True}
                    },
                    "parameters": {"group_test": {"value": "a"}},
                },
            )
            parsed = protocol_info.parse(
                self.protocol,
                {
                    "refs": {
                        "ct1test": {"id": "ct1test", "type": "96-pcr", "discard": True}
                    },
                    "parameters": {
                        "group_test": {"inputs": {"a": {"test": "ct1test/0"}, "b": {}}}
                    },
                },
            )

    def test_csv_table(self):
        protocol_info = ProtocolInfo(
            {
                "name": "Test Basic Types",
                "inputs": {
                    "table_test": {
                        "template": {
                            "header": [
                                "Destination Well",
                                "Source Well",
                                "Final concentration in ug/ml",
                            ],
                            "keys": [
                                "dest_well",
                                "source_well",
                                "final_concentration_ugml",
                            ],
                            "col_type": ["integer", "aliquot", "decimal"],
                            "rows": [
                                ["0", "ct17652537/0", "1.2"],
                                ["1", "ct17652537/0", "4.37"],
                            ],
                            "label": "Test Table CSV",
                        },
                        "type": "csv-table",
                        "label": "test table label",
                    }
                },
            }
        )
        parsed = protocol_info.parse(
            self.protocol,
            {
                "refs": {
                    "ct1test": {"id": "ct1test", "type": "micro-1.5", "discard": True},
                    "ct2test": {"id": "ct2test", "type": "micro-1.5", "discard": True},
                },
                "parameters": {
                    "table_test": [
                        {
                            "dest_well": "integer",
                            "source_well": "aliquot",
                            "final_concentration_ugml": "decimal",
                        },
                        [
                            {
                                "dest_well": 0,
                                "source_well": "ct1test/0",
                                "final_concentration_ugml": 0.5,
                            },
                            {
                                "dest_well": 1,
                                "source_well": "ct2test/0",
                                "final_concentration_ugml": 0.6,
                            },
                        ],
                    ]
                },
            },
        )
        assert isinstance(parsed["table_test"], list)
        assert isinstance(parsed["table_test"][0], dict)
        assert "final_concentration_ugml" in parsed["table_test"][0]
        assert isinstance(parsed["table_test"][1]["source_well"], Well)

    def test_blank_default(self):
        protocol_info = ProtocolInfo(
            {
                "name": "Test Basic Blank Defaults",
                "inputs": {
                    "int": "integer",
                    "str": "string",
                    "bool": "bool",
                    "decimal": "decimal",
                    "volume": "volume",
                    "temperature": "temperature",
                    "csv-table": "csv-table",
                },
            }
        )
        parsed = protocol_info.parse(self.protocol, {"refs": {}, "parameters": {}})
        assert parsed["int"] is None
        assert parsed["str"] is None
        assert parsed["bool"] is None
        assert parsed["decimal"] is None
        assert parsed["volume"] is None
        assert parsed["temperature"] is None
        assert isinstance(parsed["csv-table"], list)

    def test_ref_default(self):
        protocol_info = ProtocolInfo(
            {
                "name": "Test Basic Blank Defaults",
                "inputs": {
                    "aliquot": "aliquot",
                    "aliquot+": "aliquot+",
                    "aliquot++": "aliquot++",
                    "container": "container",
                    "container+": "container+",
                },
            }
        )
        parsed = protocol_info.parse(self.protocol, {"refs": {}, "parameters": {}})
        assert parsed["aliquot"] is None
        assert parsed["container"] is None
        assert isinstance(parsed["aliquot+"], WellGroup)
        assert 0 == len(parsed["aliquot+"])
        assert [] == parsed["aliquot++"]
        assert [] == parsed["container+"]

    def test_group_default(self):
        protocol_info = ProtocolInfo(
            {
                "name": "Test Basic Blank Defaults",
                "inputs": {
                    "group": {
                        "type": "group",
                        "inputs": {
                            "bool": "bool",
                            "aliquot": "aliquot",
                            "aliquot+": "aliquot+",
                        },
                    },
                    "group+": {"type": "group+", "inputs": {"bool": "bool"}},
                },
            }
        )
        parsed = protocol_info.parse(self.protocol, {"refs": {}, "parameters": {}})
        assert isinstance(parsed["group"], dict)
        assert parsed["group"]["bool"] is None
        assert parsed["group"]["aliquot"] is None
        assert isinstance(parsed["group"]["aliquot+"], WellGroup)
        assert 0 == len(parsed["group"]["aliquot+"])
        assert [{"bool": None}] == parsed["group+"]

    def test_container_errors(self):
        with pytest.raises(RuntimeError):
            protocol_info1 = ProtocolInfo(
                {"name": "Test Errors", "inputs": {"cont": {"type": "container"}}}
            )
            protocol_info1.parse(
                self.protocol,
                {
                    "refs": {"my_cont": {"type": "micro-1.5", "discard": True}},
                    "parameters": {"cont": "my_cont/0"},
                },
            )
        with pytest.raises(RuntimeError):
            protocol_info1 = ProtocolInfo(
                {"name": "Test Errors", "inputs": {"cont": {"type": "container"}}}
            )
            protocol_info1.parse(
                self.protocol,
                {
                    "refs": {"my_cont": {"type": "micro-1.5", "discard": True}},
                    "parameters": {"cont": "another_cont"},
                },
            )
        with pytest.raises(RuntimeError):
            protocol_info1 = ProtocolInfo(
                {"name": "Test Errors", "inputs": {"cont": {"type": "container"}}}
            )
            protocol_info1.parse(
                self.protocol,
                {
                    "refs": {"my_cont": {"type": "micro-1.5", "discard": True}},
                    "parameters": {"cont": 12},
                },
            )

    def test_container_volumes(self):
        protocol_info1 = ProtocolInfo(
            {
                "name": "Test Container Volumes",
                "inputs": {"cont": {"type": "container"}},
            }
        )
        parsed = protocol_info1.parse(
            self.protocol,
            {
                "refs": {
                    "echo_plate": {
                        "type": "384-echo",
                        "discard": True,
                        "aliquots": {"0": {"volume": "135:microliter"}},
                    }
                },
                "parameters": {"cont": "echo_plate"},
            },
        )
        assert parsed["cont"].well(0).volume == Unit(135, "microliter")

        with pytest.raises(ValueError) as e:
            protocol_info1.parse(
                self.protocol,
                {
                    "refs": {
                        "my_cont": {
                            "type": "384-echo",
                            "discard": True,
                            "aliquots": {"0": {"volume": "10000:microliter"}},
                        }
                    },
                    "parameters": {"cont": "my_cont"},
                },
            )
        assert "Theoretical volume" in str(e.value)

    def test_container_masses(self):
        protocol_info2 = ProtocolInfo(
            {
                "name": "Test Container Masses",
                "inputs": {"cont": {"type": "container"}},
            }
        )
        parsed = protocol_info2.parse(
            self.protocol,
            {
                "refs": {
                    "echo_plate": {
                        "type": "384-echo",
                        "discard": True,
                        "aliquots": {
                            "0": {"volume": "10:microliter", "mass": "100:milligram"}
                        },
                    }
                },
                "parameters": {"cont": "echo_plate"},
            },
        )
        assert parsed["cont"].well(0).mass == Unit(100, "milligram")

        # Test mass value is None
        parsed_no_mass = protocol_info2.parse(
            self.protocol,
            {
                "refs": {
                    "other_plate": {
                        "type": "384-echo",
                        "discard": True,
                        "aliquots": {"0": {"volume": "10:microliter", "mass": None}},
                    }
                },
                "parameters": {"cont": "other_plate"},
            },
        )
        assert parsed_no_mass["cont"].well(0).mass is None

    def test_container_properties(self):
        protocol_info = ProtocolInfo(
            {
                "name": "Test Container Properties",
                "inputs": {"cont": {"type": "container"}},
            }
        )
        user_launch_request_inputs = {
            "parameters": {"cont": "source_plate"},
            "refs": {
                "source_plate": {
                    "label": "source_plate",
                    "type": "res-sw384-lp",
                    "store": "cold_80",
                    "cover": None,
                    "properties": {"key": "value"},
                    "contextual_custom_properties": {
                        "orig_key": "orig_val",
                        "orig_attr": {"akey": "aval"},
                        "orig_ct_list": ["akey", "aval"],
                    },
                    "aliquots": {
                        "0": {
                            "name": None,
                            "volume": "42.0:microliter",
                            "properties": {},
                            "contextual_custom_properties": {
                                "orig_key": "aliquot value"
                            },
                        }
                    },
                }
            },
        }
        parsed = protocol_info.parse(self.protocol, user_launch_request_inputs)
        source_plate = parsed["cont"]
        assert isinstance(source_plate, Container)
        assert source_plate.properties.get("key") == "value"
        assert source_plate.ctx_properties.get("orig_attr") == {"akey": "aval"}
        assert source_plate.ctx_properties.get("orig_ct_list") == [
            "akey",
            "aval",
        ]
        assert source_plate.well(0).ctx_properties.get("orig_key") == "aliquot value"

    # Test parsing of local manifest file
    def test_json_parse(self):
        with open("test/manifest_test.json", "r", encoding="utf-8") as f:
            manifest_json = f.read()
            manifest = Manifest(json.loads(manifest_json))
            source = json.loads(manifest_json)["protocols"][0]["preview"]
            manifest.protocol_info("TestMethod").parse(self.protocol, source)

    def test_seal_on_store(self):
        seal_on_store(self.protocol)
        test = self.protocol.ref("test", None, "96-pcr", storage="cold_20")
        test2 = self.protocol.ref(
            "test2", None, "96-flat", storage="cold_20", cover="standard"
        )
        self.protocol.spin(test, "2000:g", "5:minute")
        self.protocol.spin(test2, "2000:g", "5:minute")
        assert len(self.protocol.instructions) == 3
        self.protocol.uncover(test2)
        seal_on_store(self.protocol)
        assert len(self.protocol.instructions) == 5
        assert self.protocol.instructions[-1].op == "cover"
        assert self.protocol.instructions[-1].lid == "low_evaporation"
        self.protocol.uncover(test2)
        seal_on_store(self.protocol)
        assert len(self.protocol.instructions) == 7
        assert self.protocol.instructions[-1].op == "cover"
        assert self.protocol.instructions[-1].lid == "low_evaporation"

    def test_seal_type_on_store(self):
        seal_on_store(self.protocol)
        test = self.protocol.ref("test", None, "384-pcr", storage="cold_20")
        self.protocol.seal(test, "foil")
        self.protocol.unseal(test)
        seal_on_store(self.protocol)
        assert self.protocol.instructions[-1].type == "ultra-clear"
        test2 = self.protocol.ref("test2", None, "384-pcr", storage="cold_20")
        self.protocol.seal(test2, "ultra-clear")
        self.protocol.unseal(test2)
        seal_on_store(self.protocol)
        assert self.protocol.instructions[-1].type == "ultra-clear"

    def test_cover_type_on_store(self):
        seal_on_store(self.protocol)
        test = self.protocol.ref("test", None, "96-flat-uv", storage="cold_20")
        self.protocol.cover(test, "universal")
        self.protocol.uncover(test)
        seal_on_store(self.protocol)
        assert self.protocol.instructions[-1].lid == "low_evaporation"
        test2 = self.protocol.ref("test2", None, "96-flat-uv", storage="cold_20")
        self.protocol.cover(test2)
        self.protocol.uncover(test2)
        seal_on_store(self.protocol)
        assert self.protocol.instructions[-1].lid == "low_evaporation"

    def test_get_protocol_preview(self):
        preview = get_protocol_preview(
            self.protocol, "TestMethod", manifest="test/manifest_test.json"
        )
        manifest_keys = [
            "my_string",
            "my_container",
            "my_volume",
            "my_length",
            "my_bool",
        ]
        for key in manifest_keys:
            assert key in preview

    def test_compound_type(self):
        protocol_info1 = ProtocolInfo(
            {
                "name": "Test Compound type",
                "inputs": {"compound": {"type": "compound"}},
            }
        )
        parsed = protocol_info1.parse(
            self.protocol,
            {
                "refs": {},
                "parameters": {
                    "compound": {"format": "InChI", "value": "InChI=1S/CH4/h1H4"}
                },
            },
        )
        assert parsed["compound"].value == "InChI=1S/CH4/h1H4"

    def test_multiple_compound_type(self):
        protocol_info1 = ProtocolInfo(
            {
                "name": "Test Compound type",
                "inputs": {"compound": {"type": "compound+"}},
            }
        )
        parsed = protocol_info1.parse(
            self.protocol,
            {
                "refs": {},
                "parameters": {
                    "compound": [
                        {"format": "Daylight Canonical SMILES", "value": "C1=CC=CC=C1"},
                        {"format": "Daylight Canonical SMILES", "value": "CCCC"},
                    ]
                },
            },
        )
        assert parsed["compound"][0].value == "C1=CC=CC=C1"
        assert parsed["compound"][0].format == "Daylight Canonical SMILES"
        assert parsed["compound"][1].value == "CCCC"
        assert parsed["compound"][1].format == "Daylight Canonical SMILES"

    def test_invalid_compound(self):
        with pytest.raises(RuntimeError) as e:
            protocol_info1 = ProtocolInfo(
                {
                    "name": "Test Compound type",
                    "inputs": {"compound": {"type": "compound"}},
                }
            )
            protocol_info1.parse(
                self.protocol,
                {
                    "refs": {},
                    "parameters": {
                        "compound": {
                            "format": "Daylight Canonical SMILES",
                            "value": "C1:CO&",
                        }
                    },
                },
            )

        assert "C1:CO& is not a valid Daylight Canonical SMILES value." in str(e.value)

        with pytest.raises(RuntimeError) as e:
            protocol_info1 = ProtocolInfo(
                {
                    "name": "Test Compound type",
                    "inputs": {"compound": {"type": "compound"}},
                }
            )
            protocol_info1.parse(
                self.protocol,
                {
                    "refs": {},
                    "parameters": {"compound": {"format": "foo", "value": "CCCC"}},
                },
            )

        assert "foo is not an acceptable Compound format." in str(e.value)

    def test_compound_linkage_list(self):
        protocol_info = ProtocolInfo(
            {
                "name": "Test Container With Compounds",
                "inputs": {"cont": {"type": "container"}},
            }
        )
        parsed = protocol_info.parse(
            self.protocol,
            {
                "refs": {
                    "echo_plate": {
                        "type": "384-echo",
                        "discard": True,
                        "aliquots": {
                            "0": {
                                "volume": "10:microliter",
                                "compounds": [
                                    {
                                        "id": "123",
                                        "molecularWeight": 100,
                                        "smiles": "CCCC",
                                        "solubilityFlag": False,
                                        "concentration": 10,
                                    }
                                ],
                            },
                            "1": {
                                "volume": "10:microliter",
                                "compounds": [
                                    {
                                        "id": "123",
                                        "molecularWeight": None,
                                        "concentration": 0,
                                        "solubilityFlag": True,
                                    }
                                ],
                            },
                        },
                    }
                },
                "parameters": {"cont": "echo_plate"},
            },
        )
        expected_compounds_list = [
            {
                "id": "123",
                "molecular_weight": Unit(100, "g/mol"),
                "smiles": "CCCC",
                "solubility_flag": False,
                "concentration": Unit(10, "millimol/liter"),
            }
        ]
        expected_compounds_list_default = [
            {
                "id": "123",
                "molecular_weight": None,
                "smiles": None,
                "solubility_flag": True,
                "concentration": Unit(0, "millimol/liter"),
            }
        ]
        assert parsed["cont"].well(0).compounds == expected_compounds_list
        # check non-specified values set to None
        assert parsed["cont"].well(1).compounds == expected_compounds_list_default


from app import create_app
from app.models import Article,Thumb,db

def myredis(enigne=None):
    import redis
    if enigne==None:
        enigne=redis
    pool = enigne.ConnectionPool(host='127.0.0.1',port=6379,password='')
    redis = enigne.Redis(connection_pool=pool)
    return redis

APP = None
def get_app():
    global APP
    APP = APP if APP is not None else create_app()

def redis_to_mysql():
    get_app()
    with APP.app_context():
        print("hello")
        redis = myredis()
        articles = Article.query.all()
        redis.delete('thumbs_total')
        thumbs = redis.keys(pattern='thumb-*')
        for thumb in thumbs:
            aid = int(thumb.decode().split('-')[1])
            uid_list = redis.smembers(thumb)
            for uid in uid_list:
                with db.submit_data():
                    t = Thumb()
                    t.auth_id=int(uid)
                    t.article_id=aid
                    db.session.add(t)
            redis.delete(thumb)
        for article in articles:
            redis.hset('thumbs_total',article.id,len(article.thumbs))
        print("执行了一次定时任务")


import os
import argparse

from deep_ed_PyTorch.entities.ent_name2id_freq import EntNameID

class MergeCrosswikisWiki(object):
    def __init__(self, args):
        self.args = args
        assert os.path.isdir(args.root_data_dir)

        self.wiki = 'generated/wikipedia_p_e_m.txt'
        self.wiki_file = os.path.join(args.root_data_dir, self.wiki)
        self.cross_wiki = 'basic_data/p_e_m_data/crosswikis_p_e_m.txt'
        self.cross_wiki_file = os.path.join(args.root_data_dir, self.cross_wiki)
        self.out = 'generated/crosswikis_wikipedia_p_e_m.txt'
        self.out_file = os.path.join(args.root_data_dir, self.out)

        self.ent_name_id = EntNameID(self.args)

        self.merged_e_m_counts = dict()
        self.load_from_wiki()
        self.merged_with_cross_wiki()
        self.write_p_e_m()

    @property
    def dict(self):
        return self.merged_e_m_counts

    def load_from_wiki(self):

        print('\nMerging Wikipedia and Crosswikis p_e_m')
        print('Process Wikipedia')

        self.load_from_txt(self.wiki_file)

    def merged_with_cross_wiki(self):
        print('Process Crosswikis')

        self.load_from_txt(self.cross_wiki_file)

    def load_from_txt(self, txt_file):
        with open(txt_file) as reader:
            for line in reader:
                line = line.rstrip('\t\n')
                parts = line.split('\t')
                mention = parts[0]

                if 'Wikipedia' not in mention and 'wikipedia' not in mention:
                    if mention not in self.dict:
                        self.dict[mention] = dict()

                    assert int(parts[1]) >= 1, "wiki total frequency error: {}, {}".format(repr(line), parts[1])
                    total_freq = int(parts[1])

                    num_ents = len(parts) - 2
                    for i in range(2, num_ents + 2):
                        ent_str = parts[i].split(',')

                        ent_wikiid = int(ent_str[0])
                        try:
                            ent_wikiid >= 1, "wiki id error: {}, {}".format(repr(line), ent_wikiid)

                        except:
                            print("wiki id error: {} :**: {}".format(repr(line), ent_wikiid))
                            raise 1

                        assert int(ent_str[1]) >= 1, "wiki frequency error: {}, {}".format(repr(line), ent_str[1])
                        freq = int(ent_str[1])

                        if ent_wikiid not in self.dict[mention]:
                            self.dict[mention][ent_wikiid] = 0

                        self.dict[mention][ent_wikiid] += freq

    def write_p_e_m(self):
        print('====> Now sorting and writing p_m_e_from_wiki..')
        with open(self.out_file, 'w') as writer:
            for mention in self.dict:
                el_list = self.dict[mention]
                sorted_dict_items = sorted(el_list.items(), key=lambda x: x[1], reverse=True)
                s = ''
                total_freq = 0
                num_ents = 0
                for wikiid, freq in sorted_dict_items:
                    if self.ent_name_id.is_valid_ent(wikiid):
                        s += str(wikiid) + ',' + str(freq) + ','
                        s += self.ent_name_id.get_ent_name_from_wikiid(wikiid).replace(' ', '_') + '\t'
                        total_freq += freq
                        num_ents += 1

                        if num_ents >= 100:
                            break

                s = mention + '\t' + str(total_freq) + '\t' + s + '\n'
                writer.write(s)

        print('    Done sorting and writing.')

def test(args):
    merge_crosswikis_wiki = MergeCrosswikisWiki(args)
    return merge_crosswikis_wiki

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='generate the prior dictionary p(e|m) from wikipedia'
    )

    parser.add_argument(
        '--root_data_dir',
        type=str,
        # default='/scratch365/yding4/deep_ed_PyTorch/data/',
        required=True,
        help='Root path of the data, $DATA_PATH.',
    )

    args = parser.parse_args()
    merge_crosswikis_wiki = test(args)


from enum import StrEnum, auto
from math import sin, cos, pi

from shapely import Point, LineString, Polygon
from shapely.affinity import translate, rotate

class SectionType(StrEnum):
    Triangle = auto()
    Rectangle = auto()
    Trapezoid = auto()
    TShape = auto()
    IShape = auto()
    LShape = auto()
    Box = auto()
    Pipe = auto()
    RegularPolygon = auto()
    Circle = auto()
    Ellipse = auto()
    Custom = auto()

def move_centroid_to_origin(section: Polygon) -> Polygon:
    return translate(section, -section.centroid.x, -section.centroid.y)

def TriangleSct(b: float, h: float) -> Polygon:
    sct = Polygon([(0, h), (-b/2, 0), (b/2, 0)])
    return move_centroid_to_origin(sct)

def RectangleSct(b: float, h: float) -> Polygon:
    return Polygon([(b/2, h/2), (-b/2, h/2), (-b/2, -h/2), (b/2, -h/2)])

def TrapzoidSct(b1: float, b2: float, h: float) -> Polygon:
    sct = Polygon([(b1/2, h/2), (-b1/2, h/2), (-b2/2, -h/2), (b2/2, -h/2)])
    return move_centroid_to_origin(sct)

def TShapeSct(b: float, h: float, th1: float, tb1: float,
              th2: float|None=None, tb2: float|None=None) -> Polygon:
    tb2 = tb1 if tb2 == None else tb2
    th2 = th1 if th2 == None else th2
    sct = Polygon([(b/2, h), (-b/2, h), (-b/2, h-th1), (-tb2/2, h-th2),
                  (-tb1/2, 0), (tb1/2, 0), (tb2/2, h-th2), (b/2, h-th1), (b/2, h)])
    return move_centroid_to_origin(sct)

def IShapeSct(b_top: float, t_top: float, c_top: float, h:float, tw: float,
              b_bot: float|None=None, t_bot: float|None=None, c_bot: float|None=None) -> Polygon:
    b_bot = b_top if b_bot==None else b_bot
    t_bot = t_top if t_bot==None else t_bot
    c_bot = c_top if c_bot==None else c_bot
    sct = Polygon([(b_top/2, h/2), (-b_top/2, h/2), (-b_top/2, h/2-t_top), (-tw/2, h/2-t_top-c_top),
                   (-tw/2, -h/2+t_bot+c_bot), (-b_bot/2, -h/2+t_bot), (-b_bot/2, -h/2), (b_bot/2, -h/2),
                   (b_bot/2, -h/2+t_bot), (tw/2, -h/2+t_bot+c_bot), (tw/2, h/2-t_top-c_top), (b_top/2, h/2-t_top),
                   (b_top/2, h/2)])
    return move_centroid_to_origin(sct)

def LShapeSct(b: float, h: float, th1: float, tb1: float,
              th2: float|None=None, tb2: float|None=None) -> Polygon:
    tb2 = tb1 if tb2 == None else tb2
    th2 = th1 if th2 == None else th2
    sct = Polygon([(0, 0), (0, h), (b, h), (b, h-th1),
                  (tb2, h-th2), (tb1, 0), (0, 0)])
    return move_centroid_to_origin(sct)

def BoxSct(b: float, h: float, th: float) -> Polygon:
    outerRect = Polygon(RectangleSct(b, h))
    innerRect = Polygon(RectangleSct(b-2*th, h-2*th))
    return outerRect.difference(innerRect)

def CircleSct(d: float) -> Polygon:
    return Point(0, 0).buffer(d/2)

def PipeSct(d: float, th: float) -> Polygon:
    outerCircle = Polygon(CircleSct(d))
    innerCircle = Polygon(CircleSct(d-(2*th)))
    return outerCircle.difference(innerCircle)

def CreateEllipseSct(a: float, b: float) -> Polygon:
    n = 100
    theta = [2 * pi * i / n for i in range(n)]
    return Polygon([(a*cos(t), b*sin(t)) for t in theta])

def DistanceFrom(section: Polygon, dist: float, position: str="top") -> LineString:
    minx, miny, maxx, maxy = section.bounds
    if (position == "top" or position=="bottom") and (dist > maxy-miny):  # type: ignore
        raise ValueError("distance is greater than height of shape.")
    if (position == "right" or position=="left") and (dist > maxx-minx):  # type: ignore
        raise ValueError("distance is greater than width of shape.")
    line = LineString([(maxx+10, maxy-dist), (minx-10, maxy-dist)]) if position=="top" else \
               LineString([(maxx+10, miny+dist), (minx-10, miny+dist)]) if position=="bottom" else \
               LineString([(maxx-dist, maxy+10), (maxx-dist, miny-10)]) if position=="right" else \
               LineString([(minx+dist, maxy+10), (minx+dist, miny-10)]) if position=="left" else None
    return section.intersection(line)

def Edge(section: Polygon, position: str = "top") -> LineString:
    coords = list(section.exterior.coords)
    del coords[-1]
    minx, miny, maxx, maxy = section.bounds
    Points = [point for point in coords if point[1]==maxy] if position=="top" else\
                [point for point in coords if point[1]==miny] if position=="bottom" else\
                [point for point in coords if point[0]==maxx] if position=="right" else\
                [point for point in coords if point[0]==minx] if position=="left" else None
    spoint1 = (0, 0)
    spoint2 = (0, 0)
    IsThreePoint: bool = False
    if Points==None: raise ValueError("position is wrong")
    if len(Points) > 1:
        output = LineString(Points)
    else:
        firstPoint = Points[0]
        secondPoint = (0, 0)
        if coords.index(firstPoint)==0:
            secondPoint = coords[coords.index(firstPoint)+1]
        elif coords.index(firstPoint)==len(coords)-1:
            secondPoint = coords[coords.index(firstPoint)-1]
        else:
            spoint1 = coords[coords.index(firstPoint)-1]
            spoint2 = coords[coords.index(firstPoint)+1]
            if position == "top":
                IsThreePoint = firstPoint[1]-spoint1[1] == firstPoint[1]-spoint2[1]
                secondPoint = spoint1 if firstPoint[1]-spoint1[1] < firstPoint[1]-spoint2[1] else spoint2
            elif position == "bottom":
                IsThreePoint = spoint1[1]-firstPoint[1] == spoint2[1]-firstPoint[1]
                secondPoint = spoint1 if spoint1[1]-firstPoint[1] < spoint2[1]-firstPoint[1] else spoint2
            elif position == "right":
                IsThreePoint = firstPoint[0]-spoint1[0] == firstPoint[0]-spoint2[0]
                secondPoint = spoint1 if firstPoint[0]-spoint1[0] < firstPoint[0]-spoint2[0] else spoint2
            elif position == "left":
                IsThreePoint = spoint1[0]-firstPoint[0] == spoint2[0]-firstPoint[0]
                secondPoint = spoint1 if spoint1[0]-firstPoint[0] < spoint2[0]-firstPoint[0] else spoint2

        output = LineString([spoint1, firstPoint, spoint2]) if IsThreePoint else LineString([firstPoint, secondPoint])
    return output


import Resampling as rs
import MosaicImage as mi
import MaskImage as mki
import StackBands as ms
import os
import Tkinter
import tkFileDialog
# import shutil

jp2_images_dir = '/1_jp2_images/'
resampled_images_dir = '/2_resampled_images/'
mosaiced_image_dir = '/3_mosaiced_image/'
masked_image_dir = '/4_masked_image/'
stacked_bands_dir = '/5_stacked_bands/'

root = Tkinter.Tk()
root.withdraw()
S2_zip = tkFileDialog.askopenfilenames(parent=root, title='Choose at least two Sentinel 2 products', filetypes=(("S2 Zip File","*.zip"), ))
zip_path_list = list(S2_zip)

work_dir = raw_input("Choose name for working directory: ")
cwd = os.getcwd() + '/' + work_dir
os.mkdir(cwd)
os.mkdir(cwd + jp2_images_dir)
os.mkdir(cwd + resampled_images_dir)
os.mkdir(cwd + mosaiced_image_dir)
os.mkdir(cwd + masked_image_dir)
os.mkdir(cwd + stacked_bands_dir)

rs.resampling(cwd + jp2_images_dir, cwd + resampled_images_dir, zip_path_list)
# work_dir = 'Prova'
# cwd = os.getcwd() + '/' + work_dir
mi.mosaic_images(cwd + resampled_images_dir, cwd + mosaiced_image_dir)
# work_dir = 'Prova'
# cwd = os.getcwd() + '/' + work_dir
geojson_path = tkFileDialog.askopenfilenames(parent=root, title='Choose a valid geoJSON file', filetypes=(("GeoJSON File","*.json"), ))
mki.mask_image(cwd + mosaiced_image_dir, cwd + masked_image_dir, geojson_path[0])
# work_dir = 'Prova'
# cwd = os.getcwd() + '/' + work_dir
ms.stack_bands(cwd + masked_image_dir, cwd + stacked_bands_dir)
# shutil.rmtree(cwd + jp2_images_dir)
# shutil.rmtree(cwd + resampled_images_dir)


import sys

sys.stdin = open("input.txt")

T = int(input())

for test_case in range(1, T+1):
    print(f'#{test_case}', end=' ')

    # 숫자의 길이, 숫자들의 list 받아서 정렬하기
    N = int(input())
    num_list = sorted(list(map(int, input().split())))

    # 뒤에서 하나 앞에서 하나 번갈아가면서 5개씩 출력하기
    for i in range(5):
        print(num_list[-(i+1)], end=' ')
        print(num_list[i], end=' ')
    print()


import numpy as np
import os
import cv2
from sklearn import preprocessing
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn import metrics

def reading_data():
    data = []
    labels = []
    dataset_path = "animals"
    class_folders = os.listdir(dataset_path)

    for class_name in class_folders:
        image_list = os.listdir(dataset_path +  '/' + class_name)
        for image in image_list:
            image = cv2.imread(dataset_path +  '/' + class_name + '/' + image)
            image = cv2.resize(image, (32, 32),interpolation=cv2.INTER_CUBIC)
            data.append(image)
            labels.append(class_name)
    return (data, labels)

def loading_data(data, labels):
    x = np.array(data)
    y = np.array(labels)
    return (x,y)

def encoding_data(x,y):
    label_encoder = preprocessing.LabelEncoder()
    x = x.reshape((x.shape[0],3072))
    y = label_encoder.fit_transform(y)
    return (x,y)

def train_validation_test(x,y, train_ratio, val_ratio, test_ratio):
    second_ratio = (val_ratio)/(train_ratio + val_ratio)
    train_x, test_x, train_y, test_y = train_test_split(x,y, test_size = test_ratio, random_state = 27)
    train_x, val_x, train_y, val_y= train_test_split(train_x,train_y, test_size = second_ratio, random_state = 27)
    return train_x, test_x, train_y, test_y, val_x, val_y

def metrics_score(y_test, y_pred):
    print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
    print("Precision:",metrics.precision_score(y_test, y_pred, average= 'weighted'))
    print("Recall:",metrics.recall_score(y_test, y_pred, average= 'weighted'))
    print("F Score:",metrics.f1_score(y_test,y_pred, average = 'weighted'))

def knn(train_x, test_x, train_y, test_y, neighbors, metrics):
    for neighbor in neighbors:
        for metric in metrics:
            model = KNeighborsClassifier(n_neighbors=neighbor, p=metric)
            model.fit(train_x, train_y)
            y_predict = model.predict(test_x)
            print("Neighborhood = {}, L{}".format(neighbor, metric))
            metrics_score(test_y, y_predict)
            print()

x,y = reading_data()
x,y = loading_data(x,y)
x,y = encoding_data(x,y)
train_x, test_x, train_y, test_y, val_x, val_y = train_validation_test(x,y, 0.7, 0.1, 0.2)

print("KNN Classifier.")
#Cross validation for K = [3,5,7] and L = [L1,L2]
print('Evaluating perfomance over the predictions in the validation set:')
knn(train_x, val_x, train_y, val_y, [3,5,7], [1,2])
#Testing the KNN classifier over the actual testing set
print('Evaluating perfomance over the predictions in the testing set:')
knn(train_x, test_x, train_y, test_y, [7], [1])


import streamlit as st
from PIL import Image
import io
import numpy as np
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
from pathlib import Path
from matplotlib.colors import to_hex

def get_palette(imagem_carregada, n_cores):

    with open('imagem.jpg', 'wb') as file:
        # Salva a imagem
        file.write(imagem_carregada.getbuffer())

        # Lê a imagem
        image = Image.open('imagem.jpg')

        #Transforma os Pixels em uma matriz
        N, M = image.size
        X = np.asarray(image).reshape((N*M), 3)

        # Cria e aplica o K-means
        model = KMeans(n_clusters=n_cores).fit(X)

        # Captura as cores médias dos grupos gerados no K-means
        cores = model.cluster_centers_.astype('uint8')[np.newaxis]
        cores_hex = [to_hex(cor/255) for cor in cores[0]]

        # Apaga a imagem
        try:
            Path('imagem.jpg').unlink()
        except:
            print("Erro ao apagar a imagem")

        # Retorna as cores
        return cores, cores_hex

def show(cores):
    figure = plt.figure()
    plt.imshow(cores)
    plt.axis('off')
    return figure

def download(figura):
    imagem = io.BytesIO()
    figura.savefig(imagem, format="png")
    plt.axis('off')
    return imagem

st.title("Gerador de Paletas")

# Campo de Input da Imagem
imagem = st.file_uploader(label="Carregue uma Imagem", type=["jpg","jpeg","png"])

# Divide a página em colunas
col1, col2 = st.columns([.7, .3])

#Quando uma imagem for fornecida na entrada, realiza as ações abaixo
if(imagem):
    # Cria um Preview da imagem da entrada redimensionada
    preview = Image.open(imagem).resize((320,320))

    # Exibe o preview da imagem
    col1.image(preview)

    # Campo de Input da quantidade de cores desejadas na paleta
    n_cores = col2.slider("Quantidade de Cores", min_value=2, max_value=8, value=5)

    botao_gerar_paleta = col2.button("Gerar Paleta")

    if(botao_gerar_paleta):
        # Recebe da função de gerar paleta as cores
        cores, cores_hex = get_palette(imagem, n_cores)

        # Recebe da função correspondente a figura da paleta
        figura = show(cores)

        # Exibe a figura da paleta
        st.pyplot(fig=figura)

        # Exibe as cores em hexadecimal
        st.code(f"{cores_hex}")

        # Exibe o botão para download da imagem da paleta gerada pela função correspondente
        col2.download_button("Baixar Paleta", download(figura), "paleta.png", "image/png")


from panda3d.core import *
from toontown.distributed.ToontownMsgTypes import *
from toontown.char import Char
from otp.avatar import Avatar
from toontown.toon import Toon
from toontown.toon import LocalToon
from toontown.toon import ToonDNA
from toontown.char import CharDNA
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.fsm import StateData
from toontown.toonbase import ToontownGlobals
from direct.actor.Actor import Actor
from direct.task import Task
from direct.gui.DirectGui import *
from toontown.toonbase import TTLocalizer
from .MakeAToonGlobals import *
from direct.interval.IntervalGlobal import *
from direct.directnotify import DirectNotifyGlobal
from toontown.toontowngui import TTDialog
from . import GenderShop
from . import BodyShop
from . import ColorShop
from . import MakeClothesGUI
from . import NameShop
import random

class MakeAToon(StateData.StateData):
    notify = DirectNotifyGlobal.directNotify.newCategory('MakeAToon')

    def __init__(self, parentFSM, avList, doneEvent, index, isPaid):
        self.isPaid = isPaid
        StateData.StateData.__init__(self, doneEvent)
        self.phase = 3
        self.names = ['',
         '',
         '',
         '']
        self.dnastring = None
        self.dna = None
        self.progressing = 0
        self.toonPosition = Point3(-1.62, -3.49, 0)
        self.toonScale = Point3(1, 1, 1)
        self.toonHpr = Point3(180, 0, 0)
        self.leftTime = 1.6
        self.rightTime = 1
        self.slide = 0
        self.nameList = []
        self.warp = 0
        for av in avList:
            if av.position == index:
                self.warp = 1
                self.namelessPotAv = av
            self.nameList.append(av.name)

        self.fsm = ClassicFSM.ClassicFSM('MakeAToon', [State.State('Init', self.enterInit, self.exitInit, ['GenderShop', 'NameShop']),
         State.State('GenderShop', self.enterGenderShop, self.exitGenderShop, ['BodyShop']),
         State.State('BodyShop', self.enterBodyShop, self.exitBodyShop, ['GenderShop', 'ColorShop']),
         State.State('ColorShop', self.enterColorShop, self.exitColorShop, ['BodyShop', 'ClothesShop']),
         State.State('ClothesShop', self.enterClothesShop, self.exitClothesShop, ['ColorShop', 'NameShop']),
         State.State('NameShop', self.enterNameShop, self.exitNameShop, ['ClothesShop']),
         State.State('Done', self.enterDone, self.exitDone, [])], 'Init', 'Done')
        self.parentFSM = parentFSM
        self.parentFSM.getStateNamed('createAvatar').addChild(self.fsm)
        self.gs = GenderShop.GenderShop(self, 'GenderShop-done')
        self.bs = BodyShop.BodyShop('BodyShop-done')
        self.cos = ColorShop.ColorShop('ColorShop-done')
        self.cls = MakeClothesGUI.MakeClothesGUI('ClothesShop-done')
        self.ns = NameShop.NameShop(self, 'NameShop-done', avList, index, self.isPaid)
        self.shop = GENDERSHOP
        self.shopsVisited = []
        if self.warp:
            self.shopsVisited = [GENDERSHOP,
             BODYSHOP,
             COLORSHOP,
             CLOTHESSHOP]
        self.music = None
        self.soundBack = None
        self.fsm.enterInitialState()
        self.hprDelta = -1
        self.dropIval = None
        self.roomSquishIval = None
        self.propSquishIval = None
        self.focusOutIval = None
        self.focusInIval = None
        self.toon = None
        return

    def getToon(self):
        return self.toon

    def enter(self):
        self.notify.debug('Starting Make A Toon.')
        if base.config.GetBool('want-qa-regression', 0):
            self.notify.info('QA-REGRESSION: MAKEATOON: Starting Make A Toon')
        base.cr.centralLogger.writeClientEvent('MAT - startingMakeAToon')
        base.camLens.setFov(ToontownGlobals.MakeAToonCameraFov)
        base.playMusic(self.music, looping=1, volume=self.musicVolume)
        camera.setPosHpr(-5.7, -12.3501, 2.15, -24.8499, 2.73, 0)
        if self.warp:
            if self.toon.style.torso[1] == 's':
                self.toon.gender = 's'
            else:
                self.toon.gender = 'd'
            self.toon.reparentTo(render)
            self.toon.loop('neutral')
            self.toon.setPosHpr(-4.1, -2, 0, 200, 0, 0)
        self.guiTopBar.show()
        self.guiBottomBar.show()
        self.guiCancelButton.show()
        if self.warp:
            self.progressing = 0
            self.guiLastButton.hide()
            self.fsm.request('NameShop')
        else:
            self.fsm.request('GenderShop')

    def exit(self):
        base.camLens.setFov(ToontownGlobals.DefaultCameraFov)
        self.guiTopBar.hide()
        self.guiBottomBar.hide()
        self.music.stop()
        self.fsm.request('Done')
        self.room.reparentTo(hidden)

    def load(self):
        gui = loader.loadModel('phase_3/models/gui/tt_m_gui_mat_mainGui')
        guiAcceptUp = gui.find('**/tt_t_gui_mat_okUp')
        guiAcceptDown = gui.find('**/tt_t_gui_mat_okDown')
        guiCancelUp = gui.find('**/tt_t_gui_mat_closeUp')
        guiCancelDown = gui.find('**/tt_t_gui_mat_closeDown')
        guiNextUp = gui.find('**/tt_t_gui_mat_nextUp')
        guiNextDown = gui.find('**/tt_t_gui_mat_nextDown')
        guiNextDisabled = gui.find('**/tt_t_gui_mat_nextDisabled')
        skipTutorialUp = gui.find('**/tt_t_gui_mat_skipUp')
        skipTutorialDown = gui.find('**/tt_t_gui_mat_skipDown')
        rotateUp = gui.find('**/tt_t_gui_mat_arrowRotateUp')
        rotateDown = gui.find('**/tt_t_gui_mat_arrowRotateDown')
        self.guiTopBar = DirectFrame(relief=None, text=TTLocalizer.CreateYourToon, text_font=ToontownGlobals.getSignFont(), text_fg=(0.0, 0.65, 0.35, 1), text_scale=0.18, text_pos=(0, -0.03), pos=(0, 0, 0.86))
        self.guiTopBar.hide()
        self.guiBottomBar = DirectFrame(relief=None, image_scale=(1.25, 1, 1), pos=(0.01, 0, -0.86))
        self.guiBottomBar.hide()
        self.guiCheckButton = DirectButton(parent=self.guiBottomBar, relief=None, image=(guiAcceptUp,
         guiAcceptDown,
         guiAcceptUp,
         guiAcceptDown), image_scale=halfButtonScale, image1_scale=halfButtonHoverScale, image2_scale=halfButtonHoverScale, pos=(1.165, 0, -0.018), command=self.__handleNext, text=('', TTLocalizer.MakeAToonDone, TTLocalizer.MakeAToonDone), text_font=ToontownGlobals.getInterfaceFont(), text_scale=0.08, text_align=TextNode.ARight, text_pos=(0.13, 0.13), text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 1))
        self.guiCheckButton.hide()
        self.guiCancelButton = DirectButton(parent=self.guiBottomBar, relief=None, image=(guiCancelUp,
         guiCancelDown,
         guiCancelUp,
         guiCancelDown), image_scale=halfButtonScale, image1_scale=halfButtonHoverScale, image2_scale=halfButtonHoverScale, pos=(-1.179, 0, -0.011), command=self.__handleCancel, text=('', TTLocalizer.MakeAToonCancel, TTLocalizer.MakeAToonCancel), text_font=ToontownGlobals.getInterfaceFont(), text_scale=TTLocalizer.MATguiCancelButton, text_pos=(0, 0.115), text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 1))
        self.guiCancelButton.hide()
        self.guiNextButton = DirectButton(parent=self.guiBottomBar, relief=None, image=(guiNextUp,
         guiNextDown,
         guiNextUp,
         guiNextDisabled), image_scale=(0.3, 0.3, 0.3), image1_scale=(0.35, 0.35, 0.35), image2_scale=(0.35, 0.35, 0.35), pos=(1.165, 0, -0.018), command=self.__handleNext, text=('',
         TTLocalizer.MakeAToonNext,
         TTLocalizer.MakeAToonNext,
         ''), text_font=ToontownGlobals.getInterfaceFont(), text_scale=TTLocalizer.MATguiNextButton, text_pos=(0, 0.115), text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 1))
        self.guiNextButton.hide()
        self.guiLastButton = DirectButton(parent=self.guiBottomBar, relief=None, image=(guiNextUp,
         guiNextDown,
         guiNextUp,
         guiNextDown), image3_color=Vec4(0.5, 0.5, 0.5, 0.75), image_scale=(-0.3, 0.3, 0.3), image1_scale=(-0.35, 0.35, 0.35), image2_scale=(-0.35, 0.35, 0.35), pos=(0.825, 0, -0.018), command=self.__handleLast, text=('',
         TTLocalizer.MakeAToonLast,
         TTLocalizer.MakeAToonLast,
         ''), text_font=ToontownGlobals.getInterfaceFont(), text_scale=0.08, text_pos=(0, 0.115), text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 1))
        self.guiLastButton.hide()
        self.rotateLeftButton = DirectButton(parent=self.guiBottomBar, relief=None, image=(rotateUp,
         rotateDown,
         rotateUp,
         rotateDown), image_scale=(-0.4, 0.4, 0.4), image1_scale=(-0.5, 0.5, 0.5), image2_scale=(-0.5, 0.5, 0.5), pos=(-0.329249, 0, 0.202961))
        self.rotateLeftButton.hide()
        self.rotateLeftButton.bind(DGG.B1PRESS, self.rotateToonLeft)
        self.rotateLeftButton.bind(DGG.B1RELEASE, self.stopToonRotateLeftTask)
        self.rotateRightButton = DirectButton(parent=self.guiBottomBar, relief=None, image=(rotateUp,
         rotateDown,
         rotateUp,
         rotateDown), image_scale=(0.4, 0.4, 0.4), image1_scale=(0.5, 0.5, 0.5), image2_scale=(0.5, 0.5, 0.5), pos=(0.309534, 0, 0.206116))
        self.rotateRightButton.hide()
        self.rotateRightButton.bind(DGG.B1PRESS, self.rotateToonRight)
        self.rotateRightButton.bind(DGG.B1RELEASE, self.stopToonRotateRightTask)
        gui.removeNode()
        self.roomDropActor = Actor()
        self.roomDropActor.loadModel('phase_3/models/makeatoon/roomAnim_model')
        self.roomDropActor.loadAnims({'drop': 'phase_3/models/makeatoon/roomAnim_roomDrop'})
        self.roomDropActor.reparentTo(render)
        self.dropJoint = self.roomDropActor.find('**/droppingJoint')
        self.roomSquishActor = Actor()
        self.roomSquishActor.loadModel('phase_3/models/makeatoon/roomAnim_model')
        self.roomSquishActor.loadAnims({'squish': 'phase_3/models/makeatoon/roomAnim_roomSquish'})
        self.roomSquishActor.reparentTo(render)
        self.squishJoint = self.roomSquishActor.find('**/scalingJoint')
        self.propSquishActor = Actor()
        self.propSquishActor.loadModel('phase_3/models/makeatoon/roomAnim_model')
        self.propSquishActor.loadAnims({'propSquish': 'phase_3/models/makeatoon/roomAnim_propSquish'})
        self.propSquishActor.reparentTo(render)
        self.propSquishActor.pose('propSquish', 0)
        self.propJoint = self.propSquishActor.find('**/propJoint')
        self.spotlightActor = Actor()
        self.spotlightActor.loadModel('phase_3/models/makeatoon/roomAnim_model')
        self.spotlightActor.loadAnims({'spotlightShake': 'phase_3/models/makeatoon/roomAnim_spotlightShake'})
        self.spotlightActor.reparentTo(render)
        self.spotlightJoint = self.spotlightActor.find('**/spotlightJoint')
        ee = DirectFrame(pos=(-1, 1, 1), frameSize=(-.01, 0.01, -.01, 0.01), frameColor=(0, 0, 0, 0.05), state='normal')
        ee.bind(DGG.B1PRESS, lambda x, ee = ee: self.toggleSlide())
        self.eee = ee
        self.room = loader.loadModel('phase_3/models/makeatoon/tt_m_ara_mat_room')
        self.genderWalls = self.room.find('**/genderWalls')
        self.genderProps = self.room.find('**/genderProps')
        self.bodyWalls = self.room.find('**/bodyWalls')
        self.bodyProps = self.room.find('**/bodyProps')
        self.colorWalls = self.room.find('**/colorWalls')
        self.colorProps = self.room.find('**/colorProps')
        self.clothesWalls = self.room.find('**/clothWalls')
        self.clothesProps = self.room.find('**/clothProps')
        self.nameWalls = self.room.find('**/nameWalls')
        self.nameProps = self.room.find('**/nameProps')
        self.background = self.room.find('**/background')
        self.background.reparentTo(render)
        self.floor = self.room.find('**/floor')
        self.floor.reparentTo(render)
        self.spotlight = self.room.find('**/spotlight')
        self.spotlight.reparentTo(self.spotlightJoint)
        self.spotlight.setColor(1, 1, 1, 0.3)
        self.spotlight.setPos(1.18, -1.27, 0.41)
        self.spotlight.setScale(2.6)
        self.spotlight.setHpr(0, 0, 0)
        smokeSeqNode = SequenceNode('smoke')
        smokeModel = loader.loadModel('phase_3/models/makeatoon/tt_m_ara_mat_smoke')
        smokeFrameList = list(smokeModel.findAllMatches('**/smoke_*'))
        smokeFrameList.reverse()
        for smokeFrame in smokeFrameList:
            smokeSeqNode.addChild(smokeFrame.node())

        smokeSeqNode.setFrameRate(12)
        self.smoke = render.attachNewNode(smokeSeqNode)
        self.smoke.setScale(1, 1, 0.75)
        self.smoke.hide()
        if self.warp:
            self.dna = ToonDNA.ToonDNA()
            self.dna.makeFromNetString(self.namelessPotAv.dna)
            self.toon = Toon.Toon()
            self.toon.setDNA(self.dna)
            self.toon.useLOD(1000)
            self.toon.setNameVisible(0)
            self.toon.startBlink()
            self.toon.startLookAround()
        self.gs.load()
        self.bs.load()
        self.cos.load()
        self.cls.load()
        self.ns.load()
        self.music = base.loader.loadMusic('phase_3/audio/bgm/create_a_toon.ogg')
        self.musicVolume = base.config.GetFloat('makeatoon-music-volume', 1)
        self.sfxVolume = base.config.GetFloat('makeatoon-sfx-volume', 1)
        self.soundBack = base.loader.loadSfx('phase_3/audio/sfx/GUI_create_toon_back.ogg')
        self.crashSounds = []
        self.crashSounds.append(base.loader.loadSfx('phase_3/audio/sfx/tt_s_ara_mat_crash_boing.ogg'))
        self.crashSounds.append(base.loader.loadSfx('phase_3/audio/sfx/tt_s_ara_mat_crash_glassBoing.ogg'))
        self.crashSounds.append(base.loader.loadSfx('phase_3/audio/sfx/tt_s_ara_mat_crash_wood.ogg'))
        self.crashSounds.append(base.loader.loadSfx('phase_3/audio/sfx/tt_s_ara_mat_crash_woodBoing.ogg'))
        self.crashSounds.append(base.loader.loadSfx('phase_3/audio/sfx/tt_s_ara_mat_crash_woodGlass.ogg'))
        return

    def unload(self):
        self.exit()
        if self.toon:
            self.toon.stopBlink()
            self.toon.stopLookAroundNow()
        self.gs.unload()
        self.bs.unload()
        self.cos.unload()
        self.cls.unload()
        self.ns.unload()
        del self.gs
        del self.bs
        del self.cos
        del self.cls
        del self.ns
        self.guiTopBar.destroy()
        self.guiBottomBar.destroy()
        self.guiCancelButton.destroy()
        self.guiCheckButton.destroy()
        self.eee.destroy()
        self.guiNextButton.destroy()
        self.guiLastButton.destroy()
        self.rotateLeftButton.destroy()
        self.rotateRightButton.destroy()
        del self.guiTopBar
        del self.guiBottomBar
        del self.guiCancelButton
        del self.guiCheckButton
        del self.eee
        del self.guiNextButton
        del self.guiLastButton
        del self.rotateLeftButton
        del self.rotateRightButton
        del self.names
        del self.dnastring
        del self.nameList
        del self.music
        del self.soundBack
        del self.dna
        if self.toon:
            self.toon.delete()
        del self.toon
        self.cleanupDropIval()
        self.cleanupRoomSquishIval()
        self.cleanupPropSquishIval()
        self.cleanupFocusInIval()
        self.cleanupFocusOutIval()
        self.room.removeNode()
        del self.room
        self.genderWalls.removeNode()
        self.genderProps.removeNode()
        del self.genderWalls
        del self.genderProps
        self.bodyWalls.removeNode()
        self.bodyProps.removeNode()
        del self.bodyWalls
        del self.bodyProps
        self.colorWalls.removeNode()
        self.colorProps.removeNode()
        del self.colorWalls
        del self.colorProps
        self.clothesWalls.removeNode()
        self.clothesProps.removeNode()
        del self.clothesWalls
        del self.clothesProps
        self.nameWalls.removeNode()
        self.nameProps.removeNode()
        del self.nameWalls
        del self.nameProps
        self.background.removeNode()
        del self.background
        self.floor.removeNode()
        del self.floor
        self.spotlight.removeNode()
        del self.spotlight
        self.smoke.removeNode()
        del self.smoke
        while len(self.crashSounds):
            del self.crashSounds[0]

        self.parentFSM.getStateNamed('createAvatar').removeChild(self.fsm)
        del self.parentFSM
        del self.fsm
        self.ignoreAll()
        loader.unloadModel('phase_3/models/gui/create_a_toon_gui')
        loader.unloadModel('phase_3/models/gui/create_a_toon')
        ModelPool.garbageCollect()
        TexturePool.garbageCollect()

    def getDNA(self):
        return self.dnastring

    def __handleBodyShop(self):
        self.fsm.request('BodyShop')

    def __handleClothesShop(self):
        self.fsm.request('ClothesShop')

    def __handleColorShop(self):
        self.fsm.request('ColorShop')

    def __handleNameShop(self):
        self.fsm.request('NameShop')

    def __handleCancel(self):
        self.doneStatus = 'cancel'
        self.shopsVisited = []
        base.transitions.fadeOut(finishIval=EventInterval(self.doneEvent))

    def toggleSlide(self):
        self.slide = 1 - self.slide

    def goToNextShop(self):
        self.progressing = 1
        if self.shop == GENDERSHOP:
            self.fsm.request('BodyShop')
        elif self.shop == BODYSHOP:
            self.fsm.request('ColorShop')
        elif self.shop == COLORSHOP:
            self.fsm.request('ClothesShop')
        else:
            self.fsm.request('NameShop')

    def goToLastShop(self):
        self.progressing = 0
        if self.shop == BODYSHOP:
            self.fsm.request('GenderShop')
        elif self.shop == COLORSHOP:
            self.fsm.request('BodyShop')
        elif self.shop == CLOTHESSHOP:
            self.fsm.request('ColorShop')
        else:
            self.fsm.request('ClothesShop')

    def charSez(self, char, statement, dialogue = None):
        import pdb
        pdb.set_trace()
        char.setChatAbsolute(statement, CFSpeech, dialogue)

    def enterInit(self):
        pass

    def exitInit(self):
        pass

    def enterGenderShop(self):
        base.cr.centralLogger.writeClientEvent('MAT - enteringGenderShop')
        self.shop = GENDERSHOP
        if GENDERSHOP not in self.shopsVisited:
            self.shopsVisited.append(GENDERSHOP)
            self.genderWalls.reparentTo(self.squishJoint)
            self.genderProps.reparentTo(self.propJoint)
            self.roomSquishActor.pose('squish', 0)
            self.guiNextButton['state'] = DGG.DISABLED
        else:
            self.dropRoom(self.genderWalls, self.genderProps)
        self.guiTopBar['text'] = TTLocalizer.CreateYourToonTitle
        self.guiTopBar['text_fg'] = (1, 0.92, 0.2, 1)
        self.guiTopBar['text_scale'] = TTLocalizer.MATenterGenderShop
        base.transitions.fadeIn()
        self.accept('GenderShop-done', self.__handleGenderShopDone)
        self.gs.enter()
        self.guiNextButton.show()
        self.gs.showButtons()
        self.rotateLeftButton.hide()
        self.rotateRightButton.hide()

    def exitGenderShop(self):
        self.squishRoom(self.genderWalls)
        self.squishProp(self.genderProps)
        self.gs.exit()
        self.ignore('GenderShop-done')

    def __handleGenderShopDone(self):
        self.guiNextButton.hide()
        self.gs.hideButtons()
        self.goToNextShop()

    def bodyShopOpening(self):
        self.bs.showButtons()
        self.guiNextButton.show()
        self.guiLastButton.show()
        self.rotateLeftButton.show()
        self.rotateRightButton.show()

    def enterBodyShop(self):
        base.cr.centralLogger.writeClientEvent('MAT - enteringBodyShop')
        self.toon.show()
        self.shop = BODYSHOP
        self.guiTopBar['text'] = TTLocalizer.ShapeYourToonTitle
        self.guiTopBar['text_fg'] = (0.0, 0.98, 0.5, 1)
        self.guiTopBar['text_scale'] = TTLocalizer.MATenterBodyShop
        self.accept('BodyShop-done', self.__handleBodyShopDone)
        self.dropRoom(self.bodyWalls, self.bodyProps)
        self.bs.enter(self.toon, self.shopsVisited)
        if BODYSHOP not in self.shopsVisited:
            self.shopsVisited.append(BODYSHOP)
        self.bodyShopOpening()

    def exitBodyShop(self):
        self.squishRoom(self.bodyWalls)
        self.squishProp(self.bodyProps)
        self.bs.exit()
        self.ignore('BodyShop-done')

    def __handleBodyShopDone(self):
        self.guiNextButton.hide()
        self.guiLastButton.hide()
        if self.bs.doneStatus == 'next':
            self.bs.hideButtons()
            self.goToNextShop()
        else:
            self.bs.hideButtons()
            self.goToLastShop()

    def colorShopOpening(self):
        self.cos.showButtons()
        self.guiNextButton.show()
        self.guiLastButton.show()
        self.rotateLeftButton.show()
        self.rotateRightButton.show()

    def enterColorShop(self):
        base.cr.centralLogger.writeClientEvent('MAT - enteringColorShop')
        self.shop = COLORSHOP
        self.guiTopBar['text'] = TTLocalizer.PaintYourToonTitle
        self.guiTopBar['text_fg'] = (0, 1, 1, 1)
        self.guiTopBar['text_scale'] = TTLocalizer.MATenterColorShop
        self.accept('ColorShop-done', self.__handleColorShopDone)
        self.dropRoom(self.colorWalls, self.colorProps)
        self.toon.setPos(self.toonPosition)
        self.colorShopOpening()
        self.cos.enter(self.toon, self.shopsVisited)
        if COLORSHOP not in self.shopsVisited:
            self.shopsVisited.append(COLORSHOP)

    def exitColorShop(self):
        self.squishRoom(self.colorWalls)
        self.squishProp(self.colorProps)
        self.cos.exit()
        self.ignore('ColorShop-done')

    def __handleColorShopDone(self):
        self.guiNextButton.hide()
        self.guiLastButton.hide()
        if self.cos.doneStatus == 'next':
            self.cos.hideButtons()
            self.goToNextShop()
        else:
            self.cos.hideButtons()
            self.goToLastShop()

    def clothesShopOpening(self):
        self.guiNextButton.show()
        self.guiLastButton.show()
        self.cls.showButtons()
        self.rotateLeftButton.show()
        self.rotateRightButton.show()

    def enterClothesShop(self):
        base.cr.centralLogger.writeClientEvent('MAT - enteringClothesShop')
        self.shop = CLOTHESSHOP
        self.guiTopBar['text'] = TTLocalizer.PickClothesTitle
        self.guiTopBar['text_fg'] = (1, 0.92, 0.2, 1)
        self.guiTopBar['text_scale'] = TTLocalizer.MATenterClothesShop
        self.accept('ClothesShop-done', self.__handleClothesShopDone)
        self.dropRoom(self.clothesWalls, self.clothesProps)
        self.toon.setScale(self.toonScale)
        self.toon.setPos(self.toonPosition)
        if not self.progressing:
            self.toon.setHpr(self.toonHpr)
        self.clothesShopOpening()
        self.cls.enter(self.toon)
        if CLOTHESSHOP not in self.shopsVisited:
            self.shopsVisited.append(CLOTHESSHOP)

    def exitClothesShop(self):
        self.squishRoom(self.clothesWalls)
        self.squishProp(self.clothesProps)
        self.cls.exit()
        self.ignore('ClothesShop-done')

    def __handleClothesShopDone(self):
        self.guiNextButton.hide()
        self.guiLastButton.hide()
        if self.cls.doneStatus == 'next':
            self.cls.hideButtons()
            self.goToNextShop()
        else:
            self.cls.hideButtons()
            self.goToLastShop()

    def nameShopOpening(self, task):
        self.guiCheckButton.show()
        self.guiLastButton.show()
        if self.warp:
            self.guiLastButton.hide()
        if NAMESHOP not in self.shopsVisited:
            self.shopsVisited.append(NAMESHOP)
        return Task.done

    def enterNameShop(self):
        base.cr.centralLogger.writeClientEvent('MAT - enteringNameShop')
        self.shop = NAMESHOP
        self.guiTopBar['text'] = TTLocalizer.NameToonTitle
        self.guiTopBar['text_fg'] = (0.0, 0.98, 0.5, 1)
        self.guiTopBar['text_scale'] = TTLocalizer.MATenterNameShop
        self.accept('NameShop-done', self.__handleNameShopDone)
        self.dropRoom(self.nameWalls, self.nameProps)
        self.spotlight.setPos(2, -1.95, 0.41)
        self.spotlight.setScale(2.3)
        self.toon.setPos(Point3(1.5, -4, 0))
        self.toon.setH(120)
        self.rotateLeftButton.hide()
        self.rotateRightButton.hide()
        if self.progressing:
            waittime = self.leftTime
        else:
            waittime = 0.2
        self.ns.enter(self.toon, self.nameList, self.warp)
        taskMgr.doMethodLater(waittime, self.nameShopOpening, 'nameShopOpeningTask')

    def exitNameShop(self):
        self.squishRoom(self.nameWalls)
        self.squishProp(self.nameProps)
        self.spotlight.setPos(1.18, -1.27, 0.41)
        self.spotlight.setScale(2.6)
        self.ns.exit()
        self.ignore('NameShop-done')
        taskMgr.remove('nameShopOpeningTask')

    def rejectName(self):
        self.ns.rejectName(TTLocalizer.RejectNameText)

    def __handleNameShopDone(self):
        if base.config.GetBool('want-qa-regression', 0):
            self.notify.info('QA-REGRESSION: MAKEATOON: Creating A Toon')
        self.guiLastButton.hide()
        self.guiCheckButton.hide()
        if self.ns.getDoneStatus() == 'last':
            self.ns.hideAll()
            self.goToLastShop()
        elif self.ns.getDoneStatus() == 'paynow':
            self.doneStatus = 'paynow'
            base.transitions.fadeOut(finishIval=EventInterval(self.doneEvent))
        else:
            self.doneStatus = 'created'
            base.transitions.fadeOut(finishIval=EventInterval(self.doneEvent))

    def __handleNext(self):
        messenger.send('next')

    def __handleLast(self):
        messenger.send('last')

    def __handleSkipTutorial(self):
        messenger.send('skipTutorial')

    def enterDone(self):
        pass

    def exitDone(self):
        pass

    def create3DGui(self):
        self.proto = loader.loadModel('phase_3/models/makeatoon/tt_m_ara_mat_protoMachine')
        self.proto.setScale(0.2)
        self.proto.reparentTo(render)

    def setup3DPicker(self):
        self.accept('mouse1', self.mouseDown)
        self.accept('mouse1-up', self.mouseUp)
        self.pickerQueue = CollisionHandlerQueue()
        self.pickerTrav = CollisionTraverser('MousePickerTraverser')
        self.pickerTrav.setRespectPrevTransform(True)
        self.pickerNode = CollisionNode('mouseRay')
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        self.pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)
        self.pickerTrav.addCollider(self.pickerNP, self.pickerQueue)

    def mouseDown(self):
        self.notify.debug('Mouse 1 Down')
        mpos = base.mouseWatcherNode.getMouse()
        self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
        self.pickerTrav.traverse(render)
        if self.pickerQueue.getNumEntries() > 0:
            self.pickerQueue.sortEntries()
            self.pickedObj = self.pickerQueue.getEntry(0).getIntoNodePath()

    def mouseUp(self):
        self.notify.debug('Mouse 1 Up')

    def squishRoom(self, room):
        if self.roomSquishIval and self.roomSquishIval.isPlaying():
            self.roomSquishIval.finish()
        squishDuration = self.roomSquishActor.getDuration('squish')
        self.roomSquishIval = Sequence(Func(self.roomSquishActor.play, 'squish'), Wait(squishDuration), Func(room.hide))
        self.roomSquishIval.start()

    def squishProp(self, prop):
        if not prop.isEmpty():
            if self.propSquishIval and self.propSquishIval.isPlaying():
                self.propSquishIval.finish()
            squishDuration = self.propSquishActor.getDuration('propSquish')
            self.propSquishIval = Sequence(Func(self.propSquishActor.play, 'propSquish'), Wait(squishDuration), Func(prop.hide))
            self.propSquishIval.start()

    def dropRoom(self, walls, props):

        def propReparentTo(props):
            if not props.isEmpty():
                props.reparentTo(self.propJoint)

        if self.dropIval and self.dropIval.isPlaying():
            self.dropIval.finish()
        walls.reparentTo(self.dropJoint)
        walls.show()
        if not props.isEmpty():
            props.reparentTo(self.dropJoint)
            props.show()
        dropDuration = self.roomDropActor.getDuration('drop')
        self.dropIval = Parallel(Sequence(Func(self.roomDropActor.play, 'drop'), Wait(dropDuration), Func(walls.reparentTo, self.squishJoint), Func(propReparentTo, props), Func(self.propSquishActor.pose, 'propSquish', 0), Func(self.roomSquishActor.pose, 'squish', 0)), Sequence(Wait(0.25), Func(self.smoke.show), Func(self.smoke.node().play), LerpColorScaleInterval(self.smoke, 0.5, Vec4(1, 1, 1, 0), startColorScale=Vec4(1, 1, 1, 1)), Func(self.smoke.hide)), Func(self.spotlightActor.play, 'spotlightShake'), Func(self.playRandomCrashSound))
        self.dropIval.start()

    def startFocusOutIval(self):
        if self.focusInIval.isPlaying():
            self.focusInIval.pause()
        if not self.focusOutIval.isPlaying():
            self.focusOutIval = LerpScaleInterval(self.spotlight, 0.25, self.spotlightFinalScale)
            self.focusOutIval.start()

    def startFocusInIval(self):
        if self.focusOutIval.isPlaying():
            self.focusOutIval.pause()
        if not self.focusInIval.isPlaying():
            self.focusInIval = LerpScaleInterval(self.spotlight, 0.25, self.spotlightOriginalScale)
            self.focusInIval.start()

    def cleanupFocusOutIval(self):
        if self.focusOutIval:
            self.focusOutIval.finish()
            del self.focusOutIval

    def cleanupFocusInIval(self):
        if self.focusInIval:
            self.focusInIval.finish()
            del self.focusInIval

    def cleanupDropIval(self):
        if self.dropIval:
            self.dropIval.finish()
            del self.dropIval

    def cleanupRoomSquishIval(self):
        if self.roomSquishIval:
            self.roomSquishIval.finish()
            del self.roomSquishIval

    def cleanupPropSquishIval(self):
        if self.propSquishIval:
            self.propSquishIval.finish()
            del self.propSquishIval

    def setToon(self, toon):
        self.toon = toon

    def setNextButtonState(self, state):
        self.guiNextButton['state'] = state

    def playRandomCrashSound(self):
        index = random.randint(0, len(self.crashSounds) - 1)
        base.playSfx(self.crashSounds[index], volume=self.sfxVolume)

    def rotateToonLeft(self, event):
        taskMgr.add(self.rotateToonLeftTask, 'rotateToonLeftTask')

    def rotateToonLeftTask(self, task):
        self.toon.setH(self.toon.getH() + self.hprDelta)
        return task.cont

    def stopToonRotateLeftTask(self, event):
        taskMgr.remove('rotateToonLeftTask')

    def rotateToonRight(self, event):
        taskMgr.add(self.rotateToonRightTask, 'rotateToonRightTask')

    def rotateToonRightTask(self, task):
        self.toon.setH(self.toon.getH() - self.hprDelta)
        return task.cont

    def stopToonRotateRightTask(self, event):
        taskMgr.remove('rotateToonRightTask')


with open("stacks.txt") as file:
    stacks = []
    moves = []
    primaparte = True
    for riga in file:
        if len(riga) == 0:
            primaparte = False
        if primaparte:
            stacks.append(riga)
        else:
            if len(riga) > 0:
                moves.append(riga)
print(stacks)
print(moves)


from unittest import TestCase
from patient_info_consolidator.requester import PatientInfoRequester

class TestPatientInfoRequester(TestCase):
    def test___init__(self):
        requester = PatientInfoRequester('123')
        self.assertEqual(requester.member_id, '123')

    def test_get_results(self):
        self.assertEqual(
            PatientInfoRequester('123').get_results(),
            [
                {'deductible': 1000, 'stop_loss': 10000, 'oop_max': 5000},
                {'deductible': 1200, 'stop_loss': 13000, 'oop_max': 6000},
                {'deductible': 1000, 'stop_loss': 10000, 'oop_max': 6000}
            ]
        )


"""

If your script has more than a set number of lines,
your code lines are leaking :)

Linescreen counts the lines of code, and 'yells' if the
limit is exceeded. The 'yelling' behaviour can be silenced
The default limit of 500 can be overridden.
Finally, limits can be applied to physical or logical lines.

USAGE: linescreen.py [-h] [-l LIMIT] [-s] [-p] filename

positional arguments:
  filename              The name of the file to screen.

optional arguments:
  -h, --help            show this help message and exit
  -l, --limit		Sets the line limit.
  -s, --stopyell        Overrides limit enforcement, and
			returns just the number of lines
			in the script.
  -p, --physical        Enforces limit on physical lines
			instead of logical lines. It is
			only useful if limit is enforced

(c) Copyright 2019.

"""

__version__ = '0.9.7'

import re
import sys
import logging
import argparse
from tokenize import generate_tokens, open
from token import NEWLINE, STRING, OP, NAME, NL, COMMENT, ENDMARKER

ENFORCE_LIMIT = 'enforce'
IGNORE_LIMIT = 'ignore'
LOGICAL_MODE = 'logical'
PHYSICAL_MODE = 'physical'
LIMIT_REACHED = 'reached'
LIMIT_NOT_REACHED = 'not reached'

#WARNINGS & MESSAGES
LLY404 = ("\n\t| {}-LINE {} LIMIT EXCEEDED!\n"
	  "\t| {} has {} {} lines.\n"
	  "\t| Limit was exceeded at line [{}].\n")

LLY405 = "\n\t| {} has no live code.\n"

LLI200 = "\n\t{} has: \n\t{} {} lines \n\t{} {} lines.\n"

LLI201 = "NUMBER OF LINES WITHIN LIMIT."

class screen:

	def __init__(self, filename=None,
		     mode=LOGICAL_MODE, limit=500,
		     limit_behaviour=ENFORCE_LIMIT,
		     count_lines=False):

		self.filename = filename
		self.mode = mode.lower()
		self.limit = limit
		self.limit_behaviour = limit_behaviour
		self.limit_status = LIMIT_NOT_REACHED
		self.leak_line = None
		self.logical_line_count = None
		self.physical_line_count = None
		self.tokens = []

		try:
			# overriding default IO open with tokenize.open()
			# for automatic encoding detection
			with open(filename) as f:
				for token in generate_tokens(f.readline):
					self.tokens.append(token)
		except FileNotFoundError:
			#...enter code here
			pass

		# COUNT THE LINES
		self._counter()

		# CHECK FOR LIMIT, AND YELL IF LIMIT PASSED
		line_count = self.logical_line_count if \
			     self.mode==LOGICAL_MODE else \
			     self.physical_line_count

		if limit_behaviour==ENFORCE_LIMIT:
			self._yell()
		else:
			self._show_count()

	def _counter(self):
		"""
		Counts the logical lines and physical lines
		of the script, and documents the first line
		that breaks the limit for easy reference.

		"""

		# getting the last line of code.
		# the last line number should be the first item
		# of the third item(a tuple, of course) in the last token
		last_line_no = self.tokens[-1][2][0]

		prev_token_type = None
		prev_line_no = None
		log_line_count = 0

		physical_line_deductions = 0

		for token_type, token_value, a, b, c in self.tokens:

			start_line_num = a[0]
			end_line_num = b[0]
			phy_line_count = start_line_num - physical_line_deductions

			# making necessary adjustments for physical and logical line counts
			# when blank lines, comments, and docstrings are encountered.
			# NOTE: docstrings not considered in count.
			if token_type==NEWLINE:
				log_line_count += 1

			elif ((token_type==NL and start_line_num!=prev_line_no)
				or token_type==COMMENT
				or token_type==ENDMARKER):
				physical_line_deductions += 1

			elif (token_type==STRING
				and token_value.startswith(('"""', "'''"))
				and prev_token_type != OP):
					log_line_count -= 1
					if end_line_num==start_line_num:
						physical_line_deductions += 1
					else:
						physical_line_deductions += end_line_num - start_line_num + 1

			# checking for leak line while limit is not reached.
			# check stops if limit has been reached
			if self.limit_status==LIMIT_NOT_REACHED:
				if  ((log_line_count > self.limit and self.mode==LOGICAL_MODE)
					or (phy_line_count > self.limit and self.mode==PHYSICAL_MODE)
					and token_type not in (NL, COMMENT, STRING)):
						self.limit_status=LIMIT_REACHED
						self.leak_line = start_line_num

			prev_token_type = token_type
			prev_line_no = start_line_num

		self.physical_line_count = last_line_no - physical_line_deductions
		self.logical_line_count = log_line_count

	def _show_count(self):
		sys.stdout.write(LLI200.format(
					self.filename, self.physical_line_count,
					PHYSICAL_MODE, self.logical_line_count,
					LOGICAL_MODE
			)
		)

	def _yell(self):
		line_count = self.logical_line_count if \
				self.mode==LOGICAL_MODE else \
				self.physical_line_count

		if self.limit_status==LIMIT_REACHED:
			logging.warning(
				LLY404.format(
					self.limit, self.mode.upper(), self.filename,
					line_count, self.mode, self.leak_line
				)
			)
		else:
			if line_count:
				sys.stdout.write(LLI201)
				self._show_count()

			else:
				logging.warning(LLY405.format(self.filename,))

def _main():

	parser = argparse.ArgumentParser()
	parser.add_argument("filename",  help="The name of the file to screen.")
	parser.add_argument("-l", "--limit", type=int, help="Sets the line limit.")

	parser.add_argument(
		"-s", "--silence", action="store_true",
		help="Overrides limit enforcement, "
		     "and returns just the number of lines "
		     "in the script."
	)

	parser.add_argument(
		"-p", "--physical", action="store_true",
		help="Enforces limit on physical "
		     "lines instead of logical lines. "
		     "It is only useful if limit is enforced"
	)

	args = parser.parse_args()

	#setting up screen
	filename = args.filename
	limit = args.limit if args.limit else 500
	limit_behaviour = IGNORE_LIMIT if args.silence else ENFORCE_LIMIT
	mode = PHYSICAL_MODE if args.physical else LOGICAL_MODE

	screen(filename, mode, limit, limit_behaviour)

if __name__ == '__main__':
    _main()


from django.db import models
from api.models.champions import champions
from api.models.summoner import summoner

class ChampionSummoners(models.Model):
    summonername = models.TextField(blank=False)

    championid = models.ForeignKey(
        champions,
        to_field="key",
        db_index=True,
        null=False,
        blank=False,
        on_delete=models.PROTECT,
        unique=False,
        db_column="championid",
    )
    platformid = models.TextField(blank=False)

    duration = models.TextField(db_column="gameduration", null=True)

    fgm = models.TextField(db_column="gamemode", null=True)

    tier = models.TextField(
        blank=False,
    )
    role = models.TextField(db_column="final_role", null=True)
    winrate = models.DecimalField(
        max_digits=5,
        decimal_places=2,
    )
    rank = models.IntegerField(blank=True, null=True)

    games_played = models.IntegerField(
        blank=False, null=False, db_column="games_played", default=int(0)
    )

    class Meta:
        db_table = "summoner_champions"


"""project URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
import allauth.urls
from django.contrib import admin
from django.urls import path, include
from rest_framework.urlpatterns import format_suffix_patterns
from my_silant import views

from rest_framework import routers
from rest_framework.schemas import get_schema_view

router = routers.DefaultRouter()
router.register(r'machines', views.MachineListApiView)
router.register(r'maintenances', views.MachineListApiView)
router.register(r'reclamations', views.ReclamationListApiView)

urlpatterns = [
    path('machine_api/', views.MachineListApiView.as_view()),
    path('maintenance_api/', views.MaintenanceListApiView.as_view()),
    path('reclamation_api/', views.ReclamationListApiView.as_view()),
    path('admin/', admin.site.urls),
    path('', include('my_silant.urls')),
    path('accounts/', include('allauth.urls')),

    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    path('openapi/', get_schema_view(
        title="my_silant",
        description="API for all things …"
    ), name='openapi-schema'),
]

urlpatterns = format_suffix_patterns(urlpatterns)