コード例 #1
0
ファイル: TestEmpty2.py プロジェクト: Cito/w4py-olde-docs
def test(store):
    """Bug report from Stefan Karlsson <*****@*****.**> on Dec 3 2001.

    Obj refs can be incorrectly stored to the database as zeroes for newly created objects.

    """

    from Bar import Bar
    from Foo import Foo
    from BarReq import BarReq

    # Since we're the second empty test, double check that the db is really empty
    assert len(store.fetchObjectsOfClass(Bar)) == 0
    assert len(store.fetchObjectsOfClass(Foo)) == 0

    bar = Bar()
    foo = Foo()
    store.addObject(bar)
    store.addObject(foo)
    bar.setFoo(foo)

    store.saveChanges()

    bars = store.fetchObjectsOfClass(Bar)
    assert len(bars) == 1
    bar2 = bars[0]
    assert bar2 is bar
    assert bar.foo() is not None # the sign of the bug in question
    assert bar.foo() is foo # what we should expect

    store.clear()
    bar = store.fetchObjectsOfClass(Bar)[0]
    assert bar.foo() is not None
コード例 #2
0
 def init_bars(self, num_classes, class_names=None):
     del self.bars[:]  #TO CHECK Python 2 vs Python 3
     if class_names is not None:
         for i in range(num_classes):
             self.bars.append(Bar(self.window, i, class_names[i]))
     else:
         for i in range(num_classes):
             self.bars.append(Bar(self.window, i))
コード例 #3
0
ファイル: EditLine.py プロジェクト: YivDev/illumina
	def __init__(self):
		Bar.__init__(self, "TOP_MOST")
		
		self.__txtText = TextLine()
		self.__txtText.SetParent(self)
		self.__txtText.SetPosition(4, 3)
		self.__txtText.Show()

		self.SetSize(80, 19)
		self.Show()
コード例 #4
0
ファイル: EditLine.py プロジェクト: YivDev/illumina
    def __init__(self):
        Bar.__init__(self, "TOP_MOST")

        self.__txtText = TextLine()
        self.__txtText.SetParent(self)
        self.__txtText.SetPosition(4, 3)
        self.__txtText.Show()

        self.SetSize(80, 19)
        self.Show()
コード例 #5
0
ファイル: Utils.py プロジェクト: jcmdev0/boomslang
def getBarsFromFile(filename, regex, postFunction=None, autofillXValues=False):
    (xValues, yValues) = getXYValsFromFile(filename, regex, postFunction,
                                           autofillXValues)

    bars = []

    for i in xrange(len(yValues)):
        bar = Bar()
        bar.xValues = xValues[:]
        bar.yValues = yValues[i][:]
        bars.append(bar)
    return bars
コード例 #6
0
    def __init__(self, points_to_follow):
        super().__init__()
        # initialize keys dictionary
        self.keys = {
            Qt.Key_W: False,
            Qt.Key_A: False,
            Qt.Key_D: False,
            Qt.Key_S: False
        }
        self.points = points_to_follow
        self.dest = QPointF()
        self.point_index = 0
        self.team = 1

        # set graphics
        self.setPixmap(
            QPixmap('./res/imgs/enemy_3.png').scaled(50, 50,
                                                     Qt.KeepAspectRatio))
        self.setTransformOriginPoint(25, 25)

        self.point_index = 0
        self.dest = self.points[self.point_index]
        self.rotate_to_point(self.dest)

        # connect timer to move forward
        # self.timer = QTimer()
        # self.timer.timeout.connect(self.move_forward)
        # self.timer.start(150)

        # WASD timer
        self.move_timer = QTimer()
        self.move_timer.timeout.connect(self.timer_event)
        self.move_timer.start(1000 / 60)

        # set animations
        self.current_frame = 0
        self.sprite_image = QPixmap('./res/imgs/player-move.png')

        # initialize health bar
        self.health = 100
        self.max_health = 100
        self.health_bar = Bar(self)
        self.health_bar.set_max_val(100)
        self.health_bar.set_current_val(100)

        # create a timer to change the frame
        self.sprite_timer = QTimer()
        self.sprite_timer.timeout.connect(self.nextFrame)
コード例 #7
0
ファイル: TestEmpty.py プロジェクト: Cito/w4py
def setupListTest(store, klass):
    # Create a Foo and a Bar, with the Foo pointing to the Bar
    bar = Bar()
    bar.setX(42)
    foo = Foo()
    foo.setBar(bar)
    store.addObject(foo)
    store.addObject(bar)
    store.saveChanges()

    # create an instance of klass and put it into the list in foo
    obj = klass()
    getattr(foo, 'addToListOf%s' % klass.__name__)(obj)
    store.saveChanges()

    return obj, foo, bar
コード例 #8
0
def setupListTest(store, klass):
    # Create a Foo and a Bar, with the Foo pointing to the Bar
    bar = Bar()
    bar.setX(42)
    foo = Foo()
    foo.setBar(bar)
    store.addObject(foo)
    store.addObject(bar)
    store.saveChanges()

    # create an instance of klass and put it into the list in foo
    obj = klass()
    getattr(foo, 'addToListOf%s' % klass.__name__)(obj)
    store.saveChanges()

    return obj, foo, bar
コード例 #9
0
def test(store):
    """Bug discovered by Chuck Esterbrook on 2002-10-29."""
    from Bar import Bar
    from Qux import Qux

    # import sys; store._sqlEcho = sys.stdout

    # Since we're the second empty test, double check that the db is really empty
    assert len(store.fetchObjectsOfClass(Bar)) == 0
    assert len(store.fetchObjectsOfClass(Qux)) == 0

    qux = Qux()
    store.addObject(qux)
    bar = Bar()
    qux.setBar(bar)
    store.addObject(bar)

    store.saveChanges()
    quxes = store.fetchObjectsOfClass(Qux)
    assert len(quxes) == 1
    qux2 = quxes[0]
    assert qux2 is qux
    assert qux.bar() is not None  # the sign of the bug in question
    assert qux.bar() is bar  # what we should expect

    store.clear()
    qux = store.fetchObjectsOfClass(Qux)[0]
    assert qux.bar() is not None
コード例 #10
0
ファイル: TestEmpty.py プロジェクト: techeye220/w4py
def testAddToBars(store):
    # Test 1: Use addToBars()
    f = Foo()
    store.addObject(f)

    b = Bar()
    f.addToBars(b)
    b.dumpAttrs()
    store.saveChanges()

    store.clear()
    f = store.fetchObjectsOfClass(Foo)[0]
    bars = f.bars()
    assert len(bars) == 1, 'bars=%r' % bars
    assert bars[0].foo() == f
    reset(store)
