def test_empty_properties(self): # Default values. self.assert_card_json(models.Card(), front='', back='', tags=None) # Null handling. Setting "tags" to None is an error in NDB, though. card = models.Card(front=None, back=None, tags=[]) self.assert_card_json(card, front='', back='', tags=None)
def add_cards(self, request, slug=None): obj = self.get_object() serializer = serializers.AddCardToDeckSerializer(data=request.data, many=True) if serializer.is_valid(): for d in serializer.data: print d try: #try to find card and add c = models.Card.objects.get(pk=d['card']['pk']) if c.user_created is not request.user: c = models.Card(text=c.text, flavor_text=c.flavor_text, user_created=request.user) c.save() obj.add_card(c, d['count']) except: c = models.Card(text=d['card']['text'], flavor_text=d['card']['flavor_text'], user_created=request.user) c.save() obj.add_card(c, d['count'], True) return Response( serializers.DeckSimpleSerializer(obj, many=False).data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def test_card_str(self): card1 = models.Card('Diamonds', 'A') card2 = models.Card('Hearts', 'J') card3 = models.Card('Spades', 5) self.assertEqual(card1.__str__(), "Ace of Diamonds") self.assertEqual(card2.__str__(), "Jack of Hearts") self.assertEqual(card3.__str__(), "5 of Spades")
def test_deck_gen(self): deck = models.Deck() card_first = models.Card("Hearts", 'A') card_last = models.Card(None, 'JOKER') self.assertEqual(len(deck.stack), 54) self.assertEqual(deck.stack[0], card_first) self.assertEqual(deck.stack[-1], card_last)
def test_simple_card(self): kwargs = {'front': 'Hello', 'back': 'World', 'tags': ['in-text']} self.assert_card_json(models.Card(**kwargs), **kwargs) # Now again but with markdown. kwargs = { 'front': 'Hello\n====', 'back': '* World', 'tags': ['in-text'], 'input_format': 'markdown' } self.assert_card_json(models.Card(**kwargs), **kwargs)
def post (self): res = False ret_dict= {} email = self.request.get('email','') id = self.request.get('id','') cardExist = checkIfEmailOrIdExist(email, id) if (cardExist == True or id == ''): ret_dict[constants.STATUS_CODE] = constants.ERROR ret_dict["MESSAGE"] = "Code patient ou Email existant" self.write(json.dumps(ret_dict)) return card = models.Card() m = self.request.params res = populateValuesToCard(m, card) if res == True: card_key = card.put() #session['active_card'] = card_key ret_dict[constants.STATUS_CODE] = constants.STATUS_OK else: ret_dict[constants.STATUS_CODE] = constants.ERROR ret_dict["MESSAGE"] = "Une erreur est survenue pendant la sauvegarde, merci de ressayer" self.write(json.dumps(ret_dict))
def get_deck_needs(self, name): link = self.br.find_link(text_regex=name) self.br.follow_link(link) price_total_from = 0.0 price_total_avg = 0.0 # read wants lists utf8_parser = etree.HTMLParser(encoding='utf-8') tree = etree.fromstring(self.br.response().read().decode('utf-8'), parser=utf8_parser) wl = models.WantList(0, name) print u'Deck: %s\n' %name for wlnode in tree.xpath('//table[contains(@class, "deck")]/tr'): cnarr = wlnode.xpath('td[contains(@class, "card_name")]') if (len(cnarr) > 0 ): id = wlnode.attrib['id'] havearr = wlnode.xpath('td[contains(@id, "card_count_Inventory_' + id + '")]') reqarr = wlnode.xpath('td[contains(@id, "card_count_Deck_' + id + '")]') cn = etree.tostring(cnarr[0], method="text").strip() have = int(etree.tostring(havearr[0], method="text").strip()) req = int(etree.tostring(reqarr[0], method="text").strip()) need = max(0, req-have) if ( need > 0): price, expansion = self.get_cheapest(cn) card = models.Card("", cn) want = models.Want(card, need) wl.wants.append(want) print u'%d %s (%s) @ \u20ac%.2f = \u20ac%.2f' % (need, cn, expansion, price, price*need) price_total_avg = price_total_avg + price*need print u'\nTotal: \u20ac%.2f' % price_total_avg
def get_wants_list(self): link = self.br.find_link(url="/?mainPage=showWants") self.br.follow_link(link) # read wants lists wants_lists = [] utf8_parser = etree.HTMLParser(encoding='utf-8') tree = etree.fromstring(self.br.response().read().decode('utf-8'), parser=utf8_parser) for wlnode in tree.xpath('//select[@name="sw_WantsListID"]/option'): name = re.search(r"([\w\s]+) ", wlnode.text) wl = models.WantList(int(wlnode.attrib['value']), name.group(1)) # read wants card self.br.open(self.base + wl.url()) tree = etree.fromstring(self.br.response().read().decode('utf-8'), parser=utf8_parser) for wantnode in tree.xpath( '//table[contains(@class, "wantsTable")]/tbody/tr'): node = wantnode.xpath('td[3]/a')[0] card = models.Card(node.attrib['href'], node.text) node = wantnode.xpath('td[11]')[0] want = models.Want(card, int(node.text)) wl.wants.append(want) wants_lists.append(wl) return wants_lists
def test_simple_card(self): kwargs = { 'front': 'Hello\n====', 'back': '* World', 'tags': ['in-text'] } self.assert_card_json(models.Card(**kwargs), **kwargs)
def card_import(handler): """Import another user's existing Card to the current user's account. Called with the form: /api/card/<card_id>/import """ user_data = get_current_user(handler) if not user_data: return path = handler.request.path card_key = path[len('/api/card/'):-len('/import')] card = ndb.Key(urlsafe=card_key).get() if not card: return "card not found" if user_data.key == card.user_key: # Disallow importing a card this user already owns return "can't import your own card" # Finally ready to do the update new_card = models.Card() new_card.populate(**card.to_dict()) new_card.user_key = user_data.key new_card.update_email_and_nickname() new_card.put() search.insert_cards([new_card]) # Update the list of all known tags for this user user_data.update_card_tags([], new_card.tags) user_data.put() # TODO(jace): only put if necessary # TODO(jace) Notify followers return new_card.key.urlsafe()
def cardInfo(image) -> models.Card: """ Calls __getCardValue and __getCardColor and returns Card object """ card = models.Card(__getCardValue(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)), __getCardColor(image)) return card
def from_json(cls, json_str): obj = json.loads(json_str) assert obj.get("format") == "JSONCardArchive", obj.get("format") assert obj.get("version") == "v1", obj.get("version") assert "cards" in obj cards = [] for card_obj in obj["cards"]: card = models.Card() card.update_from_dict(card_obj) cards.append(card) archive = _JSONCardArchive(cards) return archive
def load_test_data(self): with open('test_data.json', 'r') as fout: data = json.load(fout) for card_json_key in data['cards']: card_json = data['cards'][card_json_key] self.post_card(m.Card( card_json['PAN'], card_json['exp_date'], card_json['PIN'], card_json['cardholder_name'], card_json['balance'], ))
def copy(self, request, pk=None): try: obj = self.get_object() self.check_object_permissions(request, obj) c = models.Card(text=obj.text, flavor_text=obj.flavor_text, user_created=request.user) c.save() serializer = serializers.CardSerializer(c, many=False) return Response(serializer.data, status=status.HTTP_200_OK) except Exception, e: print e return Response({'status': 'Error copying card'}, status=status.HTTP_400_BAD_REQUEST)
def build_card(): if session.get('user'): card = models.Card(slug='-'.join(rw.random_words(count=4)), owner=g.user, privacy='public', playable='yes', values=[''] * 25) card.save() card.short_id = models.short_id(card) card.save() g.user.cards.append(card) g.user.save() return redirect('/build/{}'.format(card.slug)) else: return redirect('/login')
def add_card(): """Add card to database.""" if request.method == 'POST': data = request.form.to_dict() if user_loggined(): uid = session.get('user_id') cnb1 = data.get('cnb1') cnb2 = data.get('cnb2') cnb3 = data.get('cnb3') cnb4 = data.get('cnb4') c_type = data.get('type') vval = data.get('vval') month = data.get('month') year = data.get('year') if c_type in ['visa', 'master'] and \ check_int(cnb1, 4) and \ check_int(cnb2, 4) and \ check_int(cnb3, 4) and \ check_int(cnb4, 4) and \ check_int(vval, 3) and \ check_int(month, 2) and \ check_int(year, 2): card = models.Card(type=c_type, cnb=' '.join([cnb1, cnb2, cnb3, cnb4]), month=month, year='20' + year, vval=vval, user_id=uid) db.session.add(card) db.session.commit() else: session['error'] = {} session['error']['card'] = True if c_type not in ['visa', 'master']: session['error_msg'] = 'Unknown card type.' elif not (check_int(cnb1, 4) and check_int(cnb2, 4) and check_int(cnb3, 4) and check_int(cnb4, 4)): session['error_msg'] = 'Invalid card number.' elif not check_int(month, 2): session['error_msg'] = 'Invalid expiry month.' elif not check_int(year, 2): session['error_msg'] = 'Invalid expiry year.' else: session['error_msg'] = 'Something went wrong.' return redirect(url_for('index') + '#card') return redirect(url_for('index') + '#order')
def card_add(handler): """Add a new Card.""" user_data = get_current_user(handler) if not user_data: return data = json.loads(handler.request.body) card = models.Card(user_key=user_data.key) card.update_from_dict(data) card.update_email_and_nickname() card.put() search.insert_cards([card]) # Update the list of all known tags for this user # Update the list of all known tags for this user user_data.update_card_tags([], data.get('tags', [])) user_data.put() # TODO(jace): only put if necessary # TODO(jace) Notify followers return card.key.urlsafe()
def test_trade_cards_for_troops(self): cards = [ models.Card("country_A", "whiskey"), models.Card("country_B", "gin"), models.Card("country_C", "tequila") ] self.players.current_player.cards = set(cards) trade_1_troops = self.game.get_troops_for_card_set(cards) self.assertEqual(trade_1_troops, 4) self.players.current_player.cards = set(cards) trade_2_troops = self.game.get_troops_for_card_set(cards) self.assertEqual(trade_2_troops, 6) cards2 = [ models.Card("cowLand", "cow"), models.Card("mexico", "horse"), models.Card("canada", "horse") ] self.players.current_player.cards = set(cards2) with self.assertRaises(AssertionError): trade_3_troops = self.game.get_troops_for_card_set(cards2)
def test_card_init(self): card = models.Card('Spades', 'A') self.assertEqual(card.suit, 'Spades') self.assertEqual(card.display_value, 'A')
def test_deck_draw(self): deck = models.Deck() card = models.Card(None, 'JOKER') self.assertEqual(card, deck.draw())
def test_card_eq(self): card1 = models.Card('Diamonds', 'A') card2 = models.Card('Diamonds', 'A') self.assertEqual(card1, card2)
def test_card_val_change(self): card = models.Card('Hearts', 10) card.value += 5 self.assertEqual(card.display_value, 10) self.assertEqual(card.value, 15)
def get_cart(self): utf8_parser = etree.HTMLParser(encoding='utf-8') tree = etree.fromstring(self.br.response().read().decode('utf-8'), parser=utf8_parser) node = tree.xpath('//*[@id="sc_menuhub"]') if node: m = re.search("\((\d+) articles", node[0].text) na = 0 if m: na = int(m.group(1)) if na == 0: return models.Cart() link = self.br.find_link(url="/?mainPage=showShoppingCart") self.br.follow_link(link) tree = etree.fromstring(self.br.response().read().decode('utf-8'), parser=utf8_parser) # create cart c = models.Cart(tree.xpath('//*[@id="sc_hashCode"]/@value')[0]) # ships for shipnode in tree.xpath('//div[@class="sc_ShipTable"]'): # id shipid = int(shipnode.xpath('div/@id')[0].split('_')[-1]) # hash bhash = shipnode.xpath('.//button/@onclick')[0] m = re.search("jcp\('([^']+)'", bhash) if m: bhash = m.group(1) # sumary sumarynode = shipnode.xpath('.//table[@class="nestedContent"]')[2] # read seller node = sumarynode.xpath( './/a[contains(@href, "showSellerChart")]')[1] seller = models.Seller(id=node.attrib['href'], name=node.text) # ship s = models.Ship(shipid, bhash, c, seller) # shipping node = sumarynode.xpath('tr[6]/td[2]/text()')[0] m = re.search("([\d,]+) ", node) if m: s.shipping = float(m.group(1).replace(',', '.')) # shipping method node = None for tr in sumarynode.xpath('tr'): td = tr.xpath('td/text()')[0] if td.find('Shipping Method') != -1: node = tr if node is not None: m = re.search("\(([\w\s]+)\)", etree.tostring(node)) if m: s.shipping_method = m.group(1) # items for item in shipnode.xpath( './/form[contains(@name, "itemViewForm")]/table/tbody/tr'): idcard = item.xpath('td[2]/a/@href')[0] namecard = item.xpath('td[2]/a/text()')[0] pricecard = item.xpath('td[9]/text()')[0] m = re.search("([\d,]+) ", pricecard) if m: pricecard = float(m.group(1).replace(',', '.')) langcard = item.xpath('td[5]/a/span/@onmouseover')[0] m = re.search("\('([\w\s]+)'\)", langcard) if m: langcard = m.group(1) expansion = item.xpath('td[3]/span/@onmouseover')[0] m = re.search("\('([\w\s]+)'\)", expansion) if m: expansion = m.group(1) condition = item.xpath('td[6]/a/img/@onmouseover')[0] m = re.search("\('([\w\s]+)'\)", condition) if m: condition = m.group(1) quantity = int(item.xpath('td[2]/text()')[0][0:-2]) card = models.Card(idcard, namecard) cardarticle = models.CardArticle(card, pricecard, langcard, expansion, condition, quantity) s.articles.append(cardarticle) c.ships.append(s) return c
def search(self, query, lang='en'): pagenow = 0 npages = None utf8_parser = etree.HTMLParser(encoding='utf-8') while pagenow < npages or npages is None: # print "PAGE: {0}/{1}".format(pagenow, npages) self.br.open( "{0}?mainPage=showSearchResult&searchFor={1}&resultsPage={2}". format(self.base, query.replace(" ", "+"), pagenow)) tree = etree.fromstring(self.br.response().read().decode('utf-8'), parser=utf8_parser) # number of pages if npages is None: href = tree.xpath( '//*[@id="siteContents"]/div/div[1]/span[3]/a[2]/@href') npages = 1 if len(href): m = re.search('resultsPage=(\d+)', href[0]) npages = int(m.group(1)) + 1 # serach table tree2 = tree.xpath( "//table[contains(@class, 'SearchTable')]/tbody") if len(tree2) == 0: result = { 'img': '', 'expansion': '', 'rarity': '', 'name': '', 'id': '', 'category': '', 'available': '', 'price_from': 0 } data = tree.xpath( "//span[contains(@class, 'prodImage')]/img/@src")[0] if data: result['img'] = data data = tree.xpath( '//h1[contains(@class, "nameHeader")]')[0].text if data: m = re.search("(.*)\((.*)\)", data) result['name'] = m.group(1).strip() result['expansion'] = m.group(2).strip() tree2 = tree.xpath( "//table[contains(@class, 'infoTable')]/tbody")[0] data = tree2.xpath("tr[1]/td[2]/img/@onmouseover") if data: m = re.search("'(.+?)'", data[0]) result['rarity'] = m.group(1) data = tree.xpath( "//input[contains(@name, 'idProduct')]/@value")[0] if data: result['id'] = result['name'].replace( " ", "_") + "_" + result['expansion'].replace( " ", "_") + ".c1p" + data + ".prod" tree2 = tree.xpath( '//table[contains(@class, "availTable")]/tbody')[0] avstr = tree2.xpath('tr/td[2]')[0].text if (avstr is None): result['available'] = 0 else: result['available'] = int(avstr) if (result['available'] > 0): pfstr = tree2.xpath('tr/td[2]')[1].text.replace( ",", ".").replace(u'\u20ac', "") if (pfstr != "N/A"): result['price_from'] = float(pfstr) else: result['price_from'] = 0.0 else: result['price_from'] = price_from = 0.0 c = models.Card(result['id'], name=result['name'], img=result['img']) yield models.SearchResult(c, result['expansion'], result['rarity'], result['category'], result['available'], result['price_from']) tree = tree2[0] # rows rows = tree.xpath("tr[contains(@class, 'row_')]") for row in rows: result = { 'img': '', 'expansion': '', 'rarity': '', 'name': '', 'id': '', 'category': '', 'available': '', 'price_from': 0 } data = row.xpath("td[1]//img/@onmouseover") if data: m = re.search("'(.+?)'", data[0]) result['img'] = m.group(1) data = row.xpath("td[2]/span/@onmouseover") if data: m = re.search("'(.+)'", data[0]) result['expansion'] = m.group(1).strip() data = row.xpath("td[3]/img/@onmouseover") if data: m = re.search("'(.+?)'", data[0]) result['rarity'] = m.group(1).strip() data = row.xpath("td[5]/a") if data: result['id'] = data[0].attrib['href'] result['name'] = data[0].text.strip() data = row.xpath("td[6]") if data: result['category'] = data[0].text.strip() data = row.xpath("td[7]") if data: result['available'] = int(data[0].text) data = row.xpath("td[8]") if data: if data[0].text == u"N/A": result['price_from'] = 0 else: m = re.search("(\d+,\d+) ", data[0].text) result['price_from'] = float( m.group(1).replace(',', '.')) if (result['name'] == query): if (result['expansion'].find(u'WCD') < 0 and result['expansion'].find(u'Collectors\\\' Edition') < 0 and result['expansion'].find(u'International Edition') < 0): c = models.Card(result['id'], name=result['name'], img=result['img']) yield models.SearchResult(c, result['expansion'], result['rarity'], result['category'], result['available'], result['price_from']) # next page pagenow += 1