示例#1
0
 def testAgregar(self):
     print 'Test de agregar bar.\n'
     bar0 = Bar('Barcito', 'Av. Callao 493', 4, 'El bar mas bonito.', 1)
     bar1 = Bar('Tragos', 'Araoz 1274', 2,
                'Ambientes tranquilo para estudiar.', 0)
     bar2 = Bar('Hola Mundo', 'Avellaneda 621', 1, 'Todos son bienvenidos.',
                1)
     bar3 = Bar('Las Tortas', 'Av. Corrientes 948', 4,
                'Nuestra comida es la mejor de la ciudad.', 1)
     self.listaBares.agregarBar(bar0)
     self.listaBares.agregarBar(bar1)
     self.listaBares.agregarBar(bar2)
     self.listaBares.agregarBar(bar3)
     print 'bar 1:', bar0, '\nbar 2:', bar1, '\nbar 3:', bar2, '\nbar 4:', bar3, '\n'
     bares = self.listaBares.inhabilitados()
     i = 0
     for bar in bares:
         if i == 0 and bar == bar0:
             print 'Bar 1 se agrega correctamente.'
         elif i == 1 and bar == bar1:
             print 'Bar 2 se agrega correctamente.'
         elif i == 2 and bar == bar2:
             print 'Bar 3 se agrega correctamente.'
         elif i == 3 and bar == bar3:
             print 'Bar 4 se agrega correctamente.'
         else:
             print 'Alguno de los bares no fue agregado correctamente.'
         i += 1
示例#2
0
    def test_null(self):
        with TestDatabase.db.transaction() as t:
            TestDatabase.db.upsert(Bar(999, 90, 120.0, 'C'))

            bars = TestDatabase.db.select(Bar(999))

            self.assertEqual(len(bars), 1)
            self.assertEqual(
                    str(bars[0]), "bar : Keys {'id': 999} : Values {'heading': 90, 'speed': 120.0, 'signal': 'C'}")

            # force a rollback
            t.fail()
示例#3
0
 def spawnBar(self):
     h = random.randrange(100, 450, 25)
     color = (random.randrange(1, 256), random.randrange(1, 256), random.randrange(1, 256))
     bar = Bar(550, 0, 50, h, color)
     bar.accelerate(20)
     self.mBars.append(bar)
     color2 = (random.randrange(1, 256), random.randrange(1, 256), random.randrange(1, 256))
     randy = h + 100
     botbar = Bar(550, randy, 50, 500-randy, color)
     botbar.accelerate(20)
     self.mbotBars.append(botbar)
     return
示例#4
0
    def test_transaction(self):
        # test commit
        with TestDatabase.db.transaction():
            TestDatabase.db.upsert(Bar(101, 180, 33.5, 'A'))
            TestDatabase.db.upsert(Bar(102, 270, 50.33, 'B'))
        bars = TestDatabase.db.select(Bar())
        self.assertEqual(len(bars), 4)

        # test rollback on exception
        with TestDatabase.db.transaction(), \
                self.assertRaises(DatabaseIntegrityError) as cm:
            TestDatabase.db.upsert(Foo('a new foo', ))
        self.assertEqual(cm.exception.args[0], 'NOT NULL constraint failed: foo.desc')
        self.assertEqual(len(bars), 4)

        # test a forced rollback
        with TestDatabase.db.transaction() as t:
            TestDatabase.db.upsert(
                    Bar(104, 355, 99.99, 'D'))
            t.fail()
        bars = TestDatabase.db.select(Bar())
        self.assertEqual(len(bars), 4)

        # restore table to pre-test state
        with TestDatabase.db.transaction():
            TestDatabase.db.delete(Bar(101))
            TestDatabase.db.delete(Bar(102))
        bars = TestDatabase.db.select(Bar())
        self.assertEqual(len(bars), 2)