コード例 #11
0
ファイル: serveur.py プロジェクト: sylvainmetayer/pygame
 def __init__(self, *args, **kwargs):
     Channel.__init__(self, *args, **kwargs)
     pygame.sprite.Sprite.__init__(self)
     self.bar = Bar()
     self.tirCompteurTmp = outils.FREQUENCE_TIR
     self.shotAllowed = True
     self.tir_sprites = Tirs()
     self.joueur = outils.J1
コード例 #12
0
ファイル: Monster.py プロジェクト: Denise-Yang/rosg
 def __init__(self, x, y, r, grid, pLvl):
     self.x, self.y, self.r = x, y, r
     super(Monster, self).__init__()
     self.images = []
     self.index = 0
     self.initImages()
     self.image = self.images[self.index]
     self.sequence = 4
     self.grid = grid
     self.distance = 100
     self.path = []
     self.hp = 10 * int(math.sqrt(pLvl))
     self.hpBar = Bar(self.hp, (255, 0, 0), self.x, self.y - 10, 25, 5)
     self.nodes = self.getNodes()
     self.updateRect()
     self.maxStr = 2 * int(math.sqrt(pLvl))
     self.str = random.randint(0, self.maxStr)
     self.speed = 20
コード例 #13
0
ファイル: Database.py プロジェクト: dkinsbur/PyAlgo
 def day_bars_get(self, symbol, start, end=None):
     with self._connect() as conn:
         cur = conn.cursor()
         SQL = self._make_day_bar_select_command(symbol, start, end)
         print SQL
         cur.execute(SQL)
         return tuple(
             Bar(datetime.strptime(dt, '%Y-%m-%d'), h, l, o, c, v)
             for sym, dt, o, h, l, c, v in cur.fetchall())
コード例 #14
0
def setup():
    background(0)
    global bar
    numberOfBars = 5
    bar = [0] * numberOfBars
    barWidth = width / numberOfBars
    barHeight = 10
    for n in range(numberOfBars):
        bar[n] = Bar(barWidth, height, barHeight, n)
コード例 #15
0
def play_game(utility, DISPLAYSURF):
    fps_clock = pygame.time.Clock()

    pygame.mixer.music.load("./music/game_theme.mp3")
    pygame.mixer.music.play(-1, 2.0)

    player = Bar()
    ball = Ball()

    player.draw(DISPLAYSURF)
    ball.draw(DISPLAYSURF)
    blocks = draw_blocks(utility, DISPLAYSURF)

    while True:  # main game loop
        keys = pygame.key.get_pressed()

        #move bar when right or left arrow is held down or pushed down
        if (keys[pygame.K_RIGHT]):
            player.move(DISPLAYSURF, 3)
        elif (keys[pygame.K_LEFT]):
            player.move(DISPLAYSURF, -3)
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEBUTTONUP:
                print(event.pos)

        ball.move(DISPLAYSURF, player)
        draw_blocks2(utility, DISPLAYSURF, blocks)
        # determine if ball hits a block
        block_collision = utility.getBallNBlockCollision(ball, blocks)

        if block_collision:
            # deduct from that blocks health
            blocks = block_collision.deductHealth(blocks, ball, player,
                                                  DISPLAYSURF)

        if ball.outOfScreen():
            player.reduceLives()
            ball.resetPosition()

        pygame.display.update()
        fps_clock.tick(utility.getFPS())
コード例 #16
0
ファイル: Database.py プロジェクト: dkinsbur/PyAlgo
 def min_bars_get(self, symbol, start, end=None, pre_post_market=True):
     with self._connect() as conn:
         cur = conn.cursor()
         SQL = self._make_min_bar_select_command(symbol, start, end)
         print SQL
         cur.execute(SQL)
         return tuple(
             Bar(datetime.strptime(dt + ' ' +
                                   tm, '%Y-%m-%d %H:%M:%S'), h, l, o, c, v)
             for sym, dt, tm, o, h, l, c, v in cur.fetchall())
コード例 #17
0
    def __init__(self, x, y):
        
        pygame.sprite.Sprite.__init__(self)
        self.size  = 20
        super(Player, self).__init__()
        
        #initialize animation
        self.images = []
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerF1.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerF2.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerF3.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerF4.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerB1.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerB2.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerB3.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerB4.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerL1.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerL2.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerL3.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerL4.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerR1.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerR2.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerR3.png'), (20,20)))
        self.images.append(pygame.transform.scale(pygame.image.load('playeranimation/playerR4.png'), (20,20)))
        self.index, self.dir = 0, 0
        self.image = self.images[self.index]
        self.seq = 4
        self.str = 10
        self.hp = 40
        self.x =  x
        self.y = y
        self.lvlNum = 1

        #initialize stats
        self.hpBar = Bar(self.hp,(255,0,0), 10, 630, 200, 20, "HP")
        self.lvlBar = Lvl(20, (0,255,0), 10, 675, 200, 10, self.lvlNum)
        self.myfont = pygame.font.SysFont(None, 20)
        self.lvlFont  = pygame.font.SysFont('Comic Sans MS', 15)
        self.hpFont = pygame.font.SysFont('Comic Sans MS', 25)
        self.lvlTxt = self.lvlFont.render ("lvl:"+ str(self.lvlNum), False,(255,255,255))
        self.hpTxt = self.hpFont.render ("HP", False,(255,255,255))
        self.speed = 20
        self.updateRect()
コード例 #18
0
 def __init__(self):
     self.health = random.randint(200, 300)
     self.attack = random.randint(10, 20)
     self.inventory = []
     for x in range(0, 10):
         self.bar = Bar()
         self.straw = Straw()
         self.bomb = Bomb()
         self.kiss = Kiss()
         self.inventory = self.inventory + random.sample(
             [self.bomb, self.kiss, self.straw, self.bar], 1)
コード例 #19
0
def setupListTest(store, klass):
    """
	Setup 3 objects: one of the specified klass, pointing to a Foo, pointing to a Bar.
	Returns tuple (object of specified klass, foo, bar).
	"""
    # Create a Foo and a Bar, with the Foo pointing to the Bar
    bar = Bar()
    bar.setX(42)
    foo = Foo()
    foo.setBar(bar)
    store.addObject(foo)
    store.addObject(bar)
    store.saveChanges()

    # create an instance of klass and put it into the list in foo
    object = klass()
    getattr(foo, 'addToListOf%s' % klass.__name__)(object)
    store.saveChanges()

    return object, foo, bar
