コード例 #1
0
def __main__(stdscr, projection=False):
    angleX, angleY, angleZ = 0, 0, 0
    c = Canvas()
    while 1:
        # Will hold transformed vertices.
        t = []

        for v in vertices:
            # Rotate the point around X axis, then around Y axis, and finally around Z axis.
            p = v.rotateX(angleX).rotateY(angleY).rotateZ(angleZ)
            if projection:
                # Transform the point from 3D to 2D
                p = p.project(50, 50, 50, 50)
            #Put the point in the list of transformed vertices
            t.append(p)

        for f in faces:
            for x, y in line(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y):
                c.set(x, y)
            for x, y in line(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y):
                c.set(x, y)
            for x, y in line(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y):
                c.set(x, y)
            for x, y in line(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y):
                c.set(x, y)

        f = c.frame(-40, -40, 80, 80)
        stdscr.addstr(0, 0, '{0}\n'.format(f))
        stdscr.refresh()

        angleX += 2
        angleY += 3
        angleZ += 5
        sleep(1.0 / 20)
        c.clear()
コード例 #2
0
ファイル: widget.py プロジェクト: sysr-q/wopr
    def __init__(self, scr, data, maxlen=1024, enc="utf-8", name="Sparkline"):
        super(Sparkline, self).__init__(scr, enc=enc, name=name)

        def mkcanvases():
            d = {
                "data": collections.deque([], maxlen=maxlen),
                "canvas": Canvas(),
                "attr": curses.color_pair(random.choice([1, 2, 3, 4, 5])),
                "dirty": True,
            }
            return d

        self.axes = Canvas()
        self.canvases = collections.defaultdict(mkcanvases)
        self.maxlen = maxlen

        for x in data:  # data=[("foo", [...]), ("bar", [...])]
            if len(x) == 3:
                name, d, attr = x
            else:
                name, d = x
                attr = None
            self.add_data(name, d, attr=attr)

        self.edge_buffer = 20  # 20px from edges
        self.data_buffer = 3  # + 3px added buffer for the data canvas
        self.rounding = 5  # round axes up to nearest 5.
        self.fill = True  # fill inbetween points with lines
コード例 #3
0
def draw_simple_map(stdscr):

    c = Canvas()

    v1 = Point(-20, 20)
    v2 = Point(20, 20)
    v3 = Point(-20, -20)
    v4 = Point(20, -20)

    lines = [
        (v1, v2),
        (v1, v3),
        (v3, v4),
        (v4, v2),
    ]

    for start, end in lines:
        for x, y in line(start.x, start.y, end.x, end.y):
            c.set(x, y)

    df = c.frame(-40, -40, 80, 80)
    stdscr.addstr(1, 0, f"{df}")
    stdscr.refresh()

    sleep(10)
    c.clear()
コード例 #4
0
def process(data):
    positions = [pos for pos, vel in data]
    velocities = [vel for pos, vel in data]

    prev_width, prev_height = None, None
    left, top = 0, 0
    best_positions = None

    while True:
        left, right = minmax(x for x, y in positions)
        top, bottom = minmax(y for x, y in positions)

        width, height = right - left, bottom - top

        if prev_width and width > prev_width and prev_height and height > prev_height:
            break
        else:
            prev_width, prev_height = width, height

        best_positions = positions.copy()

        for i, (dx, dy) in enumerate(velocities):
            x, y = positions[i]
            x += dx
            y += dy
            positions[i] = (x, y)

    c = Canvas()
    for x, y in best_positions:
        c.set(x - left, y - top)
    print(c.frame())
