Exemple #1
0
    def draw_header(self) -> None:
        """renders the header into our array"""
        title = fmtstr(" No-Guess Sweeper :", fg="blue", underline=True)
        self.chars[1, 1:1 + title.width] = [title]

        clock = ff.plain('┊ ') + ff.green(
            self.field.clock if self.field else "00:00")
        self.chars[1, (self.max_cols - 1 - clock.width):(self.max_cols -
                                                         1)] = [clock]

        avail = self.max_cols - 2 - title.width - clock.width

        instructions: List[FmtStr] = [
            ff.yellow(' h: ') + ff.gray("Help "),
            ff.yellow(' q: ') + ff.gray("Quit "),
            ff.yellow(' n: ') + ff.gray("New "),
        ]

        # drop instructions until they fit on top line
        while sum(i.width for i in instructions) > avail:
            instructions.pop()

        per = int(avail / len(instructions))
        istr = FmtStr().join(i.ljust(per) for i in instructions)

        self.chars[1, title.width:(title.width + istr.width)] = [istr]
    def test_unhighlight_paren_bugs(self):
        """two previous bugs, parent didn't highlight until next render
        and paren didn't unhighlight until enter"""
        self.assertEqual(self.repl.rl_history.entries, [""])
        self.enter("(")
        self.assertEqual(self.repl.rl_history.entries, [""])
        screen = [">>> (", "... "]
        self.assertEqual(self.repl.rl_history.entries, [""])
        self.assert_paint_ignoring_formatting(screen)
        self.assertEqual(self.repl.rl_history.entries, [""])

        with output_to_repl(self.repl):
            self.assertEqual(self.repl.rl_history.entries, [""])
            self.repl.process_event(")")
            self.assertEqual(self.repl.rl_history.entries, [""])
        screen = fsarray(
            [
                cyan(">>> ") + on_magenta(bold(red("("))),
                green("... ") + on_magenta(bold(red(")"))),
            ]
        )
        self.assert_paint(screen, (1, 5))

        with output_to_repl(self.repl):
            self.repl.process_event(" ")
        screen = fsarray(
            [
                cyan(">>> ") + yellow("("),
                green("... ") + yellow(")") + bold(cyan(" ")),
            ]
        )
        self.assert_paint(screen, (1, 6))
    def test_unhighlight_paren_bugs(self):
        """two previous bugs, parent didn't highlight until next render
        and paren didn't unhighlight until enter"""
        self.assertEqual(self.repl.rl_history.entries, [''])
        self.enter('(')
        self.assertEqual(self.repl.rl_history.entries, [''])
        screen = [">>> (",
                  "... "]
        self.assertEqual(self.repl.rl_history.entries, [''])
        self.assert_paint_ignoring_formatting(screen)
        self.assertEqual(self.repl.rl_history.entries, [''])

        with output_to_repl(self.repl):
            self.assertEqual(self.repl.rl_history.entries, [''])
            self.repl.process_event(')')
            self.assertEqual(self.repl.rl_history.entries, [''])
        screen = fsarray([cyan(">>> ") + on_magenta(bold(red('('))),
                         green("... ") + on_magenta(bold(red(')')))])
        self.assert_paint(screen, (1, 5))

        with output_to_repl(self.repl):
            self.repl.process_event(' ')
        screen = fsarray([cyan(">>> ") + yellow('('),
                         green("... ") + yellow(')') + bold(cyan(" "))])
        self.assert_paint(screen, (1, 6))
    def test_parse(self):
        self.assertEquals(parse.parse('\x01y\x03print\x04'), yellow('print'))

        self.assertEquals(
            parse.parse('\x01y\x03print\x04\x01c\x03 \x04\x01g\x031\x04\x01c'
                        '\x03 \x04\x01Y\x03+\x04\x01c\x03 \x04\x01g\x032\x04'),
            yellow('print') + cyan(' ') + green('1') + cyan(' ') +
            bold(yellow('+')) + cyan(' ') + green(u'2'))