コード例 #20
0
ファイル: Utils.py プロジェクト: alexras/boomslang
def getBarsFromFile(filename, regex, postFunction=None, autofillXValues=False):
    """
    Turns a regularly-structured file into a collection of
    :class:`boomslang.Bar.Bar` objects.

    For more details on arguments, see :py:func:`getLinesFromFile`.

    Returns a list of :class:`boomslang.Bar.Bar` objects.
    """

    (xValues, yValues) = getXYValsFromFile(filename, regex, postFunction,
                                           autofillXValues)

    bars = []

    for i in xrange(len(yValues)):
        bar = Bar()
        bar.xValues = xValues[:]
        bar.yValues = yValues[i][:]
        bars.append(bar)
    return bars
コード例 #21
0
ファイル: TestEmpty.py プロジェクト: Cito/w4py
def setupListTest(store, klass):
    """Setup list test.

    Setup 3 objects: one of the specified klass, pointing to a Foo,
    pointing to a Bar. Returns tuple (object of specified klass, foo, bar).
    """
    # Create a Foo and a Bar, with the Foo pointing to the Bar
    bar = Bar()
    bar.setX(42)
    foo = Foo()
    foo.setBar(bar)
    store.addObject(foo)
    store.addObject(bar)
    store.saveChanges()

    # create an instance of klass and put it into the list in foo
    obj = klass()
    getattr(foo, 'addToListOf%s' % klass.__name__)(obj)
    store.saveChanges()

    return obj, foo, bar
コード例 #22
0
ファイル: Utils.py プロジェクト: fordhurley/boomslang
def getBarsFromFile(filename, regex, postFunction=None, autofillXValues=False):
    """
    Turns a regularly-structured file into a collection of
    :class:`boomslang.Bar.Bar` objects.

    For more details on arguments, see :py:func:`getLinesFromFile`.

    Returns a list of :class:`boomslang.Bar.Bar` objects.
    """

    (xValues, yValues) = getXYValsFromFile(filename, regex, postFunction,
                                           autofillXValues)

    bars = []

    for i in xrange(len(yValues)):
        bar = Bar()
        bar.xValues = xValues[:]
        bar.yValues = yValues[i][:]
        bars.append(bar)
    return bars
コード例 #23
0
def setupTest(store, klass):
    """
	Setup 3 objects: one of the specified klass, pointing to a Foo, pointing to a Bar.
	Returns tuple (object of specified klass, foo, bar).
	"""
    # Create a Foo and a Bar, with the Foo pointing to the Bar
    bar = Bar()
    bar.setX(42)
    foo = Foo()
    foo.setBar(bar)
    store.addObject(foo)
    store.addObject(bar)
    store.saveChanges()

    # create an instance of klass pointing to Foo
    object = klass()
    object.setFoo(foo)
    store.addObject(object)
    store.saveChanges()

    return object, foo, bar
コード例 #24
0
 def parse_swim(self, filename):
     """ Parse a SWIM trace. """
     self.collect_maxes_swim(filename)
     output_file = self.generate_filename(filename)
     with open(output_file, 'w') as out:
         encounters = {}
         bar = Bar(self.filesize, "Parsing SWIM file")
         with open(filename, 'r') as entrada:
             for i, line in enumerate(entrada):
                 bar.progress()
                 comps = line.strip().split(" ")
                 comps = self.remove_empty(comps)
                 encounter = Encounter(comps[2], comps[3])
                 if str(encounter) in encounters:
                     e = encounters[str(encounter)]
                     self.parsedfilesize += 1
                     out.write("{} {} ".format(comps[2], comps[3]))
                     out.write("{} {} ".format(comps[3], e))
                     out.write("{} ".format(float(comps[0]) - e))
                     out.write("{} {} ".format(comps[4], comps[5]))
                     out.write("{} ".format(comps[6]))
                     out.write("{}\n".format(comps[7]))
                 encounters[str(encounter)] = float(comps[0])
     bar.finish()
     return output_file
コード例 #25
0
ファイル: TestEmpty2.py プロジェクト: techeye220/w4py
def test(store):
    """Bug report from Stefan Karlsson <*****@*****.**> on Dec 3 2001.

    Obj refs can be incorrectly stored to the database as zeroes for newly created objects.
    """

    from Bar import Bar
    from Foo import Foo
    from BarReq import BarReq

    # Since we're the second empty test, double check that the db is really empty
    assert len(store.fetchObjectsOfClass(Bar)) == 0
    assert len(store.fetchObjectsOfClass(Foo)) == 0

    bar = Bar()
    foo = Foo()
    store.addObject(bar)
    store.addObject(foo)
    bar.setFoo(foo)

    store.saveChanges()

    bars = store.fetchObjectsOfClass(Bar)
    assert len(bars) == 1
    bar2 = bars[0]
    assert bar2 is bar
    assert bar.foo() is not None  # the sign of the bug in question
    assert bar.foo() is foo  # what we should expect

    store.clear()
    bar = store.fetchObjectsOfClass(Bar)[0]
    assert bar.foo() is not None
コード例 #26
0
ファイル: Minion.py プロジェクト: lechodiman/iic2233-2017-1
    def __init__(self):
        super().__init__()
        # set graphics
        self.setPixmap(QPixmap('./res/imgs/knight.png'))
        self.setTransformOriginPoint(16, 16)

        # initialize health bar
        h = Bar(self)
        h.set_max_val(45)
        h.set_current_val(45)
        self.set_health(h)

        # set specs
        self.set_speed(3)
        self.set_attack(2)
        self.set_range(25)

        # set destination
        self.destination_timer = QTimer()
        self.destination_timer.timeout.connect(self.set_dest_to_closest)
        self.destination_timer.start(1000 / 30)

        # connect timer to move forward
        self.move_timer = QTimer()
        self.move_timer.timeout.connect(self.move_forward)
        self.move_timer.start(1000 / 30)

        # timer to damage
        self.damage_timer = QTimer()
        self.damage_timer.timeout.connect(self.damage_if_colliding)
        self.damage_timer.start(1000)
