Пример #1
0
 def post(self):
     cid = self.get_argument('cid')
     root = self.get_secure_cookie('root')
     if root != 'suiyue':
         return self.redirect('/rootlogin')
     cards = Card.get_by_cid(cid)
     ext_allowed = ['gif', 'jpg', 'jpeg', 'png']
     cpic = cards[0].pic
     max_size = 2621440
     save_dir = os.path.join(os.path.dirname(__file__), "../public/pic/card/")
     if len(cards)>0:
         file_name = str(cards[0].cid)
         error = ""
         if 'image' in self.request.files:
             pic = self.request.files['image'][0]
             ext = pic['filename'].split('.').pop()
             if ext not in ext_allowed:
                 error="图片格式不支持"
                 self.redirect('/control')
             if len(pic['body'])>max_size:
                 error="图片太大"
                 self.redirect('/control')
             cpic = file_name+"."+ext
             with open(save_dir+cpic,'wb') as up:
                 up.write(pic['body'])
         Card.change_pic(cid, cpic)
         self.redirect("/control")
     else:
         self.redirect('/control')
def five_completed_tasks():
    card1 = Card(1, 1, "Card 1 Done", LISTS[2].id, None, YESTERDAY_DATE)
    card2 = Card(2, 2, "Card 2 Done", LISTS[2].id, None, YESTERDAY_DATE)
    card3 = Card(3, 3, "Card 3 Done", LISTS[2].id, None, YESTERDAY_DATE)
    card4 = Card(4, 4, "Card 4 Done", LISTS[2].id, None, YESTERDAY_DATE)
    card5 = Card(5, 5, "Card 5 Done", LISTS[2].id, None, YESTERDAY_DATE)
    return [card1, card2, card3, card4, card5]
Пример #3
0
def get_card_route(request, card_id):
    """
    Get a specific card given an ID. Show all relevant data, but
    not used for the learning interface.
    """

    db_conn = request['db_conn']

    card = get_card_by_kind(db_conn, card_id)
    if not card:
        return abort(404)

    unit = Unit.get_latest_accepted(db_conn, entity_id=card['unit_id'])
    if not unit:
        return abort(404)

    # TODO-2 SPLITUP create new endpoints for these instead
    topics = list_topics_by_entity_id(card_id, {}, db_conn)
    versions = Card.get_versions(db_conn, entity_id=card_id)
    requires = Card.list_requires(db_conn, entity_id=card_id)
    required_by = Card.list_required_by(db_conn, entity_id=card_id)
    params = get_card_parameters({'entity_id': card_id}, db_conn)

    return 200, {
        'card': card.deliver(access='view'),
        'card_parameters':
        (get_card_parameters_values(params) if params else None),
        'unit': unit.deliver(),
        'topics': [deliver_topic(topic) for topic in topics],
        'versions': [version.deliver() for version in versions],
        'requires': [require.deliver() for require in requires],
        'required_by': [require.deliver() for require in required_by],
    }
Пример #4
0
    def updateAsInventory(self, context):
        self.cards = []

        if context.update:
            json = self.api.updateAndGetInitFile(context)
        else:
            json = self.api.getInit(context)

        card_map = json['user_units']
        self.name = json['user_data']['name'] + "_inventory"

        # print('[Deck] inventory for ', self.name)

        for card in card_map:
            card_to_add = Card()
            card_to_add.id = int(card_map[card]['unit_id'])
            card_to_add.level = int(card_map[card]['level'])
            print('[Deck] Adding card - id: {0}, level: {1}'.format(
                card_to_add.id, card_to_add.level))
            self.cards.append(card_to_add)

        self.updateDeckFromXML()

        print('[Deck] update as inventory - returning')
        return self.cards
Пример #5
0
def get_card_route(request, card_id):
    """
    Get a specific card given an ID. Show all relevant data, but
    not used for the learning interface.
    """

    card = get_card_by_kind(card_id)
    if not card:
        return abort(404)

    unit = Unit.get_latest_accepted(entity_id=card['unit_id'])
    if not unit:
        return abort(404)

    # TODO-2 SPLITUP create new endpoints for these instead
    topics = Topic.list_by_entity_id(entity_id=card_id)
    versions = Card.get_versions(entity_id=card_id)
    requires = Card.list_requires(entity_id=card_id)
    required_by = Card.list_required_by(entity_id=card_id)
    params = CardParameters.get(entity_id=card_id)

    return 200, {
        'card': card.deliver(access='view'),
        'card_parameters': params.get_values(),
        'unit': unit.deliver(),
        'topics': [topic.deliver() for topic in topics],
        'versions': [version.deliver() for version in versions],
        'requires': [require.deliver() for require in requires],
        'required_by': [require.deliver() for require in required_by],
    }
