Exemplo n.º 1
0
class Healthy:
    def __init__(self, scene, meter_size = (30,4)):
        self._health = self.get_max_health()
        self.health_bar = Meter(V2(self.x, self.y - self._height / 2), meter_size[0], meter_size[1], PICO_RED, self.get_max_health())
        self.health_bar.value = self.health
        self.health_bar.offset = (0.5,1)
        self.health_bar.stay = False
        self.health_bar.visible = 0
        self.health_bar._recalc_rect()
        scene.ui_group.add(self.health_bar)

    @property
    def health(self):
        return self._health

    @health.setter
    def health(self, val):
        old = self._health
        self._health = max(min(val, self.get_max_health()), 0)
        if old != self._health:
            self.health_bar.value = self._health
            self.health_bar.max_value = self.get_max_health()
            self.health_bar.show()

    def get_max_health(self):
        return 0
Exemplo n.º 2
0
    def run(self):
        """Run the report."""
        report_start = time.time()
        columns = self._definition.get('columns', [])
        items = self._definition.get('items', [])

        with self.csv_scope() as csv_scope:
            # Iterate over items in definition.
            for item in items:
                m = Meter(self._client,
                          item['meter_name'],
                          max_samples=self.max_samples)
                # Meter.read() returns a generator that yields readings.
                # One reading per resource/meter pair
                for reading in m.read(start=self._start, stop=self._stop):
                    reading.convert(item.get('conversion'))
                    line_item = {
                        c.get('name'): self._encode(
                            self._field_function(c.get('func'), item, reading))
                        for c in columns
                    }
                    csv_scope.writerow(line_item)

        elapsed = time.time() - report_start
        logger.info('Report is at {}'.format(self.output.location))
        logger.debug('Finished report in {} seconds'.format(elapsed))
Exemplo n.º 3
0
 def __init__(self):
     self.label: int = 0   # identifier string, eg. a number
     self.name = ''   # full name of this v
     self.sname = ''   # short name
     self.meter = Meter()   # meter
     self.meter0 = Meter()   # meter
     self.meter1 = Meter()   # meter
     self.key = Key()   # keysig
     self.key0 = Key()   # keysig
     self.key1 = Key()   # keysig
     self.stems = 0   # +1 or -1 to force stem direction
     self.staves = 0
     self.brace = 0
     self.bracket = 0
     self.do_gch = 0   # 1 to output gchords for this v
     self.sep = 0.0   # for space to next v below
     self.syms = list()    # number of music
     self.nsym = len(self.syms)
     self.draw = False   # flag if want to draw this v
     self.select = True   # flag if selected for output
     self.insert_btype = B_INVIS
     self.insert_num = 0   # to split bars over linebreaks
     self.insert_bnum = 0   # same for bar number
     self.insert_space = 0.0   # space to insert after init syms
     self.end_slur = 0   # for a-b slurs
     self.insert_text = ''   # string over inserted barline
     self.timeinit = 0.0   # carryover time between parts
Exemplo n.º 4
0
class Test(Frame):
    _meter = None
    _position = 0
    _length = 10000
    _step = 500

    def __init__(self):
        Frame.__init__(self)

        # width = (CART_WIDTH + CART_MARGIN) * NUM_COLS
        width = METER_WIDTH

        self._meter = Meter(self.master, width, self._get_meter_data)
        self._meter.grid(row=0, column=0, columnspan=NUM_COLS) #, sticky=E+W

        Canvas(self.master, width=900, height=100, bg='#00F').grid(row=2, column=0, columnspan=NUM_COLS)

        self._meter.start()
        thread.start_new_thread(self._run, ())

        self.master.title("Testing Program")
        self.master.mainloop()

    def _run(self):
        while True:
            self._position = (self._position + self._step) % self._length
            time.sleep(self._step / 1000.)

    def _get_meter_data(self):
        return (self._position, self._length, "Fruity", "Blergs")
Exemplo n.º 5
0
 def iterate(self, epoch, phase):
     meter = Meter(phase, epoch)
     start = time.strftime("%H:%M:%S")
     print(f"Starting epoch: {epoch} | phase: {phase} | ⏰: {start}")
     batch_size = self.batch_size[phase]
     dataloader = self.dataloaders[phase]
     running_loss = 0.0
     total_batches = len(dataloader)
     tk0 = tqdm(dataloader, total=total_batches)
     self.optimizer.zero_grad()
     for itr, batch in enumerate(tk0):
         if phase == "train" and self.do_cutmix:
             images, targets = self.cutmix(batch, 0.5)
         else:
             images, targets = batch
         seg_loss, outputs, preds = self.forward(images, targets)
         loss = seg_loss / self.accumulation_steps
         if phase == "train":
             loss.backward()
             torch.nn.utils.clip_grad_norm_(self.net.parameters(), 1)
             if (itr + 1) % self.accumulation_steps == 0:
                 self.optimizer.step()
                 self.optimizer.zero_grad()
         running_loss += loss.item()
         meter.update(outputs, preds)
         tk0.set_postfix(loss=(running_loss / ((itr + 1))))
     epoch_loss = (running_loss * self.accumulation_steps) / total_batches
     dice, iou, f2 = epoch_log(phase, epoch, epoch_loss, meter, start)
     self.losses[phase].append(epoch_loss)
     self.dice_scores[phase].append(dice)
     self.iou_scores[phase].append(iou)
     self.f2_scores[phase].append(f2)
     torch.cuda.empty_cache()
     return epoch_loss, dice, iou
Exemplo n.º 6
0
    def validation(self, test_loader):
        self.model.eval()
        self.model.train(False)
        checkpoint = torch.load(self.weight_path, map_location=torch.device('cpu'))
        self.model.load_state_dict(checkpoint['state_dict'])
        meter = Meter()
        tbar = tqdm.tqdm(test_loader, ncols=80)
        loss_sum = 0

        with torch.no_grad():
            for i, (x, labels) in enumerate(tbar):
                labels_predict = self.solver.forward(x)
                labels_predict = torch.sigmoid(labels_predict)
                loss = self.solver.cal_loss(labels, labels_predict, self.criterion)
                loss_sum += loss.item()

                meter.update(labels, labels_predict.cpu())

                descript = "Val Loss: {:.7f}".format(loss.item())
                tbar.set_description(desc=descript)
        loss_mean = loss_sum / len(tbar)

        class_neg_accuracy, class_pos_accuracy, class_accuracy, neg_accuracy, pos_accuracy, accuracy = meter.get_metrics()
        print(
            "Class_0_accuracy: %0.4f | Class_1_accuracy: %0.4f | Negative accuracy: %0.4f | positive accuracy: %0.4f | accuracy: %0.4f" %
            (class_accuracy[0], class_accuracy[1], neg_accuracy, pos_accuracy, accuracy))
        return class_neg_accuracy, class_pos_accuracy, class_accuracy, neg_accuracy, pos_accuracy, accuracy, loss_mean
Exemplo n.º 7
0
class Test(Frame):
    _meter = None
    _position = 0
    _length = 10000
    _step = 500

    def __init__(self):
        Frame.__init__(self)

        # width = (CART_WIDTH + CART_MARGIN) * NUM_COLS
        width = METER_WIDTH

        self._meter = Meter(self.master, width, self._get_meter_data)
        self._meter.grid(row=0, column=0, columnspan=NUM_COLS)  #, sticky=E+W

        Canvas(self.master, width=900, height=100,
               bg='#00F').grid(row=2, column=0, columnspan=NUM_COLS)

        self._meter.start()
        thread.start_new_thread(self._run, ())

        self.master.title("Testing Program")
        self.master.mainloop()

    def _run(self):
        while True:
            self._position = (self._position + self._step) % self._length
            time.sleep(self._step / 1000.)

    def _get_meter_data(self):
        return (self._position, self._length, "Fruity", "Blergs")
