Exemple #1
0
    def test_run(self, target, barcode, kernel, rootfs, test, task_id):
        """@todo: Docstring for test_run

        :arg1: @todo
        :returns: @todo
        """
        cmd,timeout,test_case=(
                                test['cmd'],
                                test['timeout'],
                                test['test_case']
                              )
        try:
            _, out = target.run(cmd, timeout=20)
        except Exception as e:
            raise
            out = "we hit an exception, reboot the target"
            target.vlm.unreserve_target()
            target = Target(barcode, kernel, rootfs)
            target.login(deploy=False)
        finally:
            log_dir='logs/{}_{}'.format(barcode,task_id)
            if not os.path.exists(log_dir):
                os.makedirs(log_dir)
            log_file = "{}.log".format(test_case)
            log=os.path.join(log_dir,log_file)
            log = Logging(log)
            log(out)
        return out
    def __init__(self,
                 name,
                 srcs,
                 deps,
                 outs,
                 cmd,
                 blade,
                 kwargs):
        """Init method.

        Init the gen rule target.

        """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)
        outs = var_to_list(outs)

        Target.__init__(self,
                        name,
                        'gen_rule',
                        srcs,
                        deps,
                        blade,
                        kwargs)

        self.data['outs'] = outs
        self.data['cmd'] = cmd
Exemple #3
0
    def __init__(self,
                 name,
                 srcs,
                 deps,
                 outs,
                 cmd,
                 blade,
                 kwargs):
        """Init method.

        Init the gen rule target.

        """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)
        outs = var_to_list(outs)

        Target.__init__(self,
                        name,
                        'gen_rule',
                        srcs,
                        deps,
                        None,
                        blade,
                        kwargs)

        self.data['outs'] = outs
        self.data['locations'] = []
        self.data['cmd'] = location_re.sub(self._process_location_reference, cmd)
    def __init__(self,
                 name,
                 srcs,
                 deps,
                 outs,
                 cmd,
                 blade,
                 kwargs):
        """Init method.

        Init the gen rule target.

        """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)
        outs = var_to_list(outs)

        Target.__init__(self,
                        name,
                        'gen_rule',
                        srcs,
                        deps,
                        blade,
                        kwargs)

        self.data['outs'] = outs
        self.data['cmd'] = cmd
Exemple #5
0
    def __init__(self,
                 name,
                 type,
                 srcs,
                 deps,
                 resources,
                 source_encoding,
                 warnings,
                 kwargs):
        """Init method.

        Init the java jar target.

        """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)
        resources = var_to_list(resources)

        Target.__init__(self,
                        name,
                        type,
                        srcs,
                        deps,
                        None,
                        blade.blade,
                        kwargs)
        self._process_resources(resources)
        self.data['source_encoding'] = source_encoding
        if warnings is not None:
            self.data['warnings'] = var_to_list(warnings)
    def __init__(self,
                 name,
                 srcs,
                 deps,
                 type,
                 out,
                 blade,
                 kwargs):
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)

        Target.__init__(self,
                        name,
                        'package',
                        [],
                        deps,
                        None,
                        blade,
                        kwargs)

        if type not in _package_types:
            console.error_exit('%s: Invalid type %s. Types supported '
                               'by the package are %s' % (
                               self.fullname, type, ', '.join(sorted(_package_types))))
        self.data['type'] = type
        self.data['sources'], self.data['locations'] = [], []
        self._process_srcs(srcs)

        if not out:
            out = '%s.%s' % (name, type)
        self.data['out'] = out
Exemple #7
0
    def __init__(self,
                 name,
                 type,
                 srcs,
                 deps,
                 base,
                 visibility,
                 kwargs):
        """Init method. """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)

        Target.__init__(self,
                        name,
                        type,
                        srcs,
                        deps,
                        visibility,
                        blade.blade,
                        kwargs)

        if base:
            if not base.startswith('//'):
                console.error_exit('%s: Invalid base directory %s. Option base should '
                                   'be a directory starting with \'//\' from BLADE_ROOT directory.' %
                                   (self.fullname, base))
            self.data['python_base'] = base[2:]
        self.data['python_sources'] = [self._source_file_path(s) for s in srcs]
