Esempio n. 1
0
 def __init__(self):
     EA.__init__(self)
     self.beer = Beer()
     self.best_history = None
     self.tests = 40
     self.beer.tests = [
         BeerTest(1 + int(floor(i / (self.tests / 6.0))))
         for i in xrange(self.tests)
     ]
Esempio n. 2
0
 def serve_handler(self, button):
     """
     Callback when serve button was pressed.
     """
     button_pos = list(button.to_window(*button.pos))
     button_pos[0] -= 100
     beer = Beer(lane=button.lane)
     button.lane.puck_area.add_widget(beer)
     button.lane.beers.append(beer)
     beer.pos = beer.to_local(button_pos[0], 15)
Esempio n. 3
0
    def parse_response(self, beer, json, line) -> []:
        ret = []
        variants = len(json['hits'])
        if variants == 1:
            bl = json['hits'][0]

            logger.debug(
                "{} [{}] beer {} from {}, style: {}, rating: {}".format(
                    line, beer, bl['beer_name'], bl['brewery_name'],
                    bl['type_name'], bl.get('rating_score', '0')))

            ret.append(
                Beer(bl['beer_name'],
                     float(bl.get('rating_score', '0')),
                     self.shop,
                     line,
                     brewery_name=bl['brewery_name'],
                     beer_style=bl['type_name']))
        elif variants > 1:
            logger.debug("[{}, hits: {}] Too many results :(".format(
                beer, variants))

            # we want to get only the best match but we store also other if there is no ideal match
            query = self._clean_beer_name_to_compare(beer)
            eliminated_beers = []

            for variant in range(0, variants):
                bl = json['hits'][variant]

                index = self._clean_beer_name_to_compare(bl['beer_index'])

                logger.debug(
                    "\t{} [{}] beer {} from {}, style: {}, rating: {}".format(
                        line, beer, bl['beer_name'], bl['brewery_name'],
                        bl['type_name'], bl.get('rating_score', '0')))

                beer_data = Beer(bl['beer_name'],
                                 float(bl.get('rating_score', '0')),
                                 self.shop,
                                 line,
                                 variant=variant + 1,
                                 brewery_name=bl['brewery_name'],
                                 beer_style=bl['type_name'])
                if index == query:
                    ret.append(beer_data)
                else:
                    eliminated_beers.append(beer_data)
                    logger.debug("{} is not eq to {} for beer {}".format(
                        index, query, bl['beer_name']))
                # we don't want to lose beers if there is no match
                if len(eliminated_beers) == variants:
                    ret.extend(eliminated_beers)
        else:
            logger.debug("[{}, hits: {}] No results :(".format(beer, variants))
        return ret
Esempio n. 4
0
 def update_solr(self, ):
     breweries = self.session.execute(
         "select * from brewery_update WHERE in_solr = FALSE ALLOW FILTERING;"
     )
     for row in breweries:
         brewery = Brewery(row.id, row.name, row.zip, row.city, row.state,
                           row.country)
         brewery.submitBrewery2neo4j()
     beers = self.session.execute(
         "select * from beer_update WHERE in_solr = FALSE ALLOW FILTERING;")
     for row in beers:
         beer = Beer(row.id, row.name, row.brewery, row.brewery_id,
                     row.style_id, row.style, row.abv, row.ibu,
                     row.category_id, row.category)
         beer.submitBeer2neo4j()
Esempio n. 5
0
 def update_listings(self):
     try:
         available = self.parse_soup()
     except Exception as e:
         print
         print 'ERROR PARSING : ' + self.name
         print 'ERROR MESSAGE : ' + str(e)
         print
         return
     self.currently_available = {}
     previously_available = [
         b.title for b in self.all_listings.values() if b.is_available()
     ]
     for beer in available:
         title = beer['title']
         if title not in self.all_listings:
             # we have a new beer listing
             new_beer = Beer(title, beer['link'])
             self.all_listings[title] = new_beer
         else:
             if title not in previously_available:
                 # stocked since last check
                 self.all_listings[title].toggle_availability()
         self.currently_available[title] = self.all_listings[title]
     cur_avail = [b['title'] for b in available]
     for title in previously_available:
         if title not in self.currently_available:
             # it has gone out of stock
             print 'soldout'
             self.all_listings[title].toggle_availability()
     self.save_listings()
