Esempio n. 1
0
 def test_one_replacement(self):
     """Test a target with a single replacement editor
     Before the test execution we copy the target file from a sample each
     time. Target will be removed on successful test execution. On
     failure it will be kept for debugging and overwritten on next test
     execution (no checks)
     """
     sample = os.path.join(self.test_files_dir, "one_replacement.sample")
     targetfile = os.path.join(self.test_files_dir, "one_replacement.conf")
     expected = os.path.join(self.test_files_dir,
                             "one_replacement.expected")
     thisincr = 10
     backupfile = "{0}.backup.{1}".format(targetfile, thisincr)
     shutil.copy(sample, targetfile)
     tgt = target.Target()
     tgt.targetfile = targetfile
     tgt.edlist.append(
         editor.Editor("replace", 10, ("email", "*****@*****.**")))
     thisincr = mock.Mock()
     thisincr.is_current.return_value = True
     thisincr.__int__ = mock.Mock()
     thisincr.__int__.return_value = 10
     tgt.run_editors(thisincr)
     result = filecmp.cmp(targetfile, expected)
     self.assertTrue(result)
     if not result:
         print >> sys.stderr, "Failed result in {}".format(targetfile)
     else:
         os.unlink(targetfile)
     self.assertTrue(filecmp.cmp(backupfile, sample))
     os.unlink(backupfile)
Esempio n. 2
0
def createTarget(cfg, screen, targets, target_number, row_number):
    target_ = target.Target(cfg, screen)
    target_width = target_.rect.width
    target_.x = target_width + 2 * target_width * target_number
    target_.rect.x = target_.x
    target_.rect.y = target_.rect.height + 2 * target_.rect.height * row_number
    targets.add(target_)
Esempio n. 3
0
 def test_two_replacements(self):
     """Test a target with a two replacement editors
     Basically copied from test_one_replacement, did not bother to factor
     out common code.
     """
     sample = os.path.join(self.test_files_dir, "two_replacements.sample")
     targetfile = os.path.join(self.test_files_dir, "two_replacements.conf")
     expected = os.path.join(self.test_files_dir,
                             "two_replacements.expected")
     thisincr = mock.Mock()
     thisincr.is_current.return_value = True
     thisincr.__int__ = mock.Mock()
     thisincr.__int__.return_value = 22
     backupfile = "{0}.backup.{1}".format(targetfile, int(thisincr))
     shutil.copy(sample, targetfile)
     tgt = target.Target()
     tgt.targetfile = targetfile
     tgt.edlist.append(
         editor.Editor("replace", 22, ("email", "*****@*****.**")))
     tgt.edlist.append(editor.Editor("replace", 22, ("myip", "1.2.3.4")))
     tgt.run_editors(thisincr)
     result = filecmp.cmp(targetfile, expected)
     self.assertTrue(result)
     if not result:
         print >> sys.stderr, "Failed result in {}".format(targetfile)
     else:
         os.unlink(targetfile)
     self.assertTrue(filecmp.cmp(backupfile, sample))
     os.unlink(backupfile)
Esempio n. 4
0
 def __init__(self):
     """Конструктор. Инициализируем необходимые параметры"""
     self.root = tk.Tk()
     self.width = 800
     self.height = 600
     self.floor_height = 100
     self.root.geometry(str(self.width) + 'x' + str(self.height))
     self.canvas = tk.Canvas(self.root, bg='white')
     self.canvas.pack(fill=tk.BOTH, expand=1)
     self.scene = scene.Scene(self.canvas, self.width, self.height,
                              self.floor_height)
     self.targets = targets.Targets(self.scene, target.Target(self.scene),
                                    target.Target(self.scene))
     self.win_screen = self.canvas.create_text(self.width / 2,
                                               self.height / 2,
                                               text='',
                                               font='28')
     self.gun = gun_class.Gun(self.scene)
