Ejemplo n.º 1
0
class BookTest(unittest.TestCase):
	mozzarella = Recipe('mozzarella_sticks', 3, 20, ['mozzarella', 'sticks'], "", "starter")
	nugget = Recipe('nugget', 4, 65, ['chicken', 'bread'], "", "starter")
	omelette = Recipe('omelette au fromage', 2, 10, ['eggs', 'cheese', 'pepper'], "", "lunch")
	fondant = Recipe('fondant', 4, 30, ['eggs', 'chocolate', 'butter'], "", "dessert")
	creation = datetime.datetime(2019, 4, 13, 00, 00, 00)
	last = datetime.datetime(2019, 5, 27, 00, 00, 00)
	recipe_list = {
		'starter': {
			mozzarella,
			nugget,
		},
		'lunch': {
			omelette,
		},
		'dessert': {
			fondant,
		}
	}
	test_book = Book("Text Book", last, creation, recipe_list)

	def test_get_recipe_by_type_method(self):
		gibberish_type = "blabla"
		integer_type = 123

		with self.assertRaises(SystemExit):
			self.test_book.get_recipes_by_type(gibberish_type)
			self.test_book.get_recipes_by_type(integer_type)

	def test_get_recipe_by_name_method(self):
		non_existing_name = "blabla"
		int_name = 123
		empty_name = ""

		with self.assertRaises(SystemExit):
			self.test_book.get_recipes_by_type(non_existing_name)
			self.test_book.get_recipes_by_type(int_name)
			self.test_book.get_recipes_by_type(empty_name)

	def test_add_recipe_method(self):
		non_recipe_object = "blabla"

		with self.assertRaises(SystemExit):
			self.test_book.add_recipe(non_recipe_object)

	def test_add_recipe_does_the_adding(self):
		recipe_to_add = Recipe('pasta', 1, 9, ['pasta', 'water'], "", 'lunch')
		self.test_book.add_recipe(recipe_to_add)
		type_of_added_recipe = recipe_to_add.recipe_type

		self.assertIn(recipe_to_add, self.test_book.recipes_list[type_of_added_recipe])

	def test_add_recipe_method_update_time(self):
		recipe_to_add = Recipe('cheesecake', 5, 45, ['cheese', 'cake'], "", 'dessert')
		last_update1 = self.test_book.last_update
		self.test_book.add_recipe(recipe_to_add)
		self.test_book.print_content_recipe_list()
		last_update2 = self.test_book.last_update

		self.assertNotEqual(last_update1, last_update2)
