def train(args, model, device, train_loader, test_loader, optimizer, epoch): model.train() lr = optimizer.param_groups[0]['lr'] correct = 0 total = 0 losses = AverageMeter() for i, data in enumerate(train_loader): inputs, labels = data[0].to(device), data[1].to(device) optimizer.zero_grad() outputs = model(inputs) loss = nn.CrossEntropyLoss()(outputs, labels) loss.backward() optimizer.step() losses.update(loss.float().mean().item()) _, predicted = outputs.max(1) total += labels.size(0) correct += predicted.eq(labels).sum().item() acc = correct * 100. / total progress_bar( i, len(train_loader), '[Epoch %d] CE: %.4f | Top 1 Acc: %0.2f%% | LR: %.2e' % (epoch, losses.avg, acc, lr)) return test(args, model, device, test_loader)
def test(args, model, device, test_loader): model.eval() top1 = AverageMeter() top5 = AverageMeter() with torch.no_grad(): for i, data in enumerate(test_loader): inputs, labels = data[0].to(device), data[1].to(device) outputs = model(inputs) acc1, acc5 = accuracy(outputs, labels, (1, 5)) top1.update(acc1[0], inputs.size(0)) top5.update(acc5[0], inputs.size(0)) progress_bar( i, len(test_loader), 'Test accuracy Top 1: %0.2f%%, Top 5: %0.2f%%' % (top1.avg, top5.avg)) return top1.avg, top5.avg
def _download(self, url, file_name): """ See :meth:`download`. """ downloads_directory = config.CONFIG["downloads-directory"] if utils.prepare_directory(downloads_directory): logger.info( "Created directory(s) %s.", downloads_directory ) # Find an available file path final_file_path = utils.find_available_file( os.path.join(downloads_directory, file_name) ) final_file_name = os.path.basename(final_file_path) logger.debug("File will be saved to %s.", final_file_path) # Get a generator function that makes a pretty progress bar. bar = ui.progress_bar_indeterminate() # Actually try to grab the file from the server while True: ui.print_carriage( "%s Trying to download file... %s" % (ui.progress_bar(0.0), " " * 30) ) # Ask the server for the file try: file_request = self.requests_session.get( url, timeout = 1, stream = True, verify = _get_verify() ) except requests.exceptions.Timeout: logger.info( "Request timed out. Server did not accept connection after " "1 second." ) # If it's giving it to us... if file_request.status_code == 200: logger.debug( "Response headers...\n%s", pprint.pformat(file_request.headers, width = 72) ) if "content-length" in file_request.headers: size = float(file_request.headers["content-length"]) else: logger.info("File is of unknown size.") size = 0 ui.print_carriage( ui.progress_bar(-1) + " Downloading file." ) # Download the file in chunks. chunk_size = 124 downloaded = 0 with open(final_file_path, "wb") as f: for chunk in file_request.iter_content(124): if size != 0: ui.print_carriage( ui.progress_bar(downloaded / size) + " Downloading file." ) downloaded += chunk_size f.write(chunk) # If the server got particularly angry at us... if (file_request.status_code == 500 or ("X-CallSuccess" in file_request.headers and file_request.headers["X-CallSuccess"] == "False")): logger.critical( "500 response. The server encountered an error." ) sys.exit(1) if file_request.status_code == requests.codes.ok: break # Make sure that the trying prompt appears for at least a moment or # so time.sleep(0.5) period = 0.1 wait_for = 4 for i in xrange(int(wait_for / period)): ui.print_carriage( next(bar) + " Download not ready yet. Waiting." ) time.sleep(period) print "File saved to %s." % utils.shorten_path(final_file_path)
def main(): config = Null() config.keyScrollSpeed = 2000.0 config.musicVolume = .5 view = Null() view.pos = v((0, 0)) view.sprites = {} view.cursor = {} view.units = [] view.selarea = None view.begin_pos = None view.scroll_start = None view.selection = [] view.players = [] view.ct = 0.0 view.scrollleft = False view.scrollright = False view.scrollup = False view.scrolldown = False view.uisprites = [] view.config = config view.tilepalcount = 0 view.followselection = False init(sys.argv, view) dt = .001 mp = 0 #view.pathfind.set_map(chr(0)*view.mapdim[0]*view.mapdim[1]) clock = pygame.time.Clock() while True: for event in pygame.event.get(): if handle_event(event, view): return #view.path = pathf(view.occu) view.occu = list([list(x) for x in view.mapw]) for player in view.players: player.food = v(0, 0, 0) player.hunger = v(0, 0, 0) for unit in view.units: unit.update(dt, view) if view.scrollleft: view.pos = view.pos + v(-1.0, 0.0) * config.keyScrollSpeed * dt if view.scrollright: view.pos = view.pos + v(1.0, 0.0) * config.keyScrollSpeed * dt if view.scrollup: view.pos = view.pos + v(0.0, -1.0) * config.keyScrollSpeed * dt if view.scrolldown: view.pos = view.pos + v(0.0, 1.0) * config.keyScrollSpeed * dt if view.followselection and view.selection != []: poss = [x.pos for x in view.selection] poss = sum(poss) / len(poss) view.pos = poss - v(640, 480) / 2 if view.pos[0] < 0: view.pos[0] = 0 if view.pos[1] < 0: view.pos[1] = 0 maxx = view.mapdim[0] * 32 - view.screen.get_width() maxy = (view.mapdim[1] - 12) * 32 if view.pos[0] > maxx: view.pos[0] = maxx if view.pos[1] > maxy: view.pos[1] = maxy view.pos = v([int(x) for x in view.pos]) view.screen.fill((0, 0, 0)) if view.tileset == "platform": star.draw(view) draw_tiles(view) tempunits = [] for unit in view.units: tempunits.append((unit.level, unit.pos[1], unit)) tempunits.sort() view.minimapover = pygame.surface.Surface((128, 128), pygame.SRCALPHA, 32) for unit in tempunits: unit[2].draw(view) for sprite in view.uisprites: sprite.draw(view) sprite.update() if view.selarea: pygame.draw.rect(view.screen, (16, 252, 24), view.selarea, 1) #68 w 3 down player = view.players[0] player.raceindex = 1 player.minerals = 50 player.gas = 0 #print player.food, player.hunger icons = [ (0, player.minerals, (16, 252, 24)), (player.raceindex + 1, player.gas, (16, 252, 24)), ] for raceindex in range(3): food = player.food[raceindex] hunger = player.hunger[raceindex] if not food and not hunger: # heh continue if food >= hunger: color = (16, 252, 24) else: color = (200, 24, 24) icons.append((raceindex + 4, str(hunger) + "/" + str(food), color)) sprite = view.sprites["icons"] x = 640 icons.reverse() for icon in icons: x -= 68 view.screen.blit(sprite[icon[0]], (x, 3)) text = font.render(10, str(icon[1]), "game5") view.screen.blit(text, (x + 16, 3)) view.screen.blit(view.sprites['ConsoleTerran'], (0, 0)) view.screen.blit(view.minimap, v(6, 348) + (64, 64) - v(view.minimap.get_size()) / 2) view.screen.blit(view.minimapover, v(6, 348) + (64, 64) - v(view.minimap.get_size()) / 2) topleft = v(6, 348) + (64, 64) - v(view.minimap.get_size()) / 2 pygame.draw.line(view.screen, (204, 204, 208), topleft + (0, -1), topleft + (128, -1)) bottomright = v(6, 348) + (64, 64) + v(view.minimap.get_size()) / 2 pygame.draw.line(view.screen, (172, 152, 148), bottomright, bottomright + (-128, 0)) pygame.draw.rect( view.screen, (255, 255, 255), (v(6, 348) + (64, 64) - v(view.minimap.get_size()) / 2 + view.pos / 32, (20, 13)), 1) #print view.mapdim (173, 389) if len(view.selection) == 0: pass elif len(view.selection) == 1: u = view.selection[0] if u.id: w = view.sprites["Wireframe"][u.id] w.set_palette(get_wpalette(u)) view.screen.blit(w, (168, 388)) if u.health != None: s = str(int(u.health)) + "/" + str(u.maxhealth) t = font.render(8, s, "game5", True) view.screen.blit(t, v(199, 457) - v(t.get_size()) / 2) s = u.name t = font.render(10, u.name, "game0", True) view.screen.blit(t, v(315, 394) - v(t.get_size()) / 2) else: pass #multiple grpwire.grp #buttons view.screen.blit(view.sprites["TerranButtons"][4], (3, 320)) view.screen.blit(view.sprites["TerranButtons"][0], (416, 388)) view.screen.blit(font.render(8, "MENU", "game1"), (435, 394)) mp += .5 mp = mp % 10 view.screen.blit(view.movie[int(mp)], (413, 410)) #pygame.draw.rect(view.screen, (128,128,128), ((413,410),(60,56))) view.screen.blit(view.sprites["TerranOverlay"], (413, 410)) if debug: surf = font.render(8, str(int(clock.get_fps() + .5)), "game0") view.screen.blit(surf, (0, 0)) if pygame.mouse.get_focused(): view.ct += dt * 8 cursor = 'CursorArrow' u = get_unit_at_point(pygame.mouse.get_pos() + view.pos, view) if u: if u.player == view.players[0]: cursor = 'CursorTarget2Green' elif u.player == -1: cursor = 'CursorTarget2Yellow' else: cursor = 'CursorTarget2Red' if view.selarea: cursor = 'CursorDrag' if view.scroll_start: cursor = None if view.sprites['ConsoleTerran'].get_at( pygame.mouse.get_pos()) != (0, 0, 0, 255): cursor = "CursorArrow" if cursor == "CursorArrow": view.ct = view.ct % 4.0 elif cursor in ("CursorTarget2Green", "CursorTarget2Yellow", "CursorTarget2Red"): view.ct = view.ct % 14.0 else: view.ct = 0 if cursor: sprite = view.sprites[cursor][int(view.ct)] view.screen.blit( sprite, v(pygame.mouse.get_pos()) - v(sprite.get_size()) / 2) try: a except NameError: a = 0. a += dt a = a % 5 view.screen.blit(ui.progress_bar(a / 5, view), (281, 426)) pygame.display.update() pygame.mixer.music.set_volume(view.config.musicVolume) #sendp(cPickle.dumps(view.units),view) #try: # while True: # view.units = cPickle.loads(view.socket.recvfrom(2**20)[0]) #except socket.error: pass if debug: clock.tick() else: clock.tick(30) dt = clock.get_time() / 1000.0
def main(): config = Null() config.keyScrollSpeed = 2000.0 config.musicVolume = .5 view = Null() view.pos = v((0,0)) view.sprites = {} view.cursor = {} view.units = [] view.selarea = None view.begin_pos = None view.scroll_start = None view.selection = [] view.players = [] view.ct = 0.0 view.scrollleft = False view.scrollright = False view.scrollup = False view.scrolldown = False view.uisprites = [] view.config = config view.tilepalcount = 0 view.followselection = False init(sys.argv, view) dt = .001 mp = 0 #view.pathfind.set_map(chr(0)*view.mapdim[0]*view.mapdim[1]) clock = pygame.time.Clock() while True: for event in pygame.event.get(): if handle_event(event, view): return #view.path = pathf(view.occu) view.occu = list([list(x) for x in view.mapw]) for player in view.players: player.food = v(0,0,0) player.hunger = v(0,0,0) for unit in view.units: unit.update(dt, view) if view.scrollleft: view.pos = view.pos + v(-1.0,0.0)*config.keyScrollSpeed*dt if view.scrollright: view.pos = view.pos + v(1.0,0.0)*config.keyScrollSpeed*dt if view.scrollup: view.pos = view.pos + v(0.0,-1.0)*config.keyScrollSpeed*dt if view.scrolldown: view.pos = view.pos + v(0.0,1.0)*config.keyScrollSpeed*dt if view.followselection and view.selection != []: poss = [x.pos for x in view.selection] poss = sum(poss)/len(poss) view.pos = poss - v(640,480)/2 if view.pos[0] < 0: view.pos[0] = 0 if view.pos[1] < 0: view.pos[1] = 0 maxx = view.mapdim[0]*32 - view.screen.get_width() maxy = (view.mapdim[1]-12)*32 if view.pos[0] > maxx: view.pos[0] = maxx if view.pos[1] > maxy: view.pos[1] = maxy view.pos = v([int(x) for x in view.pos]) view.screen.fill((0,0,0)) if view.tileset == "platform": star.draw(view) draw_tiles(view) tempunits = [] for unit in view.units: tempunits.append((unit.level,unit.pos[1],unit)) tempunits.sort() view.minimapover = pygame.surface.Surface((128,128),pygame.SRCALPHA,32) for unit in tempunits: unit[2].draw(view) for sprite in view.uisprites: sprite.draw(view) sprite.update() if view.selarea: pygame.draw.rect(view.screen, (16,252,24), view.selarea, 1) #68 w 3 down player = view.players[0] player.raceindex = 1 player.minerals = 50 player.gas = 0 #print player.food, player.hunger icons = [ (0, player.minerals, (16, 252, 24)), (player.raceindex+1, player.gas, (16, 252, 24)), ] for raceindex in range(3): food = player.food[raceindex] hunger = player.hunger[raceindex] if not food and not hunger: # heh continue if food >= hunger: color = (16, 252, 24) else: color = (200,24,24) icons.append((raceindex+4, str(hunger)+"/"+str(food), color)) sprite = view.sprites["icons"] x = 640 icons.reverse() for icon in icons: x -= 68 view.screen.blit(sprite[icon[0]],(x,3)) text = font.render(10, str(icon[1]), "game5") view.screen.blit(text, (x+16, 3)) view.screen.blit(view.sprites['ConsoleTerran'],(0,0)) view.screen.blit(view.minimap, v(6,348)+(64,64)-v(view.minimap.get_size())/2) view.screen.blit(view.minimapover, v(6,348)+(64,64)-v(view.minimap.get_size())/2) topleft = v(6,348)+(64,64)-v(view.minimap.get_size())/2 pygame.draw.line(view.screen, (204,204,208), topleft+(0,-1), topleft+(128,-1)) bottomright = v(6,348)+(64,64)+v(view.minimap.get_size())/2 pygame.draw.line(view.screen, (172,152,148), bottomright, bottomright+(-128,0)) pygame.draw.rect(view.screen,(255,255,255), (v(6,348)+(64,64)-v(view.minimap.get_size())/2+view.pos/32,(20,13)),1) #print view.mapdim (173,389) if len(view.selection) == 0: pass elif len(view.selection) == 1: u = view.selection[0] if u.id: w = view.sprites["Wireframe"][u.id] w.set_palette(get_wpalette(u)) view.screen.blit(w, (168,388)) if u.health != None: s = str(int(u.health))+"/"+str(u.maxhealth) t = font.render(8, s, "game5", True) view.screen.blit(t,v(199,457)-v(t.get_size())/2) s = u.name t = font.render(10, u.name, "game0", True) view.screen.blit(t,v(315,394)-v(t.get_size())/2) else: pass #multiple grpwire.grp #buttons view.screen.blit(view.sprites["TerranButtons"][4], (3,320)) view.screen.blit(view.sprites["TerranButtons"][0], (416,388)) view.screen.blit(font.render(8,"MENU", "game1"),(435,394)) mp += .5 mp = mp % 10 view.screen.blit(view.movie[int(mp)], (413,410)) #pygame.draw.rect(view.screen, (128,128,128), ((413,410),(60,56))) view.screen.blit(view.sprites["TerranOverlay"], (413, 410)) if debug: surf = font.render(8, str(int(clock.get_fps()+.5)), "game0") view.screen.blit(surf,(0,0)) if pygame.mouse.get_focused(): view.ct += dt * 8 cursor = 'CursorArrow' u = get_unit_at_point(pygame.mouse.get_pos()+view.pos,view) if u: if u.player == view.players[0]: cursor = 'CursorTarget2Green' elif u.player == -1: cursor = 'CursorTarget2Yellow' else: cursor = 'CursorTarget2Red' if view.selarea: cursor = 'CursorDrag' if view.scroll_start: cursor = None if view.sprites['ConsoleTerran'].get_at(pygame.mouse.get_pos()) != (0,0,0,255): cursor = "CursorArrow" if cursor == "CursorArrow": view.ct = view.ct % 4.0 elif cursor in ("CursorTarget2Green","CursorTarget2Yellow","CursorTarget2Red"): view.ct = view.ct % 14.0 else: view.ct = 0 if cursor: sprite = view.sprites[cursor][int(view.ct)] view.screen.blit(sprite, v(pygame.mouse.get_pos())-v(sprite.get_size())/2) try: a except NameError: a = 0. a += dt a = a % 5 view.screen.blit(ui.progress_bar(a/5,view),(281,426)) pygame.display.update() pygame.mixer.music.set_volume(view.config.musicVolume) #sendp(cPickle.dumps(view.units),view) #try: # while True: # view.units = cPickle.loads(view.socket.recvfrom(2**20)[0]) #except socket.error: pass if debug: clock.tick() else: clock.tick(30) dt = clock.get_time()/1000.0
def _download(self, url, file_name): """ See :meth:`download`. """ downloads_directory = config.CONFIG["downloads-directory"] if utils.prepare_directory(downloads_directory): logger.info("Created directory(s) %s.", downloads_directory) # Find an available file path final_file_path = utils.find_available_file( os.path.join(downloads_directory, file_name)) final_file_name = os.path.basename(final_file_path) logger.debug("File will be saved to %s.", final_file_path) # Get a generator function that makes a pretty progress bar. bar = ui.progress_bar_indeterminate() # Actually try to grab the file from the server while True: ui.print_carriage("%s Trying to download file... %s" % (ui.progress_bar(0.0), " " * 30)) # Ask the server for the file try: file_request = self.requests_session.get(url, timeout=1, stream=True, verify=_get_verify()) except requests.exceptions.Timeout: logger.info( "Request timed out. Server did not accept connection after " "1 second.") # If it's giving it to us... if file_request.status_code == 200: logger.debug("Response headers...\n%s", pprint.pformat(file_request.headers, width=72)) if "content-length" in file_request.headers: size = float(file_request.headers["content-length"]) else: logger.info("File is of unknown size.") size = 0 ui.print_carriage( ui.progress_bar(-1) + " Downloading file.") # Download the file in chunks. chunk_size = 124 downloaded = 0 with open(final_file_path, "wb") as f: for chunk in file_request.iter_content(124): if size != 0: ui.print_carriage( ui.progress_bar(downloaded / size) + " Downloading file.") downloaded += chunk_size f.write(chunk) # If the server got particularly angry at us... if (file_request.status_code == 500 or ("X-CallSuccess" in file_request.headers and file_request.headers["X-CallSuccess"] == "False")): logger.critical( "500 response. The server encountered an error.") sys.exit(1) if file_request.status_code == requests.codes.ok: break # Make sure that the trying prompt appears for at least a moment or # so time.sleep(0.5) period = 0.1 wait_for = 4 for i in xrange(int(wait_for / period)): ui.print_carriage( next(bar) + " Download not ready yet. Waiting.") time.sleep(period) print "File saved to %s." % utils.shorten_path(final_file_path)