Exemple #5
0
    def test_parse(self):
        self.assertEqual(parse.parse('\x01y\x03print\x04'), yellow('print'))

        self.assertEqual(
            parse.parse('\x01y\x03print\x04\x01c\x03 \x04\x01g\x031\x04\x01c'
                        '\x03 \x04\x01Y\x03+\x04\x01c\x03 \x04\x01g\x032\x04'),
            yellow('print') + cyan(' ') + green('1') + cyan(' ') +
            bold(yellow('+')) + cyan(' ') + green(u'2'))
    def test_parse(self):
        self.assertEqual(parse.parse("\x01y\x03print\x04"), yellow("print"))

        self.assertEqual(
            parse.parse("\x01y\x03print\x04\x01c\x03 \x04\x01g\x031\x04\x01c"
                        "\x03 \x04\x01Y\x03+\x04\x01c\x03 \x04\x01g\x032\x04"),
            yellow("print") + cyan(" ") + green("1") + cyan(" ") +
            bold(yellow("+")) + cyan(" ") + green("2"),
        )
Exemple #7
0
def main():

    print(yellow('creating network'))
    net = Net()
    print(green('sending network to device'))
    net = net.to(device)

    loss_function = nn.CrossEntropyLoss()
    optimizer = optim.Adam(net.parameters(), lr=.00001)

    train_x, train_y, test_x, test_y = loadTrainingData()
    print(blue('begin training'))
    train(net, loss_function, optimizer, train_x, train_y, test_x, test_y)

    # x = train_x + test_x
    # y = train_y + test_y

    # training_data = np.load("hands.npy", allow_pickle=True)
    # x = torch.Tensor([i[0] for i in training_data]).view(-1, IMAGE_SIZE_X, IMAGE_SIZE_Y)
    # x /= 255.  # Change pixel value to range[0, 1)
    # y = [np.argwhere(i[1] == 1.)[0][0] for i in training_data]
    # y = torch.LongTensor(y)
    # acc, loss = test(net, loss_function, optimizer, x, y, size=len(train_x))
    # print(green(f'Total Dataset Accuracy: {acc}, Total Dataset Loss: {loss}'))

    while True:
        choice = str(input('test with a picture filename or type exit: '))
        if choice == 'exit':
            break
        test_image(net, choice)
 def test_enter_text(self):
     [self.repl.add_normal_character(c) for c in '1 + 1']
     screen = fsarray([
         cyan('>>> ') + bold(
             green('1') + cyan(' ') + yellow('+') + cyan(' ') + green('1')),
         cyan('Welcome to')
     ])
     self.assert_paint(screen, (0, 9))
Exemple #9
0
 def test_enter_text(self):
     [self.repl.add_normal_character(c) for c in "1 + 1"]
     screen = fsarray([
         cyan(">>> ") + bold(
             green("1") + cyan(" ") + yellow("+") + cyan(" ") + green("1")),
         cyan("Welcome to"),
     ])
     self.assert_paint(screen, (0, 9))
Exemple #10
0
def completion_string(completions, separator="", current=0):
    completions = [
        fmtstr(t.node.label +
               separator) if t.node.internal else fmtstr(t.node.label)
        for t in completions
    ]
    if current < len(completions):
        completions[current] = yellow(bold(completions[current]))
    string = fmtstr(" | ").join(completions)
    return fmtstr(" {") + string + fmtstr("}")
    def tick(self):
        for npc in self.npcs:
            self.move_entity(npc, *npc.towards(self.player))
        for entity1 in self.entities:
            for entity2 in self.entities:
                if entity1 is entity2: continue
                if (entity1.x, entity1.y) == (entity2.x, entity2.y):
                    if entity1 is self.player:
                        return 'you lost on turn %d' % self.turn
                    entity1.speed = 0
                    entity2.speed = 0
                    entity1.display = on_red(bold(yellow('o')))
                    entity2.display = on_red(bold(yellow('o')))

        if all(npc.speed == 0 for npc in self.npcs):
            return 'you won on turn %d' % self.turn
        self.turn += 1
        if self.turn % 20 == 0:
            self.player.speed = max(0, self.player.speed - 1)
            self.player.display = on_blue(green(bold(str(self.player.speed))))