Esempio n. 5
0
 def test_no_targetfile(self):
     """Make sure exception is raised when targetfile not set"""
     thisincr = 10
     tgt = target.Target()
     self.assertRaises(ValueError, tgt.run_editors, thisincr)
     # see comment about Python 2.7 above
     try:
         tgt.run_editors(thisincr)
     except ValueError as exc:
         self.assertEqual("template error: no mcfg_filename", str(exc))
Esempio n. 6
0
def execute(*args):
    global unordered
    try:
        unordered.clear(root)
    except:
        pass
    unordered = target.Target()
    unordered.draw(root)
    for _ in range(constantes.sticknum):
        unordered.sort(root)
Esempio n. 7
0
def currentDirectoryTarget():
    try:
        t = target.Target(os.getcwd())
    except pack.InvalidDescription as e:
        logging.error(e)
        return None
    if not t:
        logging.error(str(t.error))
        logging.error('The current directory does not contain a valid target.')
        return None
    return t
Esempio n. 8
0
 def test_empty_edlist(self):
     """empty edlist is the trivial case"""
     samplefile = os.path.join(self.test_files_dir, "replace1.in")
     targetfile = os.path.join(
         self.test_files_dir,
         "emptyEdlist.out-" + datetime.datetime.now().isoformat())
     shutil.copy(samplefile, targetfile)
     tgt = target.Target()
     tgt.targetfile = targetfile
     incr = mock.Mock()
     incr.is_current.return_value = True
     tgt.run_editors(incr)
     self.assertTrue(filecmp.cmp(samplefile, targetfile))
     os.unlink(targetfile)
Esempio n. 9
0
def createTargets(cfg, screen, ship, targets, state):
    print('create')
    state.levelAdd()
    target_ = target.Target(cfg, screen)
    number_target_x = getNumberTargetsX(cfg, target_.rect.width)
    number_rows = 0
    if number_rows <= getNumberRows(
            cfg, ship.rect.height,
            target_.rect.height) and (state.level % 3) is 1:
        print(number_rows, state.level % 3)
        number_rows += 1
    for row in range(number_rows):
        for number in range(number_target_x):
            createTarget(cfg, screen, targets, number, row)
Esempio n. 10
0
 def do_addtarget(self, args):
     hostname = raw_input('Target Hostname: ')  #victim host
     try:
         socket.inet_aton(hostname)
     except socket.error:
         print BAD + "Invalid IP Address."
         return
     uname = raw_input('Username: '******'Password: ')  #password for the box to be attacked
     print GOOD + "Target %d Set!" % self.target_num
     t = target.Target(hostname, uname, pword, self.target_num)
     self.targets[self.target_num] = t
     self.target_num += 1
     self.curtarget = t
Esempio n. 11
0
    def __processImportCommandline(self, commandline):
        if len(commandline) < 3:
            self.printUsage()
            return False

        for currArg in commandline[1:]:
            if currArg.lower() in ("/help", "/h", "-help", "--help", "-h"):
                self.printUsage()
                return False
            elif currArg == "--import":
                continue
            elif utilityFunctions.isURL(currArg) or os.path.isfile(
                    currArg) or os.path.isdir(currArg):
                name = target.targetPathToName(currArg)
                if name == "":
                    return False
                currTarget = target.Target(name, currArg)
                self.targetsToImport.append(currTarget)
                continue

            currFlag = currArg[:2].lower()
            currValue = currArg[2:]

            if currFlag in ("-p", "-l", "-n", "-j", "-b", "-w", "-k", "-o",
                            "-g", "-f"):
                logger.writeError(
                    "Command-line option is not allowed in import mode: " +
                    currArg)
                return False
            if currFlag == "-i":
                if not validateOption(currFlag, currValue):
                    return False
                self.interactive = True
            elif currFlag == "-v":
                if not validateOption(currFlag, currValue):
                    return False
                self.verbose = True
            else:
                logger.writeError(
                    "File not found or command-line option not understood: " +
                    currArg)
                return False

        if len(self.targetsToImport) == 0:
            self.printUsage()
            logger.writeError(
                "No packages given when MixDown is in import mode")
            return False

        return True
