Exemplo n.º 1
0
 def AddLabel(self, text, fontobj):
     if self._Label == None:
         self._Label = Label()
         self._Label.Init(text, fontobj)
     else:
         #just replace the text
         self._Label._Init(text, fontobj)
Exemplo n.º 2
0
    def _draw_title(self, gc, label=None, axis_offset=None):
        """ Draws the title for the axis.
        """
        if label is None:
            title_label = Label(text=self.title,
                                font=self.title_font,
                                color=self.title_color,
                                rotate_angle=self.title_angle)
        else:
            title_label = label

        # get the _rotated_ bounding box of the label
        tl_bounds = array(title_label.get_bounding_box(gc), float64)
        text_center_to_corner = -tl_bounds/2.0
        # which axis are we moving away from the axis line along?
        axis_index = self._major_axis.argmin()

        if self.title_spacing != 'auto':
            axis_offset = self.title_spacing

        if (self.title_spacing) and (axis_offset is None ):
            if not self.ticklabel_cache:
                axis_offset = 25
            else:
                axis_offset = max([l._bounding_box[axis_index] for l in self.ticklabel_cache]) * 1.3

        offset = (self._origin_point+self._end_axis_point)/2
        axis_dist = self.tick_out + tl_bounds[axis_index]/2.0 + axis_offset
        offset -= self._inside_vector * axis_dist
        offset += text_center_to_corner

        gc.translate_ctm(*offset)
        title_label.draw(gc)
        gc.translate_ctm(*(-offset))
        return
Exemplo n.º 3
0
    def activate(self):
        ''' Activate button. '''

        Label.activate(self)
        if self._action:
            self._action(self)
        Label.deactivate(self)
Exemplo n.º 4
0
 def __init__(self, name):
     JCircle.__init__(self, 200)
     self._label = Label(name)
     self._label.translate(-self._label.getWidth() / 2.0,
                           -self._label.getHeight() / 2.0)
     self._links_to = []
     self._arcs = []
Exemplo n.º 5
0
def load_binary_syntetic(dataset, n_train):
    # splitting syntetic dataset
    X, Y = load_syntetic_dataset(dataset)

    Xnew = []
    Ynew = []
    for x, y in zip(X, Y):
        Xnew.append((x[0], x[1], np.ones((x[2].shape[0], 1))))
        y_ = y[:, 0].astype(np.int32)
        labels = np.unique(y_)
        y[y_ == labels[0], 0] = 0
        for l in labels[1:]:
            if l == 0:
                continue
            y[y_ == l, 0] = 1
        Ynew.append(y)

    X = Xnew
    Y = Ynew

    x_train = X[:n_train]
    y_train = [
        Label(y[:, 0].astype(np.int32), None, y[:, 1], True)
        for y in Y[:n_train]
    ]

    x_test = X[n_train:]
    y_test = [
        Label(y[:, 0].astype(np.int32), None, y[:, 1], True)
        for y in Y[n_train:]
    ]

    return x_train, y_train, x_test, y_test
Exemplo n.º 6
0
def run_game():
    ai_settings = Settings()
    pygame.init()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption(ai_settings.screen_caption)
    bg = Background(screen)
    bg2 = Background2(screen)
    ship = Ship(screen)
    bullets = Group()
    aliens = Group()
    stats = GameStats(ai_settings)
    play_button = Button(ai_settings, screen, "Play")
    game_over_label = Label(ai_settings, screen, "Game Over! Play again!", 250,
                            50, 175, 300)
    game_paused_label = Label(ai_settings, screen, "Game Paused", 250, 50, 175,
                              300)
    gf.create_fleet(ai_settings, screen, aliens)

    while True:
        gf.check_events(ai_settings, stats, screen, ship, aliens, bullets,
                        play_button)
        if stats.game_active == True:
            ship.update()
            gf.update_bullets(bullets, aliens, ai_settings, screen)
            gf.update_aliens(aliens, ship, ai_settings, stats, screen, bullets)
        gf.update_screen(ai_settings, stats, screen, bg, bg2, ship, aliens,
                         bullets, play_button, game_over_label,
                         game_paused_label)
Exemplo n.º 7
0
    def test_doubled_abstract(self):

        test_data = lineify(
            textwrap.dedent("""\
        [@New records of smut fungi. 4. Microbotryum coronariae comb. nov.#Title*]
        [@Cvetomir M. Denchev & Teodor T. Denchev#Author*]
        [@Institute of Biodiversity and Ecosystem Research, Bulgarian Academy of Sciences,
        2 Gagarin St., 1113 Sofia, Bulgaria#Institution*]
        * Correspondence to: [email protected]
        [@Abstract — For Ustilago coronariae on Lychnis flos-cuculi, a new combination in
        Microbotryum, M. coronariae, is proposed. It is reported as new to Bulgaria.#Abstract*]
        [@Key words — Microbotryaceae, nomenclature#Key-words*]
        """).split('\n'))

        paragraphs = list(finder.parse_paragraphs(test_data))

        self.assertEqual(len(paragraphs), 6)
        self.assertEqual(paragraphs[0].labels, [Label('Title')])
        self.assertEqual(paragraphs[1].labels, [Label('Author')])
        self.assertEqual(paragraphs[2].labels, [Label('Institution')])
        self.assertEqual(paragraphs[3].labels, [])  # correspondence
        self.assertEqual(
            paragraphs[4].labels,
            [Label('Abstract'), Label('Key-words')])
        self.assertEqual(paragraphs[5].labels, [])  # Paragraph('\n')
Exemplo n.º 8
0
    def update(self):
        if self.expired > time.time():
            self.surface.fill((1, 1, 1))
            emSurf = pygame.Surface((self.x, self.y))
            emSurf.fill(self.colour)

            textSurfL = self.font.render('EM_L: ' + self.labels[self.emL],
                                         True, (0, 0, 0))
            textRectL = textSurfL.get_rect()
            textRectL.center = (self.x / 2, self.y / 2 - 10)

            textSurfR = self.font.render('EM_R: ' + self.labels[self.emR],
                                         True, (0, 0, 0))
            textRectR = textSurfR.get_rect()
            textRectR.center = (self.x / 2, self.y / 2 + 10)

            emSurf.blit(textSurfL, textRectL)
            emSurf.blit(textSurfR, textRectR)
            self.surface.blit(emSurf,
                              ((self.order - 1) * (self.screen_width - self.x),
                               self.screen_height - self.y))
        else:
            self.surface.fill((1, 1, 1))
            label = Label(self.screen_width,
                          self.screen_height, (1, self.order - 1),
                          14,
                          bgColour=self.colour)
            text = 'EM_L: ' + self.labels[self.emL] + ' EM_R: ' + self.labels[
                self.emR]
            self.surface.blit(label.update(text), (0, 0))
        return self.surface
Exemplo n.º 9
0
    def activate(self):
        ''' Activate button. '''

        Label.activate(self)
        if self._on_click:
            self._on_click(self)
        self.deactivate()