def test_aggregation():
    # note: uneven aggregation: we only want 1 resulting metric,
    query = Query("")
    query["avg_by"] = {"server": [""]}
    query["sum_by"] = {"type": [""]}

    targets = {
        "web1.db": {"id": "web1.db", "tags": {"server": "web1", "type": "db", "n3": "foo"}},
        "web1.php": {"id": "web1.php", "tags": {"server": "web1", "type": "php", "n3": "foo"}},
        "web2.db": {"id": "web2.db", "tags": {"server": "web2", "type": "db", "n3": "foo"}},
        "web2.php": {"id": "web2.php", "tags": {"server": "web2", "type": "php", "n3": "foo"}},
        "web2.memcache": {"id": "web2.memcache", "tags": {"server": "web2", "type": "memcache", "n3": "foo"}},
    }
    from pprint import pprint

    for (k, v) in targets.items():
        v = Target(v)
        v.get_graph_info(group_by={})
        targets[k] = v
    graphs, _query = build_graphs_from_targets(targets, query)
    # TODO: there should be only 1 graph, containing all 5 items
    print "Graphs:"
    for (k, v) in graphs.items():
        print "graph key"
        pprint(k)
        print "val:"
        pprint(v)
    assert {} == graphs
Exemple #9
0
    def __init__(self,
                 name,
                 srcs,
                 deps,
                 prebuilt,
                 blade,
                 kwargs):
        """Init method.

        Init the java jar target.

        """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)

        Target.__init__(self,
                        name,
                        'java_jar',
                        srcs,
                        deps,
                        blade,
                        kwargs)

        if prebuilt:
            self.data['type'] = 'prebuilt_java_jar'
        self.java_jar_cmd_list = []
        self.cmd_var_list = []
        self.java_jar_after_dep_source_list = []
        self.targets_dependency_map = {}
        self.java_jar_dep_vars = {}
        self.java_jars_map = self.blade.get_java_jars_map()
        self.sources_dependency_map = self.blade.get_sources_explict_dependency_map()
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()
Exemple #11
0
    def __init__(self,
                 name,
                 target_type,
                 srcs,
                 deps,
                 warning,
                 defs,
                 incs,
                 export_incs,
                 optimize,
                 extra_cppflags,
                 extra_linkflags,
                 blade,
                 kwargs):
        """Init method.

        Init the cc target.

        """
        srcs_list = var_to_list(srcs)
        srcs = []
        for item in srcs_list:
            if (';' in item):
                # file list expanded with asterisk wildcard
                file_name_array = string.split(item, ';')
                for file_name in file_name_array:
                    srcs.append(file_name)
            else:
                srcs.append(item)
        deps = var_to_list(deps)
        defs = var_to_list(defs)
        incs = var_to_list(incs)
        export_incs = var_to_list(export_incs)
        opt = var_to_list(optimize)
        extra_cppflags = var_to_list(extra_cppflags)
        extra_linkflags = var_to_list(extra_linkflags)

        Target.__init__(self,
                        name,
                        target_type,
                        srcs,
                        deps,
                        blade,
                        kwargs)

        self.data['warning'] = warning
        self.data['defs'] = defs
        # add by zxy([email protected]) 20140929 support absolute include path (/common/gsl/include)
        for index, item in enumerate(incs):
            if (item.startswith('/')):
                incs[index] = find_relative_path(self.path, item)
        #end
        self.data['incs'] = incs
        self.data['export_incs'] = export_incs
        self.data['optimize'] = opt
        self.data['extra_cppflags'] = extra_cppflags
        self.data['extra_linkflags'] = extra_linkflags

        self._check_defs()
        self._check_incorrect_no_warning()
    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 test_agg_key():
    t = Target({
        'variables': {
            'foo': 'bar',
            'target_type': 'rate',
            'region': 'us-east-1'
        }})

    # catchall bucket
    assert t.get_agg_key({'foo': ['']}) == 'foo:__region=us-east-1,target_type=rate'

    # non catchall bucket
    assert t.get_agg_key({'foo': ['ba', ''], 'bar': ['']}) == 'foo:ba__region=us-east-1,target_type=rate'

    struct = {
        'n3': ['bucketmatch1', 'bucketmatch2'],
        'othertag': ['']
    }
    # none of the structs applies
    assert t.get_agg_key(struct) == '__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) == 'region:us-east,target_type:__foo=bar'
    def __init__(self,
                 name,
                 srcs,
                 deps,
                 type,
                 out,
                 shell,
                 blade,
                 kwargs):
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)

        Target.__init__(self,
                        name,
                        'package',
                        [],
                        deps,
                        None,
                        blade,
                        kwargs)

        if type not in _package_types:
            console.error_exit('%s: Invalid type %s. Types supported '
                               'by the package are %s' % (
                               self.fullname, type, ', '.join(sorted(_package_types))))
        self.data['type'] = type
        self.data['sources'], self.data['locations'] = [], []
        self._process_srcs(srcs)

        if not out:
            out = '%s.%s' % (name, type)
        self.data['out'] = out
        self.data['shell'] = shell
    def __init__(self,
                 name,
                 srcs,
                 deps,
                 outs,
                 cmd,
                 blade,
                 kwargs):
        """Init method.

        Init the gen rule target.

        """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)
        outs = var_to_list(outs)

        Target.__init__(self,
                        name,
                        'gen_rule',
                        srcs,
                        deps,
                        None,
                        blade,
                        kwargs)

        self.data['outs'] = outs
        self.data['locations'] = []
        self.data['cmd'] = location_re.sub(self._process_location_reference, cmd)