Exemplo n.º 8
0
 def __init__(self, parent):
     Window.ControlPanel.__init__(self, parent)
     self.progressBar = Meter(self,
                              bg=parent.cget("bg"),
                              relief=SUNKEN,
                              bd=2)
     self.progressBar.pack(padx=10, pady=5, fill=X, expand=True)
Exemplo n.º 9
0
    def __init__(self):
        """Construct a Studio window."""
        Frame.__init__(self)

        # make the window resizable
        top = self.master.winfo_toplevel()
        for row in range(2, GRID_ROWS + 2):
            for col in range(0, GRID_COLS):
                top.rowconfigure(row, weight=1)
                top.columnconfigure(col, weight=1)
                self.rowconfigure(row, weight=1)
                self.columnconfigure(col, weight=1)

        # initialize the title
        title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE)
        title.grid(row=0, column=0, columnspan=GRID_COLS)

        # initialize the meter
        self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data)
        self._meter.grid(row=1, column=0, columnspan=GRID_COLS)

        # initialize the cart grid
        self._grid = Grid(self, GRID_ROWS, GRID_COLS, True, self._cart_start,
                          self._cart_stop, self._cart_end, self.add_cart)

        # initialize the dual box
        self._dual_box = DualBox(self)
        self._dual_box.grid(row=GRID_ROWS + 2, column=0, columnspan=4)

        # intialize the auto-queue control
        self._auto_queue = BooleanVar()
        self._auto_queue.set(False)

        control = Frame(self.master, bd=2, relief=Tkinter.SUNKEN)

        Checkbutton(control,
                    text=TEXT_AUTOSLOT,
                    variable=self._auto_queue,
                    onvalue=True,
                    offvalue=False).pack(anchor=Tkinter.NW)
        control.grid(row=GRID_ROWS + 2, column=4, columnspan=GRID_COLS - 4)

        # initialize the search box, button
        Label(control, font=FONT, text=TEXT_SEARCHBOX).pack(anchor=Tkinter.NW)
        self._entry = Entry(control, takefocus=True, width=45)
        self._entry.bind("<Return>", self.search)
        # self._entry.grid(row=GRID_ROWS + 3, column=0, columnspan=5)
        self._entry.pack(anchor=Tkinter.NW)
        self._entry.focus_set()

        button = Button(control, text=TEXT_SEARCH, command=self.search)
        # button.grid(row=GRID_ROWS + 3, column=5)
        button.pack(anchor=Tkinter.S)

        # begin the event loop
        self.master.protocol("WM_DELETE_WINDOW", self.master.destroy)
        self.master.title(TEXT_TITLE)
        self.master.mainloop()
Exemplo n.º 10
0
 def __init__(self, scene, meter_size = (30,4)):
     self._health = self.get_max_health()
     self.health_bar = Meter(V2(self.x, self.y - self._height / 2), meter_size[0], meter_size[1], PICO_RED, self.get_max_health())
     self.health_bar.value = self.health
     self.health_bar.offset = (0.5,1)
     self.health_bar.stay = False
     self.health_bar.visible = 0
     self.health_bar._recalc_rect()
     scene.ui_group.add(self.health_bar)
Exemplo n.º 11
0
    def test_generate_power_value(self):
        meter_house_a = Meter("HOUSE_A")
        loop = asyncio.get_event_loop()
        power_value = loop.run_until_complete(meter_house_a.generate_power_value())

        self.assertTrue(power_value["house"] is "HOUSE_A")
        self.assertIsInstance(power_value["house"], str)
        self.assertIsInstance(power_value["datetime"], float)
        self.assertIsInstance(power_value["pv"], int)
        self.assertTrue(cfg.PV_MIN < power_value["pv"] < cfg.PV_MAX)
Exemplo n.º 12
0
 def test_publish(self):
     try:
         meter_house = Meter("HOUSE_TEST")
         loop = asyncio.get_event_loop()
         loop.run_until_complete(self._publisher.connect_to_broker())
         pv_house_a = loop.run_until_complete(
             meter_house.generate_power_value())
         loop.run_until_complete(self._publisher.publish(pv_house_a))
         self.assertTrue(True)
     except ConnectionError:
         self.assertTrue(False)
    def test_put(self):
        broker_address = cfg.BROKER_ADDRESS
        broker_exchange_name = cfg.EXCHANGE_NAME
        broker_queue_name = cfg.QUEUE_NAME
        broker_client = BrokerClient(broker_address, broker_exchange_name,
                                     broker_queue_name)
        meter_house_a = Meter("HOUSE_A")
        loop = asyncio.get_event_loop()
        power_value = loop.run_until_complete(
            meter_house_a.generate_power_value())
        loop.run_until_complete(broker_client.connect())
        loop.run_until_complete(broker_client.put(power_value))

        self.assertIsInstance(broker_client, BrokerClient)
        self.assertTrue(broker_client)
Exemplo n.º 14
0
    def go(self):
        self.meter = Meter(self.duration_seconds, bpm=80)

        # Make a random scale
        options = range(12)
        scale = []
        for _ in range(7):
            pc = np.random.choice(options)
            options.remove(pc)
            scale.append(pc)
        scale.sort()
        print scale

        pitch = np.random.randint(62, 76)

        for sixteenth in self.meter.layers_by_name['sixteenth']:
            if np.random.random() < .8:
                # Rest every 10 or so notes

                pitch_options = range(max([pitch - 5, 56]),
                                      min([pitch + 6, 88]))
                pitch_options.remove(pitch)
                pitch_options = [p for p in pitch_options if p % 12 in scale]
                pitch = np.random.choice(pitch_options)

                note = self.marimba.get_note(pitch)
                self.audio.add(sixteenth.start_samples, note)
Exemplo n.º 15
0
    def __init__(self):
        Frame.__init__(self)

        # width = (CART_WIDTH + CART_MARGIN) * NUM_COLS
        width = METER_WIDTH

        self._meter = Meter(self.master, width, self._get_meter_data)
        self._meter.grid(row=0, column=0, columnspan=NUM_COLS)  #, sticky=E+W

        Canvas(self.master, width=900, height=100,
               bg='#00F').grid(row=2, column=0, columnspan=NUM_COLS)

        self._meter.start()
        thread.start_new_thread(self._run, ())

        self.master.title("Testing Program")
        self.master.mainloop()
Exemplo n.º 16
0
    def get(self, mid):
        TAG = "Gauge:"
        module = Module()
        meter = Meter()
        start_time = time.time()

        current_user = get_jwt_identity()
        username = current_user['sub']
        if (not meter.isUserHasPerm(username, mid)):
            return module.unauthorized()
        args = request.args
        param = "V0, V1, V2, I0, I1, I2, pf0, pf1, pf2, P0, P1, P2, f0, f1, f2, E0, E1, E2"
        if (module.isQueryStr(args, "parameters")):
            param = args["parameters"]
            param = param.replace(" ", ", ")
            # print(TAG, "param=", param)
        command = """SELECT %s FROM %s ORDER BY DESC LIMIT 1 """ % (param, mid)
        # print(TAG, "cmd=", command)
        if (not module.isMeterExist(mid)):
            return module.measurementNotFound()
        res = module.getData(command)
        # print(TAG, "res=", res)
        results = {"meter_id": "", "parameters": [], "values": []}
        gauge_data = {}
        if (len(res) > 0):
            tmp_res = res[0]
            results["meter_id"] = tmp_res["name"]
            results["parameters"] = tmp_res["columns"]
            results["values"] = tmp_res["values"]
        else:
            return module.measurementNotFound()

        for i in range(len(results["parameters"])):
            param_name = results["parameters"][i]
            # print(TAG, "param_name=", param_name)
            gauge_data[param_name] = results["values"][0][i]

        elapsed_time = (time.time() - start_time) * 1000
        print(TAG, "times=", elapsed_time, "ms")
        return {
            "type": True,
            "message": "success",
            "elapsed_time_ms": elapsed_time,
            "result": gauge_data
        }