Exemplo n.º 10
0
def load_msrc(n_full, n_train, dense=False):
    # loading & splitting MSRC dataset
    MSRC_DATA_PATH = '/home/dmitry/Documents/Thesis/data/msrc/msrc.hdf5'

    x_train, y_train_raw, x_test, y_test = load_msrc_hdf(MSRC_DATA_PATH)
    y_test = [
        Label(y[:, 0].astype(np.int32), None,
              y[:, 1].astype(np.float64) / np.sum(y[:, 1]), True)
        for y in y_test
    ]

    if n_train != n_full:
        train_mask = load_msrc_weak_train_mask(MSRC_DATA_PATH,
                                               n_full)[:n_train]
    else:
        train_mask = [True for i in xrange(len(y_train_raw))]
    y_train_full = [
        Label(y[:, 0].astype(np.int32), None, y[:, 1], True)
        for y in y_train_raw
    ]
    y_train = []
    for y, f in zip(y_train_raw, train_mask):
        if f:
            y_train.append(Label(y[:, 0].astype(np.int32), None, y[:, 1],
                                 True))
        else:
            y_train.append(
                Label(None, np.unique(y[:, 0].astype(np.int32)), y[:, 1],
                      False))

    x_train = [(x[0].toarray(), x[1], x[2]) for x in x_train]
    x_test = [(x[0].toarray(), x[1], x[2]) for x in x_test]

    return x_train, y_train, y_train_full, x_test, y_test
Exemplo n.º 11
0
    def activate(self):
        ''' Activate button. '''

        Label.activate(self)
        if self._on_click:
            self._on_click(self)
        self.deactivate()
Exemplo n.º 12
0
class IncrementLabel:
    step = 10

    def __init__(self, context, text, parameter, x, y):
        ''' A visual display for displaying and incrementing parametric.Parameter
            values in fixed steps.
        '''
        x *= context.xscale
        y *= context.yscale
        self.parameter = parameter
        fontsize = 80
        Label(context, text, int(x), int(y), fontsize, context.black, centered=False)
        context.add_widget(IconButton(context, "./icons/remove-circle.png", x+120, y+18, self.minus_x, scale=1.25))
        self.value = Label(context, '+200.0', x+160, y, fontsize, context.black, centered=False)
        context.add_widget(IconButton(context, "./icons/add-circle.png", x+370, y+18, self.plus_x, scale=1.25))
        self.update(self.parameter.value)

    def minus_x(self):
        self.update(str(float(self.value.text)-self.step))

    def plus_x(self):
        self.update(str(float(self.value.text)+self.step))

    def update(self, text):
        text = '{:>+{w}.{p}f}'.format(float(text), w=5, p=1)
        self.parameter(float(text))
        index=-1
        self.value.update(text)
        print(self.parameter)
Exemplo n.º 13
0
    def activate(self):
        ''' Activate button. '''

        Label.activate(self)
        if self._action:
            self._action(self)
        Label.deactivate(self)
    def SetSmallText(self, text):

        l = Label()
        l._PosX = 40
        l.SetCanvasHWND(self._Parent._CanvasHWND)
        l.Init(text, self._Fonts["small"])
        self._Labels["Small"] = l