Exemple #12
0
 def test_argspec(self):
     def foo(x, y, z=10):
         "docstring!"
         pass
     argspec = inspection.getargspec('foo', foo) + [1]
     array = replpainter.formatted_argspec(argspec, 30, setup_config())
     screen = [(bold(cyan(u'foo'))+cyan(':')+cyan(' ')+cyan('(')+cyan('x') +
               yellow(',')+yellow(' ')+bold(cyan('y'))+yellow(',') +
               yellow(' ')+cyan('z')+yellow('=')+bold(cyan('10'))+yellow(')'))]
     self.assertFSArraysEqual(fsarray(array), fsarray(screen))
 def test_argspec(self):
     def foo(x, y, z=10):
         "docstring!"
         pass
     argspec = inspection.getfuncprops('foo', foo)
     array = replpainter.formatted_argspec(argspec, 1, 30, setup_config())
     screen = [bold(cyan('foo')) + cyan(':') + cyan(' ') + cyan('(') +
               cyan('x') + yellow(',') + yellow(' ') + bold(cyan('y')) +
               yellow(',') + yellow(' ') + cyan('z') + yellow('=') +
               bold(cyan('10')) + yellow(')')]
     self.assertFSArraysEqual(fsarray(array), fsarray(screen))
Exemple #14
0
    def draw_help(self) -> None:
        """brings up the help menu"""
        self.state = "menu"
        items = [
            ('q', 'Quit Sweeper'),
            ('c', 'Close menu'),
            ('n', 'New game'),
            ('←,↑,→,↓', 'Move Cursor'),
            ('f', 'Flag/unflag'),
            ('SPACE', 'Clear'),
        ]

        max_key = max(len(item[0]) for item in items)
        lines = [
            ff.yellow(item[0]).ljust(max_key) + " : " + ff.gray(item[1])
            for item in items
        ]

        self.draw_menu(ff.bold("Help"), lines)
Exemple #15
0
    def test_argspec(self):
        def foo(x, y, z=10):
            "docstring!"
            pass

        argspec = inspection.getfuncprops("foo", foo)
        array = replpainter.formatted_argspec(argspec, 1, 30, setup_config())
        screen = [
            bold(cyan("foo")) + cyan(":") + cyan(" ") + cyan("(") + cyan("x") +
            yellow(",") + yellow(" ") + bold(cyan("y")) + yellow(",") +
            yellow(" ") + cyan("z") + yellow("=") + bold(cyan("10")) +
            yellow(")")
        ]
        assertFSArraysEqual(fsarray(array), fsarray(screen))
Exemple #16
0
    def move(self):
        print(
            yellow("left: " + str(self.power_left) + " right: " +
                   str(self.power_right)))
        left_base = 100
        right_base = 17

        if self.active:
            if self.power_left > 0:
                self.left_motor.forward(left_base)
            elif self.power_left < 0:
                self.left_motor.backward(left_base)
            else:
                self.left_motor.stop()

            if self.power_right > 0:
                self.right_motor.forward(right_base)
            elif self.power_right < 0:
                self.right_motor.backward(right_base)
            else:
                self.right_motor.stop()
Exemple #17
0
def train(net, loss_function, optimizer, train_x, train_y, test_x, test_y):
    batch_size = 100
    epochs = 10
    for epoch in range(epochs):
        count = 0
        val_count = 0
        sum_acc = 0
        sum_loss = 0
        sum_val_acc = 0
        sum_val_loss = 0
        for i in tqdm(range(0, len(train_x), batch_size)):
            batch_x = train_x[i:i + batch_size].view(-1, 1, IMAGE_SIZE_X,
                                                     IMAGE_SIZE_Y).to(device)
            batch_y = train_y[i:i + batch_size].to(device)
            with torch.enable_grad():
                acc, loss = fwd_pass(net,
                                     loss_function,
                                     optimizer,
                                     batch_x,
                                     batch_y,
                                     train=True)
                sum_acc += acc
                sum_loss += loss.item()
                count += 1

            if i % 200 == 0:
                val_acc, val_loss = test(net, loss_function, optimizer, test_x,
                                         test_y)
                sum_val_acc += val_acc
                sum_val_loss += val_loss
                val_count += 1

        print(
            yellow(f'EPOCH: {epoch}\t'
                   f'avg acc: {round(sum_acc / count, 5)}\t'
                   f'avg loss: {round(sum_loss / count, 5)}\t'
                   f'avg val acc: {round(sum_val_acc / val_count, 5)}\t'
                   f'avg val loss: {round(sum_val_loss / val_count, 5)}'))
Exemple #18
0
from __future__ import unicode_literals # convenient for Python 2
import random

from curtsies import FullscreenWindow, Input, FSArray
from curtsies.fmtfuncs import red, bold, green, on_blue, yellow