Exemple #16
0
 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)
Exemple #17
0
    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 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)
Exemple #19
0
    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 __init__(self,
                 name,
                 srcs,
                 deps,
                 prebuilt,
                 blade,
                 kwargs):
        """Init method.

        Init the java jar target.

        """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)

        Target.__init__(self,
                        name,
                        'java_jar',
                        srcs,
                        deps,
                        blade,
                        kwargs)

        if prebuilt:
            self.type = 'prebuilt_java_jar'
            self.data['jar_class_path'] = self._prebuilt_java_jar_src_path()
        self.data['java_jars'] = []
        self.java_jar_cmd_list = []
        self.cmd_var_list = []
        self.java_jar_after_dep_source_list = []
        self.targets_dependency_map = {}
        self.java_jar_dep_vars = {}
    def __init__(self,
                 name,
                 srcs,
                 deps,
                 prebuilt,
                 blade,
                 kwargs):
        """Init method.

        Init the java jar target.

        """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)

        Target.__init__(self,
                        name,
                        'java_jar',
                        srcs,
                        deps,
                        blade,
                        kwargs)

        if prebuilt:
            self.data['type'] = 'prebuilt_java_jar'
        self.java_jar_cmd_list = []
        self.cmd_var_list = []
        self.java_jar_after_dep_source_list = []
        self.targets_dependency_map = {}
        self.java_jar_dep_vars = {}
        self.java_jars_map = self.blade.get_java_jars_map()
        self.sources_dependency_map = self.blade.get_sources_explict_dependency_map()
Exemple #22
0
    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)
Exemple #23
0
    def __init__(self,
                 name,
                 type,
                 srcs,
                 deps,
                 resources,
                 source_encoding,
                 warnings,
                 kwargs):
        """Init method.

        Init the java jar target.

        """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)
        resources = var_to_list(resources)

        Target.__init__(self,
                        name,
                        type,
                        srcs,
                        deps,
                        None,
                        blade.blade,
                        kwargs)
        self._process_resources(resources)
        self.data['source_encoding'] = source_encoding
        if warnings is not None:
            self.data['warnings'] = var_to_list(warnings)
Exemple #24
0
    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
Exemple #25
0
def connectTarget(ip, port):
	target = Target(ip, int(port))
	target.secureConnect()
	if target.isConnected():
		return target
	else:
		return False
Exemple #26
0
    def __init__(self, name, target_type, srcs, deps, warning, defs, incs,
                 export_incs, optimize, extra_cppflags, extra_linkflags, blade,
                 kwargs):
        """Init method.

        Init the cc target.

        """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)
        defs = var_to_list(defs)
        incs = var_to_list(incs)
        export_incs = var_to_list(export_incs)
        opt = var_to_list(optimize)
        extra_cppflags = var_to_list(extra_cppflags)
        extra_linkflags = var_to_list(extra_linkflags)

        Target.__init__(self, name, target_type, srcs, deps, blade, kwargs)

        self.data['warning'] = warning
        self.data['defs'] = defs
        self.data['incs'] = incs
        self.data['export_incs'] = export_incs
        self.data['optimize'] = opt
        self.data['extra_cppflags'] = extra_cppflags
        self.data['extra_linkflags'] = extra_linkflags

        self._check_defs()
        self._check_incorrect_no_warning()
Exemple #27
0
	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 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 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()
Exemple #30
0
 def __init__(self, fname, *args, **kwargs):
     self.pass_filename = kwargs.get('pass_filename', False)
     if 'pass_filename' in kwargs:
         del kwargs['pass_filename']
     Target.__init__(self, *args, **kwargs)
     if self.pass_filename:
         self.passes = 1
     self.filename = fname
Exemple #31
0
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()
Exemple #32
0
 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"]
