Exemple #1
0
def init_game():
    if os.path.exists('saved.txt'):
        win = open('saved.txt', 'r')
        win_res = []
        for i in win.readlines():
            diff = i.split('\n')
            win_res.append(diff[0])
        if not win_res:
            cont = controller.Controller(10, 10, 20, 'E')
        else:
            difficulty = win_res[0]
            cont = controller.Controller(
                *{
                    'E': (10, 10, 20, difficulty),
                    'M': (15, 15, 40, difficulty),
                    'H': (20, 20, 60, difficulty)
                }[difficulty[0]])
            if win_res[0] == 'E':
                cont.load_all(win_res[1:11], win_res[11], win_res[12],
                              win_res[13])
            if win_res[0] == 'M':
                cont.load_all(win_res[1:16], win_res[16], win_res[17],
                              win_res[18])
            if win_res[0] == 'H':
                cont.load_all(win_res[1:21], win_res[21], win_res[22],
                              win_res[23])
    else:
        cont = controller.Controller(10, 10, 20, 'E')
    cont.view.show()
Exemple #2
0
def get_controller( args ) :

    l = args[ 'lesson' ]
    t = args[ 'tonic' ]
    e = args[ 'evaluate' ]
    
    if '' == l :
        if e :
            raise NameError( 'No --lesson to evaluate on.' )
        ret = controller.Controller( t, '', False )
    else :
        ret = controller.Controller( t, l, e )
        
    return ret
Exemple #3
0
 def __init__(self,
              my_node,
              conf_path,
              routing_m_mod,
              lookup_m_mod,
              experimental_m_mod,
              private_dht_name,
              debug_level,
              bootsrap_mode=False,
              swift_port=0):
     logging_conf.setup(conf_path, debug_level)
     state_filename = os.path.join(conf_path, controller.STATE_FILENAME)
     self.controller = controller.Controller(
         VERSION_LABEL, my_node, state_filename, routing_m_mod,
         lookup_m_mod, experimental_m_mod, private_dht_name, bootsrap_mode)
     self.reactor = minitwisted.ThreadedReactor(
         self.controller.main_loop, my_node.addr[1],
         self.controller.on_datagram_received)
     self.reactor.start()
     self.swift_tracker_thread = None
     if swift_port:
         print 'Creating SwiftTracker'
         self.swift_tracker_thread = swift_tracker.SwiftTracker(
             self, swift_port)
         self.swift_tracker_thread.start()
     self.timestamps = []
     self.max_num_sec = 0
     self.max_num_min = 0
     self.max_num_10min = 0
Exemple #4
0
    def __init__(self, progName = ''):
        """ Load program (not doing anything yet),
            and fill default command list """

        # setup logging
        logging.basicConfig(filename='../logs/AR2.warning.log', level=logging.WARNING)
        logging.basicConfig(filename='../logs/AR2.debug.log',   level=logging.DEBUG)
        logging.basicConfig(filename='../logs/AR2.info.log',    level=logging.INFO)

        # load protocol
        fileID = open('../conf/conf_commands.csv')
        csvID  = csv.reader(fileID, delimiter=',')

        self._commands = {}
        for row in csvID:
            new_cmd = ProgramLine(int(row[0]), row[2], row[1], '', '')
            self._commands[row[1]] = new_cmd

        # initialise program
        self.program_name = progName
        self.program = program.Program()

        # setup controller
        self.number_of_joints = 6
        self.controller = controller.Controller(self.number_of_joints)
Exemple #5
0
def inittializeControllers():
    for address in settings.topologyAddresses:
        controllers[address] = c.Controller(address)

    counter = 0
    totalControllers = 4
    for controller, v in collections.OrderedDict(sorted(
            controllers.items())).items():
        n1 = counter - 1
        n2 = counter + 1
        if n2 >= totalControllers:
            n2 = 0
        # print(n1, n2)
        # print(v.controllerAddress)
        v.setNeighbours([
            controllers[settings.topologyAddresses[n1]],
            controllers[settings.topologyAddresses[n2]]
        ])
        counter = counter + 1
        #v.calculateBorderGateways()
        #v.resolvePathByDomain(controllers["10.2.2.130"], "3.5", "4.7")

        #print(v.getSwitchPorts())
        #print(controllers[settings.topologyAddresses[n1]].getSwitchPorts())
        #print(v)
        #print(settings.topologyAddresses[n1], settings.topologyAddresses[n2])
        #print("|||||||||||||||||||||||||||||||||||||||||||||||||")

    print("neighbours...")
    paths = controllers["10.2.2.128"].resolvePathByDomain(
        controllers["10.2.2.128"], controllers["10.2.2.128"], "2.1", "3.6", [])