print(yellow('this prints normally, not to the alternate screen'))
with FullscreenWindow() as window:
    with Input() as input_generator:
        msg = red(on_blue(bold('Press escape to exit')))
        a = FSArray(window.height, window.width)
        a[0:1, 0:msg.width] = [msg]
        window.render_to_terminal(a)
        for c in input_generator:
            if c == '<ESC>':
                break
            elif c == '<SPACE>':
                a = FSArray(window.height, window.width)
            else:
                s = repr(c)
                row = random.choice(range(window.height))
                column = random.choice(range(window.width-len(s)))
                color = random.choice([red, green, on_blue, yellow])
                a[row, column:column+len(s)] = [color(s)]
            window.render_to_terminal(a)
Exemple #19
0
 def die(self):
     self.speed = 0
     self.display = on_red(bold(yellow('o')))
Exemple #20
0
 def die(self):
     self.speed = 0
     self.display = on_red(bold(yellow('o')))
    start_time -= 86400

    result = g.search_repositories(query)

    print(
        result.totalCount
    )  # Printing the total value of github repos for Python(Problem: API not returning 1.2 million search results instead returning 1000 results.)

    for repository in result:
        print(f"{repository.clone_url}")
        #print(f"{repository.tags_url}")
        #print(dir(repository))

        os.system(
            f"git clone {repository.clone_url} repos/{repository.owner.login}/{repository.name}"
        )
        d = "repos"

        for dirpath, dirnames, filenames in os.walk("repos"):
            for f in filenames:
                full_path = os.path.join(dirpath, f)

                if full_path.endswith(".py"):
                    pass
                else:
                    print(red(f"Deleting {full_path}"))
                    if d in full_path:
                        os.remove(full_path)
                    else:
                        print(yellow("Something is wrong"))
from panda3d.core import loadPrcFileData

from direct.showbase.ShowBase import ShowBase


base = ShowBase()
base.setSleep(0.001)


import random

from curtsies import FullscreenWindow, Input, FSArray
from curtsies.fmtfuncs import red, bold, green, on_blue, yellow
r = 0

print(yellow('the following code takes over the screen'))
with FullscreenWindow() as window:
    print(red(on_blue(bold('Press escape to exit'))))
    with Input() as input_generator:
        a = FSArray(window.height, window.width)
        a[r, 0] = [repr("Test " + str(r))]
        window.render_to_terminal(a)
        r += 1
        for c in input_generator:
            if c == '<ESC>':
                break
            elif c == '<SPACE>':
                a = FSArray(window.height, window.width)
            else:
                row = random.choice(range(window.height))
                column = random.choice(range(window.width-len(repr(c))))
Exemple #23
0
                self.right_motor.backward(right_base)
            else:
                self.right_motor.stop()

    def stop(self):
        print(green('stop'))
        self.power_left = 0
        self.power_right = 0

        self.move()


# robot = Robot(explorerhat.motor.one, explorerhat.motor.two)
robot = Robot(None, None)

print(yellow('use UP, DOWN, LEFT & RIGHT to steer - SPACE to stop'))
with Input() as input_generator:
    for c in input_generator:
        if c == '<ESC>':
            break
        elif c == '<SPACE>' or c == '<Ctrl-j>':
            robot.stop()
        elif c == '<UP>':
            robot.forward()
        elif c == '<DOWN>':
            robot.backward()
        elif c == '<LEFT>':
            robot.left()
        elif c == '<RIGHT>':
            robot.right()
        else:
Exemple #24
0
from __future__ import unicode_literals # convenient for Python 2
import random

from curtsies import FullscreenWindow, Input, FSArray
from curtsies.fmtfuncs import red, bold, green, on_blue, yellow

print(yellow('this prints normally, not to the alternate screen'))
with FullscreenWindow() as window:
    with Input() as input_generator:
        msg = red(on_blue(bold('Press escape to exit')))
        a = FSArray(window.height, window.width)
        a[0:1, 0:msg.width] = [msg]
        window.render_to_terminal(a)
        for c in input_generator:
            if c == '<ESC>':
                break
            elif c == '<SPACE>':
                a = FSArray(window.height, window.width)
            else:
                s = repr(c)
                row = random.choice(range(window.height))
                column = random.choice(range(window.width-len(s)))
                color = random.choice([red, green, on_blue, yellow])
                a[row, column:column+len(s)] = [color(s)]
            window.render_to_terminal(a)