Esempio n. 12
0
def main():
    pygame.init()
    fpsClock = pygame.time.Clock()
    my_serial = serial.Serial("/dev/ttyACM0")
    my_launcher = launcher.Launcher(0, 400)
    my_rock = rock.Rock(0, 400)
    my_target = target.Target(random.random() * 280 + 100, 390)
    window = pygame.display.set_mode((500, 400))
    pygame.display.set_caption('Lab 2 Stone')
    while (True):
        draw_world(window)
        mag_alt = read_arduino(my_serial)
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    my_launcher.changeAngle(.05236)
                elif event.key == pygame.K_DOWN:
                    my_launcher.changeAngle(-.05236)
                elif event.key == pygame.K_LEFT:
                    my_launcher.changeMagnitude(-3)
                elif event.key == pygame.K_RIGHT:
                    my_launcher.changeMagnitude(3)
                elif event.key == pygame.K_SPACE and not my_rock.isMoving(
                ) and not my_target.hit(my_rock, window):
                    my_launcher.fire(my_rock)
                elif event.key == pygame.K_r:
                    my_serial.write('r')
                elif event.key == pygame.K_g:
                    my_serial.write('g')
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        my_rock.move(1.0 / FPS)
        my_launcher.Alt_Mag(mag_alt)
        if (my_rock.y > 400):
            my_rock.moveto(0, 400, window)
            displaytxt("You Missed!!", window)
        if my_target.hit == True:
            my_rock.moveto(0, 400, window)
            displaytxt("Good Hit!!", window)
            my_target.moveTo(random.random() * 280 + 100, 390)

        my_launcher.draw(window)
        my_rock.draw(window)
        my_target.draw(window)
        pygame.display.update()
        fpsClock.tick(FPS)
Esempio n. 13
0
 def test_replacement_input_missing(self):
     """Call a replacement editor without the target existing"""
     targetfile = os.path.join(self.test_files_dir, "one_replacement.conf")
     thisincr = mock.Mock()
     tgt = target.Target()
     tgt.targetfile = targetfile
     tgt.edlist.append(
         editor.Editor("replace", 10, ("email", "*****@*****.**")))
     self.assertRaises(IOError, tgt.run_editors, thisincr)
     # see comment about Python 2.7 above
     try:
         tgt.run_editors(thisincr)
     except IOError as exc:
         self.assertEqual(
             "Target file {0} does not exist or is not "
             "a regular file".format(targetfile), str(exc))
Esempio n. 14
0
    def visit(self, req):
        t = target.Target(req, self.domain)
        t.links(self.urlNotContains)

        # Main Part
        if self.condition(t, self.require, self.require2):
            self.logger.info('target found')

            self.scrape(t)

            for e in t.data:
                self.logger.debug(e + ': ' + str(t.data[e]))
            t.send_data(self.day)
        else:
            t.not_found(self.day)

        del t