Exemple #6
0
 def __init__(self):
     datamodel.initModel()
     appconst.GLADE_PATH = op.join(appconst.PATHS['share'], 'ui',
                                   appconst.GLADE_FILE)
     appconst.UI_PATH = appconst.PATHS['share']
     self.controller = controller.Controller()
     self.mainWindow = MainWindow(self.controller)
Exemple #7
0
    def __init__(self, profile_name=None):
        storage_provider = storage.PickleProvider()
        storage_factory = storage.Factory(storage_provider)

        monitors_repository = monitors.Repository()
        hardware_inventory = hardware.Inventory()
        device_matcher = hardware.DeviceMatcher()
        plugin_instance_factory = plugins.instance.Factory()

        plugins_repository = plugins.Repository(monitors_repository,
                                                storage_factory,
                                                hardware_inventory,
                                                device_matcher,
                                                plugin_instance_factory)
        unit_manager = units.Manager(plugins_repository, monitors_repository)

        profile_factory = profiles.Factory()
        profile_merger = profiles.Merger()
        profile_locator = profiles.Locator(consts.LOAD_DIRECTORIES)
        profile_loader = profiles.Loader(profile_locator, profile_factory,
                                         profile_merger)

        self._daemon = daemon.Daemon(unit_manager, profile_loader,
                                     profile_name)
        self._controller = controller.Controller(self._daemon)

        self._dbus_exporter = None
        self._init_signals()

        self._pid_file = None
Exemple #8
0
 def __init__(self):
     self.date_format = '%Y-%m-%d'
     self.curr_session = Session()
     self.curr_importer = importer.Importer(self.curr_session)
     self.curr_importer.db_init()
     self.curr_controller = controller.Controller(self.curr_session)
     self.parser = argparse.ArgumentParser()
Exemple #9
0
	def __init__(self, profile_name = None, config = None):
		self._dbus_exporter = None

		storage_provider = storage.PickleProvider()
		storage_factory = storage.Factory(storage_provider)

		monitors_repository = monitors.Repository()
		hardware_inventory = hardware.Inventory()
		device_matcher = hardware.DeviceMatcher()
		device_matcher_udev = hardware.DeviceMatcherUdev()
		plugin_instance_factory = plugins.instance.Factory()
		self.variables = profiles.variables.Variables()

		self.config = GlobalConfig() if config is None else config
		if self.config.get_bool(consts.CFG_DYNAMIC_TUNING):
			log.info("dynamic tuning is enabled (can be overriden in plugins)")
		else:
			log.info("dynamic tuning is globally disabled")

		plugins_repository = plugins.Repository(monitors_repository, storage_factory, hardware_inventory,\
			device_matcher, device_matcher_udev, plugin_instance_factory, self.config, self.variables)
		def_instance_priority = int(self.config.get(consts.CFG_DEFAULT_INSTANCE_PRIORITY, consts.CFG_DEF_DEFAULT_INSTANCE_PRIORITY))
		unit_manager = units.Manager(plugins_repository, monitors_repository, def_instance_priority)

		profile_factory = profiles.Factory()
		profile_merger = profiles.Merger()
		profile_locator = profiles.Locator(consts.LOAD_DIRECTORIES)
		profile_loader = profiles.Loader(profile_locator, profile_factory, profile_merger, self.config, self.variables)

		self._daemon = daemon.Daemon(unit_manager, profile_loader, profile_name, self.config, self)
		self._controller = controller.Controller(self._daemon, self.config)

		self._init_signals()

		self._pid_file = None
