import copy

import pytest

import torch
import nni
from torch import nn
from nni.common.serializer import is_traceable
from nni.mutable import Categorical, ExpressionConstraint, ensure_frozen, frozen_context, label_scope, auto_label, SampleMissingError
from nni.mutable.mutable import _mutable_equal
from nni.nas.nn.pytorch import ModelSpace, MutableModule, ParametrizedModule
from nni.nas.space import model_context

def test_label_scope():
    from nni.nas.nn.pytorch.base import strict_label_scope

    with strict_label_scope('_unused_'):
        with pytest.raises(ValueError, match='Label'):
            Categorical([1, 2, 3])
        assert Categorical([1, 2, 3], label='x').label == 'x'
        with label_scope('hello'):
            assert auto_label() == 'hello/1'
            assert Categorical([1, 2, 3], label='x').label == 'hello/x'

def test_ensure_frozen():
    discrete = Categorical([1, 2, 3])
    with pytest.raises(RuntimeError, match='No frozen context'):
        ensure_frozen(discrete)

    class Net(ModelSpace):
        def __init__(self):
            super().__init__()
            self.module = Categorical([1, 2, 3], label='x')
            self.add_mutable(self.module)
            self.dry_run_value = ensure_frozen(self.module)

    model = Net()
    assert model.dry_run_value == 1

    with pytest.raises(NotImplementedError, match='nni.nas.space.model_context'):
        model.freeze({'x': 2})

def test_ensure_frozen_freeze():
    class Net(ModelSpace):
        def __init__(self):
            super().__init__()
            self.module = Categorical([1, 2, 3], label='x')
            self.add_mutable(self.module)
            self.dry_run_value = ensure_frozen(self.module)

        def freeze(self, sample):
            with model_context(sample):
                return self.__class__()

    model = Net()
    assert model.dry_run_value == 1
    assert model.contains({'x': 1})
    assert not model.contains({})
    assert not model.contains({'x': 4})
    model1 = model.freeze({'x': 2})
    assert model1.dry_run_value == 2
    model2 = model.freeze({'x': 3})
    assert model2.dry_run_value == 3

def test_ensure_frozen_freeze_fail(caplog):
    class Net(ModelSpace, label_prefix='model'):
        def __init__(self):
            super().__init__()
            self.module = Categorical([1, 2, 3], label='x')
            self.add_mutable(self.module)
            self.dry_run_value = ensure_frozen(self.module)

        def freeze(self, sample):
            with model_context(sample):
                return self.__class__()

    model = Net()
    assert model.dry_run_value == 1
    with pytest.raises(SampleMissingError):
        model.freeze({'x': 2})
    assert 'add_mutable()' in caplog.text

def test_ensure_frozen_no_register(caplog):
    class Net(ModelSpace, label_prefix='model'):
        def __init__(self):
            super().__init__()
            self.module = Categorical([1, 2, 3])
            self.dry_run_value = ensure_frozen(self.module)

    with pytest.raises(SampleMissingError):
        Net()
    assert 'Failed to freeze mutable' in caplog.text

def test_ensure_frozen_in_forward():
    class Net(ModelSpace, label_prefix='model'):
        def __init__(self):
            super().__init__()
            self.module = Categorical([1, 2, 3])
            self.add_mutable(self.module)

        def forward(self):
            return ensure_frozen(self.module)

    model = Net()
    with pytest.raises(RuntimeError, match='in forward'):
        model()

def test_ensure_frozen_constraint_first():
    class Net(ModelSpace, label_prefix='model'):
        def __init__(self, s: int = 4):
            super().__init__()
            discrete1 = Categorical([1, 2, 3])
            discrete2 = Categorical([1, 2, 3])
            self.add_mutable(ExpressionConstraint(discrete1 + discrete2 == s))
            self.add_mutable(discrete1)
            self.add_mutable(discrete2)
            self.a = ensure_frozen(discrete1)
            self.b = ensure_frozen(discrete2)

    model = Net()

    # assert 'Using the default' in caplog.text
    assert model.a + model.b == 4

    model = Net(5)
    assert model.a + model.b == 5

    with pytest.raises(
        ValueError,
        match=r'Cannot find a valid',
    ):
        model = Net(10)

@pytest.mark.parametrize('label_prefix', [None, 'model'])
def test_ensure_frozen_consistency(label_prefix):
    class Submodule(MutableModule):
        def __init__(self):
            super().__init__()
            discrete2 = Categorical([1, 2, 3], default=3, label='a')
            self.add_mutable(discrete2)
            self.b = ensure_frozen(discrete2)

        def forward(self, x):
            return self.conv(x)

    class Net(ModelSpace):
        def __init__(self):
            super().__init__()
            discrete1 = Categorical([1, 2, 3], default=2, label='a')
            self.add_mutable(discrete1)
            self.a = ensure_frozen(discrete1)
            self.sub = Submodule()

    with pytest.raises(ValueError, match='default value of'):
        Net()

def test_model_space_args():
    class ModelSpace1(ModelSpace):
        def __init__(self, a, b=1):
            super().__init__()
            self.a = a
            self.b = b

    model = ModelSpace1(2, 3)
    assert model.args['a'] == 2
    assert model.args['b'] == 3

    model = ModelSpace1(2)
    assert model.args['a'] == 2
    assert model.args['b'] == 1
    assert 'b' not in model.trace_kwargs

    class ModelSpace2(ModelSpace):
        def __init__(self, *args):
            super().__init__()
            self.a = args

    model = ModelSpace2(1, 2, 3)
    with pytest.raises(RuntimeError, match='args is not available'):
        model.args

    assert is_traceable(model)

def test_model_space_label():

    class MyModelSpace(ModelSpace, label_prefix='backbone'):
        def __init__(self):
            super().__init__()

            self.choice = self.add_mutable(nni.choice('depth', [2, 3, 4]))

    model = MyModelSpace()
    assert model.choice.label == 'backbone/depth'

def test_model_space_inherit():
    class ModelSpace1(ModelSpace):
        def __init__(self, a, b=1):
            super().__init__()
            self.d = self.add_mutable(Categorical([4, 5, 6], label='d'))

    class ModelSpace2(ModelSpace1):
        def __init__(self, c=2):
            super().__init__(c, b=3)
            self.c = self.add_mutable(Categorical([1, 2, 3], label='c'))

    model = ModelSpace2(5)
    assert model.trace_kwargs == {'c': 5}
    assert model.c.label == 'c'
    assert model.d.label == 'd'
    assert model.trace_symbol == ModelSpace2

def test_model_space_inherit_label_prefix():
    class ModelSpace1(ModelSpace):
        def __init__(self, a, b=1):
            super().__init__()
            self.d = self.add_mutable(Categorical([4, 5, 6], label='d'))

    class ModelSpace2(ModelSpace1, label_prefix='model2'):
        def __init__(self, c=2):
            super().__init__(c, b=3)
            self.c = self.add_mutable(Categorical([1, 2, 3], label='c'))

    model = ModelSpace2(5)
    assert model.trace_kwargs == {'c': 5}
    assert model.c.label == 'model2/c'
    assert model.d.label == 'model2/d'
    assert model.trace_symbol == ModelSpace2

def test_model_space_combination_label_prefix():
    class ModelSpace1(ModelSpace, label_prefix='model1'):
        def __init__(self, a, b=1):
            super().__init__()
            self.d = self.add_mutable(Categorical([4, 5, 6], label='d'))

    class ModelSpace2(ModelSpace, label_prefix='model2'):
        def __init__(self, c=2):
            super().__init__()
            self.s = ModelSpace1(1, 2)
            self.c = self.add_mutable(Categorical([1, 2, 3], label='c'))

    model = ModelSpace2(5)
    assert model.trace_kwargs == {'c': 5}
    assert model.c.label == 'model2/c'
    assert model.s.d.label == 'model2/model1/d'
    assert model.trace_symbol == ModelSpace2
    assert model.s.trace_symbol == ModelSpace1

def test_model_space_no_label_prefix(caplog):
    class ModelSpace1(ModelSpace, label_prefix=''):
        pass

    with pytest.raises(ValueError, match='be empty'):
        ModelSpace1()

    class ModelSpace2(ModelSpace):
        def __init__(self):
            super().__init__()
            self.a = self.add_mutable(Categorical([1, 2, 3], label='a'))
            assert self.a.label == 'a'
            with pytest.raises(ValueError, match='must be specified'):
                self.b = self.add_mutable(Categorical([1, 2, 3]))

    ModelSpace2()

    class ModelSpace3(ModelSpace):
        def __init__(self):
            super().__init__()
            self.a = self.add_mutable(Categorical([1, 2, 3], label='a'))
            assert self.a.label == 'model4/a'
            with pytest.raises(ValueError, match='must be specified'):
                self.b = self.add_mutable(Categorical([1, 2, 3]))

    class ModelSpace4(ModelSpace, label_prefix='model4'):
        def __init__(self):
            super().__init__()
            ModelSpace3()
            self.a = self.add_mutable(Categorical([1, 2, 3], label='a'))
            assert self.a.label == 'model4/a'
            self.b = self.add_mutable(Categorical([1, 2, 3]))
            assert self.b.label == 'model4/1'

    class ModelSpace5(ModelSpace):
        def __init__(self):
            super().__init__()
            ModelSpace4()

    ModelSpace5()

def test_import_nas_nn_as_nn():
    import torch
    import nni.nas.nn.pytorch.layers as nn

    dummy = torch.zeros(1, 16, 32, 24)
    nn.init.uniform_(dummy)

    nn.Conv2d(1, 3, 1)
    nn.Parameter(torch.zeros(1, 3, 24, 24))

    import nni.nas.nn.pytorch as nn2

    nn2.MutableConv2d(1, 3, 1)
    with pytest.raises(AttributeError):
        nn2.Conv2d(1, 3, 1)

