コード例 #1
0
ファイル: Controller.py プロジェクト: piastu/Patterns17
class Controller(AbstractController):
    def __init__(self):
        self.__view = ConsoleView(self)
        self.__config_db = None
        self.__classifier_types = None
        self.__init_configs()
        self.__model = Model(self.__config_db)

    def __init_configs(self):
        """ загрузить конфиги в переменные для последующего обращения к ним """
        # инициализация конфига для базы данных
        with open('Data/configs/configDatabase.json') as file:
            config_temp = json.load(file)
            self.__config_db = dict()
            self.__config_db['default'] = config_temp['driver']
            self.__config_db[self.__config_db['default']] = config_temp

    def run_app(self):
        self.__view.start_view()

    def close_app(self):
        exit(0)

    def get_predict_types(self):
        """ получить список типов предсказываемых объектов """
        # получим запрос из бд
        types = self.__model.get_object_types()
        target = []
        # преобразуем к нужной форме
        for i, record in enumerate(types):
            target.append({
                'name': record.Name,
                'command': '-' + str(i + 1),
                'code': record.Code
            })
        return tuple(target)

    def get_concrete_classifiers_by_command_type(self, classifier_type_code):
        """ получить список конкретных классификаторов по выбранному типу """
        classifiers = self.__model.get_classifiers_by_type(
            classifier_type_code)
        target = []
        for i, record in enumerate(classifiers):
            target.append({
                'name': record.Name,
                'code': record.Code,
                'command': '-' + str(i + 1)
            })
        return tuple(target)

    def classify_object(self, code_classifier_type, code_classifier,
                        object_path):
        if not os.path.isfile(object_path):
            return {
                'ok': False,
                'message': 'Файла по такому пути не существует'
            }
        return self.__model.classify_object(code_classifier_type,
                                            code_classifier, object_path)
コード例 #2
0
ファイル: main.py プロジェクト: RyanWri/Football-stats
def index():
    cols = ['home-team', 'away-team', '1', 'X', '2', '1-goals', '2-goals', '1-conceived', '2-conceived']
    today = date.today().strftime("%Y-%m-%d")
    filename = f'/Users/rywright/Football/Data/extended-{today}-predictions.csv'
    if not os.path.isfile(filename):
        model = Model()
        df = model.write_extended_csv()
    else:
        df = pd.read_csv(filename)
    return render_template('index.html', arr=df.values, columns=cols)
コード例 #3
0
    def newGame(self):
        # Push world generation along one stage at a time. After each stage we redraw the game window.
        # This lets the player watch the world get generated.
        self.model = Model(self.configManager)
        self.updateView(self.model)
        self.fpsClock.tick(self.configManager.FPS)

        while not self.model.world.worldGenDone:
            self.model.world.createWorldStep()
            self.updateView(self.model)
        self.fpsClock.tick(self.configManager.FPS)
コード例 #4
0
ファイル: Controller.py プロジェクト: hrmshams/astm_bot
    def __init__(self):
        db_connection = {
            "username": "******",
            "password": "******",
        }
        self.__model = Model()

        """ configuring the database """
コード例 #5
0
 def __init__(self, sys_argv):
     super(App, self).__init__(sys_argv)
     self.model = Model()
     initFileDirectory = os.getcwd() + "/"
     initFileName = "BER_InitFile_V100_SY.json"
     self.main_ctrl = MainController(initFileDirectory, initFileName,
                                     self.model)
     #show the windows
     self.main_view = Window(self.model, self.main_ctrl)
コード例 #6
0
    def prediction(self, dataframe, model=Model()):

        x_predict, y_predict = self.split_data(dataframe)
        Ys = model.predict(x_predict)
        predict_data = Ys.tolist()

        new_column = pd.DataFrame(predict_data, columns=["Predict_column"])
        dataframe.join_data(new_column)
        dataframe.to_csv("Predict_file.csv")
        return dataframe
コード例 #7
0
	def newGame(self):
		# Push world generation along one stage at a time. After each stage we redraw the game window.
		# This lets the player watch the world get generated.
		self.model = Model(self.configManager)
		self.updateView(self.model)
		self.fpsClock.tick(self.configManager.FPS)

		while not self.model.world.worldGenDone:
			self.model.world.createWorldStep()
			self.updateView(self.model)
        	self.fpsClock.tick(self.configManager.FPS)
コード例 #8
0
    def __init__(self):
        self._Controller = Controller()
        self._View = View()
        self._Model = Model()

        self._Controller.addView(self._View)
        self._Controller.addModel(self._Model)
        self._View.addController(self._Controller)

        self._View.initMainView()

        self._Controller.startApp()