示例#5
0
 def init(self):
     self.width, self.height = self.screen.get_size()
     bar_width = 0.03 * self.width
     bar_height = 0.3 * self.height
     self.bars = [
         Bar(0.1 * self.width, (self.height - bar_height) / 2, bar_width,
             bar_height, self.height, (255, 0, 0)),
         Bar(0.9 * self.width - bar_width, (self.height - bar_height) / 2,
             bar_width, bar_height, self.height, (0, 0, 255))
     ]
     self.balls = []
     self.score = [0, 0]
     self.last_spawn_y = 0.1
     for i in range(4 + 2 * self.difficulty):
         self.create_ball()
示例#6
0
    def restart_menu(self):
        self.progressBar = []
        for i in range(15):
            self.progressBar.append(pygame.image.load(f'img/marking_{i}.png'))

        self.students = []
        for i in range(3):
            self.students.append(
                random.choice(
                    self.student_type).clone(wish=random.randint(10, 40)))
        self.active_students = []

        self.curr_coctail = None
        self.spots = {
            (90, 525): self.alcs['Пиво'],
            (0, 525): self.alcs['Водка']
        }
        self.spot_size = (80, 150)

        self.game_over = False
        self.free_places = frozenset({1: None, 2: None, 3: None})
        self.places = {1: (100, 100), 2: (300, 100), 3: (500, 100)}
        self.bar = Bar(list(self.alcs.values()))
        self.player = Player(self.bar)
        self.menu()
示例#7
0
    def parse(file_path):
        tree = ElementTree.parse(file_path)
        score = tree.getroot()

        lines = []
        for line in score.findall('line'):
            bars = []
            for bar in line.findall('bar'):
                units = []
                time_signature = bar.get('time_signature')
                for unit in bar.findall('unit'):
                    notes = []
                    for note in unit.findall('note'):
                        pitch = note.get('pitch')
                        hold_str = note.get('hold')
                        hold = {'True': True, 'False': False}[hold_str]
                        print(pitch)
                        notes.append(Note(pitch, hold))
                    beats = unit.get('beats')
                    units.append(Unit(notes, Fraction(beats)))
                key = bar.get('key')
                bars.append(Bar(key, time_signature, units))
            lines.append(bars)

        title = score.get('title')
        author = score.get('author')

        return Score(lines, title, author)
示例#8
0
def run():
    pygame.init()

    # load the game settings
    settings = Settings()

    # create the screen and add a title
    screen = pygame.display.set_mode(settings.screen_dimension)
    pygame.display.set_caption('BreakOut - Python')

    # create the game elements
    bar = Bar(screen, settings)
    chances = Chances(screen, settings)
    score = Score(screen, settings)
    ball = Ball(screen, bar, settings, chances, score)
    btn_start = Button(screen, 'press space to start')
    btn_game_over = Button(screen, 'Game Over')

    object_group = []
    function.dispose_objects(screen, object_group, score)

    while True:
        function.check_events(bar, settings, chances, score)
        function.update_screen(bar, screen, ball, settings, object_group,
                               btn_start, btn_game_over, chances, score)
示例#9
0
	def get_last_bars(self, ticker, length, time_segment):
		if length == 250:
			return [Bar({"t": 0,"o": 400.0,"h": 550.0,"l": 340.0,"c": 500.0,"v": 100})]

		bars_copy = copy.copy(self.bars[ticker])
		del self.bars[ticker][0]
		return bars_copy[0]
示例#10
0
    def _create_sprites(self, path):
        ''' Create all of the sprites we'll need '''
        self.smiley_graphic = svg_str_to_pixbuf(
            svg_from_file(os.path.join(path, 'smiley.svg')))

        self.frown_graphic = svg_str_to_pixbuf(
            svg_from_file(os.path.join(path, 'frown.svg')))

        self.egg_graphic = svg_str_to_pixbuf(
            svg_from_file(os.path.join(path, 'Easter_egg.svg')))

        self.blank_graphic = svg_str_to_pixbuf(
            svg_header(REWARD_HEIGHT, REWARD_HEIGHT, 1.0) + \
            svg_rect(REWARD_HEIGHT, REWARD_HEIGHT, 5, 5, 0, 0,
                     '#C0C0C0', '#282828') + \
            svg_footer())

        self.ball = Ball(self.sprites, os.path.join(path, 'basketball.svg'))
        self.current_frame = 0

        self.bar = Bar(self.sprites, self.width, self.height, self.scale,
                       self.ball.width())
        self.current_bar = self.bar.get_bar(2)

        self.ball_y_max = self.bar.bar_y() - self.ball.height()
        self.ball.move_ball((int(
            (self.width - self.ball.width()) / 2), self.ball_y_max))