Esempio n. 15
0
def main():
    pygame.init()
    pygame.display.init()
    fpsClock = pygame.time.Clock()  # clock object

    SURF = pygame.display.set_mode((WIDTH, HEIGHT))  # creates game box
    pygame.display.set_caption('Launchr')  # window title

    my_launcher = launcher.Launcher(0, (HEIGHT - 20))
    my_rock = rock.Rock(0, (HEIGHT - 20))
    my_target = target.Target(100 + (random.random() * WIDTH - 100),
                              HEIGHT - 20, TARGET_WIDTH)

    while True:  # main game loop
        for event in pygame.event.get(KEYUP):
            if event.key == pygame.K_UP:
                my_launcher.changeAngle(3)
            if event.key == pygame.K_DOWN:
                my_launcher.changeAngle(-3)
            if event.key == pygame.K_RIGHT:
                my_launcher.changeMagnitude(5)
            if event.key == pygame.K_LEFT:
                my_launcher.changeMagnitude(-5)
            if (event.key == pygame.K_SPACE) and (my_rock.isMoving() == False):
                my_launcher.fire(my_rock)

            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        # game logic
        my_rock.move(1.0 / FPS)
        if (my_rock.y > HEIGHT - 19):
            my_rock.moveTo(0, HEIGHT - 20)
            displayText("You missed!", SURF)
        if my_target.hitBy(my_rock):
            my_rock.moveTo(0, HEIGHT - 20)
            displayText("Got eeeem", SURF)

        # Updates game screen
        draw_world(SURF)
        my_launcher.draw_launcher(SURF)
        my_target.draw_target(SURF)
        my_rock.draw_rock(SURF)
        pygame.display.update()
        fpsClock.tick(FPS)
Esempio n. 16
0
    def do_edittarget(self, args):
        t = self.get_target(args)
        if t == None:
            return
        hostname = raw_input('Target Hostname: ')  #victim host
        try:
            socket.inet_aton(hostname)
        except socket.error:
            print BAD + "Invalid IP Address."
            return
        uname = raw_input('Username: '******'Password: ')  #password for the box to be attacked
        self.target_num -= 1

        print GOOD + "Target %d edited" % self.target_num
        t = target.Target(hostname, uname, pword, self.target_num)
        self.targets[self.target_num] = t
        self.curtarget = t
Esempio n. 17
0
 def test_contradicting_backup(self):
     """Exception must be raised if editor with contradicting backup
     policy on same target
     """
     tgt = target.Target()
     tgt.targetfile = "contradictive"
     tgt.edlist.append(editor.Editor("replace", 10, ("foo", "bar")))
     tgt.edlist.append(
         editor.Editor("copy_file", 10, ("location", "inputFile")))
     self.assertRaises(ValueError, tgt.backup)
     # in Python 2.7 we could have used assertRaises as context manager,
     # in the first place, but we need to support Python 2.6
     # (of course this could be coded differently using try, but the
     # assertRaises conveys the idea what we are doing)
     try:
         tgt.backup()
     except ValueError as exc:
         self.assertEqual( "Editors with incompatible backup policy for " \
                          "contradictive", str(exc))
Esempio n. 18
0
def currentDirectoryModuleOrTarget():
    wd = os.getcwd()
    errors = []
    p = None
    try:
        p = component.Component(wd)
    except pack.InvalidDescription as e:
        errors.append(e)
    if not p:
        try:
            p = target.Target(wd)
        except pack.InvalidDescription as e:
            errors.append(e)
    if not p:
        for e in errors:
            logging.debug(e)
        logging.error(
            'The current directory does not contain a valid module or target.')
        return None
    return p
Esempio n. 19
0
 def take_screenshots(self):
     """
     Runs through the process of taking all screenshots.
     """
     targets = []
     for target_config in self.config.get('targets'):
         current_target = target.Target(self.config, target_config)
         try:
             self.depict(
                 current_target.url,
                 current_target.target_selector,
                 current_target.local_filepath,
                 # Depict's delay argument is defined in milliseconds
                 str(int(current_target.page_load_delay) * 1000),
                 current_target.hide_selector,
                 str(current_target.browser_width)
             )
             targets.append(current_target)
         except RuntimeError as e:
             logging.error(e)
     return targets
Esempio n. 20
0
 def test_copy_file_exists(self):
     """Make sure and editor with backup = False fails if the target
     file exists already before.
     """
     # Just reuse some files from before.
     infile = os.path.join(self.test_files_dir, "two_replacements.sample")
     targetfile = os.path.join(self.test_files_dir,
                               "two_replacements.expected")
     thisincr = mock.Mock()
     tgt = target.Target()
     tgt.targetfile = targetfile
     tgt.edlist.append(
         editor.Editor("copy_file", thisincr, ("location", infile)))
     self.assertRaises(IOError, tgt.run_editors, thisincr)
     # see comment about Python 2.7 above
     try:
         tgt.run_editors(thisincr)
     except IOError as exc:
         self.assertEqual(
             "Target file {0} already "
             "exists".format(targetfile), str(exc))