コード例 #9
0
def benchmark(truth: TruthModel, pred: Model):
    score = 0
    empty = 0
    for (a, b) in truth.pairs():
        try:
            x = truth.similarity(a, b)
            y = pred.similarity(a, b)
            score += calcError(x, y)
        except:
            empty += 1

    score /= (len(truth.pairs()) - empty)
    return score, len(truth.pairs()) - empty, empty
コード例 #10
0
def LoadModel():
    global _myData
    global _myModel
    modelList = getModelList()
    message = "Choose a Model \n"
    i = 1
    for model in modelList:
        message = message + str(i) + ". " + model + "\n"
        i += 1
    userInput = int(input(message + ">"))
    if userInput <= len(modelList):
        name = modelList[userInput - 1]
        model = getModel(name)
        if "bymerg" in name.lower():
            return KS_Model(model,
                            name=name,
                            mapping="emnist-bymerge-mapping.txt")
        elif "byclass" in name.lower():
            return KS_Model(model,
                            name=name,
                            mapping="emnist-byclass-mapping.txt")
        elif "balanced" in name.lower():
            return KS_Model(model,
                            name=name,
                            mapping="emnist-balanced-mapping.txt")
        elif "digits" in name.lower():
            return KS_Model(model,
                            name=name,
                            mapping="emnist-digits-mapping.txt")
        elif "letters" in name.lower():
            return KS_Model(model,
                            name=name,
                            mapping="emnist-letters-mapping.txt")
        elif "mnist" in name.lower():
            return KS_Model(model,
                            name=name,
                            mapping="emnist-mnist-mapping.txt")

        else:
            return Model(model, name=name)
    else:
        print("Invalid input select between 1 -", len(modelList))
        input("Press Enter to continue...")
        LoadModel()
コード例 #11
0
    def k_fold_validation(self, data_frame, model=Model()):

        self.genered_folds(data_frame)

        for i in range(self.folds.size()):
            x_training, y_training, x_test, y_test = self.get_data_sets(i)
            cv = CategoricalValues()
            y_training = cv.one_hot2(y_training, self.output_column)
            # training section
            model.train_model(x_training.iloc[:, :].values,
                              y_training.iloc[:, :].values)

            # test section
            y_test = cv.one_hot2(y_test, self.output_column)
            error = model.evaluate_model(x_test.iloc[:, :], y_test.iloc[:, :])
            #error = 3
            self.errors.append(error)

        self.mean_error = sum(self.errors) / self.k

        self.generate_report(data_frame)
        return self.mean_error
コード例 #12
0
def main():
    data_loader = setup_database(ISTRAIN, True, 5)

    with open(os.path.join('../101_ObjectCategories', 'label_dictionary.data'),
              'rb') as f:
        labels = pickle.load(f)

    for label in labels:
        print(F'{labels.index(label)} , {label["label"]}')

    model = Model(data_loader)

    if (ISTRAIN):
        model.train()
    else:
        for i in range(20):
            model.test()