Exemple #10
0
 def openFile(self):
     widgetFO = QtWidgets.QWidget()
     filename = QtWidgets.QFileDialog.getOpenFileName(
         widgetFO, 'Open File', '~', "Audio *.wav files (*.wav)")
     widgetFO.show()
     global inputAudioFileName
     inputAudioFileName = filename[0]
     #check  exist file
     if ((len(filename[0])) > 0):
         try:
             file = open(inputAudioFileName)
         except IOError as e:
             print(u'не удалось открыть файл. Причина: ' + str(e))
             widgetMB = QtWidgets.QWidget()
             QtWidgets.QMessageBox.about(widgetMB, "Ошибка",
                                         "Не удалось открыть файл!")
         else:
             with file:
                 #dialog
                 self.labelFileNameValue.setText(inputAudioFileName)
                 print(filename[0])
                 self.contr = controller.Controller(filename[0])
                 integratedLoudnessValue, luValue, rmsPeak = self.contr.getAudioInfo(
                 )
                 #self.label_LUvalue.setText(luValue)
                 self.lufsWidget.setPos(float(integratedLoudnessValue))
                 self.label_LUFSvalue.setText(integratedLoudnessValue)
                 self.label_RMSvalue.setText(rmsPeak)
Exemple #11
0
 def __init__(self,
              my_node,
              conf_path,
              routing_m_mod,
              lookup_m_mod,
              experimental_m_mod,
              private_dht_name,
              debug_level,
              auto_bootstrap=True,
              bootstrap_mode=False,
              swift_port=0):
     logging_conf.setup(conf_path, debug_level)
     self.controller = controller.Controller(
         VERSION_LABEL, my_node, conf_path, routing_m_mod, lookup_m_mod,
         experimental_m_mod, private_dht_name, bootstrap_mode)
     self.reactor = minitwisted.ThreadedReactor(
         self.controller.main_loop, my_node.addr[1],
         self.controller.on_datagram_received)
     if swift_port:
         print 'Creating SwiftTracker'
         swift_tracker.SwiftTracker(self, swift_port).start()
     self.timestamps = []
     self.max_num_sec = 0
     self.max_num_min = 0
     self.max_num_10min = 0
     if auto_bootstrap:
         # Overlay bootstrap
         self.get_peers(None, self.controller._my_id, None, 0)
     self.reactor.start()
Exemple #12
0
def motor_2 ():
    ''' Define a task to run both motors in order. Configure the motor using the motor_driver.py file. Print the data to the serial port and plot the data in pc_main_lab3'''

    # call class MotorDriver()
    motor_2 = motor_driver.MotorDriver('C1', 20000)

    # call class Controller()
    ctr_2 = controller.Controller(0.01, 16000, 30)

    ## define the encoder that is used to read the motor position
    encC = enc.Encoder('C')

    # define x to be True to collect half of the data points an allow more time for printing data
    x = True

    while True:
        # initialize the motor controller using class Controller()
        motor_2.set_duty_cycle(ctr_2.outputValue(encC.read()))

        # create a string of data to be plotted
        data = '2, ' + str(encC.read()) + ', ' + str(utime.ticks_ms()) + '\r\n'

        # print data every other pass through the while loop
        if x == True:
            print_task.put (data)
        x = not x

        # yield to another task and resume at this line
        yield (0)
Exemple #13
0
    def start_run(self, **params):

        if self._controller and self._controller.is_active:
            raise ValueError('Run in progress')

        pid_const_names = (
            'prop',
            'integral',
            'bias',
        )
        pid_constants = {k: run_param(params, k) for k in pid_const_names}
        run = attrdict.AttrDict(
            id=str(uuid.uuid4()),
            pid_constants=attrdict.AttrDict(**pid_constants),
            notes=run_param(params, 'notes'),
            target=run_param(params, 'target'),
            ramp_up_target=run_param(params, 'ramp_up'),
            start_time=datetime.datetime.now(),
            end_time=None,
            state=model.INITIALIZED,
        )
        self._run = run
        self._controller = controller.Controller(self._run, self._loggers)

        if self.is_daemon:
            thread.start_new_thread(self._controller.control, ())
        else:
            self._controller.control()