Exemple #25
0
    'flexed_bicep', 'hand_with_fingers_splayed', 'index_pointing_up',
    'left_facing_fist', 'love-you_gesture'
]

DEVICE = 'cuda:0'

MODEL_NAME = f"model-{int(time.time() % 100000)}"
IMAGE_SIZE_X = 200
IMAGE_SIZE_Y = 200

if torch.cuda.is_available():
    device = torch.device(DEVICE)
    print(blue("Running on GPU"))
else:
    device = torch.device(DEVICE)
    print(yellow("Running on CPU"))


class Net(nn.Module):
    def __init__(self):
        super().__init__()

        self.conv1 = nn.Conv2d(1, 32, 5)
        self.conv2 = nn.Conv2d(32, 64, 5)
        self.conv3 = nn.Conv2d(64, 128, 5)

        x = torch.randn(IMAGE_SIZE_X,
                        IMAGE_SIZE_Y).view(-1, 1, IMAGE_SIZE_X, IMAGE_SIZE_Y)
        self._to_linear = None
        self.convs(x)
Exemple #26
0
import os
import time
from curtsies.fmtfuncs import cyan, bold, green, red, yellow

d = 'repos'
for dirpath, dirnames, filenames in os.walk("repos"):
    for f in filenames:
        path = os.path.join(dirpath, f)

        if path.endswith('.py'):
            print(green(f"Keeping {path}"))
        else:
            print(red(f"Deleting {path}"))

            if d in path:
                os.remove(path)
            else:
                print(yellow("Something went wrong"))
                time.sleep(60)
    # time.sleep(0.5)
Exemple #27
0
    def to_fsarray(self, width, prompt, tail=""):
        """Returns wrapped and coloured output as an fsarray. Includes the given
prompt and tail and fits in the given width."""
        string = yellow(prompt) + fmtstr("".join(self.typed)) + tail
        chunks = [string[i:i + width] for i in range(0, len(string), width)]
        return fsarray(chunks)
 def test_enter_text(self):
     [self.repl.add_normal_character(c) for c in '1 + 1']
     screen = fsarray([cyan('>>> ') + bold(green('1') + cyan(' ') +
                       yellow('+') + cyan(' ') + green('1')),
                       cyan('Welcome to')])
     self.assert_paint(screen, (0, 9))
Exemple #29
0
def mainloop(window, p2_bot=False):
    p1_attrs = {
        "appearance": on_blue(cyan("1")),
        "x": window.width // 4,
        "y": window.height // 2,
        "keys": {
            "w": 90,
            "a": 180,
            "s": 270,
            "d": 0
        },
    }

    p2_attrs = {
        "appearance": on_red(yellow("2")),
        "x": 3 * window.width // 4,
        "y": window.height // 2,
        "keys": {
            "<UP>": 90,
            "<LEFT>": 180,
            "<DOWN>": 270,
            "<RIGHT>": 0
        },
    }

    FPS = 15

    players = [Cycle(p1_attrs), Cycle(p2_attrs)]
    if p2_bot:  # make p2 a bot
        players[1] = Bot(p2_attrs)

    world = gameboard(window.width, window.height, players)
    dt = 1 / FPS
    world.draw_border()
    window.render_to_terminal(world.grid)

    reactor = Input()
    schedule_next_frame = reactor.scheduled_event_trigger(Frame)
    schedule_next_frame(when=time.time())
    with reactor:
        for c in reactor:
            if isinstance(c, Frame):
                tick = world.tick()
                window.render_to_terminal(world.grid)
                if not tick:  # if no crashes
                    when = c.when + dt
                    while when < time.time():
                        when += dt
                    schedule_next_frame(when)
                else:  # if crashed
                    world.grid[0:4, 0:25] = fsarray([
                        world.winner_msg(tick),
                        "r to restart",
                        "q to quit",
                        "b to make player 2 a bot",
                    ])
                    window.render_to_terminal(world.grid)
            elif c.lower() in ["r", "q", "b"]:
                break
            else:  # common case
                world.process_event(c)
    if c.lower() == "r":
        mainloop(window, p2_bot)
    elif c.lower() == "b":
        mainloop(window, True)