コード例 #13
0
class GameController(object):
    def __init__(self):
        # Make the configManager.
        # The configManager means that all the settings are grabbed at once.
        # This will prevent the settings being changed mid way through genereation/simulation and messing things up.
        self.configManager = ConfigManager()

        self.fpsClock = pygame.time.Clock()

        # The view controller handles the two displaysurfaces that make up the game window.
        self.viewController = ViewController(self.configManager)

        # Creates a new Model and generates the world.
        self.newGame()

        # Amount of logic frames per second.
        LOGIC_UPDATES_PER_SECOND = 1
        self.SKIP_TICKS = 1000 / LOGIC_UPDATES_PER_SECOND
        self.MAX_FRAMESKIP = 10

    def main(self):
        self.buttonsPressed = defaultdict(lambda: False)

        # How long since pygame was inited
        # Used to keep track of how long it has been since the last draw.
        nextGameTick = pygame.time.get_ticks()

        while True:
            # Logic loop parameter.
            loops = 0
            # Seperate the game logic up from the game display. This means the slow update speed
            # of the model updating doesn't harm our ability to look around the world.
            while pygame.time.get_ticks(
            ) > nextGameTick and loops < self.MAX_FRAMESKIP:
                self.updateModel()

                nextGameTick += self.SKIP_TICKS
                loops += 1

            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == MOUSEBUTTONUP:
                    # Pixel co-ordinates of click.
                    mousex, mousey = event.pos

                    clickedCell = self.viewController.getClickedCell(
                        (mousex, mousey))

                    if clickedCell:
                        self.model.world.setFocusCell(clickedCell)
                    else:
                        print "Clicked outside game view"
                elif event.type == KEYDOWN and event.key == K_n:
                    self.buttonsPressed['regenWorld'] = True
                elif event.type == KEYDOWN and event.key == K_y:
                    self.buttonsPressed['confirmKey'] = True
                elif event.type == KEYDOWN and event.key == K_p:
                    self.buttonsPressed['pauseKey'] = True

            self.handleInput()

            self.updateView(self.model)

    def newGame(self):
        # Push world generation along one stage at a time. After each stage we redraw the game window.
        # This lets the player watch the world get generated.
        self.model = Model(self.configManager)
        self.updateView(self.model)
        self.fpsClock.tick(self.configManager.FPS)

        while not self.model.world.worldGenDone:
            self.model.world.createWorldStep()
            self.updateView(self.model)
        self.fpsClock.tick(self.configManager.FPS)

    def updateView(self, model, updateUI=False):
        self.configManager.currentFPS = str(int(self.fpsClock.get_fps()))

        self.viewController.updateView(model)
        self.fpsClock.tick(self.configManager.FPS)

    def updateModel(self):
        self.model.updateWorld()

    def handleInput(self):
        if self.buttonsPressed['regenWorld']:
            self.regenWorld()
            self.buttonsPressed['regenWorld'] = False

        if self.buttonsPressed['confirmKey'] and not self.model.villagePlaced:
            self.placeVillage()
            self.buttonsPressed['confirmKey'] = False

        if self.buttonsPressed['pauseKey'] and self.model.villagePlaced:
            self.model.gamePaused = not self.model.gamePaused
            self.buttonsPressed['pauseKey'] = False

    def regenWorld(self):
        self.configManager.regenSeed()
        self.newGame()

    def placeVillage(self):
        self.model.placeVillage()
        self.model.villagePlaced = True
コード例 #14
0
ファイル: iris.py プロジェクト: Atom-101/NumPyML
sys.path.append('~/common_data/Projects/Custom_CNN_Lib')

import pandas as pd
import numpy as np

from Model.Model import Model
from Layers.Dense import Dense
from Layers.Conv import Conv
from Dataset.Dataset import Dataset

df = pd.read_csv('Iris.csv')
# print(df.head())

df['Species'] = pd.factorize(df['Species'], sort=True)[0]
# print(df.head())
train = df.iloc[:135, :]
valid = df.iloc[135:, :]

Y = train.iloc[:, -1].values
Y = np.eye(np.max(Y) + 1)[Y]

train_dataset = Dataset(train.iloc[:, 1:-1].values, Y, 135)
# print(train_dataset.next())

nn = Model(4)
nn.add(Dense(6, 'relu'))
nn.add(Dense(3, 'sigmoid'))

nn.train(1e-2, train_dataset, 8000, 'binary_cross_entropy', None)
# nn.train(1e-2, train_dataset, 8000, 'softmax_cross_entropy_with_logits',None)
コード例 #15
0
 def __init__(self):
     self.Model = Model()
     self.View = View()