Esempio n. 21
0
def main():
    X_BEHAVIOUR = "x"
    Y_BEHAVIOUR = "y"
    # create instances of target and pursuer
    pursuer = p.Pursuer()
    target = t.Target()

    # get user input
    num = get_interaction()
    target.x_probability = get_probability()

    # pursuer and target interacting
    for x in range(num):
        target_behaviour = target.interact()
        pursuer_behaviour = pursuer.interact()

        # determine and display result of interaction
        result = pursuer.display_interaction_result(target_behaviour,
                                                    pursuer_behaviour)
        if result == True:
            pursuer.successful_interaction += 1
        elif result == False:
            pursuer.fail_interaction += 1

        # pursuer learns about the target
        if target_behaviour == X_BEHAVIOUR:
            pursuer.observed_x_behaviour += 1
        elif target_behaviour == Y_BEHAVIOUR:
            pursuer.observed_y_behaviour += 1

        # pursuer AI adapts to match the target
        pursuer.x_probability = pursuer.observed_x_behaviour / (
            pursuer.observed_x_behaviour + pursuer.observed_y_behaviour) * 100
        pursuer.y_probability = 100 - pursuer.x_probability

    # display final results after all interactions
    pursuer.display_simluation_result(target)
Esempio n. 22
0
 def __init__(self, templatefile, mcfgfile):
     self.targetlist = []
     template_ini = ConfigParser.SafeConfigParser()
     files = template_ini.read(templatefile)
     if files != [templatefile]:
         # in theory there could also be more than one, but let's keep 
         # the error message simple
         raise IOError, "Template {0} not found".format(templatefile)
     master_ini = ConfigParser.SafeConfigParser()
     files = master_ini.read(mcfgfile)
     if files != [ mcfgfile ] :
         # as above
         raise IOError, "Master config file {0} not found".format(mcfgfile)
     for sec in template_ini.sections():
         tgt = target.Target()
         for (name, value) in template_ini.items(sec):
             if name == self.SPECIAL_FILENAME:
                 tgt.targetfile = value
             else:
                 incr, edname = self.parsevalue(value)
                 edi = editor.Editor(edname, incr,
                                     (name, master_ini.get(sec, name)))
                 tgt.edlist.append(edi)
         self.targetlist.append(tgt)
Esempio n. 23
0
def test_target(use_cuda=False):
    with open("./params/target_params.json", 'r') as f:
        params = json.load(f)
    f.close()
    net = target.Target(**params)
    if use_cuda:
        net = net.cuda()
    dataloader = prepare_fake_data()
    optimizer = optim.Adam(net.parameters(), lr=0.0001)
    for i, sample in enumerate(dataloader):
        sample = Variable(sample)
        if use_cuda:
            sample = sample.cuda()
        optimizer.zero_grad()
        loss = target.loss_func(net, sample, use_cuda)
        loss.backward()
        optimizer.step()

        if i > 0:
            break
    gen = target.generate(net, use_cuda)
    print(gen.size())
    print("Target test finished!")
    print("\n")