Пример #6
0
 def post(self):
     uname = self.get_current_user()
     user = User.get_user_by_name(uname)
     main = self.get_argument("main")
     pic = "default.jpg"
     Card.add_one_card(pic,user[0].uid,main)
     self.render("wcard.html", msg="投稿成功,谢谢你的idea",user=user)
Пример #7
0
 def get(self):
     uname = self.get_current_user()
     user = User.get_user_by_name(uname)
     order = get_order()
     card = Card.get_by_porder(order)
     cid = self.get_argument("cid",None)
     if cid is not None:
         card=Card.get_by_cid(cid)
     article = Article.get_all_Acard(200)
     usedCard = Card.get_all_card()
     temp = []
     for one in usedCard:
         if 0 < one.porder and one.porder <= order:
             temp.append(one)
     usedCard = temp
     reArticles = Article.get_all(200)
     Rarticle = sorted(reArticles,BaseHandler.rank)
     if len(Rarticle) > 6:
         Rarticle = Rarticle[:6]
     Ruser = User.get_all_user(100)
     if len(Ruser)>9:
         Ruser = Ruser[:9]
     if len(usedCard)>3:
         usedCard = usedCard[:3]
     self.render("card.html",user=user,Rarticle=Rarticle,Article=article,usedCard=usedCard,Ruser=Ruser,card=card)
Пример #8
0
 def load_latest_game(cls, email):
     """Return latest game by a user or a new game if one didn't exist."""
     with connection:
         with connection.cursor() as cursor:
             user = User.get_user_by_email(email)
             cursor.execute(database.GET_LATEST_GAME_TABLE_BY_EMAIL, (email,))
             bulk = cursor.fetchone()
             print (bulk)
             if bulk:
                 (game_table_id, timestamp_created, computer_hand_id,
                  player_hand_id, deck_id, user_id, turn_indicator) = bulk
             else:
                 return cls.new_game(user)
             # Get Hands
             cursor.execute(database.GET_HAND_BY_ID, (player_hand_id, ))
             p_s1, p_v1, p_s2, p_v2, p_s3, p_v3, p_s4, p_v4, p_s5, p_v5,\
                 uid, mtime = cursor.fetchone()
             player = User.get_user_by_id(uid)
             player_hand = Hand(player, Card(p_s1, p_v1),
                                Card(p_s2, p_v2),
                                Card(p_s3, p_v3),
                                Card(p_s4, p_v4),
                                Card(p_s5, p_v5))
             cursor.execute(database.GET_HAND_BY_ID, (computer_hand_id, ))
             c_s1, c_v1, c_s2, c_v2, c_s3, c_v3, c_s4, c_v4, c_s5, c_v5,\
                 cuid, cmtime = cursor.fetchone()
             computer = User.get_user_by_id(COMPUTER_UID)
             computer_hand = Hand(computer, Card(c_s1, c_v1),
                                  Card(c_s2, c_v2),
                                  Card(c_s3, c_v3),
                                  Card(c_s4, c_v4),
                                  Card(c_s5, c_v5))
             deck = Deck(deck_id)
             return cls(deck, user, player_hand, computer_hand, game_table_id, turn_indicator)
Пример #9
0
def apply_card():
    u = current_user()
    if u is None:
        return abort(403)
    form = request.form
    Card.apply_card(u, form)
    return redirect(url_for(".index"))
Пример #10
0
    def test_query_cards(self):
        # initialize some sample cards
        # testing comment
        user = self.generate_user(COOL_USERNAME, PASSWORD)
        card_names = [
            "Jace, The Mind Sculptor", "Jace's Defeat",
            "Jace, Vrynn's Prodigy", "Jackal Pup", "Scalding Tarn",
            "Ancestral Vision", "Serum Visions", "Lightning Bolt",
            "Forked Bolt", "Boltwing Marauder", "Firebolt"
        ]
        for name in card_names:
            new_card = Card(name)
            db.session.add(new_card)
        db.session.commit()

        # assert that each query for a specific card has exactly one match.
        # Note for our input that none of the names are substrings of another
        for name in card_names:
            sample = Card.query.filter_by(
                search_name=Card.format_card_name_for_search(name)).first()
            query = user.query_cards(name)
            self.assertEqual(len(query), 1)

        # these queries have the query amount and expected output
        test_queries = [("Tarn", 1), ("Jace", 3), ("jace", 3), ("Jac", 4),
                        ("bolt", 4), ("vision", 2), ("visions", 1)]

        for test in test_queries:
            card_name = test[0]
            expected_quantity = test[1]
            query = user.query_cards(card_name)
            self.assertEqual(len(query), expected_quantity)