コード例 #16
0
class Controller:
    """
    *********************************
    *  A controller for a store DB  *
    *********************************
    """
    def __init__(self):
        self.model = Model()
        self.view = View()

    def start(self):
        self.view.start()
        self.main_menu()

    """
    *********************************
    *       General Controller      *
    *********************************
    """

    def main_menu(self):
        o = '0'
        while 0 != '3':
            self.view.main_menu()
            self.view.option('3')
            o = input()
            if o == '1':
                self.cita_menu()
            elif o == '2':
                self.contacto_menu()
            elif o == '3':
                self.view.end()
            else:
                self.view.not_valid_option()
        return

    def update_lists(self, fs, vs):
        fields = []
        vals = []
        for f, v in zip(fs, vs):
            if v != '':
                fields.append(f + ' = %s')
                vals.append(v)
        return fields, vals

    """
    *********************************
    *     Controllers for dates     *
    *********************************
    """

    def cita_menu(self):
        o = '0'
        while o != '8':
            self.view.cita_menu()
            self.view.option('13')
            o = input()
            if o == '1':
                self.create_cita()
            elif o == '2':
                self.read_a_cita()
            elif o == '3':
                self.read_all_citas()
            elif o == '4':
                self.read_citas_asunto()
            elif o == '5':
                self.read_cita_fecha()
            elif o == '6':
                self.update_cita()
            elif o == '7':
                self.delete_cita()
            elif o == '8':
                self.create_detalles_cita()
            elif o == '9':
                self.read_contactos_cita()
            elif o == '10':
                self.read_citas_contacto()
            elif o == '11':
                self.update_detalles_cita()
            elif o == '12':
                self.delete_usuario_cita()
            elif o == '13':
                self.main_menu()
                return
            else:
                self.view.not_valid_option()
        return

    def ask_cita(self):
        self.view.ask('Lugar: ')
        lugar = input()
        self.view.ask('Ciudad: ')
        ciudad = input()
        self.view.ask('Estado: ')
        estado = input()
        self.view.ask('Fecha: ')
        fecha = input()
        self.view.ask('Asunto: ')
        asunto = input()
        return [lugar, ciudad, estado, fecha, asunto]

    def create_cita(self):
        lugar, ciudad, estado, fecha, asunto = self.ask_cita()
        out = self.model.create_cita(lugar, ciudad, estado, fecha, asunto)
        # id_cita = self.read_a_cita(asunto)
        if out == True:
            self.view.ok(lugar + ' ' + fecha + ' ' + asunto, 'agrego')
        else:
            self.view.error('NO SE PUDO AGREGAR LA CITA. REVISA')
        return

    def read_a_cita(self):
        self.view.ask('ID cita: ')
        id_cita = input()
        cita = self.model.read_a_cita(id_cita)
        if type(cita) == tuple:
            self.view.show_cita_header(' Datos de la cita ' + id_cita + ' ')
            self.view.show_a_cita(cita)
            self.view.show_cita_midder()
            self.view.show_cita_footer()
        else:
            if cita == None:
                self.view.error('LA CITA NO EXISTE')
            else:
                self.view.error('PROBLEMA AL LEER LA CITA. REVISA')
        return

    def read_all_citas(self):
        citas = self.model.read_all_citas()
        if type(citas) == list:
            self.view.show_cita_header(' Todas las citas ')
            for cita in citas:
                self.view.show_a_cita(cita)
                self.view.show_cita_midder()
            self.view.show_cita_footer()
        else:
            self.view.error('PROBLEMA AL LEER LAS CITAS. REVISA')
        return

    def read_citas_asunto(self):
        self.view.ask('Asunto: ')
        asunto = input()
        citas = self.model.read_citas_asunto(asunto)
        if type(citas) == list:
            self.view.show_cita_header(' Asunto de la cita ' + asunto + ' ')
            for cita in citas:
                self.view.show_a_cita(cita)
                self.view.show_cita_midder()
            self.view.show_cita_footer
        else:
            self.view.error('PROBLEMA AL LEER LAS CITAS. REVISA')
        return

    def read_cita_fecha(self):
        self.view.ask('Fecha: ')
        fecha = input()
        citas = self.model.read_cita_fecha(fecha)
        if type(citas) == list:
            self.view.show_cita_header(' Fecha: ' + fecha + ' ')
            for cita in citas:
                self.view.show_a_cita(cita)
                self.view.show_cita_midder()
            self.view.show_cita_footer()
        else:
            self.view.error('PROBLEMA AL LEER La CITA. REVISA')
        return

    def update_cita(self):
        self.view.ask('ID de cita a modificar: ')
        id_cita = input()
        cita = self.model.read_a_cita(id_cita)
        if type(cita) == tuple:
            self.view.show_cita_header(' Datos del producto ' + id_cita + ' ')
            self.view.show_a_cita(cita)
            self.view.show_cita_midder()
            self.view.show_cita_footer()
        else:
            if cita == None:
                self.view.error('LA CITA NO EXISTE')
            else:
                self.view.error('PROBLEMA AL LEER LAS CITAS. REVISA')
            return
        self.view.msg(
            'Ingresa los valores a modificar (vacio para dejarlo igual): ')
        whole_vals = self.ask_cita()
        fields, vals = self.update_lists(
            ['c_lugar', 'c_ciudad', 'c_estado', 'c_fecha', 'c_asunto'],
            whole_vals)
        vals.append(id_cita)
        vals = tuple(vals)
        out = self.model.update_cita(fields, vals)
        if out == True:
            self.view.ok(id_cita, 'actualizo')
        else:
            self.view.error('NO SE PUDO ACTUALIZAR LA CITA. REVISA')
        return

    def delete_cita(self):
        self.view.ask('Id de la cita a borrar: ')
        id_cita = input()
        count = self.model.delete_cita(id_cita)
        if count != 0:
            self.view.ok(id_cita, 'borro')
        else:
            if count == 0:
                self.view.error('LA CITA NO EXISTE')
            else:
                self.view.error('PROBLEMA AL BORRAR LA CITA. REVISA.')
        return

    """
    ***********************************
    *   Controllers for Contactos     *
    ***********************************
    """

    def contacto_menu(self):
        o = '0'
        while o != '6':
            self.view.contacto_menu()
            self.view.option('6')
            o = input()
            if o == '1':
                self.create_contacto()
            elif o == '2':
                self.read_a_contacto()
            elif o == '3':
                self.read_all_contactos()
            elif o == '4':
                self.update_contacto()
            elif o == '5':
                self.delete_contacto()
            elif o == '6':
                self.main_menu()
                return
            else:
                self.view.not_valid_option()
        return

    def ask_contacto(self):
        self.view.ask('Nombre: ')
        name = input()
        self.view.ask('Apellido paterno: ')
        apellidoP = input()
        self.view.ask('Apellido materno: ')
        apellidoM = input()
        self.view.ask('Calle: ')
        calle = input()
        self.view.ask('No. exterior: ')
        noext = input()
        self.view.ask('No interior: ')
        noint = input()
        self.view.ask('Colonia: ')
        col = input()
        self.view.ask('Ciudad: ')
        ciudad = input()
        self.view.ask('Estado: ')
        estado = input()
        self.view.ask('Email: ')
        email = input()
        self.view.ask('Telefono: ')
        phone = input()
        return [
            name, apellidoP, apellidoM, calle, noext, noint, col, ciudad,
            estado, email, phone
        ]

    def create_contacto(self):
        name, apellidoP, apellidoM, calle, noext, noint, col, ciudad, estado, email, phone = self.ask_contacto(
        )
        out = self.model.create_contacto(name, apellidoP, apellidoM, calle,
                                         noext, noint, col, ciudad, estado,
                                         email, phone)
        if out == True:
            self.view.ok(name + ' ' + apellidoP + ' ' + apellidoM, 'agrego')
        else:
            self.view.error('NO SE PUDO AGREGAR EL CONTACTO. REVISA')
        return

    def read_a_contacto(self):
        self.view.ask('ID Contacto: ')
        id_contacto = input()
        contacto = self.model.read_a_contacto(id_contacto)
        if type(contacto) == tuple:
            self.view.show_contacto_header(' Datos del contacto ' +
                                           id_contacto + ' ')
            self.view.show_a_contacto(contacto)
            self.view.show_contacto_midder()
            self.view.show_contacto_footer()
        else:
            if contacto == None:
                self.view.error('EL CONTACTO NO EXISTE')
            else:
                self.view.error('PROBLEMA AL LEER EL CONTACTO. REVISA')
        return

    def read_all_contactos(self):
        contactos = self.model.read_all_contactos()
        if type(contactos) == list:
            self.view.show_contacto_header(' Todos los contacto ')
            for contacto in contactos:
                self.view.show_a_contacto(contacto)
                self.view.show_contacto_midder()
            self.view.show_contacto_footer()
        else:
            self.view.error('PROBLEMA AL LEER LOS CONTACTOS. REVISA')
        return

    def update_contacto(self):
        self.view.ask('ID de contacto a modificar: ')
        id_contacto = input()
        contactos = self.model.read_a_contacto(id_contacto)
        if type(contactos) == tuple:
            self.view.show_contacto_header(' Datos del contacto ' +
                                           id_contacto + ' ')
            self.view.show_a_contacto(contactos)
            self.view.show_contacto_midder()
            self.view.show_contacto_footer()
        else:
            if contactos == None:
                self.view.error('EL CONTACTO NO EXISTE')
            else:
                self.view.error('PROBLEMA AL LEER EL CONTACTO. REVISA')
            return
        self.view.msg(
            'Ingresa los valores a modificar (vacio para dejarlo igual): ')
        whole_vals = self.ask_contacto()
        fields, vals = self.update_lists([
            'c_nombre', 'c_apellidoP', 'c_apellidoM', 'c_calle', 'c_noext',
            'c_noint', 'c_col', 'c_ciudad', 'c_estado', 'c_email', 'c_telefono'
        ], whole_vals)
        vals.append(id_contacto)
        vals = tuple(vals)
        out = self.model.update_contacto(fields, vals)
        if out == True:
            self.view.ok(id_contacto, 'actualizo')
        else:
            self.view.error('NO SE PUDO ACTUALIZAR EL CONTACTO. REVISA')
        return

    def delete_contacto(self):
        self.view.ask('ID de contacto a borrar: ')
        id_contacto = input()
        count = self.model.delete_contacto(id_contacto)
        if count != 0:
            self.view.ok(id_contacto, 'borro')
        else:
            if count == 0:
                self.view.error('EL CONTACTO NO EXISTE')
            else:
                self.view.error('PROBLEMA AL BORRAR EL CONTACTO. REVISA')
        return

    """
    **************************************
    *   Controllers for Detalles-Cita    *
    **************************************
    """

    def create_detalles_cita(self):
        self.read_all_citas()
        self.view.ask('ID cita: ')
        id_cita = input()
        if id_cita != '':
            cita = self.model.read_a_cita(id_cita)
            if type(cita) == tuple:
                self.view.show_cita_header(' Datos de la cita ' + id_cita +
                                           ' ')
                self.view.show_a_cita(cita)
                self.view.show_cita_footer()
                self.view.ask('Cita: ')
                nombre = input()
                self.view.ask('Notas: ')
                descripcion = input()
                self.read_all_contactos()
                self.view.ask('ID contacto: ')
                id_contacto = input()
                if id_contacto != '':
                    contacto = self.model.read_a_contacto(id_contacto)
                    self.view.show_contacto_header(' Datos del contacto ' +
                                                   id_contacto + ' ')
                    self.view.show_a_contacto(contacto)
                    self.view.show_contacto_midder()
                    self.view.show_contacto_footer()
                    if type(contacto) == tuple:
                        out = self.model.create_detalles_cita(
                            id_cita, id_contacto, nombre, descripcion)
                        if out == True:
                            self.view.ok(contacto[1], 'Agrego')
                        else:
                            if out.errno == 1062:
                                self.view.error(
                                    'LA CITA YA NO ESTA PROGRAMADA')
                            else:
                                self.view.error(
                                    'NO SE PUDO AGREGAR LA CITA. REVISA')
                    else:
                        if contacto == None:
                            self.view.error('EL CONTACTO NO EXISTE')
                        else:
                            self.view.error(
                                'NO SE PUDO AGREGAR EL CONTACTO. REVISA')
                else:
                    if cita == None:
                        self.view.error('LA CITA NO EXISTE')
                    else:
                        self.view.error('NO SE PUDO AGREGAR LA CITA. REVISA')
            else:
                if cita == None:
                    self.view.error('LA CITA NO EXISTE')
                else:
                    self.view.error('PROBLEMA AL LEER LA CITA. REVISA')
        return

    def read_contactos_cita(self):
        self.view.ask('ID Cita: ')
        id_cita = input()
        contacto_cita = self.model.read_contactos_cita(id_cita)
        if type(contacto_cita) == list:
            self.view.show_contacto_cita_header('Usuarios dentro de Cita')
            for contacto in contacto_cita:
                self.view.show_a_contacto(contacto)
                self.view.show_contacto_midder()
            self.view.show_contacto_footer()
        else:
            if contacto_cita == None:
                self.view.error('LA CITA NO TIENE CONTACTOS')
            else:
                self.view.error(
                    'PROBLEMA AL LEER EL CONTACTO CON CITA. REVISA')
        return

    def read_citas_contacto(self):
        self.view.ask('ID Contacto: ')
        id_contacto = input()
        contactos_citas = self.model.read_citas_contacto(id_contacto)
        if type(contactos_citas) == list:
            self.view.show_contacto_cita_header(
                ' Todas la Citas para el contacto ')
            for cita in contactos_citas:
                self.view.show_a_cita(cita)
                self.view.show_cita_midder()
            self.view.show_cita_footer()
        else:
            self.view.error('PROBLEMA AL LEER LOS CONTACTOS Y CITAS. REVISA')
        return

    def ask_detalles_cita(self):
        self.view.ask('Nombre de Cita: ')
        nombre = input()
        self.view.ask('Nota: ')
        descripcion = input()
        return [nombre, descripcion]

    def update_detalles_cita(self):
        self.view.ask('ID de la cita a modificar: ')
        id_cita = input()
        cita = self.model.read_detalles_cita(id_cita)
        if type(cita) == tuple:
            self.view.show_cita_header('Detalles_Cita')
            self.view.show_a_detalles_cita(cita)
            self.view.show_contacto_cita_midder()
            self.view.show_contacto_cita_footer()
        else:
            if cita == None:
                self.view.error('La cita no existe')
            else:
                self.view.error('PROBLEMA AL LEER LA CITA. REVISA')
            return
        self.view.msg(
            'Ingresa los valores a modificar (vacio para dejarlo igual): ')
        whole_vals = self.ask_detalles_cita()
        fields, vals = self.update_lists(['nombre', 'descripcion'], whole_vals)
        vals.append(id_cita)
        vals = tuple(vals)
        print('vals', vals)
        print('fiels', fields)
        out = self.model.update_detalles_cita(fields, vals)
        print(out)
        if out == True:
            self.view.ok(id_cita, 'actualizo')
        else:
            self.view.error(
                'NO SE PUDO ACTUALIZAR EL CONTACTO CON LA CITA. REVISA')
        return

    def delete_usuario_cita(self):
        self.view.ask('ID de la cita a borrar contactos: ')
        id_cita = input()
        contacto_cita = self.model.read_contactos_cita(id_cita)
        contacto_cita = self.model.read_contactos_cita(id_cita)
        self.view.show_contacto_cita_header('Usuarios dentro de Cita')
        for contacto in contacto_cita:
            self.view.show_a_contacto(contacto)
            self.view.show_contacto_midder()
        self.view.show_contacto_footer()
        self.view.ask('ID del contacto a eliminar: ')
        id_contacto = input()
        count = self.model.delete_detalles_cita(id_cita, id_contacto)
        if count != 0:
            self.view.ok(id_contacto, 'borro')
        else:
            if count == 0:
                self.view.error('ERROR NO SE PUDO ELIMINAR')
            else:
                self.view.error(
                    'PROBLEMA AL BORRAR LA CITA DEL CONTACTO. REVISA')
        return