コード例 #27
0
ファイル: TestEmpty.py プロジェクト: Cito/w4py
def setupTest(store, klass):
    """Setup test.

    Setup 3 objects: one of the specified klass, pointing to a Foo,
    pointing to a Bar. Returns tuple (object of specified klass, foo, bar).
    """
    # Create a Foo and a Bar, with the Foo pointing to the Bar
    bar = Bar()
    bar.setX(42)
    foo = Foo()
    foo.setBar(bar)
    store.addObject(foo)
    store.addObject(bar)
    store.saveChanges()

    # create an instance of klass pointing to Foo
    obj = klass()
    obj.setFoo(foo)
    store.addObject(obj)
    store.saveChanges()

    return obj, foo, bar
コード例 #28
0
ファイル: Monster.py プロジェクト: Denise-Yang/rosg
 def __init__(self, x, y, r, grid, pLvl):
     super().__init__(x, y, r, grid, pLvl)
     self.image = []
     self.sequence = 2
     self.index = 0
     self.initImages()
     self.image = self.images[self.index]
     self.distance = 80
     self.hp = 100
     self.hpBar = Bar(self.hp, (255, 0, 0), self.x, self.y - 10, 25, 5)
     self.nodes = self.getNodes()
     self.updateRect()
     self.str = 10
コード例 #29
0
ファイル: Tower.py プロジェクト: lechodiman/iic2233-2017-1
    def __init__(self):
        super().__init__()
        # initialize attack range (area)
        self.attack_area = QGraphicsPolygonItem()
        self.attack_dest = QPointF(0, 0)
        self.has_target = False

        # set the graphics
        self.setPixmap(
            QPixmap('./res/imgs/lol_tower.png').scaled(80, 80,
                                                       Qt.KeepAspectRatio))

        # initializes health
        h = Bar(self)
        h.set_max_val(250)
        h.set_current_val(250)
        self.set_health(h)
        self.attack = 30

        # create points vector
        points = [
            QPointF(1, 0),
            QPointF(2, 0),
            QPointF(3, 1),
            QPointF(3, 2),
            QPointF(2, 3),
            QPointF(1, 3),
            QPointF(0, 2),
            QPointF(0, 1)
        ]

        # scale points
        SCALE_FACTOR = 100
        points = [p * SCALE_FACTOR for p in points]
        self.range = SCALE_FACTOR

        # create polygon
        self.polygon = QPolygonF(points)

        # create QGraphicsPolygonItem
        self.attack_area = QGraphicsPolygonItem(self.polygon, self)
        self.attack_area.setPen(QPen(Qt.DotLine))

        # move the polygon
        poly_center = QPointF(1.5 * SCALE_FACTOR, 1.5 * SCALE_FACTOR)
        poly_center = self.mapToScene(poly_center)
        tower_center = QPointF(self.x() + 40, self.y() + 40)
        ln = QLineF(poly_center, tower_center)
        self.attack_area.setPos(self.x() + ln.dx(), self.y() + ln.dy())

        # connect a timer to acquire target
        self.damage_timer = QTimer()
        self.damage_timer.timeout.connect(self.acquire_target)
        self.damage_timer.start(1000)

        # allow responding to hover events
        self.setAcceptHoverEvents(True)
コード例 #30
0
ファイル: serveur.py プロジェクト: sylvainmetayer/pygame
class ClientChannel(Channel, pygame.sprite.Sprite):
    """
    Cette classe gère un client, qui se connecte au serveur, et lui attribue un bar.
    """

    def __init__(self, *args, **kwargs):
        Channel.__init__(self, *args, **kwargs)
        pygame.sprite.Sprite.__init__(self)
        self.bar = Bar()
        self.tirCompteurTmp = outils.FREQUENCE_TIR
        self.shotAllowed = True
        self.tir_sprites = Tirs()
        self.joueur = outils.J1

    def Close(self):
        self._server.del_client(self)

    def Network(self, data):
        pass

    def Network_keys(self, data):
        """
        Cette fonction permet de récupérer les mouvements du client, et de les traiter.
        :param data: Les données reçues du client.
        """
        touches = data['keys']
        if touches[K_RIGHT] or touches[K_d]:
            self.bar.right()
        if touches[K_LEFT] or touches[K_q]:
            self.bar.left()
        if touches[K_SPACE]:
            if self.shotAllowed:
                tir = Tir(self.bar)
                self.tir_sprites.add(tir)
                self.shotAllowed = False
                self.tirCompteurTmp = outils.FREQUENCE_TIR
                self.send_info("sound", "shot.wav")
            else:
                if self.tirCompteurTmp >= 0:
                    self.tirCompteurTmp -= 1
                else:
                    self.shotAllowed = True

    def update_bar(self):
        self.bar.update()
        self.tir_sprites.update(self.joueur)

    def send_info(self, action, message):
        print action + " - " + message
        self.Send({"action": action, "message": message})

    def get_bar(self):
        return self.bar
コード例 #31
0
def createPiece(board):
    """Randomly generates a new piece."""
    # You can comment out parts of this to remove any not-yet-implemented 
    # pieces during testing.
    pieceChoice = randrange(7)
    if pieceChoice == 0:
        return Bar(board)
    elif pieceChoice == 1:
        return Ell(board)
    elif pieceChoice == 2:
        return Jay(board)
    elif pieceChoice == 3:
        return Tee(board)
    elif pieceChoice == 4:
        return RightZig(board)
    elif pieceChoice == 5:
        return LeftZag(board)
    
    # Default to MrChunky
    return MrChunky(board)
コード例 #32
0
    def __init__(self):
        super().__init__()
        # graphics
        self.set_sprite_image(QPixmap('./res/imgs/troll-move.png'))

        # set specs
        h = Bar(self)
        h.set_max_val(666)
        h.set_current_val(666)
        self.set_health(h)

        self.set_speed(3)
        self.set_attack(5)
        self.set_range(40)
        self.set_cooldown(40000)
コード例 #33
0
    def __init__(self):
        super().__init__()
        # graphics
        self.set_sprite_image(QPixmap('./res/imgs/ogrillion-move.png'))

        # set specs
        h = Bar(self)
        h.set_max_val(700)
        h.set_current_val(700)
        self.set_health(h)

        self.set_speed(5)
        self.set_attack(5)
        self.set_range(100)
        self.set_cooldown(10000)