def test_label():
    from nni.nas.nn.pytorch import LayerChoice

    class Model(ModelSpace, label_prefix='model'):
        def __init__(self, in_channels):
            super().__init__()
            self.conv1 = nn.Conv2d(in_channels, 10, 3)
            self.conv2 = LayerChoice([
                nn.Conv2d(10, 10, 3),
                nn.MaxPool2d(3)
            ])
            self.conv3 = LayerChoice([
                nn.Identity(),
                nn.Conv2d(10, 10, 1)
            ])
            self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
            self.fc = nn.Linear(10, 1)

        def forward(self, x):
            x = self.conv1(x)
            x = self.conv2(x)
            x = self.conv3(x)
            x = self.avgpool(x).view(x.size(0), -1)
            x = self.fc(x)
            return x

    model = Model(3)
    assert model.trace_symbol == Model
    assert model.trace_kwargs == {'in_channels': 3}
    assert model.conv2.label == 'model/1'
    assert model.conv3.label == 'model/2'
    assert model(torch.randn(1, 3, 5, 5)).size() == torch.Size([1, 1])

    model = Model(4)
    assert model.trace_symbol == Model
    assert model.conv2.label == 'model/1'  # not changed

def test_label_hierarchy():
    from nni.nas.nn.pytorch import LayerChoice

    class ModelInner(nn.Module):
        def __init__(self):
            super().__init__()
            self.net1 = LayerChoice([
                nn.Linear(10, 10),
                nn.Linear(10, 10, bias=False)
            ])
            self.net2 = LayerChoice([
                nn.Linear(10, 10),
                nn.Linear(10, 10, bias=False)
            ])

        def forward(self, x):
            x = self.net1(x)
            x = self.net2(x)
            return x

    class ModelNested(ModelSpace, label_prefix='model'):
        def __init__(self):
            super().__init__()
            self.fc1 = ModelInner()
            self.fc2 = LayerChoice([
                nn.Linear(10, 10),
                nn.Linear(10, 10, bias=False)
            ])
            self.fc3 = ModelInner()

        def forward(self, x):
            return self.fc3(self.fc2(self.fc1(x)))

    model = ModelNested()
    assert model.fc1.net1.label == 'model/1'
    assert model.fc1.net2.label == 'model/2'
    assert model.fc2.label == 'model/3'
    assert model.fc3.net1.label == 'model/4'
    assert model.fc3.net2.label == 'model/5'

def test_deepcopy():
    class MyModule(MutableModule):
        def __init__(self, a, b):
            super().__init__()
            self.a = nn.Linear(3, a)
            self.b = nn.Linear(3, b)
            self.mutable = self.add_mutable(Categorical([0, 1]))

            self.flag = ensure_frozen(self.mutable)

        def forward(self, x):
            if self.flag:
                return self.a(x)
            else:
                return self.b(x)

    with frozen_context():
        net = MyModule(5, 7)
    net2 = copy.deepcopy(net)
    assert net2.a.out_features == 5
    assert net2.b.out_features == 7
    assert net2.flag == net.flag

def test_mutable_descendants():
    class A(MutableModule):
        pass

    class B(MutableModule):
        def check_contains(self, sample):
            if 'test' in sample:
                return SampleMissingError('test')

    class C(MutableModule):
        def __init__(self):
            super().__init__()
            self.b = B()

    class D(nn.Module):
        def __init__(self):
            super().__init__()
            self.c = C()

    class E(MutableModule):
        def __init__(self):
            super().__init__()
            self.a = A()
            self.d = D()

    e = E()
    descendants = list(e.mutable_descendants())
    assert len(descendants) == 2
    assert [_[0] for _ in e.named_mutable_descendants()] == ['a', 'd.c']
    assert isinstance(descendants[0], A)
    assert isinstance(descendants[1], C)

    assert repr(e) == """E(
  (a): A()
  (d): D(
    (c): C(
      (b): B()
    )
  )
)"""
    frozen_e = e.freeze({})
    assert e is not frozen_e
    assert repr(e) == repr(frozen_e)

    e.validate({})
    with pytest.raises(SampleMissingError, match='d.c'):
        e.validate({'test': 1})

def test_parametrized_module():
    class MyModule(ParametrizedModule):
        def __init__(self, x):
            super().__init__()
            self.t = x

    with frozen_context():
        module = MyModule(nni.choice('choice1', [1, 2, 3]))
    assert module.t == 1
    assert module.args['x'].label == 'choice1'

    assert repr(module) == "MyModule(x=Categorical([1, 2, 3], label='choice1'))"
    assert str(module) == repr(module)

    class ParametrizedConv2d(ParametrizedModule, nn.Conv2d, wraps=nn.Conv2d):
        pass

    with pytest.raises(RuntimeError):
        ParametrizedConv2d(3, nni.choice('out', [8, 16]), 1)

    with frozen_context():
        conv = ParametrizedConv2d(3, nni.choice('out', [8, 16]), 1)

    assert repr(conv) == "ParametrizedConv2d(in_channels=3, out_channels=Categorical([8, 16], label='out'), kernel_size=1)"
    assert conv.out_channels == 8
    assert conv.args['padding'] == 0
    assert _mutable_equal(conv.args['out_channels'], nni.choice('out', [8, 16]))
    assert conv.contains({'out': 16})
    assert len(conv.simplify()) == 1
    assert type(conv.freeze({'out': 16})) is nn.Conv2d
    assert conv.freeze({'out': 16}).out_channels == 16

def test_parametrized_module_inheritance():
    class Module1(ParametrizedModule):
        def __init__(self, x):
            super().__init__()
            self.t = x

    class Module2(Module1):
        def __init__(self, y):
            super().__init__(y)

    choice = nni.choice('choice1', [1, 2, 3])
    with frozen_context():
        module = Module2(choice)
    assert _mutable_equal(module.args, {'y': choice})
    assert module.freeze({'choice1': 2}).t == 2

def test_nested_parametrized_module():
    class MyModule(ParametrizedModule):
        def __init__(self, x):
            if x == 0:
                self.mutable = self.add_mutable(nni.choice('a', [1, 2, 3]))
            else:
                self.mutable = self.add_mutable(nni.choice('b', [4, 5, 6]))
            self.flag = ensure_frozen(self.mutable)

    with frozen_context():
        module = MyModule(nni.choice('x', [0, 1]))
    module1 = module.freeze({'x': 0, 'a': 1})
    assert module1.flag == 1
    module2 = module.freeze({'x': 1, 'b': 5})
    assert module2.mutable.label == 'b'
    assert module2.flag == 5
    with pytest.raises(SampleMissingError):
        module.freeze({'x': 1, 'a': 2})

def test_empty_parameterized_module():
    class MutableConv(ParametrizedModule):
        def __init__(self):
            super().__init__()
            self.conv1 = nn.Conv2d(3, 3, kernel_size=1)
            self.conv2 = nn.Conv2d(3, 5, kernel_size=1)

        def forward(self, x: torch.Tensor, index: int):
            if index == 0:
                return self.conv1(x)
            else:
                return self.conv2(x)

    class MyModelSpace(ModelSpace):
        def __init__(self):
            super().__init__()
            self.conv = MutableConv()
            self.index = ensure_frozen(self.add_mutable(nni.choice('x', [0, 1])))

        def freeze(self, sample):
            with model_context(sample):
                return self.__class__()

        def forward(self, x: torch.Tensor):
            return self.conv(x, self.index)

    space = MyModelSpace()
    model = space.freeze({'x': 0})
    assert model(torch.randn(1, 3, 5, 5)).shape == (1, 3, 5, 5)
    model = space.freeze({'x': 1})
    assert model(torch.randn(1, 3, 5, 5)).shape == (1, 5, 5, 5)


# -*- coding: utf-8 -*-

n, m = [int(v) for v in input().split()]
py_list = [None] * m
py_dict = dict()

p_set = set()
for i in range(m):
    p, y = [int(v) for v in input().split()]
    py_list[i] = (p, y)

    if p not in py_dict:
        py_dict[p] = dict()
    if y not in py_dict[p]:
        py_dict[p][y] = None

    p_set.add(p)

# corrdinate compression
for p in p_set:
    y_list = list(py_dict[p].keys())
    y_list.sort()
    py_dict[p] = {y: i + 1 for i, y in enumerate(y_list)}

for p, y in py_list:
    city_id = py_dict[p][y]
    ans_id = str(p).zfill(6) + str(city_id).zfill(6)
    print(ans_id)


# DRF
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated

# Serializers
from .serializers import ReadUserProfileSerializer

# Library: drf-yasg more details at https://drf-yasg.readthedocs.io/en/stable/custom_spec.html
from drf_yasg.utils import swagger_auto_schema

import logging
logger = logging.getLogger(__name__)

class UserProfileAPIView(APIView):

    permission_classes = (IsAuthenticated,)

    @staticmethod
    @swagger_auto_schema(
        responses={
            200: ReadUserProfileSerializer()
        },
        operation_description="Read Authenticated User Profile",
        operation_id="user_profile_read"
    )
    def get(request):
        logger.info(f"authenticated: {request.user}")
        user_serializer = ReadUserProfileSerializer(request.user)
        return Response(user_serializer.data)


# point: just go through all the elem, and at each = max(previous 3 possible elem connections
# time: O(MN), space: O(1)

#for each element just take the max u can so just like the coin based and move on just
# keep the max value updated all time

def max_path(M):
    r,c = len(M), len(M[0])

    res=-1

    for i in range(1,r):
        for j in range(c):
            if j>0 and j < c-1:
                M[i][j] += max( M[i-1][j] , max(M[i-1][j-1], M[i-1][j+1]))
            elif j>0:
                M[i][j] += max(M[i-1][j-1], M[i-1][j])
            elif j < c-1:
                M[i][j] += max(M[i-1][j+1], M[i-1][j])

            res = max(M[i][j], res)

    return res