コード例 #17
0
class GameController(object):
	
	def __init__(self):
		# Make the configManager.
		# The configManager means that all the settings are grabbed at once.
		# This will prevent the settings being changed mid way through genereation/simulation and messing things up.
		self.configManager = ConfigManager()

		self.fpsClock = pygame.time.Clock()

		# The view controller handles the two displaysurfaces that make up the game window.
		self.viewController = ViewController(self.configManager)

		# Creates a new Model and generates the world.
		self.newGame()

		# Amount of logic frames per second.
		LOGIC_UPDATES_PER_SECOND = 1
		self.SKIP_TICKS = 1000 / LOGIC_UPDATES_PER_SECOND
		self.MAX_FRAMESKIP = 10

	def main(self):
		self.buttonsPressed = defaultdict(lambda: False)

		# How long since pygame was inited
		# Used to keep track of how long it has been since the last draw.
		nextGameTick = pygame.time.get_ticks()

		while True:
			# Logic loop parameter.
			loops = 0
			# Seperate the game logic up from the game display. This means the slow update speed
			# of the model updating doesn't harm our ability to look around the world.
			while pygame.time.get_ticks() > nextGameTick and loops < self.MAX_FRAMESKIP:
				self.updateModel()

				nextGameTick += self.SKIP_TICKS
				loops += 1

			for event in pygame.event.get():
				if event.type == QUIT:
					pygame.quit()
					sys.exit()
				elif event.type == MOUSEBUTTONUP:
					# Pixel co-ordinates of click.
					mousex, mousey = event.pos
					
					clickedCell = self.viewController.getClickedCell((mousex, mousey))

					if clickedCell:
						self.model.world.setFocusCell(clickedCell)
					else:
						print "Clicked outside game view"
				elif event.type == KEYDOWN and event.key == K_n:
					self.buttonsPressed['regenWorld'] = True
				elif event.type == KEYDOWN and event.key == K_y:
					self.buttonsPressed['confirmKey'] = True
				elif event.type == KEYDOWN and event.key == K_p:
					self.buttonsPressed['pauseKey'] = True

			self.handleInput()

			self.updateView(self.model)


	def newGame(self):
		# Push world generation along one stage at a time. After each stage we redraw the game window.
		# This lets the player watch the world get generated.
		self.model = Model(self.configManager)
		self.updateView(self.model)
		self.fpsClock.tick(self.configManager.FPS)

		while not self.model.world.worldGenDone:
			self.model.world.createWorldStep()
			self.updateView(self.model)
        	self.fpsClock.tick(self.configManager.FPS)

	def updateView(self, model, updateUI = False):
		self.configManager.currentFPS = str(int(self.fpsClock.get_fps()))

		self.viewController.updateView(model)
		self.fpsClock.tick(self.configManager.FPS)

	def updateModel(self):
		self.model.updateWorld()

	def handleInput(self):
		if self.buttonsPressed['regenWorld']:
			self.regenWorld()
			self.buttonsPressed['regenWorld'] = False
		
		if self.buttonsPressed['confirmKey'] and not self.model.villagePlaced:
			self.placeVillage()
			self.buttonsPressed['confirmKey'] = False

		if self.buttonsPressed['pauseKey'] and self.model.villagePlaced:
			self.model.gamePaused = not self.model.gamePaused
			self.buttonsPressed['pauseKey'] = False

	def regenWorld(self):
		self.configManager.regenSeed()
		self.newGame()

	def placeVillage(self):
		self.model.placeVillage()
		self.model.villagePlaced = True