Esempio n. 24
0
    """Defining lower and upper threshold values which determine 
detected objects"""
    lower = np.array([70, 33, 173])
    upper = np.array([195, 113, 215])
    """Threshold using lower and upper colors (above)"""
    myDetector.threshold(src, lower, upper)
    myDetector.findContours()
    myDetector.filterContours()
    """Once contours have been found and filtered they can be used"""
    contours = myDetector.getContours()
    mask = myDetector.getMask()
    """Get the thresholded image so it can be displayed"""
    """This only runs if contours were found"""
    if contours is not None:
        """Creating a new object with the contours we found"""
        thisTarget = target.Target(contours)
        """and finding the height and width"""
        height = thisTarget.getHeight()
        width = thisTarget.getWidth()
        """as well as the center of the target."""
        centerX, centerY = thisTarget.getCenter()
        """Once height, width, and center have been found, we can 
calculate the distance
        azimuth, and altitude of our camera relative to the target."""
        myProcessor.calculate(FOCAL_LENGTH, ACTUAL_WIDTH, width, src, centerX,
                              centerY)
        distance = myProcessor.getDistance()
        azimuth = myProcessor.getAzimuth()
        altitude = myProcessor.getAltitude()
        """Printing out all our found info"""
        print("Width of Rect: " + str(width) + " pixels")
Esempio n. 25
0
 def addtarget(self, hostname, uname, pword):
     t = target.Target(hostname, uname, pword, self.target_num)
     self.targets[self.target_num] = t
     self.target_num += 1
     self.curtarget = t
Esempio n. 26
0
# Scout Crooke, 1/6/20, this program plays a target game

import target
import pygame, sys
from pygame.locals import *

pygame.init()

main_surface = pygame.display.set_mode((500, 500), 0, 32)
pygame.display.set_caption("Pygame Demo - So Cool")
main_surface.fill((255, 255, 255))

my_target = target.Target(main_surface)
my_target.draw_target()

num_clicks = 0
while True:
    pygame.display.update()
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == MOUSEBUTTONDOWN and num_clicks < 5:
            num_clicks += 1
            my_target.get_score(pygame.mouse.get_pos())
Esempio n. 27
0
elif args.saved_config is not None:
    if not os.path.isfile(args.saved_config):
        utils.print_message(utils.logtype.ERROR,
                            "Specified configuration file does not exist:",
                            args.saved_config)
        sys.exit(1)

    def_fname = (args.saved_config.split("/")[-1]).split(".")[:-1][0]

    utils.print_message(utils.logtype.INFO,
                        "Using previously saved configuration file:",
                        args.saved_config)

    # initialize target
    t = target.Target(root_path, master_repo_path, "",
                      args.saved_config, "No name",
                      debug_calls, utils, history_path)

    # binaries have to be set by hand
    if t.config.has_section("binaries") is True:
        for b in t.config["binaries"]:
            if t.config.getboolean("binaries", b):
                t.set_binaries(t.config[b]["description"])
                break

    # set the project name
    t.target_name = t.config["project"]["name"]
    # set config path
    t.config_path = root_path + t.config["project"]["path"]

    state = "DO_FETCH"
Esempio n. 28
0
from glob import glob
import os
from matplotlib import pyplot as plt

import utils as ut
import circuit as ct
import target as tg

# Copy from train
nBits = 8
nHidden = 64

#########################################################################

# Actual model
data = tg.Target(nBits=nBits)
ckt = ct.Circuit(nHidden=nHidden, nBits=nBits)

gt = tf.placeholder(dtype=tf.float32)
sig = tf.placeholder(dtype=tf.float32)
hpred, acl = ckt.encode(sig)

enc_t = data.Eval(gt, hpred, acl)[0]

#########################################################################
# Start TF session
sess = tf.Session()
sess.run(tf.global_variables_initializer())