Exemplo n.º 17
0
def DownloadMeters(Frequency):
    Meters = []
    url = "http://delso.pythonanywhere.com/Meter"
    resp = UrlResponseVerification(url)
    print(resp)  ##INSERT
    for Row in resp:
        Meters = Meters + [[Row[0], Row[1], Row[2], Row[3], Meter(Row[2], Frequency)]]
    print('Meters %s\n' % Meters)
    return Meters
Exemplo n.º 18
0
    def __init__(self, scene, meter_size=(30, 4)):
        self._health = 1
        self.health_bar = Meter(V2(self.x, self.y - self._height / 2),
                                meter_size[0], meter_size[1], PICO_RED, 1)
        self.health_bar.value = self.health
        self.health_bar.offset = (0.5, 1)
        self.health_bar.stay = False
        self.health_bar.visible = 0
        self.health_bar._recalc_rect()
        scene.ui_group.add(self.health_bar)

        self._shield_damage = 0
        self.shield_bar = Meter(V2(self.x, self.y - self._height / 2 - 3),
                                meter_size[0], 2, PICO_BLUE, 1)
        self.shield_bar.value = 9999999
        self.shield_bar.offset = (0.5, 1)
        self.shield_bar.stay = False
        self.shield_bar.visible = 0
        self.shield_bar._recalc_rect()
        scene.ui_group.add(self.shield_bar)
Exemplo n.º 19
0
    def __init__(self):
        """Construct a Studio window."""
        Frame.__init__(self)

        # make the window resizable
        top = self.master.winfo_toplevel()
        for row in range(2, GRID_ROWS + 2):
            for col in range(0, GRID_COLS):
                top.rowconfigure(row, weight=1)
                top.columnconfigure(col, weight=1)
                self.rowconfigure(row, weight=1)
                self.columnconfigure(col, weight=1)

        # initialize the title
        title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE)
        title.grid(row=0, column=0, columnspan=GRID_COLS)

        # initialize the meter
        self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data)
        self._meter.grid(row=1, column=0, columnspan=GRID_COLS)

        # initialize the cart grid
        self._grid = Grid(self, GRID_ROWS, GRID_COLS, True, self._cart_start, self._cart_stop, self._cart_end, self.add_cart)

        # initialize the dual box
        self._dual_box = DualBox(self)
        self._dual_box.grid(row=GRID_ROWS + 2, column=0, columnspan=4)

        # intialize the auto-queue control
        self._auto_queue = BooleanVar()
        self._auto_queue.set(False)

        control = Frame(self.master, bd=2, relief=Tkinter.SUNKEN)

        Checkbutton(control, text=TEXT_AUTOSLOT, variable=self._auto_queue, onvalue=True, offvalue=False).pack(anchor=Tkinter.NW)
        control.grid(row=GRID_ROWS + 2, column=4, columnspan=GRID_COLS - 4)

        # initialize the search box, button
        Label(control, font=FONT, text=TEXT_SEARCHBOX).pack(anchor=Tkinter.NW)
        self._entry = Entry(control, takefocus=True, width=45)
        self._entry.bind("<Return>", self.search)
        # self._entry.grid(row=GRID_ROWS + 3, column=0, columnspan=5)
        self._entry.pack(anchor=Tkinter.NW)
        self._entry.focus_set()

        button = Button(control, text=TEXT_SEARCH, command=self.search)
        # button.grid(row=GRID_ROWS + 3, column=5)
        button.pack(anchor=Tkinter.S)

        # begin the event loop
        self.master.protocol("WM_DELETE_WINDOW", self.master.destroy)
        self.master.title(TEXT_TITLE)
        self.master.mainloop()
Exemplo n.º 20
0
    def play(self, player_ui, player_state):

        screen = 0
        sleep(1)
        constants.SOUND_EVENT_DISAPPEAR.play()
        utils.draw_sprite(self.scenes[screen])
        sleep(1)
        player_ui.render()

        screen = 0
        one = constants.CAREER_EVENT_SEQUENCE_3_BUTTON_1
        two = constants.CAREER_EVENT_SEQUENCE_3_BUTTON_2
        three = constants.CAREER_EVENT_SEQUENCE_3_BUTTON_3
        four = constants.CAREER_EVENT_SEQUENCE_3_BUTTON_4

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        pygame.quit()
                        quit()
                    if event.key in [pygame.K_DOWN]:
                        if screen == 3:
                            constants.SOUND_MENU_SELECTION.play()
                            one, two, three, four = two, three, four, one
                    if event.key in [pygame.K_UP]:
                        if screen == 3:
                            constants.SOUND_MENU_SELECTION.play()
                            one, two, three, four = four, one, two, three
                    if event.key == pygame.K_RETURN:
                        screen += 1
                        if screen != 3:
                            utils.draw_sprite(self.scenes[screen])
                            player_ui.render()
                        if screen == 5:
                            utils.draw_sprite(self.scenes[screen])
                            constants.SOUND_SAD_EVENT_APPEAR.play()
                            Meter().play_animation(1)
                            player_ui.update(2)
                            player_ui.render()
                        if screen == 6:
                            return player_state

                if screen == 3:
                    utils.draw_sprite(one)
                    player_ui.render()

            pygame.display.update()
            constants.CLK.tick(constants.FPS)
Exemplo n.º 21
0
def run_graphics():
    '''This is the PyGame graphics procedure(hardcoding). It will run from
    the main function
    '''
    #initialize screen and colour settings for the screen
    pygame.init()
    size = [900, 630]
    screen = pygame.display.set_mode(size)
    black = (0, 0, 0)
    white = (255, 255, 255)
    clock = pygame.time.Clock()
    done = False

    #default settings of the magnifying glass
    radius = 80
    power_meter = Meter(2, 10)

    while not done:
        # limit speed of while loop to be <10 times per second.
        clock.tick(120)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            if event.type == pygame.KEYDOWN:
                #Increase/decrease speed
                if event.key == pygame.K_UP:
                    power_meter.increase()
                if event.key == pygame.K_DOWN:
                    power_meter.decrease()

        #set screen background
        screen.fill(white)
        draw_tree(0, 0, 900, 600, screen, tree_map)

        #Detect and store mouse location
        pos = pygame.mouse.get_pos()
        x = pos[0]
        y = pos[1]

        if y < 600 or x < 900:
            #Checks if the mouse was held down
            if pygame.mouse.get_pressed()[0]:
                pygame.draw.ellipse(screen, white, [x - 100, y - 100,\
                                                    200, 200])
                magnify(x, y, radius, power_meter.current, tree_map, screen)
                pygame.draw.ellipse(screen, black, [x - 100, y - 100,\
                                                    200, 200], 5)
            # identify the file mouse is hovering over
            hovered_file = file_search(x, y, tree_map)
            if hovered_file:
                # Select font
                font = pygame.font.Font(None, 25)
                text = font.render(hovered_file.get_loc(), True, black)
                # display location at bottom of screen
                screen.blit(text, [10, 605])
        # Update the screen
        pygame.display.flip()

    pygame.quit()
