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_syntaxerror(self): i = interpreter.Interp() a = [] def append_to_a(message): a.append(message) i.write = append_to_a i.runsource('1.1.1.1') if pypy: expected = ( ' File ' + green('"<input>"') + ', line ' + bold(magenta('1')) + '\n 1.1.1.1\n ^\n' + bold(red('SyntaxError')) + ': ' + cyan('invalid syntax') + '\n') else: expected = ( ' File ' + green('"<input>"') + ', line ' + bold(magenta('1')) + '\n 1.1.1.1\n ^\n' + bold(red('SyntaxError')) + ': ' + cyan('invalid syntax') + '\n') self.assertMultiLineEqual(str(plain('').join(a)), str(expected)) self.assertEquals(plain('').join(a), expected)
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_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))
def test_fmt_strings_remain_unchanged_when_used_to_construct_other_ones( self): a = fmtstr('hi', 'blue') b = fmtstr('there', 'red') c = a + b green(c) self.assertEqual(a.shared_atts['fg'], FG_COLORS['blue']) self.assertEqual(b.shared_atts['fg'], FG_COLORS['red'])
def test_fmt_strings_remain_unchanged_when_used_to_construct_other_ones( self): a = fmtstr("hi", "blue") b = fmtstr("there", "red") c = a + b green(c) self.assertEqual(a.shared_atts["fg"], FG_COLORS["blue"]) self.assertEqual(b.shared_atts["fg"], FG_COLORS["red"])
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))
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'))
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"), )
def test_various_splices(self): a = blue('hi') b = a + green('bye') c = b + red('!') self.assertEqual( c.splice('asdfg', 1), blue('h') + 'asdfg' + blue('i') + green('bye') + red('!')) self.assertEqual(c.splice('asdfg', 1, 4), blue('h') + 'asdfg' + green('e') + red('!')) self.assertEqual(c.splice('asdfg', 1, 5), blue('h') + 'asdfg' + red('!'))
def test_various_splices(self): a = blue("hi") b = a + green("bye") c = b + red("!") self.assertEqual( c.splice("asdfg", 1), blue("h") + "asdfg" + blue("i") + green("bye") + red("!"), ) self.assertEqual(c.splice("asdfg", 1, 4), blue("h") + "asdfg" + green("e") + red("!")) self.assertEqual(c.splice("asdfg", 1, 5), blue("h") + "asdfg" + red("!"))
def test_traceback(self): i = interpreter.Interp() a = [] def append_to_a(message): a.append(message) i.write = append_to_a def f(): return 1 / 0 def g(): return f() i.runsource('g()', encode=False) if pypy: global_not_found = "global name 'g' is not defined" else: global_not_found = "name 'g' is not defined" expected = 'Traceback (most recent call last):\n File ' + \ green('"%s"' % _last_console_filename()) + ', line ' + bold(magenta('1')) + ', in ' + \ cyan('<module>') + '\n g()\n' + bold(red('NameError')) + ': ' + \ cyan(global_not_found) + '\n' self.assertMultiLineEqual(str(plain('').join(a)), str(expected)) self.assertEquals(plain('').join(a), expected)
def test_traceback(self): i, a = self.interp_errlog() def f(): return 1 / 0 def gfunc(): return f() i.runsource("gfunc()") global_not_found = "name 'gfunc' is not defined" expected = ( "Traceback (most recent call last):\n File " + green('"<input>"') + ", line " + bold(magenta("1")) + ", in " + cyan("<module>") + "\n gfunc()\n" + bold(red("NameError")) + ": " + cyan(global_not_found) + "\n" ) self.assertMultiLineEqual(str(plain("").join(a)), str(expected)) self.assertEqual(plain("").join(a), expected)
def __init__(self, width, height): self.width = width self.height = height n = 10 self.player = Entity(on_blue(green(bold('5'))), width // 2, height // 2 - 2, speed=5) self.npcs = [Entity(on_blue(red('X')), i * width // (n * 2), j * height // (n * 2)) for i in range(1, 2*n, 2) for j in range(1, 2*n, 2)] self.turn = 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_image(net, name): _name = name while True: try: image = cv2.imread(_name, cv2.IMREAD_GRAYSCALE) break except FileNotFoundError as _: _name = str(input(red('could not find file. try again: '))) image = image[:, (1920 - 1080) // 2:(1920 - 1080) // 2 + 1080] resize_img = cv2.resize(image, (IMAGE_SIZE_X, IMAGE_SIZE_Y)) cv2.imwrite('tiny.png', resize_img) resize_img = np.asarray(resize_img) resize_img = [i / 255. for i in resize_img] tensor_img = torch.tensor(resize_img, dtype=torch.float).view(-1, 1, IMAGE_SIZE_X, IMAGE_SIZE_Y) # cv2.imshow('current test', image) tensor_img = tensor_img.to(DEVICE) with torch.no_grad(): output = net(tensor_img) argmax = int(torch.argmax(output)) print(green(OUTPUTS[argmax]), '\tconfidence:', torch.max(output).item())
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_traceback(self): i = interpreter.Interp() a = [] def append_to_a(message): a.append(message) i.write = append_to_a def f(): return 1/0 def g(): return f() i.runsource('g()', encode=False) if pypy: global_not_found = "global name 'g' is not defined" else: global_not_found = "name 'g' is not defined" expected = 'Traceback (most recent call last):\n File ' + \ green('"%s"' % _last_console_filename()) + ', line ' + bold(magenta('1')) + ', in ' + \ cyan('<module>') + '\n g()\n' + bold(red('NameError')) + ': ' + \ cyan(global_not_found) + '\n' self.assertMultiLineEqual(str(plain('').join(a)), str(expected)) self.assertEquals(plain('').join(a), expected)
def test_syntaxerror(self): i, a = self.interp_errlog() i.runsource('1.1.1.1') if pypy: expected = (' File ' + green('"<input>"') + ', line ' + bold(magenta('1')) + '\n 1.1.1.1\n ^\n' + bold(red('SyntaxError')) + ': ' + cyan('invalid syntax') + '\n') else: expected = (' File ' + green('"<input>"') + ', line ' + bold(magenta('1')) + '\n 1.1.1.1\n ^\n' + bold(red('SyntaxError')) + ': ' + cyan('invalid syntax') + '\n') self.assertMultiLineEqual(str(plain('').join(a)), str(expected)) self.assertEqual(plain('').join(a), expected)
def test_syntaxerror(self): i, a = self.interp_errlog() i.runsource("1.1.1.1") if sys.version_info[:2] >= (3, 8): expected = ( " File " + green('"<input>"') + ", line " + bold(magenta("1")) + "\n 1.1.1.1\n ^\n" + bold(red("SyntaxError")) + ": " + cyan("invalid syntax") + "\n" ) elif pypy: expected = ( " File " + green('"<input>"') + ", line " + bold(magenta("1")) + "\n 1.1.1.1\n ^\n" + bold(red("SyntaxError")) + ": " + cyan("invalid syntax") + "\n" ) else: expected = ( " File " + green('"<input>"') + ", line " + bold(magenta("1")) + "\n 1.1.1.1\n ^\n" + bold(red("SyntaxError")) + ": " + cyan("invalid syntax") + "\n" ) self.assertMultiLineEqual(str(plain("").join(a)), str(expected)) self.assertEqual(plain("").join(a), expected)
def test_syntaxerror(self): i, a = self.interp_errlog() i.runsource('1.1.1.1') if pypy: expected = ( ' File ' + green('"<input>"') + ', line ' + bold(magenta('1')) + '\n 1.1.1.1\n ^\n' + bold(red('SyntaxError')) + ': ' + cyan('invalid syntax') + '\n') else: expected = ( ' File ' + green('"<input>"') + ', line ' + bold(magenta('1')) + '\n 1.1.1.1\n ^\n' + bold(red('SyntaxError')) + ': ' + cyan('invalid syntax') + '\n') self.assertMultiLineEqual(str(plain('').join(a)), str(expected)) self.assertEqual(plain('').join(a), expected)
def __repr__(self): s = fmtfuncs.bold(type(self).__name__) s += (': '+fmtfuncs.bold(self.title.title()) if self.title else '') s += '\n' s += fmtfuncs.gray(self.question) s += '\n' s += fmtfuncs.gray('\n').join(fmtfuncs.green(repr(x) if not isinstance(x, basestring) else x) for x in self.corrects) s += '\n' s += fmtfuncs.gray('\n').join(fmtfuncs.red(repr(x) if not isinstance(x, basestring) else x) for x in self.wrongs) s += '\n' return str(s)
def test_right_sequence_in_py3(self): red_on_blue = fmtstr('hello', 'red', 'on_blue') blue_on_red = fmtstr('there', fg='blue', bg='red') green_s = fmtstr('!', 'green') full = red_on_blue + ' ' + blue_on_red + green_s self.assertEqual( full, on_blue(red("hello")) + " " + on_red(blue("there")) + green("!")) self.assertEqual( str(full), '\x1b[31m\x1b[44mhello\x1b[49m\x1b[39m \x1b[34m\x1b[41mthere\x1b[49m\x1b[39m\x1b[32m!\x1b[39m' )
def test_right_sequence_in_py3(self): red_on_blue = fmtstr("hello", "red", "on_blue") blue_on_red = fmtstr("there", fg="blue", bg="red") green_s = fmtstr("!", "green") full = red_on_blue + " " + blue_on_red + green_s self.assertEqual( full, on_blue(red("hello")) + " " + on_red(blue("there")) + green("!")) self.assertEqual( str(full), "\x1b[31m\x1b[44mhello\x1b[49m\x1b[39m \x1b[34m\x1b[41mthere\x1b[49m\x1b[39m\x1b[32m!\x1b[39m", )
def test_ljust_rjust(self): """""" b = fmtstr(u'ab', 'blue', 'on_red', 'bold') g = fmtstr(u'cd', 'green', 'on_red', 'bold') s = b + g self.assertEqual(s.ljust(6), b + g + on_red(' ')) self.assertEqual(s.rjust(6), on_red(' ') + b + g) # doesn't add empties to end self.assertEqual(s.ljust(4), b + g) self.assertEqual(s.rjust(4), b + g) # behavior if background different s = on_blue('a') + on_green('b') self.assertEqual(s.ljust(3), fmtstr('ab ')) self.assertEqual(s.rjust(3), fmtstr(' ab')) s = blue(on_blue('a')) + green(on_green('b')) self.assertEqual(s.ljust(3), blue('a') + green('b') + fmtstr(' ')) self.assertEqual(s.rjust(3), fmtstr(' ') + blue('a') + green('b')) #using fillchar self.assertEqual(s.ljust(3, '*'), fmtstr('ab*')) self.assertEqual(s.rjust(3, '*'), fmtstr('*ab'))
def test_ljust_rjust(self): """""" b = fmtstr("ab", "blue", "on_red", "bold") g = fmtstr("cd", "green", "on_red", "bold") s = b + g self.assertEqual(s.ljust(6), b + g + on_red(" ")) self.assertEqual(s.rjust(6), on_red(" ") + b + g) # doesn't add empties to end self.assertEqual(s.ljust(4), b + g) self.assertEqual(s.rjust(4), b + g) # behavior if background different s = on_blue("a") + on_green("b") self.assertEqual(s.ljust(3), fmtstr("ab ")) self.assertEqual(s.rjust(3), fmtstr(" ab")) s = blue(on_blue("a")) + green(on_green("b")) self.assertEqual(s.ljust(3), blue("a") + green("b") + fmtstr(" ")) self.assertEqual(s.rjust(3), fmtstr(" ") + blue("a") + green("b")) # using fillchar self.assertEqual(s.ljust(3, "*"), fmtstr("ab*")) self.assertEqual(s.rjust(3, "*"), fmtstr("*ab"))
def test_syntaxerror(self): i = interpreter.Interp() a = [] def append_to_a(message): a.append(message) i.write = append_to_a i.runsource('1.1.1.1') expected = ''+u''+u' File '+green(u'"<input>"')+u', line '+bold(magenta(u'1'))+u'\n'+u' '+u'1.1'+u'.'+u'1.1'+u'\n'+u' '+u' '+u'^'+u'\n'+bold(red(u'SyntaxError'))+u': '+cyan(u'invalid syntax')+u'\n' self.assertEquals(str(plain('').join(a)), str(expected)) self.assertEquals(plain('').join(a), expected)
def __init__(self, width, height): self.width = width self.height = height n = 5 self.player = Entity(on_blue(green(bold('5'))), width // 2, height // 2 - 2, speed=5) self.npcs = [ Entity(on_blue(red('X')), i * width // (n * 2), j * height // (n * 2)) for i in range(1, 2 * n, 2) for j in range(1, 2 * n, 2) ] self.turn = 0
def draw_won(self) -> None: """Confirms we want to restart the game""" assert self.field is not None items = [ ff.plain( f"Congratulations! You won in {self.field.game_time.in_words()}" ), ff.plain(f"Press ") + fmtstr("n", fg="yellow", underline=True) + " to start a new game,", ff.plain("or ") + fmtstr("c", fg="yellow", underline=True) + " to savor your success.", ] self.draw_menu(ff.green("Victory!"), items)
def tick(self): for npc in self.npcs: self.move_entity(npc, *npc.towards(self.player)) for entity1, entity2 in itertools.combinations(self.entities, 2): if (entity1.x, entity1.y) == (entity2.x, entity2.y): if self.player in (entity1, entity2): return 'you lost on turn %d' % self.turn entity1.die() entity2.die() 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))))
def tick(self): """Returns a message to be displayed if game is over, else None""" for npc in self.npcs: self.move_entity(npc, *npc.towards(self.player)) for entity1, entity2 in itertools.combinations(self.entities, 2): if (entity1.x, entity1.y) == (entity2.x, entity2.y): if self.player in (entity1, entity2): return 'you lost on turn %d' % self.turn entity1.die() entity2.die() 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(1, self.player.speed - 1) self.player.display = on_blue(green(bold(str(self.player.speed))))
def tick(self): """Returns a message to be displayed if game is over, else None""" for npc in self.npcs: self.move_entity(npc, *npc.towards(self.player)) for entity1, entity2 in itertools.combinations(self.entities, 2): if (entity1.x, entity1.y) == (entity2.x, entity2.y): if self.player in (entity1, entity2): return 'you lost on turn %d' % self.turn entity1.die() entity2.die() 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(1, self.player.speed - 1) self.player.display = on_blue(green(bold(str(self.player.speed).decode('utf8'))))
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))))
def test_traceback(self): i = interpreter.Interp() a = [] def append_to_a(message): a.append(message) i.write = append_to_a def f(): return 1/0 def g(): return f() i.runsource('g()') expected = u'Traceback (most recent call last):\n'+''+u' File '+green(u'"<input>"')+u', line '+bold (magenta(u'1'))+u', in '+cyan(u'<module>')+u'\n'+''+bold(red(u'NameError'))+u': '+cyan(u"name 'g' is not defined")+u'\n' self.assertEquals(str(plain('').join(a)), str(expected)) self.assertEquals(plain('').join(a), expected)
def test_traceback(self): i, a = self.interp_errlog() def f(): return 1 / 0 def gfunc(): return f() i.runsource('gfunc()') if pypy and not py3: global_not_found = "global name 'gfunc' is not defined" else: global_not_found = "name 'gfunc' is not defined" expected = ( 'Traceback (most recent call last):\n File ' + green('"<input>"') + ', line ' + bold(magenta('1')) + ', in ' + cyan('<module>') + '\n gfunc()\n' + bold(red('NameError')) + ': ' + cyan(global_not_found) + '\n') self.assertMultiLineEqual(str(plain('').join(a)), str(expected)) self.assertEqual(plain('').join(a), expected)
def test_traceback(self): i = interpreter.Interp() a = [] def append_to_a(message): a.append(message) i.write = append_to_a def f(): return 1/0 def g(): return f() i.runsource('g()') expected = 'Traceback (most recent call last):\n File ' + \ green('"<input>"') + ', line ' + bold(magenta('1')) + ', in ' + \ cyan('<module>') + '\n' + bold(red('NameError')) + ': ' + \ cyan("name 'g' is not defined") + '\n' self.assertEquals(str(plain('').join(a)), str(expected)) self.assertEquals(plain('').join(a), expected)
def test_traceback(self): i, a = self.interp_errlog() def f(): return 1 / 0 def gfunc(): return f() i.runsource('gfunc()') if pypy: global_not_found = "global name 'gfunc' is not defined" else: global_not_found = "name 'gfunc' is not defined" expected = ('Traceback (most recent call last):\n File ' + green('"<input>"') + ', line ' + bold(magenta('1')) + ', in ' + cyan('<module>') + '\n gfunc()\n' + bold(red('NameError')) + ': ' + cyan(global_not_found) + '\n') self.assertMultiLineEqual(str(plain('').join(a)), str(expected)) self.assertEqual(plain('').join(a), expected)
def render(self): return linesplit(green(''.join(s.decode('latin-1') for s in self.received)), 80) if self.received else ['']
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))
def render(self): return linesplit( green(''.join( s.decode('latin-1') for s in self.received)), 80) if self.received else ['']
def stop(self): print(green('stop')) self.power_left = 0 self.power_right = 0 self.move()
def right(self): print(green('right')) if self.power_left < 1: self.power_left += 1 if self.power_right > -1: self.power_right -= 1 self.move()