示例#1
0
    def ParseAwards(self, contents):
        awards = []
        awards_iter = re.finditer("<tr> <td><b>(?P<title>[^<]+)</b><br />(?P<description>.+?)</td> <td align=\"right\" valign=\"top\"><nobr>\$?(?P<value>[\d\.\s]+)?</nobr></td></tr>", contents)
        for award_match in awards_iter:
            title = award_match.group("title")
            description = award_match.group("description")
            if "Medal" in description and "Excellence Award -" in title:
                # Fix the title to be more useful.
                title = title.split("-")[0] + "- " + \
                        re.search(r"\w+ medal", description, re.IGNORECASE).group(0) + " -" + \
                        title.split("-")[-1]
            award = Award(
                name = title,
                description = description,
                value = float(award_match.group("value").replace(" ", "")) if award_match.group("value") else None,
                type = AwardType.Unknown
            )
            keyword_text = str(award.Name + award.Description).lower()
            for type, keywords in self._typeKeywords.items():
                if not keywords:
                    award.Type = type
                    continue
                for keyword in keywords:
                    if keyword in keyword_text:
                        award.Type = type
                        break
            if not award.Value and award.Type == AwardType.Cash:
                award.Type = AwardType.Other # It's not cash if it has no $ value
            awards.append(award)

        return awards
    def post(self):
        """ send the list to the api server """
        player_key = self.request.get('player_key')
        logging.info(player_key)
        
        player_name = self.request.get('player_name')
        logging.info(player_name)
        
        award_amount = self.request.get('award_amount')
        logging.info(award_amount)
        
        award_title = self.request.get('award_title')
        logging.info(award_title)
        
        award = Award(
            player_key,
            player_name,
            int(award_amount),
            award_title
        )
        
        award_json = json.dumps(award.to_dict())
            
        uri = "/api/issue_award"
        
        
        params = OrderedDict([
                ("award", award_json),
                ("nonce", time.time()),
                  ])
                          
        params = urllib.urlencode(params)
        
        logging.info(params)

        # Hash the params string to produce the Sign header value
        H = hmac.new(shared_secret, digestmod=hashlib.sha512)
        H.update(params)
        sign = H.hexdigest()

        headers = {"Content-type": "application/x-www-form-urlencoded",
                           "Key":api_key,
                           "Sign":sign}
        if local_testing:
            conn = httplib.HTTPConnection(url)
        else:
            conn = httplib.HTTPSConnection(url)
        
        conn.request("POST", uri, params, headers)
        response = conn.getresponse()
        
        self.response.write(response.read())
示例#3
0
def test_normal_award(initial_expires_in, initial_quality, expected_quality):
    award = Award(name='NORMAL ITEM',
                  expires_in=initial_expires_in,
                  quality=initial_quality)
    update_quality([award])
    assert award.expires_in == initial_expires_in - 1
    assert award.quality == expected_quality
示例#4
0
def test_blue_star(initial_expires_in, initial_quality, expected_quality):
    award = Award(name='Blue Star',
                  expires_in=initial_expires_in,
                  quality=initial_quality)
    update_quality([award])
    assert award.expires_in == initial_expires_in - 1
    assert award.quality == expected_quality
def test_blue_distinction(initial_expires_in, initial_quality,
                          expected_quality):
    award = Award(name='Blue Distinction Plus',
                  expires_in=initial_expires_in,
                  quality=initial_quality)
    update_quality([award])
    assert award.expires_in == initial_expires_in
    assert award.quality == expected_quality
示例#6
0
def test_several_awards():
    award1 = Award(name = 'NORMAL ITEM', expires_in = 5, quality = 10)
    award2 = Award(name = 'Blue First', expires_in = 3, quality = 10)
    award1.update_quality([award1])
    award2.update_quality([award2])

    assert award1.quality == 9
    assert award1.expires_in == 4
    assert award2.quality == 11
    assert award2.expires_in == 2