コード例 #5
0
ファイル: gameoflife.py プロジェクト: A1rPun/GameOfLife
def main(stdscr):
    stdscr.nodelay(1)
    curses.curs_set(0)

    termSize = getTerminalSize()
    argsSize = len(sys.argv)
    WIDTH = min((int(sys.argv[1]) if argsSize > 1 else 64), termSize[0] * 2)
    HEIGHT = min((int(sys.argv[2]) if argsSize > 2 else 64), termSize[1] * 4)
    FRAMES = 4
    display = Canvas()
    grid = getGrid(WIDTH, HEIGHT)

    addPentomino(grid, int(WIDTH / 2), int(HEIGHT / 2))
    drawGrid(display, grid, stdscr)
    time.sleep(1. / FRAMES)

    while True:
        grid = updateGrid(grid, WIDTH, HEIGHT)
        drawGrid(display, grid, stdscr)
        key = stdscr.getch()
        if key == ord('q'):
            break
        elif key == ord('s'):
            addPentomino(grid, int(WIDTH / 2), int(HEIGHT / 2))
        elif key == curses.KEY_UP:
            FRAMES += 1 if FRAMES < 60 else 0
        elif key == curses.KEY_DOWN:
            FRAMES -= 1 if FRAMES > 2 else 0
        time.sleep(1. / FRAMES)
コード例 #6
0
ファイル: image2term.py プロジェクト: lzskiss/drawille
def image2term(image, threshold=128, ratio=None, invert=False):
    if image.startswith('http://') or image.startswith('https://'):
        i = Image.open(StringIO(urllib2.urlopen(image).read())).convert('L')
    else:
        i = Image.open(open(image)).convert('L')
    w, h = i.size
    if ratio:
        w = int(w * ratio)
        h = int(h * ratio)
        i = i.resize((w, h), Image.ANTIALIAS)
    else:
        tw, th = getTerminalSize()
        tw *= 2
        th *= 2
        if tw < w:
            ratio = tw / float(w)
            w = tw
            h = int(h * ratio)
            i = i.resize((w, h), Image.ANTIALIAS)
    can = Canvas()
    x = y = 0
    for pix in i.tobytes():
        if invert:
            if ord(pix) > threshold:
                can.set(x, y)
        else:
            if ord(pix) < threshold:
                can.set(x, y)
        x += 1
        if x >= w:
            y += 1
            x = 0
    return can.frame(0, 0)
コード例 #7
0
    def render(self, width, height, values):
        """
        :type width: int
        :type height: int
        :type values: list[int or float]
        :rtype: list[str or unicode]
        """
        from drawille import Canvas

        vertical_chart_resolution = height * self.char_resolution_vertical
        horizontal_chart_resolution = width * self.char_resolution_horizontal

        canvas = Canvas()
        x = 0
        for value in values:
            for y in range(1, int(round(value, 0)) + 1):
                canvas.set(x, vertical_chart_resolution - y)
            x += 1

        rows = canvas.rows(min_x=0,
                           min_y=0,
                           max_x=horizontal_chart_resolution,
                           max_y=vertical_chart_resolution)

        if not rows:
            rows = [u'' for _ in range(height)]

        for i, row in enumerate(rows):
            rows[i] = u'{0}'.format(row.ljust(width))

        return rows
コード例 #8
0
ファイル: image2term3.py プロジェクト: zhengsongyue/drawille
def image2term(image, threshold=128, ratio=None, invert=False):
    """
    Prints an image converted to drawille
    Args:
        image: filepath / URL of the image
        threshold: The color (0-255) threshold to convert a pixel to a drawille dot
        ratio: Ratio to scale the printed image (e.g. ratio=0.5 is 50%)
        invert: Inverts the threshold check
    """

    if image.startswith('http://') or image.startswith('https://'):
        r = requests.get(image,stream=True)
        i = Image.open(r.raw).convert('L')
    else:
        f = open(image,'rb') #Open in binary mode
        i = Image.open(f).convert('L')
    image_width, image_height = i.size
    if ratio:
        image_width = int(image_width * ratio)
        image_height = int(image_height * ratio)
        i = i.resize((image_width, image_height), Image.ANTIALIAS)
    else:
        terminal_width = getTerminalSize()[0] * 2#Number of Columns
        terminal_height = getTerminalSize()[1] * 4
    
        w_ratio = 1
        h_ratio = 1

        if terminal_width < image_width:
            w_ratio = terminal_width / float(image_width)
        
        if terminal_height < image_height:
            h_ratio = terminal_height / float(image_height)
        

        ratio = min([w_ratio,h_ratio])
        image_width = int(image_width * ratio)
        image_height = int(image_height * ratio)
        i = i.resize((image_width, image_height), Image.ANTIALIAS)
    can = Canvas()
    x = y = 0

    try:
        i_converted = i.tobytes()
    except AttributeError:
        i_converted = i.tostring()

    for pix in i_converted:
        if invert:
            if pix > threshold:
                can.set(x, y)
        else:
            if pix < threshold:
                can.set(x, y)
        x += 1
        if x >= image_width:
            y += 1
            x = 0
    return can.frame(0, 0)