Exemplo n.º 15
0
class Game:
    def __init__(self):
        pygame.init()
        self.is_over = False
        self.game_display = pygame.Surface(config.WINDOW_SIZE)
        self.cells = []
        self.snake = Snake(config.SNAKE_START_RECT, 6)
        self.items_manager = ItemsManager(1)

        self.clock = pygame.time.Clock()
        self.score_label = Label("0", "Consolas", 30, colors.WHITE)

    def update_scene(self):
        self.game_display = pygame.display.set_mode(config.WINDOW_SIZE)
        while not self.is_over:
            self.game_display.fill(colors.BACKGROUND_COLOR)

            if self.snake.rect.colliderect(self.items_manager.item.rect):
                self.snake.score += 1
                self.score_label.set_text(str(self.snake.score))
                self.items_manager.append_item()
                #for i in range(3):
                #self.snake.snake_body.insert(0, list([self.snake.rect.x, self.snake.rect.y]))
            else:
                self.snake.snake_body.pop()

            for snake_pos in self.snake.snake_body[1:]:
                if self.snake.snake_body[0] == snake_pos:
                    print("test")
                    sys.exit(-1)

            pygame.draw.rect(self.game_display, self.items_manager.item.color,
                             self.items_manager.item.rect)

            self.snake.update(config.WINDOW_SIZE)
            for tail in self.snake.snake_body:
                pygame.draw.rect(self.game_display, colors.WHITE,
                                 pygame.Rect(tail[0], tail[1], 15, 15))

            self.game_display.blit(self.score_label.text_obj, [0, 0])

            self.event_handler()
            pygame.display.flip()
            self.clock.tick(60)

    def event_handler(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                print("Close!")
                self.is_over = True
                return
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    self.snake.set_direction(Direction.UP)
                if event.key == pygame.K_RIGHT:
                    self.snake.set_direction(Direction.RIGHT)
                if event.key == pygame.K_DOWN:
                    self.snake.set_direction(Direction.DOWN)
                if event.key == pygame.K_LEFT:
                    self.snake.set_direction(Direction.LEFT)
Exemplo n.º 16
0
    def _draw_title(self, gc, label=None, axis_offset=None):
        """ Draws the title for the axis.
        """
        if label is None:
            title_label = Label(text=self.title,
                                font=self.title_font,
                                color=self.title_color,
                                rotate_angle=self.title_angle)
        else:
            title_label = label

        # get the _rotated_ bounding box of the label
        tl_bounds = array(title_label.get_bounding_box(gc), float64)
        text_center_to_corner = -tl_bounds/2.0
        # which axis are we moving away from the axis line along?
        axis_index = self._major_axis.argmin()

        if self.title_spacing != 'auto':
            axis_offset = self.title_spacing

        if (self.title_spacing) and (axis_offset is None ):
            if not self.ticklabel_cache:
                axis_offset = 25
            else:
                axis_offset = max([l._bounding_box[axis_index] for l in self.ticklabel_cache]) * 1.3

        offset = (self._origin_point+self._end_axis_point)/2
        axis_dist = self.tick_out + tl_bounds[axis_index]/2.0 + axis_offset
        offset -= self._inside_vector * axis_dist
        offset += text_center_to_corner

        gc.translate_ctm(*offset)
        title_label.draw(gc)
        gc.translate_ctm(*(-offset))
        return
Exemplo n.º 17
0
    def __init__(self, easy_questions, average_questions, hard_questions):
        super().__init__(is_visible=False)
        self._show_highlight = False
        self._highlighted_index = 0
        self._selected_question = None

        self._choose_question_label = Label("Choose a question difficulty:", 0,
                                            0)
        easy_question_label = Button('Easy', 0, 0,
                                     lambda: self._on_difficulty_clicked(0))
        average_question_label = Button('Average', 0, 0,
                                        lambda: self._on_difficulty_clicked(1))
        hard_question_label = Button('Hard', 0, 0,
                                     lambda: self._on_difficulty_clicked(2))

        total_w = self._choose_question_label.get_size()[0] + 25 + easy_question_label.get_size()[0] + 25 + \
            average_question_label.get_size()[0] + 25 + hard_question_label.get_size()[0]

        self._choose_question_label.x = SCREEN_WIDTH / 2 - total_w / 2
        easy_question_label.x = self._choose_question_label.x + self._choose_question_label.get_size(
        )[0] + 25
        average_question_label.x = easy_question_label.x + easy_question_label.get_size(
        )[0] + 25
        hard_question_label.x = average_question_label.x + average_question_label.get_size(
        )[0] + 25

        self._questions = [easy_questions, average_questions, hard_questions]
        self._buttons = [
            easy_question_label, average_question_label, hard_question_label
        ]

        get_game().register('on_draw', self.on_draw)

        for btn in self._buttons:
            get_game().register_button_mouse_events(btn)
Exemplo n.º 18
0
    def __init__(self, name, label = None,
                 vmin=None, vmax=None, vstep=None, vformat=None,
                 getter=None, setter=None, on_change=None,
                 namespace=locals(), read_only=False):
        ''' '''
        self._name = name
        self._namespace = namespace
        self._read_only = read_only
        self._getter = getter
        self._setter = setter
        self._on_change = on_change
        self._type = None
        if '.' in name:
            self._object = eval(string.join(name.split('.')[:-1],'.'),namespace)
            self._attribute = name.split('.')[-1]
            self._type = type(getattr(self._object, self._attribute))
        else:
            self._object = None
            self._attribute = None
            self._type = type(namespace[name])

        # Create dedicated entry
        if self._type == bool:
            self._entry = BoolEntry(value=self.get(), on_change=on_change,
                                    getter=self.get, setter=self.set)
        elif self._type == int:
            if vmin == None:
                vmin = -sys.maxint-1
            if vmax == None:
                vmax = sys.maxint
            vstep = vstep or 1
            vformat = vformat or '%d'
            self._entry = ScalarEntry(value=self.get(), on_change=on_change,
                                      getter=self.get, setter=self.set,
                                      vmin=vmin, vmax=vmax, vstep=vstep, vformat=vformat)
        elif self._type == float:
            if vmin == None:
                vmin = -sys.maxint-1
            if vmax == None:
                vmax = sys.maxint
            vstep = vstep or 0.1
            vformat = vformat or '%.2f'
            self._entry = ScalarEntry(self.get(), on_change=on_change,
                                      getter=self.get, setter=self.set,
                                      vmin=vmin, vmax=vmax, vstep=vstep,vformat=vformat) 
        elif self._type == str:
            self._entry = TextEntry(self.get(), self.get, self.set, on_change=on_change)
        else:
            self._entry = Label(str(self.get()))

        if self._read_only:
            self._entry.focusable = False
            self._entry.activable = False

        if label:
            self._label = Label(label)
        else:
            self._label = Label(name)        
        HBox.__init__(self, [self._label, self._entry], homogeneous=True)
Exemplo n.º 19
0
    def __init__(self, text='Label', on_click=None):
        ''' Creates button. '''

        Label.__init__(self, text)
        self._focusable = True
        self._activable = True
        self._on_click = on_click
        self.style = theme.Button
Exemplo n.º 20
0
 def _update_value(self, dt):
     value = self._getter()
     if value != self._active:
         self._active = value
         if self._active:
             Label.activate(self)
         else:
             Label.deactivate(self)
Exemplo n.º 21
0
 def __init__(self):
     self._share = type(self).START_SHARE
     self._share_diff_sum = 0
     self._last_share_diff = 0
     self._label = Label('', 0, 0, font_size=20)
     self._diff_label = Label('', 0, 0, font_size=20)
     self.update()
     get_game().register('on_draw', self.on_draw)
Exemplo n.º 22
0
    def __init__(self, text='Label', on_click=None):
        ''' Creates button. '''

        Label.__init__(self, text)
        self._focusable = True
        self._activable = True
        self._on_click = on_click
        self.style = theme.Button
Exemplo n.º 23
0
 def _update_value(self, dt):
     value = self._getter()
     if value != self._active:
         self._active = value
         if self._active:
             Label.activate(self)
         else:
             Label.deactivate(self)
Exemplo n.º 24
0
def render_title_menu_screen(app, MOUSE_POS=None):
    '''(App, tuple) -> NoneType'''
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)

    app.ui_elements.clear()  # remove old ui elements in old screen, if any

    FONT_FAMILY = join("data", "font", "Alien-Encounters-Regular.ttf")
    FONT_SIZE = 30
    FONT_COLOUR = WHITE

    app.background = BLACK
    app.window.fill(BLACK)

    # title
    TEXT = app.title
    COORD = (100, 100)
    title_label = Label(TEXT, COORD, FONT_FAMILY, FONT_SIZE, FONT_COLOUR)
    app.ui_elements.append(title_label)
    title_label.render(app.window)

    # levels button
    COORD = (100, 200)
    WIDTH = 800
    HEIGHT = 40
    TEXT = "levels"
    FOO = render_level_menu_screen
    levels_button = Button(COORD,
                           WIDTH,
                           HEIGHT,
                           TEXT,
                           FONT_FAMILY,
                           FONT_SIZE,
                           COLOUR=FONT_COLOUR,
                           FOO=FOO)
    app.ui_elements.append(levels_button)
    levels_button.render(app.window)

    # exit button
    COORD = (100, 300)
    WIDTH = 800
    HEIGHT = 40
    TEXT = "exit"
    FOO = exit_app
    exit_button = Button(COORD,
                         WIDTH,
                         HEIGHT,
                         TEXT,
                         FONT_FAMILY,
                         FONT_SIZE,
                         COLOUR=FONT_COLOUR,
                         FOO=FOO)
    app.ui_elements.append(exit_button)
    exit_button.render(app.window)

    app.to_update.append(None)  # update whole software display

    app.status = 0
Exemplo n.º 25
0
 def __init__(self, text, link, enable_gaussian=True, 
              text_color=ui_theme.get_color("link_text")):
     '''Init link button.'''
     Label.__init__(self, text, text_color, enable_gaussian=enable_gaussian, text_size=9,
                    gaussian_radious=1, border_radious=0)
     
     self.connect("button-press-event", lambda w, e: run_command("xdg-open %s" % link))
     
     set_clickable_cursor(self)
Exemplo n.º 26
0
    def test_load_from_db(self):
        label = Label()
        label.load_from_db(1, self.connection)

        self.assertEquals(label.id, 1)
        self.assertEquals(label.day, "SUN, AM")
        self.assertEquals(label.sermon_title, "Test Title")
        self.assertEquals(label.minister, "H.L. Sheppard")
        self.assertEquals(label.date, datetime.date(2014, 1, 1))
    def Init(self, text):

        #self._Fonts["normal"] = fonts["Eurostile12"]

        l = Label()
        l._PosX = 10
        l.SetCanvasHWND(self._Parent._CanvasHWND)

        l.Init(text, self._Fonts["normal"])
        self._Labels["Text"] = l
Exemplo n.º 28
0
    def __init__(self):
        pygame.init()
        self.is_over = False
        self.game_display = pygame.Surface(config.WINDOW_SIZE)
        self.cells = []
        self.snake = Snake(config.SNAKE_START_RECT, 6)
        self.items_manager = ItemsManager(1)

        self.clock = pygame.time.Clock()
        self.score_label = Label("0", "Consolas", 30, colors.WHITE)
Exemplo n.º 29
0
class Map:
    def __init__(self, window_width, window_height, map_file):
        self.krakow_map = pyglet.image.load(map_file)
        self.krakow_map.anchor_x = self.krakow_map.width // 2
        self.krakow_map.anchor_y = self.krakow_map.height // 2
        self.label = Label(window_width)

    def draw(self, window_width, window_height, x, y):
        self.krakow_map.blit(x, y)
        self.label.draw(window_width)