コード例 #18
0
for i, name in enumerate(file_names):
    labels[i] = np.eye(10)[int(name.split('/')[-2])]


def read(addresses):
    X = []
    for address in addresses:
        im = cv2.cvtColor(cv2.imread(address), cv2.COLOR_BGR2GRAY)
        im = im[:, :, np.newaxis]
        im = im / 255.0
        # im = im.reshape(-1)
        X.append(im)

    return np.array(X)


train_ds = Dataset(file_names, labels, 8, True, read)

nn = Model((28, 28, 1))
nn.add(Conv(5, 6, 1, 'same', 'relu'))
nn.add(BatchNorm(0.9))
# nn.add(MaxPool(2))
nn.add(Conv(5, 16, 1, 'same', 'relu'))

nn.add(Flatten())
nn.add(Dense(84, 'relu'))
nn.add(BatchNorm(0.9))
nn.add(Dense(10, 'linear'))

nn.train(1e-4, train_ds, 10, 'softmax_cross_entropy_with_logits')
コード例 #19
0
ファイル: Source.py プロジェクト: gradzka/NeuralPoker
# # Uncomment to generate sets
# from Sets.SetGenerator import SetGenerator
# generator = SetGenerator()
# generator.generate_sets(2)

# from Sets.SetImporter import SetImporter
# from Sets.SetGenerator import SetGenerator
from Model.Model import Model