Exemplo n.º 22
0
class MeterDaemon(Daemon):

    def __init__(self, pid):
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.INFO)
        ##create a file handler
        handler = logging.FileHandler('/var/log/meterd.log')
        handler.setLevel(logging.INFO)
        ##create a logging format
        formatter = logging.Formatter('%(asctime)s - '
                                      + '%(name)s - '
                                      + '%(levelname)s - '
                                      + '%(message)s')
        handler.setFormatter(formatter)
        ##add the handlers to the logger
        self.logger.addHandler(handler)
        self.logger.info('Logging started...')
        self.logger.info('Pid is:' + pid)
        super(MeterDaemon, self).__init__(pid)
        self.m = Meter('/dev/ttyUSB0',
                       57600,
                       8,
                       'mastermeter',
                       'watts',
                       self.logger)

    def run(self):
        self.m.open()
        self.logger.debug('Meter open.')
        while 1:
            self.m.read()
            self.m.parse()
            self.m.submit()
            time.sleep(6)

    def stop(self):
        self.m.close()
        self.logger.debug('Meter close.')
        super(MeterDaemon, self).stop()
Exemplo n.º 23
0
    def __init__(self):
        """Construct a CartMachine window."""
        Frame.__init__(self)

        # make the window resizable
        top = self.winfo_toplevel()
        for row in range(2, GRID_ROWS + 2):
            for col in range(0, GRID_COLS):
                top.rowconfigure(row, weight=1)
                top.columnconfigure(col, weight=1)
                self.rowconfigure(row, weight=1)
                self.columnconfigure(col, weight=1)

        # initialize the title
        title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE)
        title.grid(row=0, column=0, columnspan=GRID_COLS - 1, sticky=Tkinter.N)

        # initialize the reload button
        reload_button = Button(self.master, \
            bg=COLOR_RELOAD_BG, fg=COLOR_RELOAD_FG, \
            font=FONT_RELOAD, text=TEXT_RELOAD, \
            command=self.reload)
        reload_button.grid(row=0, column=GRID_COLS - 1)

        # initialize the meter
        self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data)
        self._meter.grid(row=1, column=0, columnspan=GRID_COLS)
        # self._meter.grid_propagate(0)

        # initialize the grid
        self._grid = Grid(self, GRID_ROWS, GRID_COLS, False, self._cart_start,
                          self._cart_stop, self._cart_end, None)
        self._load()

        # begin the event loop
        self.master.protocol("WM_DELETE_WINDOW", self.master.destroy)
        self.master.title(TEXT_TITLE)
        self.mainloop()
Exemplo n.º 24
0
    def __init__(self):
        """Construct an Automation window."""
        Frame.__init__(self)

        # initialize title
        title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE)
        title.grid(row=0, column=0, columnspan=3)

        # initialize button and state
        self._state = STATE_STOPPED

        self._button_text = StringVar()

        self._button = Button(self.master, textvariable=self._button_text, command=self._update_state, width=16, height=2)
        self._button.config(bd=2)
        self._button.grid(row=0, column=3)

        # initialize the meter
        self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data)
        self._meter.grid(row=1, column=0, columnspan=4)

        # initialize playlist view
        playlist = Frame(self.master, bd=2, relief=Tkinter.SUNKEN)
        Label(playlist, font=FONT, anchor=Tkinter.CENTER, width=16, text=TEXT_PLAYLIST_TIME).grid(row=0, column=0)
        Label(playlist, font=FONT, anchor=Tkinter.CENTER, width=32, text=TEXT_PLAYLIST_TRACK).grid(row=0, column=1)
        Label(playlist, font=FONT, anchor=Tkinter.CENTER, width=32, text=TEXT_PLAYLIST_ARTIST).grid(row=0, column=2)

        inner_playlist = Frame(playlist)
        scroll = Scrollbar(inner_playlist, orient=Tkinter.VERTICAL, command=self._scroll_playlist)
        self._list_time = Listbox(inner_playlist, selectmode=Tkinter.SINGLE, yscrollcommand=scroll.set, exportselection=0, width=16, height=20)
        self._list_track = Listbox(inner_playlist, selectmode=Tkinter.SINGLE, yscrollcommand=scroll.set, exportselection=0, width=32, height=20)
        self._list_artist = Listbox(inner_playlist, selectmode=Tkinter.SINGLE, yscrollcommand=scroll.set, exportselection=0, width=32, height=20)

        scroll.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)
        self._list_time.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True, padx=2, pady=2)
        self._list_track.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True, padx=2, pady=2)
        self._list_artist.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True, padx=2, pady=2)

        inner_playlist.grid(row=1, column=0, columnspan=3)
        playlist.grid(row=4, column=0, columnspan=4)

        # initialize cart queue
        self._cart_queue = CartQueue(self._cart_start, self._cart_stop)
        self._cart_queue.add_tracks()
        self._update_ui()

        # begin the event loop
        self.master.protocol("WM_DELETE_WINDOW", self.master.destroy)
        self.master.title(TEXT_TITLE)
        self.master.mainloop()
Exemplo n.º 25
0
 def __init__(self, pid):
     self.logger = logging.getLogger(__name__)
     self.logger.setLevel(logging.INFO)
     ##create a file handler
     handler = logging.FileHandler('/var/log/meterd.log')
     handler.setLevel(logging.INFO)
     ##create a logging format
     formatter = logging.Formatter('%(asctime)s - '
                                   + '%(name)s - '
                                   + '%(levelname)s - '
                                   + '%(message)s')
     handler.setFormatter(formatter)
     ##add the handlers to the logger
     self.logger.addHandler(handler)
     self.logger.info('Logging started...')
     self.logger.info('Pid is:' + pid)
     super(MeterDaemon, self).__init__(pid)
     self.m = Meter('/dev/ttyUSB0',
                    57600,
                    8,
                    'mastermeter',
                    'watts',
                    self.logger)
Exemplo n.º 26
0
def _dp_parser_v2(logger, acls_conf, dps_conf, meters_conf, routers_conf,
                  vlans_conf):
    dps = []
    vid_dp = {}
    for identifier, dp_conf in list(dps_conf.items()):
        try:
            dp = DP(identifier, dp_conf)
            dp.sanity_check()
            dp_id = dp.dp_id

            vlans = {}
            for vlan_ident, vlan_conf in list(vlans_conf.items()):
                vlans[vlan_ident] = VLAN(vlan_ident, dp_id, vlan_conf)
            acls = []
            for acl_ident, acl_conf in list(acls_conf.items()):
                acls.append((acl_ident, ACL(acl_ident, acl_conf)))
            for router_ident, router_conf in list(routers_conf.items()):
                router = Router(router_ident, router_conf)
                dp.add_router(router_ident, router)
            for meter_ident, meter_conf in list(meters_conf.items()):
                dp.meters[meter_ident] = Meter(meter_ident, meter_conf)
            ports_conf = dp_conf.pop('interfaces', {})
            ports = {}
            # as users can config port vlan by using vlan name, we store vid in
            # Port instance instead of vlan name for data consistency
            for port_num, port_conf in list(ports_conf.items()):
                port = port_parser(dp_id, port_num, port_conf, vlans)
                ports[port_num] = port
                if port.native_vlan is not None:
                    vlan = _get_vlan_by_identifier(dp_id, port.native_vlan,
                                                   vlans)
                    port.native_vlan = vlan
                    _dp_add_vlan(vid_dp, dp, vlan)
                if port.tagged_vlans is not None:
                    tagged_vlans = []
                    for vlan_ident in port.tagged_vlans:
                        vlan = _get_vlan_by_identifier(dp_id, vlan_ident,
                                                       vlans)
                        tagged_vlans.append(vlan)
                        _dp_add_vlan(vid_dp, dp, vlan)
                    port.tagged_vlans = tagged_vlans
        except AssertionError as err:
            logger.exception('Error in config file: %s', err)
            return None
        for port in list(ports.values()):
            dp.add_port(port)
        for acl_ident, acl in acls:
            dp.add_acl(acl_ident, acl)
        dps.append(dp)
    return dps