Ejemplo n.º 2
0
def parse_input(file):
    B = 0
    L = 0
    D = 0
    libraries = []
    books = []

    with open("input/" + file, "r") as input:
        lines = input.readlines()
        [B, L, D] = [int(i) for i in lines[0].split(" ")]
        book_scores = [int(i) for i in lines[1].split(" ")]

        for idx, score in enumerate(book_scores):
            books.append(Book(score, idx))

        lines = lines[2:]
        for idx, line in enumerate(lines):

            if line == "\n":
                break

            if idx % 2 == 0:
                libraries.append(
                    Library(lines[idx], lines[idx + 1], idx // 2, books))

    return Problem(B, L, D, books, libraries)
Ejemplo n.º 3
0
    def generate_item(call_num):
        user_input = None
        # If entered invalid option, loops user back to choices below
        while user_input != 4:
            print("What type of item would you like to add")
            print("1. Book")
            print("2. DVD")
            print("3. Journal")
            print("4. Back")
            string_input = input("Please enter your choice (1-4)")
            user_input = int(string_input)
            title = input("Enter title: ")
            num_copies = int(input("Enter number of copies (positive number): "))
            item_data = (call_num, title, num_copies)

            # creates the item object of input choice
            if user_input == 1:
                author = input("Enter Author Name: ")
                return Book(item_data[0], item_data[1], item_data[2], author)
            if user_input == 2:
                release_date = input("Enter release date (yyyy/mm/dd): ")
                code = input("Enter region code: ")
                return DVD(item_data[0], item_data[1], item_data[2], release_date, code)
            if user_input == 3:
                names = input("Enter names")
                issue_number = input("Please enter issue number")
                publisher = input("Enter publisher")
                return Journal(item_data[0], item_data[1], item_data[2], names, issue_number, publisher)
            # return to menu
            if user_input == 4:
                pass
Ejemplo n.º 4
0
 def adding_book(self, this_author, appInfo):
     if self.lineEdit_4.text():
         if self.lineEdit.text():
             book = self.lineEdit_4.text()
             self.lineEdit_4.setText("")
             if book not in this_author.book_list:
                 this_author.book_list.append(book)
             this_book = Book(book, self.lineEdit.text())
             if this_book not in appInfo.library.book_list:
                 appInfo.library.add_book_object(this_book)
                 appInfo.books_database.insert_one({
                     "name":
                     this_book.name,
                     "author":
                     this_book.author,
                     "year":
                     this_book.year,
                     "description":
                     this_book.description,
                     "tags":
                     this_book.tag_list,
                     "genres":
                     this_book.genre_list
                 })
                 message = CreateABook(appInfo, this_book)
                 message.exec_()
         else:
             message = ErrorDialog()
             message.label_2.setText("Enter a name first.")
             message.exec_()
     self.update_tables(this_author)
Ejemplo n.º 5
0
def reading_file(name, books, libraries):
    #print("Reading file")
    mon_fichier = open(name, "r")
    content = mon_fichier.readlines()
    nb_books = content[0].split(" ")[0]
    nb_libraries = content[0].split(" ")[1]
    nb_days_scanning = content[0].split(" ")[2]

    for idx, livre in enumerate(content[1].split(" ")):
        new_book = Book(idx, int(livre))
        books.append(new_book)

    for idx, library in enumerate(content[2:]):
        if len(library) > 2:
            #print(idx, library)
            if idx % 2 == 0:
                new_library = Library(int(idx / 2), [],
                                      int(library.split(" ")[1]),
                                      int(library.split(" ")[2]))
                libraries.append(new_library)
            else:
                libraries[-1].books = []
                temp_list_livres = library.split(" ")
                for num in temp_list_livres:
                    num = int(num)
                    libraries[-1].books.append(books[num])
        #time.sleep(0.01)

    mon_fichier.close()
    return int(nb_days_scanning)
Ejemplo n.º 6
0
    def addBook(self, author, country, imageLink, language, link, pages, title, year):


        """
        books리스트에 Book클래스로 추가하고 bookset.json에 추가로 저장할것
        :param author:
        :param country:
        :param imageLink:
        :param language:
        :param link:
        :param pages:
        :param title:
        :param year:
        :return:
        """
        self.books.append(Book(author, country, imageLink, language, link, pages, title, year))
        json_data = []
        obj = {"author": author, "country": country, "imageLink": imageLink, "language": language, "link": link,
               "pages": pages, "title": title, "year": year}

        with open('bookset.json') as f:
            json_data = json.load(f)
        json_data.append(obj)

        with open('bookset.json', 'w') as f:
            json.dump(json_data, f)
        print(f'성공적으로 책제목: {obj["title"]}을 저장하였습니다.')
Ejemplo n.º 7
0
    def insert_book(self):
        if (not self.title_input.text or not self.author_input.text
                or not self.length_input.text):
            self.parent.book_list_panel.status_bar_text = \
                'All fields must be completed!'
            return

        try:
            length = int(self.length_input.text)
        except Exception as e:
            print(e)
            self.parent.book_list_panel.status_bar_text = \
                'Please enter a valid number!'
            return

        if length <= 0:
            self.parent.book_list_panel.status_bar_text = \
                'Pages must be a positive integer!'
            return

        book = Book(self.title_input.text, self.author_input.text, length,
                    False)

        self.parent.book_list_panel.book_list.add(book)
        self.parent.book_list_panel.book_list.save()
        self.parent.book_list_panel.refresh_books(False)

        self.parent.book_list_panel.status_bar_text = \
            'Book added successfully!'
def create_book_list():
    book_list = []
    for i in range(0, 10):
        book_list.append(Book())

    with open('resources/book_list', 'wb') as fp:
        pickle.dump(book_list, fp)
Ejemplo n.º 9
0
 def seach_command(self):
     self.results_list.delete(0, END)
     book = Book(title=self.title_entry.get(), author=self.author_entry.get(), year=self.year_entry.get(), isbn=self.isbn_entry.get())
     rows = self.storage.search(book)
     for row in rows:
         self.results_list.insert(END, row)
     self.clear_entries()
Ejemplo n.º 10
0
 def test_constructor_vacio(self):
     book = Book()
     self.assertDictEqual(book.__dict__, {
         '_name': '',
         '_authorName': '',
         '_memberLegajo': ''
     })
Ejemplo n.º 11
0
 def add(self, **data):
     shelf = self.context
     book = Book()
     self.applyData(book, **data)
     name = INameChooser(shelf).chooseName(data.get('title'), book)
     shelf[name] = book
     self.redirect(self.url(shelf))
 def create_book(item_info: dict) -> Book:
     """
     Creates a book.
     """
     author = input("Enter Author Name: ")
     item_info["author"] = author
     return Book(**item_info)
Ejemplo n.º 13
0
 def add_book(self,
              book=Book(),
              campus_location="西馆书库四层南 社科图书库",
              call_no="I712.4/W015-3/(1)",
              number=3):
     print("正在向" + self.name + "添加《" + book.title + "》......")
     # 先查重
     try:
         index = self.collection['isbn'].index(book.isbn)
     except ValueError:
         book.number = number
         book.campus_location = campus_location
         book.return_book_position = self.return_book_position + "/" + campus_location
         book.call_no = call_no
         for i in range(number):
             book.barcode_and_state_list.append({
                 'barcode':
                 self.get_barcode_no(),
                 'state':
                 "可借"
             })
         self.number_of_collection = self.number_of_collection + number
         self.number_of_type = self.number_of_type + 1
         self.collection['title'].append(book.title)
         self.collection['author'].append(book.author)
         self.collection['isbn'].append(book.isbn)
         self.collection['book'].append(book)
     else:
         print("《" + book.title + "》已存在于" + self.name)
         book.number = book.number + number
         for i in range(number):
             self.collection['book'][index].barcode_and_state_list\
                 .append({'barcode': self.get_barcode_no(), 'state': "可借"})
         self.number_of_collection = self.number_of_collection + number
     print(str(number) + "本《" + book.title + "》添加成功!")
Ejemplo n.º 14
0
def book_add_page():
    searchform = SearchForm()
    if not current_user.is_admin:
        abort(401)
    form = BookEditForm()
    if form.validate_on_submit():
        title = form.data["title"]
        author = form.data["author"]
        year = form.data["year"]
        genres = form.data["genres"]
        genres = genres.split(', ')
        pageNumber = form.data["pageNumber"]
        description = form.data["description"]
        cover = form.data["cover"]
        book = Book(title=title,
                    author=author,
                    year=year,
                    genres=genres,
                    pageNumber=pageNumber,
                    description=description,
                    cover=cover)
        db = current_app.config["db"]
        book_id = db.add_book(book)
        return redirect(url_for("book_page", book_id=book_id))
    return render_template("book_edit.html", form=form, searchform=searchform)
Ejemplo n.º 15
0
def fetch_free_books(url, page):
    r = requests.get(url + str(page), headers=config.header)
    from bs4 import BeautifulSoup, Tag
    import lxml

    bs = BeautifulSoup(r.text, lxml.__name__)
    items = bs.find_all('li', attrs={'class': 's-result-item celwidget'})

    kindle = {'books': []}

    for item in items:
        if isinstance(item, Tag):
            book = Book()
            book.title = item.find('h2').text
            # book.item_id = item.find('span', attrs={'name': re.compile('.*')}).get('name')
            book.item_id = item.get('data-asin')
            book.url = base_url + book.item_id
            book.average = 0
            book.price = 0
            book.min = 0
            score = item.find('span', attrs={'class': 'a-icon-alt'})
            if score:
                book.score = re.match('平均(.*) 星', score.text).group(1)

            import amz
            amz.lookup(book)

            kindle['books'].append(book)

    kindle['count'] = len(kindle['books'])
    kindle['page'] = page
    return kindle
Ejemplo n.º 16
0
def read_input_file(filename: str) -> File:
    """Reads the data of input problem

    returns:
    D: number of days,
    LIBS: list of Library objects,
    BOOKS: list of Book objects,
    """
    lines = list(
        map(lambda x: [int(y) for y in x.strip().split()],
            open(filename).readlines()))
    book_count, libs_count, days = lines[0]
    books = []
    for idx, score in enumerate(lines[1]):
        books.append(Book(idx, score))
    assert len(books) == len(lines[1])

    libraries = []
    for i in range(2, len(lines), 2):
        if len(lines[i]) == 0:
            continue
        num_books, signup_delay, books_per_day = lines[i]

        lib_books = list(map(lambda x: books[x], lines[i + 1]))
        assert len(lib_books) == num_books, f"Incorrect parsing of {line[i]}"
        libraries.append(
            Library((i - 2) // 2, signup_delay, lib_books, books_per_day))

    return File(books, libraries, days)
Ejemplo n.º 17
0
 def get_book(self, book_id):
     with dbapi2.connect(self.db_url) as connection:
         cursor = connection.cursor()
         query1 = "SELECT TITLE, AUTHORID, YR, PGNUM, COVER, DESCRIPTION FROM BOOK WHERE (ID = %s)"
         cursor.execute(query1, (book_id, ))
         title, author_id, year, pageNumber, cover, description = cursor.fetchone(
         )
         author = None
         if author_id:
             query2 = "SELECT NAME FROM AUTHOR WHERE (ID = %s)"
             cursor.execute(query2, (author_id, ))
             author = cursor.fetchone()[0]
         query3 = "SELECT AVG(SCORE) FROM REVIEW WHERE (BOOKID = %s)"
         cursor.execute(query3, (book_id, ))
         avgscore = cursor.fetchone()[0]
         genres = self.get_genres(book_id)
     book_ = Book(id=book_id,
                  title=title,
                  author=author,
                  year=year,
                  genres=genres,
                  pageNumber=pageNumber,
                  cover=cover,
                  description=description,
                  avgscore=avgscore)
     return book_, author_id
Ejemplo n.º 18
0
def get_books(**kwargs):
    ''' Return books from DB. With no arguments, returns everything. '''

    sql = None

    books = []

    if kwargs == None:
        sql = 'SELECT * FROM {}'.format(BOOK_TABLE)

    if kwargs['read'] == True:
        sql = 'SELECT * FROM {} WHERE {} = 1'.format(BOOK_TABLE, READ)

    if kwargs['read'] == False:
        sql = 'SELECT * FROM {} WHERE {} = 0'.format(BOOK_TABLE, READ)

    if sql:

        conn = sqlite3.connect(DB_NAME)
        conn.row_factory = sqlite3.Row  # This type of row can be accessed by column name
        cur = conn.cursor()
        rows = cur.execute(sql)

        for row in rows:
            read_bool = tf_val(row[3])
            book = Book(row[TITLE], row[AUTHOR], read_bool, row[ID])
            books.append(book)

        conn.close()

    return books
Ejemplo n.º 19
0
 def get_books(self, query=None, genre=None, year=None, p=None):
     books = []
     offset = (int(p) - 1) * 12 if (int(p) > 0 and p) else 0
     with dbapi2.connect(self.db_url) as connection:
         cursor = connection.cursor()
         if query:
             query1 = "SELECT ID, TITLE, YR, COVER FROM BOOK WHERE LOWER(TITLE) LIKE LOWER(%s) ORDER BY ID OFFSET %s LIMIT 12"
             query_words = query.split()
             like_pattern = '%'
             for word in query_words:
                 like_pattern += '{}%'.format(word)
             cursor.execute(query1, (like_pattern, offset))
         elif genre:
             query1 = "SELECT BOOK.ID, BOOK.TITLE, BOOK.YR, BOOK.COVER FROM BOOK INNER JOIN GENRES ON BOOK.ID = GENRES.BOOKID WHERE (GENRE = %s) GROUP BY BOOK.ID, BOOK.TITLE, BOOK.YR, BOOK.COVER ORDER BY BOOK.ID OFFSET %s LIMIT 12"
             cursor.execute(query1, (genre, offset))
         elif year:
             query1 = "SELECT ID, TITLE, YR, COVER FROM BOOK WHERE (YR = %s) ORDER BY ID OFFSET %s LIMIT 12"
             cursor.execute(query1, (year, offset))
         else:
             query1 = "SELECT ID, TITLE, YR, COVER FROM BOOK ORDER BY ID OFFSET %s LIMIT 12"
             cursor.execute(query1, (offset, ))
         for book_id, title, year, cover in cursor:
             books.append(
                 Book(id=book_id, title=title, year=year, cover=cover))
     return books
Ejemplo n.º 20
0
def main() -> None:
    refactoring = Book("Refactoring: imporving the design of existing code",
                       "ISBN323232", "$44.95", "Martin Fowloer",
                       "*****@*****.**")

    print("rafactoring: ")
    print(refactoring.to_xml())
Ejemplo n.º 21
0
    def hydrate_books(self):
        self.login()
        self.logger.debug('Waiting for books to be fetched...')
        locator = self.driver.find_element_by_css_selector(
            '.myAccountLoadingHolder')
        WebDriverWait(self.driver, 10).until(
            expected_conditions.invisibility_of_element_located(locator))
        dom_books = self.driver.find_elements_by_css_selector('.checkoutsLine')

        # TODO: Find element with corresponding index (0, 1, 2, etc) as ID detailZone[INDEX] (ex. detailZone0)
        # ^(need to click it first and wait..!)
        # TITLE IS #detail_biblio0 .INITIAL_TITLE_SRCH
        # AUTHOR IS #detail_biblio0 .PERSONAL_AUTHOR
        # PAGES AND SIZE IS #detail_biblio0 .PHYSICAL_DESC (needs to be parsed)

        for dom_book in dom_books:
            book_object = Book()
            book_object.author = dom_book.find_element_by_class_name(
                'checkouts_author').text

            book_object.due_date = dom_book.find_element_by_class_name(
                'checkoutsDueDate').text
            book_object.renewed = int(
                dom_book.find_element_by_class_name(
                    'checkoutsRenewCount').text)
            book_object.id = dom_book.find_element_by_class_name(
                'checkouts_itemId').text
            book_object.title = dom_book.find_element_by_class_name(
                'hideIE').text
            self.book_objects.append(book_object)
        self.logger.debug('Books hydrated!')
Ejemplo n.º 22
0
    def __init__(self, conn_details, status_light):
        
        """Setup a connection to MPD to be able to play audio.
        Also update the MPD database with any new MP3 files that may have been added
        and clear any existing playlists.
        """
        self.status_light = status_light
        self.book = Book()
        self.book_titles = []
        
        self.index_lock = RLock()
        self.current_index = -1;

        self.mpd_client = LockableMPDClient()
        with self.mpd_client:
            self.mpd_client.connect(**conn_details)

            self.mpd_client.update()
            self.mpd_client.clear()
            self.mpd_client.setvol(100)
            
            files = self.mpd_client.search('filename', ".mp3")
            if not files:
                self.status_light.interrupt('blink_fast', 3)
            else:
                for file in files:
                    book_title = os.path.dirname(file['file']) + "/"
                    if book_title not in self.book_titles:
                        self.book_titles.append(book_title) 
Ejemplo n.º 23
0
def main():
    book = Book("TEST")
    book.insert_buy(10, 10.0)
    book.insert_sell(120, 12.0)
    book.insert_buy(5, 10.0)
    book.insert_buy(2, 11.0)
    book.insert_sell(1, 10.0)
    book.insert_sell(10, 10.0)
Ejemplo n.º 24
0
 def getbyisbn(self, isbn):
     r = requests.get(
         "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn)
     data = r.json()["items"][0]["volumeInfo"]
     book = Book(data["title"], data["authors"][0],
                 data["industryIdentifiers"][1]["identifier"],
                 data["categories"][0], data["imageLinks"]["thumbnail"])
     return book
Ejemplo n.º 25
0
def save_book():
    content = request.get_json()
    book = Book()
    book_dao = BookDAO()
    book.name = content['name']
    book.type = content['type']
    book_dao.save_book(book)
    return 'saved'
Ejemplo n.º 26
0
 def create_book(self, title, isbn, price):
     """
     Return book object with title and isbn
     """
     if self.isbn_exists_check(isbn=isbn):
         print("Existing isbn number: {}".format(isbn))
     else:
         return Book(title=title, isbn=isbn, price=price)
Ejemplo n.º 27
0
 def setUp(self):
     self.recipe_one = Recipe(name="recipe_one",
                              cooking_lvl=2,
                              cooking_time=20,
                              ingredients=["sugar", "flour"],
                              description="",
                              recipe_type="starter")
     self.cook_book = Book(name="Test cookBook")
    def setUp(self):
        self.mock_api_json = {
            'volumeInfo': {
                'title': 'Book Title',
                'authors': ['Au Thor', 'Aut Hor'],
                'publisher': 'Publisher',
                'imageLinks': {
                    'thumbnail': ""
                },
                'infoLink': 'www.info.com'
            }
        }

        self.book = Book(self.mock_api_json)

        self.mock_blank_json = {'volumeInfo': {}}
        self.blank_book = Book(self.mock_blank_json)
Ejemplo n.º 29
0
def test_add_book(collection):
    a = Book("TitleA", "AuthorA")
    collection.add_book(a)
    assert len(collection) == 1
    assert a in collection

    a_copy = Book("TitleA", "AuthorA")
    assert a_copy in collection

    b = Book("TitleB", "AuthorB")
    collection.add_book(b)
    assert len(collection) == 2
    assert b in collection
    assert a in collection

    collection.add_book(a_copy)
    assert len(collection) == 2  # Hasn't changed, book already present
Ejemplo n.º 30
0
 def get_books(self, array):
     books = []
     num_of_books = int(len(array) / 5)
     for i in range(num_of_books):
         index = i * 5
         book = Book(array[index:index + 5])
         books.append(book)
     return books