Пример #11
0
def get_card_route(request, card_id):
    """
    Get a specific card given an ID. Show all relevant data, but
    not used for the learning interface.
    """

    card = get_card_by_kind(card_id)
    if not card:
        return abort(404)

    unit = Unit.get_latest_accepted(entity_id=card['unit_id'])
    if not unit:
        return abort(404)

    # TODO-2 SPLITUP create new endpoints for these instead
    topics = Topic.list_by_entity_id(entity_id=card_id)
    versions = Card.get_versions(entity_id=card_id)
    requires = Card.list_requires(entity_id=card_id)
    required_by = Card.list_required_by(entity_id=card_id)
    params = CardParameters.get(entity_id=card_id)

    return 200, {
        'card': card.deliver(access='view'),
        'card_parameters': params.get_values(),
        'unit': unit.deliver(),
        'topics': [topic.deliver() for topic in topics],
        'versions': [version.deliver() for version in versions],
        'requires': [require.deliver() for require in requires],
        'required_by': [require.deliver() for require in required_by],
    }
Пример #12
0
 def test_get_cards_by_list_id(self):
     uid0 = User.add("test1", "password", "*****@*****.**")
     bid0 = Board.add("board1", "A")
     lid0 = List.add("To Do", bid0)
     card_id = Card.add("card0", lid0, uid0)
     card = Card.get(card_id)
     assert card_id in [card.id for card in Card.get_cards_by_list_id(lid0)]
Пример #13
0
    def test_card_search_name(self):
        # there's 18000 in this AllCards.json so we only check some of them
        # This variable can be adjusted to check all of them
        # To check all 18000 cards, it will take at least 30 seconds
        # and will bog down other tests

        NUM_CARDS_TO_CHECK = 100

        with open("./data/AllCards.json", "r") as f:
            card_data = json.load(f)
            count = 0
            for name in card_data:
                if count < NUM_CARDS_TO_CHECK:
                    new_card = Card(name)
                    db.session.add(new_card)
                    count += 1
            db.session.commit()

        count = 0
        for name in card_data:
            if count < NUM_CARDS_TO_CHECK:
                card = Card.search_card_by_name(name)
                self.assertIsNotNone(card)
                formatted_name = Card.format_card_name_for_search(name)
                cards = Card.query.filter_by(search_name=formatted_name).all()
                self.assertEqual(len(cards), 1)
                count += 1
Пример #14
0
 def test_get_user_ids(self):
     uid0 = User.add("test1", "password", "*****@*****.**")
     bid0 = Board.add("board1", "A")
     lid0 = List.add("To Do", bid0)
     card_id = Card.add("card0", lid0, uid0)
     card = Card.get(card_id)
     assert str(uid0) in [user_id for user_id in card.get_user_ids()]
Пример #15
0
def choose_card(db_conn, user, unit):
    """
    Given a user and a unit, choose an appropriate card.
    Return a card instance.
    """

    # TODO-3 simplify this method

    unit_id = unit['entity_id']
    query = (Card.start_accepted_query().filter({
        'unit_id': unit_id
    }).sample(10))  # TODO-2 index
    # TODO-3 does this belong as a model method?
    # TODO-2 is the sample value decent?
    # TODO-2 has the learner seen this card recently?

    cards = [Card(d) for d in query.run(db_conn)]
    if not len(cards):
        return None

    previous_response = get_latest_response(user['id'], unit_id, db_conn)
    if previous_response:
        learned = previous_response['learned']
        # Don't allow the previous card as the next card
        cards = [
            card for card in cards
            if card['entity_id'] != previous_response['card_id']
        ]
    else:
        learned = init_learned

    shuffle(cards)
    assessment, nonassessment = partition(cards, lambda c: c.has_assessment())
    choose_assessment = random() < p_assessment_map[floor(learned * 10)]

    if choose_assessment:
        if not len(assessment):
            return nonassessment[0]
        for card in assessment:
            params = get_card_parameters({'entity_id': card['entity_id']},
                                         db_conn)
            if params:
                values = get_card_parameters_values(params)
                guess = values['guess']
                slip = values['slip']
                correct = calculate_correct(guess, slip, learned)
                if 0.25 < correct < 0.75:
                    return card
            else:
                return card
        return assessment[0]

    if len(nonassessment):
        return nonassessment[0]

    if len(assessment):
        return assessment[0]

    return None
Пример #16
0
 def test_set_and_get_card(self):
     uid0 = User.add("test1", "password", "*****@*****.**")
     bid0 = Board.add("board1", "A")
     lid0 = List.add("To Do", bid0)
     card_id = Card.add("card0", lid0, uid0)
     card = Card.get(card_id)
     assert card.title == 'card0'
     assert card.list_id == lid0
