示例#1
0
文件: fcp.py 项目: verolero86/pcircle
def fcp_start():
    global circle, fcp, treewalk

    workq = None  # if fresh start, workq is None

    if not args.rid: # if not in recovery
        treewalk = FWalk(circle, G.src, G.dest, force=args.force)
        circle.begin(treewalk)
        circle.finalize()
        G.totalsize = treewalk.epilogue()
    else:  # okay, let's do checkpoint recovery
        workq = prep_recovery()

    circle = Circle()
    fcp = FCP(circle, G.src, G.dest,
              treewalk=treewalk,
              totalsize=G.totalsize,
              verify=args.verify,
              workq=workq,
              hostcnt=num_of_hosts)

    if comm.rank == 0 and G.verbosity > 0:
        rcl, wcl = fcp.rw_cache_limit()
        print("")
        print("\t{:<25}{:<10}{:5}{:<25}{:<10}".format("Read Cache:", "%s" % rcl, "|",
                                                      "Write Cache:", "%s" % wcl))
        print("")
    set_chunksize(fcp, G.totalsize)
    fcp.checkpoint_interval = args.cptime
    fcp.checkpoint_file = ".pcp_workq.%s.%s" % (args.cpid, circle.rank)

    circle.begin(fcp)
    circle.finalize()
    fcp.cleanup()
示例#2
0
	def __init__(self):
		position = Point(random.randint(0,config.SCREEN_X),random.randint(0,config.SCREEN_Y))
		radius = config.STAR_RADIUS
		rotation = 0
		random_color = random.randint(0, 255)
		color = (random_color, random_color , random_color)
		Circle.__init__(self, position, radius, color, rotation)
示例#3
0
文件: fcp.py 项目: fwang2/pcircle
def fcp_start():
    global circle, fcp, treewalk

    workq = None  # if fresh start, workq is None

    if not args.rid: # if not in recovery
        treewalk = FWalk(circle, G.src, G.dest, force=args.force)
        circle.begin(treewalk)
        circle.finalize()
        treewalk.epilogue()
    else:  # okay, let's do checkpoint recovery
        workq = prep_recovery()

    circle = Circle(dbname="fcp")
    fcp = FCP(circle, G.src, G.dest,
              treewalk=treewalk,
              totalsize=T.total_filesize,
              verify=args.verify,
              workq=workq,
              hostcnt=num_of_hosts)

    set_chunksize(fcp, T.total_filesize)
    fcp.checkpoint_interval = args.cptime
    fcp.checkpoint_file = ".pcp_workq.%s.%s" % (args.cpid, circle.rank)

    circle.begin(fcp)
    circle.finalize()
    fcp.epilogue()
示例#4
0
文件: mygroup.py 项目: btownshend/crs
class MyGroup(Group):
    """Represents a group on the floor.

    Create a group as a subclass of the basic data element.

    Stores the following values:
        m_color: color of cell

    """

    def __init__(self, field, id, gsize=None, duration=None, x=None, y=None,
                 diam=None, color=None):
        if color is None:
            self.m_color = DEF_GROUPCOLOR
        else:
            self.m_color = color
        self.m_shape = Circle()
        super(MyGroup, self).__init__(field, id, gsize, duration, x, y, diam)

    def update(self, gsize=None, duration=None, x=None, y=None,
                 diam=None, color=None):
        """Store basic info and create a DataElement object"""
        if color is not None:
            self.m_color = color
        super(MyGroup, self).update(gsize, duration, x, y, diam)

    def draw(self):
        if self.m_x is not None and self.m_y is not None:
            self.m_shape.update(self.m_field, (self.m_x, self.m_y),
                                self.m_diam/2, self.m_color, solid=False)
            self.m_shape.draw()
示例#5
0
def test_set_area():
    c = Circle(4)
    try:
        c.area = 10
    except AttributeError as error:
        assert error.message == "can't set attribute"
    else:
        assert False
class Controller:
    def __init__(self):
        self.circle = Circle(width/2, height/2, 100)
    def draw(self):
        background(0, 0, 0)
	stroke(50, 50, 200) # set stroke color bluish
        self.circle.draw()
        self.circle.move(0.25,0.25)