Exemple #33
0
def targets(img, readText=False):
    # Edge detection
    modimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    modimg = cv2.GaussianBlur(img, (5, 5), 0)
    modimg = cv2.Canny(img, 100, 200)

    # Find contours
    contImg, contours, _ = cv2.findContours(modimg, cv2.RETR_LIST,
                                            cv2.CHAIN_APPROX_SIMPLE)

    # Find squares
    squares = []
    for c in contours:
        contour_length = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02 * contour_length, True)

        if 4 <= len(approx) <= 6:
            (x, y, w, h) = cv2.boundingRect(approx)
            aspectRatio = w / float(h)

            area = cv2.contourArea(c)
            hullArea = cv2.contourArea(cv2.convexHull(c))
            solidity = area / float(hullArea)

            checkDimensions = w > 25 and h > 25
            checkSolidity = solidity > 0.95
            checkAspectRatio = 0.5 <= aspectRatio <= 1.5

            if checkDimensions and checkSolidity and checkAspectRatio:
                s = Square(c, x, y, w, h)
                if s not in squares:
                    squares.append(s)
                    # print "Added %s" %s

    # Reject similar squares
    for s1, s2 in itertools.combinations(squares, 2):
        if s1.similar(s2) and s2 in squares:
            squares.remove(s2)
            # print "Removed %s" %s2

    # Find targets
    targets = []
    for s1, s2 in itertools.combinations(squares, 2):
        if s1.concentric(s2):
            t = Target(s1, s2)
            if t not in targets:
                targets.append(t)
                # print "Found %s" %t

    # Read text inside targets
    if readText == True:
        for t in targets:
            t.readText(img)

    # print "Total number of squares: %s" %(len(squares))
    # print "Total number of targets: %s" %(len(targets))

    return targets
Exemple #34
0
def worker_thread(p, organizations, auto_create_repositories, s3,
                  deployment_map, parameter_store):
    pipeline = Pipeline(p)

    if auto_create_repositories == 'enabled':
        try:
            code_account_id = next(param['SourceAccountId']
                                   for param in p['params']
                                   if 'SourceAccountId' in param)
            has_custom_repo = bool(
                [item for item in p['params'] if 'RepositoryName' in item])
            if auto_create_repositories and code_account_id and str(
                    code_account_id).isdigit() and not has_custom_repo:
                repo = Repo(code_account_id, p.get('name'),
                            p.get('description'))
                repo.create_update()
        except StopIteration:
            LOGGER.debug(
                "No need to create repository as SourceAccountId is not found in params"
            )

    for target in p.get('targets', []):
        target_structure = TargetStructure(target)
        for step in target_structure.target:
            for path in step.get('path'):
                regions = step.get('regions',
                                   p.get('regions', DEPLOYMENT_ACCOUNT_REGION))
                step_name = step.get('name')
                params = step.get('params', {})
                pipeline.stage_regions.append(regions)
                pipeline_target = Target(path, regions, target_structure,
                                         organizations, step_name, params)
                pipeline_target.fetch_accounts_for_target()

        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_pipeline(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(ADF_PIPELINE_PREFIX, pipeline.name),
        s3=None,
        s3_key_path=None,
        account_id=DEPLOYMENT_ACCOUNT_ID)
    cloudformation.create_stack()
Exemple #35
0
def test_fetch_accounts_for_approval():
    cls = Target(path='approval',
                 regions=['region1', 'region2'],
                 target_structure=MockTargetStructure(),
                 organizations=None,
                 step_name=None)
    with patch.object(cls, '_target_is_approval') as mock:
        cls.fetch_accounts_for_target()
        mock.assert_called_once_with()
Exemple #36
0
    def __init__(self, name, srcs, deps, prebuilt, blade, kwargs):
        """Init method. """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)

        Target.__init__(self, name, 'py_binary', srcs, deps, blade, kwargs)

        if prebuilt:
            self.data['type'] = 'prebuilt_py_binary'