Exemple #14
0
def motor_1 ():
    ''' Define a task to run both motors in order. Configure the motor using the motor_driver.py file. Print the data to the serial port and plot the data in pc_main_lab3'''

    # call class MotorDriver()
    motor = motor_driver.MotorDriver('A10', 20000)

    # call class Controller()
    ctr = controller.Controller(0.01, 16000, 30)
    
    ## define the encoder that is used to read the motor position
    encB = enc.Encoder('B')
    
    # run the proportional contorller on the motor and feed the data into the shares and queues using put()
    x = True
    while True:

        # set the motor duty cycle using class Controller()
        motor.set_duty_cycle(ctr.outputValue(encB.read()))

        # create a string of data to be plotted
        data = '1, ' + str(encB.read()) + ', ' + str(utime.ticks_ms()) + '\r\n'

        # print data every other pass through the while loop
        if x == True:
            print_task.put (data)

        # yield to another task and resume at this line
        yield (0)
Exemple #15
0
    def onInit(self):
	self.log("Screensaver starting")
        
        self.addon      = xbmcaddon.Addon(scriptId)
        if (self.addon.getSetting('setting_show_seconds') in ['false', 'False']):
            self.showSeconds = False
        else:
	    self.showSeconds = True
	if (self.addon.getSetting('setting_show_random_sec') in ['false', 'False']):
	    self.randSec = False
	else:
	    self.randSec = True        
        if (self.addon.getSetting('setting_show_random_hourmin') in ['false', 'False']):
            self.randHourMin = False
        else:
            self.randHourMin = True
        self.redrawInterval = int(self.addon.getSetting('setting_redraw_interval'))
	self.hour1Color = (self.addon.getSetting('setting_color_col_1')+".png").lower()
	self.hour2Color = (self.addon.getSetting('setting_color_col_2')+".png").lower()
	self.min1Color = (self.addon.getSetting('setting_color_col_3')+".png").lower()
	self.min2Color = (self.addon.getSetting('setting_color_col_4')+".png").lower()
	self.secondsColor = (self.addon.getSetting('setting_color_col_5')+".png").lower()	
	self.monitor = self.ExitMonitor(self.exit, self.log)
	self.allImages = list()
	self.topX = 20
        self.topY = 20
        
        #self.log(addon_path)

        self.showClock(False)
        self.cont = controller.Controller(self.log, self.showClock, self.showSeconds, self.redrawInterval)
        self.cont.start() 
Exemple #16
0
def main():
    """
    Launch app from command line
    """
    parser = argparse.ArgumentParser(description='Start the metric monitor.')

    parser.add_argument("-c",
                        "--config",
                        type=str,
                        default="conf/local.cfg",
                        help="The configuration file to use")

    args = parser.parse_args()

    # Start up the controller
    config = TheoriaConfig()
    config.read(['conf/default.cfg', args.config])
    ctrlr = controller.Controller(config)
    ctrlr.start()

    print 'Theoria started. Type CTRL-C to Exit.'

    done = False
    while not done:
        try:
            ctrlr.join(1)
        except KeyboardInterrupt:
            done = True
            ctrlr.quit()

    print 'Theoria Exiting.'

    return 0
Exemple #17
0
 def test_hours_filter(self):
     control = controller.Controller('../data/sample.csv',
                                     '../data/paths0.png')
     self.assertEquals(
         control.hours_filter(datetime.time(int(1), int(27), int(9)),
                              datetime.time(int(1), int(28),
                                            int(19))).shape[0], 16)
Exemple #18
0
    def __init__(self):
        # Queue for data thread safe
        self.data = queue.LifoQueue()
        self.control_data = queue.LifoQueue()

        # Create thread lock
        # self.lock = threading.Lock()

        # stop thread variable
        self.stop = False

        # variable to prevent multiple solutions form running
        self.solving = False

        # Create thread parameters
        self.MPC_thread = threading.Thread(target=self.run, args=(), daemon=True)

        # Controller state to pass into get_output function
        self.controllerState = con.Controller()

        # Optimal Control data updated by thread
        self.u_pitch_star = 0.0
        self.u_star = 0.0


        # time.sleep(1)
        # self.MPC_queue.put('worked')

        # Initialize optimization parameters
        self.initialize_optimization()