示例#11
0
def main():
    if path.exists("wp_plugins.txt"):
        w = open("wp_plugins.txt", 'r')
        #w=lista de todos los plugins del fichero
        w = w.read().split('\n')
        #lista=lista de los plugins encontrados
        lista = []
        url = "https://www.nationalarchives.gov.uk"
        with Bar("Espere...", count=len(w)) as b:

            for plugin in w:
                b.step()
                try:
                    p = requests.get(url=url + "/" + plugin)
                    # si la url formada existe
                    if p.status_code == 200:
                        final = url + "/" + plugin
                        lista.append(final.split("/")[-2])
                except:
                    pass
            b.exit()
        for plugin in lista:
            print("Plugin encontrado: {}".format(plugin))

    else:
        print("No se encuentra la lista")
示例#12
0
    def test_delete(self):
        with TestDatabase.db.transaction():
            TestDatabase.db.upsert(Bar(123, 456, 78.9, 'D'))

        bars = TestDatabase.db.select(Bar())
        self.assertEqual(len(bars), 3)
        self.assertEqual(
                str(bars[2]), "bar : Keys {'id': 123} : Values {'heading': 456, 'speed': 78.9, 'signal': 'D'}")

        with TestDatabase.db.transaction():
            TestDatabase.db.delete(Bar(123))
        bars = TestDatabase.db.select(Bar())
        self.assertEqual(len(bars), 2)

        bars = TestDatabase.db.select(Bar(123))
        self.assertEqual(len(bars), 0)
示例#13
0
 def __init__(self, width, height):
     self.mWidth = width
     self.mHeight = height
     self.mBackground = Background(width, height)
     self.mBall = Ball(width, height)
     self.mBars = []
     self.mBars.append(Bar(width, height))
     self.mBars[0].evolve()
     self.mScore = 0
     self.mGameStart = False
     self.mEZGame = False
     self.mEZText = Text("EZ MODE", self.mWidth / 2, 40)
     self.mGameStartTextTop = Text("Press 'W' to flap", self.mWidth / 2,
                                   self.mHeight / 3)
     self.mGameStartTextBot = Text("Press 'E' for EZ Mode", self.mWidth / 2,
                                   self.mHeight / 3 + 35)
     self.mScoreText = Text(str(self.mScore), self.mWidth / 10 - 20,
                            self.mHeight / 10 - 20)
     self.mGameOverTextTop = Text("GAME OVER NERD", self.mWidth / 2,
                                  self.mHeight / 3)
     self.mGameOverTextBot = Text("Press 'A' to play again",
                                  self.mWidth / 2, self.mHeight / 3 + 35)
     self.mGameOver = False
     self.mFlapSound = Sound("sounds/flap.wav")
     self.mPipeSound = Sound("sounds/pipe_sound.wav")
     self.mHitSound = Sound("sounds/hit.wav")
     self.mThemeSong = Sound("sounds/theme_song.wav")
     self.mThemePlaying = False
     self.mThemeSong.setVolume(.5)
     self.mWings = 0
     return