Esempio n. 6
0
 def __init__(self, json_data):
   self.photo_id = json_data.get('photo_id')
   self.photo = MediaPhoto(json_data.get('photo')) if json_data.get('photo') else None
   self.created_at = json_data.get('created_at')
   self.venue = None # UNSUPPORTED NOW json_data.get('venue')
   self.checkin_id = json_data.get('checkin_id')
   self.beer = Beer(json_data.get('beer')) if json_data.get('beer') else None
   self.user = None # UNSUPPORTED NOW json_data.get('user')
   self.brewery = Brewery(json_data.get('brewery')) if json_data.get('brewery') else None
Esempio n. 7
0
    def parse_response(self, beer, json, line):
        logger.debug(json)
        ret = []
        variants = json['data']['results']['totalCount']
        if variants == 1:
            bl = json['data']['results']['items'][0]['beer']

            logger.debug(
                "{} [{}] beer {} from {}, style: {}, rating: {}".format(
                    line, beer, bl['name'], bl['brewer']['name'],
                    bl['style']['name'], bl['averageQuickRating']))

            ret.append(
                Beer(bl['name'],
                     float('0' if bl.get('averageQuickRating', '0') is None
                           else bl.get('averageQuickRating')),
                     self.shop,
                     line,
                     brewery_name=bl['brewer']['name'],
                     beer_style=bl['style']['name']))
        elif variants > 1:
            logger.debug("[{}, hits: {}] Too many results :(".format(
                beer, variants))
            for variant in range(0, min(
                    10, variants)):  # TODO ath this moment max 10 per page
                bl = json['data']['results']['items'][variant]['beer']

                logger.debug(
                    "\t{} [{}] beer {} from {}, style: {}, rating: {}".format(
                        line, beer, bl['name'], bl['brewer']['name'],
                        bl['style']['name'], bl['averageQuickRating']))

                ret.append(
                    Beer(bl['name'],
                         float('0' if bl.get('averageQuickRating', '0') is None
                               else bl.get('averageQuickRating')),
                         self.shop,
                         line,
                         variant=variant + 1,
                         brewery_name=bl['brewer']['name'],
                         beer_style=bl['style']['name']))
        else:
            logger.debug("[{}, hits: {}] No results :(".format(beer, variants))
        return ret
Esempio n. 8
0
class BeerTest(unittest.TestCase):
    def setUp(self):
        self.beer = Beer()

    def test_a_verse(self):
        self.assertEqual(
            self.beer.verse(8),
            "8 bottles of beer on the wall, 8 bottles of beer.\n"
            "Take one down and pass it around, 7 bottles of beer on the wall.\n"
        )

    def test_verse_1(self):
        self.assertEqual(
            self.beer.verse(1),
            "1 bottle of beer on the wall, 1 bottle of beer.\n"
            "Take it down and pass it around, no more bottles of beer on the wall.\n"
        )

    def test_verse_2(self):
        self.assertEqual(
            self.beer.verse(2),
            "2 bottles of beer on the wall, 2 bottles of beer.\n"
            "Take one down and pass it around, 1 bottle of beer on the wall.\n"
        )

    def test_verse_0(self):
        self.assertEqual(
            self.beer.verse(0),
            "No more bottles of beer on the wall, no more bottles of beer.\n"
            "Go to the store and buy some more, 99 bottles of beer on the wall.\n"
        )

    def test_singing_several_verses(self):
        self.assertEqual(
            self.beer.sing(8, 6),
            "8 bottles of beer on the wall, 8 bottles of beer.\n"
            "Take one down and pass it around, 7 bottles of beer on the wall.\n"
            "\n"
            "7 bottles of beer on the wall, 7 bottles of beer.\n"
            "Take one down and pass it around, 6 bottles of beer on the wall.\n"
            "\n"
            "6 bottles of beer on the wall, 6 bottles of beer.\n"
            "Take one down and pass it around, 5 bottles of beer on the wall.\n"
            "\n")

    def test_sing_all_the_rest_of_the_verses(self):
        self.assertEqual(
            self.beer.sing(3),
            "3 bottles of beer on the wall, 3 bottles of beer.\n"
            "Take one down and pass it around, 2 bottles of beer on the wall.\n"
            "\n"
            "2 bottles of beer on the wall, 2 bottles of beer.\n"
            "Take one down and pass it around, 1 bottle of beer on the wall.\n"
            "\n"
            "1 bottle of beer on the wall, 1 bottle of beer.\n"
            "Take it down and pass it around, no more bottles of beer on the wall.\n"
            "\n"
            "No more bottles of beer on the wall, no more bottles of beer.\n"
            "Go to the store and buy some more, 99 bottles of beer on the wall.\n"
            "\n")