コード例 #34
0
    def extractLocations(self):
        bar = Bar(self.filesize / 2, "Extracting locations")
        with open(self.file, 'r') as entrada:
            for line in entrada:
                split = line.strip().split(" ")
                key = "{} {}".format(split[5], split[6])
                if key not in self.locations:
                    self.locations[key] = self.locationsIndex
                    self.locationsIndex += 1

                key = "{} {}".format(split[7], split[8])
                if key not in self.locations:
                    self.locations[key] = self.locationsIndex
                    self.locationsIndex += 1
                bar.progress()
        bar.finish()
コード例 #35
0
    def extractVenues(self):
        numberVenues = int(self.maxX * self.maxY / (self.r * self.r))
        numberVenues = min(835, numberVenues)

        _set = list(self.locations.keys())
        randomIndex = 0
        venuesIndex = 0
        bar = Bar(numberVenues, "Extracting venues")
        for i in range(0, numberVenues):
            randomIndex = random.randint(0, len(_set) - 1)
            while _set[randomIndex] not in self.locations:
                randomIndex = random.randint(0, len(_set) - 1)
            self.venues[venuesIndex] = _set[randomIndex]
            venuesIndex += 1
            bar.progress()
        bar.finish()
コード例 #36
0
    def __init__(self):
        super().__init__()
        # graphics
        self.set_sprite_image(QPixmap('./res/imgs/player-move.png'))

        # set specs
        h = Bar(self)
        h.set_max_val(500)
        h.set_current_val(500)
        self.set_health(h)

        self.set_speed(5)
        self.set_attack(5)
        self.set_range(100)
        self.set_cooldown(30000)

        self.items_freezed = []
コード例 #37
0
 def __init__(self, manager, editor):
     from ButtonSwitcher import Switcher
     Switcher(manager, editor)
     from Bar import Bar
     Bar(manager, editor)
     from Entry import Entry
     Entry(manager, editor)
     from ComboBox import ComboBox
     ComboBox(manager, editor)
     from MenuButton import Button
     Button(manager, editor)
     from PopupMenu import PopupMenu
     PopupMenu(manager, editor)
     #		from MatchCaseButton import Button
     #		Button(manager, editor)
     from MatchWordButton import Button
     Button(manager, editor)
     #		from MenuComboBox import ComboBox
     #		ComboBox(manager, editor)
     from EntryActivator import Activator
     Activator(manager, editor)
     from PreviousButton import Button
     Button(manager, editor)
     from NextButton import Button
     Button(manager, editor)
     from StopButton import Button
     Button(manager, editor)
     from FindButton import Button
     Button(manager, editor)
     from ReplaceWidgetDisplayer import Displayer
     Displayer(manager, editor)
     from ReplaceEntry import Entry
     Entry(manager, editor)
     from ReplaceButton import Button
     Button(manager, editor)
     from ReplaceAllButton import Button
     Button(manager, editor)
コード例 #38
0
ファイル: Classifier.py プロジェクト: augdomingues/MOCHA
    def best_fit_distribution(self, data, filename, bins=200):
        """ Computes and returns the distribution that best fits the data. """
        y, x = np.histogram(data, bins=bins, density=True)
        x = (x + np.roll(x, -1))[:-1] / 2.0

        DISTRIBUTIONS = [
            st.dweibull, st.expon, st.gamma, st.logistic, st.lognorm, st.norm,
            st.pareto
        ]

        best_distribution = st.norm
        best_params = (0.0, 1.0)
        best_sse = np.inf

        if os.sep in filename:
            metric = filename.split(os.sep)[1]
        else:
            metric = filename

        progressbar = Bar(len(DISTRIBUTIONS), "Fitting {}".format(metric))
        for distribution in DISTRIBUTIONS:
            warnings.filterwarnings('ignore')
            params = distribution.fit(data)
            arg = params[:-2]
            loc = params[-2]
            scale = params[-1]
            pdf = distribution.pdf(x, loc=loc, scale=scale, *arg)
            sse = np.sum(np.power(y - pdf, 2.0))
            sse = -2 * math.log(sse) + 2 * (len(params) + 1)
            if sse < best_sse:
                best_distribution = distribution
                best_params = params
                best_sse = sse

            print(" SSE of {} is {}(Current best: {})".format(
                distribution.name, round(sse, 2), round(best_sse, 2)),
                  end="")
            progressbar.progress()

        print(" Fit to {} with params [{}]".format(best_distribution.name,
                                                   best_params),
              end="")
        progressbar.finish()
        return (best_distribution.name, best_params)
コード例 #39
0
    def __init__(self):
        super().__init__()

        # set the graphics
        self.setPixmap(
            QPixmap('./res/imgs/lol_inhibitor_2.png').scaled(
                50, 50, Qt.KeepAspectRatio))

        # initializes health
        h = Bar(self)
        h.set_max_val(600)
        h.set_current_val(600)
        self.set_health(h)

        # initializes signal (when it dies)
        self.s = InhibitorSignal()

        # allow responding to hover events
        self.setAcceptHoverEvents(True)
コード例 #40
0
	def main(self):
		pygame.init()
		self.connectServer()
		self.bar=Bar()
		self.board = wiiboard.Wiiboard()
		self.address = self.board.discover()
		#self.address ="00:1F:C5:AA:4F:6D"
		self.board.connect(self.address) #The wii board must be in sync mode at this time
		time.sleep(0.1)
		self.board.setLight(True)
		self.sysfont = pygame.font.SysFont(None, 80)
		self.screen = pygame.display.set_mode((self.width,self.height))
		# タイトルバーの文字列をセット
		pygame.display.set_caption(u"Wii Board Controller")
		self.screenUpdate()
		send=False
		done = False
		validity=False
		while (not done):
			time.sleep(1./30.)
			self.screenUpdate()
			while(len(self.recvQueue)>0):
				e=self.recvQueue[0]
				del self.recvQueue[0]
				if(e[0]=="bar_config"):
					self.barInit=True
					self.bar.width=float(e[1]["width"])
					self.bar.region=[float(e[1]["region"][0]),float(e[1]["region"][1])]
					self.bar.calib=[float(e[1]["calib"][0]),float(e[1]["calib"][1])]
					print "bar width initialized"
			for event in pygame.event.get():
				if event.type == KEYDOWN:  # キーを押したとき
					# ESCキーならスクリプトを終了
					if event.key == K_s:
						if(self.barInit):
							self.sendArrow=not self.sendArrow
						else:
							self.sendArrow=False
					elif(event.key==K_b):
						self.barInit=True
					elif event.key==K_c:
						self.board.calibrate()
					elif event.key==K_o:
						self.client.sendData("px_ready",["Manager"],True)
					elif event.key==K_p:
						self.client.sendData("px_ready",["Manager"],False)
					elif event.key == K_q:
						done=True
				if event.type == wiiboard.WIIBOARD_MASS:
					if (event.mass.totalWeight > 10):
						self.cogX = ((event.mass.topRight + event.mass.bottomRight) - (event.mass.topLeft + event.mass.bottomLeft))/(event.mass.totalWeight)
					        self.cogY = ((event.mass.topRight + event.mass.topLeft) - (event.mass.bottomRight + event.mass.bottomLeft))/(event.mass.totalWeight)
						validity=True
						#print "COG (x,y)=("+`self.cogX`+","+`self.cogY`+")"
					else:
						validity=False
						self.cogX = 0.
					        self.cogY = 0.
				elif event.type == wiiboard.WIIBOARD_BUTTON_PRESS:
					print "Button pressed!"
	
				elif event.type == wiiboard.WIIBOARD_BUTTON_RELEASE:
					print "Button released"
					self.board.calibrate()