Exemplo n.º 27
0
    def validation(self, valid_loader):
        self.model.eval()
        meter = Meter()
        tbar = tqdm(valid_loader)
        loss_sum = 0

        with torch.no_grad():
            for i, (images, labels) in enumerate(tbar):
                labels_predict = self.solver.forward(images)
                # print(labels + (labels_predict.cpu() > 0.5).int())
                # labels_predict = labels_predict.unsqueeze(dim=2).unsqueeze(dim=3)
                loss = self.solver.cal_loss(labels, labels_predict,
                                            self.criterion)
                # loss = F.cross_entropy(labels_predict[0], labels)
                loss_sum += loss.item()

                meter.update(labels, labels_predict.cpu())

                descript = "Val Loss: {:.7f}".format(loss.item())
                tbar.set_description(desc=descript)
        loss_mean = loss_sum / len(tbar)

        class_neg_accuracy, class_pos_accuracy, class_accuracy, neg_accuracy, pos_accuracy, accuracy = meter.get_metrics(
        )
        print(
            "Class_0_accuracy: %0.4f | Positive accuracy: %0.4f | Negative accuracy: %0.4f | \n"
            "Class_1_accuracy: %0.4f | Positive accuracy: %0.4f | Negative accuracy: %0.4f |"
            %
            (class_accuracy[0], class_pos_accuracy[0], class_neg_accuracy[0],
             class_accuracy[1], class_pos_accuracy[1], class_neg_accuracy[1]))
        # print("Class_0_accuracy: %0.4f | Positive accuracy: %0.4f | Negative accuracy: %0.4f | \n"
        #       "Class_1_accuracy: %0.4f | Positive accuracy: %0.4f | Negative accuracy: %0.4f | \n"
        #       "Class_2_accuracy: %0.4f | Positive accuracy: %0.4f | Negative accuracy: %0.4f |" %
        #       (class_accuracy[0], class_pos_accuracy[0], class_neg_accuracy[0],
        #        class_accuracy[1], class_pos_accuracy[1], class_neg_accuracy[1],
        #        class_accuracy[2], class_pos_accuracy[2], class_neg_accuracy[2]))
        return class_neg_accuracy, class_pos_accuracy, class_accuracy, neg_accuracy, pos_accuracy, accuracy, loss_mean
Exemplo n.º 28
0
def evaluate(model, data_loader, args):
    model.eval()
    meter = Meter()
    with torch.no_grad():
        for batch in data_loader:
            batch = tuple(t.to(args.device) for t in batch)
            _, items = calc_loss(model, batch)
            meter.add(*items)
    return meter.average(), meter.print_str(False)
Exemplo n.º 29
0
    def __init__(self):
        Frame.__init__(self)

        # width = (CART_WIDTH + CART_MARGIN) * NUM_COLS
        width = METER_WIDTH

        self._meter = Meter(self.master, width, self._get_meter_data)
        self._meter.grid(row=0, column=0, columnspan=NUM_COLS) #, sticky=E+W

        Canvas(self.master, width=900, height=100, bg='#00F').grid(row=2, column=0, columnspan=NUM_COLS)

        self._meter.start()
        thread.start_new_thread(self._run, ())

        self.master.title("Testing Program")
        self.master.mainloop()
Exemplo n.º 30
0
    def __init__(self, hdf_filename, ID=None):
        assert os.path.isfile(hdf_filename)
        with pd.get_store(hdf_filename) as store:
            metadata = store.root._v_attrs.metadata

        if ID is None:
            self.ID = hdf_filename.split('/')[-1]
        else:
            self.ID = ID
        self.metadata = metadata
        self.filename = hdf_filename

        meters_ID = []
        for meter_ID in metadata['meters'].keys():
            meters_ID.append(meter_ID)
        self.meters_ID = meters_ID

        meters = []
        for meter_ID in metadata['meters'].keys():
            meter = Meter.from_user(self, meter_ID)
            meters.append(meter)
        self.meters = meters
Exemplo n.º 31
0
    def play(self, player_ui: object, player_state: dict):

        screen = 0
        sleep(1)
        constants.SOUND_EVENT_DISAPPEAR.play()
        utils.draw_sprite(self.scenes[screen])
        player_ui.update(2)  # (player_state)
        sleep(1)
        player_ui.render()

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        pygame.quit()
                        quit()
                    elif event.key == pygame.K_RETURN:
                        if screen == 1:
                            player_state['cash'] -= 1
                            player_state['heart'] += 1
                            player_state['face'] -= 2
                            # utils.draw_sprite(self.scenes[screen])
                            constants.SOUND_HAPPY_EVENT_APPEAR.play()
                            Meter().play_animation(2)
                            player_ui.update(3)  # (player_state)
                            player_ui.render()
                        if screen == 2:
                            return player_state
                        screen += 1
                        utils.draw_sprite(self.scenes[screen])
                        # player_ui.update(player_state)
                        player_ui.render()

            pygame.display.update()
            constants.CLK.tick(constants.FPS)
Exemplo n.º 32
0
def evaluate_kcBert(model, data_loader, args):
    model.eval()
    meter = Meter()
    with torch.no_grad():
        for batch in data_loader:
            batch = tuple(t.to(args.device) for t in batch)
            noise_input_ids, clean_input_ids, noise_mask, clean_mask = batch

            outputs = model(noise_input_ids,
                            labels=clean_input_ids,
                            attention_mask=noise_mask)
            loss = outputs[0]

            bsz = clean_input_ids.size(0)
            items = [loss.data.item(), bsz, clean_mask.sum().item()]
            meter.add(*items)

    return meter.average(), meter.print_str(False)
Exemplo n.º 33
0
    def __init__(self):
        """Construct a CartMachine window."""
        Frame.__init__(self)

        # make the window resizable
        top = self.winfo_toplevel()
        for row in range(2, GRID_ROWS + 2):
            for col in range(0, GRID_COLS):
                top.rowconfigure(row, weight=1)
                top.columnconfigure(col, weight=1)
                self.rowconfigure(row, weight=1)
                self.columnconfigure(col, weight=1)

        # initialize the title
        title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE)
        title.grid(row=0, column=0, columnspan=GRID_COLS - 1, sticky=Tkinter.N)

        # initialize the reload button
        reload_button = Button(self.master, \
            bg=COLOR_RELOAD_BG, fg=COLOR_RELOAD_FG, \
            font=FONT_RELOAD, text=TEXT_RELOAD, \
            command=self.reload)
        reload_button.grid(row=0, column=GRID_COLS - 1)

        # initialize the meter
        self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data)
        self._meter.grid(row=1, column=0, columnspan=GRID_COLS)
        # self._meter.grid_propagate(0)

        # initialize the grid
        self._grid = Grid(self, GRID_ROWS, GRID_COLS, False, self._cart_start, self._cart_stop, self._cart_end, None)
        self._load()

        # begin the event loop
        self.master.protocol("WM_DELETE_WINDOW", self.master.destroy)
        self.master.title(TEXT_TITLE)
        self.mainloop()