示例#14
0
    def evolve(self):
        if self.mThemePlaying == False:
            self.mThemeSong.play()
            self.mThemePlaying = True
        for bar in self.mBars:
            if bar.getWidth() + bar.getShift() - self.mBall.getWidth() == 0:
                self.mPipeSound.play()
                self.mScore += 1
                self.mScoreText = Text(str(self.mScore), self.mWidth / 10 - 20,
                                       self.mHeight / 10 - 20)

        if self.groundCollide() or self.barCollide():
            self.mGameOver = True
            self.mHitSound.play()
            self.mThemeSong.stop()
            self.mBall.flip(180)

        if not self.mGameOver:
            self.mBall.evolve()
            for bar in self.mBars:
                bar.evolve()

        lastBar = self.mBars[len(self.mBars) - 1]
        if lastBar.getShift() <= -150:
            newBar = Bar(self.mWidth, self.mHeight)
            self.mBars.append(newBar)
        return
示例#15
0
def from_mktdata_to_bar(mktData, freq):
    if (mktData.isnull().sum() == 0) or (mktData.isnull().sum() == 1
                                         and np.isnan(mktData.adjClose)):
        return Bar(mktData.dateTime, mktData.open, mktData.high, mktData.low,
                   mktData.close, mktData.volume, mktData.adjClose, freq)
    else:
        return None
示例#16
0
def get_bar(bar_id, day):
    day = int(day)
    auth_header = request.headers.get('Authorization')
    auth_token, valid = get_authorization(auth_header)
    if valid:
        try:
            bar = db_ops.check_bar_db(bar_id)
            if bar:
                specials = create_specials(bar['specials'][day])
                bar = Bar(bar['bar_id'], bar['name'], bar['location'],
                          bar['phone'], bar['cover'])
                bar.specials[day] = specials
                print(bar)
                responseObject = {
                    'status': 'success',
                    'message': 'Found bar.',
                    'bar': bar.to_dict(day)
                }
                return make_response(jsonify(responseObject)), 200
            else:
                create_response('fail', 'Did not find bar', 401)
        except Exception as e:
            traceback.print_exc(file=sys.stdout)
            return create_response('fail', 'Threw an Exception', 401)
    else:
        return create_response('fail', 'Invalid Token', 401)
示例#17
0
def create_bar():
    auth_header = request.headers.get('Authorization')
    auth_token, valid = get_authorization(auth_header)
    if valid:
        try:
            resp, success = User.decode_auth_token(auth_token)
            user = db_ops.check_user_db(resp)
            if success:
                if user['status'] == 'admin':
                    content = request.get_json()
                    bar = Bar(content['username'], content['password'],
                              content['name'], content['location'],
                              content['phone'])
                    responseObject = {
                        'status': 'success',
                        'message': 'Successfully added bar.'
                    }
                    db_ops.add_bar_to_db(bar)
                    return make_response(jsonify(responseObject)), 200
                else:
                    return create_response('fail', 'Incorrect Priveleges', 401)
            else:
                return create_response('fail', resp, 401)
        except Exception as e:
            return create_response('fail', 'Threw an Exception', 401)
    else:
        return create_response('fail', 'Invalid Token', 401)