#					done = True
				elif event.type == QUIT:
					print "Quit"
					done=True
							
				#Other event types:
				#wiiboard.WIIBOARD_CONNECTED
				#wiiboard.WIIBOARD_DISCONNECTED
			if(self.client.isConnected and self.sendArrow):
				if(self.cogX>1):
					self.cogX=1.0
				elif(self.cogX<-1.0):
					self.cogX=-1.0
				if(validity):
					self.bar.calculate(self.client,self.cogX)
					print "send : cog=X",self.cogX,",pos=",self.bar.position
		self.board.disconnect()
		pygame.quit()
コード例 #41
0
class Controller:
	def __init__(self):
		self.cogX=0.
		self.cogY=0.
		self.clickPos=(0,0)
		self.width=480
		self.height=480
		self.recvQueue=[]
		self.sendArrow=False
		self.pushed=False
		self.barInit=False
	def screenUpdate(self):
		self.screen.fill((255,255,255))
		pygame.draw.line(self.screen, (0,0,0), (0,self.height/2), (self.width,self.height/2))
		pygame.draw.line(self.screen, (0,0,0), (self.width/2,0), (self.width/2,self.height))
		pygame.draw.circle(self.screen, (255,0,0), (int(0.5*(1+self.cogX)*self.width),int((1-0.5*(1+self.cogY))*self.height)), 5)
		#pygame.draw.circle(self.screen, (255,255,0), self.clickPos, 5)
		send="Enabled" if self.sendArrow else "Disabled"
		if(self.barInit):
			drawText(self.screen,"S key: Enable/Disable Sending (Now "+send+")",True,(0,0,0),(30,20),fontSize=24)
		else:
			drawText(self.screen,"S key: Enable/Disable Sending (Now Waiting bar_width)",True,(0,0,0),(30,20),fontSize=24)
		drawText(self.screen,"C key: Calibrate (or push Board button)",True,(0,0,0),(30,40),fontSize=24)
		drawText(self.screen,"Q key: Quit",True,(0,0,0),(30,60),fontSize=24)
		pygame.display.update()  # 画面を更新
	def connectServer(self):
		self.client=SioClient()
		#受信するイベント名一覧をリストとしてclientに渡す
		eventList=["bar_width"];
		self.client.setEventList(eventList)
		#自身を表す部屋名を設定する(Game Serverなら例えば"Game"と決める)
		self.client.setMyRoom("Controller")
		#受信データを格納するキューを追加する
		self.client.setDataQueue(self.recvQueue)
		#URLを指定して接続開始
		#self.client.start("http://ailab-mayfestival2016-base.herokuapp.com")
		self.client.start("http://192.168.1.58:8000")
		#self.client.start("http://localhost:8000")
	def main(self):
		pygame.init()
		self.connectServer()
		self.bar=Bar()
		self.board = wiiboard.Wiiboard()
		self.address = self.board.discover()
		#self.address ="00:1F:C5:AA:4F:6D"
		self.board.connect(self.address) #The wii board must be in sync mode at this time
		time.sleep(0.1)
		self.board.setLight(True)
		self.sysfont = pygame.font.SysFont(None, 80)
		self.screen = pygame.display.set_mode((self.width,self.height))
		# タイトルバーの文字列をセット
		pygame.display.set_caption(u"Wii Board Controller")
		self.screenUpdate()
		send=False
		done = False
		validity=False
		while (not done):
			time.sleep(1./30.)
			self.screenUpdate()
			while(len(self.recvQueue)>0):
				e=self.recvQueue[0]
				del self.recvQueue[0]
				if(e[0]=="bar_config"):
					self.barInit=True
					self.bar.width=float(e[1]["width"])
					self.bar.region=[float(e[1]["region"][0]),float(e[1]["region"][1])]
					self.bar.calib=[float(e[1]["calib"][0]),float(e[1]["calib"][1])]
					print "bar width initialized"
			for event in pygame.event.get():
				if event.type == KEYDOWN:  # キーを押したとき
					# ESCキーならスクリプトを終了
					if event.key == K_s:
						if(self.barInit):
							self.sendArrow=not self.sendArrow
						else:
							self.sendArrow=False
					elif(event.key==K_b):
						self.barInit=True
					elif event.key==K_c:
						self.board.calibrate()
					elif event.key==K_o:
						self.client.sendData("px_ready",["Manager"],True)
					elif event.key==K_p:
						self.client.sendData("px_ready",["Manager"],False)
					elif event.key == K_q:
						done=True
				if event.type == wiiboard.WIIBOARD_MASS:
					if (event.mass.totalWeight > 10):
						self.cogX = ((event.mass.topRight + event.mass.bottomRight) - (event.mass.topLeft + event.mass.bottomLeft))/(event.mass.totalWeight)
					        self.cogY = ((event.mass.topRight + event.mass.topLeft) - (event.mass.bottomRight + event.mass.bottomLeft))/(event.mass.totalWeight)
						validity=True
						#print "COG (x,y)=("+`self.cogX`+","+`self.cogY`+")"
					else:
						validity=False
						self.cogX = 0.
					        self.cogY = 0.
				elif event.type == wiiboard.WIIBOARD_BUTTON_PRESS:
					print "Button pressed!"
	
				elif event.type == wiiboard.WIIBOARD_BUTTON_RELEASE:
					print "Button released"
					self.board.calibrate()