Exemple #19
0
 def test_drow(self):
     control = controller.Controller('../data/sample.csv',
                                     '../data/paths0.png')
     control.draw_lines([([30, 100, 150, 200, 250], [30, 40, 60, 90, 150]),
                         ([350, 300], [30, 50]), ([400, 300], [30, 100]),
                         ([250, 150], [30, 50]), ([100, 250], [30, 50])],
                        False)
Exemple #20
0
def main():
    """#############################################################################################
    Program:    DIARY PRINT

    Files:    main.py, controller.py, view.py, model.py, db_days, create_table_days.sql, 
              week_backward.png, week_forward.png, week_ home.pgn, diary.css.
        
    Description:    Prints personal diary files in html

    Author:    Pekka Paldánius (PP)

    Environments:    Linux Z87MPlus 3.16.0-38-generic #52~14.04.1-Ubuntu SMP 
                    Fri May 8 09:43:57 UTC 2015 
                    x86_64 x86_64 x86_64 GNU/Linux, python 3.4, SQLite 3.6.18,
                     Firefox Quantum 57.0.1(64-bit)

    Remarks:        This is computer hobbyists homework

    Updates:        0.1 29.12.2017 (PP)

        
    Global main function on main.py
 
    ################################################################################################"""
    root = tk.Tk()
    root.geometry("700x950+300+300")
    root.title("Päiväkirja")
    app = controller.Controller(root)
    root.mainloop()
Exemple #21
0
def debug_wrapper():
    # initialize things
    pygame.init()
    pose_source = user_pose.FPS_Pose(two_d=True)  # initialize position source
    visar_controller = controller.Controller(
        pose_source)  # initialize controller
    renderer = rendering.Renderer(visar_controller)  # initialize renderer

    # add pose source to update stack
    visar_controller.add_update(pose_source.update)

    # setup a static square object (from rendertest)
    square1 = Debug_Static()  # create a render module
    renderer.add_module(square1)  # add module to render stack

    # setup dynamic (moving) square object (rendertest)
    square2 = Debug_Dynamic()  # create another module
    visar_controller.add_update(square2.update)  # add pose listener
    renderer.add_module(square2)  # add drawable to render stack

    # setup a static square object with depth (from rendertest)
    square3 = Debug_Depth()  # create a render module
    renderer.add_module(square3)  # add module to render stack

    # run the controller (spawns new thread)
    #visar_controller.do_loop() # removed unused code

    # run the renderer (blocks until code is done)
    renderer.do_loop(visar_controller.kill_flag)

    # program quit, kill pygame
    pygame.quit()
Exemple #22
0
    def __init__(self, master=None):
        self.root = master

        self.top_left_frame = tk.Frame(self.root, width=410, height=100)
        self.middle_left_frame = tk.Frame(self.root, width=410, height=20)
        self.bottom_left_frame = tk.Frame(self.root, width=410, height=20)

        self.top_left_frame.grid_propagate(False)
        self.middle_left_frame.grid_propagate(False)
        self.bottom_left_frame.grid_propagate(False)

        self.top_left_frame.grid(row=0,
                                 column=0,
                                 sticky=tk.W + tk.E + tk.S + tk.N)
        self.middle_left_frame.grid(row=1,
                                    column=0,
                                    sticky=tk.W + tk.E + tk.S + tk.N)
        self.bottom_left_frame.grid(row=2,
                                    column=0,
                                    sticky=tk.W + tk.E + tk.S + tk.N)

        self.root.grid_columnconfigure(0, weight=1)
        self.root.grid_rowconfigure(0, weight=1)
        self.root.grid_rowconfigure(1, weight=1)
        self.root.grid_rowconfigure(2, weight=1)

        self.root.title("GUI")
        self.root.resizable(1, 0)
        self.init_window()
        self.controller = cont.Controller(self.console)
        self.init_middle_frame()
 def test_29_controller_pickle(self):
     # actual returns True even though it is unable to load a csv
     # this is a problem with the feedback provided in the model
     cont = controller.Controller()
     expected = True
     actual = cont.pickle_modules('linkedlist.csv')
     self.assertEqual(expected, actual)