def test_area2():
	"""
	area should change if radius changes 
	"""
	c = Circle(4)

	c.radius = 2

	assert c.get_area() == math.pi * 4
示例#8
0
def test_change_diameter():
    c = Circle(2)

    assert c.radius == 2
    assert c.diameter == 4

    c.diameter = 6
    assert c.radius == 3
    assert c.diameter == 6
def initial_trilateration(p0, p1, distance_matrix):
    points = [p0, p1]
    for target_number in range(2, distance_matrix.shape[0]):
        d0t = distance_matrix[0][target_number]
        c0t = Circle(p0, d0t)
        d1t = distance_matrix[1][target_number]
        c1t = Circle(p1, d1t)
        points.append(c0t.positive_intersection_with(c1t))
    return points
示例#10
0
def main():
    global comm, args
    args = parse_and_bcast(comm, gen_parser)

    try:
        G.src = utils.check_src(args.path)
    except ValueError as e:
        err_and_exit("Error: %s not accessible" % e)

    G.use_store = args.use_store
    G.loglevel = args.loglevel

    hosts_cnt = tally_hosts()

    if comm.rank == 0:
        print("Running Parameters:\n")
        print("\t{:<20}{:<20}".format("FWALK version:", __version__))
        print("\t{:<20}{:<20}".format("Num of hosts:", hosts_cnt))
        print("\t{:<20}{:<20}".format("Num of processes:", MPI.COMM_WORLD.Get_size()))
        print("\t{:<20}{:<20}".format("Root path:", utils.choplist(G.src)))

    circle = Circle()
    treewalk = FWalk(circle, G.src)
    circle.begin(treewalk)

    if G.use_store:
        treewalk.flushdb()

    if args.stats:
        hist = global_histogram(treewalk)
        total = hist.sum()
        bucket_scale = 0.5
        if comm.rank == 0:
            print("\nFileset histograms:\n")
            for idx, rightbound in enumerate(bins[1:]):
                percent = 100 * hist[idx] / float(total)
                star_count = int(bucket_scale * percent)
                print("\t{:<3}{:<15}{:<8}{:<8}{:<50}".format("< ",
                    utils.bytes_fmt(rightbound), hist[idx],
                    "%0.2f%%" % percent, '∎' * star_count))

    if args.stats:
        treewalk.flist.sort(lambda f1, f2: cmp(f1.st_size, f2.st_size), reverse=True)
        globaltops = comm.gather(treewalk.flist[:args.top])
        if comm.rank == 0:
            globaltops = [item for sublist in globaltops for item in sublist]
            globaltops.sort(lambda f1, f2: cmp(f1.st_size, f2.st_size), reverse=True)
            if len(globaltops) < args.top:
                args.top = len(globaltops)
            print("\nStats, top %s files\n" % args.top)
            for i in xrange(args.top):
                print("\t{:15}{:<30}".format(utils.bytes_fmt(globaltops[i].st_size),
                      globaltops[i].path))

    treewalk.epilogue()
    treewalk.cleanup()
    circle.finalize()
示例#11
0
文件: mycell.py 项目: btownshend/crs
 def __init__(self, field, id, x=None, y=None, vx=None, vy=None, major=None,
              minor=None, gid=None, gsize=None, color=None):
     if color is None:
         self.m_color = DEF_LINECOLOR
     else:
         self.m_color = color
     self.m_body_color = DEF_BODYCOLOR
     self.m_shape = Circle()
     self.m_bodyshape = Circle()
     super(MyCell, self).__init__(field, id, x, y, vx, vy, major, minor,
                                  gid, gsize)
示例#12
0
    def define (self, dwg):

        for element in range(0,1000):
            circle = Circle()
            line = Line()
            parabola = Parabola()
            splash = Splash()
            circle.define(dwg)
            line.define(dwg)
            parabola.define(dwg)
            splash.define(dwg)