Exemplo n.º 34
0
    def create_linear_meter(self, name):
        """ Create linear method
        
        :param name: meter name
        """
        config = self.meter_config[name]

        if config[CHANNELS] == 2:
            meter = Meter(self.util, TYPE_LINEAR, config[UI_REFRESH_PERIOD],
                          self.data_source)
            meter.channels = 2
            meter.left_x = config[LEFT_X]
            meter.left_y = config[LEFT_Y]
            meter.right_x = config[RIGHT_X]
            meter.right_y = config[RIGHT_Y]
        else:
            meter = Meter(self.util, TYPE_LINEAR, config[UI_REFRESH_PERIOD],
                          self.data_source)
            meter.x = config[MONO_X]
            meter.y = config[MONO_Y]

        meter.positions_regular = config[POSITION_REGULAR]
        meter.step_width_regular = config[STEP_WIDTH_REGULAR]
        if POSITION_OVERLOAD in config:
            meter.positions_overload = config[POSITION_OVERLOAD]
            meter.step_width_overload = config[STEP_WIDTH_OVERLOAD]
        else:
            meter.positions_overload = 0
            meter.step_width_overload = 0
        meter.total_steps = meter.positions_regular + meter.positions_overload + 1
        meter.step = 100 / meter.total_steps

        meter.add_background(config[BGR_FILENAME])

        if config[CHANNELS] == 2:
            meter.add_channel(config[INDICATOR_FILENAME], meter.left_x,
                              meter.left_y)
            meter.add_channel(config[INDICATOR_FILENAME], meter.right_x,
                              meter.right_y)
        else:
            meter.add_channel(config[INDICATOR_FILENAME], meter.x, meter.y)

        meter.add_foreground(config[FGR_FILENAME])

        factory = MaskFactory()
        meter.masks = factory.create_masks(meter.positions_regular,
                                           meter.positions_overload,
                                           meter.step_width_regular,
                                           meter.step_width_overload)

        return meter
Exemplo n.º 35
0
 def __init__(self, parent):
     Window.ControlPanel.__init__(self, parent)
     self.progressBar = Meter(self, bg=parent.cget("bg"), relief=SUNKEN, bd=2)
     self.progressBar.pack(padx=10, pady=5, fill=X, expand=True)
Exemplo n.º 36
0
class Studio(Frame):
    """The Studio class is a GUI for the digital library."""
    _meter = None
    _grid = None
    _dual_box = None
    _auto_queue = None
    _entry = None
    _search_results = None
    _selected_cart = None

    def __init__(self):
        """Construct a Studio window."""
        Frame.__init__(self)

        # make the window resizable
        top = self.master.winfo_toplevel()
        for row in range(2, GRID_ROWS + 2):
            for col in range(0, GRID_COLS):
                top.rowconfigure(row, weight=1)
                top.columnconfigure(col, weight=1)
                self.rowconfigure(row, weight=1)
                self.columnconfigure(col, weight=1)

        # initialize the title
        title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE)
        title.grid(row=0, column=0, columnspan=GRID_COLS)

        # initialize the meter
        self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data)
        self._meter.grid(row=1, column=0, columnspan=GRID_COLS)

        # initialize the cart grid
        self._grid = Grid(self, GRID_ROWS, GRID_COLS, True, self._cart_start, self._cart_stop, self._cart_end, self.add_cart)

        # initialize the dual box
        self._dual_box = DualBox(self)
        self._dual_box.grid(row=GRID_ROWS + 2, column=0, columnspan=4)

        # intialize the auto-queue control
        self._auto_queue = BooleanVar()
        self._auto_queue.set(False)

        control = Frame(self.master, bd=2, relief=Tkinter.SUNKEN)

        Checkbutton(control, text=TEXT_AUTOSLOT, variable=self._auto_queue, onvalue=True, offvalue=False).pack(anchor=Tkinter.NW)
        control.grid(row=GRID_ROWS + 2, column=4, columnspan=GRID_COLS - 4)

        # initialize the search box, button
        Label(control, font=FONT, text=TEXT_SEARCHBOX).pack(anchor=Tkinter.NW)
        self._entry = Entry(control, takefocus=True, width=45)
        self._entry.bind("<Return>", self.search)
        # self._entry.grid(row=GRID_ROWS + 3, column=0, columnspan=5)
        self._entry.pack(anchor=Tkinter.NW)
        self._entry.focus_set()

        button = Button(control, text=TEXT_SEARCH, command=self.search)
        # button.grid(row=GRID_ROWS + 3, column=5)
        button.pack(anchor=Tkinter.S)

        # begin the event loop
        self.master.protocol("WM_DELETE_WINDOW", self.master.destroy)
        self.master.title(TEXT_TITLE)
        self.master.mainloop()

    def _search_internal(self):
        """Search the digital library in a separate thread."""
        query = self._entry.get()

        if len(query) >= 3:
            print "Searching library with query \"%s\"..." % query

            self._search_results = database.search_library(query)
            self._dual_box.fill(self._search_results)

            print "Found %d results." % len(self._search_results)

    def search(self, *args):
        """Search the digital library.

        :param args
        """
        thread.start_new_thread(self._search_internal, ())

    def select_cart(self, index):
        """Select a cart from the search results.

        :param index: index of cart in search results
        """
        if index is not None:
            self._selected_cart = self._search_results[index]

    def add_cart(self, key):
        """Add the selected cart to the grid.

        :param key
        """
        if not self._grid.has_cart(key) and self._selected_cart is not None:
            self._grid.set_cart(key, self._selected_cart)

    def _cart_start(self):
        """Start the meter when a cart starts."""
        self._meter.start()

    def _cart_stop(self):
        """Reset the meter when a cart stops."""
        self._meter.reset()

    def _cart_end(self, key):
        """Reset the meter when a cart ends.

        Also, if auto-queue is enabled, queue the next cart.

        :param key
        """
        self._meter.reset()

        if self._auto_queue.get():
            next_key = get_next_key(GRID_ROWS, GRID_COLS, key)
            if self._grid.has_cart(next_key):
                self._grid.start(next_key)

    def _get_meter_data(self):
        """Get meter data for the currently active cart."""
        return self._grid.get_active_cell().get_cart().get_meter_data()
Exemplo n.º 37
0
    def create_circular_meter(self, name):
        """ Create circular method
        
        :param name: meter name
        """
        config = self.meter_config[name]

        if config[CHANNELS] == 2:
            meter = Meter(self.util, TYPE_CIRCULAR, config[UI_REFRESH_PERIOD],
                          self.data_source)
            meter.channels = 2
        else:
            meter = Meter(self.util, TYPE_CIRCULAR, config[UI_REFRESH_PERIOD],
                          self.data_source)

        meter.steps_per_degree = config[STEPS_PER_DEGREE]
        start_angle = config[START_ANGLE]
        stop_angle = config[STOP_ANGLE]
        meter.incr = (abs(start_angle) + abs(stop_angle)) / 100
        meter.add_background(config[BGR_FILENAME])
        needle = meter.load_image(config[INDICATOR_FILENAME])[1]

        factory = NeedleFactory(needle, config)
        meter.needle_sprites = factory.needle_sprites

        if config[CHANNELS] == 2:
            meter.left_needle_rects = factory.left_needle_rects
            meter.right_needle_rects = factory.right_needle_rects
            meter.left_needle_rects = factory.left_needle_rects
            s = meter.needle_sprites[0]
            r = meter.left_needle_rects[0]
            meter.add_image(s, 0, 0, r)
            r = meter.right_needle_rects[0]
            meter.add_image(s, 0, 0, r)
        else:
            meter.mono_needle_rects = factory.mono_needle_rects
            s = meter.needle_sprites[0]
            r = meter.mono_needle_rects[0]
            meter.add_image(s, 0, 0, r)

        if config[FGR_FILENAME]:
            meter.add_foreground(config[FGR_FILENAME])

        return meter