Exemplo n.º 30
0
    def activate(self):
        ''' Activate toggle button. '''

        Label.activate(self)
        if not self._active:
            self._active = True
        else:
            self._active = False
        if self._on_click:
            self._on_click(self)
        Label.deactivate(self)
Exemplo n.º 31
0
    def activate(self):
        ''' Activate toggle button. '''

        Label.activate(self)
        if not self._active:
            self._active = True
        else:
            self._active = False
        if self._on_click:
            self._on_click(self)
        Label.deactivate(self)
Exemplo n.º 32
0
def main() -> None:
    people = [
        Person(Label("Alice"), Label("*****@*****.**")), 
        Person(Label("Boby"), Label("*****@*****.**")), 
        Person(Label("Chirs"), None)
    ]

    for p in people:
        print(p)
        p.display()
        print("")
Exemplo n.º 33
0
    def load_label(self, filename):
        """Loads a label if not already loaded.

        :params filename: filename of the label
        :raises Exception: if a label is already loaded
        """
        if self.label is None:
            self.label = Label(filename)
            self.label_file = filename
        else:
            raise Exception('Label is already loaded')
Exemplo n.º 34
0
	def create_design_page(self,notebook,page_num):
		frame = notebook.get_frame(page_num)

		self.label_dict["# Parameters"] = Label(frame, "# Parameters")
		w1 = Dropdown(frame, ["1 Parameter", "2 Parameters"])

		self.label_dict["Variable 1"] = Label(frame, "Variable 1")
		w2 = Dropdown(frame, self.var_names)

		self.label_dict["Variable 2"] = Label(frame, "Variable 2")
		w3 = Dropdown(frame, self.var_names)
Exemplo n.º 35
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((200,200),16)
    back = pygame.Surface(screen.get_size(),16)
    ##color = (238,238,230)
    color = (255,255,255)
    back.fill(color)
    screen.blit(back,(0,0))

    clock = pygame.time.Clock()
    
    MyEvent = Event()


    cb_images = []
    cb_images.append(load_image(os.path.join('data'),'checkbox_off.png'))
    cb_images.append(load_image(os.path.join('data'),'checkbox_on.png'))

    b_images = []
    b_images.append(load_image(os.path.join('data'),'button_off.png'))
    b_images.append(load_image(os.path.join('data'),'button_on.png'))

    checkbox = CheckBox('Check me',cb_images,(10,40))
    button = Button('Click me',b_images,(10,80))
    label = Label('Hola ...',(10,120))
    textbox = TextField('',100,(10,160))

    

    while 1:
        btn = 0
        key = 0
        
        clock.tick(40)

        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    return
                else:
                    key = event.key
            elif event.type == MOUSEBUTTONDOWN:
                btn = event.button
                
        checkbox.notify(MyEvent, btn)
        button.notify(MyEvent)
        textbox.notify(MyEvent, key)
        
        label.update(screen)
        button.update(screen)
        textbox.update(screen)
        checkbox.update(screen)

        pygame.display.flip()
Exemplo n.º 36
0
 def fetch_mailboxes(self):
     response, mailbox_list = self.imap.list()
     if response == 'OK':
         for mailbox in mailbox_list:
             mailbox_name = mailbox.split('"/"')[-1].replace('"', '').strip()
             mailbox = Mailbox(self)
             mailbox.external_name = mailbox_name
             if mailbox_name.split('/')[0] !='[Gmail]':
                 label = Label(self)
                 label.label_tree = mailbox_name
                 self.labels[mailbox_name] = label
             self.mailboxes[mailbox_name] = mailbox
Exemplo n.º 37
0
 def __init__(self, x, y, specialist_instance, selectable=False):
     self.surface = Surface((200, 60))
     self.specialist = specialist_instance
     self.s_type = Label(0, 0, specialist.mapping[specialist_instance.s_type])
     self.s_exp = Label(0, 40, "")
     self.s_level = Label(0, 20, "")
     self.selectable = selectable
     self.selected = False
     self.x = x
     self.y = y
     self.w = 200
     self.h = 60
Exemplo n.º 38
0
 def __init__(self, context, text, parameter, x, y):
     ''' A visual display for displaying and incrementing parametric.Parameter
         values in fixed steps.
     '''
     x *= context.xscale
     y *= context.yscale
     self.parameter = parameter
     fontsize = 80
     Label(context, text, int(x), int(y), fontsize, context.black, centered=False)
     context.add_widget(IconButton(context, "./icons/remove-circle.png", x+120, y+18, self.minus_x, scale=1.25))
     self.value = Label(context, '+200.0', x+160, y, fontsize, context.black, centered=False)
     context.add_widget(IconButton(context, "./icons/add-circle.png", x+370, y+18, self.plus_x, scale=1.25))
     self.update(self.parameter.value)
Exemplo n.º 39
0
 def __init__(self, id, center, canvas, color=VERTEX_FILL_COLOR):
     Element.__init__(self, id)
     self.center = center
     self.color = color
     self.canvas = canvas
     self.degree = 0
     self.edgeGroups = []
     self.label = Label(
         id, id, Point(center.x + VERTEX_RADIUS, center.y - VERTEX_RADIUS))
     self.degree = 0
     self.degreeLabel = Label(
         id, self.degree,
         Point(center.x - VERTEX_RADIUS, center.y - VERTEX_RADIUS), 'red')
Exemplo n.º 40
0
	def create_simulate_page(self,notebook,page_num):
		frame = notebook.get_frame(page_num)

		b1 = Button(frame,'SIMULATE')

		self.label_dict["# Parameters"] = Label(frame, "Event")
		w1 = Dropdown(frame, ["Endurance","Acceleration","Skidpad","All"])

		self.label_dict["Variable 1"] = Label(frame, "Car Selection")
		w2 = Dropdown(frame, ["None"])

		self.label_dict["Variable 2"] = Label(frame, "Track selection")
		w3 = Dropdown(frame, ["Michigan","Germany"])
Exemplo n.º 41
0
    def createWidgets (self):
        "Creates all widgets for the dialog."
        # labels
        self.wm.register ( Label (self.titlefont, "Select a scenario", (10, 10), color=(255, 0, 0)))

        # start index for the labels
        x = 100
        y = 100
        
        # create a scenario manager if we don't already have one. This will read the scenarios from
        # the server
        if scenario.scenario_manager == None:
            scenario.scenario_manager = ServerScenarioManager ()
    
            # read in all scenario info:s
            scenario.scenario_manager.loadScenarioIndex ( properties.path_scenarios )

        # start from index 0
        index = 0
        
        # loop over all infos we got
        for info in scenario.scenario_manager.getScenarios ():
            # get the name and location
            name = info.getName ()
            location = info.getLocation ()

            # get the date and create a string
            (year, month, day, hour, minute) = info.getDate ()
            date = `year` + "." + `month` + "." + `day` + " " + `hour` + ":" + `minute`

            # create a label
            text = name + ", " + location + ", " + date

            # create a label
            label = Label (self.smallfont, text, (x, y), color=(255, 255, 255),
                           callbacks = {widget.MOUSEBUTTONUP : self.select } )

            # register it
            self.wm.register ( label )

            # make sure we know the filename from the label later
            self.namemap [text] = ( index, info )
           
            # increment the y-offset and index
            y += label.getHeight () + 5
            index += 1

        # buttons. We create only the Cancel button so far, the other are created later
        self.wm.register ( Button ( properties.path_dialogs + "butt-cancel-moff.png",
                                    properties.path_dialogs + "butt-cancel-mover.png",
                                    (650, 650 ), {widget.MOUSEBUTTONUP : self.cancel } ) )
