def choose_action(self): if self.lastAction.value + 1 == len(self.actions): index = 0 else: index = self.lastAction.value + 1 self.lastAction = actions.Action(index) return actions.Action(index)
def actions(self): return [ actions.Action("Stop", "stop", self.spotify.stop), actions.Action("Pause", "pause", self.spotify.playpause), actions.Action("Next", "next", self.spotify.next), actions.Action("Previous", "previous", self.spotify.previous) ]
def _simple_actions(self): return [ actions.Action("Stop", "stop", self.client.stop), actions.Action("Pause", "pause", self.client.pause), actions.Action("Next", "next", self.client.next), actions.Action("Previous", "previous", self.client.previous), ]
def choose_action(self): if tuple(self.husk_sequence) in self.counts: next_action = actions.Action( max(self.counts[tuple(self.husk_sequence)], key=lambda key: self.counts[tuple(self.husk_sequence)][key] )) return actions.Action(next_action.who_beats_me()) else: return actions.Action(random.randint(0, 2))
def setUpHierarchy(browser="*chrome", path="", ipaddr="localhost", ipport=4444, webURL="http://127.0.0.1:8000/"): """ This method would typically only be run once it will create a Selenium instance and then start it. This is a static method with the idea that the properties created in this method are shared amongst all subclasses. That is: SahanaTest.selenium and SahanaTest.action """ if (SahanaTest.ipaddr != ipaddr) or (SahanaTest.ipport != ipport) or ( SahanaTest.browser != browser) or (SahanaTest.webURL != webURL): SahanaTest._seleniumCreated = False # Only run once if not SahanaTest._seleniumCreated: if browser == "*custom": browser += " %s" % path print "selenium %s %s %s %s" % (ipaddr, ipport, browser, webURL) SahanaTest.ipaddr = ipaddr SahanaTest.ipport = ipport SahanaTest.browser = browser SahanaTest.webURL = webURL SahanaTest.selenium = selenium(ipaddr, ipport, browser, webURL) SahanaTest.action = actions.Action(SahanaTest.selenium) SahanaTest._seleniumCreated = True if SahanaTest.selenium.sessionId == None: SahanaTest.selenium.start()
def test_get_relative_frame(): task = actions.Action(Actor('A'), 5, 10) assert task.get_relative_frame(5) == 1 assert task.get_relative_frame(6) == 2 assert task.get_relative_frame(7) == 3 assert task.get_relative_frame(8) == 4 assert task.get_relative_frame(9) == 5 assert task.get_relative_frame(10) == 6
def test_last_frame(): task = actions.Action(Actor('A'), 5, 10) with pytest.raises(ValueError): task.is_last(4) assert not task.is_last(5) assert not task.is_last(6) assert not task.is_last(7) assert not task.is_last(8) assert not task.is_last(9) assert task.is_last(10) with pytest.raises(ValueError): task.is_last(11)
def test_matching_containers_by_env(self): test_containers = [ self.start_container(environment=['PYGEN_TARGET=pygen-action-by-env']), self.start_container(environment=['PYGEN_TARGET=pygen-action-by-env']), self.start_container(environment=['PYGEN_TARGET=pygen-action-by-env']) ] action = actions.Action(self.api) containers = list(action.matching_containers('pygen-action-by-env')) self.assertEqual(len(containers), 3) for container in containers: self.assertIn(container.id, (c.id for c in test_containers))
def test_matching_containers(self): test_container = self.start_container(labels={'pygen.target': 'pygen-action-target'}) action = actions.Action(self.api) containers = list(action.matching_containers('pygen-action-target')) self.assertEqual(len(containers), 1) self.assertEqual(containers[0].id, test_container.id) container_ids = list(c.id for c in containers) six.assertCountEqual(self, list(c.id for c in action.matching_containers(test_container.id)), container_ids) six.assertCountEqual(self, list(c.id for c in action.matching_containers(test_container.short_id)), container_ids) six.assertCountEqual(self, list(c.id for c in action.matching_containers(test_container.name)), container_ids)
def __init__(self, filepath): self.processors = {} self.basedir, self.filename = path.split(filepath) if self.basedir not in sys.path: sys.path.append(self.basedir) with open(filepath) as fi: self.cfg = yaml.load(fi.read()) if 'result' in self.cfg: self.result = self.loadfunc(self.cfg['result'], None) if 'disable_robots' not in self.cfg: self.accessible = httputils.accessible else: self.accessible = lambda url: True if 'interval' in self.cfg: self.limit = httputils.SpeedLimit(self.cfg['interval']) self.http = httputils.HttpHub(self.cfg) for proccfg in self.cfg['patterns']: assert 'name' in proccfg, 'without name' self.processors[proccfg['name']] = actions.Action(self, proccfg) del self.cfg['patterns']
def test_matching_compose_container(self): composefile = """ version: '2' services: actiontest: image: {image} command: "sleep 300" """.format(image=os.environ.get('TEST_IMAGE', 'alpine')) project = self.start_compose_project('pygen-actions', 'compose', 'action.yml', composefile) action = actions.Action(self.api) containers = list(action.matching_containers('actiontest')) self.assertEqual(len(containers), 1) project.get_service('actiontest').scale(3) containers = list(action.matching_containers('actiontest')) self.assertEqual(len(containers), 3)
def test_uso(): sch = Scheduler() bob = Square('Bob') task = actions.Action(bob, 5, 10) sch.add_action(task) assert (task.actor.name, 5) in sch.actions
def test_action_inverval(): task = actions.Action(Actor('A'), 5, 10) assert task.lower_bound == 5 assert task.upper_bound == 10 assert task.num_steps == 5
def choose_action(self): action = actions.Action( max(self.counts, key=lambda key: self.counts[key])) return actions.Action(action.who_beats_me())
def actions(self): return [actions.Action("Poweroff", "poweroff", self._poweroff)]
def __init__(self): self.lastAction = actions.Action(0) super().__init__()
def choose_action(self): return actions.Action(random.randint(0, 2))
#!/usr/bin/python3 """ Module defined for testing multiple aspects from Puppy modules. """ import actions import users import unittest action = actions.Action() user = users.User() class Probe(unittest.TestCase): """ Probing functionalities from Puppy. """ # User() class test def test_1_user_create(self): """ Testing user ceation. """ self.assertEqual(user.create("Captain Nemo", "nemo", "nemo2000"), 0) def test_2_user_login(self): """ Testing user login. """ self.assertEqual(user.login("nemo", "nemo2000"), 0) def test_3_user_remove(self): """ Testing user removal. """ self.assertEqual(user.remove("nemo"), 0) # Action() class test def test_4_action_create(self): """ Testing action creation. """ self.assertEqual(action.create("Create File", "touch /tmp/file"), 0)
def main(argv): try: opts, args = getopt.getopt(argv, "d:i:o:t:f:ha:v:", [ "download=", "tle=", "noconfirm", "output=", "write-trajectories", "time=", "frequency=", "help", "trajectory=", "view=" ]) except getopt.GetoptError as E: print("ERROR: {}\n".format(E)) usage() sys.exit(2) if len(args) != 0: print("Too many arguments.") sys.exit(1) # List of all the actions needed acts = [] context = Context() for opt, arg in opts: if opt in ("-d", "--download"): acts.append(actions.Action("Download TLE coordinates", 0, actions.downloadTLE)) context.id_file = arg elif opt in ("-i", "--tle"): context.tle_file = arg elif opt in ("--noconfirm"): context.confirm = False elif opt in ("-t", "--time"): context.time, valid = get_time(arg, opt) if not valid: sys.exit(1) elif opt in ("-o", "--output"): context.output_file = arg elif opt == "--write-trajectories": context.write_trajectories = True elif opt in ("-f", "--frequency"): try: context.frequency = float(arg) except ValueError: print("{} argument must be a real number.".format(opt)) sys.exit(1) print(f"Frequency set to {context.frequency/1e6} MHz") elif opt in ("-h", "--help"): usage() sys.exit(0) elif opt in ("-a", "--trajectory"): acts.append(actions.Action("Calculate the trajectory", 10, actions.trajectory)) context.trajectory_file = arg elif opt in ("--view"): acts.append(actions.Action("3D visualization of previous results.", 15, actions.view3D)) context.visualization_file = arg # Sort actions according to their priority acts.sort(key=lambda a: a.priority) for action in acts: try: action.run(context) except RuntimeError as E: print("Error: {}".format(E)) sys.exit(1)
('is', '?object', 'Airport'), ] FLY_NEG_PRECONDS = [ ('at', '?subject', '?object'), ] FLY_RETRACTIONS = [ ('at', '?subject', '?current'), ] FLY_UPDATES = [ ('at', '?subject', '?object'), ] fly = actions.Action(FLY_POS_PRECONDS, FLY_NEG_PRECONDS, FLY_RETRACTIONS, FLY_UPDATES) class ActionTestSuite(unittest.TestCase): def setUp(self): self.kb = kb.from_facts(INITIAL_FACTS) def test_a_flight(self): self.assertTrue(self.kb.ask(('at', 'N10IV', 'oak'))) self.assertFalse(self.kb.ask(('at', 'N10IV', 'lga'))) shadow = fly.perform(self.kb, 'N10IV', 'lga') self.assertTrue(shadow) # Shadow should reflect the updates and retractions. self.assertTrue(shadow.ask(('at', 'N10IV', 'lga')))
def run_server(self, world): print('Server online: Accepting connections...') while True: readable, writable, exceptional = select.select(self.sockets, self.broadcasting, self.sockets) # possible renames: readable -> incoming, writable -> outgoing for sock in readable: if sock == self.server: new_client, client_address = self.server.accept() new_client.setblocking(False) print(f'Connection from {client_address[0]}:{client_address[1]} established') self.sockets.append(new_client) self.broadcast_queues[new_client] = queue.Queue() elif sock in self.sockets: try: code = self.receive_code(sock) except Exception as e: print('Exception reached: ', e) self.close_client(sock) continue if code == '00' and sock not in self.active_players: # '00' can be used other than login, so both conditions here is ok login_name = self.receive_login(sock) if not login_name: self.close_client(sock) # Logging in # Login sequence needs more granular structure if login_name in [player.name for player in world.players]: for player in world.players: if login_name == player.name: player.socket = sock self.active_players[sock] = player print(f'{sock.getsockname} logged in as {self.active_players[sock].name}') self.broadcast(sock, f'Logged in as {self.active_players[sock].name}. Welcome back.') else: self.active_players[sock] = people.Player(world, login_name) self.broadcast_queues[sock] = queue.Queue() self.active_players[sock].server = self self.active_players[sock].socket = sock print(f'New player {login_name} created by {sock.getsockname()}') world.players.append(self.active_players[sock]) world.active_players.append(self.active_players[sock]) # world.high_priority_timers[self.active_players[sock]] = queue.Queue() self.broadcast(sock, f'Welcome to the world, {self.active_players[sock].name}') elif code == '01': # Get command, validate it, send into central loop player_command = self.receive_command(sock) player_action = actions.Action(self, self.active_players[sock], player_command.verb, player_command.target, player_command.quantity) self.active_players[sock].current_action = player_action for sock in writable: try: message = self.broadcast_queues[sock].get_nowait() except queue.Empty: self.broadcasting.remove(sock) else: self.broadcast(sock, message) for sock in exceptional: print(f'(From exceptional list) Lost connection from {sock.getsockname()}.') self.close_client(sock)
tenantId = input('Enter your Tenant ID: ') appId = input('Enter your application ID: ') appSecret = getpass.getpass('Enter your application Secret (does not show in cli): ') list_machine_actions = list.List(tenantId, appId, appSecret, 'machineactions', 'machineactions.csv') list_machine_actions.list() elif args.collect: tenantId = input('Enter your Tenant ID: ') appId = input('Enter your application ID: ') appSecret = getpass.getpass('Enter your application Secret (does not show in cli): ') comment = input('Comment: ') av_body = { 'Comment' : comment } filename = input('CSV filename with machine IDs: ') column = input('Column with machine IDs: ') action_collect = actions.Action(tenantId, appId, appSecret, av_body, 'collectInvestigationPackage', filename, column) action_collect.action() elif args.full_isolate: tenantId = input('Enter your Tenant ID: ') appId = input('Enter your application ID: ') appSecret = getpass.getpass('Enter your application Secret (does not show in cli): ') comment = input('Comment: ') body = { 'Comment' : comment, 'IsolationType' : 'Full' } filename = input('CSV filename with machine IDs: ') column = input('Column with machine IDs: ') action_full_isolate = actions.Action(tenantId, appId, appSecret, body, 'isolate', filename, column) action_full_isolate.action() elif args.selective_isolate:
def actions(self): return [ actions.Action("Update", "update", self.client.update), actions.Action("Rescan", "rescan", self.client.rescan), ]
def _volume_actions(self): return [ actions.Action("Volume " + str(v), "v" + str(v), self.volume_f(v)) for v in range(0, 110, 10) ]