Exemplo n.º 38
0
class CartMachine(Frame):
    """The CartMachine class is a GUI that provides a grid of carts."""
    _meter = None
    _grid = None

    def __init__(self):
        """Construct a CartMachine window."""
        Frame.__init__(self)

        # make the window resizable
        top = self.winfo_toplevel()
        for row in range(2, GRID_ROWS + 2):
            for col in range(0, GRID_COLS):
                top.rowconfigure(row, weight=1)
                top.columnconfigure(col, weight=1)
                self.rowconfigure(row, weight=1)
                self.columnconfigure(col, weight=1)

        # initialize the title
        title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE)
        title.grid(row=0, column=0, columnspan=GRID_COLS - 1, sticky=Tkinter.N)

        # initialize the reload button
        reload_button = Button(self.master, \
            bg=COLOR_RELOAD_BG, fg=COLOR_RELOAD_FG, \
            font=FONT_RELOAD, text=TEXT_RELOAD, \
            command=self.reload)
        reload_button.grid(row=0, column=GRID_COLS - 1)

        # initialize the meter
        self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data)
        self._meter.grid(row=1, column=0, columnspan=GRID_COLS)
        # self._meter.grid_propagate(0)

        # initialize the grid
        self._grid = Grid(self, GRID_ROWS, GRID_COLS, False, self._cart_start, self._cart_stop, self._cart_end, None)
        self._load()

        # begin the event loop
        self.master.protocol("WM_DELETE_WINDOW", self.master.destroy)
        self.master.title(TEXT_TITLE)
        self.mainloop()

    def _load(self):
        """Load the grid with carts.

        Since there are four cart types, each type is assigned
        to a corner of the grid, and the carts in that type expand
        from that corner. Carts are added one type at a time until
        the grid is full.

        Typically, since PSAs are the most numerous cart type, they
        fill middle space not covered by the other types.
        """

        # generate a progression of cells for each corner
        progs = {}
        for cart_type in CONFIG_CARTS:
            progs[cart_type] = progression(GRID_ROWS, GRID_COLS, CONFIG_CARTS[cart_type]["corner"])

        # get a dictonary of carts for each cart type
        carts = database.get_carts()

        # apply shuffling and limiting to each cart type
        for cart_type in carts:
            random.shuffle(carts[cart_type])

            limit = CONFIG_CARTS[cart_type]["limit"]
            if limit is not -1:
                carts[cart_type] = carts[cart_type][0:limit]

        # insert carts until the grid is full or all carts are inserted
        num_inserted = 0

        for i in range(0, max(GRID_ROWS, GRID_COLS)):
            for cart_type in carts:
                # insert a layer for each cart type
                num_toinsert = 1 + 2 * i

                while len(carts[cart_type]) > 0 and num_toinsert > 0:
                    # pop the first empty coordinate from the progression
                    key = progs[cart_type].pop(0)
                    while self._grid.has_cart(key):
                        key = progs[cart_type].pop(0)

                    # add the cart to the grid
                    self._grid.set_cart(key, carts[cart_type].pop(0))
                    num_inserted += 1
                    num_toinsert -= 1

                    # exit if the grid is full
                    if num_inserted is GRID_ROWS * GRID_COLS:
                        return

                # exit if all carts are inserted
                if len([key for key in carts if len(carts[key]) > 0]) is 0:
                    break

    def reload(self):
        """Reload the cart machine."""

        if self._grid.is_playing():
            return

        print "Reloading the Cart Machine..."
        self._grid.clear()
        self._load()
        print "Cart Machine reloaded."

    def _cart_start(self):
        """Start the meter when a cart starts."""
        self._meter.start()

    def _cart_stop(self):
        """Reset the meter when a cart stops."""
        self._meter.reset()

    def _cart_end(self, key):
        """Reset the meter when a cart ends."""
        self._meter.reset()

    def _get_meter_data(self):
        """Get meter data for the currently active cart."""
        return self._grid.get_active_cell().get_cart().get_meter_data()
Exemplo n.º 39
0
 def create_linear_meter(self, name):
     """ Create linear method
     
     :param name: meter name
     """
     config = self.meter_config[name]
     
     if config[CHANNELS] == 2:
         meter = Meter(self.util, TYPE_LINEAR, config[UI_REFRESH_PERIOD], self.data_source)
         meter.channels = 2
         meter.left_x = config[LEFT_X]
         meter.left_y = config[LEFT_Y]
         meter.right_x = config[RIGHT_X]
         meter.right_y = config[RIGHT_Y]            
     else:
         meter = Meter(self.util, TYPE_LINEAR, config[UI_REFRESH_PERIOD], self.data_source)
         meter.x = config[MONO_X]
         meter.y = config[MONO_Y]
     
     meter.positions_regular = config[POSITION_REGULAR]
     meter.step_width_regular = config[STEP_WIDTH_REGULAR]
     if POSITION_OVERLOAD in config:
         meter.positions_overload = config[POSITION_OVERLOAD]
         meter.step_width_overload = config[STEP_WIDTH_OVERLOAD]
     else:
         meter.positions_overload = 0
         meter.step_width_overload = 0
     meter.total_steps = meter.positions_regular + meter.positions_overload + 1
     meter.step = 100/meter.total_steps
     
     meter.add_background(config[BGR_FILENAME])
     
     if config[CHANNELS] == 2:
         meter.add_channel(config[INDICATOR_FILENAME], meter.left_x, meter.left_y)
         meter.add_channel(config[INDICATOR_FILENAME], meter.right_x, meter.right_y)
     else:
         meter.add_channel(config[INDICATOR_FILENAME], meter.x, meter.y)
     
     meter.add_foreground(config[FGR_FILENAME])
     
     factory = MaskFactory()
     meter.masks = factory.create_masks(meter.positions_regular, meter.positions_overload, meter.step_width_regular, meter.step_width_overload)
     
     return meter
Exemplo n.º 40
0
    def create_circular_meter(self, name):
        """ Create circular method
        
        :param name: meter name
        """
        config = self.meter_config[name]
        
        if config[CHANNELS] == 2:
            meter = Meter(self.util, TYPE_CIRCULAR, config[UI_REFRESH_PERIOD], self.data_source)
            meter.channels = 2
        else:
            meter = Meter(self.util, TYPE_CIRCULAR, config[UI_REFRESH_PERIOD], self.data_source)

        meter.steps_per_degree = config[STEPS_PER_DEGREE]                 
        start_angle = config[START_ANGLE]
        stop_angle = config[STOP_ANGLE]
        meter.incr = (abs(start_angle) + abs(stop_angle)) / 100
        meter.add_background(config[BGR_FILENAME])
        needle = meter.load_image(config[INDICATOR_FILENAME])[1]
        
        factory = NeedleFactory(needle, config)
        meter.needle_sprites = factory.needle_sprites
        
        if config[CHANNELS] == 2:
            meter.left_needle_rects = factory.left_needle_rects
            meter.right_needle_rects = factory.right_needle_rects
            meter.left_needle_rects = factory.left_needle_rects     
            s = meter.needle_sprites[0]
            r = meter.left_needle_rects[0]
            meter.add_image(s, 0, 0, r)
            r = meter.right_needle_rects[0]
            meter.add_image(s, 0, 0, r)
        else:
            meter.mono_needle_rects = factory.mono_needle_rects     
            s = meter.needle_sprites[0]
            r = meter.mono_needle_rects[0]
            meter.add_image(s, 0, 0, r)
        
        if config[FGR_FILENAME]:
            meter.add_foreground(config[FGR_FILENAME])
        
        return meter      
        
        