Exemple #37
0
def main():  #pylint: disable=R0915
    LOGGER.info('ADF Version %s', ADF_VERSION)
    LOGGER.info("ADF Log Level is %s", ADF_LOG_LEVEL)

    parameter_store = ParameterStore(DEPLOYMENT_ACCOUNT_REGION, boto3)
    deployment_map = DeploymentMap(parameter_store, ADF_PIPELINE_PREFIX)
    s3 = S3(DEPLOYMENT_ACCOUNT_REGION, S3_BUCKET_NAME)
    sts = STS()
    role = sts.assume_cross_account_role(
        'arn:aws:iam::{0}:role/{1}-readonly'.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.get('targets', []):
            target_structure = TargetStructure(target)
            for step in target_structure.target:
                for path in step.get('path'):
                    regions = step.get(
                        'regions', p.get('regions', DEPLOYMENT_ACCOUNT_REGION))
                    step_name = step.get('name')
                    params = step.get('params', {})
                    pipeline.stage_regions.append(regions)
                    pipeline_target = Target(path, regions, target_structure,
                                             organizations, step_name, params)
                    pipeline_target.fetch_accounts_for_target()

            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_pipeline(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(ADF_PIPELINE_PREFIX, pipeline.name),
            s3=None,
            s3_key_path=None,
            account_id=DEPLOYMENT_ACCOUNT_ID)
        cloudformation.create_stack()
Exemple #38
0
    def __init__(self, name, srcs, deps, prebuilt, blade, kwargs):
        """Init method. """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)

        Target.__init__(self, name, 'py_egg', srcs, deps, None, blade, kwargs)

        if prebuilt:
            self.type = 'prebuilt_py_egg'
Exemple #39
0
 def task_run(self, barcode, kernel, rootfs, plan, task_id):
     """@todo: Docstring for task_run
     :returns: @todo
     """
     target = Target(barcode, kernel, rootfs)
     target.login(deploy=True)
     for test in plan:
         self.test_run(target, barcode, kernel, rootfs, test, task_id)
     target.vlm.unreserve_target()
Exemple #40
0
def test_fetch_account_error_invalid_account_id():
    cls = Target(
        path='12345678910',  #11 digits rather than 12 (invalid account id)
        regions=['region1', 'region2'],
        target_structure=MockTargetStructure(),
        organizations=Mock(),
        step_name=None)
    with raises(InvalidDeploymentMapError):
        cls.fetch_accounts_for_target()
Exemple #41
0
    def add_process(self, **kwargs):
        """ Adds a new process to the solver.
        
        Adds a new process to the solver.  The process data is passed with
        keyword arguments.

        Parameters
        ----------
        type : string
           one of "EFFECTIVE", "MOMENTUM", "EXCITATION", "IONIZATION"
           or "ATTACHMENT".
        target : string
           the target species of the process (e.g. "O", "O2"...).
        ratio : float
           the ratio of the electron mass to the mass of the target
           (for elastic/momentum reactions only).
        threshold : float
           the energy threshold of the process in eV (only for 
           inelastic reactions).
        data : array or array-like
           cross-section of the process array with two columns: column
           0 must contain energies in eV, column 1 contains the
           cross-section in square meters for each of these energies.

        Returns
        -------
        process : :class:`process.Process`
           The process that has been added.

        Examples
        --------
        >>> import numpy as np
        >>> from bolos import solver, grid
        >>> grid.LinearGrid(0, 60., 400)
        >>> solver = BoltzmannSolver(grid)
        >>> # This is an example cross-section that decays exponentially
        >>> energy = np.linspace(0, 10)
        >>> cross_section = 1e-20 * np.exp(-energy)
        >>> solver.add_process(type="EXCITATION", target="Kriptonite", 
        >>>                    ratio=1e-5, threshold=10, 
        >>>                    data=np.c_[energy, cross_section])

        See Also
        --------
        load_collisions : Add a set of collisions.
        
        """
        proc = Process(**kwargs)
        try:
            target = self.target[proc.target_name]
        except KeyError:
            target = Target(proc.target_name)
            self.target[proc.target_name] = target

        target.add_process(proc)

        return proc
    def __init__(self, name, srcs, deps, testdata, kwargs):
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)
        testdata = var_to_list(testdata)

        Target.__init__(self, name, 'sh_test', srcs, deps, None, blade.blade,
                        kwargs)

        self._process_test_data(testdata)