示例#13
0
 def test_circle_distance_from_frame(self):
     '''
     Test overlap between circles and frame.
     '''
     new_circle = Circle(20)
     new_circle.set_position(160, 160)
     self.assertAlmostEqual(200 - math.sqrt(2)*20 - 20,
                            new_circle.get_distance_from_frame(200), 2) 
     new_circle.set_position(420, 180)
     self.assertAlmostEqual(-60, new_circle.get_distance_from_frame(200), 2)
     new_circle.set_position(180 + 1 / math.sqrt(2) * 180, 
                             180 + 1 / math.sqrt(2) * 180)
     self.assertAlmostEqual(0, new_circle.get_distance_from_frame(200), 2)
示例#14
0
def test_nonsense_diameter():
    """
    Make sure we can't create a Circle object with a negative or zero 
    diameter.
    """
    with pytest.raises(ValueError):
        c = Circle.from_diameter(-2.468)
    with pytest.raises(ValueError):
        c = Circle.from_diameter(0)
    c = Circle.from_diameter(2.468)
    with pytest.raises(ValueError):
        c.diameter = -2.468
    with pytest.raises(ValueError):
        c.diameter = 0
示例#15
0
def test_nonsense_radius():
    """
    Make sure we can't create a Circle object with a negative or zero 
    radius.
    """
    with pytest.raises(ValueError):
        c = Circle(-1.234)
    with pytest.raises(ValueError):
        c = Circle(0)
    c = Circle(1.234)
    with pytest.raises(ValueError):
        c.radius = -1.234 
    with pytest.raises(ValueError):
        c.radius = 0
示例#16
0
class MyApp(PygameApp):
    """
    Custom version of PygameApp, to display moving circle
    """
    def __init__(self, screensize = (400,400)):
        """
        Application initialization is executed only ONCE!
        """
        super().__init__(screensize = screensize, title="My Test Application") # call base class initializer
        pygame.key.set_repeat(100)              # allow keys to repeat when held 100 msec
        self.setbackgroundcolor((220,220,220))  # set a new background color
        self.circ = Circle(self.spritegroup)    # create a default circle

    def handle_event(self, event):
        """
        Override the base class event handler. Based on mouse and keyboard input make adjustments
        to the Circle object or make copies of it.
        """
        if event.type == MOUSEMOTION:
            self.circ.setpos(event.pos)
        elif event.type == MOUSEBUTTONDOWN:
            if event.button == 4:                   # scroll UP "button"
                self.circ.setradius(self.circ.radius+1)
            elif event.button == 5:                 # scroll DOWN "button"
                self.circ.setradius(self.circ.radius-1)
            elif event.button == 1:
                newcirc = self.circ.copy()          # "drop" a copy of the current circle
                newcirc.setcolor((255,0,0,200))
                newcirc.setthickness(1)
                newcirc.update()                    # force update and display
        elif event.type == KEYDOWN:                 # keyboard
            circpos = self.circ.pos
            if event.key == K_UP:                   # cursor up
                circpos = (circpos[0],circpos[1]-1) # calculate a new position
            elif event.key == K_DOWN: # cursor down
                circpos = (circpos[0],circpos[1]+1) # calculate a new position
            self.circ.setpos(circpos)             # update the position
        else:
            print (pygame.event.event_name(event.type))   # view unhandled events on the console
            
        return True                                 # Keep going!

    def quit(self):
        """
        Override default quit behavior here, if desired
        """
        pass

    def poll(self):
        """
        Override default poll behavior here, if desired
        """
        pass
示例#17
0
class TestGetArea(unittest.TestCase):
  def setUp(self):
    self.radius = 3.0
    self.circle = Circle(self.radius)

  def test_get_area(self):
    self.assertEqual(self.circle.getArea(), math.pi * self.radius * self.radius)