Exemplo n.º 42
0
    def __init__(self, text='Label', action=None):
        '''
        :Parameters:

        `text` : str
            Text to be displayed within button
        `action` : function(button)
            Action to be executed when button is toggled
        '''

        Label.__init__(self, text)
        self._focusable = True
        self._activable = True
        self._action = action
        self.style = theme.Button
Exemplo n.º 43
0
    def _compute_labels(self, gc):
        """Generates the labels for tick marks.

        Overrides PlotAxis.
        """
        try:
            self.ticklabel_cache = []
            for text in self._tick_label_list:
                ticklabel = Label(text=text, font=self.tick_label_font,
                                  color=self.tick_label_color,
                                  rotate_angle=self.label_rotation)
                self.ticklabel_cache.append(ticklabel)

            self._tick_label_bounding_boxes = [array(ticklabel.get_bounding_box(gc), float64) for ticklabel in self.ticklabel_cache]
        except:
            print_exc()
        return
Exemplo n.º 44
0
def handle_exception(ex, stacktrace=None):
    err_icon = os.path.join(os.path.dirname(__file__), 'graphics', 'icon_error.gif')
    frm = Form(caption='Exception: {}'.format(ex.__class__.__name__),
               left=100, top=100, width=350, height=180)
    frm.resizable = False
    msg = Label(frm, left=45, top=5, width=305, height=40, caption=ex.message)
    msg.wordwrap = True
    img = Image(frm, left=5, top=15, width=32, height=32, file=err_icon)
    trace = Memo(frm, left=5, top=55, width=335, height=90)
    trace.text = stacktrace

    def close_form():
        frm.close()
    
    btn = Button(frm, left=140, top=148, width=65, height=27, caption="Close")
    btn.on_click = close_form
    frm.show_modal()
Exemplo n.º 45
0
def render_title_menu_screen(app, MOUSE_POS=None):
    '''(App, tuple) -> NoneType'''
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)

    app.ui_elements.clear() # remove old ui elements in old screen, if any

    FONT_FAMILY = join("data", "font", "Alien-Encounters-Regular.ttf")
    FONT_SIZE = 30
    FONT_COLOUR = WHITE

    app.background = BLACK
    app.window.fill(BLACK)

    # title
    TEXT = app.title
    COORD = (100, 100)
    title_label = Label(TEXT, COORD, FONT_FAMILY, FONT_SIZE, FONT_COLOUR)
    app.ui_elements.append(title_label)
    title_label.render(app.window)

    # levels button
    COORD = (100, 200)
    WIDTH = 800
    HEIGHT = 40
    TEXT = "levels"
    FOO = render_level_menu_screen
    levels_button = Button(COORD, WIDTH, HEIGHT, TEXT, FONT_FAMILY, FONT_SIZE,
            COLOUR=FONT_COLOUR, FOO=FOO)
    app.ui_elements.append(levels_button)
    levels_button.render(app.window)

    # exit button
    COORD = (100, 300)
    WIDTH = 800
    HEIGHT = 40
    TEXT = "exit"
    FOO = exit_app
    exit_button = Button(COORD, WIDTH, HEIGHT, TEXT, FONT_FAMILY, FONT_SIZE,
            COLOUR=FONT_COLOUR, FOO=FOO)
    app.ui_elements.append(exit_button)
    exit_button.render(app.window)

    app.to_update.append(None) # update whole software display

    app.status = 0
Exemplo n.º 46
0
  def setHidden(self, hidden):
    if self.hidden and not hidden:
      if framework.world and framework.world.scene:
        scene = framework.world.scene
        analyzer = panda.SceneGraphAnalyzer()
        analyzer.addNode(scene.node())
        
        text = "Scene: %s / Layer: %s\n" % (scene.name,
          framework.layers[scene.activeLayer])
        text += ("(Nodes: %d, Vertices: %d, Faces: %d, Memory: %.2f MB)" %
          (analyzer.getNumNodes(), analyzer.getNumVertices(),
          analyzer.getNumTris(), (analyzer.getVertexDataSize()+
          analyzer.getTextureBytes())/float(2**20)))
      else:
        text = "Scene statistics n/a"

      self.text = text
      
    Label.setHidden(self, hidden)
Exemplo n.º 47
0
 def setHidden(self, hidden):
   if self.hidden and not hidden:
     text = "%s [Build: %s on %s %s]\n\n" % (
       framework.configuration.fullName,
       framework.configuration.buildType,
       framework.configuration.buildSystem,
       framework.configuration.buildArchitecture)
     text += "Author(s): %s (%s)\n" % (
       framework.configuration.authors,
       framework.configuration.contact)
     text += "License: %s\n\n" % framework.configuration.license
     
     text += "You may use the following keyboard shortcuts:\n"
     for key in sorted(framework.shortcuts.iterkeys()):
       description = framework.shortcuts[key]
       text += "* "+key.upper()+": "+description+"\n"
       
     self.text = text
     
   Label.setHidden(self, hidden)
Exemplo n.º 48
0
 def __init__(self,caption=""):
     BasicContainer.__init__(self)
     self.mHasMouse=False
     self.mTabbedArea=None
     self.mLabel=Label()
     self.mLabel.setPosition(4,4)
     self.setCaption(caption)
     self.add(self.mLabel)
     
     self.addMouseListener(self)
     self.addFocusListener(self)
Exemplo n.º 49
0
 def __init__(self, items, droplist_height=None, select_index=0, max_width=None):
     '''Init combo box.'''
     # Init.
     gtk.VBox.__init__(self)
     self.set_can_focus(True)
     self.items = items
     self.droplist_height = droplist_height
     self.select_index = select_index
     self.focus_flag = False
     
     self.droplist = Droplist(self.items, max_width=max_width)
     if self.droplist_height:
         self.droplist.set_size_request(-1, self.droplist_height)
     self.width = self.droplist.get_droplist_width() 
     self.height = 22
     self.label_padding_left = 6
     self.box = gtk.HBox()
     self.dropbutton_width = ui_theme.get_pixbuf("combo/dropbutton_normal.png").get_pixbuf().get_width()
     self.label = Label(self.items[select_index][0], 
                        label_width=self.width - self.dropbutton_width - 1 - self.label_padding_left,
                        enable_select=False,
                        enable_double_click=False)
     self.label.text_color = ui_theme.get_color("menu_font")
     self.dropbutton = DisableButton(
         (ui_theme.get_pixbuf("combo/dropbutton_normal.png"),
          ui_theme.get_pixbuf("combo/dropbutton_hover.png"),
          ui_theme.get_pixbuf("combo/dropbutton_press.png"),
          ui_theme.get_pixbuf("combo/dropbutton_disable.png")),
         )
             
     self.align = gtk.Alignment()
     self.align.set(0.5, 0.5, 0.0, 0.0)
     self.align.set_padding(1, 1, 1 + self.label_padding_left, 1)
     
     self.pack_start(self.align, False, False)
     self.align.add(self.box)
     self.box.pack_start(self.label, False, False)
     self.box.pack_start(self.dropbutton, False, False)
     
     self.align.connect("expose-event", self.expose_combobox_frame)
     self.label.connect("button-press-event", self.click_drop_button)
     self.dropbutton.connect("button-press-event", self.click_drop_button)
     self.droplist.connect("item-selected", self.update_select_content)
     self.droplist.connect("key-release", lambda dl, s, o, i: self.emit("key-release", s, o, i))
     self.connect("key-press-event", self.key_press_combo)
     self.connect("key-release-event", self.key_release_combo)
     self.connect("focus-in-event", self.focus_in_combo)
     self.connect("focus-out-event", self.focus_out_combo)
     
     self.keymap = {
         "Home" : self.select_first_item,
         "End" : self.select_last_item,
         "Up" : self.select_prev_item,
         "Down" : self.select_next_item}