def cards_with_last_modified_dates():
    card1 = Card(1, 1, "Card 1 Todo Yesterday", LISTS[0].id, None,
                 YESTERDAY_DATE)
    card2 = Card(2, 2, "Card 2 Todo Today", LISTS[0].id, None, TODAY_DATE)
    card3 = Card(3, 3, "Card 3 Done Yesterday", LISTS[2].id, None,
                 YESTERDAY_DATE)
    card4 = Card(4, 4, "Card 4 Done Today", LISTS[2].id, None, TODAY_DATE)
    return [card1, card2, card3, card4]
Пример #18
0
 def test_get_and_test_description(self):
     uid0 = User.add("test1", "password", "*****@*****.**")
     bid0 = Board.add("board1", "A")
     lid0 = List.add("To Do", bid0)
     card_id = Card.add("card0", lid0, uid0)
     card = Card.get(card_id)
     card.set_description('desc')
     assert 'desc' in card.get_description()
Пример #19
0
class TestCard:
    def setup(self):
        self.numbers_list = [
            9, 43, 62, 74, 90, 2, 27, 75, 78, 82, 41, 56, 63, 76, 86
        ]
        self.card = Card(self.numbers_list)

    def test_is_empty(self):
        assert not self.card.is_empty()
        # Если вычеркнуть все чифры?
        for item in self.numbers_list:
            self.card.cross_out(item)

        assert self.card.is_empty()

    def test_str(self):
        result = """
        --------------------------
            9 43 62          74 90
         2    27    75 78    82
           41 56 63     76      86
        --------------------------
        """
        assert result == str(self.card)

    def test_contains(self):
        assert 9 in self.card
        assert 99 not in self.card
        assert CardNumber(9) in self.card
        assert CardNumber(99) not in self.card

    def test_cross_out(self):
        # Зачеркиваем число которое есть
        self.card.cross_out(43)
        result = """
        --------------------------
            9 - 62          74 90
         2    27    75 78    82
           41 56 63     76      86
        --------------------------
        """
        assert str(self.card) == result

        self.card.cross_out(CardNumber(62))
        result = """
        --------------------------
            9 - -          74 90
         2    27    75 78    82
           41 56 63     76      86
        --------------------------
        """
        assert str(self.card) == result

        # В карточке нет такого числа
        with raises(CardNotContainsNumberError):
            self.card.cross_out(CardNumber(99))
Пример #20
0
    def __initialize_deck(self):
        for suite in self.__suites:
            for count, name in enumerate(self.__names, start=1):
                if name == 'ACE':
                    card = Card(suite, name, 'ACE', 10)
                elif name == 'JACK' or name == 'QUEEN' or name == 'KING':
                    card = Card(suite, name, 'FACE_CARD', 10)
                else:
                    card = Card(suite, name, 'RANKS', count)

                self.__cards.append(card)
Пример #21
0
 def post(self):
     cid = self.get_argument('cid')
     porder = self.get_argument('porder')
     root = self.get_secure_cookie('root')
     if root == 'suiyue':
         temp = Card.get_by_porder(porder)
         if len(temp) > 0:
             Card.change_porder(temp[0].cid, 0)
         Card.change_porder(cid, porder)
         self.redirect('/control')
     else:
         self.redirect('/rootlogin')
Пример #22
0
    def match_pair(cls, game, pair_1, pair_2):
        """Match a pair and update game state"""
        game.attempts += 1
        game.put()
        card_1 = Card.query(Card.game == game.key).filter(Card.index == pair_1).get()
        card_2 = Card.query(Card.game == game.key).filter(Card.index == pair_2).get()

        if card_1.matched or card_2.matched:
            raise RuntimeError('Could not rematch a matched card')

        form = MatchResultForm()
        if card_1.value == card_2.value:
            card_1.matched = True
            card_1.put()
            card_2.matched = True
            card_2.put()
            game.matched += 2
            game.put()
            form.message = 'Success'
        else:
            form.message = 'Fail'

        # Construct return info form
        form.card_1 = card_1.to_form()
        form.card_2 = card_2.to_form()
        form.matched_count = game.matched

        if game.matched == 52:
            game.game_over = True
            game.put()
            Card.delete_cards_for_game(game)

            # Update average attempts of user
            user = game.user.get()
            games = Game.get_user_finished_games(user)
            count = len(games)
            if user.average_attempts == float('inf'):
                user.average_attempts = 0
            user.average_attempts = ((count - 1) * user.average_attempts + game.attempts) / count
            user.put()

            score = Score(user=game.user, date=date.today(), attempts=game.attempts)
            score.put()
            form.message = 'Win'

        # Create history log
        History.create_history(game=game,
                               card_1=card_1,
                               card_2=card_2,
                               message=form.message)
        return form