#					done = True
				elif event.type == QUIT:
					print "Quit"
					done=True
							
				#Other event types:
				#wiiboard.WIIBOARD_CONNECTED
				#wiiboard.WIIBOARD_DISCONNECTED
			if(self.client.isConnected and self.sendArrow):
				if(self.cogX>1):
					self.cogX=1.0
				elif(self.cogX<-1.0):
					self.cogX=-1.0
				if(validity):
					self.bar.calculate(self.client,self.cogX)
					print "send : cog=X",self.cogX,",pos=",self.bar.position
		self.board.disconnect()
		pygame.quit()
コード例 #42
0
ファイル: EditLine.py プロジェクト: YivDev/illumina
	def __del__(self):
		Bar.__del__(self)
コード例 #43
0
class Controller:
	def __init__(self):
		self.cogX=0.
		self.cogY=0.
		self.clickPos=(0,0)
		self.width=480
		self.height=480
		self.recvQueue=[]
		self.sendArrow=False
		self.pushed=False
		self.barInit=False
	def screenUpdate(self):
		self.screen.fill((255,255,255))
		pygame.draw.line(self.screen, (0,0,0), (0,self.height/2), (self.width,self.height/2))
		pygame.draw.line(self.screen, (0,0,0), (self.width/2,0), (self.width/2,self.height))
		pygame.draw.circle(self.screen, (255,0,0), (int(0.5*(1+self.board.cogX)*self.width),int((1-0.5*(1+self.board.cogY))*self.height)), 5)
		#pygame.draw.circle(self.screen, (255,255,0), self.clickPos, 5)
		send="Enabled" if self.sendArrow else "Disabled"
		if(self.barInit):
			drawText(self.screen,"S key: Enable/Disable Sending (Now "+send+")",True,(0,0,0),(30,20),fontSize=24)
		else:
			drawText(self.screen,"S key: Enable/Disable Sending (Now Waiting bar_width)",True,(0,0,0),(30,20),fontSize=24)
		drawText(self.screen,"C key: Calibrate (or push Board button)",True,(0,0,0),(30,40),fontSize=24)
		drawText(self.screen,"Q key: Quit",True,(0,0,0),(30,60),fontSize=24)
		pygame.display.update()  # 画面を更新
	def connectServer(self):
		self.client=SioClient()
		#受信するイベント名一覧をリストとしてclientに渡す
		eventList=["bar_width","bar_config"];
		self.client.setEventList(eventList)
		#自身を表す部屋名を設定する(Game Serverなら例えば"Game"と決める)
		self.client.setMyRoom("Controller")
		#受信データを格納するキューを追加する
		self.client.setDataQueue(self.recvQueue)
		#URLを指定して接続開始
		#self.client.start("http://ailab-mayfestival2016-base.herokuapp.com")
		self.client.start("http://192.168.1.58:8000")
		#self.client.start("http://localhost:8000")
	def updateCallback(self):
		self.board=self.wii.getBoardState()
		if(self.wii.isPressed("A")):
			self.pushed=True
		else:
			if(self.pushed):
				self.wii.calibrate()
			self.pushed=False
		
	def main(self):
		pygame.init()
		self.connectServer()
		self.bar=Bar()
		self.wii=WiiRemote.WiiRemote()
		self.wii.setUpdateCallback(self.updateCallback)
		self.wii.connect()
		self.board = self.wii.getBoardState()
		self.wii.startListening()
		self.wii.setDataReportingMode(True,0x31)
		self.wii.requestStatus()
		time.sleep(0.1)
		self.wii.setLED(0x0F)
		led=0x0F
		
		print "make window"
		#self.sysfont = pygame.font.SysFont(None, 80)
		self.screen = pygame.display.set_mode((self.width,self.height))
		pygame.display.update()
		pygame.display.set_caption(u"Wii Board Controller")
		self.screenUpdate()
		done = False
		validity=False
		print "MainLoop"
		while (not done):
			time.sleep(1./30.)
			self.screenUpdate()
			while(len(self.recvQueue)>0):
				e=self.recvQueue[0]
				del self.recvQueue[0]
				if(e[0]=="bar_config"):
					self.barInit=True
					self.bar.width=float(e[1]["width"])
					self.bar.region=[float(e[1]["region"][0]),float(e[1]["region"][1])]
					self.bar.calib=[float(e[1]["calib"][0]),float(e[1]["calib"][1])]
					print "bar width initialized"
			for event in pygame.event.get():
				if event.type == KEYDOWN:  # キーを押したとき
					# ESCキーならスクリプトを終了
					if event.key == K_s:
						if(self.barInit):
							self.sendArrow=not self.sendArrow
						else:
							self.sendArrow=False
					elif(event.key==K_b):
						self.barInit=True
					elif event.key==K_c:
						self.wii.calibrate()
					elif event.key==K_o:
						self.client.sendData("px_ready",["Manager"],True)
					elif event.key==K_p:
						self.client.sendData("px_ready",["Manager"],False)
					elif event.key == K_q:
						done=True
				elif event.type == QUIT:
					print "Quit"
					done=True
			if(self.client.isConnected and self.sendArrow and self.board.calibrated):
				if(self.board.cogX>1):
					self.board.cogX=1.0
				elif(self.board.cogX<-1.0):
					self.board.cogX=-1.0
				#self.client.sendData("controller",["Game"],self.board.cogX)
				#self.client.sendData("controller",["Game"],self.board.cogX)
				if(self.board.totalWeight>10.):
					self.bar.calculate(self.client,self.board.cogX)
					print "send : cog=X",self.board.cogX,",pos=",self.bar.position,"total=",self.board.totalWeight
		#self.wii.disconnect()
		self.wii.endListening()
		pygame.quit()