示例#18
0
    def load(self, host="localhost", port=6499):
        print "Tuner.load " + str(port)

        # Recalibrate page
        self.recalibrate = Recalibrate(changefunc=self.onChange, host=host,
                                       port=port)
        self.tabs.addTab( self.recalibrate.get_widget(), "Recalibrate" )

        # Preflight page
        self.preflight = Preflight(changefunc=self.onChange, host=host,
                                   port=port)
        self.tabs.addTab( self.preflight.get_widget(), "Preflight" )

        # Launch page
        self.launch = Launch(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab( self.launch.get_widget(), "Launch" )

        # Circle hold page
        self.circle = Circle(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab( self.circle.get_widget(), "Circle" )

        # Chirp page
        self.chirp = Chirp(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab( self.chirp.get_widget(), "Chirp" )

        # Land page
        self.land = Land(changefunc=self.onChange, host=host, port=port)
        self.tabs.addTab( self.land.get_widget(), "Land" )
示例#19
0
class TestGetRadius(unittest.TestCase):
  def setUp(self):
    self.radius = 3.0
    self.circle = Circle(self.radius)

  def test_get_radius(self):
    self.assertEqual(self.circle.getRadius(), self.radius)
示例#20
0
 def __init__(self, screensize = (400,400)):
     """
     Application initialization is executed only ONCE!
     """
     super().__init__(screensize = screensize, title="My Test Application") # call base class initializer
     pygame.key.set_repeat(100)              # allow keys to repeat when held 100 msec
     self.setbackgroundcolor((220,220,220))  # set a new background color
     self.circ = Circle(self.spritegroup)    # create a default circle
示例#21
0
文件: mygroup.py 项目: btownshend/crs
 def __init__(self, field, id, gsize=None, duration=None, x=None, y=None,
              diam=None, color=None):
     if color is None:
         self.m_color = DEF_GROUPCOLOR
     else:
         self.m_color = color
     self.m_shape = Circle()
     super(MyGroup, self).__init__(field, id, gsize, duration, x, y, diam)
示例#22
0
def main():
    global comm, args
    args = parse_and_bcast(comm, gen_parser)

    try:
        G.src = utils.check_src2(args.path)
    except ValueError as e:
        err_and_exit("Error: %s not accessible" % e)

    G.loglevel = args.loglevel

    hosts_cnt = tally_hosts()

    if comm.rank == 0:
        print("Running Parameters:\n")
        print("\t{:<20}{:<20}".format("fprof version:", __version__))
        print("\t{:<20}{:<20}".format("Num of hosts:", hosts_cnt))
        print("\t{:<20}{:<20}".format("Num of processes:", MPI.COMM_WORLD.Get_size()))
        print("\t{:<20}{:<20}".format("Root path:", G.src))

    circle = Circle()
    treewalk = ProfileWalk(circle, G.src, perfile=args.perfile)
    circle.begin(treewalk)

    gen_histogram()

    # we need the total file size to calculate GPFS efficiency
    total_file_size = treewalk.epilogue()

    if args.gpfs_block_alloc:
        gpfs_blocks = gather_gpfs_blocks()
        if comm.rank == 0:
            print("\nGPFS Block Alloc Report:\n")
            print("\tSubblocks: %s\n" % gpfs_blocks)
            for idx, bsz in enumerate(G.gpfs_block_size):
                gpfs_file_size = gpfs_blocks[idx] * G.gpfs_subs[idx]
                fmt_msg = "\tBlocksize: {:<6}   Estimated Space: {:<20s}   Efficiency: {:>6.0%}"
                if gpfs_file_size != 0:
                    print(fmt_msg.format(bsz, bytes_fmt(gpfs_file_size), total_file_size/float(gpfs_file_size)))
                else:
                    print(fmt_msg.format(bsz, bytes_fmt(gpfs_file_size), 0))

    treewalk.cleanup()
    circle.finalize()
class Controller:
    def __init__(self):
        self.circlea = Circle(PVector(width/2, height/2), 100, PVector(1, 1))
        self.circleb = Circle(PVector(width/2, height/2), 100, PVector(3, 3))
    
    def draw(self):
        background(0, 0, 0)
        self.circlea.draw()
        self.circleb.draw()
        self.circlea.move()
        self.circleb.move()
class Controller:
    def __init__(self):                            # sx, sy
        self.circlea = Circle(width/2, height/2, 100, 1, 1)
        self.circleb = Circle(width/2, height/2, 100, 3, 3)
        
    def draw(self):
        background(0, 0, 0)
        self.circlea.draw()
        self.circleb.draw()
        self.circlea.move()
        self.circleb.move()
 def test_intersection(self):
    first = Circle()
    second = Circle((2.0, 0.0), 1.2)
    third = Circle((12.0, 0.0), 1.2)
    self.assertTrue(first.intersects(first))
    self.assertTrue(first.intersects(second))
    self.assertTrue(second.intersects(first))
    self.assertFalse(first.intersects(third))
    self.assertFalse(second.intersects(third))
def trilateration_phase(points_in, distance_matrix):
    points_out = [points_in[0]]  # force point 0 to stay at origin
    for target_idx in range(1, len(points_in)):
        approximations = []  # points which are approximate 'target' 
        # we want pairs of circles which intersect at target. Will have circle A and circle B.
        for source_a_idx, source_b_idx in itertools.combinations(range(0, len(points_in)), 2):
            # ensure the centre of the circle isn't target. 
            # It must be defined by another point and target
            if (source_a_idx != target_idx) and (source_b_idx != target_idx):
                a_center = points_in[source_a_idx]
                a_rad = distance_matrix[source_a_idx][target_idx]
                a = Circle(a_center, a_rad)
                b_center = points_in[source_b_idx]
                b_rad = distance_matrix[source_b_idx][target_idx]
                b = Circle(b_center, b_rad)
                intersections = a.intersection_with(b)
                approximations.append(points_in[target_idx].get_closest(intersections))
        approximation = get_centroid(approximations)
        points_out.append(approximation)
    return points_out
class CircleTester(unittest.TestCase):
    def setUp(self):
        self.c0 = Circle(point.Point(4, 0.5), 5)
        self.c1 = Circle(point.Point(1, -1), 4)

    def test_intersection(self):
        intersection = self.c0.intersection_with(self.c1)
        # as per: http://www.calcul.com/circle-circle-intersection
        p0 = point.Point(3.0825543469976, -4.4151086939952)
        p1 = point.Point(-0.48255434699759, 2.7151086939952)
        expected = [p0, p1]
        self.assertAlmostEqual(intersection[0].x, expected[0].x)
        self.assertAlmostEqual(intersection[0].y, expected[0].y)
        self.assertAlmostEqual(intersection[1].x, expected[1].x)
        self.assertAlmostEqual(intersection[1].y, expected[1].y)

    def test_positive_intersection(self):
        intersection = self.c0.positive_intersection_with(self.c1)
        expected = point.Point(-0.48255434699759, 2.7151086939952)
        self.assertAlmostEqual(intersection.x, expected.x)
        self.assertAlmostEqual(intersection.y, expected.y)
示例#28
0
文件: mycell.py 项目: btownshend/crs
class MyCell(Cell):
    """Represents one person/object on the floor.

    Create a cell as a subclass of the basic data element.

    Stores the following values:
        m_color: color of cell

    makeBasicShape: create the set of arcs that will define the shape

    """

    def __init__(self, field, id, x=None, y=None, vx=None, vy=None, major=None,
                 minor=None, gid=None, gsize=None, color=None):
        if color is None:
            self.m_color = DEF_LINECOLOR
        else:
            self.m_color = color
        self.m_body_color = DEF_BODYCOLOR
        self.m_shape = Circle()
        self.m_bodyshape = Circle()
        super(MyCell, self).__init__(field, id, x, y, vx, vy, major, minor,
                                     gid, gsize)

    def update(self, x=None, y=None, vx=None, vy=None, major=None,
               minor=None, gid=None, gsize=None, color=None, visible=None,
               frame=None):
        """Store basic info and create a DataElement object"""
        if color is not None:
            self.m_color = color
        super(MyCell, self).update(x, y, vx, vy, major, minor, gid, gsize,
                                   visible=visible, frame=frame)

    def draw(self):
        if self.m_x is not None and self.m_y is not None:
            self.m_shape.update(self.m_field, (self.m_x, self.m_y),
                                self.m_diam/2,
                                color=self.m_color,
                                solid=False)
            self.m_field.m_osc.send_laser(OSCPATH['graph_begin_cell'],[self.m_id])
            self.m_shape.draw()
            if DRAW_BODIES:
                self.m_bodyshape.update(self.m_field, (self.m_x, self.m_y),
                                          self.m_body_diam/2, 
                                          color=self.m_body_color,
                                          solid=True)
                self.m_bodyshape.draw()
            self.m_field.m_osc.send_laser(OSCPATH['graph_end_cell'],[self.m_id])
示例#29
0
def test_get_diameter():
    c = Circle(4)
    assert c.diameter == 2 * 4
示例#30
0
def test_repr():
    c = Circle(4)
    assert c.__repr__() == 'Circle(4)'
示例#31
0
def test_mult_circles0():
    c = Circle(2)
    c *= 3
    return c.radius == Circle(12).radius
示例#32
0
def test_gt():
    c1 = Circle(2)
    c2 = Circle(4)
    assert not (c1 > c2)
示例#33
0
def test_area():
	circle = Circle(2)
	assert circle.area == math.pi * 4
	circle = Circle(1)
	assert circle.area == math.pi
示例#34
0
def test_set_diameter():
    c = Circle(4)
    c.diameter = 2
    assert c.diameter == 2
    assert c.radius == 1
示例#35
0
def test_default_radius():
	circle = Circle()
	assert circle.radius == 1
示例#36
0
文件: main.py 项目: ferchovzla/python
from circle import Circle
from square import Square
from triangle import Triangle

print("***Calcular area, perimetro del Circulo ***\n")
radius = float(input("Ingrese el valor del radio del circulo: "))

myCircle = Circle(radius)

print("Area = " + str(myCircle.area))
print("Perimetro = " + str(myCircle.perimeter) + "\n")

print("***Calcular area, perimetro del Cuadrado ***\n")
lenght = float(input("Ingrese el valor del lado del cuadrado: "))

mySquare = Square(lenght)
print("Area = " + str(mySquare.area))
print("Perimetro = " + str(mySquare.perimeter) + "\n")

print("***Calcular area, perimetro del Rectangulo ***\n")
lenght = float(input("Ingrese el valor del largo del rectangulo: "))
width = float(input("Ingrese el valor del ancho del rectangulo: "))

myRectangle = Square(lenght, width)
print("Area = " + str(myRectangle.area))
print("Perimetro = " + str(myRectangle.perimeter) + "\n")

print("***Calcular area, perimetro del Triangulo ***\n")
lenght_side_a = float(input("Ingrese el valor del lado A del triangulo: "))
lenght_side_b = float(input("Ingrese el valor del lado B del triangulo: "))
base = float(input("Ingrese el valor de la base del triangulo: "))
from circle import Circle
from circle import Sphere
from math import pi

c = Circle(5)
s = Sphere(3)


def test_radius():

    assert c.radius == 5


def test_diameter():

    assert c.diameter == 10


def test_area():

    assert c.area == pi * 25


def test_str():

    assert str(c) == 'Circle with a radius: 5.000000'


def test_repr():

    assert repr(5) == "Circle(5)"
示例#38
0
def test_eq0():
    c1 = Circle(2)
    c2 = Circle(4)
    c3 = Circle(4)
    assert (c2 == c3)
示例#39
0
def test_get_area():
    c = Circle(2)
    assert c.area == 2 * math.pi * 2
示例#40
0
def test_set_area():
    c = Circle(4)

    with pytest.raises(AttributeError):
        c.area = 44
def main():
    # set up pygame and window
    pygame.init()
    bg_color = WHITE
    screen.fill(bg_color)

    # variables for determining if red/green light is on
    start_value = random.randrange(
        1, 10)  # random determination if red or green starts
    if start_value % 2 == 0:
        green_on = True
        red_on = False
    else:
        green_on = False
        red_on = True

    change_light = True
    tot_seconds = 0  # start value

    # timer
    start_ticks = pygame.time.get_ticks()

    # player dot
    player = Circle(radius=20,
                    color=(0, 50, 255),
                    pos=Vec2(400, 600),
                    mass=float('inf'))
    goal = Circle(radius=20,
                  color=(255, 0, 0),
                  pos=Vec2(400, 100),
                  mass=float('inf'))
    objects.append(player)
    objects.append(goal)

    # game loop
    running = True

    idle = True  # set idle state to true initially

    # clock within pygame
    clock = pygame.time.Clock()
    fps = 60
    dt = 1 / fps

    screen.fill(bg_color)
    for o in objects:
        o.update(dt)
        o.draw(screen)
    pygame.display.flip()

    idle_lights()
    pir.wait_for_motion()
    countdown()

    while running:
        seconds = (pygame.time.get_ticks() - start_ticks) / 1000
        screen.fill(bg_color)

        if tot_seconds < seconds:  # once we surpass the time limit for the light, set to true and swap lights
            change_light = True

        if change_light:
            num_seconds = random.randrange(
                3,
                10)  # random duration between 3 and 10 seconds for each light
            tot_seconds = seconds + num_seconds  # number to reach before
            print("wait for: ", num_seconds)
            print("target time: ", tot_seconds)
            print("green: ", green_on)
            print("red: ", red_on)
            if green_on:  # if green light is on, turn it off and turn red on
                GREEN.off()
                RED.on()
                green_on = False
                red_on = True
            else:
                GREEN.on()
                RED.off()
                red_on = False
                green_on = True
            change_light = False  # don't go in this if statement while we're counting

        #if pir.motion_detected:
        #   print("motion")
        #else:
        #   print("no motion")

        for o in objects:
            o.update(dt)
            o.draw(screen)

        if button.is_pressed:
            player.pos.y -= 1

        if green_on and pir.motion_detected:
            player.pos.y -= 1

        if red_on and pir.motion_detected:
            move_player(player)

        distanceFromGoal = player.pos - goal.pos
        if distanceFromGoal.mag() < 39:
            print("You win!")
            running = False

        for e in pygame.event.get():
            # user clicks closed button
            if e.type == pygame.QUIT:
                running = False

        pygame.display.flip()
        clock.tick(fps) / 1000
    RED.off()
    GREEN.off()
    pygame.quit()
示例#42
0
def test_radius():
	circle = Circle(5)
	assert circle.radius == 5
示例#43
0
def test_add_circles():
    c1 = Circle(2)
    c2 = Circle(4)
    c = c1 + c2
    return c.radius == 4
示例#44
0
def test_no_negative_radius():
	circle = Circle(2)
	with pytest.raises(ValueError):
		circle.radius = -10
示例#45
0
def test_augmented_mult():
    a_circle = Circle(4)
    a_circle *= 2
    assert a_circle.r == 8
示例#46
0
def test_mult_circles1():
    c = Circle(2)
    return (3 * c) == Circle(12)
示例#47
0
def test_str():
    c = Circle(4)
    assert c.__str__() == "Circle with radius: 4.000000"
示例#48
0
def test_augmented_add():
    a_circle = Circle(2)
    another_circle = Circle(4)
    a_circle += another_circle
    assert a_circle.r == 6
示例#49
0
def test_dynamic_radius():
	circle = Circle(2)
	assert circle.diameter == 4
	circle.diameter = 3
	assert circle.radius == 1.5
示例#50
0
import pygame
from random import randint
from circle import Circle
from player import Player
from enemy import Enemy
from pygame.locals import *
# import locals for mypy assist?

pygame.init()

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

my_circle = Circle([SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2])
player = Player([100, 100], 50, 50)

enemies = pygame.sprite.Group()

for num in range(0, 5):
    enemies.add(
        Enemy([randint(0, SCREEN_WIDTH),
               randint(0, SCREEN_HEIGHT)], 30, (210, 142, 12)))

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running == False
示例#51
0
def test_diameter_changes():
	circle = Circle(2)
	assert circle.diameter == 4
	circle.radius = 3
	assert circle.diameter == 6
示例#52
0
def test_create_with_diameter():
    c = Circle.from_diameter(8)
    assert c.diameter == 8
    assert c.radius == 4
示例#53
0
# -*- coding: utf-8 -*-
"""
Created on Tue Mar  2 18:26:18 2021

@author: antons.sincovs

"""

from circle import Circle

c1 = Circle((1, 5), 4)
c2 = Circle()
print(c1)
print(type(c1))

print("c1: ", c1.get_center(), c1.get_radius())
print("c2: ", c2.get_center(), c2.get_radius())

c1.move((10, 11))
c1.grow()

print("c1: ", c1.get_center(), c1.get_radius())

print("c1 area", c1.get_area(), "circumference: ", c1.get_circumference())
print("c2 area", c2.get_area(), "circumference: ", c2.get_circumference())
print(str(c1))
print(c1)

print("c1 x:", c1.get_x(), "y:", c1.get_y())

print("Distance between c1 and c2: ", c1.distance(c2))
示例#54
0
def test_get_radius():
    c = Circle(5)
    assert c.radius == 5
示例#55
0
def main():
    global comm, args
    args = parse_and_bcast(comm, gen_parser)

    try:
        G.src = utils.check_src(args.path)
    except ValueError as e:
        err_and_exit("Error: %s not accessible" % e)

    G.use_store = args.use_store
    G.loglevel = args.loglevel

    hosts_cnt = tally_hosts()

    if comm.rank == 0:
        print("Running Parameters:\n")
        print("\t{:<20}{:<20}".format("FWALK version:", __version__))
        print("\t{:<20}{:<20}".format("Num of hosts:", hosts_cnt))
        print("\t{:<20}{:<20}".format("Num of processes:",
                                      MPI.COMM_WORLD.Get_size()))
        print("\t{:<20}{:<20}".format("Root path:", utils.choplist(G.src)))

    circle = Circle()
    treewalk = FWalk(circle, G.src)
    circle.begin(treewalk)

    if G.use_store:
        treewalk.flushdb()

    if args.stats:
        hist = global_histogram(treewalk)
        total = hist.sum()
        bucket_scale = 0.5
        if comm.rank == 0:
            print("\nFileset histograms:\n")
            for idx, rightbound in enumerate(bins[1:]):
                percent = 100 * hist[idx] / float(total)
                star_count = int(bucket_scale * percent)
                print("\t{:<3}{:<15}{:<8}{:<8}{:<50}".format(
                    "< ", utils.bytes_fmt(rightbound), hist[idx],
                    "%0.2f%%" % percent, '∎' * star_count))

    if args.stats:
        treewalk.flist.sort(lambda f1, f2: cmp(f1.st_size, f2.st_size),
                            reverse=True)
        globaltops = comm.gather(treewalk.flist[:args.top])
        if comm.rank == 0:
            globaltops = [item for sublist in globaltops for item in sublist]
            globaltops.sort(lambda f1, f2: cmp(f1.st_size, f2.st_size),
                            reverse=True)
            if len(globaltops) < args.top:
                args.top = len(globaltops)
            print("\nStats, top %s files\n" % args.top)
            for i in xrange(args.top):
                print("\t{:15}{:<30}".format(
                    utils.bytes_fmt(globaltops[i].st_size),
                    globaltops[i].path))

    treewalk.epilogue()
    treewalk.cleanup()
    circle.finalize()
示例#56
0
def test_reflected_numerics():
    a_circle = Circle(2)
    assert (a_circle * 3) == (3 * a_circle)
示例#57
0
def test_lt():
    c1 = Circle(2)
    c2 = Circle(4)
    assert (c1 < c2)
示例#58
0
def test_set_area():
    c = Circle(2)
    with pytest.raises(AttributeError):
        c.area = 42
示例#59
0
def test_alternate_constructor():
  c = Circle.from_diameter(8)

  assert c.diameter == 8
  assert c.radius == 4
示例#60
0
def test_eq0():
    c1 = Circle(2)
    c2 = Circle(4)
    assert (c1 != c2)