Пример #23
0
    def test_get_cards(self):
        bid0 = Board.add("board1", "A")
        lid0 = List.add("List0", bid0) 
        list0 = List.get(lid0)
        lid1 = List.add("List1", bid0) 
        list1 = List.get(lid1)

        uid0 = User.add("test1", "password", "*****@*****.**")
        
        caid0 = Card.add("card1", lid0, uid0)
        caid1 = Card.add("card2", lid1, uid0)

        assert caid0 in [card.id for card in list0.get_cards()]
        assert caid1 not in [card.id for card in list0.get_cards()]
Пример #24
0
 def post(self):
     body = request.get_json()
     card = Card(body["card_number"], body["emp_id"])
     try:
         card.save()
     except Exception as e:
         return (
             {
                 "msg": "Something went wrong while adding access card to db.",
                 "description": e,
             },
             500,
         )
     return {"msg": "New card created for employee.", "card": card.json()}, 201
Пример #25
0
    def add(cls, card_id, user_id, content):
        comment = cls(card_id = card_id, user_id = user_id, content = content)
        from models.card import Card
        Card.incr_comment(card_id)
        try:
            mysql_session.add(comment)
            mysql_session.commit()
        except Exception as e:
            mysql_session.rollback()
            print "error in mysql commit:", e
            raise
        finally:
            mysql_session.close()

        return comment.id
Пример #26
0
def flush_entities(db_conn, descs):
    """
    Given a list of kinds and entity_ids,
    return a list filled out with entities.
    """

    output = []

    for desc in descs:
        if desc['kind'] == 'card':
            card = Card.get_latest_accepted(db_conn, entity_id=desc['id'])
            card = flip_card_into_kind(card)
            if card:
                output.append(card)
        elif desc['kind'] == 'unit':
            output.append(Unit.get_latest_accepted(
                db_conn,
                entity_id=desc['id']
            ))
        elif desc['kind'] == 'set':
            output.append(Set.get_latest_accepted(
                db_conn,
                entity_id=desc['id']
            ))
        else:
            output.append(None)

    return output
Пример #27
0
def api_card(list_id = None):
    if request.method == 'GET':
        list_id = request.args.get('list_id')
        if list_id != None:
            cards = Card.get_cards_by_list_id(list_id)
            return jsonify(json_list=[card.serialize() for card in cards])
        else:
            return jsonify({'code': 404, 'message': 'Card ID not valid.'})
    else:
        try:
            list_id = long(request.form['list_id'])
            title = request.form['title']
        except KeyError:
            return jsonify({'code': 400, 'message': 'Bad Request'})

        return jsonify({"card_id": Card.add(title, list_id, current_user.id)})
Пример #28
0
    def make_game_easier(cls, game, hint_num):
        cards = Card.get_cards_for_game(game)
        unmatched_cards = filter(lambda c: not c.matched, cards)
        hint_histories = []

        while game.matched != 52 and hint_num > 0:
            card_1 = unmatched_cards[0]
            card_2 = filter(lambda c: c != card_1 and c.value == card_1.value, unmatched_cards)[0]
            # Update game state
            card_1.matched = True
            card_2.matched = True
            game.matched += 2
            game.attempts += 1
            hint_num -= 1
            # Update card state unmatched card list
            unmatched_cards.remove(card_1)
            unmatched_cards.remove(card_2)
            card_1.put()
            card_2.put()
            # Create history log
            history = History.create_history(game=game, card_1=card_1, card_2=card_2, message='Hint Match')
            hint_histories.append(history)

        game.put()
        return hint_histories
Пример #29
0
def get_card_by_kind(db_conn, card_id):
    """
    Given a card data, return a new card model to replace it by kind.
    """

    card = Card.get_latest_accepted(db_conn, card_id)
    return flip_card_into_kind(card)
Пример #30
0
def get_card_by_kind(db_conn, card_id):
    """
    Given a card data, return a new card model to replace it by kind.
    """

    card = Card.get_latest_accepted(db_conn, card_id)
    return flip_card_into_kind(card)
Пример #31
0
def get_card_by_kind(card_id):
    """
    Given a card data, return a new card model to replace it by kind.
    """

    card = Card.get_latest_accepted(card_id)
    if not card:
        return

    data, kind = card.data, card.data.get('kind')

    map = {
        'audio': AudioCard,
        'choice': ChoiceCard,
        'embed': EmbedCard,
        'formula': FormulaCard,
        'match': MatchCard,
        'number': NumberCard,
        'page': PageCard,
        'slideshow': SlideshowCard,
        'upload': UploadCard,
        'video': VideoCard,
        'writing': WritingCard,
    }

    if kind in map:
        return map[kind](data)