示例#7
0
def update_block(group, blocks, controllers, awards, settings, screen, controller, game_contiune):
    # 判断当前的球是否与砖块发生碰撞,如果发生碰撞.进行角度的转换
    dic = pygame.sprite.groupcollide(group, blocks, False, False)
    # 返回的是字典.进行遍历操作
    # {<Ball sprite(in 1 groups)>: [<Block sprite(in 1 groups)>]}
    for key, value in dic.items():
        if (key.rect.top < value[0].rect.top) or (key.rect.bottom > value[0].rect.bottom):
            # 说明接触面在上面或下面
            key.make_turn(2)
        else:
            key.make_turn(True)
        # 移除砖块
        for v in value:
            # 如果是不能损毁的砖块移除
            if v.destory == False:
                value.remove(v)
            else:
                if random.randint(0, 100) <= settings.aware_occurrence_rate:
                    new_award = Award(settings, screen, v)
                    awards.add(new_award)

        blocks.remove(value)

    dic2 = pygame.sprite.groupcollide(group, controllers, False, False)
    for key, value in dic2.items():
        key.make_turn(2)
        # ball.make_turn(2)

    dic3 = pygame.sprite.groupcollide(controllers, awards, False, False)
    for key, value in dic3.items():
        for v in value:
            if v.flag:
                # 分裂
                temp_list = []
                for ball in group:
                    for index in range(3):
                        new_ball = Ball(settings=settings, screen=screen, controller=controller)
                        new_ball.setX_Y(ball.x, ball.y, index)
                        temp_list.append(new_ball)

                # 完成分裂之后.再添加到group当中
                for ball in temp_list:
                    group.add(ball)
            else:
                # 发射三个
                for index in range(3):
                    new_ball = Ball(settings=settings, screen=screen, controller=controller)
                    new_ball.setX_Y(controller.rect.centerx, controller.rect.centery, index)
                    group.add(new_ball)
                print("send three")
        awards.remove(value)
示例#8
0
def Create_new_award(check):
    while True:
        try:
            award_name = input("Nazwa nagrody: ")
            award_weight = input("Waga nagrody (od 1 do 5): ")
            person_id = input("Id osoby otrzymującej nagrode: ")
            x = Award(award_name, award_weight, person_id)
            c.execute(
                "INSERT INTO award VALUES(:award_name,:award_weight,:person_id)",
                {
                    'award_name': x.award_name,
                    'award_weight': x.award_weight,
                    'person_id': x.person_id
                })
            conn.commit()
            break
        except sqlite3.IntegrityError:
            print("Nie ma takiej osoby, sprobuj ponownie")
            Create_new_award()
    menu(check)
示例#9
0
    async def newaward_handler(self, request):
        json_recv = await request.json()
        try:
            print(json.dumps(json_recv, indent=True))
            print(self.badges)
            badge_id = None
            for badge_id2 in self.badges:
                if self.badges[badge_id2]['name'] == json_recv['name']:
                    badge_id = badge_id2
                    break
            if badge_id is None:
                raise ValueError
            badge_url = f"{self.api_path}/badge/{badge_id}/json"
            params = dict()
            params['id'] = uuid.uuid4().hex
            params['email'] = json_recv['email']
            params['timestamp'] = str(datetime.utcnow().isoformat())
            params['badge_url'] = badge_url
            award = Award(**params)

            award_path = f"api/award/{award.id}/award.json"
            os.makedirs(f"api/award/{award.id}/")
            with open(award_path, 'w') as f:
                json.dump(award.json, f)

            self.awards[award.id] = {
                    'name': json_recv['name'] + " to " + json_recv['email'],
                    'url': f"{self.api_path}/award/{award.id}/json"
                    }
            with open("api/awards.json", 'w') as f:
                json.dump(self.awards, f)

            await self.bake_award(award.id)

            return web.Response(text=award.id)
        except:
            traceback.print_exc(file=sys.stdout)
            return web.HTTPBadRequest()
示例#10
0
import datetime
from task import Task
from module import Module
from award import Award
from schedule import Schedule
from interfaces import ParentInterface, ChildInterface

if __name__ == "__main__":

    # tworzenie domyślnych nagród
    award_list = [
        Award("Złoty medal."),
        Award("Świetna robota!"),
        Award("Brawo :)"),
        Award("Oby tak dalej")
    ]

    # tworzenie domyślnych zadań do biblioteki
    lazienka = Task("Idę do łazienki.")
    wez = Task("Wyciągam szczoteczkę i pastę.")
    naloz = Task("Nakładam pastę na szczoteczkę.")
    czysc_z = Task("Szoruję zęby")
    plucz = Task("Płuczę usta.")
    plucz2 = Task("Płuczę szczoteczkę.")
    odloz = Task("Odkładam szczoteczkę i pastę.")
    wytrzyj = Task("Wycieram buzię i ręce.")
    lista = Task("Robię listę zakupów.")
    buty_on = Task("Ubieram buty.")
    kurtka_on = Task("Ubieram kurtkę.")
    klucz = Task("Biorę klucze.")
    drzwi = Task("Zamykam drzwi.")
示例#11
0
def test_blue_compare(initial_expires_in, initial_quality, expected_quality):
    award = Award(name = 'Blue Compare', expires_in = initial_expires_in,
            quality = initial_quality)
    award.update_quality([award])
    assert award.expires_in == initial_expires_in - 1
    assert award.quality == expected_quality