Exemplo n.º 50
0
    def init(self):
        Focusable.__init__(self)
        self.minWidth = self.size[0]
        self.minHeight = self.size[1]

        self.bgLabel = Label(self, level=10, size=self.size, text='', bgcolor=self.bgcolor)
        self.hoverButton = TransButton(self, level=11, size=self.size)
        self.txtLabel = Label(self, level=12, size=self.size, 
                color=self.color, text=self.text, bgcolor=COLOR_TRANS)

        self.redraw()
        self.bind(EV_CLICK, self.set_as_focus, BLK_PRE_BLOCK)

        self._editing = False
        Timer.add(Timer(1./FPS, self.animate))
        self.blinker = ColorAnimate(self.bgcolor, self.bgcolor)

        self.confirmCallBacks = []
        self.changeCallBacks = []
        self._confirmed = False
Exemplo n.º 51
0
class List:
  def __init__(self, x, y, w, title, entries=None):
    self.x = x
    self.y = y
    self.w = w
    self.h = len(entries) + 2
    x += 2
    w -= 4
    self.tlabel = Label(x,y,w,title, align=Label.ALIGN_CENTER, fg=COLOR_LIGHT_GREY)
    self.labels = []
    y += 1
    self.lx = x
    self.ly = y
    self.lw = w
    if entries != None:
      self.add_entries(entries)
    
  def add_entries(self, entries):
    y = self.ly
    for e in entries:
      l = Label(self.lx,y,self.lw,e)
      self.labels.append(l)
      y += 1
    self.ly = y
  
  def add_entry(self, entry):
    l = Label(self.lx,self.ly,self.lw,entry)
    self.ly += 1
  
  def draw(self, gc):
    gc.set_color_fg(COLOR_LIGHT_GREY)
    gc.draw_border(1, self.x, self.y, self.w-2, self.h-2)
    self.tlabel.draw(gc)
    for l in self.labels:
      l.draw(gc)
  
  def get_label(self, i):
    return self.labels[i]
Exemplo n.º 52
0
class SpecialistPanel(Clickable):
    def __init__(self, x, y, specialist_instance, selectable=False):
        self.surface = Surface((200, 60))
        self.specialist = specialist_instance
        self.s_type = Label(0, 0, specialist.mapping[specialist_instance.s_type])
        self.s_exp = Label(0, 40, "")
        self.s_level = Label(0, 20, "")
        self.selectable = selectable
        self.selected = False
        self.x = x
        self.y = y
        self.w = 200
        self.h = 60

    def draw(self, screen):
        self.surface.fill(0x000000)
        pygame.draw.rect(self.surface, 0xb7f315 if self.selected else 0xffffff, Rect(0, 0, 198, 58), 2)
        self.s_exp.set_text("Exp: %s/%s" % (self.specialist.experience, self.specialist.level_up_exp))
        self.s_level.set_text("Level: %s" % self.specialist.level)
        self.s_type.draw(self.surface)
        self.s_exp.draw(self.surface)
        self.s_level.draw(self.surface)
        screen.blit(self.surface, (self.x, self.y))

    def is_pressed(self, x, y, button):
        if not self.selectable:
            return False
        if x < self.x:
            return False
        elif x > self.x + self.w:
            return False
        elif y < self.y:
            return False
        elif y > self.y + self.h:
            return False

        self.selected = not self.selected
        return True
Exemplo n.º 53
0
 def __init__(self, x, y, w, title, entries=None):
   self.x = x
   self.y = y
   self.w = w
   self.h = len(entries) + 2
   x += 2
   w -= 4
   self.tlabel = Label(x,y,w,title, align=Label.ALIGN_CENTER, fg=COLOR_LIGHT_GREY)
   self.labels = []
   y += 1
   self.lx = x
   self.ly = y
   self.lw = w
   if entries != None:
     self.add_entries(entries)
Exemplo n.º 54
0
 def findroutes(self, start_node, end_node):
     self.start_node = start_node
     self.end_node = end_node
     
     self.startLabel = Label(self.start_node, parentLabel=None, parentEdge=None, endNode=self.end_node, routeFinder=self)
     self.startLabel.expand(MAXIMUM_LENGTH, MINIMUM_LENGTH, endNode=self.end_node)
     
     # print "startnode " + str(self.start_node.getAttributes()) + " " + str(self.start_node.getPoint())
     # print "endnode " + str(self.end_node.getAttributes())
     
     #currentlabel = Label(self.start_node)
     
     #self.iterative_expansion(currentlabel)
            
     return self.results
Exemplo n.º 55
0
    def __init__(self, id, connection):

        logging.debug (" Initializing Job: %s" % id)

        strSQL = "select * from jobs where id = ?"
        cursor = connection.cursor()
        cursor.execute(strSQL, id)
        row = cursor.fetchone()

        if row:
            self.id = row.id
            self.label_id = row.tapeid
            self.copies = row.copies
            self.status = row.status
            self.printonly = (row.printonly == "y")
            self.dvd = (row.dvd == "y")
            self.master = (row.master == "y")
            self.pulpit = (row.pulpit == "y")
            self.label = Label()
            self.label.load_from_db(self.label_id, connection)

        logging.debug(" Finished initializing Job: %s" % id)
Exemplo n.º 56
0
    def overlay(self, component, gc, view_bounds=None, mode="normal"):
        """ Draws the box overlaid on another component.

        Overrides AbstractOverlay.
        """

        if not self.visible:
            return

        # draw the label on a transparent box. This allows us to draw
        # different shapes and put the text inside it without the label
        # filling a rectangle on top of it
        label = Label(text=self.text, font=self.font, bgcolor="transparent",
                      margin=5)
        width, height = label.get_width_height(gc)

        valign, halign = self.align

        if self.alternate_position:
            x, y = self.alternate_position
            if valign == "u":
                y += self.padding
            else:
                y -= self.padding + height

            if halign == "r":
                x += self.padding
            else:
                x -= self.padding + width
        else:
            if valign == "u":
                y = component.y2 - self.padding - height
            else:
                y = component.y + self.padding

            if halign == "r":
                x = component.x2 - self.padding - width
            else:
                x = component.x + self.padding

        # attempt to get the box entirely within the component
        if x + width > component.width:
            x = max(0, component.width-width)
        if y + height > component.height:
            y = max(0, component.height - height)
        elif y < 0:
            y = 0

        # apply the alpha channel
        color = self.bgcolor_
        if self.bgcolor != "transparent":
            if self.alpha:
                color = list(self.bgcolor_)
                if len(color) == 4:
                    color[3] = self.alpha
                else:
                    color += [self.alpha]

        with gc:
            gc.translate_ctm(x, y)

            gc.set_line_width(self.border_size)
            gc.set_stroke_color(self.border_color_)
            gc.set_fill_color(color)

            # draw a rounded rectangle
            x = y = 0
            end_radius = 8.0
            gc.begin_path()
            gc.move_to(x + end_radius, y)
            gc.arc_to(x + width, y,
                    x + width,
                    y + end_radius, end_radius)
            gc.arc_to(x + width,
                    y + height,
                    x + width - end_radius,
                    y + height, end_radius)
            gc.arc_to(x, y + height,
                    x, y,
                    end_radius)
            gc.arc_to(x, y,
                    x + width + end_radius,
                    y, end_radius)
            gc.draw_path()

            label.draw(gc)