Пример #32
0
    def post(self):
        ''' Create new card '''
        board = self.get_board(self.request.get('board_id'))

        card = Card(board_key=board.key,
                    content=self.request.get('content'),
                    author_key=self.current_ganban_user().key)
        card.put()

        if settings.SEND_EMAILS:
            self.send_new_card_email(card)

        logging.info("Card with id: %s created.", card.key.id())

        self.send_channel_message('create', card)
        self.response.out.write(json.dumps(card.to_dict()))
Пример #33
0
def test_get_kind():
    """
    Expect to return kind as string given data.
    """

    kind = entity.get_kind(Card({}))
    assert kind == 'card'
Пример #34
0
def flush_entities(db_conn, descs):
    """
    Given a list of kinds and entity_ids,
    return a list filled out with entities.
    """

    output = []

    for desc in descs:
        if desc['kind'] == 'card':
            card = Card.get_latest_accepted(db_conn, entity_id=desc['id'])
            card = flip_card_into_kind(card)
            if card:
                output.append(card)
        elif desc['kind'] == 'unit':
            output.append(Unit.get_latest_accepted(
                db_conn,
                entity_id=desc['id']
            ))
        elif desc['kind'] == 'subject':
            output.append(Subject.get_latest_accepted(
                db_conn,
                entity_id=desc['id']
            ))
        else:
            output.append(None)

    return output
    def sell_card(self, card_name: str, user_name: str):
        user_doc_ref = self.firestore_db.collection(
            self.user_coll_name).document(user_name)
        user = User.from_dict(user_doc_ref.get().to_dict())
        user_owned_cards = [ref.split("/")[-1] for ref in user.cards]
        card_doc_ref = self.firestore_db.collection(
            self.card_coll_name).document(card_name)
        card = Card.from_dict(card_doc_ref.get().to_dict())

        if card_name in user_owned_cards:
            new_value = user.total_currency_value + card.value
            user.set_coins(*User.get_coins_from_value(new_value))
            user_doc_ref.update({
                u'cards':
                firestore_api.ArrayRemove([card_doc_ref.path]),
                u'galleons':
                user.galleons,
                u'sickles':
                user.sickles,
                u'knuts':
                user.knuts
            })
            return user  # Return the new values
        else:
            raise UnownedItemException(
                "You cannot sell that card because you do not own it.",
                user=user)
Пример #36
0
    def test_add_and_get_cards(self):
        uid0 = User.add("test_user1", "password", "*****@*****.**")
        user0 = User.get(uid0)
        uid1 = User.add("test_user2", "password", "*****@*****.**")
        user1 = User.get(uid1)
        bid0 = Board.add("board1", "A")
        lid0 = List.add("List0", bid0)

        caid0 = Card.add("card1", lid0, uid0)
        caid1 = Card.add("card2", lid0, uid1)
        card0 = Card.get(caid0)


        print caid0, user0.get_card_ids()
        assert str(caid0) in user0.get_card_ids()
        assert str(caid1) not in user0.get_card_ids()
Пример #37
0
def get_card_by_kind(card_id):
    """
    Given a card data, return a new card model to replace it by kind.
    """

    card = Card.get_latest_accepted(card_id)
    if not card:
        return

    data, kind = card.data, card.data.get('kind')

    map = {
        'audio': AudioCard,
        'choice': ChoiceCard,
        'embed': EmbedCard,
        'formula': FormulaCard,
        'match': MatchCard,
        'number': NumberCard,
        'page': PageCard,
        'slideshow': SlideshowCard,
        'upload': UploadCard,
        'video': VideoCard,
        'writing': WritingCard,
    }

    if kind in map:
        return map[kind](data)
Пример #38
0
    def test_get_comments_by_card_id(self):
        uid0 = User.add("test1", "password", "*****@*****.**")
        bid0 = Board.add("board1", "A")
        lid0 = List.add("To Do", bid0)

        caid0 = Card.add("card1", lid0, uid0)
        caid1 = Card.add("card2", lid0, uid0)

        coid0 = Comment.add(caid0, uid0, "comment1")
        coid1 = Comment.add(caid1, uid0, "comment2")

        comment0 = Comment.get(coid0)
        comment1 = Comment.get(coid1)

        assert coid0 in [comment.id for comment in Comment.get_comments_by_card_id(caid0)]
        assert coid1 not in [comment.id for comment in Comment.get_comments_by_card_id(caid0)]
Пример #39
0
def get_version(db_conn, kind, id_):
    if kind == 'card':
        card = Card.get(db_conn, id=id_)
        return flip_card_into_kind(card)
    elif kind == 'unit':
        return Unit.get(db_conn, id=id_)
    elif kind == 'set':
        return Set.get(db_conn, id=id_)