Exemple #43
0
def main():
    # total number of interactions between 1 and infinity
    validInter = False # flag for a valid user input
    while validInter == False:
        try:
            totalInter = int(input("Enter total number of interactions (greater than or equal to 1): "))
        except ValueError:
            print("Do not enter non-numeric values.")
        else:
            if (totalInter >= 1):
                validInter = True
            else:
                validInteractions = False
                print("Input is out of range.")
    # Set the target's probability of X or Y
    validProb = False # flag for a valid user input
    while validProb == False:
        try:
            probX = int(input("Probability of X-type Interactions for the target (1-100): "))
        except ValueError:
            print("Do not enter non-numeric values.")
        else:
            if (1 <= probX <= 100):
                validProb = True
            else:
                validProb = False
                print("Input is out of range.")
    probY = 100 - probX # probabilty of Y interactions
    #DEBUG
    DEBUG.dprint("total # interactions: %r" % totalInter)
    DEBUG.dprint("probability of X: %r" % probX)
    # Pursuer class takes the two probabilities
    aPursuer = Pursuer(totalInter)
    aTarget = Target(probX, probY)
    # Main Loop
    i = 0 # flag
    while i < totalInter:
        # create an interaction for the pursuer and the target
        interP = aPursuer.createInteraction()
        interT = aTarget.createInteraction()
        # DEBUG
        DEBUG.dprint("aPursuer Interaction: %r" % interP)
        DEBUG.dprint("aTarget Interaction: %r" % interT)
        DEBUG.dprint("i: %r" % i)
        # record and display the result
        result = aPursuer.reportInteraction(interP, interT)
        print(result)
        i += 1 # update flag
        if i >= 2:
            aPursuer.adaptBehaviour(interP, interT)
    targetX, targetY = aTarget.reportEnd()
    aPursuer.reportEnd(targetX, targetY)
def main ():

    #Introduction
    print ("This program uses a cannonball to shoot at a target.")

    #Create graphics window
    win = GraphWin(200, 200)
    win.setCoords(0.0, 0.0, 25.0, 25.0)
    target = Target(win)

    flag = False
    targetHit = False
    while not flag:

    #Get inputs
        print ()
        a = eval(input("Enter the launch angle in degrees: "))
        v = eval(input("Enter the initial velocity in meters per second: "))
        h = eval(input("Enter the initial height in meters: "))

    #Create tracker
        projectile = Projectile(a, v, h)
        tracker = Tracker(win, projectile)
        time = 0.0
        while projectile.getY() >= -5:
            time += .0005
            projectile.update(time)
            tracker.update()

    #Calculate if cannonball hit target
            points = target.points()
            center = tracker.circ.getCenter()
            center_x = center.getX()
            center_y = center.getY()
            radius = tracker.circ.getRadius()
            for point in points:
                x = point.getX()
                y = point.getY()
                square_dist = (center_x-x) ** 2 + (center_y-y) ** 2
                if square_dist <= radius ** 2:
                    targetHit = True
        if targetHit:
            print ("\nYou hit the target!")
            flag = True
        else:
            flag = False
            print ("\nTry again!")


    #Close window
    win.getMouse()
    win.close()
Exemple #45
0
    def __init__(self,
                 name,
                 target_type,
                 srcs,
                 deps,
                 warning,
                 defs,
                 incs,
                 export_incs,
                 optimize,
                 extra_cppflags,
                 extra_linkflags,
                 install_dir,
                 extra_cmds,
                 blade,
                 kwargs):
        """Init method.

        Init the cc target.

        """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)
        defs = var_to_list(defs)
        incs = var_to_list(incs)
        export_incs = var_to_list(export_incs)
        opt = var_to_list(optimize)
        extra_cppflags = var_to_list(extra_cppflags)
        extra_linkflags = var_to_list(extra_linkflags)
        extra_cmds = var_to_list(extra_cmds)
        
        Target.__init__(self,
                        name,
                        target_type,
                        srcs,
                        deps,
                        blade,
                        kwargs)

        self.data['warning'] = warning
        self.data['defs'] = defs
        self.data['incs'] = incs
        self.data['export_incs'] = export_incs
        self.data['optimize'] = opt
        self.data['extra_cppflags'] = extra_cppflags
        self.data['extra_linkflags'] = extra_linkflags
        self.data['install_dir'] = install_dir
        self.data['extra_cmds'] = extra_cmds

        self._check_defs()
        self._check_incorrect_no_warning()
Exemple #46
0
    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
Exemple #47
0
    def __init__(self, *args, **kwargs):
        ''' Not perfect but the bike uses hardcoded constants
            Warning! Lots of opaque physics and math
        '''
        super(Bike, self).__init__(*args, **kwargs)

        # Not ideal to use white as the color key
        # Not ideal to hardcode the bike image asset
        self.original, self.rect = util.load_image('bike.png', (255,255,255))
        self.image = self.original

        self.speed = 0
        self.max_speed = 5

        # Is this bike moving?
        self.driving = 0

        # Each bike has its own target
        self.target = Target()

        # start at the origin
        self.x, self.y = self.rect.centerx, self.rect.centery
        self.angle = 0.0

        self.dt = 0.0

        # Some physics constants. These and the image ought to be parameters
        # F_c = mv*v/r --> v_max = sqrt(F_traction/m) * sqrt(r)
        self.ft = 5.0
        self.mass = 200.0
        self.brake = 0.1
        self.accel = 0.05
        self.draw_cb = []