Esempio n. 9
0
    def update(self):
        self.ticks += 1

        if len(self.beers) < self.max_beers:
            if self.ticks % 12 == 0:
                self.beers.append(
                    Beer((random.randint(20, self.width - 20), -50),
                         int(0.05 * self.width),
                         self.default_speed + random.random() * 0.25))

        for beer in self.beers:
            beer.move()

        self._delete_beers(
            [beer for beer in self.beers if beer.rect.y > self.height])
Esempio n. 10
0
    def find_match(self):
        candidate_beers = [] # empty array which will contain the cadidates
        # Each bear is coupled to a meal(category). If a beer's meal(category)
        # is the same as the user input it will be considered a candidate.

        # First, we search meal names:
        query = Beer.select().where(Beer.meal == self.input)
        if len(query) > 0: # if the query yields some beers...
            for candidate in query:
                if candidate.name not in [beer.name for beer in candidate_beers]:
                    candidate_beers.append(candidate) #...add those beers to the candidate list

        # Second, we search meal categories:
        query = Beer.select().where(Beer.mealcategory == self.input)
        if len(query) > 0: # if the query yields some beers...
            for candidate in query:
                if candidate.name not in [beer.name for beer in candidate_beers]:
                    candidate_beers.append(candidate) #...add those beers to the candidate list

        # And lastly, we return the best choice:
        if len(candidate_beers) > 0: # if there are any candidate beers...
            candidate_beers = self.assign_scores(candidate_beers) # assign penalty scores to those beers
            candidate_beers.sort(key=lambda x: x.penalties) # sort the candidate list ascending by penalty count

            # This code block prints all the found candidates and their penalty
            # scores to the terminal. Uncomment for debugging purposes, or if
            # you're just curious. ;-)
            for beer in candidate_beers:
               print beer.name.encode('utf8', 'replace')
               print beer.penalties

            return candidate_beers[0] # return the first (best) candidate

        else: # if there are no candidate beers...
            self.emergency_plan(sirens=True) # ...sound the alarm!
            return None
Esempio n. 11
0
def ingest(filename):
    """create a list of beers from data from a csv"""
    with open(filename) as csv_in:
        beer_data_in = csv.reader(csv_in, delimiter=',')
        isHeader = True
        for row in beer_data_in:
            if not isHeader:
                # create beer
                beer = Beer(row[NAME], row[BREWERY], row[LOCATION], row[STYLE],
                            row[SIZE], row[ABV], row[IBU])

                # add beer to list of beers
                lsBeers.append(beer)
            else:
                isHeader = False
    pass
Esempio n. 12
0
 def check_database_for(self, meal_name=None, beer_name=None,
                        category_name=None, user_chat_id=None):
     """Checks the database for various things. Returns truth value."""
     if meal_name:
         query = Meal.select().where(Meal.name == meal_name)
     elif beer_name:
         query = Beer.select().where(Beer.name == beer_name)
     elif category_name:
         query = MealCategory.select().where(MealCategory.name == category_name)
     elif user_chat_id:
         query = User.select().where(User.chat_id == user_chat_id)
     else:
         print 'No query specified!'
         return False
     if len(query) > 0:
         return True # return true when results are found
     return False
Esempio n. 13
0
 def __init__(self, json_data):
     self.checkin_comment = json_data.get('checkin_comment')
     self.media = None  # NOT SUPPORTED json_data.get('media')
     self.created_at = datetime.strptime(
         json_data.get('created_at'), '%a, %d %b %Y %H:%M:%S +0000'
     ) if json_data.get('created_at') else None
     self.venue = None  # NOT SUPPORTED json_data.get('venue')
     self.checkin_id = json_data.get('checkin_id')
     self.comments = json_data.get('comments')
     self.source = None  # NOT SUPPORTED json_data.get('source')
     self.beer = Beer(
         json_data.get('beer')) if json_data.get('beer') else None
     self.user = User(
         json_data.get('user')) if json_data.get('user') else None
     self.rating_score = json_data.get('rating_score')
     self.toasts = None  # NOT SUPPORTED json_data.get('toasts')
     self.brewery = Brewery(
         json_data.get('brewery')) if json_data.get('brewery') else None
     self.badges = None  # NOT SUPPORTED json_data.get('badges')