Пример #40
0
def get_version(kind, id_):
    if kind == 'card':
        return Card.get(id=id_)
        # TODO-1 This needs to also get the right card kind...
    elif kind == 'unit':
        return Unit.get(id=id_)
    elif kind == 'set':
        return Set.get(id=id_)
Пример #41
0
    def setUp(self):
        db.create_all()

        # initialize 100 cards
        for x in range(0, 100):
            new_card = Card("card" + str(x))
            db.session.add(new_card)
        db.session.commit()
Пример #42
0
def get_rand_card():
    """返回随机 card 或 None."""
    # 实例化 mark_plan
    mark_plan = MarkPlan.new()
    # 实例化 plan
    plan = Plan(mark_plan.is_updated)
    c_id = plan.get_random_id()
    return Card.get_card_by_id(c_id)
Пример #43
0
def get_version(db_conn, kind, id_):
    if kind == 'card':
        card = Card.get(db_conn, id=id_)
        return flip_card_into_kind(card)
    elif kind == 'unit':
        return Unit.get(db_conn, id=id_)
    elif kind == 'set':
        return Set.get(db_conn, id=id_)
Пример #44
0
def get_version(kind, id_):
    if kind == 'card':
        return Card.get(id=id_)
        # TODO-1 This needs to also get the right card kind...
    elif kind == 'unit':
        return Unit.get(id=id_)
    elif kind == 'set':
        return Set.get(id=id_)
Пример #45
0
def get_card_versions_route(request, card_id):
    """
    Get versions card given an ID. Paginates.
    """

    versions = Card.get_versions(entity_id=card_id, **request['params'])
    return 200, {
        'versions': [version.deliver(access='view') for version in versions]
    }
Пример #46
0
def get_card_versions_route(request, card_id):
    """
    Get versions card given an ID. Paginates.
    """

    versions = Card.get_versions(entity_id=card_id, **request['params'])
    return 200, {
        'versions': [version.deliver(access='view') for version in versions]
    }
Пример #47
0
 def draw(self):
     with connection:
         with connection.cursor() as cursor:
             cursor.execute(database.DRAW_A_CARD, (self.id, ))
             _id, suit, value, deck = cursor.fetchone()
             cursor.execute(database.MARK_A_CARD_DRAWN,
                            (datetime.datetime.timestamp(
                                datetime.datetime.now()), _id))
             return Card(suit, value)
Пример #48
0
def test_get_cards(api):
    response = api.get('https://statsroyale.com/api/cards')
    assert response.ok

    cards = []
    for card in response.json():
        cards.append(Card(**card))

    assert len(cards) == 98
Пример #49
0
 def get(self):
     root = self.get_secure_cookie('root')
     if root=='suiyue':
         current_order = get_order()
         cards = Card.get_all_card()
         stories = Story.get_all_story()
         self.render("control.html", order=current_order, cards=cards, stories=stories)
     else:
         self.redirect('/rootlogin')
Пример #50
0
def card_list(request):
    msg = ''
    batch_id = int(request.REQUEST.get('batch_id', '0'))
    page_num = int(request.REQUEST.get('page_num', '1'))    
    if page_num < 1:
        page_num = 1 
    page_num = int(request.REQUEST.get('page_num', '1'))
    page_size = 50
    list_data = []    
    search_type = int(request.REQUEST.get('search_type','0'))
    status = request.REQUEST.get('status','')
    
    sdate = request.REQUEST.get('start_date','')
    edate = request.REQUEST.get('end_date','')
    
    search_val = request.REQUEST.get('search_val','')
    query = ['1=1']
    total_record = 0
    card_batch = None
    list_server = get_server_list()
    server_id = int(request.REQUEST.get('server_id','0'))
    if batch_id > 0:
        query.append(" and batch_id = '%s'"%batch_id)
        try:
            card_batch = CardBatch.objects.using('card').get(id = batch_id)
            key = card_batch.key
            Card._meta.db_table = Card.get_card_table_name(key)
            if search_type != 0 and search_val !='':
                if search_type == 1:
                    query.append(" and number = '%s'"%search_val)
                elif search_type == 2:
                    query.append(" and player_id = '%s'"%search_val)
#                elif search_type == 3:
#                    query.append(" and password = '******'"%search_val)                    
            if server_id != 0:
                query.append(" and server_id = %d "%server_id)
            if status != '':
                try:
                    status = int(status)
                    query.append(" and status = %d "%status)
                except:
                    pass
            if sdate != '' and edate != '':
                query.append(" AND DATE(`use_time`) >= '%s' AND DATE(`use_time`) <= '%s'"%(sdate,edate))
            total_record = Card.objects.using('card').extra(where=[''.join(query)]).count()
            if total_record > 0:
                list_data = Card.objects.using('card').extra(where=[''.join(query)]).order_by('-id')[(page_num - 1) * page_size:page_num * page_size]
                for item in list_data:
                    item.server = ''
                    if item.server_id:
                        the_server = Server.objects.get(id = item.server_id)
                        if the_server:
                            item.server = the_server.name
        except Exception, e:
            print('create card number error:', e)   
            msg = '%s'%e        