Exemple #48
0
    def __init__(self,
                 name,
                 srcs,
                 deps,
                 testdata,
                 kwargs):
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)
        testdata = var_to_list(testdata)

        Target.__init__(self,
                        name,
                        'sh_test',
                        srcs,
                        deps,
                        None,
                        blade.blade,
                        kwargs)

        self._process_test_data(testdata)
Exemple #49
0
    def __init__(self,
                 name,
                 type,
                 srcs,
                 deps,
                 kwargs):
        """Init the go target. """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)

        Target.__init__(self,
                        name,
                        type,
                        srcs,
                        deps,
                        None,
                        blade.blade,
                        kwargs)

        self._set_go_package()
        self._init_go_environment()
Exemple #50
0
    def __init__(self,
                 name,
                 srcs,
                 deps,
                 prebuilt,
                 blade,
                 kwargs):
        """Init method. """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)

        Target.__init__(self,
                        name,
                        'py_binary',
                        srcs,
                        deps,
                        blade,
                        kwargs)

        if prebuilt:
            self.data['type'] = 'prebuilt_py_binary'
Exemple #51
0
    def __init__(self,
                 name,
                 srcs,
                 deps,
                 prebuilt,
                 blade,
                 kwargs):
        """Init method. """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)

        Target.__init__(self,
                        name,
                        'py_egg',
                        srcs,
                        deps,
                        None,
                        blade,
                        kwargs)

        if prebuilt:
            self.type = 'prebuilt_py_egg'
Exemple #52
0
    def __init__(self,
                 name,
                 type,
                 srcs,
                 deps,
                 prebuilt,
                 blade,
                 kwargs):
        """Init method.

        Init the java jar target.

        """
        srcs = var_to_list(srcs)
        deps = var_to_list(deps)

        Target.__init__(self,
                        name,
                        type,
                        srcs,
                        deps,
                        blade,
                        kwargs)
Exemple #53
0
 def check_depends(self, builder):
     if Target.check_depends(self, builder):
         return True
     if not os.path.exists(self.filename):
         return True
     last_mod = os.path.getctime(self.filename)
     for dep in self.depends:
         if dep.startswith('@'):continue
         files = glob.glob(os.path.expanduser(dep))
         if not len(files):
             raise Exception, 'file not found %s -- depended on by ' % dep + self.filename
         for fname in files:
             if last_mod < os.path.getctime(fname):
                 return True
     return False
Exemple #54
0
    def openBackup(self):  # WARNING -> obsolete, use targets and performance
        result = Result()
        tarTemp = Target(0)
        with open("backup.txt") as f:
            temp = f.readlines()
        f.close()
        # open("backup.txt", "w").close()  # TODO uncomment to activate backup refresh
        for index, line in enumerate(temp):  # on parcourt toutes les lignes du fichier
            if line.__len__() > 10 and line[:1] == "|":  # la ligne ne contient pas qu'un |
                if index < temp.__len__() - 1 and temp[index + 1][:13] != line[:13]: # on est pas sur une ligne partielle
                    line = line.split(",")
                    tarTemp = Target(line[0][1:])
                    lineb = line[1].split("/")
                    print(lineb.__len__())
                    for p in lineb:
                        tempPoint = Point(line[0][1:], p)
                        tarTemp.addPoint(tempPoint)
                        del tempPoint
                    result.append(tarTemp)
        return result

    # def targets(self):
    #     result = Result()
    #     return 0
    def start(self):
        #Call to Analyze APK
        #Creating directory for the current apk

        apkname = os.path.basename(os.path.splitext(self.apkpath)[0])
        dir = self.config.outputdir + str(apkname) + "/"
        #Creating directory if not exists
        if not os.path.exists(dir):
            #print "Creating directory " + str(dir) + " for APK " + str(apkname) + "..."
            os.makedirs(dir)
            os.chmod(dir,0755)
        static_target = str(self.apkpath) #this must be the complete path of apk file
        logpath = self.config.outputdir + apkname + '/log.txt'
        log = Logger(logpath)

        #Opening APK with Androguard
        targetapp = Target(static_target,self.config)
        if targetapp.status:    #If open APK result is OK, we continue...
            if targetapp.package_name is not None:
                session_name = targetapp.package_name #usare md5, meglio
            else:
                session_name = "dummyname"

            #Check if the current APK has a cache file
            if os.path.isfile(dir + "cache"):
                log.write("Restoring session for " + apkname)
                targetapp.restore_session(dir + "cache")
            else:
                log.write("Saving session for " + apkname)
                targetapp.save_session(dir + "cache")

            # Creating database connection
            database = hashesDB(self.config.dbpath)
            database.connect()
            manifestInfo = Manifest(targetapp)

            #Changing stdout to apkName.txt file (Normal output and errors)
            manifestAnalysis = ManifestAnalyzer(manifestInfo,targetapp);
            log.write("analyzing...\n" + targetapp._print())
            #manifestInfo.checkPermissions(self.config,apkname,targetapp.package_name,log)          <- JSON
            manifestInfo.checkPermissionsInDB(self.config, apkname, database)                # <- DB
            log.write(apkname + " has been analyzed.")
            print apkname + " has been analyzed."
            print "**********************************************************"
            #Check frida option
            if self.launch_writer:
                frida = Frida(self.apkpath)

            log.close()
            database.close()

        else:
            shutil.rmtree(dir)  #Deleting folder for apk analysis