Esempio n. 14
0
class BeerEA(EA):

    def __init__(self):
        EA.__init__(self)
        self.beer = Beer()
        self.best_history = None
        self.tests = 40
        self.beer.tests = [BeerTest(1 + int(floor(i/(self.tests/6.0)))) for i in xrange(self.tests)]

    def create_individual(self, genotype=None):
        return BeerAgent(self.mutation_rate, genotype)

    def run_fitness_tests(self):
        individuals = self.children #if not self.adults else self.children + self.adults
        for individual in individuals:
            individual.fitness = max(0.001, self.beer.run(individual))
            if individual.fitness > self.best_individual.fitness or not self.best_history:
                self.best_history = self.beer.history

    def run_finals(self):
        self.best_individual.do_tests_on_ann()
Esempio n. 15
0
class BeerEA(EA):
    def __init__(self):
        EA.__init__(self)
        self.beer = Beer()
        self.best_history = None
        self.tests = 40
        self.beer.tests = [
            BeerTest(1 + int(floor(i / (self.tests / 6.0))))
            for i in xrange(self.tests)
        ]

    def create_individual(self, genotype=None):
        return BeerAgent(self.mutation_rate, genotype)

    def run_fitness_tests(self):
        individuals = self.children  #if not self.adults else self.children + self.adults
        for individual in individuals:
            individual.fitness = max(0.001, self.beer.run(individual))
            if individual.fitness > self.best_individual.fitness or not self.best_history:
                self.best_history = self.beer.history

    def run_finals(self):
        self.best_individual.do_tests_on_ann()
Esempio n. 16
0
def load_data(data_dir, file='beer_50000.json', cache_file='cache.pkl'):
    data_dir = Path(data_dir)
    if (data_dir / cache_file).exists():
        logging.info("Loading beer data from cache...")
        with open(data_dir / cache_file, 'rb') as fp:
            reviews, beers = pickle.load(fp)
    else:
        logging.info("Loading beer data from file...")

        beers = {}
        reviews = []
        for review in tqdm(load_json(data_dir, file)):
            beer_id = int(review['beer/beerId'])
            if beer_id not in beers:
                try:
                    beers[beer_id] = Beer.from_json(review)
                except:
                    continue
            beer = beers[beer_id]

            reviews.append(Review.from_json(review, beer))
        with open(data_dir / cache_file, 'wb') as fp:
            pickle.dump((reviews, beers), fp)
    return reviews, beers
Esempio n. 17
0
 def __init__(self, json_data):
   self.beer = Beer(json_data.get('beer')) if json_data.get('beer') else None
   self.brewery = Brewery(json_data.get('brewery')) if json_data.get('brewery') else None
Esempio n. 18
0
 def setUp(self):
     self.beer = Beer()
Esempio n. 19
0
from beer import Beer
from player import Player
from gui import printGUI
from parser import Parser

import sys
           # name hops malt turns
beer = Beer('IPA',15,10,2)
beer2 = Beer('Bud',1,1,4)
beer3 = Beer('Dubble',1,1,4)

beers = [beer,beer2,beer3]

player = Player('Mike',1000,100,1000,[],[])
parser = Parser(player,beers)

beerPrices = {'IPA':50,'Bud':10,'Dubble':50}
resourcePrices = {'hops':10,'malt':2 }

def buy(noun,quantity):
    if noun == 'hops':
      player.buyHops(quantity,resourcePrices['hops'])
    elif noun == 'malt':
      player.buyMalt(quantity,resourcePrices['malt'])
    else:
        print "that's not for sale"

def getBeer(noun):
    for beer in beers:
        if noun == beer.name.lower():
            return beer