示例#18
0
def index():
    turmas = Turma.query.all()
    turmas = turmas_schema.dump(turmas)
    instituicoes = Instituicao.query.all()
    instituicoes = instituicoes_schema.dump(instituicoes)
    alunos = Aluno.query.all()
    totais = []
    tick_label = []
    for instituicao in instituicoes:
        for inst in instituicao:
            if len(inst['name']) > 0:
                id = inst['id']
                tick_label.append(inst['name'])
                points = db.engine.execute(
                    f'SELECT points FROM aluno WHERE instituicao_id = {id}')
                points = [{
                    column: value
                    for column, value in rowproxy.items()
                } for rowproxy in points]
                total = 0
                for point in points:
                    total += point['points']
                total = total / len(points)
                totais.append(total)
    color = ['red', 'green']
    width = 0.8
    graph = Bar(tick_label, totais, width, color, 'nome', 'média', '', 'bar')
    return render_template('pages/index.html',
                           turmas=turmas.data,
                           instituicoes=instituicoes.data,
                           grafico=graph.plotGraph())
    def submit_values(self):
        caption = ""
        value = 0

        # get data from input boxes
        for button in self.menu:

            # input box id 0 is the caption box
            if button.id == 0:
                # so the data is a string
                caption = str(button.data)

            # input box id 1 is the value box
            elif button.id == 1:

                # so the data should be int
                try:
                    value = int(button.data)
                except:
                    print "Incorrect input!"

        # if either data field is empty or invalid
        if caption == "" or value < 1:
            for button in self.menu:
                if button.id == 2:

                    # flash the "Add" button red
                    button.throw_error()

        else:
            maxvalue = value

            if self.bars:
                # get greatest current value of a bar
                maxvalue = max(bar.value for bar in self.bars)
                # if new value is bigger than current maxvalue
                if value > maxvalue:
                    # set it as new maxvalue
                    maxvalue = value
                    for bar in self.bars:
                        # and scale all bars according to it
                        bar.set_size(maxvalue)

            barwidth = self.buttonheight + self.padding * 3
            bars = len(self.bars) * barwidth
            oldpadding = len(self.bars) * self.padding
            # other bar paddings and bars, padding left
            x = oldpadding + bars + self.padding

            # don't let the user add more bars if end of window is reached
            if x + self.buttonheight + self.padding * 3 > self.width:
                for button in self.menu:
                    if button.id == 2:
                        button.throw_error()
            else:
                y = self.height - self.bbarheight - self.buttonheight
                self.bars.add(
                    Bar(caption, value, maxvalue, self.maxheight, x,
                        y - self.padding * 2, barwidth))
示例#20
0
 def __on_bar(self, data):
     bar = Bar()
     bar.set_pd(data)
     bar.set_symbol(self.__symbol)
     # 撮合限价单
     self.cross_limit_order(bar)
     # 推送给策略
     self.__strategy.on_bar(bar)
示例#21
0
    def test_select(self):
        bars = TestDatabase.db.select(Bar())

        self.assertEqual(len(bars), 2)
        self.assertEqual(
                str(bars[0]), "bar : Keys {'id': 98} : Values {'heading': 98, 'speed': 2.3, 'signal': 'X'}")
        self.assertEqual(bars[1].getTable(), 'bar')
        self.assertEqual(bars[1].getId(), 99)
        self.assertEqual(bars[1].getHeading(), 99)
        self.assertEqual(bars[1].getSignal(), 'Z')

        bars = TestDatabase.db.select(Bar(98))
        self.assertEqual(len(bars), 1)
        self.assertEqual(
                str(bars[0]), "bar : Keys {'id': 98} : Values {'heading': 98, 'speed': 2.3, 'signal': 'X'}")

        bars = TestDatabase.db.select(Bar.createAdhoc({'signal': 'Z'}))
        self.assertEqual(len(bars), 1)
        self.assertEqual(
                str(bars[0]), "bar : Keys {'id': 99} : Values {'heading': 99, 'speed': 2.4, 'signal': 'Z'}")
示例#22
0
 def getBars(self, day, period=PERIOD, intervals=INTERVALS):
     if self.average_height is None:
         return []
     tomorrow = day + timedelta(days=1)
     # day = day.strftime("%Y-%m-%d")
     # tomorrow = tomorrow.strftime("%Y-%m-%d")
     data = self.getData(day, tomorrow, period, intervals, update=True)
     self._bars = [Bar(self.name, 
             data.reset_index().iloc[[x]],
             self.average_height,
             self.average_volume) for x in range(len(data))]
