def hunt_unseen(self, ants, a_row, a_col, destinations, hunted, orders): getLogger().debug("Start Finding Unseen") closest_unseen = ants.closest_unseen(a_row, a_col, hunted) getLogger().debug("Done Finding Unseen") if closest_unseen != None: return self.do_order(ants, UNSEEN, (a_row, a_col), closest_unseen, destinations, hunted, orders)
def get_direction(self, start, end): opened = Queue() opened.put(start) openedBefore = {} cameFrom = {} destination = False DIRECTIONS = ['n', 'w', 'e', 's'] while (not opened.empty()) and (not destination): current = opened.get() for direction in DIRECTIONS: newLoc = self.destination(current, direction) if (not openedBefore.get(newLoc, False)) and self.passable(newLoc): #Open a node cameFrom[newLoc] = (current, direction) opened.put(newLoc) openedBefore[newLoc] = True #If goal is found if(newLoc == end): destination = newLoc if not destination: getLogger().debug("Path not found") return '#' while cameFrom[destination][0] != start: destination = cameFrom[destination][0] getLogger().debug("Found: " + str(cameFrom[destination][1])) return cameFrom[destination][1]
def __init__(self): """Add our log filter so that botversion and turn number are output correctly""" log_filter = LogFilter() getLogger().addFilter(log_filter) self.visited = [] #keep track of visited row/cols self.standing_orders = [] self.ants_with_food = []
def hunt_food(self, ants, a_row, a_col, destinations, hunted, orders): getLogger().debug("Start Finding Food") closest_food = ants.closest_food(a_row, a_col, hunted) getLogger().debug("Done Finding Food") if closest_food != None: return self.do_order(ants, FOOD, (a_row, a_col), closest_food, destinations, hunted, orders)
def createBattalions(self, soldiers): getLogger().debug("Creating battalion: " + str(soldiers)) soldiersCount = len(soldiers) while soldiersCount > self.battalionSize: self.battalions.append(Battalion(soldiers[0:self.battalionSize - 1])) soldiers = soldiers[self.battalionSize] soldiersCount -= self.battalionSize
def hunt_unseen(self,ants,a_row,a_col,destinations,hunted,orders): getLogger().debug("Start Finding Unseen") closest_unseen = ants.closest_unseen(a_row,a_col,hunted) getLogger().debug("Done Finding Unseen") if closest_unseen!=None: return self.do_order(ants, UNSEEN, (a_row,a_col), closest_unseen, destinations, hunted, orders)
def do_turn(self, ants): global turn_number turn_number = turn_number+1 destinations = [] getLogger().debug("Starting Turn") # continue standing orders orders = [] hunted = [] for order in self.standing_orders: ant_loc, step_loc, dest_loc, order_type = order if ((order_type == HILL and dest_loc in ants.enemy_hills()) or (order_type == FOOD and dest_loc in ants.food()) or (order_type == ANTS and dest_loc in ants.enemy_ants()) or (order_type == UNSEEN and ants.map[dest_loc[0]][dest_loc[1]] == UNSEEN)): self.do_order(ants, order_type, ant_loc, dest_loc, destinations, hunted, orders) origins = [order[0] for order in orders] for a_row, a_col in ants.my_ants(): if (a_row, a_col) not in origins: if not self.hunt_hills(ants, a_row, a_col, destinations, hunted, orders): if not self.hunt_food(ants, a_row, a_col, destinations, hunted, orders): if not self.hunt_ants(ants, a_row, a_col, destinations, hunted, orders): if not self.hunt_unseen(ants, a_row, a_col, destinations, hunted, orders): if not self.random_move(ants, a_row, a_col, destinations, hunted, orders): getLogger().debug("blocked:can't move:%d,%d",a_row,a_col) destinations.append((a_row,a_col)) self.standing_orders = orders for order in self.standing_orders: # move ant location to step destination order[0] = order[1]
def executeMove(self, ants, direction, colony): if direction != '#': newPos = ants.destination(self.position, direction) if (not self.isOccupied(newPos, colony.occupied)) and ants.passable(newPos): ants.issue_order((self.position, direction)) colony.occupied[newPos] = True self.position = newPos return True elif ants.passable(newPos): getLogger().debug("Moved randomly: " + str(newPos) + " is occupied.") directions = ['n', 's','e', 'w'] for direction in directions: newPos = ants.destination(self.position, direction) if (not self.isOccupied(newPos, colony.occupied)) and ants.passable(newPos): ants.issue_order((self.position, direction)) colony.occupied[newPos] = True #colony.occupied[self.position] = False self.position = newPos return True elif self.noob: directions = ['n', 's','e', 'w'] for direction in directions: newPos = ants.destination(self.position, direction) if (not self.isOccupied(newPos, colony.occupied)) and ants.passable(newPos): ants.issue_order((self.position, direction)) colony.occupied[newPos] = True self.position = newPos return True self.noob = False else: getLogger().debug("Failed to execute move: Direction is #") return False
def hunt_ants(self, ants, a_row, a_col, destinations, hunted, orders): getLogger().debug("Start Finding Ant") closest_enemy_ant = ants.closest_enemy_ant(a_row, a_col, hunted) getLogger().debug("Done Finding Ant") if closest_enemy_ant != None: return self.do_order(ants, ANTS, (a_row, a_col), closest_enemy_ant, destinations, hunted, orders)
def hunt_hills(self, ants, a_row, a_col, destinations, hunted, orders): getLogger().debug("Start Finding Ant") closest_enemy_hill = ants.closest_enemy_hill(a_row, a_col) getLogger().debug("Done Finding Ant") if closest_enemy_hill != None: return self.do_order(ants, HILL, (a_row, a_col), closest_enemy_hill, destinations, hunted, orders)
def hunt_home(self,ants,a_row,a_col,destinations,hunted,orders): getLogger().debug("Start Finding Home") closest_home = self.closest_home(a_row,a_col) getLogger().debug("Done Finding Home") if closest_home!=None: if ants.distance(closest_home[0], closest_home[1], a_row, a_coll) <= 2: # Ant has home next turn; Change orders to be random return self.do_order(ants, None, (a_row,a_col), closest_home, destinations, hunted, orders) return self.do_order(ants, HOME, (a_row,a_col), closest_home, destinations, hunted, orders)
def do_turn(self, ants): global turn_number turn_number = turn_number+1 destinations = [] getLogger().debug("Starting Turn") for a_row, a_col in ants.my_ants(): if not self.hunt_food(ants,destinations,a_row,a_col): if not self.hunt_ants(ants,destinations,a_row,a_col): if not self.random_move(ants,destinations,a_row,a_col): if not self.random_move(ants,destinations,a_row,a_col,True): getLogger().debug("blocked:can't move:%d,%d",a_row,a_col) destinations.append((a_row,a_col))
def closest_food(self, row1, col1): #find the closest food from this row/col min_dist = MAX_INT closest_food = None for food in self.food_list: getLogger().debug("Investigating food at:%d,%d", food[0], food[1]) dist = self.distance(row1, col1, food[0], food[1]) getLogger().debug("Investigating food dist:%d", dist) if dist < min_dist: min_dist = dist closest_food = food return closest_food
def hunt_home(self, ants, a_row, a_col, destinations, hunted, orders): getLogger().debug("Start Finding Home") closest_home = self.closest_home(a_row, a_col) getLogger().debug("Done Finding Home") if closest_home != None: if ants.distance(closest_home[0], closest_home[1], a_row, a_coll) <= 2: # Ant has home next turn; Change orders to be random return self.do_order(ants, None, (a_row, a_col), closest_home, destinations, hunted, orders) return self.do_order(ants, HOME, (a_row, a_col), closest_home, destinations, hunted, orders)
def closest_enemy_ant(self, row1, col1): #find the closest enemy ant from this row/col min_dist = MAX_INT closest_ant = None for ant in self.enemy_ants(): getLogger().debug("Investigating ant at:%d,%d", ant[0][0], ant[0][1]) dist = self.distance(row1, col1, ant[0][0], ant[0][1]) getLogger().debug("Investigating ant dist:%d", dist) if dist < min_dist: min_dist = dist closest_ant = ant[0] return closest_ant
def move(self, ants): self.deleteDead(ants) self.newRecruits(ants) getLogger().debug("Moving colony") self.setOccupied() getLogger().debug(str(self.occupied)) #March forward self.moveCollectors(ants) self.moveScouts(ants) self.moveBattalions(ants) self.checkBattalion()
def do_turn(self, ants): global turn_number turn_number = turn_number + 1 destinations = [] getLogger().debug("Starting Turn") for a_row, a_col in ants.my_ants(): if not self.hunt_food(ants, destinations, a_row, a_col): if not self.hunt_ants(ants, destinations, a_row, a_col): if not self.random_move(ants, destinations, a_row, a_col): if not self.random_move(ants, destinations, a_row, a_col, True): getLogger().debug("blocked:can't move:%d,%d", a_row, a_col) destinations.append((a_row, a_col))
def do_order(self, ants, order_type, loc, dest, destinations, hunted, orders): order_type_desc = [ "ant", "hill", "unseen", None, "food", "random", None ] a_row, a_col = loc getLogger().debug("chasing %s:start" % order_type_desc) directions = ants.direction(a_row, a_col, dest[0], dest[1]) getLogger().debug("chasing %s:directions:%s" % (order_type_desc[order_type], "".join(directions))) shuffle(directions) for direction in directions: getLogger().debug("chasing %s:direction:%s" % (order_type_desc[order_type], direction)) (n_row, n_col) = ants.destination(a_row, a_col, direction) if (not (n_row, n_col) in destinations and ants.unoccupied(n_row, n_col)): ants.issue_order((a_row, a_col, direction)) getLogger().debug("issue_order:%s,%d,%d,%s", "chasing %s" % order_type_desc[order_type], a_row, a_col, direction) destinations.append((n_row, n_col)) hunted.append(dest) orders.append([loc, (n_row, n_col), dest, order_type]) return True return False
def get_nearest_unseen(self, start): unseen = {} for row in range(self.rows): for col in range(self.cols): unseen[(row, col)] = True for key in unseen.keys(): if self.visible(key): del unseen[key] opened = Queue() opened.put(start) openedBefore = {} cameFrom = {} destination = False DIRECTIONS = ['n', 'w', 'e', 's'] while (not opened.empty()) and (not destination): current = opened.get() for direction in DIRECTIONS: newLoc = self.destination(current, direction) if (not openedBefore.get(newLoc, False)) and self.passable(newLoc): #Open a node cameFrom[newLoc] = (current, direction) opened.put(newLoc) openedBefore[newLoc] = True #If goal is found if(unseen.get(newLoc, False)): destination = newLoc if not destination: getLogger().debug("Path not found") return [] path = [] target = destination while cameFrom[destination][0] != start: path.insert(0, cameFrom[destination]) destination = cameFrom[destination][0] path.insert(0, cameFrom[destination]) getLogger().debug("Found: " + str(path)) return path
def get_nearest_target(self, start): #Fill in the targets targets = {} for row in range(self.rows): for col in range(self.cols): targets[(row, col)] = True for key in targets.keys(): if self.visible(key): del targets[key] for hill in self.enemy_hills(): targets[hill] = True for ant in self.enemy_ants(): targets[ant] = True opened = Queue() opened.put(start) openedBefore = {} cameFrom = {} destination = False DIRECTIONS = ['n', 'w', 'e', 's'] while (not opened.empty()) and (not destination): current = opened.get() for direction in DIRECTIONS: newLoc = self.destination(current, direction) if (not openedBefore.get(newLoc, False)) and self.passable(newLoc): #Open a node cameFrom[newLoc] = (current, direction) opened.put(newLoc) openedBefore[newLoc] = True #If goal is found if(targets.get(newLoc, False)): destination = newLoc if not destination: getLogger().debug("Target not found") return None return destination
def __init__(self, *args): desc = textwrap.dedent(__doc__) parser = argparse.ArgumentParser( description=desc, formatter_class=argparse.RawDescriptionHelpFormatter, epilog="Copyright (C) 2012-21 Sven Erik Knop/Robert Cowham, Perforce Software Ltd" ) parser.add_argument('-c', '--config', default=CONFIG_FILE, help="Default is " + CONFIG_FILE) parser.add_argument('-n', '--notransfer', action='store_true', help="Validate config file and setup source/target workspaces but don't transfer anything") parser.add_argument('-m', '--maximum', default=None, type=int, help="Maximum number of changes to transfer") parser.add_argument('-r', '--repeat', action='store_true', help="Repeat transfer in a loop - for continuous transfer as background task") parser.add_argument('-s', '--stoponerror', action='store_true', help="Stop on any error even if --repeat has been specified") parser.add_argument('--sample-config', action='store_true', help="Print an example config file and exit") parser.add_argument('--end-datetime', type=valid_datetime_type, default=None, help="Time to stop transfers, format: 'YYYY/MM/DD HH:mm' - useful" " for automation runs during quiet periods e.g. run overnight but stop first thing in the morning") self.options = parser.parse_args(list(args)) self.options.sync_progress_size_interval = None if self.options.sample_config: printSampleConfig() return self.logger = logutils.getLogger(LOGGER_NAME) self.previous_target_change_counter = 0 # Current value
def moveCollectors(self, ants): getLogger().debug("Moving collectors: " + str(len(self.collectors))) toRemove = [] #Get moves from collectors for i in range (0, len(self.collectors)): direction = self.collectors[i].suggestMove(ants, self) if direction == '#': self.scouts.append(ScoutAnt(self.collectors[i].getPosition())) toRemove.append(self.collectors[i]) else: getLogger().debug("Moving collector: " + str(self.collectors[i].getPosition()) + " to " + direction) self.collectors[i].executeMove(ants, direction, self) for i in range(0, len(toRemove)): self.collectors.remove(toRemove[i])
def __init__(self, port): self.port = port self.ident = "Worker:%s" % os.getpid() signal.signal(signal.SIGTERM, self.signal_hander) self.logger = getLogger(self.ident) self.logger.debug("Started") self.run()
def __init__(self): self.ident = "%s-%s" % (self.__class__.__name__, os.getpid()) signal.signal(signal.SIGTERM, self.signal_hander) self.logger = getLogger(self.ident) self.logger.debug("Started") self.child_procs = [] self.mainloop()
def suggestMove(self, ants, colony): if(len(self.path) == 0): self.path = ants.get_nearest_unseen(self.position) self.index = 0 if(len(self.path) != 0 and self.path[self.index][0] != self.getPosition()): getLogger().debug("Reset" + str(self.getPosition()) + ", " + str(self.path[self.index][0])) self.path = ants.get_nearest_unseen(self.position) self.index = 0 if(len(self.path) != 0): direction = self.path[self.index][1] self.index = self.index + 1 if(self.index == len(self.path)): self.path = [] self.target = None return direction return '#'
def suggestMove(self, ants, colony): if(len(self.path) == 0): targets = [colony.collectors[i].target for i in range(0, len(colony.collectors))] (self.path, self.target) = ants.get_nearest_food(self.position, targets) self.index = 0 if(len(self.path) != 0 and self.path[self.index][0] != self.getPosition()): getLogger().debug("Reset" + str(self.getPosition()) + ", " + str(self.path[self.index][0])) targets = [colony.collectors[i].target for i in range(0, len(colony.collectors))] (self.path, self.target) = ants.get_nearest_food(self.position, targets) self.index = 0 if(len(self.path) != 0): direction = self.path[self.index][1] self.index = self.index + 1 if(self.index == len(self.path)): self.path = [] self.target = None return direction else: return '#'
def moveScouts(self, ants): getLogger().debug("Moving scouts: " + str(len(self.scouts))) toRemove = [] food = ants.food() targetedFood = [self.collectors[i].target for i in range(0, len(self.collectors))] foodNotTargeted = len(food) - len(targetedFood) #Get moves from scouts for i in range (0, len(self.scouts)): direction = self.scouts[i].suggestMove(ants, self) if foodNotTargeted > 5: self.collectors.append(CollectorAnt(self.scouts[i].getPosition())) self.collectors.append toRemove.append(self.scouts[i]) foodNotTargeted = foodNotTargeted - 1 else: getLogger().debug("Moving scout: " + str(self.scouts[i].getPosition()) + " to " + direction) self.scouts[i].executeMove(ants, direction, self) for i in range(0, len(toRemove)): self.scouts.remove(toRemove[i])
def do_setup(self, ants): """Add our log filter so that botversion and turn number are output correctly""" log_filter = LogFilter() getLogger().addFilter(log_filter) self.hills = [] self.directions = [] self.seen = [] #areas that have been seen, use this to avoid repetition self.unseen = [] self.stepped_on = [] self.intent = {} self.lc = {} #center of mass for a location self.i = {} #number of iterations for an ant for row in range(ants.rows): for col in range(ants.cols): self.unseen.append((row, col)) self.intent[(row,col)] = Intent.GATHER self.lc[(row,col)] = (-1.0,-1.0) #set up center of mass self.i[(row,col)] = -1
def random_move(self,ants,a_row,a_col,destinations,hunted,orders): #if we didn't move as there was no food try a random move directions = list(AIM.keys()) getLogger().debug("random move:directions:%s","".join(directions)) shuffle(directions) getLogger().debug("random move:shuffled directions:%s","".join(directions)) for direction in directions: getLogger().debug("random move:direction:%s",direction) (n_row, n_col) = ants.destination(a_row, a_col, direction) if (not (n_row, n_col) in destinations and ants.unoccupied(n_row, n_col)): return self.do_order(ants, LAND, (a_row,a_col), (n_row, n_col), destinations, hunted, orders)
def do_order(self, ants, order_type, loc, dest, destinations, hunted, orders): order_type_desc = ["ant", "hill", "unseen", None, "food", "random", None] a_row, a_col = loc getLogger().debug("chasing %s:start" % order_type_desc) directions = ants.direction(a_row,a_col,dest[0],dest[1]) getLogger().debug("chasing %s:directions:%s" % (order_type_desc[order_type],"".join(directions))) shuffle(directions) for direction in directions: getLogger().debug("chasing %s:direction:%s" % (order_type_desc[order_type],direction)) (n_row,n_col) = ants.destination(a_row,a_col,direction) if (not (n_row,n_col) in destinations and ants.unoccupied(n_row,n_col)): ants.issue_order((a_row,a_col,direction)) getLogger().debug("issue_order:%s,%d,%d,%s","chasing %s" % order_type_desc[order_type],a_row,a_col,direction) destinations.append((n_row,n_col)) hunted.append(dest) orders.append([loc, (n_row,n_col), dest, order_type]) return True return False
def random_move(self,ants,destinations,a_row,a_col,do_visited=False): #if we didn't move as there was no food try a random move moved=False directions = AIM.keys() getLogger().debug("random move:directions:%s","".join(directions)) shuffle(directions) getLogger().debug("random move:shuffled directions:%s","".join(directions)) for direction in directions: getLogger().debug("random move:direction:%s",direction) (n_row, n_col) = ants.destination(a_row, a_col, direction) if (not (n_row, n_col) in destinations and ants.unoccupied(n_row, n_col)): if (n_row,n_col) not in self.visited or (do_visited and (n_row,n_col) in self.visited): moved=True ants.issue_order((a_row, a_col, direction)) getLogger().debug("issue_order:%s,%d,%d,%s","random move",a_row,a_col,direction) destinations.append((n_row, n_col)) break else: continue return moved
def get_nearest_food(self, start, filters): foods = self.food() for food in foods: if food in filters: foods.remove(food) if(len(foods) == 0): return ([], None) opened = Queue() opened.put(start) openedBefore = {} cameFrom = {} destination = False DIRECTIONS = ['n', 'w', 'e', 's'] getLogger().debug(str(filters)) while (not opened.empty()) and (not destination): current = opened.get() for direction in DIRECTIONS: newLoc = self.destination(current, direction) if (not openedBefore.get(newLoc, False)) and self.passable(newLoc): #Open a node cameFrom[newLoc] = (current, direction) opened.put(newLoc) openedBefore[newLoc] = True #If goal is found if(self.map[newLoc[0]][newLoc[1]] == FOOD and not(self.map[newLoc[0]][newLoc[1]] in filters)): destination = newLoc if not destination: getLogger().debug("Path not found") return ([], None) path = [] target = destination while cameFrom[destination][0] != start: path.insert(0, cameFrom[destination]) destination = cameFrom[destination][0] path.insert(0, cameFrom[destination]) getLogger().debug("Found: " + str(path)) return (path, target)
def random_move(self, ants, destinations, a_row, a_col, do_visited=False): #if we didn't move as there was no food try a random move moved = False directions = AIM.keys() getLogger().debug("random move:directions:%s", "".join(directions)) shuffle(directions) getLogger().debug("random move:shuffled directions:%s", "".join(directions)) for direction in directions: getLogger().debug("random move:direction:%s", direction) (n_row, n_col) = ants.destination(a_row, a_col, direction) if (not (n_row, n_col) in destinations and ants.unoccupied(n_row, n_col)): if (n_row, n_col) not in self.visited or ( do_visited and (n_row, n_col) in self.visited): moved = True ants.issue_order((a_row, a_col, direction)) getLogger().debug("issue_order:%s,%d,%d,%s", "random move", a_row, a_col, direction) destinations.append((n_row, n_col)) break else: continue return moved
def moveBattalions(self, ants): getLogger().debug("Moving battalions: " + str(len(self.battalions))) toRemove = [] #Get moves from battalions for battalion in self.battalions: alive = battalion.updateTarget(ants) if alive: getLogger().debug("Moving battalion: " + str(battalion.target)) target = battalion.target for soldier in battalion.soldiers: direction = soldier.suggestMove(ants, target) getLogger().debug("Moving soldier: " + str(soldier.getPosition()) + " to " + direction) soldier.executeMove(ants, direction, self) else: toRemove.append(battalion) for battalion in toRemove: self.battalions.remove(battalion)
def hunt_ants(self,ants,a_row,a_col,destinations,hunted,orders): getLogger().debug("Start Finding Ant") closest_enemy_ant = ants.closest_enemy_ant(a_row,a_col,hunted) getLogger().debug("Done Finding Ant") if closest_enemy_ant!=None: return self.do_order(ants, ANTS, (a_row,a_col), closest_enemy_ant, destinations, hunted, orders)
def hunt_food(self, ants, destinations, a_row, a_col): getLogger().debug("Start Finding Food") closest_food = ants.closest_food(a_row, a_col) getLogger().debug("Done Finding Food") moved = False if closest_food != None: getLogger().debug("chasing food:start") directions = ants.direction(a_row, a_col, closest_food[0], closest_food[1]) getLogger().debug("chasing food:directions:%s", "".join(directions)) shuffle(directions) for direction in directions: getLogger().debug("chasing food:direction:%s", direction) (n_row, n_col) = ants.destination(a_row, a_col, direction) if (not (n_row, n_col) in destinations and ants.unoccupied(n_row, n_col)): moved = True ants.issue_order((a_row, a_col, direction)) getLogger().debug("issue_order:%s,%d,%d,%s", "chasing food", a_row, a_col, direction) destinations.append((n_row, n_col)) break return moved
os.remove('C:\Users\Amy\Documents\aichallenge\ants.log') logging.basicConfig(filename='ants.log', level=logging.DEBUG) import sys from optparse import OptionParser from logutils import initLogging,getLogger # define a class with a do_turn method # the Ants.run method will parse and update bot input # it will also run the do_turn method for us turn_number = 0 bot_version = 'v0.1' getLogger().debug("------") class LogFilter(logging.Filter): """ This is a filter that injects stuff like TurnNumber into the log """ def filter(self,record): global turn_number,bot_version record.turn_number = turn_number record.version = bot_version return True class MyBot: def __init__(self): # define class level variables, will be remembered between turns
def checkBattalion(self): getLogger().debug("Checking Battalions") pass
def newRecruits(self, ants): recruits = [] for ant in ants.my_ants(): if not self.isRegistered(ant): getLogger().debug("Found an ant: " + str(ant)) self.collectors.append(CollectorAnt(ant))
import os import pprint import re import shutil import tempfile import threading import requests import logutils logger = logutils.getLogger('fetch') shutdown_event = threading.Event() def get_target_path(url): """Wget's algorithm""" target_path = os.path.basename(url) or 'index.html' while os.path.exists(target_path): try: root, seq = re.findall('^(.*)\.([0-9]+)$', target_path)[0] seq = int(seq) except IndexError: root = target_path seq = 0 seq += 1 target_path = '%s.%s' % (root, seq) return target_path class Request(object):
def do_turn(self, ants): global turn_number turn_number = turn_number+1 getLogger().debug(" ------ Starting Turn %d",turn_number) # track all moves, prevent collisions orders = {} for ant_loc in ants.my_ants(): if self.lc[ant_loc] == (-1.0,-1.0): self.lc[ant_loc] = ant_loc #set up center of mass if self.i[ant_loc] == -1: self.i[ant_loc] = 0 def do_move_direction(loc, direction): if loc not in self.stepped_on: self.stepped_on.append(loc) ## new_loc = ants.destination(loc, direction) row, col = loc ## new_row, new_col = new_loc dlist = ['n','s','w','e'] dlist.remove(direction) dlist.insert(0, direction) #direction you were trying to go to is first priority for d in dlist[:]: if not ants.passable(ants.destination(loc, d)): dlist.remove(d) if len(dlist) == 0: dlist.append(ants.randlist(['n','s','w','e'])) tempdir = dlist[0] #default direction to try for ant_loc in ants.my_ants(): row_1, col_1 = ant_loc getLogger().debug("Focusing on ant [%d,%d]",row_1, col_1) if (self.intent[ant_loc] != Intent.EXPLORE): break rib, cib = self.lc[ant_loc] #note: distinction between ci-bar and ci di_1 = float (abs(row_1 - rib) + abs(col_1 - cib)) #di at i-1 for d in dlist: row, col = ants.destination(ant_loc, d) #test all four directions if self.i[ant_loc] < 0: rib = row_1 cib = col_1 if self.i[ant_loc] > 0: new_rib = float(((self.i[ant_loc])*rib + 10*row)/(self.i[ant_loc] + 10)) new_cib = float(((self.i[ant_loc])*cib + 10*col)/(self.i[ant_loc] + 10)) #update the ci's and ri's else: new_rib = row new_cib = col di = float(abs(row - new_rib) + abs(col - new_cib)) #di at i getLogger().debug("d %s, self.i %d, row_1 %d, row %d, rib %2f, new_rib %.2f", d, self.i[ant_loc], row_1, row, rib, new_rib) getLogger().debug("d %s, self.i %d, col_1 %d, col %d, cib %2f, new_cib %2f, di %2f, di_1 %2f", d, self.i[ant_loc], col_1, col, cib, new_cib, di, di_1) tempdir = d #TODO: double check all this if di >= di_1 - 0.1: # if this is true, go this way! tempdir = d #TODO: double check all this break else: tempdir = ants.randlist(dlist) self.directions.append(tempdir) new_loc = ants.destination(loc, tempdir) if (self.intent[ant_loc] == Intent.EXPLORE): self.lc[new_loc] = new_rib, new_cib self.i[new_loc] = self.i[ant_loc] + 1 self.lc[ant_loc] = (-1.0, -1.0) self.i[ant_loc] = -1 getLogger().debug("Trying to move in %s",direction) getLogger().debug("Actually moving in %s",tempdir) self.intent[ant_loc] = Intent.GATHER if ants.unoccupied(new_loc) and new_loc not in orders: ants.issue_order((loc, tempdir)) #only move if no one else is there orders[new_loc] = loc return True else: return False targets = {} def do_move_location(loc, dest): #move ants from here to there directions = ants.find_path(loc, dest, self.intent[loc], self.stepped_on, ants.my_hills()) for direction in directions: if do_move_direction(loc, direction): targets[dest] = loc return True return False def move_around(loc, dest): #get ants to cluster around #getting an "is not iterable" error possibles = [] row, col = dest possibles.append((row+2,col)) possibles.append((row-2,col)) possibles.append((row,col+2)) possibles.append((row,col-2)) ri = random.randint(0,3) do_move_location(loc,possibles[ri]) # prevent stepping on own hill for hill_loc in ants.my_hills(): orders[hill_loc] = None # find close food for ant_loc in ants.my_ants(): if self.intent[ant_loc] == Intent.DEFEND: for hill_loc in ants.my_hills(): c,r = ant_loc getLogger().debug("Defending Hill with %d,%d",c,r) move_around(ant_loc,hill_loc) ant_dist = [] for food_loc in ants.food(): for ant_loc in ants.my_ants(): dist = ants.distance(ant_loc, food_loc) ant_dist.append((dist, ant_loc, food_loc)) ant_dist.sort() #perform actions for the shortest distances first for dist, ant_loc, food_loc in ant_dist: if food_loc not in targets and ant_loc not in targets.values(): #only retrieve food if no other ant is gathering it #and if the given ant is not doing anything else self.intent[ant_loc] = Intent.GATHER do_move_location(ant_loc, food_loc) # attack hills for hill_loc, hill_owner in ants.enemy_hills(): if hill_loc not in self.hills: self.hills.append(hill_loc) ant_dist = [] for hill_loc in self.hills: for ant_loc in ants.my_ants(): if ant_loc not in orders.values(): dist = ants.distance(ant_loc, hill_loc) ant_dist.append((dist, ant_loc, hill_loc)) ant_dist.sort() for dist, ant_loc, hill_loc in ant_dist: self.intent[ant_loc] = Intent.CONQUER do_move_location(ant_loc, hill_loc) for loc in self.unseen[:]: if ants.visible(loc): self.seen.append(loc) self.unseen.remove(loc) for ant_loc in ants.my_ants(): if ant_loc not in orders.values(): unseen_dist = [] for unseen_loc in self.unseen: dist = ants.distance(ant_loc, unseen_loc) unseen_dist.append((dist, unseen_loc)) unseen_dist.sort() self.intent[ant_loc] = Intent.EXPLORE for dist, unseen_loc in unseen_dist: if do_move_location(ant_loc, unseen_loc): break # unblock own hill for hill_loc in ants.my_hills(): if hill_loc in ants.my_ants() and hill_loc not in orders.values(): #try to get off the hill in any of the four directions by trying all possibilities for direction in ('s','e','w','n'): if do_move_direction(hill_loc, direction): break
import os import pprint import re import shutil import tempfile import threading import requests import logutils logger = logutils.getLogger('fetch') shutdown_event = threading.Event() def get_target_path(url): """Wget's algorithm""" target_path = os.path.basename(url) or 'index.html' while os.path.exists(target_path): try: root, seq = re.findall('^(.*)\.([0-9]+)$', target_path)[0] seq = int(seq) except IndexError: root = target_path seq = 0 seq += 1 target_path = '%s.%s' % (root, seq) return target_path class Request(object): def __init__(self, fetcher, url, chunk_size=10240, keep_file=False):
def do_move_direction(loc, direction): if loc not in self.stepped_on: self.stepped_on.append(loc) ## new_loc = ants.destination(loc, direction) row, col = loc ## new_row, new_col = new_loc dlist = ['n','s','w','e'] dlist.remove(direction) dlist.insert(0, direction) #direction you were trying to go to is first priority for d in dlist[:]: if not ants.passable(ants.destination(loc, d)): dlist.remove(d) if len(dlist) == 0: dlist.append(ants.randlist(['n','s','w','e'])) tempdir = dlist[0] #default direction to try for ant_loc in ants.my_ants(): row_1, col_1 = ant_loc getLogger().debug("Focusing on ant [%d,%d]",row_1, col_1) if (self.intent[ant_loc] != Intent.EXPLORE): break rib, cib = self.lc[ant_loc] #note: distinction between ci-bar and ci di_1 = float (abs(row_1 - rib) + abs(col_1 - cib)) #di at i-1 for d in dlist: row, col = ants.destination(ant_loc, d) #test all four directions if self.i[ant_loc] < 0: rib = row_1 cib = col_1 if self.i[ant_loc] > 0: new_rib = float(((self.i[ant_loc])*rib + 10*row)/(self.i[ant_loc] + 10)) new_cib = float(((self.i[ant_loc])*cib + 10*col)/(self.i[ant_loc] + 10)) #update the ci's and ri's else: new_rib = row new_cib = col di = float(abs(row - new_rib) + abs(col - new_cib)) #di at i getLogger().debug("d %s, self.i %d, row_1 %d, row %d, rib %2f, new_rib %.2f", d, self.i[ant_loc], row_1, row, rib, new_rib) getLogger().debug("d %s, self.i %d, col_1 %d, col %d, cib %2f, new_cib %2f, di %2f, di_1 %2f", d, self.i[ant_loc], col_1, col, cib, new_cib, di, di_1) tempdir = d #TODO: double check all this if di >= di_1 - 0.1: # if this is true, go this way! tempdir = d #TODO: double check all this break else: tempdir = ants.randlist(dlist) self.directions.append(tempdir) new_loc = ants.destination(loc, tempdir) if (self.intent[ant_loc] == Intent.EXPLORE): self.lc[new_loc] = new_rib, new_cib self.i[new_loc] = self.i[ant_loc] + 1 self.lc[ant_loc] = (-1.0, -1.0) self.i[ant_loc] = -1 getLogger().debug("Trying to move in %s",direction) getLogger().debug("Actually moving in %s",tempdir) self.intent[ant_loc] = Intent.GATHER if ants.unoccupied(new_loc) and new_loc not in orders: ants.issue_order((loc, tempdir)) #only move if no one else is there orders[new_loc] = loc return True else: return False
# coding: utf-8 import os import socket import ftplib from tools import getConf from logutils import getLogger logger = getLogger("ftp") con = Canon('xxxx.xxxx.xxxx.xxxx', 21, 'ubuntu', '...................') class Canon(): ''' Controls the amount of debugging output printed 0 - produces no debugging output 1 - produces a moderate amount of debugging output 2+ - produces the maximum amount of debugging output ''' debuglevel = 2 timeout = 30 appConf = getConf() def __init__(self, host, port, username, password): print host,port,username,password self.host = host self.port = port self.username = username self.password = password self.f = None
def hunt_food(self,ants,a_row,a_col,destinations,hunted,orders): getLogger().debug("Start Finding Food") closest_food = ants.closest_food(a_row,a_col,hunted) getLogger().debug("Done Finding Food") if closest_food!=None: return self.do_order(ants, FOOD, (a_row,a_col), closest_food, destinations, hunted, orders)
def hunt_food(self, ants, a_row, a_col, destinations, hunted, orders): getLogger().debug("Start Finding Food") closest_food = ants.closest_food(a_row, a_col, hunted) getLogger().debug("Done Finding Food") if closest_food != None: getLogger().debug("Found Food!") getLogger().debug( '%s' % ants.distance(closest_food[0], closest_food[1], a_row, a_col)) if ants.distance(closest_food[0], closest_food[1], a_row, a_col) <= 2: getLogger().debug("Found Food!") return self.do_order(ants, HOME, (a_row, a_col), closest_food, destinations, hunted, orders) # Ant now has food; Change orders to go back to nearest hill getLogger().debug("Ordering Finding Food") return self.do_order(ants, FOOD, (a_row, a_col), closest_food, destinations, hunted, orders)
def hunt_hills(self,ants,a_row,a_col,destinations,hunted,orders): getLogger().debug("Start Finding Ant") closest_enemy_hill = ants.closest_enemy_hill(a_row,a_col) getLogger().debug("Done Finding Ant") if closest_enemy_hill!=None: return self.do_order(ants, HILL, (a_row,a_col), closest_enemy_hill, destinations, hunted, orders)
def hunt_food(self,ants,destinations,a_row,a_col): getLogger().debug("Start Finding Food") closest_food = ants.closest_food(a_row,a_col) getLogger().debug("Done Finding Food") moved =False if closest_food!=None: getLogger().debug("chasing food:start") directions = ants.direction(a_row,a_col,closest_food[0],closest_food[1]) getLogger().debug("chasing food:directions:%s","".join(directions)) shuffle(directions) for direction in directions: getLogger().debug("chasing food:direction:%s",direction) (n_row,n_col) = ants.destination(a_row,a_col,direction) if (not (n_row,n_col) in destinations and ants.unoccupied(n_row,n_col)): moved=True ants.issue_order((a_row,a_col,direction)) getLogger().debug("issue_order:%s,%d,%d,%s","chasing food",a_row,a_col,direction) destinations.append((n_row,n_col)) break return moved
# Description: minicap setup scripts, # Usage: python minicap_setup.py -s serialno -H host -P port # Author: ydbn2153 # Created: ydbn2153 <2016-03-15> # Modified: hzsunshx <2016-03-19> import argparse import functools import os import subprocess import sys import tempfile import logutils logger = logutils.getLogger('minicap') def log(*args): logger.info(*args) def check_output(cmdstr, shell=True): output = subprocess.check_output(cmdstr, stderr=subprocess.STDOUT, shell=shell) return output def run_adb(*args, **kwargs): cmds = ['adb']
#!/usr/bin/env python import os import re import sys import urlparse from bs4 import BeautifulSoup from models import app from models import db from models import QueuedUrl from models import Url import logutils logger = logutils.getLogger('crawl') class Crawler(object): def __init__(self, host): self.host = host self.enqueue_new(None, dict(url=self.host, level=0, context='anchor')) def urljoin(self, url, path): url_new = path if path: if not path.startswith('http'): url_new = urlparse.urljoin(url, path) url_new = re.sub('#.*$', '', url_new) # remove fragment url_new = re.sub('[.]{2}\/', '', url_new) return url_new
#!/usr/bin/env python # coding: utf-8 import os import threading import logging import tkinter as tk from queue import Queue import logutils from layoututils import dump_nodes import uiautomator2 as u2 from PIL import Image, ImageTk import io log = logutils.getLogger('tkgui') log.setLevel(logging.DEBUG) class CropIDE(object): def __init__(self, title='AirtestX Basic GUI', ratio=0.5, picture=Queue): self._picture = picture self._root = tk.Tk() self._root.title(title) self._queue = Queue() self._ratio = ratio self._image = Image.open(r'/home/cts/PycharmProjects/SmartRecord2.0/screen.png') self._size = (90, 90) self._tkimage = None self._uinodes = None self._poffset = (0, 0) self._color = 'red'
def do_turn(self, ants): destinations = [] new_straight = {} new_lefty = {} new_food = {} new_hunter = {} new_hill = {} new_unseen = {} for a_row, a_col in ants.my_ants(): if self.time_remaining(ants) < 50: break # send new ants toward closest goal cur_ant = (a_row, a_col) if (not cur_ant in self.ants_straight and not cur_ant in self.ants_lefty and not cur_ant in self.food_ants): closest_home = ants.closest_home(cur_ant[0], cur_ant[1]) if cur_ant in self.has_food and closest_home: # If ant has food, and there's a closest home, just go there direction = ants.direction(cur_ant[0], cur_ant[1], closest_home[0], closest_home[1]) ants.issue_order((a_row, a_col, direction[0])) closest_food = ants.closest_food(cur_ant[0], cur_ant[1]) closest_enemy_hill = ants.closest_enemy_hill(cur_ant[0], cur_ant[1]) closest_unseen = ants.closest_unseen(cur_ant[0], cur_ant[1]) distance_food = 9999999 if closest_food: distance_food = ants.distance(cur_ant[0], cur_ant[1], closest_food[0], closest_food[1]) getLogger().debug("Found food at distance %s" % distance_food) distance_hill = 9999999 if closest_enemy_hill: distance_hill = ants.distance(cur_ant[0], cur_ant[1], closest_enemy_hill[0], closest_enemy_hill[1]) getLogger().debug("Found hill at distance %s" % distance_food) distance_unseen = 9999999 if closest_unseen: distance_unseen = ants.distance(cur_ant[0], cur_ant[1], closest_unseen[0], closest_unseen[1]) getLogger().debug("Found unseen at distance %s" % closest_unseen) if closest_food or closest_enemy_hill or closest_unseen: minimum = min(distance_food, distance_hill, distance_unseen) if minimum == distance_food: getLogger().debug("Going toward food") direction = ants.direction(cur_ant[0], cur_ant[1], closest_food[0], closest_food[1]) new_food[cur_ant] = direction[0] elif minimum == distance_hill: getLogger().debug("Going toward hill") direction = ants.direction(cur_ant[0], cur_ant[1], closest_enemy_hill[0], closest_enemy_hill[1]) new_hill[cur_ant] = direction[0] elif minimum == distance_unseen: getLogger().debug("Going toward unseen") direction = ants.direction(cur_ant[0], cur_ant[1], closest_unseen[0], closest_unseen[1]) new_unseen[cur_ant] = direction[0] ants.issue_order((a_row, a_col, direction[0])) else: if a_row % 2 == 0: if a_col % 2 == 0: direction = 'n' else: direction = 's' else: if a_col % 2 == 0: direction = 'e' else: direction = 'w' self.ants_straight[(a_row, a_col)] = direction # send ants going in a straight line in the same direction if (cur_ant in self.ants_straight) or (cur_ant in self.food_ants): direction = self.ants_straight.get((a_row, a_col)) if not direction: direction = self.food_ants.get((a_row, a_col)) getLogger().debug("Direction is %s" % direction) n_row, n_col = ants.destination(a_row, a_col, direction) if ants.passable(n_row, n_col): if (ants.unoccupied(n_row, n_col) and not (n_row, n_col) in destinations): ants.issue_order((a_row, a_col, direction)) new_straight[(n_row, n_col)] = direction destinations.append((n_row, n_col)) else: # pause ant, turn and try again next turn new_straight[(a_row, a_col)] = LEFT[direction] destinations.append((a_row, a_col)) else: # hit a wall, start following it self.ants_lefty[(a_row, a_col)] = RIGHT[direction] # send ants following a wall, keeping it on their left if (a_row, a_col) in self.ants_lefty: direction = self.ants_lefty[(a_row, a_col)] directions = [LEFT[direction], direction, RIGHT[direction], BEHIND[direction]] # try 4 directions in order, attempting to turn left at corners for new_direction in directions: n_row, n_col = ants.destination(a_row, a_col, new_direction) if ants.passable(n_row, n_col): if (ants.unoccupied(n_row, n_col) and not (n_row, n_col) in destinations): ants.issue_order((a_row, a_col, new_direction)) new_lefty[(n_row, n_col)] = new_direction destinations.append((n_row, n_col)) break else: # have ant wait until it is clear new_straight[(a_row, a_col)] = RIGHT[direction] destinations.append((a_row, a_col)) break # reset lists self.ants_straight = new_straight self.ants_lefty = new_lefty self.food_ants = new_food self.razer_ants = new_hunter