Esempio n. 20
0
query_messages = {
    "BbC": "beer by countries",
    "BbS": "beer by sorts",
    "BfL": "beer full list",
    "bBbC": "bottled beer by countries",
    "bBbS": "bottled beer by sorts",
    "bBfL": "bottled beer full list",
    "bookfordate": "book for date"
}
day = 0
test_beer_list = [
    Beer(
        "Meizels Weisse",
        "Germany",
        "some brewery",
        10,
        5.5,
        "https://untappd.com/b/brauerei-gebr-maisel-maisel-s-weisse-original/35642",
        type="Weize beer",
        bottled=False),
    Beer("French Beer", "France", "some brewery", 10, 5.5,
         "https://untappd.com/b/ratio-beerworks-dear-you/955352",
         "French Type", False),
    Beer(
        "Second German beer",
        "Germany",
        "some brewery",
        10,
        5.5,
        "https://untappd.com/b/warsteiner-warsteiner-premium-verum-german-pilsener/10703",
        type="Warsteiner",
Esempio n. 21
0
 def __init__(self):
     EA.__init__(self)
     self.beer = Beer()
     self.best_history = None
     self.tests = 40
     self.beer.tests = [BeerTest(1 + int(floor(i/(self.tests/6.0)))) for i in xrange(self.tests)]
Esempio n. 22
0
inv = Inventory()


def json_serialize(_filename, _object):
    with open('data/' + _filename + '.json', 'w', encoding='utf-8') as output:
        json.dump(json.loads(jsonpickle.encode(_object, unpicklable=False)),
                  output,
                  indent=4,
                  ensure_ascii=False)


with open('data/beers.json', encoding='utf-8') as beers_json:
    data = json.load(beers_json)
    for b in data:
        inv.push(
            Beer(b['type'], b['name'], b['id'], b['price'], b['alcohol'],
                 b['ingredients'], b['isCan']), b['brand'])

feladat1 = inv
feladat2 = inv.search_by_type("Búza")
feladat3 = inv.cheapest_brand()
feladat4 = inv.lack_of_ingredient("búza")
feladat5 = inv.create_water_list()
bonus = inv.create_hash_map()

json_serialize('feladat1', feladat1)
json_serialize('feladat2', feladat2)
json_serialize('feladat3', feladat3)
json_serialize('feladat4', feladat4)
json_serialize('feladat5', feladat5)
json_serialize('bonus', bonus)
 def setUp(self):
     self.beer = Beer()
Esempio n. 24
0
def test_name():
    b = Beer("Guinness", "12/12 OZ. BTL", "Stout", "30.00")
    assert b.get_name() == "Guinness"
    assert b.get_size() == "12/12 OZ. BTL"
    assert b.get_style() == "Stout"
    assert b.get_price() == "30.00"
class BeerTest(unittest.TestCase):
    def setUp(self):
        self.beer = Beer()

    def test_a_verse(self):
        self.assertEqual(
            self.beer.verse(8),
            "8 bottles of beer on the wall, 8 bottles of beer.\n"
            "Take one down and pass it around, 7 bottles of beer on the wall.\n"
        )

    def test_verse_1(self):
        self.assertEqual(
            self.beer.verse(1),
            "1 bottle of beer on the wall, 1 bottle of beer.\n"
            "Take it down and pass it around, no more bottles of beer on the wall.\n"
        )

    def test_verse_2(self):
        self.assertEqual(
            self.beer.verse(2),
            "2 bottles of beer on the wall, 2 bottles of beer.\n"
            "Take one down and pass it around, 1 bottle of beer on the wall.\n"
        )

    def test_verse_0(self):
        self.assertEqual(
            self.beer.verse(0),
            "No more bottles of beer on the wall, no more bottles of beer.\n"
            "Go to the store and buy some more, 99 bottles of beer on the wall.\n"
        )

    def test_singing_several_verses(self):
        self.assertEqual(
            self.beer.sing(8, 6),

            "8 bottles of beer on the wall, 8 bottles of beer.\n"
            "Take one down and pass it around, 7 bottles of beer on the wall.\n"
            "\n"
            "7 bottles of beer on the wall, 7 bottles of beer.\n"
            "Take one down and pass it around, 6 bottles of beer on the wall.\n"
            "\n"
            "6 bottles of beer on the wall, 6 bottles of beer.\n"
            "Take one down and pass it around, 5 bottles of beer on the wall.\n"
            "\n"
        )

    def test_sing_all_the_rest_of_the_verses(self):
        self.assertEqual(
            self.beer.sing(3),

            "3 bottles of beer on the wall, 3 bottles of beer.\n"
            "Take one down and pass it around, 2 bottles of beer on the wall.\n"
            "\n"
            "2 bottles of beer on the wall, 2 bottles of beer.\n"
            "Take one down and pass it around, 1 bottle of beer on the wall.\n"
            "\n"
            "1 bottle of beer on the wall, 1 bottle of beer.\n"
            "Take it down and pass it around, no more bottles of beer on the wall.\n"
            "\n"
            "No more bottles of beer on the wall, no more bottles of beer.\n"
            "Go to the store and buy some more, 99 bottles of beer on the wall.\n"
            "\n"
        )