Exemplo n.º 57
0
    def __init__(self, 
                 button_mask=["theme", "menu", "max", "min", "close"],
                 icon_path=None,
                 app_name=None,
                 title=None,
                 add_separator=False,
                 height=26,
                 show_title=True,
                 enable_gaussian=True,
                 name_size=DEFAULT_FONT_SIZE,
                 title_size=DEFAULT_FONT_SIZE,
                 ):
        '''
        Initialize the title bar.

        @param button_mask: A string list. Each item of it indicates that there is a corresponding button on the title bar. By default, it's ["theme", "menu", "max", "min", "close"], which means theme button, menu button, max button, min button and close button, respectively.
        @param icon_path: The path of icon image.
        @param app_name: Application name string. It will be displayed just next to the icon_dpixbuf. By default, it's None.
        @param title: Title string of the application. It will be displayed on the center of the title bar. By default, it's None.
        @param add_separator: If True, add a separation line between the title bar and the body of the window. By default, it's False.
        @param height: The height of the title bar. By default, it's 26 pixels.
        @param show_title: If False, the title bar will not be displayed. By default, it's True.
        @param enable_gaussian: Whether enable gaussian on title, default is True.
        @param name_size: The size of name, default is DEFAULT_FONT_SIZE.
        @param title_size: The size of title, default is DEFAULT_FONT_SIZE.
        '''
        # Init.
        EventBox.__init__(self)
        self.set_size_request(-1, height)
        self.v_layout_box = gtk.VBox()
        self.h_layout_box = gtk.HBox()
        self.add(self.v_layout_box)
        self.v_layout_box.pack_start(self.h_layout_box, True, True)
        
        # Init separator.
        if add_separator:
            self.separator = gtk.HBox()
            self.separator.set_size_request(-1, 1)
            self.separator.connect("expose-event", self.expose_titlebar_separator)
            self.v_layout_box.pack_start(self.separator, True, True)
        
        # Add drag event box.
        self.drag_box = EventBox()
        self.h_layout_box.pack_start(self.drag_box, True, True)
        
        # Init left box to contain icon and title.
        self.left_box = gtk.HBox()
        self.drag_box.add(self.left_box)
        
        if show_title:
            # Add icon.
            if icon_path != None:
                self.icon_image_box = gtk.image_new_from_pixbuf(gtk.gdk.pixbuf_new_from_file(icon_path))
                self.icon_align = gtk.Alignment()
                self.icon_align.set(0.5, 0.5, 0.0, 0.0)
                self.icon_align.set_padding(5, 5, 5, 0)
                self.icon_align.add(self.icon_image_box)
                self.left_box.pack_start(self.icon_align, False, False)
                        
            # Add app name.
            if app_name == None:
                app_name_label = ""
            else:
                app_name_label = app_name
            self.app_name_box = Label(
                app_name_label,
                text_color=ui_theme.get_color("title_text"),
                enable_gaussian=enable_gaussian, text_size=name_size,
                )
            self.app_name_align = gtk.Alignment()
            self.app_name_align.set(0.5, 0.5, 0.0, 0.0)
            self.app_name_align.set_padding(2, 0, 5, 0)
            self.app_name_align.add(self.app_name_box)
            self.left_box.pack_start(self.app_name_align, False, False)
            
            # Add title.
            if title == None:
                title_label = ""
            else:
                title_label = title
            self.title_box = Label(
                title_label,
                text_color=ui_theme.get_color("title_text"),
                enable_gaussian=enable_gaussian, 
                text_x_align=pango.ALIGN_CENTER,
                text_size=title_size,
                )
            self.title_align = gtk.Alignment()
            self.title_align.set(0.5, 0.5, 0.0, 0.0)
            self.title_align.set_padding(2, 0, 30, 30)
            self.title_align.add(self.title_box)
            self.left_box.pack_start(self.title_align, True, True)
            
        # Add button box.
        self.button_box = gtk.HBox()
        self.button_align = gtk.Alignment()
        self.button_align.set(1.0, 0.0, 0.0, 0.0)
        self.button_align.set_padding(0, 0, 0, 0)
        self.button_align.add(self.button_box)
        self.right_box = gtk.VBox()
        self.right_box.pack_start(self.button_align, False, False)
        self.h_layout_box.pack_start(self.right_box, False, False)
        
        # Add theme button.
        if "theme" in button_mask:
            self.theme_button = ThemeButton()
            self.button_box.pack_start(self.theme_button, False, False, 1)
            Tooltip.text(self.theme_button, _("Change skin")).show_delay(self.theme_button, 2000)

        # Add menu button.
        if "menu" in button_mask:
            self.menu_button = MenuButton()
            self.button_box.pack_start(self.menu_button, False, False, 1)
            Tooltip.text(self.menu_button, _("Main menu")).show_delay(self.menu_button, 2000)
        
        # Add min button.
        if "min" in button_mask:
            self.min_button = MinButton()
            self.button_box.pack_start(self.min_button, False, False, 1)
            Tooltip.text(self.min_button, _("Minimum")).show_delay(self.min_button, 2000)        
            
        # Add max button.
        if "max" in button_mask:
            self.max_button = MaxButton()
            self.button_box.pack_start(self.max_button, False, False, 1)
            Tooltip.text(self.max_button, _("Maximize")).show_delay(self.max_button, 2000)        

        # Add close button.
        if "close" in button_mask:
            self.close_button = CloseButton()
            self.button_box.pack_start(self.close_button, False, False)
            Tooltip.text(self.close_button, _("Close")).show_delay(self.close_button, 2000)        
        
        # Show.
        self.show_all()
