def get_data_from_csv(name_of_file): """ Parse the file containing all the information :return: a list of target objects """ res = [] with open(name_of_file, 'r') as f: reader = csv.reader(f) # skip the first line (header) next(reader) for row in reader: data = row[0].split() if data[11] == "Damaging": res.append(Target(data)) elif data[11] == "Probably": data[11] = data[11] + " " + data[12] del data[12] res.append(Target(data)) elif data[11] == "Potentially": data[11] = data[11] + " " + data[12] del data[12] res.append(Target(data)) elif data[11] == "Unknown": res.append(Target(data)) return res
def create_target(self): """ Creates a new target of a random type and adds it to the list. :return: """ # TODO: Decide what type of target to create and append it to the list #randomly select a number from 1 to 3 num = random.uniform(0, 3) #if the number is 1 the new target is a standard target if num <= 1: new = Target() #if the number is 2 the new target is a strong target elif num <= 2: new = Strong() #if the number is 3 the new target is a safe target elif num <= 3: new = Safe() #if we get anything else create standard target else: new = Target() #add new target to list of targets self.targets.append(new) # create a 1 in 20 chance of creating a UFO if (random.uniform(0, 20) <= 1): ufo = UFO() self.targets.append(ufo)
def setUp(self) -> None: """Сохраняет ссылки на нужные объекты, откатывает их к первоначальному состоянию :return: None """ # Две цели first_target = Target(number=1, coordinates=np.array([100000, 1001, 30000.]), velocities=np.array([-50., 0., -60.])) second_target = Target(number=2, coordinates=np.array([30000, 5001, 30000.]), velocities=np.array([-50., 0., -60.])) # Список целей self.target_list = [first_target, second_target] # Два локатора first_radar = MultiFunctionalRadar(target_list=self.target_list, stable_point=np.array( [1001, 0, -780]), mfr_number=1) second_radar = MultiFunctionalRadar(target_list=self.target_list, stable_point=np.array( [-1000, 0, 780]), mfr_number=2) # Список локаторов self.radar_list = [first_radar, second_radar] # Собственный ПБУ self.command_post = CommandPost(mfr_list=self.radar_list) self.failure_msg = "Что-то пошло не так"
def calculate_checkpoints(self): goal = Vec3(0.0, 5125.0, 0.0) ball_to_target = Line(goal, self.S.ball_location) self.D.draw_line(ball_to_target) car_to_ball = Line(self.S.car_location, self.S.ball_location) self.D.draw_line(car_to_ball) hit_prep = ball_to_target.get_point_on_line(1.2) hit_prep.z = 0 car_to_hit_prep = Line(self.S.car_location, hit_prep) target = Target(location=hit_prep) self.checkpoints.append(target) ball = Target(location=self.S.ball_location) self.checkpoints.append(target) print([check.location for check in self.checkpoints]) # if car_to_hit_prep is not mostly straight, target hit prep # angle_diff = abs(ball_to_target.angle_difference(car_to_hit_prep)) # print(angle_diff) # if angle_diff < 2: # print("GOFORIT") # self.go = True # planned_location = self.S.ball_location # else: planned_location = hit_prep # self.go = False # print("not yet") # # plan = Line(self.S.car_location, planned_location) # self.D.draw_line(plan, color="orange") return Target(location=planned_location)
def test_update_trace_list(self) -> None: """Проверим, что все цели с корректными координатами могут сопровождаться, а с некоректными нет :return: None """ # Определение нужных для функции данных # Создадим три цели, которые можем сопровождать first_target = Target(coordinates=np.array([10_000., 5_000., 1_000.])) second_target = Target( coordinates=np.array([30_000., 4_900., 30_000.])) third_target = Target(coordinates=np.array([55_000., 4_950., 3_000.])) # Создание тестируемого МФР mfr = MultiFunctionalRadar( target_list=[first_target, second_target, third_target]) # Вызов тестируемой функции mfr.update_trace_list() # Проверка для длины массива трасс len_trace_list = len(mfr.trace_list) real_len_trace_list = 3 self.assertEqual(real_len_trace_list, len_trace_list, "Длина списка трасс определена неверно") # ______________________________________________________________________________________________________________ # Если координаты целей стали некорректными, то и массив трасс должен измениться # Первую и вторую цель не можем сопровождать из-за некорректного азимута и угла места соответственно first_target.coordinates = np.array([10_000., 5_000., 30_000.]) second_target.coordinates = np.array([1_000., 10_000., 1_000.]) # Вызов тестируемой функции mfr.update_trace_list() # Проверка для длины массива трасс len_trace_list = len(mfr.trace_list) real_len_trace_list = 1 self.assertEqual(real_len_trace_list, len_trace_list, "Длина списка трасс определена неверно") # ______________________________________________________________________________________________________________ # Если при этом координаты целей снова станут корректными, то сопровождение станет возможным first_target.coordinates = np.array([30_000., 5_000., 30_000.]) second_target.coordinates = np.array([10_000., 5_000., 1_000.]) # Вызов тестируемой функции mfr.update_trace_list() # Проверка для длины массива трасс len_trace_list = len(mfr.trace_list) real_len_trace_list = 3 self.assertEqual(real_len_trace_list, len_trace_list, "Длина списка трасс определена неверно")
def build_targets(args): GRADE = ['Red', 'Blue', 'Gold'] o = [ Target("{}-{}".format(GRADE[2 - i], j + 1), args.unit[2 - i], args.timerate, True, False) for i in range(len(GRADE)) for j in range(args.offence[2 - i]) ] d = [ Target("{}-{}".format(GRADE[2 - i], j + 1), args.unit[2 - i], args.timerate, False, True) for i in range(len(GRADE)) for j in range(args.defense[2 - i]) ] return o, d
def __init__(self, i): self.i = i # i-th run for each scenario self.scheduling_protocol = None # create targets self.targets = [Target(i) for i in range(0, cf.NUM_TARGETS)] # create nodes self.nodes = [Node(i) for i in range(0, cf.NUM_NODES)] # create matrix of sensing probability self.matrix = np.zeros((cf.NUM_TARGETS, cf.NUM_NODES), dtype=float) self.threshold = 1 - cf.SENSING_THRESHOLD # 1 - sensing threshold self.create_matrix() # create matrix and log_matrix # self.log_matrix = -np.log(self.matrix) self.log_threshold = -np.log( self.threshold) # ln (no sensing threshold) # result trace values self.num_of_active_nodes_list = [ ] # the numbers of active nodes at each time slot self.costs = [] # objective function value at each time slot self.result = [] # create Communication graph if cf.CONNECTIVITY: self.sink_node = Node(-1, sink=True) self.comm_graph = self.create_comm_graph() else: cf.COMMUNICATION_ENERGY = 0
def __init__(self, target_json_file, plane_json_file=None, camera_json_file=None): self.targets = [] self.idx = index.Index() with open(target_json_file) as target_json: target_data = json.load(target_json) for i, target in enumerate(target_data): t = Target(target["lat"], target["lon"], target, target["size"]) self.targets.append(t) diff = t.size / 2 left, bottom, right, top = (t.x - diff, t.y - diff, t.x + diff, t.y + diff) self.idx.insert(i, (left, bottom, right, top), obj=t) if plane_json_file: self.update_plane_json(plane_json_file) else: # Defualt Plane Telemetry self.x, self.y, self.z = 0.0, 0.0, 500.0 # Default Gimbal Orientation self.roll, self.pitch, self.yaw = 0.0, 0.0, 0.0 if camera_json_file: self.update_camera_json(camera_json_file) else: # Defualt Image resolution self.width, self.height = 5456, 3632 # Default Camera Setting self.fov_x = 78 * np.pi / 180 self.fov_y = np.arctan( self.height * np.tan(self.fov_x / 2) / self.width) * 2
def main(self): args = input_args() if IP(args.ip) or 'localhost' and (type(args.port) is int and 0 < args.port <= 65533): target_dict = {'ip': args.ip, 'port': args.port, 'path': args.path, 'enumerated': False} target = Target(target_dict) if args.enum: enum = Enum() # Will return a modified 'target' dictionary target = enum.enumerate(args, target) else: if target.enumerated: pass else: pass pass # pwn module here sys.exit() else: print("Invalid Arguments") sys.exit()
def cls(): cls = Target(path='/thing/path', regions=['region1', 'region2'], target_structure=MockTargetStructure(), organizations=None, step_name=None) return cls
def _create_target(self, num, row_number): target = Target(self) target_width, target_height = target.rect.size target.x = target_width+2 * target_width * num target.rect.x = target.x target.rect.y = target.rect.height + 2 * target.rect.height * row_number self.targets.add(target)
def run_game(): """Initialize game, create window object.""" pygame.init() # NOTE: Initialize a pygame instance. ai_settings = Settings() # Screen settings. screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) # Add title to window. pygame.display.set_caption('Alien Invasion') # Draw button. play_button = Button(ai_settings, screen, "Play") # Make a ship. ship = Ship(ai_settings, screen) # Make bullets. bullets = Group() # Make target target = Target(ai_settings, screen) # Create the fleet of . # gf.create_fleet(ai_settings, screen, ship) # Initalize stats for a new game stats = GameStats(ai_settings) # Start the run loop for our game. while True: gf.check_events(ai_settings, screen, ship, bullets, stats, play_button) if stats.game_active: ship.update() target.update() gf.update_target(ai_settings, screen, target, bullets) gf.update_bullets(ai_settings, screen, ship, bullets, target, stats, play_button) gf.update_screen(ai_settings, screen, ship, bullets, stats, play_button, target)
def main(): parameter_store = ParameterStore(DEPLOYMENT_ACCOUNT_REGION, boto3) deployment_map = DeploymentMap(parameter_store, os.environ["ADF_PIPELINE_PREFIX"]) s3 = S3(DEPLOYMENT_ACCOUNT_REGION, boto3, S3_BUCKET_NAME) sts = STS(boto3) role = sts.assume_cross_account_role( 'arn:aws:iam::{0}:role/{1}-org-access-adf'.format( MASTER_ACCOUNT_ID, parameter_store.fetch_parameter('cross_account_access_role')), 'pipeline') organizations = Organizations(role) clean(parameter_store, deployment_map) for p in deployment_map.map_contents.get('pipelines'): pipeline = Pipeline(p) for target in p['targets']: target_structure = TargetStructure(target) for step in target_structure.target: for path in step.get('path'): try: regions = step.get( 'regions', p.get('regions', DEPLOYMENT_ACCOUNT_REGION)) pipeline.stage_regions.append(regions) pipeline_target = Target(path, regions, target_structure, organizations) pipeline_target.fetch_accounts_for_target() except BaseException: raise Exception( "Failed to return accounts for {0}".format(path)) pipeline.template_dictionary["targets"].append( target_structure.account_list) if DEPLOYMENT_ACCOUNT_REGION not in regions: pipeline.stage_regions.append(DEPLOYMENT_ACCOUNT_REGION) parameters = pipeline.generate_parameters() pipeline.generate() deployment_map.update_deployment_parameters(pipeline) s3_object_path = upload_if_required(s3, pipeline) store_regional_parameter_config(pipeline, parameter_store) cloudformation = CloudFormation( region=DEPLOYMENT_ACCOUNT_REGION, deployment_account_region=DEPLOYMENT_ACCOUNT_REGION, role=boto3, template_url=s3_object_path, parameters=parameters, wait=True, stack_name="{0}-{1}".format(os.environ["ADF_PIPELINE_PREFIX"], pipeline.name), s3=None, s3_key_path=None) cloudformation.create_stack()
def test_create_measurement(self) -> None: """Тест для создания измерений по цели :return: None """ # Подготовка нужных данных для функции target = Target(coordinates=np.array([10_000., 0., 10_000.])) mfr = MultiFunctionalRadar(target_list=[target], stable_point=np.array([0., 0., 10_000.])) trace = mfr.trace_list[0] mfr.tick = 20 # Вызов тестируемой функии mfr.create_measurement(trace) # Измеренные биконические координаты range_, phi_v, phi_n = trace.coordinates_data.measure_coordinates_bcs # Так как процесс вероятностный, можем только предполагать пределы для биконических координат # Проверка для дальности is_range_in_limits = 9_980 <= range_ <= 10_020 self.assertTrue(is_range_in_limits) # Проверка для первого угла is_phi_v_in_limits = -0.53 <= phi_v <= -0.51 self.assertTrue(is_phi_v_in_limits) # Проверка для второго угла is_phi_n_in_limits = -0.01 <= phi_n <= 0.01 self.assertTrue(is_phi_n_in_limits)
def run_game(): pygame.init() g_settings = Settings() screen = pygame.display.set_mode( (g_settings.screen_width, g_settings.screen_height)) pygame.display.set_caption("Target practice") # Создание экземпляра корабля. spaceship = SpaceShip(screen, g_settings) # Создание экземпляра мишени. target = Target(screen, g_settings) # Экземпляр статистики игры. stats = GameStats(g_settings) # Создание группы для пуль bullets = Group() # Создание экземпляра кнопки. play_button = Button(g_settings, screen, 'В бой!') while True: fg.event_tracking(spaceship, g_settings, screen, bullets, play_button, stats, target) # Отслеживание событий клавиатуры. if stats.game_active: spaceship.update_ship() # Обновление позиции корабля. fg.update_bullets(g_settings, bullets, target, spaceship, stats) fg.update_target(target) fg.update_screen(screen, g_settings, spaceship, target, bullets, play_button, stats) # Обновление и перерисовка экрана
def __gettargets(self, index): accesspoint = self.accesspoints[index] commands.cleanfiles(accesspoint.dumpfilename, wildcard=True) commands.sniffssid(self.mondevice, accesspoint.ssid, accesspoint.channel, accesspoint.dumpfilename) time.sleep(20) try: with open(accesspoint.dumpfilename + '-01.csv', 'r') as f: lines = f.readlines() accesspoint.mac = filter(lambda line: accesspoint.ssid in line, lines)[0].split(',')[0] #accesspoint.mac = ((lines[2].split(','))[0]).strip() cleanlines = lines[lines.index( 'Station MAC, First time seen, Last time seen, Power, # packets, BSSID, Probed ESSIDs\r\n' ):] print cleanlines #self.targets = map(lambda client: Target(client.split(',')[0], accesspoint), filter(lambda fullline: accesspoint.mac in fullline, filter(lambda line: len(line.strip()) > 1, lines[5:]))) self.targets = map( lambda client: Target(client.split(',')[0], accesspoint), filter(lambda fullline: accesspoint.mac in fullline, cleanlines)) print 'TARGETS FOUND' + str(self.targets) for target in self.targets: print str(target) except IOError as e: print str(e)
def run(self): # main event/animation loop count = 0 while True: key = self.win.checkKey() self.updateBullets() self.updateTargets() if key in ["q", "Q"]: break if self.launcher and key == "Up": self.launcher.translate(1) elif self.launcher and key == "Down": self.launcher.translate(-1) elif self.launcher and key == "Right": self.launcher.slide(1) elif self.launcher and key == "Left": self.launcher.slide(-1) elif self.launcher and key == "period": self.launcher.rotate(-10) elif self.launcher and key == "comma": self.launcher.rotate(10) elif key in ["enter", "space", "f", "F"]: if self.launcher: self.bullets.append(self.launcher.shoot()) elif key in ["s", "S"]: self.startGame() update(30) count += 1 if count % 15 == 0: self.targets.append(Target(self.win)) self.win.close()
def run_game(): # Initialize game pygame.init() ai_settings = Settings() # Create the screen screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # Make the Play button play_button = Button(screen, "Play") # Create an instance to store game statistics. stats = GameStats(ai_settings) # Make a character, a ship, a group of bullets, and a group of aliens. character = Character(ai_settings, screen) ship = Ship(ai_settings, screen) bullets = Group() target = Target(ai_settings, screen) # Main loop for the game. while True: gf.check_events(ai_settings, screen, stats, play_button, ship, bullets) # update ship and bullets position if stats.game_active: ship.update() gf.update_target(ai_settings, target) gf.update_bullets(ai_settings, target, bullets, stats) gf.update_screen(ai_settings, screen, stats, ship, character, bullets, target, play_button)
def run_game(): pygame.init() screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption("Sideways Shooter") settings = Settings() target = Target(screen) play_button = Button(settings, screen, "Play") ship = sideways_ship.Ship(settings, screen) bullets = Group() target.draw_target() fun.update_screen(settings, screen, ship, bullets, target) while True: fun.check_events(settings, screen, ship, bullets, play_button) if settings.active: ship.update() fun.update_bullets(bullets, settings) fun.update_screen(settings, screen, ship, bullets, target) target.update(settings) else: pygame.mouse.set_visible(True) play_button.draw_button() pygame.display.flip()
def _gen_attached_luns(self): ''' Fast scan of luns attached to a storage object. This is an order of magnitude faster than using root.luns and matching path on them. ''' isdir = os.path.isdir islink = os.path.islink listdir = os.listdir realpath = os.path.realpath path = self.path from root import RTSRoot rtsroot = RTSRoot() target_names_excludes = FabricModule.target_names_excludes for fabric_module in rtsroot.fabric_modules: base = fabric_module.path for tgt_dir in listdir(base): if tgt_dir not in target_names_excludes: tpgts_base = "%s/%s" % (base, tgt_dir) for tpgt_dir in listdir(tpgts_base): luns_base = "%s/%s/lun" % (tpgts_base, tpgt_dir) if isdir(luns_base): for lun_dir in listdir(luns_base): links_base = "%s/%s" % (luns_base, lun_dir) for lun_file in listdir(links_base): link = "%s/%s" % (links_base, lun_file) if islink(link) and realpath(link) == path: val = (tpgt_dir + "_" + lun_dir) val = val.split('_') target = Target(fabric_module, tgt_dir) yield LUN(TPG(target, val[1]), val[3])
def __init__(self): """intialize the game, and create resources""" pygame.init() self.settings = Settings() #Set the window size and caption self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Target Practice") #create an instance to store game statistics self.stats = GameStats(self) #import the rocket ship and make an instance of it self.rocketShip = RocketShip(self) #import the orb self.orbs = pygame.sprite.Group() #import the target self.target = Target(self) #Create a play button self.play_button = Button(self, "Play") #misses self.miss = 0
def connectTarget(ip, port): target = Target(ip, int(port)) target.secureConnect() if target.isConnected(): return target else: return False
def getTarget(self, target_name=None, password=None): # Override self.target_name if set if not target_name: target_name = self.target_name # TODO: Controllare anche che il master sia connesso. Se e' configurato ma non connesso si deve solo connettere. Il problema e' che non c'e' modo di sapere se effettivamente e' connesso if not self.master: print("Connecting to master") # The first parameter as False creates a Master target self.master = Target(False, self.protocol, self.address, self.port, target_name) # TODO: Serve lo stato del master per capire se e' gia' connesso (e quindi ci si riconnette) oppure se serve una nuova connessione if self.master.is_connected or self.master.connect(password): print("Connected to master") else: print("Error while connecting to master") return False print("Connecting to slave") self.slave = self.master.getSlave(target_name) if self.slave and ( not self.slave.is_connected) and self.slave.connect(): print("Connected to slave") else: print("Error while connecting to the slave target") return self.slave
def test_agg_key(): t = Target({ 'variables': { 'foo': 'bar', 'target_type': 'rate', 'region': 'us-east-1' }}) # catchall bucket assert t.get_agg_key({'foo': ['']}) == 'agg_id_found:foo:__agg_id_missing:__variables:region=us-east-1,target_type=rate' # non catchall bucket assert t.get_agg_key({'foo': ['ba', ''], 'bar': ['']}) == 'agg_id_found:foo:ba__agg_id_missing:bar__variables:region=us-east-1,target_type=rate' struct = { 'n3': ['bucketmatch1', 'bucketmatch2'], 'othertag': [''] } # none of the structs applies assert t.get_agg_key(struct) == 'agg_id_found:__agg_id_missing:n3,othertag__variables:foo=bar,region=us-east-1,target_type=rate' struct = { 'target_type': [''], 'region': ['us-east', 'us-west', ''] } # one catchall, the other matches assert t.get_agg_key(struct) == 'agg_id_found:region:us-east,target_type:__agg_id_missing:__variables:foo=bar'
def generateTarget(self): while True: x,y=randint(2,self.GRIDS_X-3),randint(2,self.GRIDS_Y-3) if self.grid[y][x] == 0: self.target = Target(x,y,True) self.grid[y][x] = self.target break
def plot1(): fig, ax = plt.subplots() ax.set_aspect('equal') ax.set_xlim(-60, 110) ax.set_ylim(-60, 110) # Initialize classes params = Parameters() target = Target(25, 25, 0) agents = [] for i in range(params.nveh): agents.append(Agent(0, 25 * i, 0, params.monSpeed, 0, params, ax=ax)) # Give the target a commanded speed target.send_cmd(3, 0) # Get first plan for i, agent in enumerate(agents): agent.detect_target(target.get_state()) agent.compute_flight_traj(tf=params.tflight + i * params.tmon) # Plot initial states pts = target.get_state() trgtPlot = ax.plot(pts[0], pts[1], 'r*', markersize=10, label='Target') for i, agent in enumerate(agents): agent.plot_arrow() # Plot the inner and outer radii cir1 = Circle(target.get_state()[:2], ls=':', fill=False, ec='r', label='Outer Radius', radius=params.outerR) cir2 = Circle(target.get_state()[:2], ls=':', fill=False, ec='r', label='Outer Radius', radius=params.innerR) cir3 = Circle(target.get_state()[:2], lw=None, fc='gray', alpha=0.5, label='No Fly Zone', radius=params.noflyR) ax.add_artist(cir1) ax.add_artist(cir2) ax.add_artist(cir3) # Draw legend and clean up Agent class ax.legend([trgtPlot[0]] + [agent._arrow for agent in agents], ['Target', 'Agent 1', 'Agent 2', 'Agent 3']) Agent.agentIdx = 0 Agent.trajList = [] Agent.timeList = [] plt.title('$t = 0$') return
def __init__(self): self.reset = False self.quit = False self.time_inc = .1 self.time = 0 self.bal = 0 self.target = Target() self.cmd_list = ["dstab", "wait", "quit", "reset"]
def test_fetch_accounts_for_target_account_id(): cls = Target(path='12345678910', regions=['region1', 'region2'], target_structure=MockTargetStructure(), organizations=None) with patch.object(cls, '_target_is_account_id') as mock: cls.fetch_accounts_for_target() mock.assert_called_once_with()
def test_fetch_account_error(): cls = Target(path='some_string', regions=['region1', 'region2'], target_structure=MockTargetStructure(), organizations=Mock(), step_name=None) with raises(InvalidDeploymentMapError): cls.fetch_accounts_for_target()
def scan_mxs(self): mxs = MxRecords(self.domain).__get__() if mxs: targets = [ Target(mx, 'mx', timeout=1) for mx in mxs ] return self.scan(targets)