n=int(input(': '))
i=int(input(': '))
j=int(input(': '))

c=int()
b=int()

if n%i==0:
    print(n,(n//i),0)
elif n%j==0:
    print(n,0,(n//j))
elif not (n%i==0 and n%j==0):
    c=n%i
    result=c%j
    b = n % j
    second_res = b % i
    if result==0:

        print(n,n//i,c//j)

    elif second_res==0:
        print(n, b // i, n // j)

    elif c%j==c or n%j==n:
            print("-1")


import torch
from torch.nn import ZeroPad2d
from torch import LongTensor
from torch.utils.data import random_split
from torch import count_nonzero
import math
from collections import deque
from treelib import Tree, Node
from sklearn.model_selection import train_test_split
from itertools import zip_longest
import networkx as nx
from treelib import Tree, Node
import numpy as np
from itertools import compress, islice
import os
from pathlib import Path
import json

from data.tokens import grouper_mol

DATA_DIR = "resource"
NODE_TYPE_DICT = {'F': 9, 'O': 10, 'N': 11, 'C': 12, 'P': 13, 'I': 14, 'Cl': 15, 'Br': 16, 'S': 17}
TYPE_NODE_DICT = {str(key): value for value, key in NODE_TYPE_DICT.items()}
BOND_TYPE_DICT = {1: 5, 2: 6, 3: 7, 1.5: 8}
TYPE_BOND_DICT = {key: value for value, key in NODE_TYPE_DICT.items()}

def get_level(node):
    return int(node.identifier.split('-')[0])

def get_location(node):
    return int(node.identifier.split('-')[1])

def get_k(tree):
    return math.sqrt(len(tree[tree.root].successors(tree.identifier)))

def get_parent(node, tree):
    return tree[node.predecessor(tree.identifier)]

def get_children_identifier(node, tree):
    return sorted(node.successors(tree.identifier), key=lambda x: get_sort_key(x))

def get_sort_key(node_id):
    if len(node_id.split('-')) > 2:
        return (int(node_id.split('-')[0]), int(node_id.split('-')[1]), int(node_id.split('-')[2]))
    else:
        return (int(node_id.split('-')[0]), int(node_id.split('-')[1]))

def nearest_power(N, base=2):
    a = int(math.log(N, base))
    if base**a == N:
        return N

    return base**(a + 1)

def adj_to_k2_tree(adj, return_tree=False, is_wholetree=False, k=4, is_mol=False):
    if not is_mol:
        adj[adj > 0] = 1
    n_org_nodes = adj.shape[0]
    # add padding (proper size for k)
    n_nodes = nearest_power(n_org_nodes, k)
    k_square = k**2
    padder = ZeroPad2d((0, n_nodes-n_org_nodes, 0, n_nodes-n_org_nodes))
    padded_adj = padder(adj)
    total_level = int(math.log(n_nodes, k))
    tree_list = []
    leaf_list = []
    tree = Tree()
    # add root node
    tree.create_node("root", "0")
    tree_key_list = deque([])
    slice_size = int(n_nodes / k)
    # slice matrices
    start_index = range(0,n_nodes,slice_size)
    end_index = range(slice_size,n_nodes+1,slice_size)
    slices = []
    for row_start, row_end in zip(start_index, end_index):
        for col_start, col_end in zip(start_index, end_index):
            slices.append(padded_adj[row_start:row_end, col_start:col_end])

    sliced_adjs = deque(slices)
    sliced_adjs_is_zero = LongTensor([int(count_nonzero(adj)>0) for adj in sliced_adjs])
    tree_list.append(sliced_adjs_is_zero)
    # molecule + only leaf
    if is_mol and adj.shape[0] == k:
        tree_element_list = deque(list(map(int, torch.flatten(adj).tolist())))
    else:
        tree_element_list = deque(sliced_adjs_is_zero)

    for i, elem in enumerate(tree_element_list, 1):
        tree.create_node(elem, f"1-{i}", parent="0")
        tree_key_list.append(f"1-{i}")

    while (slice_size != 1):
        n_nodes = sliced_adjs[0].shape[0]
        if n_nodes == k:
            if is_wholetree:
                leaf_list = [adj.reshape(k_square,) for adj in sliced_adjs]
            else:
                leaf_list = [adj.reshape(k_square,) for adj in sliced_adjs if count_nonzero(adj)>0]
            break
        slice_size = int(n_nodes / k)
        target_adj = sliced_adjs.popleft()
        target_adj_size = target_adj.shape[0]
        if return_tree:
            parent_node_key = tree_key_list.popleft()
        # remove adding leaves to 0
        if not is_wholetree:
            if count_nonzero(target_adj) == 0:
                continue
        # generate tree_list and leaf_list
        new_sliced_adjs = []
        start_index = range(0,n_nodes,slice_size)
        end_index = range(slice_size,n_nodes+1,slice_size)
        for row_start, row_end in zip(start_index, end_index):
            for col_start, col_end in zip(start_index, end_index):
                new_sliced_adjs.append(target_adj[row_start:row_end, col_start:col_end])
        new_sliced_adjs_is_zero = LongTensor([int(count_nonzero(adj)>0) for adj in new_sliced_adjs])
        sliced_adjs.extend(new_sliced_adjs)
        tree_list.append(new_sliced_adjs_is_zero)

        if return_tree:
            # generate tree
            tree_element_list.extend(new_sliced_adjs_is_zero)
            cur_level = int(total_level - math.log(target_adj_size, k) + 1)
            cur_level_key_list = [int(key.split('-')[1]) for key in tree_key_list if int(key.split('-')[0]) == cur_level]
            if len(cur_level_key_list) > 0:
                key_starting_point = max(cur_level_key_list)
            else:
                key_starting_point = 0
            for i, elem in enumerate(new_sliced_adjs_is_zero, key_starting_point+1):
                tree.create_node(elem, f"{cur_level}-{i}", parent=parent_node_key)
                tree_key_list.append(f"{cur_level}-{i}")

    if return_tree:
        # add leaves to tree
        leaves = [node for node in tree.leaves() if node.tag == 1]
        index = 1
        for leaf, leaf_values in zip(leaves, leaf_list):
            for value in leaf_values:
                tree.create_node(int(value), f"{total_level}-{index}", parent=leaf)
                index += 1
        return tree
    else:
        return tree_list, leaf_list

def check_tree_validity(tree):
    depth = tree.depth()
    if depth == 1:
        return False
    leaves = [leaf for leaf in tree.leaves() if leaf.tag != '0']
    invalid_leaves = [leaf for leaf in leaves if tree.depth(leaf)!=depth]
    if len(invalid_leaves) == 0:
        return True
    else:
        return False

def tree_to_adj(tree, k=2):
    '''
    convert k2 tree to adjacency matrix
    '''
    tree = map_starting_point(tree, k)
    depth = tree.depth()
    leaves = [leaf for leaf in tree.leaves() if leaf.tag != '0']
    one_data_points = [leaf.data for leaf in leaves]
    x_list = [data[0] for data in one_data_points]
    y_list = [data[1] for data in one_data_points]
    label_list = [NODE_TYPE_DICT[leaf.tag] if leaf.tag in NODE_TYPE_DICT.keys() else int(leaf.tag) for leaf in leaves]
    matrix_size = int(k**depth)
    adj = torch.zeros((matrix_size, matrix_size))
    for x, y, label in zip(x_list, y_list, label_list):
        # if (x > len(adj)) or (y > len(adj)):
        #     return None
        adj[x, y] = label

    return adj

def map_starting_point(tree, k):
    '''
    map starting points for each elements in tree (to convert adjacency matrix)
    '''
    try:
        bfs_list = [tree[node] for node in tree.expand_tree(mode=Tree.WIDTH,
                                                            key=lambda x: (int(x.identifier.split('-')[0]), int(x.identifier.split('-')[1]), int(x.identifier.split('-')[2])))]
    except:
        bfs_list = [tree[node] for node in tree.expand_tree(mode=Tree.WIDTH,
                                                            key=lambda x: (int(x.identifier.split('-')[0]), int(x.identifier.split('-')[1])))]
    bfs_list[0].data = (0,0)

    for node in bfs_list[1:]:
        parent = get_parent(node, tree)
        siblings = get_children_identifier(parent, tree)
        index = siblings.index(node.identifier)
        level = get_level(node)
        tree_depth = tree.depth()
        matrix_size = k**tree_depth
        adding_value = int(matrix_size/(k**level))
        parent_starting_point = parent.data
        node.data = (parent_starting_point[0]+adding_value*int(index/k), parent_starting_point[1]+adding_value*int(index%k))

    return tree

def map_child_deg(node, tree):
    '''
    return sum of direct children nodes' degree (tag)
    '''
    if node.is_leaf():
        return str(int(node.tag))

    children = get_children_identifier(node, tree)
    child_deg = sum([int(tree[child].tag > 0) for child in children])

    return str(child_deg)

def map_all_child_deg(node, tree):
    '''
    return sum of all children nodes' degree (tag)
    '''
    if node.is_leaf():
        return str(int(node.tag))

    children = get_children_identifier(node, tree)
    child_deg = sum([int(tree[child].tag) for child in children])

    return str(child_deg)

def tree_to_bfs_string(tree, string_type='bfs'):
    bfs_node_list = [tree[node] for node in tree.expand_tree(mode=tree.WIDTH,
                                                             key=lambda x: (int(x.identifier.split('-')[0]), int(x.identifier.split('-')[1])))][1:]
    if string_type in ['bfs', 'group', 'bfs-tri', 'group-red', 'group-red-3']:
        bfs_value_list = [str(int(node.tag)) for node in bfs_node_list]
    elif string_type in ['bfs-deg', 'bfs-deg-group']:
        bfs_value_list = [map_child_deg(node, tree) for node in bfs_node_list]

    return ''.join(bfs_value_list)

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(fillvalue=fillvalue, *args)

def bfs_string_to_tree(string, is_zinc=False, k=2):
    k_square = k**2
    tree = Tree()
    tree.create_node("root", "0")
    parent_node = tree["0"]
    node_deque = deque([])
    if is_zinc:
        node_groups = grouper_mol(string)
    else:
        node_groups = grouper(k_square, string)
    for node_1, node_2, node_3, node_4 in node_groups:
        parent_level = get_level(parent_node)
        cur_level_max = max([get_location(node) for node in tree.nodes.values() if get_level(node) == parent_level+1], default=0)
        for i, node_tag in enumerate([node_1, node_2, node_3, node_4], 1):
            if node_tag == None:
                break
            new_node = Node(tag=node_tag, identifier=f"{parent_level+1}-{cur_level_max+i}")
            tree.add_node(new_node, parent=parent_node)
            node_deque.append(new_node)
        parent_node = node_deque.popleft()
        while(parent_node.tag == '0'):
            if len(node_deque) == 0:
                return tree
            parent_node = node_deque.popleft()
    return tree

def clean_string(string):

    if "[pad]" in string:
        string = string[:string.index("[pad]")]

    return string

def train_val_test_split(
    data: list,
    data_name='GDSS_com',
    train_size: float = 0.7, val_size: float = 0.1, test_size: float = 0.2,
    seed: int = 42,
):
    if data_name in ['qm9', 'zinc']:
        # code adpated from https://github.com/harryjo97/GDSS
        with open(os.path.join(DATA_DIR, f'{data_name}/valid_idx_{data_name}.json')) as f:
            test_idx = json.load(f)
        if data_name == 'qm9':
            test_idx = test_idx['valid_idxs']
        test_idx = [int(i) for i in test_idx]
        train_idx = [i for i in range(len(data)) if i not in test_idx]
        test = [data[i] for i in test_idx]
        train_val = [data[i] for i in train_idx]
        train, val = train_test_split(train_val, train_size=train_size / (train_size + val_size), random_state=seed, shuffle=True)
    elif data_name in ['planar', 'sbm', 'proteins']:
        # code adapted from https://github.com/KarolisMart/SPECTRE
        test_len = int(round(len(data)*0.2))
        train_len = int(round((len(data) - test_len)*0.8))
        val_len = len(data) - train_len - test_len
        train, val, test = random_split(data, [train_len, val_len, test_len], generator=torch.Generator().manual_seed(1234))
    else:
        train_val, test = train_test_split(data, train_size=train_size + val_size, shuffle=False)
        train, val = train_test_split(train_val, train_size=train_size / (train_size + val_size), random_state=seed, shuffle=True)
    return train, val, test

def adj_to_graph(adj, is_cuda=False):
    if is_cuda:
        adj = adj.detach().cpu().numpy()
    G = nx.from_numpy_matrix(adj)
    G.remove_edges_from(nx.selfloop_edges(G))
    G.remove_nodes_from(list(nx.isolates(G)))
    if G.number_of_nodes() < 1:
        G.add_node(1)
    return G

def map_tree_pe(tree):
    depth = tree.depth()
    k = get_k(tree)
    size = int(depth*(k**2))
    pe = torch.zeros((size))
    for node in tree.nodes.values():
        node.data = pe
        if not node.is_root():
            parent = get_parent(node, tree)
            branch = get_children_identifier(parent, tree).index(node.identifier)
            current_pe = torch.zeros(int(k**2))
            current_pe[branch] = 1
            pe = torch.cat((current_pe, parent.data[:int(size-k**2)]))
            node.data = pe
    return tree

def map_new_ordered_graph(ordered_graph):
    '''
    Map ordered_graph object to ordered networkx graph
    '''
    org_graph = ordered_graph.graph
    ordering = ordered_graph.ordering
    mapping = {i: ordering.index(i) for i in range(len(ordering))}
    new_graph = nx.relabel_nodes(org_graph, mapping)
    return new_graph

# for redundant removed strings

def generate_final_tree_red(tree, k=2):
    tree_with_iden = add_zero_to_identifier(tree)
    final_tree = add_symmetry_to_tree(tree_with_iden, k)

    return final_tree

def generate_initial_tree_red(string_token_list, k=2):
    node_groups = [tuple(grouper_mol(string, k)[0]) for string in string_token_list]
    tree = Tree()
    tree.create_node("root", "0-0-0")
    parent_node = tree["0-0-0"]
    node_deque = deque([])
    for nodes in node_groups:
        parent_level = get_level(parent_node)
        cur_level_max = max([get_location(node) for node in tree.nodes.values() if get_level(node) == parent_level+1], default=0)
        for i, node_tag in enumerate(nodes, 1):
            if node_tag == None:
                break
            new_node = Node(tag=node_tag, identifier=f"{parent_level+1}-{cur_level_max+i}")
            tree.add_node(new_node, parent=parent_node)
            node_deque.append(new_node)
        parent_node = node_deque.popleft()
        while(parent_node.tag == '0'):
            if len(node_deque) == 0:
                return tree
            parent_node = node_deque.popleft()

    return tree

def find_new_identifier(node_id, index, is_dup=1):
    split = node_id.split('-')
    # k = 2
    if index == 1:
        num = 1
        num *= is_dup
        cur_pre_identifier = split[0] + '-' + split[1]
    # k = 3
    elif index == 2:
        num = 2
        num *= is_dup
        cur_pre_identifier = split[0] + '-' + split[1]
    elif index == 4:
        num = 1
        num *= is_dup
        cur_pre_identifier = split[0] + '-' + str(int(split[1])-2)
    elif index == 5:
        num = 1
        num *= is_dup
        cur_pre_identifier = split[0] + '-' + str(int(split[1])-1)
    else:
        num = 2
        num *= is_dup
        cur_pre_identifier = split[0] + '-' + split[1]

    new_last_identifier = int(split[2])-num
    return cur_pre_identifier + '-' + str(new_last_identifier)

def get_child_index(k):
    indices = []
    c = 0
    for i in range(k+1):
        for j in range(1,i+1):
            c=c+1
            if j != i:
                indices.append(c)
    return indices

def add_symmetry_to_tree(tree, k):
    k_square = k**2
    bfs_node_list = [tree[node] for node in tree.expand_tree(mode=tree.WIDTH, key=lambda x: (int(x.identifier.split('-')[0]), int(x.identifier.split('-')[1])))]
    node_list = [node for node in bfs_node_list[::-1] if not node.is_leaf()]
    for node in node_list:
        child_nodes = get_children_identifier(node, tree)
        if len(child_nodes) < k_square:
            postfixes = get_child_index(k)

            for index in postfixes:
                copy_node = tree.get_node(child_nodes[int(index)-1])
                new_node = Node(tag=copy_node.tag, identifier=find_new_identifier(copy_node.identifier, index))
                subtree = Tree(tree.subtree(child_nodes[int(index)-1]), deep=True)
                new_tree = Tree(subtree, deep=True)
                if len(subtree) > 1:
                    for nid, n in sorted(subtree.nodes.items(), key=lambda x: (int(x[0].split('-')[0]), int(x[0].split('-')[1]), int(x[0].split('-')[2]))):
                        count_dup = len([key for key in subtree.nodes.keys()
                                        if (key.split('-')[0] == nid.split('-')[0]) and (key.split('-')[1] == nid.split('-')[1])])
                        org_dup = len([key for key in tree.nodes.keys()
                                        if (key.split('-')[0] == nid.split('-')[0]) and (key.split('-')[1] == nid.split('-')[1])])
                        new_iden = find_new_identifier(nid, index, (count_dup+org_dup)*100)
                        while (new_iden in tree):
                            new = int(new_iden.split('-')[2]) - 1
                            new_iden = new_iden.split('-')[0] + '-' + new_iden.split('-')[1] + '-' +  str(new)
                        new_tree.update_node(nid, identifier=new_iden)
                    tree.paste(node.identifier, new_tree)

                else:
                    tree.add_node(new_node, parent=node)

    return tree

def add_zero_to_identifier(tree):
    new_tree = Tree(tree, deep=True)
    for node in tree.nodes:
        new_identifier = node
        while (len(new_identifier.split('-'))<3):
            new_identifier = new_identifier + '-10000'
        new_tree.update_node(node, identifier=new_identifier)
    return new_tree

def fix_symmetry(adj):
    sym_adj = torch.tril(adj) + torch.tril(adj).T
    return torch.where(sym_adj>0, 1, 0)

def map_deg_string(string):
    new_string = []
    group_queue = deque(grouper(4, string))
    group_queue.popleft()
    for index, char in enumerate(string):
        if len(group_queue) == 0:
            left = string[index:]
            break
        if char == '0':
            new_string.append(char)
        else:
            new_string.append(str(sum([int(char) for char in group_queue.popleft()])))

    return ''.join(new_string) + left

def remove_redundant(input_string, is_mol=False, k=2):
    k_square = k**2
    string = input_string[0:k_square]
    pos_list = list(range(1, k_square+1))
    str_pos_queue = deque([(s, p) for s, p in zip(string, pos_list)])
    if is_mol:
        group_list = list(grouper_mol(input_string))
    else:
        group_list = list(grouper(k_square, input_string))
    for cur_string in [''.join(token) for token in group_list][1:]:
        cur_parent, cur_parent_pos = str_pos_queue.popleft()
        # if value is 0, it cannot be parent node -> skip
        while((cur_parent == '0') and (len(str_pos_queue) > 0)):
            cur_parent, cur_parent_pos = str_pos_queue.popleft()
        # i: order of the child node in the same parent
        cur_pos = [cur_parent_pos*10+i for i in range(1,k_square+1)]
        # pos_list: final position of each node
        pos_list.extend(cur_pos)
        if is_mol:
            str_pos_queue.extend([(s, c) for s, c in zip(grouper_mol(cur_string)[0], cur_pos)])
        else:
            str_pos_queue.extend([(s, c) for s, c in zip(cur_string, cur_pos)])

    pos_list = [str(pos) for pos in pos_list]
    # prefix: diagonal
    prefixes = [str((i-1)*k + i) for i in range(1,k+1)]
    # posfix: upper diagonal
    postfixes = []
    for i in range(1,k+1):
        for j in range(i+1, k+1):
            postfixes.append(str((i-1)*k+j))

    # find positions ends with 2 including only 1 and 4
    remove_pos_prefix_list = [pos for i, pos in enumerate(pos_list)
                                if (pos[-1] in postfixes) and len((set(pos[:-1]))-set(prefixes))==0]
    remain_pos_index = [not pos.startswith(tuple(remove_pos_prefix_list)) for pos in pos_list]
    remain_pos_list = [pos for pos in pos_list if not pos.startswith(tuple(remove_pos_prefix_list))]

    # find cutting points (one block)
    cut_list = [i for i, pos in  enumerate(remain_pos_list) if pos[-1] == str(k**2)]
    cut_list_2 = [0]
    cut_list_2.extend(cut_list[:-1])
    cut_size_list = [i - j for i, j in zip(cut_list , cut_list_2)]
    cut_size_list[0] += 1
    if is_mol:
        final_string_list = list(compress([item for sublist in grouper_mol(input_string) for item in sublist], remain_pos_index))
    else:
        final_string_list = list(compress([*input_string], remain_pos_index))

    pos_list_iter = iter(final_string_list)
    final_string_cut_list = [list(islice(pos_list_iter, i)) for i in cut_size_list]

    return [''.join(l) for l in final_string_cut_list]

def get_max_len(data_name, order='C-M', k=2):
    total_strings = []
    k_square = k**2
    for split in ['train', 'test', 'val']:
        string_path = os.path.join(DATA_DIR, f"{data_name}/{order}/{data_name}_str_{split}_{k}.txt")
        strings = Path(string_path).read_text(encoding="utf=8").splitlines()

        total_strings.extend(strings)

    red_list = [remove_redundant(string, is_mol=False, k=k) for string in total_strings]
    # red_strings = [''.join(red) for red in red_list]

    max_len = max([len(string) for string in total_strings])
    group_max_len = max_len / k_square
    red_max_len = max([len(string) for string in red_list])

    return max_len, group_max_len, red_max_len


'''
Stores core model's parameters:
(Bacteria)
P_BACT_DIVIDE - probability that bacteria will divide on two bacteria (both in the same cell) unless there are >= BACT_OVERCROWD bacteria in given cell
P_BACT_STAY - probability that bacteria will stand still (in case if it not divided)
BACT_OVERCROWD - number of maximum number of bacteria within BACT_OVERCROWD_RADIUS (if more or equal, bacteria will not divide)
BACT_OVERCROWD_RADIUS - ...
(Predator)
PR_INIT_ENERGY - initial predator's energy
PR_MAX_ENERGY - value of energy when predator stops hunting (until loose energy below this value)
PR_DIVIDE_ENERGY - minimal energy value at which predator's divide is possible. Offsprings will have (E-PR_DIVIDE_COST)//2 energy
PR_DIVIDE_COST - energy cost of predator's division
PR_TURN_COST - energy cost of each predator's turn (except division or feed)
PR_FEED_VALUE - energy gained by predator after successful hunting
PR_SIGHT - predator's sight range
P_PR_DIVIDE - probability of predator's division (if its energy>=PR_DIVIDE_ENERGY)
P_PR_STAY - probability that predator remain still if he is fed up (energy>=PR_MAX_ENERGY)
PR_OVERCROWD - number of maximum number of predators within PR_OVERCROWD_RADIUS (if more or equal, predator will not divide)
PR_OVERCROWD_RADIUS - ...
'''

from collections import namedtuple

from decimal import Decimal

ModelParams = namedtuple('ModelParams', ['P_BACT_DIVIDE',
                                        'P_BACT_STAY',
                                        'BACT_OVERCROWD',
                                        'BACT_OVERCROWD_RADIUS',
                                        'BACT_VELOCITY',
                                        'PR_INIT_ENERGY',
                                        'PR_MAX_ENERGY',
                                        'PR_DIVIDE_ENERGY',
                                        'PR_DIVIDE_COST',
                                        'PR_TURN_COST',
                                        'PR_FEED_VALUE',
                                        'PR_SIGHT',
                                        'P_PR_DIVIDE',
                                        'P_PR_STAY',
                                        'PR_OVERCROWD',
                                        'PR_OVERCROWD_RADIUS'])

def default_model_params():
    return ModelParams(
            P_BACT_DIVIDE=Decimal('0.5'),
            P_BACT_STAY=Decimal('0.05'),
            BACT_OVERCROWD=2,
            BACT_OVERCROWD_RADIUS=2,
            BACT_VELOCITY = 1,
            PR_INIT_ENERGY=100,
            PR_MAX_ENERGY=150,
            PR_DIVIDE_ENERGY=148,
            PR_DIVIDE_COST=0,
            PR_TURN_COST=10,
            PR_FEED_VALUE=80,
            PR_SIGHT=4,
            P_PR_DIVIDE=Decimal('0.2'),
            P_PR_STAY=Decimal('0.8'),
            PR_OVERCROWD=2,
            PR_OVERCROWD_RADIUS=6)

def load_model_params(configSection):
    '''
    Loads modelParams from given section of INI file (parsed with configparser.ConfigParser)
    '''
    return ModelParams(
            P_BACT_DIVIDE=Decimal(configSection['P_BACT_DIVIDE']),
            P_BACT_STAY=Decimal(configSection['P_BACT_DIVIDE']),
            BACT_OVERCROWD=configSection.getint('BACT_OVERCROWD'),
            BACT_OVERCROWD_RADIUS=configSection.getint('BACT_OVERCROWD_RADIUS'),
            BACT_VELOCITY=configSection.getint('BACT_VELOCITY'),
            PR_INIT_ENERGY=configSection.getint('PR_INIT_ENERGY'),
            PR_MAX_ENERGY=configSection.getint('PR_MAX_ENERGY'),
            PR_DIVIDE_ENERGY=configSection.getint('PR_DIVIDE_ENERGY'),
            PR_DIVIDE_COST=configSection.getint('PR_DIVIDE_COST'),
            PR_TURN_COST=configSection.getint('PR_TURN_COST'),
            PR_FEED_VALUE=configSection.getint('PR_FEED_VALUE'),
            PR_SIGHT=configSection.getint('PR_SIGHT'),
            P_PR_DIVIDE=Decimal(configSection['P_PR_DIVIDE']),
            P_PR_STAY=Decimal(configSection['P_PR_STAY']),
            PR_OVERCROWD=configSection.getint('PR_OVERCROWD'),
            PR_OVERCROWD_RADIUS=configSection.getint('PR_OVERCROWD_RADIUS'))


import threading
import transaction

from dobbin.exc import InvalidObjectReference
from dobbin.exc import WriteConflictError
from dobbin.exc import ReadConflictError
from dobbin.exc import ConflictError
from dobbin.persistent import checkout
from dobbin.persistent import Broken
from dobbin.persistent import Persistent
from dobbin.persistent import sync

ROOT_OID = 0

setattr = object.__setattr__

class Manager(object):
    """Transactional object manager.

    This class implements a two-phase transactional object manager.

    Subclasses must implement:

    -new_oid(obj)
    -read(jar, timestamp)
    -write(obj)

    Subclasses can implement:

    -tpc_begin
    -tpc_vote
    -tpc_abort
    -tpc_finish

    """

    tx_ref = None
    tx_count = 0
    tx_timestamp = None

    def __init__(self):
        # define reentrant thread-lock
        l = threading.RLock()
        self.lock_acquire = l.acquire
        self.lock_release = l.release

        # persistent-id to object mapping
        self._oid2obj = {}

        # initialize thread-local state
        self._thread = ThreadState()

        # load objects from storage
        self._sync()

    def __deepcopy__(self, memo):
        return self

    def __len__(self):
        return len(self._oid2obj)

    def __repr__(self):
        return '<%s size="%d">' % (type(self).__name__, len(self))

    @property
    def root(self):
        if self._thread.timestamp is None:
            transaction.manager.registerSynch(self)
            tx = transaction.manager.get()
            self.newTransaction(tx)
        return self.get(ROOT_OID)

    def abort(self, transaction):
        """Abort changes."""

        self._revert(self._thread.modified)
        self._revert(self._thread.committed)

    def add(self, obj):
        """Add an object to the database.

        Note that the recommended way to add objects is through the
        root object graph.
        """

        if obj._p_jar is None:
            obj._p_jar = self
        elif obj._p_jar is self:
            raise RuntimeError("Object already added to the database.")
        else:
            raise InvalidObjectReference(obj)

        checkout(obj)

    def afterCompletion(self, transaction):
        pass

    def beforeCompletion(self, transaction):
        pass

    def commit(self, transaction):
        """Commit changes to disk."""

        committed = self._thread.committed
        modified = self._thread.modified
        timestamp = self._thread.timestamp

        # update transaction timestamp
        self._thread.timestamp = sync.timestamp

        while modified:
            for obj in tuple(modified):
                # assert that object belongs to this database
                if obj._p_jar is not self:
                    raise InvalidObjectReference(obj)

                # if the object has been updated since we begun our
                # transaction, it's a write-conflict.
                if obj._p_serial is not None and obj._p_serial > timestamp:
                    try:
                        state = self._resolve(obj)
                    except ConflictError:
                        raise WriteConflictError(obj)
                else:
                    state = obj.__getstate__()

                # make sure the object has an oid
                oid = obj._p_oid
                if oid is None:
                    oid = self.new_oid(obj)

                self.write(oid, obj._p_class, state)
                committed.append((obj, state))
                modified.remove(obj)

        # update database timestamp
        self.tx_timestamp = self._thread.timestamp

    def get(self, oid, cls=None):
        obj = self._oid2obj.get(oid)
        if obj is None and cls is not None:
            obj = Broken(oid, cls)
            self._oid2obj[oid] = obj
        return obj

    def elect(self, obj):
        """Elect object as database root."""

        if not isinstance(obj, Persistent):
            raise TypeError(
                "Can't set non-persistent object as database root.")

        if obj._p_oid is not None:
            raise ValueError("Can't elect already persisted object.")

        if self.root is not None:
            raise RuntimeError("This database already has a root object.")

        obj._p_oid = ROOT_OID
        self.add(obj)

    def newTransaction(self, transaction):
        """New transaction."""

        self._sync()

    def save(self, obj):
        return self._register(obj)

    def snapshot(self, database, timestamp=None):
        """Return database snapshot."""

        # restore snapshot from database
        for record in self._read(database, end=timestamp):
            pass

        # write snapshot to storage
        tx = transaction.Transaction()
        tx.join(database)
        tx.commit()

    def sortKey(self):
        """Sort-key.

        This method is required by the transaction machinery; the key
        returned guarantees that the first thread to check out an
        object wins the transaction.
        """

        return id(self), self._thread.timestamp

    def tpc_abort(self, transaction):
        """Abort transaction.

        Called when an exception occurred during ``tpc_vote`` or
        ``tpc_finish``.
        """

        self._tpc_cleanup()

    def tpc_begin(self, transaction):
        """Begin commit (two-phase) of a transaction."""

        # catch up on transactions; other processes may have committed
        # transactions which may conflict
        self._sync()

    def tpc_vote(self, transaction):
        """Vote on transaction."""

    def tpc_finish(self, transaction):
        """Indicate confirmation that the transaction is done."""

        state = self._thread
        oid2obj = self._oid2obj
        timestamp = self._thread.timestamp
        committed = self._thread.committed

        while committed:
            obj, state = committed.pop()
            oid2obj[obj._p_oid] = obj
            obj.__setstate__(state)
            obj._p_serial = timestamp

        self._tpc_cleanup()

    def _register(self, obj):
        if self._thread.needs_to_join:
            transaction.get().join(self)
            self._thread.needs_to_join = False
            self._thread.timestamp = sync.timestamp

        modified = self._thread.modified
        if obj not in modified:
            modified.add(obj)

    def _read(self, jar, start=None, end=None):
        conflicts = set()

        for record, objects in self.read(jar, start):
            timestamp = record.timestamp
            if end and timestamp > end:
                break

            for oid, cls, state in objects:
                obj = jar.get(oid, cls)

                if obj in self._thread.modified:
                    # if our version of the object is persistent-local
                    # then we have a write conflict; it may be
                    # resolved, if the object provides a conflict
                    # resolution method; it gets called with three
                    # arguments: (old_state, saved_state, new_state).
                    try:
                        state = self._resolve(obj, new_state=state)
                    except ConflictError:
                        conflicts.add(obj)
                else:
                    setattr(obj, "__class__", cls)

                # update timestamp
                setattr(obj, '_p_serial', timestamp)

                # associate with this database
                setattr(obj, '_p_jar', jar)

                # set shared state
                obj.__setstate__(state)

            yield record

        if conflicts:
            raise ReadConflictError(*conflicts)

    def _resolve(self, obj, new_state=None):
        self.lock_acquire()
        try:
            if obj._p_resolve_conflict is None:
                raise ConflictError(obj)
            if new_state is None:
                new_state = obj.__getstate__()
            return obj._p_resolve_conflict(
                obj.__oldstate__(),
                super(type(obj), obj).__getstate__(),
                new_state
                )
        finally:
            self.lock_release()

    def _revert(self, objects):
        while objects:
            obj = objects.pop()
            obj.__setstate__()

    def _sync(self):
        for record in self._read(self, self.tx_timestamp):
            self.tx_count += 1
            self.tx_timestamp = record.timestamp

    def _tpc_cleanup(self):
        """Performs cleanup operations to support ``tpc_finish`` and
        ``tpc_abort``."""

        self._thread.needs_to_join = True
        self.tx_count += 1

class ThreadState(threading.local):
    """Thread-local database state."""

    needs_to_join = True
    timestamp = None

    def __init__(self):
        self.modified = set()
        self.committed = []


from flask import jsonify, request
from app.models import TaskModel
from flask import current_app
from sqlalchemy.orm.exc import UnmappedInstanceError
from flask_cors import  cross_origin

@cross_origin()
def create_task_controller():
    data = request.get_json()
    session = current_app.db.session
    new_data = TaskModel(**data)
    session.add(new_data)
    session.commit()

    return jsonify(new_data), 201

@cross_origin()
def get_task_controller():
   all_tasks = TaskModel.query.all()
   return jsonify(all_tasks)

@cross_origin()
def patch_task_controller(id):
    try:
        task = TaskModel.query.get(id)
        data = request.get_json()
        session = current_app.db.session

        for key, value in data.items():
             setattr(task, key, value)

        session.add(task)
        session.commit()

        return jsonify(task), 201
    except AttributeError:
        return {"Error": "Task not found"}, 404

@cross_origin()
def delete_task_controller(id):
    try:
        task = TaskModel.query.get(id)

        session = current_app.db.session

        session.delete(task)
        session.commit()
        return "", 204

    except UnmappedInstanceError:
        return {"Error": "Task not found"}, 404


# Author: Alice Knag
# Recitation: CSCI 1300-210 X. Zhang
#
# Assignment 9
# assignment9.py

#basic math. rates is a list, pop is an int.
def compute_census(rates, pop):
    secondsInYear = 86400*365
    bornInYear = secondsInYear / rates[0]
    deathsInYear = secondsInYear / rates[1]
    immigrantsInYear = secondsInYear / rates[2]
    return (pop + bornInYear + immigrantsInYear - deathsInYear)

def convert_seconds():
    sec = input("Enter the amount of seconds you want to convert? ")
    sec = int(sec)
    print
    days = sec / 60 / 60 / 24
    hours = sec / 60 / 60 % 24
    minutes = sec / 60 % 60
    seconds = sec % 60
    print("%s corresponds to: %s days, %s hours,"
          " %s minutes, %s seconds." % (sec, days, hours, minutes, seconds))
          # linebreak for PEP8 line size requirements

#this works with any size list, as long as it ends with a string and not a prompt string. Passes cog.
def generate_story(l):
    inputs = []
    strings = []
    string = ""
    for index, item in enumerate(l):
        if(index % 2):
            inputs.append(raw_input(item))
        else:
            strings.append(item)
    for index, s in enumerate(strings):
        try:
            string += s + " " + inputs[index] + " "
        except:
            string += s + "."
    return string

#uses zip to iterate through vaues of each sequence (strings), then if they're not equal, it returns true, and adds 1 to it. As it loops through, the sum gets added as difference increases.
def similarity_score(seq1, seq2):
    if not len(seq1) == len(seq2):
        return 0
    l = len(seq1)
    dist = sum(c1 != c2 for c1, c2 in zip(seq1, seq2))
    return float(float(l - dist)/l)

#it iterates through possible positions of the sequence on the genome, if the score is greater than the best, the index is recorded and later returned.
def best_match(genome, seq):
    bestScore = 0.0
    bestIndex = 0
    for index, s in enumerate(genome):
        score = similarity_score(genome[index:index+len(seq)], seq)
        if(score > bestScore):
            bestScore = score
            bestIndex = index
    return bestIndex

#finds the median with this logic, the average is sum/length
def calc_stats(l):
    l.sort()
    ll = len(l)
    if not ll % 2:
        return [(sum(l)/float(ll)), ((l[ll / 2] + l[ll / 2 - 1]) / 2.0)]
    return [(sum(l)/float(ll)), l[ll / 2]]

#it loops through each line, strips out the endline, then strips commas, then it strips spaces for the text to the right of the comma.
#then creates the nested list with append.
def parse_ratings(filename):
    l = []
    for line in open(filename):
        line.rstrip('\n')
        s = [x.strip() for x in line.split(',')]
        i = [int(x.strip()) for x in s[1].split(' ')]
        l.append([s[0], i])
    return l

#test functions
def main():
    rates = [8, 12, 33]
    print(compute_census(rates, 10000000))
    convert_seconds()
    list_to_story = ["I went skiing to", "Enter a location: ",
                     "it was really crowded and I stayed in line for",
                     "Enter number of hours: ", "hours"]
    print(generate_story(list_to_story))
    print("sscore: " + str(similarity_score("CCGCCGCCGA", "CCTCCTCCTA")))
    print("bestMatch: " + str(best_match("yyyxxxyyy", "xxx")))
    l = [1, 2.5, 3, 8, 10.5, 5]
    print("calc_stats: mean: " + str(calc_stats(l)[0]) +
          " | median: " + str(calc_stats(l)[1]))
    print(parse_ratings("ratings.txt"))

if __name__ == '__main__':
    main()


import sys
from collections import deque

fast_input = sys.stdin.readline

def app() -> None:
    N: int = int(fast_input())
    M: int = int(fast_input())

    computer: dict[int : list[int]] = dict()
    for _ in range(M):
        src, dist = list(map(int, input().split()))

        if src in computer.keys():
            computer[src].append(dist)
        else:
            computer[src] = [dist]

        if dist in computer.keys():
            computer[dist].append(src)
        else:
            computer[dist] = [src]

    queue: deque = deque([1])
    visited: list[int] = [1]
    while queue:
        target: int = queue.popleft()

        for next_computer in computer[target]:
            if next_computer not in visited:
                queue.append(next_computer)
                visited.append(next_computer)

    print(len(visited) - 1)

if __name__ == "__main__":
    app()


import time
import requests
import re

def get_code_from_nada(email: str):
    if any(['@dropjar.com' in email, '@inboxbear.com' in email, '@tafmail.com' in email]):
        url = f"https://getnada.com/api/v1/inboxes/{email}"
        response = requests.get(url).json()
        try:
            subject = response['msgs'][0]['s']
            if subject == 'Proton Verification Code':
                uid = response['msgs'][0]['uid']
                code = re.search(r'\d{4,10}', requests.get(f"https://getnada.com/api/v1/messages/html/{uid}")
                                 .text.split('\n')[2])
                code = code.group() if code else code
        except:
            return None
    return code

def get_code_by_many_tries(email, tries=5, time_to_sleep=5):
    for i in range(tries):
        print(f"Try {i+1}")
        code = get_code_from_nada(email)
        if code:
            print('Code found!')
            return code
        else:
            print('Code not found.. ')
        time.sleep(time_to_sleep)


"""
Usage: train.py MODEL_DIR NODE_NAMES ...

Arguments:
    MODEL_DIR   path to tensorflow checkpoint
    NODE_NAMES  list of nodes to export from graph

Based on: https://blog.metaflow.fr/tensorflow-how-to-freeze-a-model-and-serve-it-with-a-python-api-d4f3596b3adc
"""
import os
import logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',)

import tensorflow as tf

from typeopt import Arguments

def freeze_graph(model_dir, node_names):
    '''
    Extracts the sub-graph defined by the nodes and converts
    all its variables into constants
    '''
    logger = logging.getLogger(__name__)

    if not tf.gfile.Exists(model_dir):
        raise AssertionError(
            "Export directory doesn't exists. Please specify an export directory: %s" %
            model_dir)

    if not node_names:
        logger.warning("You need to supply the name of a node")
        return

    checkpoint = tf.train.get_checkpoint_state(model_dir)
    input_checkpoint = checkpoint.model_checkpoint_path

    # We precise the file fullname of our freezed graph
    output_graph = os.path.join(os.path.dirname(model_dir), "frozen_model.pb")

    # We clear devices to allow TensorFlow to control on which device it will
    # load operations
    clear_devices = True

    # We start a session using a temporaty fresh Graph
    with tf.Session(graph=tf.Graph()) as sess:
        # We import the meta graph in the current default Graph
        saver = tf.train.import_meta_graph(
            "%s.meta" % input_checkpoint, clear_devices=True)

        # Restore the weights
        saver.restore(sess, input_checkpoint)

        # use built-in TF helper to export variables to constants
        output_graph_def = tf.graph_util.convert_variables_to_constants(
            sess,                                   # session is used to retrieve the weights
            tf.get_default_graph().as_graph_def(),  # The graph_def is used to retrieve the nodes
            node_names,                             # The nodes are used to select the subgraphs nodes
            variable_names_blacklist=['global_step'])

        # Serialize and dump the output subgraph to the filesystem
        with tf.gfile.GFile(output_graph, 'wb') as f:
            f.write(output_graph_def.SerializeToString())

        logger.info("%d ops in the source graph." %
                    len(tf.get_default_graph().get_operations()))
        logger.info("%d ops in the final graph." % len(output_graph_def.node))

if __name__ == '__main__':
    args = Arguments(__doc__, version='text')
    freeze_graph(args.model_dir, args.node_names)


import pickle

import numpy as np
import pandas as pd

from .... import opcodes as OperandDef
from ....core import recursive_tile
from ....serialization.serializables import KeyField, BytesField, DictField, FieldTypes
from ....dataframe.core import SERIES_CHUNK_TYPE, DATAFRAME_CHUNK_TYPE
from ....dataframe.utils import parse_index
from ....tensor.core import TENSOR_TYPE, TensorOrder
from ....utils import has_unknown_shape, ensure_own_data
from ...operands import LearnOperand, LearnOperandMixin, OutputType
from .dmatrix import ToDMatrix, check_data

class XGBPredict(LearnOperand, LearnOperandMixin):
    _op_type_ = OperandDef.XGBOOST_PREDICT

    data = KeyField("data", default=None)
    model = BytesField(
        "model", on_serialize=pickle.dumps, on_deserialize=pickle.loads, default=None
    )
    kwargs = DictField("kwargs", key_type=FieldTypes.string, default_factory=dict)

    def __init__(self, output_types=None, gpu=None, **kw):
        super().__init__(_output_types=output_types, gpu=gpu, **kw)

    def _set_inputs(self, inputs):
        super()._set_inputs(inputs)
        self.data = self._inputs[0]

    def __call__(self):
        num_class = self.model.attr("num_class")
        if num_class is not None:
            num_class = int(num_class)
        if num_class is not None:
            shape = (self.data.shape[0], num_class)
        else:
            shape = (self.data.shape[0],)
        inputs = [self.data]
        if self.output_types[0] == OutputType.tensor:
            # tensor
            return self.new_tileable(
                inputs,
                shape=shape,
                dtype=np.dtype(np.float32),
                order=TensorOrder.C_ORDER,
            )
        elif self.output_types[0] == OutputType.dataframe:
            # dataframe
            dtypes = pd.DataFrame(np.random.rand(0, num_class), dtype=np.float32).dtypes
            return self.new_tileable(
                inputs,
                shape=shape,
                dtypes=dtypes,
                columns_value=parse_index(dtypes.index),
                index_value=self.data.index_value,
            )
        else:
            # series
            return self.new_tileable(
                inputs,
                shape=shape,
                index_value=self.data.index_value,
                name="predictions",
                dtype=np.dtype(np.float32),
            )

    @classmethod
    def tile(cls, op: "XGBPredict"):
        out = op.outputs[0]
        out_chunks = []
        data = op.data
        if data.chunk_shape[1] > 1:
            if has_unknown_shape(op.data):
                yield
            data = yield from recursive_tile(data.rechunk({1: op.data.shape[1]}))
        for in_chunk in data.chunks:
            chunk_op = op.copy().reset_key()
            chunk_index = (in_chunk.index[0],)
            if op.model.attr("num_class"):
                chunk_shape = (in_chunk.shape[0], int(op.model.attr("num_class")))
                chunk_index += (0,)
            else:
                chunk_shape = (in_chunk.shape[0],)
            if op.output_types[0] == OutputType.tensor:
                out_chunk = chunk_op.new_chunk(
                    [in_chunk],
                    shape=chunk_shape,
                    dtype=out.dtype,
                    order=out.order,
                    index=chunk_index,
                )
            elif op.output_types[0] == OutputType.dataframe:
                # dataframe chunk
                out_chunk = chunk_op.new_chunk(
                    [in_chunk],
                    shape=chunk_shape,
                    dtypes=data.dtypes,
                    columns_value=data.columns_value,
                    index_value=in_chunk.index_value,
                    index=chunk_index,
                )
            else:
                # series chunk
                out_chunk = chunk_op.new_chunk(
                    [in_chunk],
                    shape=chunk_shape,
                    dtype=out.dtype,
                    index_value=in_chunk.index_value,
                    name=out.name,
                    index=chunk_index,
                )
            out_chunks.append(out_chunk)

        new_op = op.copy()
        params = out.params
        params["chunks"] = out_chunks
        nsplits = (data.nsplits[0],)
        if out.ndim > 1:
            nsplits += ((out.shape[1],),)
        params["nsplits"] = nsplits
        return new_op.new_tileables(op.inputs, kws=[params])

    @classmethod
    def execute(cls, ctx, op: "XGBPredict"):
        from xgboost import DMatrix

        raw_data = data = ctx[op.data.key]
        if isinstance(data, tuple):
            data = ToDMatrix.get_xgb_dmatrix(ensure_own_data(data))
        else:
            data = data.spmatrix if hasattr(data, "spmatrix") else data
            data = DMatrix(data)

        # do not pass arguments that are None
        kwargs = dict((k, v) for k, v in op.kwargs.items() if v is not None)
        result = op.model.predict(data, **kwargs)

        if isinstance(op.outputs[0], DATAFRAME_CHUNK_TYPE):
            result = pd.DataFrame(result, index=raw_data.index)
        elif isinstance(op.outputs[0], SERIES_CHUNK_TYPE):
            result = pd.Series(result, index=raw_data.index, name="predictions")

        ctx[op.outputs[0].key] = result

def predict(
    model,
    data,
    output_margin=False,
    ntree_limit=None,
    validate_features=True,
    base_margin=None,
    session=None,
    run_kwargs=None,
    run=True,
):
    import xgboost

    data = check_data(data)
    if not isinstance(model, xgboost.Booster):
        raise TypeError(f"model has to be a xgboost.Booster, got {type(model)} instead")

    num_class = model.attr("num_class")
    if isinstance(data, TENSOR_TYPE):
        output_types = [OutputType.tensor]
    elif num_class is not None:
        output_types = [OutputType.dataframe]
    else:
        output_types = [OutputType.series]

    kwargs = {
        "output_margin": output_margin,
        "ntree_limit": ntree_limit,
        "validate_features": validate_features,
        "base_margin": base_margin,
    }
    op = XGBPredict(
        data=data,
        model=model,
        kwargs=kwargs,
        gpu=data.op.gpu,
        output_types=output_types,
    )
    result = op()
    if run:
        result.execute(session=session, **(run_kwargs or dict()))
    return result


from operator import index
from PyQt5.QtWidgets import QMainWindow, QApplication, QComboBox, QLabel
from PyQt5 import uic
import sys

class UI(QMainWindow):
    def __init__(self):
        super(UI, self).__init__()

        ##load ui file
        uic.loadUi("Window.ui", self)

        #define our widgets
        self.combo1 = self.findChild(QComboBox ,"comboBox")
        self.combo2 = self.findChild(QComboBox ,"comboBox_2")
        self.label = self.findChild(QLabel ,"label")

        #Add items to combobox
        self.combo1.addItem("male",["john", "wes", "Dan"])
        self.combo1.addItem("female", ["April", "steph", "Beth"])

        #Click the 1st opert
        self.combo1.activated.connect(self.clicker)

        ##show app
        self.show()

    def clicker(self, index):
            #clear second box
            self.combo2.clear()
            #Do the dependence
            self.combo2.addItems(self.combo1.itemData(index))

    def clicker2(self):
        self.label.setText(f'you picked: {self.combo2.currentText()} - {self.combo1.currentText()}')

##initialise app
app = QApplication(sys.argv)
UIWiWindow = UI()
app.exec_()


import sys
#
import csv
import itertools as it
import numpy as np

import pandas as pd

from keras.datasets import mnist
from keras.layers import Input, Dense, Reshape, Flatten, Dropout, multiply
from keras.layers import BatchNormalization, Activation, Embedding
from keras.layers import concatenate, ReLU, ZeroPadding2D
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import UpSampling2D, Conv2D
from keras.models import Sequential, Model
# from keras.optimizers import Adam # the Keras version of Adam causes a error
# from tensorflow.keras.optimizers import Adam

import matplotlib.pyplot as plt

import numpy as np
from keras import utils
from keras.utils import to_categorical

import math

from utilities_v2 import Tokenizer, train_model, eval_model

from keras.preprocessing.sequence import pad_sequences

np.random.seed(0)

def get_topic(number):
    if not math.isnan(number):
        return int(number)

def load_data(file_name):
    data = pd.read_csv(file_name, sep='\t', names=["url", "title", "text", "topic1", "topic2", "topic3", "topic4",
                                                   "topic5", "topic6", "topic7", "topic8", "topic9", "topic10"])
    all_texts1 = list(data['text'])
    all_topics = []
    all_texts = []
    for i in range(len(all_texts1)):
        if len(str(all_texts1[i])) > 10:
            article_topics = []
            for j in topic_numbers:
                try:
                    article_topics.append(int(data[j][i]))
                except:
                    pass
            all_texts.append(str(all_texts1[i]))
            all_topics.append(article_topics)
    return all_texts, all_topics

def create_one_hot(item, num_items):
    one_hot = np.zeros(num_items)
    for thing in item:
        one_hot[int(thing)] += 1
    return one_hot

if __name__ == "__main__":

    # Code to load in TOPIC_TRAINING_DATA corpus
    # -----------------------------------------------------------------------------------------------------
    print("Starting to load in data")
    topic_numbers = ["topic1", "topic2", "topic3", "topic4", "topic5", "topic6", "topic7", "topic8", "topic9",
                     "topic10"]

    years = ['2019']  # , '2018']
    news_sources = ['cnn']  # ['atlantic', 'blaze', 'breitbart', 'businessinsider', 'buzzfeed', 'cbs', 'cnbc', 'cnn',
    # 'dailycaller', 'dailynews', 'foxnews', 'guardian', 'huffpo', 'latimes', 'nbc', 'newmax',
    # 'newyorker', 'politico', 'reuters', 'slate', 'time', 'usatoday', 'vox', 'wapo',
    # 'wsj', 'wsjblogs', 'yahoonews']
    texts = []
    topics = []

    for year in years:
        for source in news_sources:
            new_texts, new_topics = load_data('tagtraining' + year + source + '.tsv')
            # new_texts, new_topics = load_data('~/DATA1/DIANBO/TOPIC_TRAINING_DATA/tagtraining' + year + source + '.tsv')
            texts += new_texts
            topics += new_topics

    texts = np.array(texts)
    topics = np.array(topics)

    # Shuffle the data
    permutation = np.random.permutation(len(texts))
    texts = texts[permutation]
    topics = topics[permutation]

    num_examples = len(texts)
    val_index = (7 * num_examples) // 8

    # val_index = 100  # DELETE AFTER TESTING
    # num_examples = 150  # DELETE AFTER TESTING

    train_texts = texts[0:val_index]
    train_labels = topics[0:val_index]

    test_texts = texts[val_index:num_examples]
    test_labels = topics[val_index:num_examples]

    num_topics = 600
    print("Loaded in data")
    # -----------------------------------------------------------------------------------------------------

    corpus = train_texts

    embed_dim = 500
    context_size = 5
    hidden_size = 64
    learning_rate = 0.001
    n_epochs = 3
    n_batch = 500

    max_length = 25000

    # step1: train word2vec embedding

    print("Tokenizing Data")

    tokenizer = Tokenizer()
    tokenizer.build_tokenizer(corpus)

    vocab_size = len(tokenizer.vocabulary)

    tokenized_corpus = tokenizer.tokenize(corpus)

    word_to_token = tokenizer.get_word_to_token()
    word_to_token.pop(',', None)
    w = csv.writer(open("updated/tokenizer.csv", "w"))
    for key, val in word_to_token.items():
        w.writerow([key, val])

    # step 2 train topic classification model

    Tokenized_X_train = tokenized_corpus
    # one_hot_x_train = []
    # for tokenized_text in Tokenized_X_train:
    #     one_hot_x_train.append(create_one_hot(tokenized_text, vocab_size))
    # Tokenized_X_train = vectorize_aggregate(Tokenized_X_train, reps_word2vec)
    lengths = [len(i) for i in Tokenized_X_train]
    # max_length = max(lengths)
    # print(max_length)
    Tokenized_X_train = pad_sequences(Tokenized_X_train, maxlen=max_length, padding='post')

    Y_train = []
    for point in train_labels:
        Y_train.append(create_one_hot(point, num_topics))
    Y_train = np.array(Y_train)

    Tokenized_X_test = tokenizer.tokenize(test_texts)
    # one_hot_x_test = []
    # for tokenized_text in Tokenized_X_test:
    #     one_hot_x_test.append(create_one_hot(tokenized_text, vocab_size))
    # Tokenized_X_test = vectorize_aggregate(Tokenized_X_test, reps_word2vec)
    Tokenized_X_test = pad_sequences(Tokenized_X_test, maxlen=max_length, padding='post')

    Y_test = []
    for point in test_labels:
        Y_test.append(create_one_hot(point, num_topics))
    Y_test = np.array(Y_test)

    name = "w2v"

    print(f"{name} features, {Tokenized_X_train.shape[0]} examples")

    print("Starting classifier training")
    model = train_model(Tokenized_X_train, Y_train, vocab_size, max_length, n_batch=250, n_epochs=6)

    model.save("updated/topic_classifier.h5")

    ACC = eval_model(model, Tokenized_X_test, Y_test)


"""
Parameter handling from CLI
"""

# Python standard library
import argparse
import yaml
import importlib

class Arbutus:
    def __init__(self, cli_path=None, arguments=None):
        self.main_branch = argparse.ArgumentParser(arguments)
        self.parsed_args = {}
        self.breadcrumbs = ''
        self.parameters = {}

    def parse_args(self) -> dict:
        self.parsed_args = vars(self.main_branch.parse_args())
        self.__process_args__()
        return self.parsed_args

    def get_branch(self, branch_name: str) -> argparse.ArgumentParser:
        return self.__dict__[branch_name + '_branch']

    def add_branch(self, branch_name: str, node_name: str = 'main', help_text: str = None) -> argparse.ArgumentParser:
        if not self.__dict__.get(node_name + '_node'):
            self.__dict__[node_name + '_node'] = self.__dict__[node_name + '_branch'].add_subparsers(dest=node_name)
        self.__dict__[branch_name + '_branch'] = \
            self.__dict__[node_name + '_node'].add_parser(branch_name, help=help_text)
        return self.__dict__[branch_name + '_branch']

    def add_argument(self, branch: argparse.ArgumentParser, argument_name: str, **kwargs):
        if 'type' in kwargs and kwargs['type'] in ['int', 'str', 'float']:
            kwargs['type'] = eval(kwargs['type'])
        if 'action' in kwargs:
            if type(kwargs['action']) is dict:
                try:
                    module = importlib.import_module(f"{kwargs['action']['source']}")
                    kwargs['action'] = eval(f"module.{kwargs['action']['name']}")
                except KeyError:
                    raise
            elif type(kwargs['action']) is str:
                if kwargs['action'] not in ['store', 'store_const', 'store_true', 'append', 'append_const', 'count',
                                            'help', 'version']:
                    raise KeyError
            else:
                raise TypeError
        if 'optional' in kwargs and kwargs['optional'] == True:
            argument_name = '--' + argument_name
            print(argument_name)
            kwargs.pop('optional')
        branch.add_argument(argument_name, **kwargs)

    @staticmethod
    def new_action(method):
        class NewAction(argparse.Action):
            def __call__(self, parser, namespace, values, option_string=None):
                method(parser=parser, namespace=namespace, values=values, option_string=option_string)
                setattr(namespace, self.dest, values)
        return NewAction

    def __process_args__(self) -> None:
        all_args = list(self.parsed_args.keys())
        self.breadcrumbs = '{}.{}'.format(all_args[0], all_args[1])
        for x in all_args:
            if self.parsed_args[x] in all_args:
                self.breadcrumbs += '.' + self.parsed_args[self.parsed_args[x]]
            elif x in self.breadcrumbs:
                pass
            else:
                self.parameters[x] = self.parsed_args[x]

    def from_dict(self, dict_: dict):
        for key, value in dict_.items():
            if 'branches' in value:
                for _key in value['branches']:
                    help_text = value['branches'][_key].get('help')
                    self.add_branch(_key, key, help_text)
                self.from_dict(value['branches'])
            elif 'arguments' in value:
                for _key in value['arguments']:
                    self.add_argument(self.get_branch(key), _key, **value['arguments'][_key])
            else:
                self.from_dict(value)

    def from_yaml(self, filename: str = './config/cli.yaml'):
        with open(filename, 'r') as yaml_file:
            yaml_as_dict = yaml.load(yaml_file, Loader=yaml.SafeLoader)
        self.from_dict(yaml_as_dict)


import numpy as np
import math
import cv2
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import logging

from .score_semantic import ScoreSemantic
from .chromaticChannels import composeChromaticMap

def scoreAnno (heatmap, srcimg, labels, target=[]):
	#print(f'heatmap:{heatmap.shape} srcimg{srcimg.shape}')

	labels_count = len(labels)
	#labels_count = min(labels_count, 4)

	jout = ScoreSemantic(heatmap, labels)
	#print(jout.dump_json())
	marks = jout.marks
	# print(f"jout.marks: {len(marks)}")
	clean_bgr = np.zeros_like(heatmap[0])

	if len(target) > 0:
		_, ax = plt.subplots(labels_count+2, 3)
	else:
		_, ax = plt.subplots(labels_count+2, 2)

	for i in range(labels_count):
		ax[i][1].imshow(clean_bgr)

		if marks[i].get('points') is not None:
			points = marks[i]['points']
			if len(points) > 0:
				ax[i][1].plot(points[:, 0], points[:, 1], 'g.')
		elif marks[i].get('vlines') is not None:
			lines = marks[i]['vlines']
			if len(lines) > 0:
				ax[i][1].vlines(lines[:, 0], lines[:, 1], lines[:, 2], color = 'g')
		elif marks[i].get('rectangles') is not None:
			rectangles = marks[i]['rectangles']
			if len(rectangles) > 0:
				for rect in rectangles:
					rc = patches.Rectangle((rect[0], rect[1]), rect[2], rect[3], linewidth=1, edgecolor='b', facecolor='g')
					ax[i][1].add_patch(rc)
		elif marks[i].get('boxes') is not None:
			boxes = marks[i]['boxes']
			if len(boxes) > 0:
				for box in boxes:
					#print('box:', box)
					angle = box[2] * math.pi / 180
					wcos = box[1][0] * math.cos(angle)
					wsin = box[1][0] * math.sin(angle)
					hcos = box[1][1] * math.cos(angle)
					hsin = box[1][1] * math.sin(angle)
					rx = wcos - hsin
					ry = wsin + hcos
					rc = patches.Rectangle((box[0][0] - rx / 2, box[0][1] - ry / 2), box[1][0], box[1][1], angle=box[2], linewidth=1, edgecolor='b', facecolor='g')
					ax[i][1].add_patch(rc)

		ax[i][1].set_ylabel(labels[i], fontsize='small', rotation='horizontal')
		ax[i][0].imshow(heatmap[i],cmap='jet')

		hm_max = np.max(heatmap[i])
		ax[i][0].set_ylabel(f'({hm_max})', fontsize='small', rotation='horizontal')

		if len(target) > 0:
			ax[i][2].imshow(target[...,i], cmap='jet')

	ax[labels_count][1].imshow(clean_bgr)

	all_points = [m.get('points') for m in marks if len(m.get('points', [])) > 0]
	if len(all_points) > 0:
		all_points = np.concatenate(all_points)
		print(f'all_points-{all_points.shape} heatmap-{heatmap.shape}')
		ax[labels_count][1].plot(all_points[:, 0], all_points[:,1], 'g.')

	ax[labels_count][1].set_ylabel('max', fontsize='small', rotation='horizontal')
	ax[labels_count][0].imshow(np.max(heatmap, axis=0), cmap='jet')
	if len(target) > 0:
		ax[labels_count][2].imshow(np.max(target, axis=-1), cmap='jet')
		ax[labels_count+1][2].imshow(srcimg, cmap='gray')

	ax[labels_count+1][1].set_ylabel('srcimg', fontsize='small', rotation='horizontal')
	ax[labels_count+1][1].imshow(srcimg, cmap='gray')
	#ax[labels_count+1][0].imshow(srcimg, cmap='gray')
	ax[labels_count+1][0].imshow(srcimg)
	plt.get_current_fig_manager().full_screen_toggle()
	plt.show()
	#plt.close()

def scoreAnnoChromatic (feature, targets, predictions=None):
	#print('scoreAnnoChromatic:', feature.shape, targets.shape, predictions.shape)
	with_pred = predictions is not None
	_, ax = plt.subplots(2, 2)

	colored_target = composeChromaticMap(targets)
	cv2.imwrite('./temp/feature.png', feature)
	cv2.imwrite('./temp/target.png', colored_target)

	#print('colored_target:', colored_target.shape, targets.dtype)
	ax[0][0].imshow(colored_target, cmap='gray')
	if with_pred:
		colored_pred = composeChromaticMap(predictions)
		ax[0][1].imshow(colored_pred)
		cv2.imwrite('./temp/pred.png', colored_pred)

	ax[1][0].imshow(feature)
	ax[1][1].set_ylabel('feature', rotation='vertical')
	ax[1][1].imshow(feature, cmap='gray')

	plt.get_current_fig_manager().full_screen_toggle()
	plt.show()
	#plt.close()

def gaugeToRGB (gauge, frac_y = False):	# gauge: [Y(h, w), K(h, w)]
	mapy = gauge[0] * 8 + 128
	mapk = gauge[1] * 127 + 128

	result = None
	if frac_y:
		B, R = np.modf(mapy)
		result = np.stack([B * 256, mapk, R], axis = 2)
	else:
		result = np.stack([np.zeros(mapy.shape, np.float32), mapk, mapy], axis = 2)
	result = np.uint8(np.clip(result, 0, 255))

	return result

image_staff_frame = None

def gaugeToFrame (gauge):	# gauge: [Y(h, w), K(h, w)]
	global image_staff_frame
	if image_staff_frame is None:
		image_staff_frame = cv2.imread('./assets/staff-frame.png')
		image_staff_frame = image_staff_frame[:, :, ::-1]

	# integrate to make X map
	map_x = np.zeros(gauge.shape[1:], np.float32)
	half_height = gauge.shape[1] // 2
	for x in range(gauge.shape[2]):
		map_x[half_height, x] = x + 100

	for y in range(half_height):	# X[y - 1] = X[y] - K[y]
		map_x[half_height - y - 1, :] = map_x[half_height - y, :] - gauge[1, half_height - y, :]

	for y in range(1, half_height):	# X[y] = X[y - 1] + K[y]
		map_x[half_height + y, :] = map_x[half_height + y - 1, :] + gauge[1, half_height + y, :]

	map_y = gauge[0] * 8 + image_staff_frame.shape[0] // 2

	return cv2.remap(image_staff_frame, map_x, map_y, cv2.INTER_CUBIC, borderMode = cv2.BORDER_REPLICATE)

def gaugeToFrameFeature (gauge, feature):
	frame = gaugeToFrame(gauge).astype(np.float32)

	inv_feature = 255 - np.minimum(np.float32(feature) + 64, 255)
	inv_feature = np.clip(inv_feature, 0, 255)

	inv_feature = np.tile(inv_feature[:, :, None], (1, 1, 3))

	return (frame + inv_feature).clip(0, 255).astype(np.uint8)

def scoreAnnoGauge (feature, targets, predictions=None):
	with_pred = predictions is not None
	fig, ax = plt.subplots(4, 2)

	cv2.imwrite('./temp/feature.png', feature)
	cv2.imwrite('./temp/target.png', gaugeToRGB(targets))

	if len(targets) >= 3:
		ax[0][0].imshow(targets[2])
	else:
		ax[0][0].imshow(feature)
	ax[0][1].set_ylabel('feature', rotation='vertical')
	ax[0][1].imshow(feature, cmap='gray')

	ax[1][1].set_ylabel('Y')
	ax[2][1].set_ylabel('K')

	y = ax[1][0].imshow(targets[0])
	k = ax[2][0].imshow(targets[1])
	fig.colorbar(y, ax = ax[1][0], shrink=0.4, pad=0.01)
	fig.colorbar(k, ax = ax[2][0], shrink=0.4, pad=0.01)

	frame = gaugeToFrameFeature(targets, feature)
	ax[3][0].imshow(frame)

	if with_pred:
		y = ax[1][1].imshow(predictions[0])
		k = ax[2][1].imshow(predictions[1])
		fig.colorbar(y, ax = ax[1][1], shrink=0.4, pad=0.01)
		fig.colorbar(k, ax = ax[2][1], shrink=0.4, pad=0.01)
		cv2.imwrite('./temp/pred.png', gaugeToRGB(predictions))

		pred_frame = gaugeToFrameFeature(predictions, feature)
		ax[3][1].imshow(pred_frame)

	plt.get_current_fig_manager().full_screen_toggle()
	plt.show()
	#plt.close()

class DatasetViewer:
	def __init__(self, config, chromatic=True, gauge_mode=False):
		self.chromatic = chromatic
		self.gauge_mode = gauge_mode

		self.labels = config['data.args.labels']

	def show(self, data_set):
		for batch, (feature, target) in enumerate(data_set):
			bsize = len(feature)
			for i in range(bsize):
				index = batch * bsize + i
				logging.info(index)

				img = feature[i].cpu().numpy()
				hm = target[i].cpu().numpy()
				img = np.moveaxis(img, 0, -1)
				img = img.reshape(img.shape[:2]) if img.shape[2] == 1 else img.reshape(img.shape[:3])
				img = np.clip(img, 0., 1.)
				img = np.uint8(img * 255)
				#print('img shape2:', img.shape)

				if self.gauge_mode:
					scoreAnnoGauge(img, hm)
				else:
					if self.chromatic:
						scoreAnnoChromatic(img, hm)
					else:
						hm = np.uint8(hm * 255)
						scoreAnno(hm, img, labels = self.labels)


path = 240 # расстояние до местоназна-е

bmwx5 = 20 # расход на 100 км
mercedes220 = 18 # расход на 100 км
hondafit = 9 # расход на 100 км

fuel = int(input("Введите объем бензобака: "))

result = path / 100

car = input(f'Введите свое авто: ')

if car == "hondafit":
     fuel = fuel - (result * hondafit)
     print (f"Вам не хватило : {fuel} литр(а) бензина")
     result = 100 / hondafit
     result = result * hondafit
     print(f'У вас закончится бензин на {round(result)} километре!')
elif car == "mercedes220":
     fuel = fuel - (result * mercedes220)
     print (f"Вам не хватило: {round(fuel)} литр(а) бензина")
elif car == "bmwx5":
     fuel = fuel - (result * bmwx5)
     print (f"Вам не хватило: {round(fuel)} литр(а) бензина")

Courses/1 month/1 week/day 5/Домашка(в проессе).py

Домашка(в проессе).py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import unittest
import tb

class TestTbSetup(unittest.TestCase):

    def test_setup_current(self):

        os.environ["TERRAFORM_BIN"] = os.path.dirname(os.path.realpath(__file__))+'/bin/mock_terraform_current'
        retcode = tb.main(["tb", "--check-setup"])
        assert retcode == 0

    def test_check_setup_outdated(self):
        u = tb.Utils(
            terraform_path = os.path.dirname(os.path.realpath(__file__))+'/bin/mock_terraform_outdated'
        )

        missing, outdated = u.check_setup(verbose=True)

        assert len(missing) == 0
        assert "terraform" in outdated

    def test_check_setup_missing(self):
        u = tb.Utils(
            terraform_path = os.path.dirname(os.path.realpath(__file__))+'/bin/none'
        )

        missing, outdated = u.check_setup(verbose=True)

        print (missing)
        print (outdated)
        assert len(outdated) == 0
        assert "terraform" in missing

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


import json
import sys

"""
Script accepts three parameters : input file(json formatted) , output file , role, user that needs to be added the role
If the json input passed has an entry for role:"roles/<ROLE>" and the user exists as its member, no action is taken
If the json input passed has an entry for role:"roles/<ROLE>" and the user doesn't exists as its member, it is added to members list
If the json input passed has no entry for role:"roles/<ROLE>", an entry is added with user as member and role as "roles/<ROLE>
"""

input = sys.argv[1]
output = sys.argv[2]
role = sys.argv[3]
users = sys.argv[4].split(',')
users = [ "serviceAccount:" + user  for user in users ]
flag=0
with open(input) as f:
  input = json.load(f)

for user in users:
  for k,v in input.items():
    if k == "bindings":
      for list_item_dict in v:
        if 'role' in list_item_dict and list_item_dict['role']=="roles/" + role :
          if user in list_item_dict['members']:
            flag = 1 #no change needed as the user already exists as roles/<ROLE>
          else:
            list_item_dict['members'].append(user)
            flag = 1 #added the user as roles/<ROLE>

  if flag == 0: # No entry was found for roles/<ROLE>
    #print(input['bindings'])
    for k,v in input.items():
      if k == "bindings":
        v.append({"members":[user],"role":"roles/" + role })

  with open(output,'w') as f:
    json.dump(input,f,indent=2)


import logging

DEBUGGING = False
LOGGING_LEVEL = logging.WARN

class DebugFilter(object):

    def filter(self, record):
        return DEBUGGING and record.levelno == logging.DEBUG

# set up logging to file - this sets up the default logging for the root handler
# logging.basicConfig(level=logging.DEBUG,
#                     format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
#                     datefmt='%m-%d %H:%M',
#                     filename='example.log',
#                     filemode='w')

# add the handlers to logger
log = logging.getLogger('condorpy')
log.setLevel(logging.DEBUG)
log.addHandler(logging.NullHandler())

def activate_debug_logging():
    # define a Handler which writes DEBUG messages to sys.stderr
    debugger = logging.StreamHandler()
    debugger.setLevel(logging.DEBUG)
    debugger.addFilter(DebugFilter())
    formatter = logging.Formatter('%(levelname)-8s %(message)s -- Module: %(module)s in %(funcName)s, line %(lineno)d')
    debugger.setFormatter(formatter)
    log.addHandler(debugger)

def activate_console_logging():
    # define a Handler which writes INFO messages or higher to the sys.stderr
    console = logging.StreamHandler()
    console.setLevel(LOGGING_LEVEL)
    formatter = logging.Formatter('%(levelname)-8s %(message)s')
    console.setFormatter(formatter)
    log.addHandler(console)

def activate_file_logging(file_name='condorpy.log'):
    # define a Handler which logs all messages to a file
    log_file = logging.FileHandler(file_name, mode='w')
    log_file.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
    log_file.setFormatter(formatter)
    log.addHandler(log_file)


import random

async def randomChoice(*args: str):
    arguments = " ".join(args).split(",")
    choices = list(
        filter(None, map(lambda choice: choice.strip().capitalize(), arguments)))
    if len(choices) == 0:
        return 'You have given me no choice'
    flavor = ["is by far the best choice", "and if you pick anything else I'll never talk to you again",
              "try it, you'll love it", "is clearly the only choice here", "is best by all measures"]
    return f'**{random.choice(choices)}** {random.choice(flavor)}.'


import logging

import pytest
from codenamesbot.state import (UNLIMITED, Game, GameMode, GamePhase, InvalidGameState, Player,
                                Players, PlayingTeam, Team)

logging.basicConfig(level=logging.DEBUG)

def test_player_rename():
    p = Player("tris")
    assert p.name == "tris"

    p.rename("nottris")
    assert p.name == "nottris"

def test_toggle_spymaster_preference():
    p = Player("tris")
    assert not p.spymaster_preference

    p.toggle_spymaster_preference()
    assert p.spymaster_preference

    p.toggle_spymaster_preference()
    p.toggle_spymaster_preference()
    assert p.spymaster_preference

def test_players_track_rename():
    ps = Players()

    tris = ps.add("tris")
    assert ps["tris"] == tris
    assert "tris" in ps

    ps["tris"].rename("nottris")
    assert ps["nottris"] is tris
    assert "tris" not in ps

    claire = ps.add("claire")
    assert tris != claire

    with pytest.raises(KeyError):
        ps["tris"]

def test_players_track_length():
    ps = Players()

    ps.add("tris")
    ps.add("claire")
    ps.add("bob")
    assert len(ps) == 3

    ps.remove("claire")
    assert len(ps) == 2

def test_players_shuffle():
    ps = Players()

    ps.add("tris")
    ps.add("claire")
    ps.add("bob")

    assert len(ps.shuffled()) == 3

def test_players_to_str():
    ps = Players()

    ps.add("tris")
    ps.add("claire")
    ps.add("bob")
    assert str(ps) == "3 players: tris, claire, bob"

    ps.remove("bob")
    ps.remove("tris")
    assert str(ps) == "1 player: claire"

def test_team_opposite():
    assert ~Team.GREEN == Team.PINK
    assert ~Team.PINK == Team.GREEN

def test_playingteam_normal():
    for t in [Team.GREEN, Team.PINK]:
        team = PlayingTeam(t)

        team.add(Player("tris"))
        team.add(Player("claire"))

        assert team.spymaster.name == "tris"
        assert len(team.guessers) == 1
        assert team.guessers[0].name == "claire"

        players = list(team)
        assert players == team.players

def test_playingteam_gray():
    team = PlayingTeam(Team.GRAY)

    team.add(Player("tris"))
    team.add(Player("claire"))

    assert team.spymaster is None
    assert len(team.guessers) == 2

def test_playingteam_length():
    team = PlayingTeam(Team.GRAY)

    team.add(Player("tris"))
    team.add(Player("claire"))

    assert len(team) == 2

def test_playingteam_contains():
    team = PlayingTeam(Team.GRAY)

    tris = Player("tris")
    claire = Player("claire")
    team.add(tris)

    assert tris in team
    assert claire not in team

def test_player_double_join():
    game = Game()
    game.join("tris")

    with pytest.raises(InvalidGameState):
        game.join("tris")

def test_player_double_leave():
    game = Game()

    with pytest.raises(InvalidGameState):
        game.leave("tris")

def test_assign_players_gray_small():
    game = Game()

    tris = game.join("tris")
    claire = game.join("claire")
    bob = game.join("bob")

    bob.team = Team.GREEN
    tris.team = Team.PINK

    game.mode = GameMode.GRAY
    game.assign_teams()

    assert tris.team == Team.PINK
    assert claire.team == Team.GRAY
    assert bob.team == Team.GREEN

    assert game.teams[Team.GREEN].spymaster == bob
    assert not game.teams[Team.GREEN].guessers

    assert game.teams[Team.PINK].spymaster == tris
    assert not game.teams[Team.PINK].guessers

    assert game.teams[Team.GRAY].guessers == [claire]

def test_assign_players_gray_big():
    for _ in range(100):
        game = Game()

        game.join("tris")
        game.join("claire")
        game.join("bob")
        alice = game.join("alice")
        eve = game.join("eve")

        # two players want to be on the green team
        # nobody in particular wants to be on the pink team
        alice.team = Team.GREEN
        eve.team = Team.GREEN

        game.mode = GameMode.GRAY
        game.assign_teams()

        # make sure alice and eve got on different teams, but one of them got on the green team
        green_preferred_resulting_teams = {alice.team, eve.team}
        assert len(green_preferred_resulting_teams) == 2
        assert Team.GREEN in green_preferred_resulting_teams

        # sanity check that
        assert game.teams[Team.GREEN].spymaster in {alice, eve}

        # make sure someone is the pink spymaster
        pink_spymaster = game.teams[Team.PINK].spymaster

        # make sure pink spymaster is not on gray team as well
        assert pink_spymaster.team == Team.PINK
        assert pink_spymaster not in game.teams[Team.GRAY].players

        # make sure gray team has exactly 3 players
        assert len(game.teams[Team.GRAY]) == 3

def test_assign_players_gray_spymaster_preference():
    for _ in range(100):
        game = Game()

        game.join("tris")
        game.join("claire")
        game.join("bob")
        alice = game.join("alice")
        eve = game.join("eve")

        alice.spymaster_preference = True
        eve.spymaster_preference = True

        game.mode = GameMode.GRAY
        game.assign_teams()

        # make sure alice and eve are the spymasters
        assert {game.teams[Team.GREEN].spymaster, game.teams[Team.PINK].spymaster} == {alice, eve}

def test_assign_players_gray_for_gray_preference():
    for _ in range(100):
        game = Game()

        tris = game.join("tris")
        claire = game.join("claire")
        bob = game.join("bob")
        alice = game.join("alice")

        bob.team = Team.GRAY
        alice.team = Team.GRAY

        game.mode = GameMode.GRAY
        game.assign_teams()

        assert {game.teams[Team.GREEN].spymaster, game.teams[Team.PINK].spymaster} == {tris, claire}

def test_assign_players_versus_all_team_preference():
    for _ in range(100):
        game = Game()

        tris = game.join("tris")
        claire = game.join("claire")
        bob = game.join("bob")
        alice = game.join("alice")
        eve = game.join("eve")

        tris.team = Team.GREEN
        bob.team = Team.GREEN
        claire.team = Team.PINK
        alice.team = Team.PINK
        eve.team = Team.PINK

        game.mode = GameMode.VERSUS
        game.assign_teams()

        assert tris.team == bob.team == Team.GREEN
        assert claire.team == alice.team == eve.team == Team.PINK

def test_assign_players_versus_two_spymasters():
    for _ in range(100):
        game = Game()

        tris = game.join("tris")
        claire = game.join("claire")
        game.join("bob")
        game.join("alice")
        game.join("eve")

        tris.spymaster_preference = True
        claire.spymaster_preference = True

        game.mode = GameMode.VERSUS
        game.assign_teams()

        spymaster_teams = {tris.team, claire.team}
        assert len(spymaster_teams) == 2

def test_assign_players_versus_team_preference_overrides_spymaster_preference():
    for _ in range(100):
        game = Game()

        tris = game.join("tris")
        claire = game.join("claire")
        game.join("bob")
        game.join("alice")
        game.join("eve")

        tris.spymaster_preference = True
        claire.spymaster_preference = True

        tris.team = Team.GREEN
        claire.team = Team.GREEN

        game.mode = GameMode.VERSUS
        game.assign_teams()

        assert tris.team == claire.team == Team.GREEN

def test_assign_players_versus_balanced_teams():
    for _ in range(100):
        game = Game()

        tris = game.join("tris")
        claire = game.join("claire")
        bob = game.join("bob")
        alice = game.join("alice")

        tris.team = claire.team = bob.team = Team.GREEN

        game.mode = GameMode.VERSUS
        game.assign_teams()

        assert alice.team == Team.PINK
        assert len(game.teams[Team.GREEN]) == 2
        assert len(game.teams[Team.PINK]) == 2

def test_assign_words():
    game = Game()

    game.join("tris")
    game.join("claire")
    game.join("bob")

    game.assign_words()

    assert len(game.words[Team.GREEN]) == 9
    assert len(game.words[Team.PINK]) == 8
    assert len(game.words[Team.GRAY]) == 7
    assert game.assassin is not None

def test_start_game():
    game = Game()

    game.join("tris")
    game.join("claire")
    game.join("bob")

    game.mode = GameMode.GRAY
    game.start_game()

    assert game.teams[Team.GREEN].spymaster is not None
    assert game.teams[Team.PINK].spymaster is not None
    assert len(game.teams[Team.GRAY].guessers) > 0

    assert game.words[Team.GREEN]
    assert game.words[Team.PINK]
    assert game.words[Team.GRAY]
    assert game.assassin is not None

def test_start_game_not_enough_players():
    game = Game()

    game.join("tris")
    game.join("claire")

    with pytest.raises(InvalidGameState):
        game.start_game()

def test_start_game_after_player_leaves():
    game = Game()

    game.join("tris")
    game.join("claire")
    game.join("bob")
    game.leave("bob")

    with pytest.raises(InvalidGameState):
        game.start_game()

def test_midgame_join_forced_gray():
    game = Game()

    game.join("tris")
    game.join("claire")
    game.join("bob")

    game.start_game()

    alice = game.join("alice")
    assert alice.team == Team.GRAY

    eve = game.join("eve", team=Team.GREEN)
    assert eve.team == Team.GRAY

def test_midgame_join_gray_in_versus():
    game = Game()

    game.join("tris")
    game.join("claire")
    game.join("bob")
    game.join("alice")

    game.mode = GameMode.VERSUS
    game.start_game()

    eve = game.join("eve", team=Team.GRAY)
    assert eve.team != Team.GRAY

def test_midgame_join_allowed_to_select_if_balanced():
    for _ in range(100):
        game = Game()

        game.join("tris")
        game.join("claire")
        game.join("bob")
        game.join("alice")

        game.start_game()

        eve = game.join("eve", team=Team.GREEN)
        assert eve.team == Team.GREEN

def test_midgame_join_forced_if_unbalanced():
    for _ in range(100):
        game = Game()

        game.join("tris", team=Team.GREEN)
        game.join("claire", team=Team.GREEN)
        game.join("bob", team=Team.GREEN)
        game.join("alice", team=Team.PINK)
        game.join("charlie", team=Team.PINK)

        game.start_game()

        eve = game.join("eve", team=Team.GREEN)
        assert eve.team == Team.PINK

    for _ in range(100):
        game = Game()

        game.join("tris", team=Team.PINK)
        game.join("claire", team=Team.PINK)
        game.join("bob", team=Team.PINK)
        game.join("alice", team=Team.GREEN)
        game.join("charlie", team=Team.GREEN)

        game.start_game()

        eve = game.join("eve", team=Team.PINK)
        assert eve.team == Team.GREEN

def test_midgame_join_assigned_if_unbalanced():
    game = Game()

    game.join("tris", team=Team.GREEN)
    game.join("claire", team=Team.GREEN)
    game.join("bob", team=Team.GREEN)
    game.join("alice", team=Team.PINK)
    game.join("charlie", team=Team.PINK)

    game.start_game()

    eve = game.join("eve")
    assert eve.team == Team.PINK

    game = Game()

    game.join("tris", team=Team.PINK)
    game.join("claire", team=Team.PINK)
    game.join("bob", team=Team.PINK)
    game.join("alice", team=Team.GREEN)
    game.join("charlie", team=Team.GREEN)

    game.start_game()

    eve = game.join("eve")
    assert eve.team == Team.GREEN

def setup_4p_game():
    game = Game()

    tris = game.join("tris", team=Team.GREEN)
    tris.spymaster_preference = True

    bob = game.join("bob", team=Team.PINK)
    bob.spymaster_preference = True

    game.join("claire", team=Team.GREEN)
    game.join("alice", team=Team.PINK)

    game.start_game()

    return game, tris

def test_hint_normal():
    game, tris = setup_4p_game()

    assert game.phase == GamePhase.HINTING
    assert game.active_team == Team.GREEN

    game.hint(tris, "foo", 2)

    assert game.phase == GamePhase.GUESSING
    assert game.active_team == Team.GREEN
    assert game.current_hint == ("foo", 2)
    assert game.remaining_guesses == 3

def test_hint_from_disallowed_actors():
    game, tris = setup_4p_game()

    with pytest.raises(InvalidGameState):
        game.hint(game.players["claire"], "foo", 2)

    with pytest.raises(InvalidGameState):
        game.hint(game.players["bob"], "foo", 2)

    assert game.phase == GamePhase.HINTING
    assert game.active_team == Team.GREEN

def test_hint_with_too_many_words():
    game, tris = setup_4p_game()

    with pytest.raises(InvalidGameState):
        game.hint(tris, "foo", 10)

def test_hint_is_active_word():
    game, tris = setup_4p_game()

    with pytest.raises(InvalidGameState):
        game.hint(tris, game.assassin, 1)

def test_hint_after_hint():
    game, tris = setup_4p_game()

    game.hint(tris, "foo", 1)

    assert game.phase == GamePhase.GUESSING

    with pytest.raises(InvalidGameState):
        game.hint(tris, "quux", 1)

def test_unlimited_hint():
    game, tris = setup_4p_game()

    game.hint(tris, "foo", UNLIMITED)

    assert game.current_hint == ("foo", UNLIMITED)
    assert game.remaining_guesses == UNLIMITED

def test_guess_civilian():
    game, tris = setup_4p_game()
    game.hint(tris, "foo", 4)

    word = game.words[Team.GRAY][0]
    game.guess(game.players["claire"], word)

    assert game.phase == GamePhase.HINTING
    assert game.active_team == Team.PINK
    assert word not in game.all_words
    assert word not in game.remaining_words[Team.GRAY]
    assert word in game.words[Team.GRAY]

def test_guess_opposite_team():
    game, tris = setup_4p_game()
    game.hint(tris, "foo", 4)

    word = game.words[Team.PINK][0]
    game.guess(game.players["claire"], word)

    assert game.phase == GamePhase.HINTING
    assert game.active_team == Team.PINK
    assert word not in game.all_words
    assert word not in game.remaining_words[Team.PINK]
    assert word in game.words[Team.PINK]

def test_guess_same_team():
    game, tris = setup_4p_game()
    game.hint(tris, "foo", 4)

    assert game.remaining_guesses == 5

    word = game.words[Team.GREEN][0]
    game.guess(game.players["claire"], word)

    assert game.phase == GamePhase.GUESSING
    assert game.active_team == Team.GREEN
    assert game.remaining_guesses == 4

    assert word not in game.all_words
    assert word not in game.remaining_words[Team.GREEN]
    assert word in game.words[Team.GREEN]

    with pytest.raises(InvalidGameState):
        game.guess(game.players["claire"], word)

    word = game.words[Team.GREEN][1]
    game.guess(game.players["claire"], word)

    assert game.remaining_guesses == 3

def test_guess_assassin():
    game, tris = setup_4p_game()
    game.hint(tris, "foo", 4)

    game.guess(game.players["claire"], game.assassin)

    assert game.phase == GamePhase.POST_GAME
    assert game.winner == Team.PINK

def test_running_out_of_guesses():
    game, tris = setup_4p_game()
    game.hint(tris, "foo", 1)

    game.guess(game.players["claire"], game.remaining_words[Team.GREEN][0])
    game.guess(game.players["claire"], game.remaining_words[Team.GREEN][0])

    assert game.phase == GamePhase.HINTING
    assert game.active_team == Team.PINK

def test_stopping_guess_phase_early():
    game, tris = setup_4p_game()
    game.hint(tris, "foo", 1)

    game.guess(game.players["claire"], game.remaining_words[Team.GREEN][0])
    game.stop(game.players["claire"])

    assert game.phase == GamePhase.HINTING
    assert game.active_team == Team.PINK

def test_spymaster_cannot_guess():
    game, tris = setup_4p_game()
    game.hint(tris, "foo", 1)

    with pytest.raises(InvalidGameState):
        game.guess(tris, game.remaining_words[Team.GREEN][0])

    assert game.phase == GamePhase.GUESSING
    assert game.active_team == Team.GREEN
    assert game.remaining_guesses == 2
    assert len(game.remaining_words[Team.GREEN]) == 9

def test_spymaster_cannot_stop_guessing():
    game, tris = setup_4p_game()
    game.hint(tris, "foo", 1)

    with pytest.raises(InvalidGameState):
        game.stop(tris)

    assert game.phase == GamePhase.GUESSING
    assert game.active_team == Team.GREEN

def test_cannot_guess_during_hint_phase():
    game, tris = setup_4p_game()

    with pytest.raises(InvalidGameState):
        game.guess(game.players["claire"], game.all_words[0])

    assert game.phase == GamePhase.HINTING
    assert game.active_team == Team.GREEN

def test_cannot_stop_during_hint_phase():
    game, tris = setup_4p_game()

    with pytest.raises(InvalidGameState):
        game.stop(game.players["claire"])

    assert game.phase == GamePhase.HINTING
    assert game.active_team == Team.GREEN

def test_cannot_guess_for_other_team():
    game, tris = setup_4p_game()
    game.hint(tris, "foo", 1)

    with pytest.raises(InvalidGameState):
        game.guess(game.players["alice"], game.assassin)

    assert game.phase == GamePhase.GUESSING
    assert game.active_team == Team.GREEN
    assert game.remaining_guesses == 2

def test_cannot_stop_for_other_team():
    game, tris = setup_4p_game()
    game.hint(tris, "foo", 1)

    with pytest.raises(InvalidGameState):
        game.stop(game.players["alice"])

    assert game.phase == GamePhase.GUESSING
    assert game.active_team == Team.GREEN

def test_winning():
    game, tris = setup_4p_game()
    game.hint(tris, "pony", 9)

    for word in game.words[Team.GREEN]:
        game.guess(game.players["claire"], word)

    assert game.phase == GamePhase.POST_GAME
    assert game.winner == Team.GREEN

def test_winning_during_guessing_phase():
    game, tris = setup_4p_game()
    game.hint(tris, "pony", UNLIMITED)

    game.stop(game.players["claire"])
    game.hint(game.players["bob"], "pony", 7)

    for word in game.words[Team.PINK][:-1]:
        game.guess(game.players["alice"], word)

    game.stop(game.players["alice"])
    game.hint(tris, "pony", UNLIMITED)

    game.guess(game.players["claire"], game.remaining_words[Team.PINK][0])

    assert game.phase == GamePhase.POST_GAME
    assert game.winner == Team.PINK

def test_winning_during_guessing_phase_with_0_guesses_remaining():
    game, tris = setup_4p_game()
    game.hint(tris, "pony", UNLIMITED)

    game.stop(game.players["claire"])
    game.hint(game.players["bob"], "pony", 7)

    for word in game.words[Team.PINK][:-2]:
        game.guess(game.players["alice"], word)

    game.stop(game.players["alice"])
    game.hint(tris, "pony", 1)

    game.guess(game.players["claire"], game.words[Team.GRAY][0])

    game.hint(game.players["bob"], "pony", 1)

    game.guess(game.players["alice"], game.remaining_words[Team.PINK][0])
    game.guess(game.players["alice"], game.remaining_words[Team.PINK][0])

    assert game.phase == GamePhase.POST_GAME
    assert game.winner == Team.PINK

def test_leave_during_game():
    game, tris = setup_4p_game()

    with pytest.raises(InvalidGameState):
        game.leave(tris)

def test_join_after_game():
    # the game state needs to be reset externally before new joins are accepted
    game, tris = setup_4p_game()
    game.hint(tris, "pony", 9)
    game.guess(game.players["claire"], game.assassin)

    assert game.phase == GamePhase.POST_GAME

    with pytest.raises(InvalidGameState):
        game.join("steve")

def test_start_ongoing_game():
    game, _ = setup_4p_game()

    with pytest.raises(InvalidGameState):
        game.start_game()


# -*- coding: utf-8 -*-
# !/usr/bin/env python
"""
@time           : 2019/5/24 下午10:22
@author         : liuning11@jd.com
@file           : gun.py
@description    : gunicorn config

    ##########################################################
    #
    #
    #
    #
    ##########################################################

"""
# Server Socket
bind = '0.0.0.0:8088'
backlog = 2048
# Worker Processes
workers = 20
worker_class = "gevent"
worker_connections = 1000
# Server Mechanics
daemon = False
pidfile = './log/cap-faiss/gunicorn.pid'
# Process Naming
proc_name = 'app_api'
# timeout = 100
# graceful_timeout = 50
# Logging
loglevel = 'error'  # info debug error
accesslog = "./log/cap-faiss/gunicorn-access.log"
errorlog = './log/cap-faiss/gunicorn-error.log'


import socket
import os
import struct

enc = "windows-1252"

C2E_MAGIC = b"c2e@"

class CSMIHead():
	"""
	Class to manage a shared memory interface header.
	"""
	def __init__(self, b: bytes = None):
		"""
		Initializes a blank default shared memory interface header object.
		If bytes are supplied, loads the contents of said bytes into this object via of_bytes.
		"""
		self.magic = C2E_MAGIC
		self.process_id = 0
		self.result_code = 0
		self.data_len = 0
		self.data_len_max = 1048576
		self.padding = 0
		if not (b is None):
			self.of_bytes(b)
	def is_valid(self) -> bool:
		"""
		Returns True if this header is valid.
		"""
		return self.magic == C2E_MAGIC
	def of_bytes(self, b: bytes):
		"""
		Loads the contents of the given bytes into the fields of this object.
		"""
		unpacked = struct.unpack("<4sIiIIi", b)
		self.magic = unpacked[0]
		self.process_id = unpacked[1]
		self.result_code = unpacked[2]
		self.data_len = unpacked[3]
		self.data_len_max = unpacked[4]
		self.padding = unpacked[5]
	def to_bytes(self) -> bytes:
		"""
		Converts this object back to a shared memory interface header's bytes.
		"""
		return struct.pack("<4sIiIIi", self.magic, self.process_id, self.result_code, self.data_len, self.data_len_max, self.padding)
	def __repr__(self):
		"""
		Provides a description of the object fields.
		"""
		return "CSMIHead: magic=" + self.magic.decode(enc) + " pid=" + str(self.process_id) + " code=" + str(self.result_code) + " dl=" + str(self.data_len) + " dlm=" + str(self.data_len_max) + " pad=" + str(self.padding)

def recvall(s: socket.socket, l: int) -> bytes:
	"""
	Calls recv repeatedly until end of stream (raising EOFError if encountered early) or until the given length has been fulfilled.
	"""
	data = b""
	while len(data) < l:
		chunk = s.recv(l - len(data))
		if chunk == b"":
			raise EOFError("at " + str(len(data)) + " during recvall(" + str(s) + ", " + str(l) + ")")
		data += chunk
	return data

csmihead_len = 24

def decode_cpxrhead(b: bytes) -> int:
	"""
	Decodes a CPX request header (just an integer for the length)
	"""
	return struct.unpack("<I", b)[0]
def encode_cpxr(b: bytes) -> bytes:
	"""
	Encodes a CPX request (i.e. adds a length prefix).
	"""
	return struct.pack("<I", len(b)) + b
cpxrhead_len = 4

def cut_terminated(b: bytes, t: bytes):
	idx = b.find(t)
	if idx == -1:
		return b, b""
	return b[:idx], b[idx + len(t):]

def open_default() -> socket:
	"""
	Opens a socket to the "default" CPX server.
	"""
	return socket.create_connection((os.getenv("CPX_HOST") or "localhost", os.getenv("CPX_PORT") or 19960))

class CPXError(Exception):
	"""
	This exception type is specifically for errors returned by the remote host.
	Any networking errors or such are returned as other exceptions.
	"""
	pass

# -- main client functions --

def raw_request(s: socket.socket, request: bytes) -> bytes:
	"""
	Performs a raw CPX request, sending and returning binary data.
	Realistically, what you're sending is always going to be a *null-terminated* string.
	The main purpose of this function is that it handles the fiddly bits (i.e. raising CPXError).
	"""
	hdr1 = CSMIHead(recvall(s, csmihead_len))
	if not hdr1.is_valid():
		raise Exception("Server description header not valid")
	# send request
	s.sendall(encode_cpxr(request))
	hdr2 = CSMIHead(recvall(s, csmihead_len))
	resp = recvall(s, hdr2.data_len)
	if not hdr2.is_valid():
		raise Exception("Response header not valid")
	if hdr2.result_code != 0:
		# Error
		raise CPXError(cut_terminated(resp, b"\0")[0].decode(enc))
	return resp

def execute_caos(s: socket.socket, t: str) -> str:
	"""
	Runs some CAOS and gets a textual result.
	This isn't qualified to handle binary data as it expects (and removes) the null terminator and decodes the string.
	"""
	resp = raw_request(s, b"execute\n" + (t.encode(enc)) + b"\0")
	return cut_terminated(resp, b"\0")[0].decode(enc)

# -- main client functions, defaults --

def raw_request_default(t: bytes) -> bytes:
	"""
	Performs a raw CPX request, sending and returning binary data.
	Realistically, what you're sending is always going to be a *null-terminated* string.
	The main purpose of this function is that it handles the fiddly bits (i.e. raising CPXError).
	"""
	s = open_default()
	try:
		return raw_request(s, t)
	finally:
		s.close()

def execute_caos_default(t: str) -> str:
	"""
	Runs some CAOS and gets a textual result.
	This isn't qualified to handle binary data as it expects (and removes) the null terminator and decodes the string.
	"""
	s = open_default()
	try:
		return execute_caos(s, t)
	finally:
		s.close()


print("this is fragile. enter only great than 2 whole numbers")

occur=int(input("Enter the occurence of the prime number you want: "))
x=2
num=3

#First to write the logic to determine if a number is prime or not.
#Ignore even numbers

while True:
    is_prime = True
    for i in range(2, num):
        if num % i == 0:
            is_prime = False  # number is not prime
            break  # exit from for loop

    if is_prime:
        if(x==occur):
            print("Found: ",num)
            break
        x=x+1
        num=num+2
    else:
        num=num+2

print("Done")