print(max_path([[ 0, 10, 2, 0, 200, 4 ],
                [ 1000, 0, 100, 0, 2, 5 ],
                [ 0, 10, 4, 0, 2, 0 ],
                [ 1, 0, 2, 20, 0, 4 ]]))


import string
from collections import deque

def algo() -> int:
    heights = dict()
    start_point = (-1, -1)
    end_goal = (-1, -1)
    result = -1
    directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

    print("hello, day 12: Hill Climbing Algorithm")

    # you'll need to find the shortest path from any square at elevation a to the square marked E
    # What is the fewest steps required to move starting from any square with elevation a
    # to the location that should get the best signal?

    grid_list = read_instructions()
    height = len(grid_list)
    width = len(grid_list[0])

    for y, line in enumerate(grid_list):
        for x, char in enumerate(line):
            if char == "S":
                start_point = (x, y)
                heights[(x, y)] = 0
            elif char == "E":
                end_goal = (x, y)
                heights[(x, y)] = 25
            else:
                heights[(x, y)] = string.ascii_lowercase.index(char)

    visited = set()
    visited.add(end_goal)

    q = deque()
    distance = 0
    q.appendleft((distance, end_goal))

    while q:
        current_distance, current_location = q.popleft()
        current_height = heights[current_location]
        if current_height == 0:
            result = current_distance
            break

        x, y = current_location
        for dx, dy in directions:
            new_x, new_y = x + dx, y + dy
            # don't go outside the grid
            if new_x < 0 or new_x >= width or new_y < 0 or new_y >= height:
                continue

            neighbour_location = (new_x, new_y)
            if neighbour_location in visited:
                continue

            neighbour_height = heights[neighbour_location]
            if current_height - 1 <= neighbour_height:
                new_distance = current_distance + 1
                neighbour_entry = (new_distance, neighbour_location)
                q.append(neighbour_entry)
                visited.add(neighbour_location)

    return result

def read_instructions() -> list[str]:
    instructions_raw = open(instruction_file).readlines()
    instructions_lines = [line.strip() for line in instructions_raw]
    return instructions_lines

if __name__ == '__main__':
    instruction_file = 'day12_input.txt'
    debug = False
    trace = False

    print(f'result: {algo()}')


import json
import requests
from common import get_token

BASE = "<>"
PASS = "<>"
USER = "<>"
COLLECTION = "<>"

def headers():
    return {"X-Metabase-Session": get_token(BASE, USER, PASS)}

def get_collection(old):
    collections = requests.get(f"{BASE}/api/collection/", headers=headers()).json()
    collections = [c for c in collections if c["name"] == old["name"]]
    if collections:
        return collections[0]["id"]
    else:
        return requests.post(
            f"{BASE}/api/collection/", headers=headers(), json=old
        ).json()["id"]

def delete_model(id, model):
    return requests.delete(
        f"{BASE}/api/{model}/{id}",
        headers=headers(),
    ).json()

def clear_collection(id):
    items = requests.get(
        f"{BASE}/api/collection/{id}/items",
        headers=headers(),
    ).json()

    for item in items["data"]:
        try:
            delete_model(item["id"], item["model"])
        except:
            pass

def update_collection(id, c):
    clear_collection(id)
    out = requests.put(
        f"{BASE}/api/collection/{id}",
        headers=headers(),
        json=c,
    ).json()
    return out["id"]

def create_card(c):
    out = requests.post(
        f"{BASE}/api/card/", headers=headers(), json=c
    ).json()
    return out["id"]

def create_dashboard(c, cache):
    id = requests.post(
        f"{BASE}/api/dashboard/", headers=headers(), json=c
    ).json()["id"]
    for card in c["ordered_cards"]:
        card["cardId"] = cache["card__" + str(card["card_id"])]
        out = requests.post(
            f"{BASE}/api/dashboard/{id}/cards",
            headers=headers(),
            json=card,
        ).text
        print(out)
    return out

def get_databases():
    items = requests.get(
        f"{BASE}/api/database?include=tables", headers=headers()
    ).json()
    out = {}
    for db in items["data"]:
        out[db["name"]] = {
            "tables": dict((t["name"], t["id"]) for t in db["tables"]),
            "id": db["id"],
        }
    return out

def map_table(src_dbs, dst_dbs, db, table):
    src_db = src_dbs[str(db)]
    dst_db = dst_dbs[src_db["name"]]

    if table is not None:
        src_table = src_db["tables"][str(table)]
        dst_table = dst_db["tables"][src_table]
    else:
        dst_table = None

    return dst_db["id"], dst_table

def process_and_upload_card(c, src_dbs, dst_dbs, cards, cache={}):
    print(c['id'])
    if f"card__{c['id']}" in cache:
        return

    def find_card(id):
        return [c for c in cards if f"card__{c['id']}" == id][0]

    def table_mapper(table):
        if isinstance(table, str):
            process_and_upload_card(find_card(table), src_dbs, dst_dbs, cards, cache)
            return "card__" + str(cache[table])
        else:
            return map_table(src_dbs, dst_dbs, src_db, table)[1]

    c["collection_id"] = id
    src_db = c["database_id"]
    c["database_id"] = map_table(src_dbs, dst_dbs, src_db, c["table_id"])[0]
    dataset_query = c["dataset_query"]
    dataset_query["database"] = c["database_id"]
    if "query" in dataset_query:
        query = dataset_query["query"]
        if "source-table" in query:
            query["source-table"] = table_mapper(query["source-table"])
        if "source-query" in query and "source-table" in query["source-query"]:
            query["source-query"]["source-table"] = table_mapper(
                query["source-query"]["source-table"]
            )
        for join in query.get("joins", []):
            join["source-table"] = table_mapper(join["source-table"])
    cache[f"card__{c['id']}"] = create_card(c)

if __name__ == "__main__":
    dbs = get_databases()
    data = json.load(open(f"{COLLECTION}.json"))
    src_dbs = data["db"]
    id = get_collection(data["collection"])
    update_collection(id, data["collection"])
    cards, dashboards = data["cards"], data["dashboards"]

    cache = {}
    for c in cards:
        process_and_upload_card(c, src_dbs, dbs, cards, cache)

    for c in dashboards:
        for card in c['ordered_cards']:
            process_and_upload_card(card['card'], src_dbs, dbs, cards, cache)
        c["collection_id"] = id
        create_dashboard(c, cache)


import sys
sys.path.append('../')

import connector

from microdot import Microdot, send_file
from microdot_websocket import with_websocket

app = Microdot()

@app.route('/')
def index(request):
    return send_file('index.html')

@app.route('/echo')
@with_websocket
def echo(request, ws):
    from machine import Pin
    while True:
        data = ws.receive()
        led = Pin(int(data), Pin.OUT)
        if led.value() == 0:
            led.on()
            ws.send("PIN " + data + " ON")
        else:
            led.off()
            ws.send("PIN " + data + " OFF")

app.run()


#!/usr/bin/env python3
import database
import time
import json
import math
import random

"""
ideas:
    - nose size = throw radius
    - limb size = speed
    - ear size = evade chance / defense
    - eye size = hit chance / attack
    - primary = 100% attack (or heal)
    - secondary = 50% attack and 50% defense

0     1         2       3    4      5      6       7
fire, electric, nature, ice, water, magic, healer, evil

TODO:
- primary evil pets will attack their friends instead of the boss
"""

elements_table = [
 2, 4, 4, 8, 8, 2, 2, 4,
 8, 2, 2, 8, 8, 2, 2, 4,
 4, 4, 4, 4, 4, 4, 2, 4,
 4, 4, 4, 4, 8, 2, 2, 4,
 8, 2, 4, 2, 4, 2, 2, 4,
 4, 4, 2, 4, 4, 8, 2, 4,
 0, 0, 0, 0, 0, 0, 0, 0,
 2, 2, 2, 2, 2, 2, 2, 4,
    ]

def element_damge(atp, dep, ats, des):
    x = elements_table[atp * 8 + dep]
    y = elements_table[ats * 8 + des]
    return x + y // 2

class Server:

    def start(self):
        database.access_db()
        self.active = {}
        self.t0 = time.time()
        self.t1 = self.t0
        average = 0
        i = 0
        while True:
            self.tick()
            self.t1 += 1
            dt = self.t1 - time.time()
            if dt < 0.5:
                print("sleep %.2f" % dt)
            if dt > 0:
                time.sleep(dt)
                average += dt
            database.server_heartbeat(1)
            i += 1
            if i % 60 == 0:
                print("average sleep in last 60 seconds: %.2f" % (average / 60))
                average = 0

    def tick(self):
        arenas = database.get_open_arenas()
        for aid, name, restart, arena_round in arenas:
            if name in self.active and not restart:
                self.active[name].tick()
            else:
                a = Arena(aid, name, arena_round)
                a.start(restart)
                self.active[name] = a