コード例 #9
0
 def test_get(self):
     c = Canvas()
     self.assertEqual(c.get(0, 0), False)
     c.set(0, 0)
     self.assertEqual(c.get(0, 0), True)
     self.assertEqual(c.get(0, 1), False)
     self.assertEqual(c.get(1, 0), False)
     self.assertEqual(c.get(1, 1), False)
コード例 #10
0
ファイル: widget.py プロジェクト: sysr-q/wopr
 def mkcanvases():
     d = {
         "data": collections.deque([], maxlen=maxlen),
         "canvas": Canvas(),
         "attr": curses.color_pair(random.choice([1, 2, 3, 4, 5])),
         "dirty": True,
     }
     return d
コード例 #11
0
ファイル: __init__.py プロジェクト: yoavtzelnick/graphscii
 def draw(self):
     """Draw the graph
     """
     c = Canvas()
     for node in self.nodes.itervalues():
         self.draw_node(c, node)
     for edge in self.edges:
         self.draw_edge(c, edge)
     print(c.frame())
コード例 #12
0
 def spawn(self):
     while(True):
         self.spawn_next()
         print(chr(27) + "[2J")
         _canvas = Canvas()
         for room in self.queue:
             draw(_canvas, room)
         print(_canvas.frame())
         if self.total_amount_required == 0:
             # seal all doors
             for room in self.queue:
                 for door in room.available_doors:
                     room.doors.remove(door)
             print(chr(27) + "[2J")
             _canvas = Canvas()
             for room in self.queue:
                 draw(_canvas, room)
             print(_canvas.frame())
             break
         time.sleep(0.05)
コード例 #13
0
def complexset2drawille(complexset, n):
    can = Canvas()
    w, h = getTerminalSize()
    w *= 2
    h *= 4

    for row in range(h):
        for col in range(w):
            if complexset.plot(col, row, w, h, n) >= complexset.MAX_ITER:
                can.set(col, row)
    return can.frame()