all_cards_no = 5
# train_set = SetImporter("{}/poker-hand-{}-{}.data".format(SetGenerator.dir_path, "training", all_cards_no),
# all_cards_no)
# test_set = SetImporter("{}/poker-hand-{}-{}.data".format(SetGenerator.dir_path, "test", all_cards_no), all_cards_no)

# model = Model(train_set)
model = Model()
# neurons_in_hidden_layer = 28
# model.create(neurons_in_hidden_layer)
model.load("{}/model-{}".format(Model.dir_path, all_cards_no), all_cards_no)
# model.train()
# model.save("{}/model-{}".format(Model.dir_path, all_cards_no))
# model.test(test_set)
print(model.predict(['Qs', 'Qh', 'Qd', 'Kc', 'Kh']))
コード例 #20
0
ファイル: main.py プロジェクト: alex-ong/TFRevolution
async def main():
    m = Model()
    v = View()
    c = Controller(m, v)

    await run_tk(v, c)
コード例 #21
0
ファイル: cats_dogs.py プロジェクト: Atom-101/NumPyML
    X = []
    for address in addresses:
        im = cv2.cvtColor(
            cv2.resize(cv2.imread(address), (32, 32),
                       interpolation=cv2.INTER_AREA), cv2.COLOR_BGR2GRAY)
        im = im[:, :, np.newaxis]
        im = im / 255.0
        # im = im.reshape(-1)
        X.append(im)

    return np.array(X)