sigs, bits = data.uSamp(100000)
bits = np.sum(bits * np.reshape(2**np.arange(nBits), [1, nBits]), 1)
Esempio n. 29
0
File: game.py Progetto: jdonnal/lab2
def main():
    # start up pygame and build a game window
    pygame.init()
    fpsClock=pygame.time.Clock()
    window = pygame.display.set_mode((WIDTH,HEIGHT),0,32)
    pygame.display.set_caption('Launchr')
    s = serial.Serial("/dev/ttyACM1",timeout=0.5)
    # create custom objects
    my_launcher = launcher.Launcher(0,HEIGHT-20)
    my_rock = rock.Rock(0,HEIGHT-20)
    my_target = target.Target((random.random()*280)+50, HEIGHT-20,
                              TARGET_WIDTH)
    objs = [my_launcher, my_rock, my_target]

    # Main game loop
    while(True):
        # 1 Process Events
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                """arduino controls launcher mag/angle
                if event.key == pygame.K_UP:
                    my_launcher.changeAngle(3)
                if event.key == pygame.K_DOWN:
                    my_launcher.changeAngle(-3)
                if event.key == pygame.K_RIGHT:
                    my_launcher.changeMag(5)
                if event.key == pygame.K_LEFT:
                    my_launcher.changeMag(-5)
                """
                if ((event.key == pygame.K_SPACE) and
                    not my_rock.isMoving()):
                    my_launcher.fire(my_rock)
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        # 2 Update Game State
        # read from arduino
        s.write('p')
        str_data = s.readline()
        if(len(str_data)>0):
            data = [int(x) for x in str_data.split(',')]
            my_launcher.setAngle((data[0]/1024.0)*90)
            my_launcher.setMag((data[1]/1024.0)*100)

        my_rock.move(1.0/FPS) # force floating point division
        if(my_rock.y>HEIGHT):
            # rock is below the screen
            my_rock.moveTo(0,HEIGHT-20)
            s.write('r')
            displayMessage(window,"Miss!")
        if(my_target.hitBy(my_rock.getRect())):
           # rock hit the target!
           my_rock.moveTo(0,HEIGHT-20)
           s.write('g')
           displayMessage(window,"Hit!")
           my_target.moveTo((random.random()*280)+50)

        # 3 Update Display
        drawWorld(window)
        for obj in objs:
            obj.draw(window)
        pygame.display.update()
        fpsClock.tick(FPS)
Esempio n. 30
0
def satisfyTarget(name,
                  version_required,
                  working_directory,
                  update_installed=None):
    ''' returns a Target for the specified version (either to an already
        installed copy (from disk), or to a newly downloaded one), or None if
        the version could not be satisfied.

        update_installed = {None, 'Check', 'Update'}
            None:   prevent any attempt to look for new versions if the
                    target already exists
            Check:  check for new versions, and pass new version information to
                    the target object
            Update: replace any existing version with the newest available, if
                    the newest available has a higher version
    '''

    spec = None
    v = None

    target_path = os.path.join(working_directory, name)
    local_target = target.Target(target_path,
                                 installed_linked=fsutils.isLink(target_path),
                                 latest_suitable_version=v)

    if local_target and (local_target.installedLinked()
                         or update_installed != 'Update'
                         or not local_target.outdated()):
        # if a target exists (has a valid description file), and either is
        # not outdated, or we are not updating
        return local_target

    # if we need to check for latest versions, get the latest available version
    # before checking for a local target so that we can create the local
    # target with a handle to its latest available version
    if update_installed is None:
        logger.debug('attempt to check latest version of %s @%s...' %
                     (name, version_required))
        v = latestSuitableVersion(name, version_required, registry='targets')
    elif local_target and local_target.outdated():
        logger.info('%soutdated: %s@%s -> %s' %
                    (('update ' if update_installed == 'Update' else ''), name,
                     local_target.getVersion(), v))
        # must rm the old target before continuing
        fsutils.rmRf(target_path)

    if not v and update_installed is not None:
        v = latestSuitableVersion(name, version_required, registry='targets')

    if not v:
        raise access_common.TargetUnavailable(
            '"%s" is not a supported specification for a target (the target is %s)'
            % (version_required, name))
    directory = os.path.join(working_directory, name)
    v.unpackInto(directory)
    r = target.Target(directory)
    if not r:
        raise Exception(
            '"%s":"%s" is not a valid target (its description file is invalid)'
            % (name, version_required))
    return r