Пример #51
0
def add_card():
    log('调用路由')
    form = request.form
    # todo 用户判断
    # u = current_user()
    log(f'Card: {Card}')
    card_id = Card.new(form)
    plan = Plan()
    plan.insert_id(card_id)
    return redirect(url_for('.review', card_id=card_id))
Пример #52
0
 def post(self):
     parsed_args = parser.parse_args()
     card = Card(title=parsed_args['title'], content=parsed_args['content'])
     if 'links' in parsed_args and parsed_args['links'] is not None:
         for l in parsed_args['links']:
             link = Link(url=l['url'])
             card.links.append(link)
     session.add(card)
     session.commit()
     return card, 201
Пример #53
0
 def test_add_and_get(self):
     uid0 = User.add("test1", "password", "*****@*****.**")
     bid0 = Board.add("board1", "A")
     lid0 = List.add("To Do", bid0)
     caid0 = Card.add("card1", lid0, uid0)
     coid0 = Comment.add(caid0, uid0, "comment1")
     comment0 = Comment.get(coid0)
     assert caid0 == comment0.card_id
     assert uid0 == comment0.user_id
     assert "comment1" == comment0.content
Пример #54
0
def get_latest_accepted(kind, entity_id):
    """
    Given a kind and an entity_id, pull the latest accepted
    version out of the database.
    """

    if kind == 'card':
        return Card.get_latest_accepted(entity_id)
        # TODO-1 This needs to also get the right card kind...
    elif kind == 'unit':
        return Unit.get_latest_accepted(entity_id)
    elif kind == 'set':
        return Set.get_latest_accepted(entity_id)
Пример #55
0
def api_get_card(card_id = None):
    if card_id == None:
        return jsonify({'code': 400, 'message': 'Bad Request'})
    else:
        card = Card.get(long(card_id))
        if card == None:
            return jsonify({'code': 404, 'message': 'Page Not Found'})
        _list = List.get(card.list_id)
        return render_template('card.html',
                                card=card,
                                list=_list,
                                edit_card_desc_form=EditCardDescForm(),
                                add_comment_form=AddCommentForm());
Пример #56
0
def get_latest_accepted(db_conn, kind, entity_id):
    """
    Given a kind and an entity_id, pull the latest accepted
    version out of the database.
    """

    if kind == 'card':
        card = Card.get_latest_accepted(db_conn, entity_id)
        return flip_card_into_kind(card)
    elif kind == 'unit':
        return Unit.get_latest_accepted(db_conn, entity_id)
    elif kind == 'set':
        return Set.get_latest_accepted(db_conn, entity_id)
Пример #57
0
def test_language(db_conn, cards_table):
    """
    Expect a card to require a language.
    """

    card, errors = Card.insert({
        'previous_id': 'TJKL35',
        'unit_id': 'RUF531',
        'name': 'What is?',
        'kind': 'video'
    })
    assert len(errors) == 0
    card['language'] = 'en'
Пример #58
0
def test_entity_id(db_conn, cards_table):
    """
    Expect a card to require an entity_id.
    """

    card, errors = Card.insert(db_conn, {
        'previous_id': 'TJKL35',
        'language': 'en',
        'unit_id': 'RUF531',
        'name': 'What is?',
        'kind': 'video'
    })
    assert len(errors) == 0
    assert card['entity_id']
Пример #59
0
def api_edit_card(card_id = None):
    if card_id == None:
        return jsonify({'code': 400, 'message': 'Bad Request'})
    else:
        card = Card.get(long(card_id))
        if card == None:
            return jsonify({'code': 404, 'message': 'Page Not Found'})

    try:
        desc = request.form['desc']
        card.set_description(desc)
    except KeyError:
        return jsonify({'code': 400, 'message': 'Bad Request'})
    return jsonify({'code': 200, 'card_id':card_id}) 
Пример #60
0
def test_unit_id(db_conn, cards_table):
    """
    Expect a card to require a unit id.
    """

    card, errors = Card.insert({
        'previous_id': 'TJKL35',
        'language': 'en',
        'name': 'What is?',
        'kind': 'video'
    })
    assert len(errors) == 1
    card['unit_id'] = 'RUF531A'
    card, errors = card.save()
    assert len(errors) == 0