Exemplo n.º 41
0
class Automation(Frame):
    """The Automation class is a GUI that provides radio automation."""
    _state = None
    _button_text = None
    _button = None

    _meter = None
    _cart_queue = None

    _list_time = None
    _list_track = None
    _list_artist = None

    def __init__(self):
        """Construct an Automation window."""
        Frame.__init__(self)

        # initialize title
        title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE)
        title.grid(row=0, column=0, columnspan=3)

        # initialize button and state
        self._state = STATE_STOPPED

        self._button_text = StringVar()

        self._button = Button(self.master, textvariable=self._button_text, command=self._update_state, width=16, height=2)
        self._button.config(bd=2)
        self._button.grid(row=0, column=3)

        # initialize the meter
        self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data)
        self._meter.grid(row=1, column=0, columnspan=4)

        # initialize playlist view
        playlist = Frame(self.master, bd=2, relief=Tkinter.SUNKEN)
        Label(playlist, font=FONT, anchor=Tkinter.CENTER, width=16, text=TEXT_PLAYLIST_TIME).grid(row=0, column=0)
        Label(playlist, font=FONT, anchor=Tkinter.CENTER, width=32, text=TEXT_PLAYLIST_TRACK).grid(row=0, column=1)
        Label(playlist, font=FONT, anchor=Tkinter.CENTER, width=32, text=TEXT_PLAYLIST_ARTIST).grid(row=0, column=2)

        inner_playlist = Frame(playlist)
        scroll = Scrollbar(inner_playlist, orient=Tkinter.VERTICAL, command=self._scroll_playlist)
        self._list_time = Listbox(inner_playlist, selectmode=Tkinter.SINGLE, yscrollcommand=scroll.set, exportselection=0, width=16, height=20)
        self._list_track = Listbox(inner_playlist, selectmode=Tkinter.SINGLE, yscrollcommand=scroll.set, exportselection=0, width=32, height=20)
        self._list_artist = Listbox(inner_playlist, selectmode=Tkinter.SINGLE, yscrollcommand=scroll.set, exportselection=0, width=32, height=20)

        scroll.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)
        self._list_time.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True, padx=2, pady=2)
        self._list_track.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True, padx=2, pady=2)
        self._list_artist.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True, padx=2, pady=2)

        inner_playlist.grid(row=1, column=0, columnspan=3)
        playlist.grid(row=4, column=0, columnspan=4)

        # initialize cart queue
        self._cart_queue = CartQueue(self._cart_start, self._cart_stop)
        self._cart_queue.add_tracks()
        self._update_ui()

        # begin the event loop
        self.master.protocol("WM_DELETE_WINDOW", self.master.destroy)
        self.master.title(TEXT_TITLE)
        self.master.mainloop()

    def _scroll_playlist(self, *args):
        """Scroll the playlist view.

        :param args
        """
        self._list_time.yview(*args)
        self._list_track.yview(*args)
        self._list_artist.yview(*args)

    def _update_state(self):
        """Move Automation to the next state.

        The state machine is as follows:
        STATE_STOPPED -> STATE_PLAYING -> STATE_STOPPING -> STATE_STOPPED
        """
        if self._state is STATE_STOPPED:
            print "Starting Automation..."
            self._cart_queue.start()
            self._state = STATE_PLAYING
        elif self._state is STATE_PLAYING:
            print "Stopping Automation after this track..."
            self._cart_queue.stop_soft()
            self._state = STATE_STOPPING
        elif self._state is STATE_STOPPING:
            print "Stopping Automation immediately."
            self._cart_queue.transition()
            self._state = STATE_STOPPED
        self._update_ui()

    def _cart_start(self):
        """Start the meter when a cart starts."""
        self._meter.start()
        self._update_ui()

    def _cart_stop(self):
        """Reset the meter when a cart stops.

        Also, if a soft stop occured, update the button state.
        """
        self._meter.reset()

        if self._state is STATE_STOPPING:
            self._state = STATE_STOPPED
            self._update_ui()

    def _update_ui(self):
        """Update the button and playlist."""
        self._button_text.set(TEXT_BUTTON[self._state])
        self._button.config(bg=COLOR_BUTTON[self._state], highlightbackground=COLOR_BUTTON[self._state])

        self._list_time.delete(0, Tkinter.END)
        self._list_track.delete(0, Tkinter.END)
        self._list_artist.delete(0, Tkinter.END)

        for cart in self._cart_queue.get_queue():
            self._list_time.insert(Tkinter.END, cart.start_time.strftime("%I:%M:%S %p"))
            self._list_track.insert(Tkinter.END, cart.title)
            self._list_artist.insert(Tkinter.END, cart.issuer)

    def _get_meter_data(self):
        """Get meter data for the first track in the queue."""
        queue = self._cart_queue.get_queue()

        if len(queue) > 0:
            return queue[0].get_meter_data()
        else:
            return None
Exemplo n.º 42
0
def config_monitor(mid, rect):
    from meter import Meter;
    from widget.linear_meter import LinearMeterWidget;
    from widget.circle_meter import CircleMeterWidget;
    from widget.surface import SurfaceWidget;
    from widget.pango import PangoWidget;
    from monitor import Monitor;
    from datetime import datetime;
    import math;
    import cairo;

    c = Meter(300, 300);
    c.add_widget(LinearMeterWidget(LambdaMonitor(lambda : Monitor.get().cpu_usage), 
                                   145, 6, color = (1,1,1), alpha = 0.5,
                                   gravity = LinearMeterWidget.GRAVITY_EAST),
                 145, 300, 1, 1);
    c.add_widget(LinearMeterWidget(LambdaMonitor(lambda : Monitor.get().pmem_usage),
                                   145, 6, color = (1,1,1), alpha = 0.5,
                                   gravity = LinearMeterWidget.GRAVITY_WEST),
                 155, 300, -1, 1);
    c.add_widget(CircleMeterWidget(LambdaMonitor(lambda : (datetime.now().time().hour % 12) / 12.0), 
                                   140, 6, -math.pi / 2 + math.pi / 10, -math.pi / 2 - math.pi / 10,
                                   color=(1,1,1), alpha = 0.5, style = CircleMeterWidget.STYLE_SEGMENT),
                 150, 150, 0, 0);
    c.add_widget(CircleMeterWidget(LambdaMonitor(lambda : datetime.now().time().minute / 60.0 + datetime.now().time().second / 3600.0),
                                   128, 10, -math.pi / 2, -math.pi / 2,
                                   color=(1,1,1), alpha = 0.5),
                 150, 150, 0, 0);
    c.add_widget(CircleMeterWidget(LambdaMonitor(lambda : datetime.now().time().second / 60.0),
                                   112, 10, -math.pi / 2 - math.pi / 10, -math.pi / 2 + math.pi / 10,
                                   style=CircleMeterWidget.STYLE_SEGMENT, color=(1,1,1), alpha = 0.5), 
                 150, 150, 0, 0);
    c.add_widget(PangoWidget(LambdaMonitor(lambda :
                                           "<span font='Monospace 25'>" + datetime.now().strftime("%H%M%S") + "</span>\n" +
                                           "<span font='Monospace 20'>" + datetime.now().strftime("%y%m%d") + "</span>"),
                             color=(1,1,1), alpha = 0.5, alignment = "center"), 
                 150, 150, 0, 0);
            
    c.add_widget(PangoWidget(LambdaMonitor(lambda :
                                           "<span font='Monospace 20'>" + str(Monitor.get().gmail_unread_count) + "</span>"),
                             color=(1,1,1), alpha = 0.5, alignment = "center"), 
                 gmail_icon.get_width(), 0, -1, -1);

    c.add_widget(SurfaceWidget(gmail_icon, gmail_icon.get_width(), gmail_icon.get_height()),
                 0, 0, -1, -1);

    c.get_window().move(rect.x + (rect.width - c.width) / 2,
                        rect.y + (rect.height - c.height) / 2);
    c.show();