示例#23
0
    def test_upsert(self):
        with TestDatabase.db.transaction() as t:
            TestDatabase.db.upsert(Bar(101, 180, 23.45, 'F'))

            bars = TestDatabase.db.select(Bar())

            self.assertEqual(len(bars), 3)
            self.assertEqual(
                    str(bars[2]), "bar : Keys {'id': 101} : Values {'heading': 180, 'speed': 23.45, 'signal': 'F'}")

            TestDatabase.db.upsert(Bar(98, 270, signal='B'))

            bars = TestDatabase.db.select(Bar(98))

            self.assertEqual(len(bars), 1)
            self.assertEqual(
                    str(bars[0]), "bar : Keys {'id': 98} : Values {'heading': 270, 'speed': None, 'signal': 'B'}")

            # force a rollback
            t.fail()
 def menuAgregarBar(self):
     print "Ingrese nombre del bar "
     nombre = raw_input()
     print "Ingrese direccion (Todas las palabras separadas por espacios) "
     direcc = raw_input()
     print "Ingrese cantidad de enchufes "
     enchuf = input()
     print "Ingrese Descripcion"
     desc = raw_input()
     wifi = self.ingresarWifi()
     self.listaDeBares.agregarBar(Bar(nombre, direcc, enchuf, desc, wifi))
     self.menuInicial()
示例#25
0
    def readData(self):
        with open(self.filename, 'rb') as f:
            header = f.read(148)
            while 1:
                first = f.read(4)
                if not first:
                    break
                datetime = struct.unpack('I', first)[0]
                tmp = struct.unpack('ddddq', f.read(40))

                bar = Bar(datetime, tmp[0], tmp[1], tmp[2], tmp[3], tmp[4])
                self.data.append(bar)
示例#26
0
    def test_center_and_var2(self):
        chords = [
            Note.init_notes(['d1', 'e1']),
            Note.init_notes(['d1', 'f#1']),
            Note.init_notes(['d1', 'g#1']),
            Note.init_notes(['d1', 'a#1'])
        ]

        units = [Unit(chord, Fraction(1, 1)) for chord in chords]
        bar = Bar(key='C', time_signature='4/4', units=units)

        self.assertAlmostEqual(bar.center, 5.5, delta=self.ERROR)
        self.assertAlmostEqual(bar.var, 1.25, delta=self.ERROR)
示例#27
0
    def __init__(self, starting_point, angle):
        """
        Creates a set of bars
        :param starting_point: initial point where all begins
        :type starting_point: tuple of float
        :param angle: set of angles for each bar
        :type angle: numpy array
        """
        self.bars = []
        self.starting_point = starting_point

        for i in range(len(angle)):
            if i is 0:
                self.bars.append(
                    Bar(self.starting_point,
                        angle[i],
                        length=BAR_LENGTH / len(angle)))
            else:
                self.bars.append(
                    Bar(self.bars[i - 1].end_point,
                        angle[i],
                        length=BAR_LENGTH / len(angle)))
示例#28
0
 def __init__(self, width, height, color=(28, 28, 28)):
     self.wall_thickness = 15
     self.width = width
     self.height = height
     self.color = color
     self.elements = [
         Wall(0, 0, self.width, self.wall_thickness),  # top
         Wall(self.width - self.wall_thickness, 0, self.wall_thickness,
              self.height),  # right
         Wall(0, self.height - self.wall_thickness, self.width,
              self.wall_thickness),  # bottom
         Bar(),
         Ball()
     ]
示例#29
0
    def update(self, order):
        self.update_charts()
        values = self.charts[order]
        directions = [
            Bar(i, self.screen, self.screen_width, self.screen_height,
                self.xliftoff, self.yliftoff, self.bar_width) for i in range(6)
        ]
        self.screen.fill((200, 200, 255))
        self.screen = self.axes.draw()

        for i in range(6):
            self.screen = directions[i].draw(self.screen, values[i],
                                             self.labels[i])

        return self.screen
示例#30
0
 def traerTodos(self, file, habil):
     bares = []
     f = open(file, 'r')
     for line in f:
         linea = line.split('--')
         nombre = linea[0]
         direccion = linea[1]
         enchufes = linea[2]
         descripcion = linea[3]
         wifi = int(linea[4])
         habilitado = linea[5]
         if int(habilitado) == int(habil):
             bar = Bar(nombre, direccion, enchufes, descripcion, wifi)
             bares.append(bar)
     return bares