train_ds = Dataset(file_names, labels, 8, True, read)

nn = Model((32, 32, 1))
# nn.add(Conv(7,32,1,'same','relu'))
# nn.add(BatchNorm(0.9))
# nn.add(Conv(3,64,1,'same','relu'))
# nn.add(BatchNorm(0.9))
# nn.add(MaxPool(2))

# nn.add(Conv(5,128,1,'same','relu'))
# nn.add(BatchNorm(0.9))
# nn.add(Conv(3,128,1,'same','relu'))
# nn.add(BatchNorm(0.9))
# nn.add(MaxPool(2))

# nn.add(Conv(1,32,2,'valid','relu'))

# nn.add(Flatten())
コード例 #22
0
 def __init__(self, root):
     self.model = Model()
     #    self.model.myMoney.addCallback(self.MoneyChanged)
     self.view1 = View(root)
コード例 #23
0
def main():
    model = Model()
    controller = Controller(model, 'dataset')

    root = tk.Tk()
    ui = UI(root, "Aggressivity Detection - A Security Tool", controller)
コード例 #24
0
ファイル: Controller.py プロジェクト: piastu/Patterns17
 def __init__(self):
     self.__view = ConsoleView(self)
     self.__config_db = None
     self.__classifier_types = None
     self.__init_configs()
     self.__model = Model(self.__config_db)
コード例 #25
0
ファイル: main_app.py プロジェクト: LEDS/Lifebox
 def __init__(self, sys_argv):
     super(App, self).__init__(sys_argv)
     self.model = Model()
     self.main_ctrl = Control()
     self.main_view = MainWindow(self.model, self.main_ctrl)
     self.main_view.show()
コード例 #26
0
 def __init__(self):
     self.view = MainView(self)
     self.model = Model()
コード例 #27
0
 def on_clear_button_click(self):
     self.__init__(model=Model(), view=View())
コード例 #28
0
 def __init__(self):
     self.model = Model()
     self.view = View()