Exemple #56
0
class Coffesploit(object):
    """Main Class"""
    def __init__(self, basepath):
        self.target = Target()
        self.tool = None
        self.pluginmanager = PluginManager()
        self.helper = Help()
        self.basepath = basepath
        
    def set_target(self,rhost=None,url=None):
        if url is not None:
            self.target.seturl(url)
        if rhost is not None:
            self.target.setrhost(rhost)
    def set(self, arg1, arg2):
        self.pluginmanager.current_plugin.set_arg(arg1,arg2)
    def show(self,arg):
        if arg == "target":
            print "ip:",self.target.getrhost(),"url:",self.target.geturl()
        if arg == "status":
            if self.pluginmanager.current_plugin is not None:
                self.pluginmanager.plugin_status()
        if arg == "version":
            print "Currnt Version:",self.version()
                
    def use(self,arg):
        self.pluginmanager.load_plugin(arg)
        
    def run(self):
        self.pluginmanager.plugin_run()
        self.pluginmanager.plugin_result()

    def main_help (self):
        return self.helper.main_help()
    def main_list (self):
        return self.pluginmanager.importer.get_plugins_list()
    def help(self,arg):
        """show help info of t"""
        if arg == "target":
            self.helper.help_set_tartget()
        if arg == "show":
            self.helper.help_show()
        if arg == "use":
            self.helper.help_use()
    def exit(self):
        exit(0)
    def version(self):
        return __Version__
Exemple #57
0
	def mouseReleaseEvent(self, QMouseEvent):
		
		x = QMouseEvent.x()
		y = QMouseEvent.y()
		
		if self.mouseActionType == Map.PlaceRobotAction:

			self.mouseActionType = Map.NoAction
			
			self.simStats.btPlaceRobot.setEnabled(False)
			
			ab = x - self.robot.posX
			mb = math.sqrt(math.pow(x - self.robot.posX, 2) + math.pow(y - self.robot.posY, 2))
			if mb == 0:
				newTheta = 0
			else:
				newTheta = math.acos(ab / mb)
			
			if y < self.robot.posY:
				newTheta = math.pi - newTheta + math.pi
			
			self.robot.setOrientation(newTheta)
			
			if self.target is not None:
				
				# I am computing the angle relative to Ox ax.
				x = self.target.x - self.robot.posX
				y = self.target.y - self.robot.posY
				
				ab = x
				mb = math.sqrt(x * x + y * y)
			
				if mb == 0:
					theta = 0
				else:
					theta = math.acos(ab / mb)
				
				if self.target.y < self.robot.posY:
					theta = math.pi - theta + math.pi
				
				theta = theta - newTheta
				if theta < 0:
					theta = theta + 2 * math.pi
				
				self.robot.setTargetDirection(theta)
			
			self.repaint()
			
		elif self.mouseActionType == Map.PlaceTargetAction:
			
			self.target = Target(x, y)
			self.mouseActionType = Map.NoAction
			
			self.simStats.btPlaceTarget.setEnabled(False)
			self.simStats.btPlaceRobot.setEnabled(True)
			
			self.repaint()
			
		elif self.mouseActionType == Map.PlaceBlockAction:
			
			self.dragXend = x
			self.dragYend = y
			
			self.dragObject.updateDrag(self.dragXstart, self.dragYstart,
					self.dragXend, self.dragYend)
		
			self.objects.append(self.dragObject)
			self.dragObject = None
		
			self.saveToImage = True
			self.setChanged(True)
		
			self.mouseActionType = Map.NoAction
			#TODO
			#print(QMouseEvent.pos())
			self.repaint()