class Arena:

    def __init__(self, aid, name, r):
        self.aid = aid
        self.name = name
        self.pets = {}
        self.w = 100
        self.h = 100
        self.boss = 0
        self.collider = 0 # pid of colliding pet
        self.round = r
        self.boss_defeat_t = None

    def start(self, restart):
        print("starting arena", self.aid, self.name, "round", self.round)
        pos = database.get_pos_in_arena(aid = self.aid)
        for args in pos:
            pet = Pet(*args)
            if pet.owner != 0 and pet.pid not in self.pets:
                pet.reset = True
            self.pets[pet.pid] = pet
            if pet.owner == 0:
                self.boss = pet.pid

        dna = database.get_dna_in_arena(self.name)
        for pid, owner, name, d in dna:
            self.pets[pid].setup_dna(d)

        if self.boss == 0:
            print("creating boss for", self.aid, self.name)
            self.create_boss()

        if restart:
            database.update_boss(self.boss, self.make_boss_dna())
            update = []
            i = 0
            n = len(self.pets) - 1
            for pet in self.pets.values():
                pet.target = 0
                if pet.owner == 0:
                    pet.x = 90
                    pet.y = 50
                    pet.a = 90
                    pet.hp = 1000
                else:
                    pet.x = 10
                    pet.y = 10 + i * 80 / ((n - 1) if n > 1 else 2)
                    pet.a = 270
                    pet.hp = 100
                update.append((pet.pid, pet.x, pet.y, pet.z, pet.a, pet.target, pet.hp))
                i += 1
            database.set_pos_in_arena(update)
            database.restart_arena(self.name, 0, self.round)

    def find_closest_pet(self, boss):
        minq = None
        minp = None
        for pet in self.pets.values():
            if pet.owner == 0: continue
            if pet.hp <= 0: continue
            if pet.x is None: continue
            dx = pet.x - boss.x
            dy = pet.y - boss.y
            q = dx * dx + dy * dy
            if minq is None or q < minq:
                minq = q
                minp = pet
        return minp

    def find_wounded(self):
        minh = None
        minp = None
        for pet in self.pets.values():
            if pet.owner == 0: continue
            if pet.hp <= 0: continue
            if pet.x is None: continue
            if minh is None or pet.hp < minh:
                minh = pet.hp
                minp = pet
        return minp

    def get_update(self):
        update = []
        for pet in self.pets.values():
            update.append((pet.pid, pet.x, pet.y, pet.z, pet.a, pet.target, pet.hp))
        return update

    def tick(self):
        pos = database.get_pos_in_arena(aid = self.aid)
        redo = False
        want_target = 0

        existing = set()
        coli = random.randint(1, len(pos))
        i = 0
        for pid, owner, x, y, z, a, target, hp in pos:
            i += 1
            if owner is None: owner = 0
            if target is None: target = 0
            if pid not in self.pets:
                redo = True
                continue
            if i == coli:
                self.collider = pid
            existing.add(pid)
            if x is None: continue
            pet = self.pets[pid]
            if owner == 0: # boss
                if target != 0:
                    tpet = self.pets.get(target, None)
                    if tpet:
                        dx = tpet.x - x
                        dy = tpet.y - y
                        ta = math.atan2(dy, dx)
                        a = (ta * 180) / math.pi - 90
            else:
                target = 0
                towards = 0
                if pet.primary == 6 or pet.primary == 7: # healer or evil
                    wounded = self.find_wounded()
                    if wounded:
                        towards = wounded.pid
                else:
                    towards = self.boss

                if towards != 0 and hp > 0:
                    tpet = self.pets[towards]
                    dx = tpet.x - x
                    dy = tpet.y - y
                    ta = math.atan2(dy, dx)
                    d = math.sqrt(dx * dx + dy * dy)
                    if d > 1:
                        a = (ta * 180) / math.pi - 90
                    if d > pet.attack_distance:
                        x += math.cos(ta) * pet.speed
                        y += math.sin(ta) * pet.speed
                    else:
                        target = towards

                if self.collider and hp > 0:
                    # will collide with itself but we do not care, it
                    # gives us some random movement
                    cpet = self.pets[self.collider]
                    cx = cpet.x - x
                    cy = cpet.y - y
                    if cx * cx + cy * cy < 5 * 5:
                        c = math.sqrt(cx * cx + cy * cy)
                        if c < 0.1: c = 0.1
                        x += random.randint(-1, 1) - cx / c * (5 - c)
                        y += random.randint(-1, 1) - cy / c * (5 - c)

            pet.update(x, y, z, a, target, hp)

        # fight
        for pet in self.pets.values():
            if not pet.target: continue
            tpet = self.pets.get(pet.target, None)
            if not tpet: continue
            pet.attack(tpet)

        if self.boss != 0:
            boss = self.pets[self.boss]
            if boss.hp <= 0:
                boss.target = 0
                if not self.boss_defeat_t:
                    self.boss_defeat_t = time.time()
                    print("boss is dead for", self.name, "advancing to round", self.round + 1)
                elif time.time() - self.boss_defeat_t > 5:
                    database.restart_arena(self.name, 1, self.round + 1)
            else:
                target = self.find_closest_pet(boss)
                if target:
                    boss.target = target.pid

        if self.pets:
            update = self.get_update()
            database.set_pos_in_arena(update)

            for pid in list(self.pets.keys()):
                if pid not in existing:
                    self.pets.pop(pid)
                    print("Lost", pid, "in", self.name)

        if redo:
            self.start(False)

    def make_boss_dna(self):
        eye_count = min(3, (self.round + 9) // 10)
        eye_size = (self.round - 1) % 10
        ear_size = self.round // 3
        dna = {
            "behavior_primary":random.randint(0, 5), "behavior_secondary":random.randint(0, 7),
            "eye_count":eye_count,"eye_height":8,"eye_space":3,"eye_size":eye_size,
            "limb_count":1,"limb_size":4,"limb_n":6,
            "nose_height":6,"nose_size":6,"nose_n":6,
            "nose_color":3,"nose_nostrils":2,
            "ear_height":10,"ear_size":ear_size,
            "body_size":self.round // 2}
        return json.dumps(dna)

    def create_boss(self):
        x, y, z, a = 90, 50, 0, 90
        args = database.create_boss(self.aid,
            self.make_boss_dna(), x, y, z, a, 1000), 0, x, y, z, a, 0, 1000
        pet = Pet(*args)
        self.pets[pet.pid] = pet
        pet.dna = dna
        self.boss = pet.pid

class Pet:
    def __init__(pet, pid, owner, x, y, z, a, target, hp):
        pet.pid = pid
        pet.owner = owner if owner else 0
        pet.name = "unknown"
        pet.reset = False
        pet.update(x, y, z, a, target, hp)

    def update(pet, x, y, z, a, target, hp):
        if pet.reset:
            pet.reset = False
            pet.x = 10
            pet.y = random.randint(10, 18 + 80)
            pet.z = 0
            pet.a = 270
            pet.hp = 100
        else:
            if x is not None:
                if x < 0: x = 0
                if x > 100: x = 100
                if y < 0: y = 0
                if y > 100: y = 100
            pet.x = x
            pet.y = y
            pet.z = z
            pet.a = a
            pet.hp = hp
        pet.target = target if target else 0

    def setup_dna(pet, d):
        pet.dna = json.loads(d)
        pet.attack_distance = (1 + pet.dna["nose_size"]) * (1 + pet.dna["nose_n"]) / 32 * 80
        pet.speed = (1 + pet.dna["limb_count"]) * (1 + pet.dna["limb_size"]) * (1 + pet.dna["limb_n"]) / 128 * 16
        visual_strength = [0, 1, 1.5, 1.75][pet.dna.get("eye_count", 0)]
        body_strength = 1 + pet.dna.get("body_size", 0) / 5
        pet.attack_power = body_strength * visual_strength * (1 + pet.dna["eye_size"])
        pet.defense_power = pet.dna.get("ear_size", 0)
        pet.primary = pet.dna["behavior_primary"]
        pet.secondary = pet.dna["behavior_secondary"]
        pet.extra_damage = pet.dna.get("body_size", 0)

    def attack(pet, other):
        if other.hp <= 0:
            pet.target = 0
            return
        attack_points = pet.attack_power
        if attack_points == 0: return
        if pet.primary == 6: # healer
            other.hp += attack_points
            if other.hp > 100: other.hp = 100
            return
        defense_points = other.defense_power
        p = attack_points / (attack_points + defense_points)
        #print("hit chance (%d) %.2f" % (pet.owner, p))
        r = random.random()
        if p > r:
            damage = element_damge(pet.primary, other.primary, pet.secondary, other.secondary)
            damage += pet.extra_damage
            other.hp -= damage
            if other.hp < 0: other.hp = 0

if __name__ == "__main__":
    server = Server()
    server.start()


# Author: Andrey Boytsov <andrey.boytsov@uni.lu> <andrey.m.boytsov@gmail.com>
# License: BSD 3 clause (C) 2017

# Fitting iris dataset (from sklearn). Generating embedding function and using it to visualize smooth transition from
# one value to another. Comparing to embedding_close, explores way more options, different transformations.

import sys
import os
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt

# Importing from parent directory
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import dynamic_tsne
import numpy as np

if __name__ == "__main__":
    data = load_iris()
    X = data.data
    labels = data.target

    # Embedding function requires unique arrays.
    # Well, embedding fuction can protect from it, but still we can get some confusion in mean square error, if it
    # "chooses" different sample
    temp = np.ascontiguousarray(X).view(np.dtype((np.void, X.dtype.itemsize * X.shape[1])))
    _, un_idx = np.unique(temp, return_index=True)
    X = X[un_idx, :]
    labels = labels[un_idx]

    dTSNE = dynamic_tsne.DynamicTSNE(perplexity=20)
    # Small dataset. Iterations are very fast, we can afford more
    y = dTSNE.fit(X, verbose=2, optimizer_kwargs={'momentum': 0.8, 'n_iter' : 3000}, random_seed=1)
    embedder_lagrange_norm = dTSNE.generate_embedding_function(embedding_function_type='makeshift-lagrange-norm')
    embedder_weighted = dTSNE.generate_embedding_function(embedding_function_type='weighted-inverse-distance')
    embedder_linear = dTSNE.generate_embedding_function(embedding_function_type='linear')
    embedder_dim_linear = dTSNE.generate_embedding_function(embedding_function_type='linear-per-dimension')
    embedder_lagrange = dTSNE.generate_embedding_function(embedding_function_type='lagrange-per-dimension')
    embedder_rbf = dTSNE.generate_embedding_function(embedding_function_type='rbf')
    start_index = 0
    end_index = 100
    steps = 100
    Xtransition = [X[start_index, :] + (X[end_index,:] - X[start_index, :])*i/steps for i in range(steps+1)]
    y_lagrange_norm = embedder_lagrange_norm(Xtransition, verbose=2)
    y_lagrange_per_dimension = embedder_lagrange(Xtransition, verbose=2)
    y_linear_per_dimension = embedder_dim_linear(Xtransition, verbose=2)
    y_weighted = embedder_weighted(Xtransition, verbose=2)
    y_linear = embedder_linear(Xtransition, verbose=2)
    y_rbf = embedder_rbf(Xtransition, verbose=2)
    color_list = ['blue', 'orange', 'green']

    plt.gcf().set_size_inches(10, 10)
    legend_list = list()
    legend_list.append("Lagrange-like norm polynomial)")
    legend_list.append("Sum of 1D lagrange interpolations")
    legend_list.append("Sum of 1D linear interpolations")
    legend_list.append("Weighted by inverse distances")
    legend_list.append("Multidimensional linear")
    legend_list.append("RBF (multiquadratic)")
    for l in set(sorted(labels)):
        plt.scatter(y[labels == l, 0], y[labels == l, 1], c=color_list[l])
        legend_list.append(str(data.target_names[l]))
    plt.plot(y_lagrange_norm[:, 0], y_lagrange_norm[:, 1], color='black', marker='x')
    plt.plot(y_lagrange_per_dimension[:, 0], y_lagrange_per_dimension[:, 1], color='red', marker='x')
    plt.plot(y_linear_per_dimension[:, 0], y_linear_per_dimension[:, 1], color='blue', marker='x')
    plt.plot(y_weighted[:, 0], y_weighted[:, 1], color='cyan', marker='x')
    plt.plot(y_linear[:, 0], y_linear[:, 1], color='grey', marker='x')
    plt.plot(y_rbf[:, 0], y_rbf[:, 1], color='green', marker='x')
    plt.legend(legend_list)
    plt.xlim([np.min(y[:, 0])-20, np.max(y[:, 0])+20])
    plt.ylim([np.min(y[:, 1])-20, np.max(y[:, 1])+20])
    plt.title("Smooth transitioning of samples "+str(start_index) + " to " + str(end_index))
    plt.show()


# encoding: utf-8
'''
@author: jinjin
@contact: cantaloupejinjin@gmail.com
@file: expanddata.py
@time: 2019/5/10 11:13
'''
import pandas as pd
from  imblearn.over_sampling import SMOTE
filePath = "preprocess/test1.csv"
df = pd.read_csv(filePath,names=['sentiment','review'])
x = df["review"].tolist()  #x
y = df["sentiment"].tolist()#y
groupby_data_orginal = df.groupby('sentiment').count()
print("print x", x)
print("print y", y)
print(groupby_data_orginal)#打印输出原始数据集样本分类分布

# 使用SMOTE方法进行过抽样处理
model_smote = SMOTE() # 建立SMOTE模型对象
x_smote_resampled, y_smote_resampled = model_smote.fit_sample(x,y) # 输入数据并作过抽样处理
print("上一步没问题")
x_smote_resampled = pd.DataFrame(x_smote_resampled, columns=['review']) # 将数据转换为数据框并命名列名
y_smote_resampled = pd.DataFrame(y_smote_resampled,columns=['sentiment']) # 将数据转换为数据框并命名列名
smote_resampled = pd.concat([x_smote_resampled, y_smote_resampled],axis=1) # 按列合并数据框
groupby_data_smote = smote_resampled.groupby('sentiment').count() # 对label做分类汇总
print (groupby_data_smote) # 打印输出经过SMOTE处理后的数据集样本分类分布


import numpy as np
import matplotlib.pyplot as plt

def _get_spline_basis(node_points, j, k=3):
    """
    replaces template place holder with values

    @param  node_points    1d-array that is also called Knot sequence by lecture notes, is assumed to be sorted
    @param int  j      index of basis function
    @param int  k           degree of splines

    @return
    """

    def spline_basis(u):
        """
        Evaluates basis function at the point(s) u

        @param int or float or array u     point(s) at which the spline is to be evaluated

        @return numpy.ndarray       Basis functions N(u)
        """
        # initialisation of recursion
        nis = np.zeros((k + 1, len(u)))
        for l, current_j in enumerate(range(j, j + k + 1)):
            index = np.searchsorted(
                node_points[current_j - 1 : current_j + 1], u, side="right"
            )
            nis[l] = index == 1

        # loop recursion
        for current_k in range(1, k + 1):
            for current_j in range(j, j + k - current_k + 1):
                # coeff0X is for the quota in front of current_j
                coeff00 = u - node_points[current_j - 1]
                coeff01 = (
                    node_points[current_j + current_k - 1] - node_points[current_j - 1]
                )
                # coeff1X is for the quota in front of current_j + 1
                coeff10 = node_points[current_j + current_k] - u
                coeff11 = node_points[current_j + current_k] - node_points[current_j]
                if coeff01 != 0:
                    quota1 = coeff00 / coeff01
                else:
                    # divide by zero so set to zero
                    quota1 = 0
                if coeff11 != 0:
                    quota2 = coeff10 / coeff11
                else:
                    # divide by zero so set to zero
                    quota2 = 0

                # index variable
                l = current_j - j
                nis[l] = quota1 * nis[l] + quota2 * nis[l + 1]

        values = nis[0]
        return values

    return spline_basis

def _de_boor(node_points, control_points, u):
    """
    Using de boor algorithm to evaluate the spline at u
    only for cubic spline
    assuming that node points are sorted
    assuming that all values in u are inside valid u[2] <= u[-3] interval

    @param numpy.ndarray node_points     knot sequence or grid
    @param numpy.ndarray control_points    control points or de boor points
    @param int or float or array u     point(s) at which the spline is to be evaluated

    @return int or float numpy.ndarray      spline evaluated at the point(s) u
    """
    # initialisation of recursion
    hot_index = np.searchsorted(node_points, u, side="right") - 1

    dis = np.zeros((4, len(u), control_points.shape[1]))
    for current_j in range(-2, 2):
        current_index = hot_index + current_j
        current_index[current_index < 0] = 0
        current_index[current_index >= len(control_points)] = len(control_points) - 1
        # if error here, probably u outside of assumed interval is the problem
        current_control_points = control_points[current_index]
        dis[current_j + 2] = current_control_points

    # loop recursion
    for current_k in range(1, 4):
        for current_j in range(4 - current_k):
            rightmost_index = hot_index + current_j + 1
            leftmost_index = hot_index + current_j - 3 + current_k
            coeff0 = node_points[rightmost_index] - u
            coeff1 = node_points[rightmost_index] - node_points[leftmost_index]
            valid = coeff1 != 0
            alpha = np.zeros((len(u), 1))
            alpha[valid, 0] = coeff0 / coeff1
            alpha[~valid, 0] = np.nan
            # setting singular second dimension for broadcasting

            # index variable
            dis[current_j] = alpha * dis[current_j] + (1 - alpha) * dis[current_j + 1]
    values = dis[0]
    return values

def _get_automatic_node_points(points):
    """
    Create node points if they are not given.

    @param numpy.ndarray points     points that the spline should go through. Of dimension nxd, where n is the
        number of points and d the dimension

    @return numpy.ndarray      node points
    """
    # distances between points
    inter_distances = np.linalg.norm(np.diff(points, axis=0), axis=1)
    # cumsum to get nodes
    node_points = np.cumsum(inter_distances)
    # adding a starting zero
    node_points = np.insert(node_points, 0, 0)
    return node_points

class Cubic_spline:
    """
    Class for cubic splines.
    """

    def __init__(self, control_points, node_points=None):
        """
        Creates a cubic spline object. If node points are given the constructor sorts them together with the control_points. If node_points are not given the L2 norm between control_points will be used to get a node_points vector.

        @param numpy.ndarray control_points    control points or de boor points for the spline
        @param numpy.ndarray node_points     knot sequence or grid (optional)

        @return Cubic_spline object
        """
        if node_points is None:
            node_points = _get_automatic_node_points(control_points)
        else:
            # should have equal length
            assert len(control_points) == len(node_points)
            # confirm sorting of node points
            argsort = np.argsort(node_points)
            control_points = control_points[argsort]
            node_points = node_points[argsort]

        control_points = np.concatenate(
            ([control_points[0]] * 2, control_points, [control_points[-1]] * 2)
        )
        # padding to avoid indexing errors
        node_points = np.concatenate(
            (
                node_points[0] - np.zeros(2),
                node_points,
                node_points[-1] + np.arange(5) + 1,
            )
        )

        self._node_points = node_points
        self._control_points = control_points
        self._n_dimensions = control_points.shape[1]

    def get_definition_range(self):
        return [self._node_points[2], self._node_points[-4] - 1e-8]

    def __call__(self, u):
        """
        De boor's algorithm to  evaluate spline.

        @param int or float or array u     point(s) at which the spline is to be evaluated

        @return numpy.ndarray      spline evaluated at the point(s) u
        """
        if isinstance(u, (int, float)):
            u = np.array([u])

        s = np.zeros((len(u), self._n_dimensions))
        valid_u = (self._node_points[2] <= u) & (u <= self._node_points[-3])
        # setting all values not valid as nan
        s[~valid_u] = np.nan
        s[valid_u] = _de_boor(self._node_points, self._control_points, u[valid_u])

        # if not input is array output is expected to not be array
        s = s.squeeze()
        return s

    def plot(self, show=True):
        """
        Method to plot spline of the Cubic_spline class.
        De boor's algorithm to  evaluate spline.

        @param bool                if true matplotlib.pyplot.show() is executed

        @return optionally (matplotlib.figure, matplotlib.axes) if show == False the matplotlib figure and axes is returned for further formatting / saving

        """
        u = np.linspace(self._node_points[2], self._node_points[-3], 100)[:-1]
        s = self(u)
        if self._n_dimensions == 2:
            subplot_kw = None
        elif self._n_dimensions == 3:
            subplot_kw = dict(projection="3d")
        else:
            raise ValueError(
                f"This spline with {self._n_dimensions} dimensions can not be plotted."
            )
        fig, ax = plt.subplots(subplot_kw=subplot_kw)
        ax.plot(*s.T, label="spline")
        ax.plot(*self._control_points.T, "ro--", label="control points")
        ax.plot(*self._control_points[0], "ro", markersize=10)
        if show:
            ax.legend()
            plt.show()
        else:
            return fig, ax

FMNN25 - Advanced Course in Numerical Algorithms with Python and SciPy/Project 1/splines/__init__.py


#!/usr/bin/env python
# encoding: utf-8

# Before running this program, first Start HFO server:
# $> ./bin/HFO --offense-agents 1

import itertools
import math
from hfo import *
import argparse

"""
Possible game statuses:
  [IN_GAME] Game is currently active
  [GOAL] A goal has been scored by the offense
  [CAPTURED_BY_DEFENSE] The defense has captured the ball
  [OUT_OF_BOUNDS] Ball has gone out of bounds
  [OUT_OF_TIME] Trial has ended due to time limit
  [SERVER_DOWN] Server is not alive
"""

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--port', default=6000, type=int)
  parser.add_argument('--feature_set', default=HIGH_LEVEL_FEATURE_SET, type=int)
  args = parser.parse_args()

  # Create the HFO Environment
  hfo = HFOEnvironment()
  # Connect to the server with the specified
  # feature set. See feature sets in hfo.py/hfo.hpp.
  hfo.connectToServer(args.feature_set,
                      '/home/student/Desktop/HFO-master/bin/teams/base/config/formations-dt', args.port,
                      'localhost', 'base_right', True)

  for episode in range(5):
    status = IN_GAME
    while status == IN_GAME:
      # Grab the state features from the environment
      features = hfo.getState()
      status = hfo.step()
    # Check the outcome of the episode
    print(('Episode %d ended with %s'%(episode, hfo.statusToString(status))))
    # Quit if the server goes down
    if status == SERVER_DOWN:
      hfo.act(QUIT)
      exit()

if __name__ == '__main__':
  main()


import os
import sys
import glob
import random
from pathlib import Path
from argparse import ArgumentParser
import numpy as np
import torch
from mmcv.onnx import register_extra_symbolics
from mmocr.apis import init_detector

sys.path.append('mmocr/tools')
from deployment.pytorch2onnx import _convert_batchnorm

def create_input_data(prep_dir):
    prep_dir = Path(prep_dir)
    file_name = random.choice(os.listdir(prep_dir/'texts'))

    dummy_input = []
    for input_name in ['relations', 'texts', 'mask']:
        file_path = prep_dir/input_name/file_name
        data = torch.from_numpy(np.load(file_path))
        dummy_input.append(data)

    return tuple(dummy_input)

def pytorch2onnx(config_file, checkpoint_file, prep_dir,
                 output_file, opset_version=12):
    device = torch.device(type='cpu')
    model = init_detector(config_file, checkpoint_file, device=device)
    if hasattr(model, 'module'):
        model = model.module
    model.to(torch.device('cpu')).eval()
    _convert_batchnorm(model)

    dummy_input = create_input_data(prep_dir)
    dynamic_axes = {
        'relations': {0: 'num_texts', 1: 'num_texts'},
        'texts': {0: 'num_texts', 1: 'num_chars'},
        'mask': {0: 'num_texts', 1: 'num_chars'},
        'nodes': {0: 'num_texts', 1: 'num_texts'},
        'edges': {0: 'num_edges'},
    }

    model.forward = model.forward_onnx
    model.bbox_head.forward = model.bbox_head.forward_onnx
    register_extra_symbolics(opset_version)
    with torch.no_grad():
        torch.onnx.export(
            model,
            dummy_input,
            output_file,
            input_names=['relations', 'texts', 'mask'],
            output_names=['nodes', 'edges'],
            export_params=True,
            keep_initializers_as_inputs=False,
            verbose=False,
            opset_version=opset_version,
            dynamic_axes=dynamic_axes,
        )
    print(f'Successfully exported ONNX model: {output_file}')

def main():
    parser = ArgumentParser('Convert MMOCR models from pytorch to ONNX')
    parser.add_argument('--config', type=str, help='config file.')
    parser.add_argument('--checkpoint', type=str, help='checkpint file.')
    parser.add_argument('--prep-dir', type=str, help='path to preprocessed data')
    parser.add_argument('--onnx', type=str, help='path to save onnx model.')
    parser.add_argument('--opset-version', type=int, default=12,
                        help='ONNX opset version.')
    args = parser.parse_args()

    pytorch2onnx(args.config, args.checkpoint, args.prep_dir,
                 args.onnx, opset_version=args.opset_version)

if __name__ == '__main__':
    main()


import json
import re
from tqdm import tqdm
import random

def process_one_line(line):
    question = line.split("col : ")[0].strip()
    if not question:
        return None, None

    header = line.split("col : ")[1].split("row 1 : ")[0].strip()
    header = [i.strip() for i in header.split("|")]
    num_col = len(header)

    rows = re.split("row \d+ : ", line.split("col : ")[1].strip())
    output_rows = []
    for row in rows:
        row = row.strip()
        if row == "":
            continue
        row = row.split("|")
        row = [x.strip() for x in row]
        output_rows.append(row)
        if len(row) != num_col:
            return None, None

    table = {
        "header": header,
        "rows": output_rows,
    }

    return question, table

def process_tapex_data(src_file, tgt_file):
    src_lines = open(src_file).readlines()
    tgt_lines = open(tgt_file).readlines()
    outputs = []
    err_count = 0

    for i, line in enumerate(tqdm(src_lines)):
        question, table = process_one_line(line)
        if not question:
            err_count += 1
            continue
        answer = tgt_lines[i].strip().split(", ")

        cur_example = {
            "source": "tapex",
            "question": question,
            "table": table,
            "answers": answer,
        }

        outputs.append(cur_example)

    print("Error count: ", err_count)
    print("Total examples: ", len(outputs))
    return outputs

if __name__ == "__main__":
    src_file = "tapex_data/sql_executor.src"
    tgt_file = "tapex_data/sql_executor.tgt"
    output_file = "output/tapex_pretrain_data.json"
    output_sample_file = "output/tapex_pretrain_data_sample.json"

    outputs = process_tapex_data(src_file, tgt_file)
    json.dump(outputs, open(output_file, "w"), indent=4)
    json.dump(random.sample(outputs, 1000), open(output_sample_file, "w"), indent=4)


import cv2
import numpy as np
from PIL import Image
import os
# from matplotlib import pyplot as plt

dir = '/test/nPCR'
image_path = 'D:/Study/Dataset/medicaldata_uint16_png_3_2_1' + dir
outputpath = 'D:/Study/Dataset/medicaldata_uint16_png_3_2_2' + dir
outputpath = outputpath + '/'
#outputpath = 'D:/Study/Dataset/PCR_nPCR/output_GE/'

def rotateimage(img_path,outputpath,filename):
    img = cv2.imread(img_path,-1)
    #img180 = np.rot90(img, 2)
    img180 = cv2.rotate(img, cv2.ROTATE_180)
    # cv2.imshow("rotate", img180)
    # cv2.waitKey(0)
    output_imagepath = outputpath + 'rotate' + filename
    cv2.imwrite(output_imagepath, img180)

filelist = os.listdir(image_path) #获取主目录下的子文件
for first_dir in filelist:
    img_path = image_path + '/' + first_dir
    #imagename, suffix = os.path.splitext(first_dir)
    rotateimage(img_path, outputpath, first_dir)


#!/usr/bin/env python3

import argparse
import logging
from time import sleep
import json

from market_data import MarketDataListener
from trading_client import TradingClientFactory
from candle import CandleManager
from tick import TickManager
from collections import OrderedDict
import os
from os import path
from utils import get_workdir

def main(args):
    workdir = get_workdir()
    os.makedirs(workdir, exist_ok=True)

    logging.basicConfig(level=logging.DEBUG, filename=path.join(workdir, 'log.txt'), format='%(asctime)s - %(levelname)s - %(message)s')

    with open(args.portfolio_file, 'r') as f:
        portfolio = json.load(f)

    client_factory = TradingClientFactory()

    candle_manager_dict = {} #Contains mapping from symbol to its candle manager to prevent duplication of candle managers for clients of same symbol
    symbol_list = []
    clients = []

    for client in portfolio:
        symbol = client['symbol']
        if(symbol not in symbol_list):
            symbol_list.append(symbol)
        trading_client = client_factory.load(client['Name'], **OrderedDict(client))
        clients.append(trading_client)

        if(symbol not in candle_manager_dict):
            candle_manager = CandleManager(symbol)
            candle_manager_dict[symbol] = candle_manager
        else:
            candle_manager = candle_manager_dict[symbol]
        candle_manager.register_trading_client(trading_client)

    market_data_listener = MarketDataListener(symbol_list, args.api_key, args.request_token, args.api_secret)
    tick_manager = TickManager(market_data_listener.instrument_token_to_symbol)

    for client in clients:
        client.order_manager.initialize_kite(market_data_listener.kite)

    for symbol, candle_manager in candle_manager_dict.items():
        candle_manager.create_candle_generators()
        tick_manager.register_candle_manager(candle_manager)

    market_data_listener.connect()
    while True:
        market_data_listener.kws.on_ticks = tick_manager.on_ticks

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--portfolio_file',help='give the json file having the portfolio to be traded on', required=True)
    parser.add_argument('--api_key', help='API Key, contact developer', required=True)
    parser.add_argument('--api_secret', help='API Secret, contact developer', required=True)
    parser.add_argument('--request_token', help='API request_token, login at https://kite.trade/connect/login?api_key={api_key}&v=3', required=True)
    return parser.parse_args()

if __name__ == "__main__":
    main(get_args())


#!/usr/bin/env python3

def main():
    count=0
    inputList = [ int(input()) for i in range(4) ]
    for i in range(inputList[0]+1):
        for j in range(inputList[1]+1):
            if 0 <= (inputList[3]-(500*i+100*j))/50 <= inputList[2]:
                count=count+1
    print(count)
if __name__ == '__main__':
    main()


import torch
import numpy as np
from functions import plot_results

def training_loop(num_epochs, model, trainloader, valloader, optimizer, save_path):

    val_loss_n = [100000, 99999]
    train_loss_n = [100000, 99999]

    for epoch in range(num_epochs):

        print(f'Epoch {epoch+1}/{num_epochs}')
        print('-' * 10)

        train_loss = []
        val_loss = []

        model.train()
        for inputs, targets in trainloader:

            inputs = [input.permute(2, 0, 1) for input in inputs] #H W C to C H W
            outputs = model(inputs, targets)
            losses = sum(loss for loss in outputs.values())
            loss_value = losses.item()

            optimizer.zero_grad()
            losses.backward()
            optimizer.step()

            train_loss.append(loss_value)

        with torch.no_grad():
            for inputs, targets in valloader:
                inputs = [input.permute(2, 0, 1) for input in inputs]
                outputs = model(inputs, targets)
                losses = sum(loss for loss in outputs.values())
                loss_value = losses.item()

                val_loss.append(loss_value)

            train_loss = np.sum(train_loss)/len(train_loss)
            val_loss = np.sum(val_loss)/len(val_loss)

            if val_loss < np.min(val_loss_n):
                torch.save({
                        'epoch': epoch,
                        'model_state_dict': model.state_dict(),
                        'optimizer_state_dict': optimizer.state_dict(),
                        'loss': val_loss,
                        }, save_path)
                print('\nmodel saved!\n')

            train_loss_n.append(train_loss)
            val_loss_n.append(val_loss)

        print(f'Training loss: {train_loss:.2f}, Validation loss: {val_loss:.2f}')

    return model

def testing_loop(model, testloader, threshold):

    model.eval()

    for inputs, targets in testloader:
        images = []
        for img in inputs:
            images.append(img.cpu().detach().numpy())

        inputs = [input.permute(2, 0, 1) for input in inputs]

        outputs = model(inputs)

        plot_results(images, outputs, targets, threshold)
        break


import pytest
import random
from x264codec.x264codec import X264Codec

def test_creategif():
    vh = X264Codec.from_format_video("tests/video_file/done_h.mp4")
    for _ in range(10):
        start = random.random() * 100
        height = random.randint(240, 480)
        last = random.random() * 100
        gif = vh.gif(start, last, height)
        print(f"===== start: {start}, last: {last}, height: {height} =====")
        print(gif)


# 1 countdown
num = ()
def count_down(num):
    for num in range(num, -1, -1):
        print(num)
count_down(5)

# 2 print and return
def print_and_return(a,b):
    print(a)
    return b
print_and_return(5,4)

# 3 First plus length
list = [1,2,3,4,5]
a = 0
b = 0
def first_plus_length():
    a = list[0]
    b = len(list)
    return(a+b)
print(first_plus_length())

# 4 values greater than second
list1 = [1,2,3,5,6,2,1]
greater_than = list1[1]
length = len(list1)
def values_greater_than_second(list):
    if length < 2:
        return False
    new_list = []
    for i in list:
        if i > greater_than:
            new_list.append(i)
    print(len(new_list))
    return new_list
print(values_greater_than_second(list1))

#5 this length, that value
def length_and_value(length, value):
    list1 = []
    for i in range(length):
        list1.append(value)
    return list1
print(length_and_value(5,6))


from ..pages.product_page import ProductPage
from ..pages.main_page import MainPage
from ..pages.login_page import LoginPage
from ..pages.basket_page import BasketPage
from ..pages.locators import ProductPageLocators
from pytest import mark, param, fixture
from time import sleep, time

PROD_PAGE_LINK = "http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/"

class TestUserAddToBasketFromProductPage:

    @fixture(scope="function", autouse=True)
    def setup(self, browser):
        page = ProductPage(browser, PROD_PAGE_LINK)
        page.open()
        page.go_to_login_page()
        login_page = LoginPage(browser, browser.current_url)
        login_page.register_new_user(str(time()) + "@fakemail.org", "VerySecurePassword")
        login_page.should_be_authorized_user()

    def test_user_cant_see_success_message(self, browser):
        page = ProductPage(browser, PROD_PAGE_LINK)
        page.open()
        page.should_not_be_success_message()

    @mark.need_review
    def test_user_can_add_product_to_basket(self, browser):
        page = MainPage(browser, PROD_PAGE_LINK)
        page.open()
        prod_page = ProductPage(browser, browser.current_url)
        product, price = prod_page.should_be_product_page()
        prod_page.put_to_basket()
        prod_page.shoud_be_notified(product, price)

@mark.need_review
@mark.parametrize("promo", [
    *range(0, 7),
    param(7, marks=mark.xfail(reason="Bug that is not gonna be fixed")),
    8, 9
    ])
def test_guest_can_add_product_to_basket(browser, promo):
    link = PROD_PAGE_LINK + "?promo=offer{promo}"
    page = MainPage(browser, link)
    page.open()
    prod_page = ProductPage(browser, browser.current_url)
    product, price = prod_page.should_be_product_page()
    prod_page.put_to_basket()
    page.solve_quiz_and_get_code()
    prod_page.shoud_be_notified(product, price)

def test_guest_cant_see_success_message_after_adding_product_to_basket(browser):
    page = MainPage(browser, PROD_PAGE_LINK)
    page.open()
    prod_page = ProductPage(browser, browser.current_url)
    prod_page.put_to_basket()
    assert page.is_not_element_present(*ProductPageLocators.ALERT_SUCCESS)

def test_message_disappeared_after_adding_product_to_basket(browser):
    page = MainPage(browser, PROD_PAGE_LINK)
    page.open()
    prod_page = ProductPage(browser, browser.current_url)
    prod_page.put_to_basket()
    assert page.is_disappeared(*ProductPageLocators.ALERT_SUCCESS)

def test_guest_should_see_login_link_on_product_page(browser):
    link = "http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/"
    page = ProductPage(browser, link)
    page.open()
    page.should_be_login_link()

@mark.need_review
def test_guest_can_go_to_login_page_from_product_page(browser):
    link = "http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/"
    page = ProductPage(browser, link)
    page.open()
    page.go_to_login_page()
    login_page = LoginPage(browser, browser.current_url)
    login_page.should_be_login_page()

@mark.need_review
def test_guest_cant_see_product_in_basket_opened_from_product_page(browser):
    link = "http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/"
    page = ProductPage(browser, link)
    page.open()
    page.view_cart()
    basket = BasketPage(browser, browser.current_url)
    basket.should_be_empty_cart()
    basket.should_be_empty_cart_message()


#!/usr/bin/python3
from threading import Thread,Semaphore
import os
import time
import threading

Semaforo_descargue=Semaphore(2)

semaforo_p=Semaphore(3)
cont_pesado = 0
cont_descar = 1
l_caminones=[]

class Camion(Thread):
	def __init__(self,id,peso): #Constructor de la clase
		Thread.__init__(self)
		self.peso=peso
		self.id=id
		self.estado=0
#	def givepeso(self):
#		return self.peso
#	def giveid(self):
#		return self.id
#	def give_estado(self):
#		return self.estado

	def run(self):
		pesar(self.id,self.peso)
		print("-- Salio zona de pesado")
		descargue(self.id,self.peso)

def pesar(car,val):
	global cont_pesado	#donde se va a pesar
	print("++ El carro: "+ str(car) +" Esta en espera de Peso")
	semaforo_p.acquire()
	posini=cont_pesado
	posini=posini+1
	if posini>3 :
		posini=1
	cont_pesado=posini
	time.sleep(1)
	print("** El carro: "+ str(car) +" Fue atendido en:"+str(posini)+ " y Pesa: " + str(val))
	semaforo_p.release()

def descargue(car,val):
	global cont_descar	#donde se va a pesar
	Semaforo_descargue.acquire()
	print("** El carro: "+ str(car) +" Esta en espera de Descargue")
	posini=cont_descar
	posini=cont_descar+3
	if posini>4 :
		posini=1
	cont_descar=posini

	time.sleep(3)
	print("++ El carro: "+ str(car) +" Fue Descargado en:"+str(posini)+ " y Pesa: " + str(val))
	Semaforo_descargue.release()

def main():
	global l_caminones
	l_caminones=[Camion(1,54),Camion(2,22),Camion(3,45),Camion(4,67),Camion(5,43)]
	for h in l_caminones:
		h.start()
main()


import json
import os
import pickle
import re
import string

import requests
import zhconv
import jieba
from keras.preprocessing import sequence
from config import config

class Result:
    label2zh = {'location_traffic_convenience': '交通是否便利',
                'location_distance_from_business_district': '距离商圈远近',
                'location_easy_to_find': '是否容易寻找',
                'service_wait_time': '排队等候时间',
                'service_waiters_attitude': '服务人员态度',
                'service_parking_convenience': '是否容易停车',
                'service_serving_speed': '点菜/上菜速度', 'price_level': '价格水平',
                'price_cost_effective': '性价比', 'price_discount': '折扣力度',
                'environment_decoration': '装修情况', 'environment_noise': '嘈杂情况',
                'environment_space': '就餐空间', 'environment_cleaness': '卫生情况',
                'dish_portion': '分量', 'dish_taste': '口感', 'dish_look': '外观',
                'dish_recommendation': '推荐程度',
                'others_overall_experience': '本次消费感受',
                'others_willing_to_consume_again': '再次消费的意愿', 'location': '位置',
                'service': '服务', 'price': '价格', 'environment': '环境',
                'dish': '菜品', 'others': '其它'}

    label_layers = {'location': ['location_traffic_convenience',
                                 'location_distance_from_business_district',
                                 'location_easy_to_find'],
                    'service': ['service_wait_time', 'service_waiters_attitude',
                                'service_parking_convenience',
                                'service_serving_speed'],
                    'price': ['price_level', 'price_cost_effective',
                              'price_discount'],
                    'environment': ['environment_decoration',
                                    'environment_noise', 'environment_space',
                                    'environment_cleaness'],
                    'dish': ['dish_portion', 'dish_taste', 'dish_look',
                             'dish_recommendation'],
                    'others': ['others_overall_experience',
                               'others_willing_to_consume_again']}

    sentiment = ['未提及', '负向', '中性', '正向']

    def render(self, prob_dict, mode='tree'):
        if mode == 'tree':
            results = {'name': '点评', 'children': []}
            for layer1 in self.label_layers.keys():
                layer1_zh = self.label2zh[layer1]
                layer1_dict = {'name': layer1_zh, 'children': []}
                for layer2 in self.label_layers[layer1]:
                    probs = prob_dict.get(
                        layer2,{"predictions": [[0, 0, 0, 0]]})["predictions"][0]
                    label = ['未提及', '负向', '中性', '正向']
                    layer2_zh = self.label2zh[layer2]
                    prob_with_label = [{'name': l, 'value': str(round(v, 2))}
                                       for l, v in zip(label, probs)]
                    # 如何可视化这结果？？？
                    layer2_dict = {'name': layer2_zh,
                                   'children': prob_with_label}
                    layer1_dict['children'].append(layer2_dict)
                results['children'].append(layer1_dict)
            return results

class SentimentClassifier:
    def __init__(self):
        clfs_dir = config['production'].CLASSIFIER_DIR
        clfs_path = {p: os.path.join(clfs_dir, p) for p in os.listdir(clfs_dir)
                     if os.path.isdir(os.path.join(clfs_dir, p))}
        base_api = 'http://localhost:8012/v1/models/{}:predict'
        clfs_api = {cate: base_api.format(cate) for cate in clfs_path}

        with open(config['production'].TOKENIZER, 'rb') as f:
            tokenizer = pickle.load(f)

        self.tokenizer = tokenizer
        self.clfs_api = clfs_api

    def preprocess(self, text):
        punct = r"，。！？、；：“”\n＂＃＄％＆＇（）＊＋－／＜＝＞＠［＼］＾＿｀｛｜｝～｟｠｢｣､" \
                r"〃《》「」『』【】〔〕〖〗〘〙〚〛〜〝〟〰〾〿–—‛„‟…‧﹏★☆•→▽"

        def clean_special_chars(text):
            text = text.encode('utf-8').decode('utf-8')
            re_tok = re.compile(f'([{string.punctuation}{punct}])')
            return re_tok.sub(r' ', text)

        def simplify(text):
            return zhconv.convert(text, 'zh-cn')

        def cut_join(text):
            space = ' '
            words = jieba.cut(text)
            return space.join([w.lower() for w in words if not w.isspace()])

        sents = re.split('[.!?。！？]', text.strip())
        results = []
        for sent in sents:
            if sent:
                sent = clean_special_chars(sent)
                sent = simplify(sent)
                sent = cut_join(sent)
                results.append(sent)
        return ' '.join(results)

    def text2vector(self, text):
        text = self.preprocess(text)
        text_seq = self.tokenizer.texts_to_sequences([text])
        text_seq = sequence.pad_sequences(text_seq, maxlen=250)
        return text_seq

    def predict(self, text):
        results = {}
        X_input = self.text2vector(text)

        X_input = X_input.astype('int').tolist()[0]
        print(X_input)
        payload = {"instances": [{'input_text': X_input}]}
        for cate in self.clfs_api.keys():
            r = self.single_predict(cate, payload)
            results[cate] = r
        return self.format_probs(results)

    def single_predict(self, cate, payload):
        api = self.clfs_api[cate]
        r = requests.post(api, json=payload)
        if r.ok:
            print(cate, r.content.decode('utf-8'))
            result = json.loads(r.content.decode('utf-8'))
        else:
            result = {"predictions": [[0.0, 0.0, 0.0, 0.0]]}
        return result

    def format_probs(self, probs):
        r = Result()
        results = r.render(probs, mode='tree')

        return results


from inspect import classify_class_attrs
import numpy
import cv2
import customtkinter
import pickle
from PIL import ImageTk, Image
import pandas
import mediapipe
import tkinter
from sample_landmarks import landmarks

app = tkinter.Tk()
customtkinter.set_appearance_mode("dark")
app.title("Computer Vision Workout App")
app.geometry("480x700")

def reset():
    global reps
    reps = 0

#obtains the picture of the motion done on the camera and analyzes it via pose estimation
def detect_motions():
    global prob
    global current_motion_point
    global reps
    global class_current

    r, f = video_capture.read()

    captured_image = cv2.cvtColor(f, cv2.COLOR_BGR2RGB)

    process_image = pose_estimation.process(captured_image)

    draw_lines.draw_landmarks(captured_image, process_image.pose_landmarks, get_estimation.POSE_CONNECTIONS, draw_lines.DrawingSpec(circle_radius = 2, color = (0,0,255), thickness = 2), draw_lines.DrawingSpec(circle_radius = 2, color = (0,255,0), thickness = 2))

    try:
        landmark_row = numpy.array([[landmark.x, landmark.y, landmark.z, landmark.visibility] for landmark in process_image.pose_landmarks.landmark]).flatten().tolist()
        landmark_row_col = pandas.DataFrame([landmark_row], columns = landmarks)
        prob = train_model.predict_proba(landmark_row_col)[0]
        class_current = train_model.predict(landmark_row_col)[0]
        if(prob[prob.argmax()] > 0.7 and class_current == "up" and current_motion_point == "down"):
            current_motion_point = "up"
            reps = reps + 1
        elif(prob[prob.argmax()] > 0.7 and class_current == "down"):
            current_motion_point = "down"
    except Exception as error:
        pass

    slice_img = captured_image[:, :460, :] #slice the image
    array_img = Image.fromarray(slice_img) #convert it into an array
    tk_img = ImageTk.PhotoImage(array_img) #convert from array to tk image
    window_l.tk_img = tk_img
    window_l.configure(image = tk_img)
    window_l.after(10, detect_motions)
    probability_b.configure(text = prob[prob.argmax()])
    class_b.configure(text = current_motion_point)
    counter_b.configure(text = reps)

probability_l = customtkinter.CTkLabel(app, text_font = ("Arial", 18), text_color = "black", padx = 10, width = 120, height = 40)
probability_l.configure(text = "Odds")
probability_l.place(x = 300, y = 1)
probability_b = customtkinter.CTkLabel(app, text_font = ("Arial", 18), text_color = "black", fg_color = "red", width = 120, height = 40)
#probability_b.configure(text = "0")
probability_b.place(x = 300, y = 41)

class_l = customtkinter.CTkLabel(app, text_font = ("Arial", 18), text_color = "black", padx = 10, width = 120, height = 40)
class_l.configure(text = "Motion")
class_l.place(x = 10, y = 1)
class_b = customtkinter.CTkLabel(app, text_font = ("Arial", 18), text_color = "black", fg_color = "red", width = 120, height = 40)
class_b.configure(text = "0")
class_b.place(x = 10, y = 41)

counter_l = customtkinter.CTkLabel(app, text_font = ("Arial", 18), text_color = "black", padx = 10, width = 120, height = 40)
counter_l.configure(text = "Reps")
counter_l.place(x = 160, y = 1)
counter_b = customtkinter.CTkLabel(app, text_font = ("Arial", 18), text_color = "black", fg_color = "red", width = 120, height = 40)
counter_b.configure(text = "0")
counter_b.place(x = 160, y = 41)

reset_button = customtkinter.CTkButton(app, text_font = ("Arial", 18), text_color = "black", command = reset, fg_color = "red", text = "Reset Reps", width = 120, height = 40)
reset_button.place(x = 10, y = 600)

window = tkinter.Frame(width = 480, height = 480)
window.place(x = 10, y = 90)
window_l = tkinter.Label(window)
window_l.place(x = 0, y = 0)

get_estimation = mediapipe.solutions.pose
pose_estimation = get_estimation.Pose(min_detection_confidence = 0.5, min_tracking_confidence = 0.5)

draw_lines = mediapipe.solutions.drawing_utils

with open('deadlift_training_data.pkl', 'rb') as data:
    train_model = pickle.load(data)

prob = numpy.array([0,0])
current_motion_point = ''
reps = 0
class_current = ''
video_capture = cv2.VideoCapture(0)
detect_motions()

app.mainloop()


# https://leetcode.com/problems/subsets-ii/description/

class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        """
        Logic: Backtracking

        Time: O(n*2^n)
        Space: O(n)
        """
        def backtrack(start, curr, res):
            res.append(curr[::])
            for i in range(start, len(nums)):
                if i != start and nums[i] == nums[i-1]:
                    continue
                curr.append(nums[i])
                backtrack(i+1, curr, res)
                curr.pop()

        nums.sort()
        res = []
        backtrack(0, [], res)

        return res


""" Remove Duplicates from the list """
def remove_duplicate(lst):
    # initializing empty list
    res = []

    # iterate over the elements
    for i in lst:
        if i not in res:
            # add items that are not in the new list
            res.append(i)

    # return list without duplicates
    return res

# input list elements
list_data = list(map(int, input('Enter elements: ').split()))

# printing result
print(f'The list after removing duplicates: {remove_duplicate(list_data)}')


from math import sqrt

# invoer
a = float(input('Geef x: '))

# berekening
if a < 2:
    if x == 2:
        mes = '{:.2f} ∉ dom(f)'.format(a)
    else:
        mes = ''
elif x < 2:
    mes = 'x ∉ dom(f)'

# uitvoer
print(mes)