コード例 #44
0
	def main(self):
		pygame.init()
		self.connectServer()
		self.bar=Bar()
		self.wii=WiiRemote.WiiRemote()
		self.wii.setUpdateCallback(self.updateCallback)
		self.wii.connect()
		self.board = self.wii.getBoardState()
		self.wii.startListening()
		self.wii.setDataReportingMode(True,0x31)
		self.wii.requestStatus()
		time.sleep(0.1)
		self.wii.setLED(0x0F)
		led=0x0F
		
		print "make window"
		#self.sysfont = pygame.font.SysFont(None, 80)
		self.screen = pygame.display.set_mode((self.width,self.height))
		pygame.display.update()
		pygame.display.set_caption(u"Wii Board Controller")
		self.screenUpdate()
		done = False
		validity=False
		print "MainLoop"
		while (not done):
			time.sleep(1./30.)
			self.screenUpdate()
			while(len(self.recvQueue)>0):
				e=self.recvQueue[0]
				del self.recvQueue[0]
				if(e[0]=="bar_config"):
					self.barInit=True
					self.bar.width=float(e[1]["width"])
					self.bar.region=[float(e[1]["region"][0]),float(e[1]["region"][1])]
					self.bar.calib=[float(e[1]["calib"][0]),float(e[1]["calib"][1])]
					print "bar width initialized"
			for event in pygame.event.get():
				if event.type == KEYDOWN:  # キーを押したとき
					# ESCキーならスクリプトを終了
					if event.key == K_s:
						if(self.barInit):
							self.sendArrow=not self.sendArrow
						else:
							self.sendArrow=False
					elif(event.key==K_b):
						self.barInit=True
					elif event.key==K_c:
						self.wii.calibrate()
					elif event.key==K_o:
						self.client.sendData("px_ready",["Manager"],True)
					elif event.key==K_p:
						self.client.sendData("px_ready",["Manager"],False)
					elif event.key == K_q:
						done=True
				elif event.type == QUIT:
					print "Quit"
					done=True
			if(self.client.isConnected and self.sendArrow and self.board.calibrated):
				if(self.board.cogX>1):
					self.board.cogX=1.0
				elif(self.board.cogX<-1.0):
					self.board.cogX=-1.0
				#self.client.sendData("controller",["Game"],self.board.cogX)
				#self.client.sendData("controller",["Game"],self.board.cogX)
				if(self.board.totalWeight>10.):
					self.bar.calculate(self.client,self.board.cogX)
					print "send : cog=X",self.board.cogX,",pos=",self.bar.position,"total=",self.board.totalWeight
		#self.wii.disconnect()
		self.wii.endListening()
		pygame.quit()
コード例 #45
0
ファイル: TestEmpty1.py プロジェクト: Cito/w4py-olde-docs
def test(store):
    from Foo import Foo
    from Bar import Bar
    from BarReq import BarReq

    # Create a Foo and a Bar that refers to it
    f = Foo()
    f.setX(3)

    store.addObject(f)
    store.saveChanges()

    b = Bar()
    b.setFoo(f)
    store.addObject(b)
    store.saveChanges()

    # Test fetching
    store.clear()
    results = store.fetchObjectsOfClass(Bar)
    assert len(results)
    b = results[0]
    f1 = b.foo()
    f2 = b.foo()
    assert f1 is not None, 'got None instead of a Foo'
    assert f1 is f2 # test uniqueness
    assert b.foo().x() == 3

    # Fetch in reverse order
    store.clear()
    f = store.fetchObjectsOfClass(Foo)[0]
    b = store.fetchObjectsOfClass(Bar)[0]
    assert b.foo() is f

    # Test None, set, save and retrieve
    b.setFoo(None)
    store.saveChanges()
    store.clear()
    b = store.fetchObjectsOfClass(Bar)[0]
    assert b.foo() is None

    # Test the assertions in setFoo()
    b = BarReq()
    try:
        b.setFoo(None)
    except Exception:
        pass
    else:
        NoException('b.setFoo(None) # None not allowed')

    try:
        b.setFoo('x')
    except Exception:
        pass
    else:
        NoException('b.setFoo("x") # wrong type not allowed')

    try:
        b.setFoo(Bar())
    except Exception:
        pass
    else:
        NoException('b.setFoo(Bar()) # wrong class not allowed')
コード例 #46
0
ファイル: TestEmpty.py プロジェクト: Cito/w4py
def test(store):
    # We invoke testAddToBars twice on purpose, just to see that
    # the second time around, things are stable enough to pass again
    testAddToBars(store)
    testAddToBars(store)

    # Test 2: do not use addToBars()
    f = Foo()
    store.addObject(f)
    b = Bar()
    b.setFoo(f)
    b.setX(7)
    store.addObject(b)
    store.saveChanges()
    store.clear()

    f = store.fetchObjectsOfClass(Foo)[0]
    assert f._mk_store
    assert f._mk_inStore
    bars = f.bars()
    assert isinstance(bars, list)
    assert len(bars) == 1, 'bars=%r' % bars
    assert bars[0].x() == 7

    # Test addToXYZ() method
    bar = Bar()
    bar.setX(42)
    f.addToBars(bar)
    assert bar.foo() == f
    store.saveChanges()
    store.clear()

    f = store.fetchObjectsOfClass(Foo)[0]
    bars = f.bars()
    assert isinstance(bars, list)
    assert len(bars) == 2, 'bars=%r' % bars
    assert bars[0].x() == 7
    assert bars[1].x() == 42

    # Test the assertion checking in addToXYZ()
    try:
        f.addToBars(None)
    except Exception:
        pass
    else:
        NoException('f.addToBars(None)  # None not allowed')

    try:
        f.addToBars(5)
    except Exception:
        pass
    else:
        NoException('f.addToBars(5)  # not an object')

    try:
        f.addToBars(f)
    except Exception:
        pass
    else:
        NoException('f.addToBars(f)  # wrong class')

    try:
        f.addToBars(bar)
    except Exception:
        pass
    else:
        NoException('f.addToBars(bar)  # already added')

    # Test delFromXYZ() method
    bar = bars[1]
    f.delFromBars(bar)
    assert len(bars) == 1
    assert bar.foo() is None
    store.saveChanges()
    store.clear()

    f = store.fetchObjectsOfClass(Foo)[0]
    bars = f.bars()
    assert isinstance(bars, list)
    assert len(bars) == 1, 'bars=%r' % bars
    assert bars[0].x() == 7

    # Test the assertion checking in delFromXYZ()
    try:
        f.delFromBars(None)
    except Exception:
        pass
    else:
        NoException('f.delFromBars(None)  # None not allowed')

    try:
        f.delFromBars(5)
    except Exception:
        pass
    else:
        NoException('f.delFromBars(5)  # not an object')

    try:
        f.delFromBars(f)
    except Exception:
        pass
    else:
        NoException('f.delFromBars(f)  # wrong class')

    try:
        f.delFromBars(bar)
    except Exception:
        pass
    else:
        NoException('f.delFromBars(bar)  # already deleted')