Exemple #24
0
 def __init__(self):
     self.robo = cartpole.cart_pole()
     self.ctrl = controller.Controller()
     self.learn_epoch_max = 10
     self.epoch = 0
     self.timeMax = 200
     self.time = 0
def test_lqr():
    control_spec = {
        'feedback': 'LQR',
        'params': {
            'feedback': {
                'Q': np.array([[1, 0], [0, 1]]),
                'R': 1
            }
        }
    }

    model = Model(np.array([[0, 1], [1, 0]]), [[0], [1]])

    dt = 0.01
    x = np.array([[1], [1]])
    goal_x = np.array([[0], [0]])
    est_params = []

    test_controller = controller.Controller(control_spec, model)
    output = test_controller.control(dt, x, goal_x, est_params)

    # expected results
    K, S, E = control.lqr(model.A, model.B,
                          control_spec['params']['feedback']['Q'],
                          control_spec['params']['feedback']['R'])
    expec_output = -K @ x

    assert output == expec_output
Exemple #26
0
def main():

    repo = repository.Repository()
    contr = controller.Controller(repo)
    view = ui.UI(contr, repo)

    view.menu()
 def setUp(self):
     self.read = reader.FileReader()
     self.valid = validator.Validator()
     self.db = database.DatabaseMaker()
     self.con = controller.Controller()
     self.cmd = command_line.DomainCmd(self.con)
     self.chart = display.PyGal()
 def __init__(self, dht_addr, conf_path, routing_m_mod, lookup_m_mod,
              private_dht_name, debug_level):
     logging_conf.setup(conf_path, debug_level)
     self.controller = controller.Controller(dht_addr, conf_path,
                                             routing_m_mod, lookup_m_mod,
                                             private_dht_name)
     self.controller.start()
Exemple #29
0
def main():
    # Define the options for DeeProtein
    parser = argparse.ArgumentParser(description='Options to run DeeProtein')
    set_default_options(config_file=os.path.join(sys.path[0], 'config.JSON'),
                        parser=parser)

    # then parse the args
    FLAGS = parser.parse_args()
    logger = set_up_logger(FLAGS.info_path, FLAGS.modelname)
    controller = cont.Controller(FLAGS)

    if FLAGS.mask == 'True':
        logger.debug('mask')
        controller.evaluate_masked_set(filepath=FLAGS.validdata)
    elif FLAGS.infer == 'True':
        logger.debug('infer')
        controller.init_for_infer()
        controller.interactive_inference()
    elif FLAGS.sequence:
        logger.debug('infering single sequence')
        controller.init_for_infer()
        preds = controller.infer(FLAGS.sequence)
        with open(os.path.join(FLAGS.info_path, 'results.txt'), 'w') as ofile:
            ofile.write(preds)
        logger.debug(preds)
    elif FLAGS.test == 'True':
        logger.debug('test')
        controller.test()
    else:
        logger.debug('train')
        controller.train()

    logger.info('Done.')
Exemple #30
0
    def directions_return(self):
        d = self.locationlist
        k = c.Controller()
        ret_direc_value = k.return_direction(d)
        # creates a new window to print directions
        self.master = Tk()
        p = ret_direc_value
        self.master.minsize(width=400, height=400)

        # creates a new label
        lab1 = Label(self.master,
                     text='Directions from {} to {} is'.format(
                         self.from_loc, self.to_loc),
                     font=("Helvetica", 14))
        lab1.grid(row=0, column=0)

        # shows as text in the window
        lab2 = Label(self.master, text=p, font=("Helvetica", 12))
        lab2.grid(row=3, column=0)

        # creates a new label
        lab4 = Label(self.master,
                     text='Have a safe journey !!',
                     font=("Helvetica", 14))
        lab4.grid(row=6, column=0)

        # creates a new button
        But1 = Button(self.master,
                      text='Back to main menu',
                      command=self.destroy_dir)
        But1.grid(row=8, column=0)

        mainloop()