コード例 #14
0
def __main__():
    args = argparser()
    out = args['output']

    orig_img = image.load(args['image']).convert('RGB')
    if args['contrast'] != None:
        orig_img = ImageEnhance.Contrast(orig_img).enhance(args['contrast'])
    orig_img = resizer.resize(orig_img, 1, ANTI_FONT_DISTORTION)
    fit_ratio = resizer.fit_in_ratio(orig_img.size, term.size())
    if args['ratio']:
        fit_ratio *= args['ratio']

    img = resizer.resize(orig_img, fit_ratio, (1, 1))
    lows, mids, highs = posterizer.thresholds(img)
    if args['color'] != None:
        lows = map(lambda val: bound_addition(val, args['color']), lows)
        mids = map(lambda val: bound_addition(val, args['color']), mids)
        highs = map(lambda val: bound_addition(val, args['color']), highs)
    colors = posterizer.posterize(img, mids, highs)

    #    img.show()
    shapes = resizer.resize(orig_img, fit_ratio, (2, 4))
    #    shapes.show()
    shapes = shapes.convert('L')
    threshold = otsu.threshold(shapes.histogram())
    #    mask = shapes.point(lambda val: 255 if val <= threshold else 0).convert('1')
    #    threshold = otsu.threshold(shapes.histogram(mask))
    if args['shape'] != None:
        threshold = bound_addition(threshold, args['shape'])
    shapes = shapes.point(lambda val: 255
                          if val > threshold else 0).convert('1')
    #    shapes.show()
    dots = Canvas()
    w, h = shapes.size
    for index, pixel in enumerate(list(shapes.getdata()), 0):
        if pixel:
            dots.set(index % w, index // w)


#    out.write(dots.frame(0,0,w,h))
#    out.write('\n')

    w, h = colors.size
    for index, pixel in enumerate(list(colors.getdata()), 0):
        x = (index % w) * 2
        y = (index // w) * 4
        miniframe = unicode(dots.frame(x, y, x + 2, y + 4), 'utf-8')
        miniframe = miniframe if len(miniframe) else u'\u2800'
        out.write(color_print.rgb2esc(pixel, [0, 0, 0], lows, highs,
                                      miniframe))
        if not (1 + index) % w:
            out.write('\n')
コード例 #15
0
def main(stdscr):
    global frame_no, speed, position, score
    c = Canvas()
    bar_width = 16
    bars = [Bar(bar_width)]
    stdscr.refresh()

    while True:
        frame_no += 1
        for bar in bars:
            if check_collision(position, bar):
                return
        while not keys.empty():
            if keys.get() == 113:
                return
            speed = 32.0

        c.set(0,0)
        c.set(width, height)
        if frame_no % 50 == 0:
            bars.append(Bar(bar_width))
        for x,y in bird:
            c.set(x,y+position)
        for bar_index, bar in enumerate(bars):
            if bar.x < 1:
                bars.pop(bar_index)
                score += 1
            else:
                bars[bar_index].x -= 1
                for x,y in bar.draw():
                    c.set(x,y)
        f = c.frame()+'\n'
        stdscr.addstr(0, 0, f)
        stdscr.addstr(height/4+1, 0, 'score: {0}'.format(score))
        stdscr.refresh()
        c.clear()

        speed -= 2

        position -= speed/10

        if position < 0:
            position = 0
            speed = 0.0
        elif position > height-13:
            position = height-13
            speed = 0.0


        sleep(1.0/fps)
コード例 #16
0
def __main__(stdscr, projection=False):
    angleX, angleY, angleZ = 0, 0, 0
    canvas = Canvas()
    while 1:
        # Will hold transformed vertices.
        transformed_vertices = []

        for vertex in vertices:
            # Rotate the point around X axis, then around Y axis, and finally around Z axis.
            point = vertex.rotateX(angleX).rotateY(angleY).rotateZ(angleZ)
            if projection:
                # Transform the point from 3D to 2D
                point = point.project(50, 50, 50, 50)
            #Put the point in the list of transformed vertices
            transformed_vertices.append(point)

        for face in faces:
            for x, y in line(transformed_vertices[face[0]].x,
                             transformed_vertices[face[0]].y,
                             transformed_vertices[face[1]].x,
                             transformed_vertices[face[1]].y):
                canvas.set(x, y)
            for x, y in line(transformed_vertices[face[1]].x,
                             transformed_vertices[face[1]].y,
                             transformed_vertices[face[2]].x,
                             transformed_vertices[face[2]].y):
                canvas.set(x, y)
            for x, y in line(transformed_vertices[face[2]].x,
                             transformed_vertices[face[2]].y,
                             transformed_vertices[face[3]].x,
                             transformed_vertices[face[3]].y):
                canvas.set(x, y)
            for x, y in line(transformed_vertices[face[3]].x,
                             transformed_vertices[face[3]].y,
                             transformed_vertices[face[0]].x,
                             transformed_vertices[face[0]].y):
                canvas.set(x, y)

        frame = canvas.frame(-40, -40, 80, 80)
        stdscr.addstr(0, 0, '{0}\n'.format(frame))
        stdscr.refresh()

        angleX += 2
        angleY += 3
        angleZ += 5
        sleep(1.0 / 20)
        canvas.clear()
コード例 #17
0
ファイル: ui.py プロジェクト: ajaiswal-ht/imdino
    def update(self):
        '''
            Update the form in background
        '''
        # get the information
        try:

            # game Stats
            row1 = [
                'Status: %s' % (self.learn.state, ),
                'Fitness: %s ' % (self.gm.points, ),
                'GameStatus: %s ' % (self.gm.gamestate, ),
                'Generation: %s : %s/%s' %
                (self.learn.generation, self.learn.genome,
                 len(self.learn.genomes))
            ]
            self.genome_stats.values = row1
            self.genome_stats.display()
            if self.gm.gameOutput:
                row2 = 'Action: %s \n Activation: %s \n' % (
                    self.gm.gameOutputString, self.gm.gameOutput)

            else:
                row2 = 'Loading...'
            self.game_stats.value = row2
            self.game_stats.display()

            ### current state
            network_canvas = Canvas()
            y = {
                'size': self.gm.sensors[0].size,
                'distance': self.gm.sensors[0].value,
                'speed': self.gm.sensors[0].speed,
                'activation': self.gm.gameOutput
            }
            self.network_chart.value = (self.draw_chart(network_canvas,y)) + \
            '\n   %s     %s    %s    %s  \n     Distance         Size          Speed            Activation\n' % (self.gm.sensors[0].value,
                self.gm.sensors[0].size,self.gm.sensors[0].speed,self.gm.gameOutput)
            self.network_chart.display()
            #self.logger.info(self.gm.gameOutput)

        # catch the KeyError caused to c
        # cumbersome point of reading the stats data structures
        except KeyError:
            pass
コード例 #18
0
def __main__(stdscr):
    i = 0
    c = Canvas()
    height = 40
    while True:

        for x,y in line(0, height, 180, int(math.sin(math.radians(i)) * height + height)):
            c.set(x,y)

        for x in range(0, 360, 2):
            coords = (x/2, height + int(round(math.sin(math.radians(x+i)) * height)))
            c.set(*coords)

        f = c.frame()
        stdscr.addstr(0, 0, '{0}\n'.format(f))
        stdscr.refresh()

        i += 2
        sleep(1.0/24)
        c.clear()
コード例 #19
0
ファイル: image2term.py プロジェクト: ubunatic/drawille
def image2term(image, threshold=128, ratio=None, invert=False):
    if image.startswith('http://') or image.startswith('https://'):
        f = BytesIO(requests.get(image).content)
        i = Image.open(f).convert('L')
    else:
        with open(image, 'rb') as f:
            i = Image.open(f).convert('L')
    w, h = i.size
    if ratio:
        w = int(w * ratio)
        h = int(h * ratio)
        i = i.resize((w, h), Image.ANTIALIAS)
    else:
        tw = getTerminalSize()[0]
        tw *= 2
        if tw < w:
            ratio = tw / float(w)
            w = tw
            h = int(h * ratio)
            i = i.resize((w, h), Image.ANTIALIAS)
    can = Canvas()
    x = y = 0

    try:
        i_converted = i.tobytes()
    except AttributeError:
        i_converted = i.tostring()

    for pix in i_converted:
        if type(pix) is not int: pix = ord(pix)
        if invert:
            if pix > threshold:
                can.set(x, y)
        else:
            if pix < threshold:
                can.set(x, y)
        x += 1
        if x >= w:
            y += 1
            x = 0
    return can.frame(0, 0)
コード例 #20
0
ファイル: server.py プロジェクト: staceb/sshoneypot
    async def handle_client(cls, process):
        pos = 0, 0
        i = 0
        process.stdout.write('\e[8;50;100t')
        while i < 1000:
            c = Canvas()

            process.stdout.write('\033[2J')
            process.stdout.write("\033[?25l")

            for i in range(pos[0], pos[0] + 10):
                for j in range(pos[1], pos[1] + 10):
                    c.set(i % 80 - 40, j % 60 - 30)

            process.stdout.write(c.frame(-40, -30, 40, 30))

            await asyncio.sleep(1. / 15)
            pos = pos[0] + 1, pos[1] + 1
            i += 1

        process.exit(0)
コード例 #21
0
def draw_coords(stdscr, design):

    c = Canvas()

    for i in range(10):

        for point in design:
            c.set(point.x, point.y)
    
        df = c.frame(-40, -40, 80, 80)
        stdscr.addstr(1, 0, df)
        stdscr.refresh()

        new_move_delta = Point(choice([-1, 0, 1]), choice([-1, 0, 1]))
        design = move(design, new_move_delta)

        sleep(.5)
        c.clear()

    sleep(6)
    c.clear()
コード例 #22
0
def __main__(projection=False):
    angleX, angleY, angleZ = 0, 0, 0
    c = Canvas()
    while 1:
        # Will hold transformed vertices.
        t = []

        for v in vertices:
            # Rotate the point around X axis, then around Y axis, and finally around Z axis.
            p = v.rotateX(angleX).rotateY(angleY).rotateZ(angleZ)
            if projection:
                # Transform the point from 3D to 2D
                p = p.project(50, 50, 50, 50)
            #Put the point in the list of transformed vertices
            t.append(p)

        for f in faces:
            for x, y in line(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y):
                c.set(x, y)
            for x, y in line(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y):
                c.set(x, y)
            for x, y in line(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y):
                c.set(x, y)
            for x, y in line(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y):
                c.set(x, y)

        f = c.frame(-20, -20, 20, 20)
        s = 'broadcast "\\n\\n\\n'
        for l in format(f).splitlines():
            s += l.replace(' ', '  ').rstrip('\n') + '\\n'
        s = s[:-2]
        s += '"'
        print(s)
        sys.stdout.flush()

        angleX += 2
        angleY += 3
        angleZ += 5
        sleep(1.0 / 10)
        c.clear()
コード例 #23
0
ファイル: __init__.py プロジェクト: ikornaselur/scatterping
def get_frame(terminal_width: int = 80) -> str:
    pixel_width = terminal_width * 2
    cutoff = get_cutoff(pixel_width)

    base_path = path.dirname(__file__)
    world_path = path.abspath(path.join(base_path, "world.svg"))

    drawing = svg2rlg(world_path)
    image = renderPM.drawToPIL(drawing)
    height, width = image.size
    image = image.resize((pixel_width, int(width / height * pixel_width)))
    height, width = image.size

    canvas = Canvas()

    for x in range(0, height):
        for y in range(0, width):
            pixel = image.getpixel((x, y))
            if pixel[0] < cutoff and pixel[1] < cutoff and pixel[2] < cutoff:
                canvas.set(x, y)

    return canvas.frame()
コード例 #24
0
ファイル: __init__.py プロジェクト: gooofy/drawilleplot
    def to_txt(self, sep="\n", tw=240, invert=False, threshold=200):
        # import pdb; pdb.set_trace()

        buf = io.BytesIO()
        self.print_png(buf)
        buf.seek(0)

        i = Image.open(buf)

        w, h = i.size

        ratio = tw / float(w)
        w = tw
        h = int(h * ratio)
        i = i.resize((w, h), Image.ANTIALIAS)

        i = i.convert(mode="L")

        can = Canvas()

        for y in range(h):
            for x in range(w):

                pix = i.getpixel((x, y))

                if invert:
                    if pix > threshold:
                        can.set(x, y)
                else:
                    if pix < threshold:
                        can.set(x, y)

        for x, y, s in self.renderer.texts:
            can.set_text(int(x * ratio), int(y * ratio), s)

        return can.frame()
コード例 #25
0
ファイル: speed_test.py プロジェクト: lleixat/vim-minimap
from drawille import Canvas
from timeit import timeit

canvas = Canvas()

frames = 1000 * 10

sizes = ((0, 0),
         (10, 10),
         (20, 20),
         (20, 40),
         (40, 20),
         (40, 40),
         (100, 100))

for x, y in sizes:
    canvas.set(0, 0)

    for i in range(y):
        canvas.set(x, i)

    r = timeit(canvas.frame, number=frames)
    print('{0}x{1}\t{2}'.format(x, y, r))
    canvas.clear()
コード例 #26
0
ファイル: GUI.py プロジェクト: bryant1410/ptop
    def update(self):
        '''
            Update the form in background
        '''
        # get the information
        try:
            disk_info = self.statistics['Disk']['text']['/']
            swap_info = self.statistics['Memory']['text']['swap_memory']
            memory_info = self.statistics['Memory']['text']['memory']
            processes_info = self.statistics['Process']['text']
            system_info = self.statistics['System']['text']
            cpu_info = self.statistics['CPU']['graph']

            # overview
            row1 = "Disk Usage (/) {4}{0: <6}/{1: >6} MB{4}{2: >2} %{5}Processes{4}{3: <8}".format(
                disk_info["used"], disk_info["total"], disk_info["percentage"],
                processes_info["running_processes"],
                " " * int(4 * self.X_SCALING_FACTOR),
                " " * int(9 * self.X_SCALING_FACTOR))

            row2 = "Swap Memory    {4}{0: <6}/{1: >6} MB{4}{2: >2} %{5}Threads  {4}{3: <8}".format(
                swap_info["active"], swap_info["total"],
                swap_info["percentage"], processes_info["running_threads"],
                " " * int(4 * self.X_SCALING_FACTOR),
                " " * int(9 * self.X_SCALING_FACTOR))

            row3 = "Main Memory    {4}{0: <6}/{1: >6} MB{4}{2: >2} %{5}Boot Time{4}{3: <8}".format(
                memory_info["active"], memory_info["total"],
                memory_info["percentage"], system_info['running_time'],
                " " * int(4 * self.X_SCALING_FACTOR),
                " " * int(9 * self.X_SCALING_FACTOR))

            self.basic_stats.value = row1 + '\n' + row2 + '\n' + row3
            self.basic_stats.display()

            ### cpu_usage chart
            cpu_canvas = Canvas()
            next_peak_height = int(
                math.ceil(
                    (float(cpu_info['percentage']) / 100) * self.CHART_HEIGHT))
            self.cpu_chart.value = (self.draw_chart(cpu_canvas,
                                                    next_peak_height, 'cpu'))
            self.cpu_chart.display()

            ### memory_usage chart
            memory_canvas = Canvas()
            next_peak_height = int(
                math.ceil((float(memory_info['percentage']) / 100) *
                          self.CHART_HEIGHT))
            self.memory_chart.value = self.draw_chart(memory_canvas,
                                                      next_peak_height,
                                                      'memory')
            self.memory_chart.display()

            ### processes_table
            processes_table = self.statistics['Process']['table']

            # check sorting flags
            if MEMORY_SORT:
                sorted_table = sorted(processes_table,
                                      key=lambda k: k['memory'],
                                      reverse=True)
            elif TIME_SORT:
                sorted_table = sorted(processes_table,
                                      key=lambda k: k['rawtime'],
                                      reverse=True)
            else:
                sorted_table = processes_table

            # to keep things pre computed
            temp_list = []
            for proc in sorted_table:
                if proc['user'] == system_info['user']:
                    temp_list.append(
                        "{0: <30} {1: >5}{5}{2: <10}{5}{3}{5}{4: >6.2f} % \
                    ".format((proc['name'][:25] + '...')
                             if len(proc['name']) > 25 else proc['name'],
                             proc['id'], proc['user'], proc['time'],
                             proc['memory'],
                             " " * int(5 * self.X_SCALING_FACTOR)))
            self.processes_table.entry_widget.values = temp_list
            self.processes_table.display()

        # catch the f*****g KeyError caused to c
        # cumbersome point of reading the stats data structures
        except KeyError:
            pass
コード例 #27
0
 def test_set(self):
     c = Canvas()
     c.set(0, 0)
     self.assertTrue(0 in c.chars and 0 in c.chars[0])
コード例 #28
0
 def test_max_min_limits(self):
     c = Canvas()
     c.set(0, 0)
     self.assertEqual(c.frame(min_x=2), '')
     self.assertEqual(c.frame(max_x=0), '')
コード例 #29
0
 def test_frame(self):
     c = Canvas()
     self.assertEqual(c.frame(), '')
     c.set(0, 0)
     self.assertEqual(c.frame(), 'РаЂ')
コード例 #30
0
 def test_set_text(self):
     c = Canvas()
     c.set_text(0, 0, "asdf")
     self.assertEqual(c.frame(), "asdf")