Exemplo n.º 58
0
    def __init__(self, 
                 button_mask=["theme", "menu", "max", "min", "close"],
                 icon_dpixbuf=None,
                 app_name=None,
                 title=None,
                 add_separator=False,
                 height=26,
                 show_title=True,
                 ):
        """
        Initialize the title bar.

        @param button_mask: A string list. Each item of it indicates that there is a corresponding button on the title bar. By default, it's ["theme", "menu", "max", "min", "close"], which means theme button, menu button, max button, min button and close button, respectively.
        @param icon_dpixbuf: A pixbuf of type dtk.ui.theme.DynamicPixbuf. It will be displayed at the top left of the window. By default, it's None.
        @param app_name: Application name string. It will be displayed just next to the icon_dpixbuf. By default, it's None.
        @param title: Title string of the application. It will be displayed on the center of the title bar. By default, it's None.
        @param add_separator: If True, add a separation line between the title bar and the body of the window. By default, it's False.
        @param height: The hight of the title bar. By default, it's 26 pixels.
        @param show_title: If False, the title bar will not be displayed. By default, it's True.
        """
        # Init.
        EventBox.__init__(self)
        self.set_size_request(-1, height)
        self.v_layout_box = gtk.VBox()
        self.h_layout_box = gtk.HBox()
        self.add(self.v_layout_box)
        self.v_layout_box.pack_start(self.h_layout_box, True, True)
        
        # Init separator.
        if add_separator:
            self.separator = gtk.HBox()
            self.separator.set_size_request(-1, 1)
            self.separator.connect("expose-event", self.expose_titlebar_separator)
            self.v_layout_box.pack_start(self.separator, True, True)
        
        # Add drag event box.
        self.drag_box = EventBox()
        self.h_layout_box.pack_start(self.drag_box, True, True)
        
        # Init left box to contain icon and title.
        self.left_box = gtk.HBox()
        self.drag_box.add(self.left_box)
        
        if show_title:
            # Add icon.
            if icon_dpixbuf != None:
                self.icon_image_box = ImageBox(icon_dpixbuf)
                self.icon_align = gtk.Alignment()
                self.icon_align.set(0.5, 0.5, 0.0, 0.0)
                self.icon_align.set_padding(5, 5, 5, 0)
                self.icon_align.add(self.icon_image_box)
                self.left_box.pack_start(self.icon_align, False, False)
                        
            # Add app name.
            if app_name != None:
                self.app_name_box = Label(app_name, enable_gaussian=True)
                self.app_name_align = gtk.Alignment()
                self.app_name_align.set(0.5, 0.5, 0.0, 0.0)
                self.app_name_align.set_padding(2, 0, 5, 0)
                self.app_name_align.add(self.app_name_box)
                self.left_box.pack_start(self.app_name_align, False, False)
            
            # Add title.
            if title != None:
                self.title_box = Label(title, enable_gaussian=True, text_x_align=pango.ALIGN_CENTER)
                self.title_align = gtk.Alignment()
                self.title_align.set(0.5, 0.5, 0.0, 0.0)
                self.title_align.set_padding(2, 0, 30, 30)
                self.title_align.add(self.title_box)
                self.left_box.pack_start(self.title_align, True, True)
            
        # Add button box.
        self.button_box = gtk.HBox()
        self.button_align = gtk.Alignment()
        self.button_align.set(1.0, 0.0, 0.0, 0.0)
        self.button_align.set_padding(0, 0, 0, 0)
        self.button_align.add(self.button_box)
        self.h_layout_box.pack_start(self.button_align, False, False)
        
        # Add theme button.
        if "theme" in button_mask:
            self.theme_button = ThemeButton()
            self.button_box.pack_start(self.theme_button, False, False, 1)
            Tooltip.text(self.theme_button, _("Change skin")).show_delay(self.theme_button, 2000)

        # Add menu button.
        if "menu" in button_mask:
            self.menu_button = MenuButton()
            self.button_box.pack_start(self.menu_button, False, False, 1)
            Tooltip.text(self.menu_button, _("Main menu")).show_delay(self.menu_button, 2000)
        
        # Add min button.
        if "min" in button_mask:
            self.min_button = MinButton()
            self.button_box.pack_start(self.min_button, False, False, 1)
            Tooltip.text(self.min_button, _("Minimum")).show_delay(self.min_button, 2000)        
            
        # Add max button.
        if "max" in button_mask:
            self.max_button = MaxButton()
            self.button_box.pack_start(self.max_button, False, False, 1)
            Tooltip.text(self.max_button, _("Maximize")).show_delay(self.max_button, 2000)        

        # Add close button.
        if "close" in button_mask:
            self.close_button = CloseButton()
            self.button_box.pack_start(self.close_button, False, False)
            Tooltip.text(self.close_button, _("Close")).show_delay(self.close_button, 2000)        
        
        # Show.
        self.show_all()
Exemplo n.º 59
0
import database
from label import Label

print 'Running driver ...'
db = database.Database()

# authors
following = db.get_authors()

# set up a label
label = Label('schools')
label.add_author('Yale')
label.add_author('CarnegieMellon')
# label.add_author('Harvard')
# label.add_author('facebook')
# label.add_author('Yale')
# label.add_author('UWaterloo')
# label.add_author('espn')
# label.remove_author('facebook')
label.train(db)

# print out some information about the label
print 'Label: ', label
for el in label.pos_ranks[:20]:
  print '  ', el[1], el[0]

# see which authors are chosen for membership
members = label.members(db, following)
print 'Members:'
for m in members:
  print '  ', m
Exemplo n.º 60
0
    def expandLabel(self, parentLabel):
        """
        """
        expansion = []   # list of labels
        newLabel = None  #
        
        #out_edges = self.graph.edges(parentLabel.getNode(), self.graph)
        #out_edges = [e[2].get('edge') for e in out_edges]
        
        #print "expanding label at" + str(parentLabel.getNode().getAttributes()) + " " + str(len(out_edges))
        
#        for edge in out_edges:
#            print edge.getAttributes()
            
        print "------"
        print "Length " ,len(parentLabel.getNode().getOutEdges()) , parentLabel.getNode().getAttributes().get("nodecounter") 
        for e in parentLabel.getNode().getOutEdges():
            print "Outedge " , e.getAttributes()
        
        for currentEdge in parentLabel.getNode().getOutEdges():
            # check constraints
            
            # import pdb;pdb.set_trace()
            
            length = parentLabel.getLength() + currentEdge.getLength()
            
            print "currentEdge " + str(currentEdge.getAttributes())

            # newLabel = Label(currentEdge.getToNode(), parent=parentLabel, back_edge=currentEdge, length=length)
            newLabel = Label(currentEdge.getOutNode(parentLabel), parent=parentLabel, back_edge=currentEdge, length=length)
            
#            if len(newLabel.getNode().getOutEdges()) == 1:
#                break
            
#            edgeOccurances = newLabel.getOccurancesOfEdge(newLabel)
            
#            isInBridges = True
#            try:
#                self.bridges.index(newLabel)
#            except ValueError:
#                isInBridges = False
#            
#            if (isInBridges) and edgeOccurances > BRIDGE_OVERLAP:
#                print "break (isInBridges)"
#                break
            
            # path length including this segment longer that MAXIMUM_LENGTH 
            # constraint
            if (length > MAXIMUM_LENGTH):
                print "break (MAXLENGTH)"
                break
            
            print ".."
            
            # euclidean distance to endNode > maxLength * distancefactor
            distanceToEndNode = newLabel.getNode().getGeometry().distance(self.end_node.getGeometry())
            totalLength = newLabel.getLength() + distanceToEndNode
            
            if totalLength > (MAXIMUM_LENGTH * DISTANCE_FACTOR):
                print "break : euclidian distance greater than max"
                break
            
            nodeOccurances = newLabel.getOccurancesOfNode(newLabel.getNode())
            
            if nodeOccurances > NODE_OVERLAP:
                print "node occurance break (%d) at %s." % (nodeOccurances, str(currentEdge.getAttributes()))
                break
            
            self.num_labels = self.num_labels + 1
            expansion.append(newLabel)
            
        return expansion