Beispiel #1
0
def main():
    p1 = Patron("Jeff")
    p2 = Patron("Jill")

    b1 = Book("Atonement", "McEwan")
    b2 = Book("The March", "Doctorow")
    b3 = Book("Beach Music", "Conroy")
    b4 = Book("Thirteenth Moon", "Frazier")

    print(p1)
    print(p2)

    print(b1)

    b1.borrowMe(p1)
    b2.borrowMe(p1)
    b3.borrowMe(p1)

    b1.borrowMe(p2)
    print(b1)

    print(b1.returnMe())
    b4.borrowMe(p1)
    b4.borrowMe(p1)

    print(p1)
    print(p2)

    print(b1)
    print(b2)
    print(b3)
    print(b4)
Beispiel #2
0
def addBook(Inventory):
    lastName = ''
    firstName = ''
    bookTitle = ''
    bookPrice = 0
    bookQuantity = 0
    validInput = False
    lastName = raw_input("Please enter author's last name: ").lower()
    firstName = raw_input("Please enter the author's first name: ").lower()
    fullname = "{0}, {1}".format(lastName.title(), firstName.title())
    bookTitle = raw_input("Please enter the book's title: ").lower()
    # test to see if the title and author have a match
    if Inventory.has_key(fullname):
        for book in Inventory[fullname]:
            # test to see if any of the books have the same title
            if book.get_title().lower() == bookTitle:
                # if so, return without adding
                print "Sorry, this book is already in the Inventory."
                return
                # if none of the titles match, we can add it!
    # if they don't match, we now ask for a price and quantity
    while not (validInput):
        bookQuantity = raw_input("Please enter a quantity: ")
        # send bookQuantity to cvalidate to test for proper parameters.
        validInput = cvalidate("int", bookQuantity)
        if validInput:
            # cvalidate will return false if bookQuantity is not an int
            # and will return bookQuantity as an int if it IS.
            bookQuantity = validInput
        else:
            print "Please enter a whole number for quantity."
    validInput = False  # reset the boolean
    while not (validInput):
        bookPrice = raw_input("Please enter a price: ")
        # send bookPrice to cvalidate to test for proper parameters.
        validInputInt = cvalidate('int', bookPrice)
        validInputFloat = cvalidate("float", bookPrice)
        debug(DEBUG, ('validInputInt: ', validInputInt))
        debug(DEBUG, ('validInputInt: ', validInputFloat))
        if validInputInt or validInputFloat:
            # price can be either an int or float, so we must check for both.
            # cvalidate will return false if bookPrice is not a price
            # and will return bookPrice as a float if it IS.
            validInput = True
            debug(DEBUG, validInput)
            # one of those has to be True, so we see check to see which
            # it'll also be a number, which is True to an IF statement.
            if validInputInt:
                bookPrice = validInputInt
            else:
                bookPrice = validInputFloat
        else:
            print "Please enter a number for price"
    if Inventory.has_key(fullname):
        Inventory[fullname].append(
            Book(fullname, bookTitle, bookQuantity, bookPrice))
    else:
        Inventory[fullname] = [
            Book(fullname, bookTitle, bookQuantity, bookPrice)
        ]
Beispiel #3
0
def Ex2():
    lib = Library(1, "51 Some str., NY")
    lib += Book("Leo Tolstoi", "War and Peace")
    lib += Book("Charles Dickens", "David Copperfield")
    for book in lib:
        # вывод в виде: [1] L.Tolstoi "War and Peace"
        print(book)
        # вывод в виде: ["War", "Peace"]
        print(book.tag())
Beispiel #4
0
def main():

    bookshelf = BookShelf()
    bookshelf.appendBook(Book("Around the World in 80 Days"))
    bookshelf.appendBook(Book("Bible"))
    bookshelf.appendBook(Book("Cinderella"))
    bookshelf.appendBook(Book("Daddy-Long-Legs"))
    it = bookshelf.iterator()
    while it.hasNext():
        book = it.next()
        print(book.getName())
Beispiel #5
0
def generate_test_books():
    """
    Return a list of books with dummy data.

    :return: a list
    """
    book_list = [
        Book("100.200.300", "Harry Potter 1", 2, "J K Rowling"),
        Book("999.224.854", "Harry Potter 2", 5, "J K Rowling"),
        Book("631.495.302", "Harry Potter 3", 4, "J K Rowling"),
        Book("123.02.204", "The Cat in the Hat", 1, "Dr. Seuss")
    ]
    return book_list
Beispiel #6
0
def main():
    bookShelf = BookShelf()

    bookShelf.appendBook(Book("append"))
    bookShelf.appendBook(Book("GoF"))
    bookShelf.appendBook(Book("Design"))
    bookShelf.appendBook(Book("Pattern"))

    it = bookShelf.iterator()

    while(it.hasNext()):
        book = it.next()
        print(book.getName())
Beispiel #7
0
def Main():
    b1 = Book("Romeo and Juliet", "Shakespeare", "Roman", "1597")
    b2 = Book("Game of Thrones", "Martin", "Epic fantasy", "1996")
    b3 = Book("Harry Potter", "Roiling", "Roman", "1997")
    b4 = Book("War and peace", "Tolstoi", "Roman", "1867")
    mylibrary = HomeLibrari()
    mylibrary.AddBook(b1)
    mylibrary.AddBook(b2)
    mylibrary.AddBook(b3)
    mylibrary.AddBook(b4)
    mylibrary.SearchBookByName('Harry Potter')
    mylibrary.SearchBookByAuthor("Martin")
    mylibrary.SearchBookByYear('1997')

    mylibrary.DeleteBook('Romeo and Juliet')
Beispiel #8
0
    def constructBook(arguments):
        time_arg = "added_on"

        arguments[time_arg] = datetime.strptime(arguments[time_arg],
                                                rfc_822_format)

        return Book(**arguments)
Beispiel #9
0
def getSearchResultJson():
    query = request.form['query']
    jsonarr = []

    for index in range(len(booksList)):
        #Filter html file under the director
        if booksList[index].endswith(".html"):

            book = BeautifulSoup(
                open('static/ChallengeBooks/' + booksList[index]),
                "html.parser")
            bookName = book.title.string
            authorName = book.h4.find_next(re.compile('^h')).string
            bookURL = URLHeader + url_for(
                'static', filename='ChallengeBooks/') + booksList[index]
            bookImageURL = URLHeader + url_for(
                'static', filename='BooksImages/') + booksImageList[index]

            i = Book(index, bookName, authorName, bookURL, bookImageURL)

            if query in i.getBookName().lower() or query in i.getAuthorName(
            ).lower():
                jsonarr.append({
                    'bookId': i.getBookId(),
                    'bookName': i.getBookName(),
                    'authorName': i.getAuthorName(),
                    'bookURL': i.getBookURL(),
                    'bookImageURL': i.getBookImageURL()
                })

    #Turn jsonarr into json object
    return json.dumps(jsonarr)
Beispiel #10
0
def load():
    if os.path.isfile('data/accounts.csv'):
        path = 'data/accounts.csv'
    else:
        path = 'data/FakeNameSet20.csv'
    with open(path, mode='r') as csv_file:
        csv_reader = csv.reader(csv_file)
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                print(f'Column names are {", ".join(row)}')
                line_count += 1
            else:
                accounts.append(
                    Account(row[0], row[1], row[2], row[3], row[4], row[5],
                            row[6], row[7], row[8], row[9], row[10]))
                line_count += 1
        csv_file.close()

    if os.path.isfile('data/books.json'):
        path = 'data/books.json'
    else:
        path = 'data/booksset1.json'

    js_books = json.load(open(path, 'r'))
    for js_book in js_books:
        book = Book(js_book['author'], js_book['country'],
                    js_book['image_link'], js_book['language'],
                    js_book['link'], js_book['pages'], js_book['title'],
                    js_book['year'])
        books.append(book)
Beispiel #11
0
    def __init__(self,
                 parent,
                 id,
                 title="Boîte de dialogue",
                 size=(770, 650),
                 state=False,
                 defValue=Book().__dict__):
        wx.Dialog.__init__(self,
                           parent,
                           id,
                           title,
                           size=size,
                           style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)

        self.principalFrame = parent
        self.SetBackgroundColour("#FFFFFF")
        self.size = size  # Dimension de la fenêtre
        if self.principalFrame.win32:
            self.size = (self.size[0], self.size[1] + 60)
            self.SetSize(self.size)
        self.isModif = state  # Prend la valeur de l'ID du livre à modifier, sinon False
        self.defValue = defValue  # Valeur par défaut pour chaque widget de capture
        self.modifActuelle = ""  # Prend la valeur de la dernière valeur entrée dans les widgets TextCtrl
        self.InitUI()

        # --- Définition des évènements
        self.Bind(wx.EVT_TEXT, self.OnTextChange)
        self.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.SetMinSize(self.size)
 def __preLoadedBooks(self):
     textFile = open('recommendedbooks.txt', 'r')
     books = textFile.read().split("\n")
     for b in books:
         content = b.split(",")
         if len(content) == 3:
             self.recommended_books.append(Book(content[0], content[1].strip().split("&"), content[2].strip()))
Beispiel #13
0
    def populate_libraries(self, book_score_list, libraries):
        my_libraries = []
        # Distributing books to libraries
        repeated_queue = []
        for l_id, library in enumerate(tqdm(libraries)):
            prop, books = library
            desirable_books_list = []

            repeated_objs = [b.b_id for b in repeated_queue]
            for book_id in books:
                if book_id not in repeated_objs:
                    book_score = book_score_list[book_id]
                    book_obj = Book(b_id=book_id, b_score=book_score)
                    desirable_books_list.append(book_obj)
                    repeated_queue.append(book_obj)
                else:
                    for book_obj in repeated_queue:
                        if book_obj.b_id == book_id:
                            desirable_books_list.append(book_obj)
            # print("LIB", l_id, "completer")
            _, buff_time, capacity = prop

            my_libraries.append(
                Library(l_id, buff_time, capacity, desirable_books_list))
        return my_libraries
def bookSearch(url):
    content = requests.get(url).text
    soup = bs(content, "lxml")

    bookList = []
    allDivs = soup.findAll('div', attrs={'class': 'product-info'})

    for div in allDivs:
        #extract the authorname
        bookInfo = {}
        lists = div.find_all(True, {"class": "contributors"})[0]
        author = lists.contents[1].string
        #bookInfo["author"] = author

        product_list = div.find_all(True, {"class": "product-info-title"})[0]
        title = product_list.contents[1].string
        #bookInfo["title"] = title

        links = product_list.findAll('a')
        for a in links:
            #copy to the book_info
            url = a['href']
        #url = url.split(";")[0]
        bookInfo["url"] = url
        bookInfo = Book(author, title, url)
        bookList.append(bookInfo)
    return bookList
Beispiel #15
0
    def test_add_book(self):
        book = Book(0, 'Death', 'None', 2005)
        self.library.add_book(book)

        books = self.library.get_books()

        self.assertEqual([book], books)
Beispiel #16
0
def parse_books(line):
    line = line.split()
    for score, i in zip(line, range(len(line))):
        score = float(score)
        books.append(Book(i, score))

    print("There are {} books".format(len(books)))
Beispiel #17
0
def main(forRange, version):
    for i in range(forRange[0], forRange[1]):
        bookNamePtBR = Bible().getBooksPtBRName(i)
        bookAbbreviation = Bible().getBooksPtBRAbbreviation(i)
        numChapters = int(Bible().getbooksChapterNumber(i))
        fileName = "biblia-" + version + ".txt"

        with open(fileName, 'a+', encoding='utf-8') as file:
            file.write('"{}/{}":{}'.format(bookNamePtBR, bookAbbreviation, '{'))

        for j in range(1, numChapters + 1):
            chapter = str(j)
            with open(fileName, 'a+', encoding='utf-8') as file:
                file.write('"{}":{}'.format(chapter, '{'))

            site = "https://www.bibliaonline.com.br/"
            url = site + version + "/" + bookNamePtBR.lower().replace(" ", "")  + "/" + chapter
            verses = Book().getInfo(url, bookAbbreviation)

            with open(fileName, 'a+', encoding='utf-8') as file:
                for numVerse, verse in enumerate(verses):
                    file.write('"{}":"{}",'.format((numVerse + 1), verse))
                file.write('},')
        
        with open(fileName, 'a+', encoding='utf-8') as file:
            file.write('},')

        print("\nLivro de " + bookNamePtBR + " concluído.")

    print("\nArquivo gerado com sucesso.")
def new():
    form = PublicationForm(request.form)
    if request.method == 'POST' and form.validate():
        if  form.pubtype.data == 'smag':
            title = form.title.data
            type = form.pubtype.data
            category = form.category.data
            status = form.status.data
            frequency = form.frequency.data
            publisher = form.publisher.data
            created_by = "U0001" # hardcoded value

            mag = Magazine(title, publisher, status, created_by, category, type, frequency)

            mag_db = root.child('publications')
            mag_db.push({
                    'title': mag.get_title(),
                    'type': mag.get_type(),
                    'category': mag.get_category(),
                    'status': mag.get_status(),
                    'frequency': mag.get_frequency(),
                    'publisher': mag.get_publisher(),
                    'created_by': mag.get_created_by(),
                    'create_date': mag.get_created_date()
            })

            flash('Magazine Inserted Sucessfully.', 'success')

        elif form.pubtype.data == 'sbook':
            title = form.title.data
            type = form.pubtype.data
            category = form.category.data
            status = form.status.data
            isbn = form.isbn.data
            author = form.author.data
            synopsis = form.synopsis.data
            publisher = form.publisher.data
            created_by = "U0001"  # hardcoded value

            book = Book(title, publisher, status, created_by, category, type, synopsis, author, isbn)
            book_db = root.child('publications')
            book_db.push({
                'title': book.get_title(),
                'type': book.get_type(),
                'category': book.get_category(),
                'status': book.get_status(),
                'author': book.get_author(),
                'publisher': book.get_publisher(),
                'isbn': book.get_isbnno(),
                'synopsis': book.get_synopsis(),
                'created_by': book.get_created_by(),
                'create_date': book.get_created_date()
            })

            flash('Book Inserted Sucessfully.', 'success')

        return redirect(url_for('viewpublications'))


    return render_template('create_publication.html', form=form)
Beispiel #19
0
 def setUp(self):
     self.book = Book(
         "Laurent", "Gounelle", "L'homme qui voulait être heureux",
         "POCKET", 2013, "Roman", 168, "Chambre de Cyril", 5,
         "Commentaire de ce livre, blabliblou\ttchou\ttchou.\nRetour a la ligne baby.",
         "L'homme qui voulait etre heureux.jpg")
     print self.book.__module__
Beispiel #20
0
 def _addBook(self, name, author, publish_date, pages):
     book = Book(name, author, publish_date, pages)
     self.different_book_count += 1
     Catalog.different_books_count = self.different_book_count
     self.books.append(book)
     Catalog.books.append(book)
     return book
 def __init__(self):
     "Constructor. Loads book details from a csv file, creates it's book objects and appends them to the Catalog."
     self.catalog = []
     self.IDobj = it.count(1)
     self.authorSet = set()  #containes all the names of authors
     self.publisherSet = set()  #containes all the names of publishers
     stock = [
         1, 2, 1, 6, 10, 3, 4, 10, 6, 0, 3, 3, 6, 1, 3, 7, 0, 0, 10, 0, 0,
         7, 0, 5, 5, 4, 10, 3, 2, 6, 2, 1, 4, 1, 7, 3, 2, 9, 0, 8, 10, 3, 5,
         1, 10, 8, 4, 10, 6, 1, 2, 5, 9, 3, 1, 9, 4, 6, 6, 5, 0, 0, 10, 7,
         8, 9, 2, 7, 10, 1, 2, 4, 7, 7, 4, 10, 9, 5, 0, 7, 5, 9, 1, 0, 5,
         10, 8, 9, 2, 9, 1, 9, 9, 0, 10, 1, 4, 7, 6, 5
     ]
     iter_stock = iter(stock)
     with open("data.txt", "r", encoding="UTF-8") as csvfile:
         csvreader = csv.reader(csvfile)
         row = []
         next(csvreader)
         i = 0
         while True:
             temp = next(csvreader)
             if "," not in temp[2] and len(temp[1]) < 40 and len(
                     temp[1]) > 0:
                 row.append(temp)
                 i += 1
             if i == 100:
                 break
         for i in row:
             bookobj = Book("BId_" + str(next(self.IDobj)), i[1], i[2],
                            i[0], i[12], i[3], i[5], next(iter_stock))
             self.authorSet.add(i[2])
             self.publisherSet.add(i[12])
             self.catalog.append(bookobj)
Beispiel #22
0
def run_Autors():
    
    with open('AutorList.json') as json_file:
        data = json.load(json_file)
        for p in data['Autor']:
            print(p['Name'])
            print(p['LastName'])
            print('Author id', p['AutorNumber'])
            autorid = p['AutorNumber']

            with open('BooksList.json') as json_file:
    
                data = json.load(json_file)
            autorarray = []
            for p in data['book']:
                book = Book(p['Title'], p['Release'], p['Autor'], p['Publisher'], p['ISBN'], p['Category'], p['Pages'])
                title = book.gettitle()
                autor = p['Autor']
                #print(title)
                if autorid == autor:
                    autorarray.append(title)
                    autorarray.sort()

            if len(autorarray)>2:
                print('books: ' , autorarray[0],'\n', autorarray[1],'\n',autorarray[2])
            elif len(autorarray)==2:
                print('books: ' , autorarray[0],'\n',autorarray[1])
            elif len(autorarray)==1:
                print('books: ' , autorarray[0])
            else:
                print('No Books for this author yet...')
            print('-------------------------------------------')
Beispiel #23
0
    def test_delete_book(self):
        book = Book(0, 'Death', 'None', 2005)
        self.library.add_book(book)

        self.library.del_book(0)

        self.assertEqual([], self.library.get_books())
    def __init__(self):
        inf = open('book.txt', 'r')
        if inf.closed:
            print("Error opening file.")
        for i in inf.readlines():
            mystring = i.strip().split('|')
            CardCatalog.append(Book(*mystring))
        inf.close()

        inf = open('periodic.txt', 'r')
        if inf.closed:
            print("Error opening file.")
        for i in inf.readlines():
            mystring = i.strip().split('|')
            CardCatalog.append(Periodical(*mystring))
        inf.close()

        inf = open('video.txt', 'r')
        if inf.closed:
            print("Error opening file.")
        for i in inf.readlines():
            mystring = i.strip().split('|')
            CardCatalog.append(Video(*mystring))
        inf.close()

        inf = open('film.txt', 'r')
        if inf.closed:
            print("Error opening file.")
        for i in inf.readlines():
            mystring = i.strip().split('|')
            CardCatalog.append(Film(*mystring))
        inf.close()
    def test_str(self):
        """ 
        Test that str method returns a string representation of the object.
        """

        # Create a Resource object
        book = Book("Penguin Group", "New York", "fiction", 1, "White Noise",
                    Name("Don", "", "DeLillo"),
                    "Delillo's White Noise follows narrator Jack "\
                    "Gladney, a professor at a small Liberal Arts "\
                    "college and describes an academic year. Jack "\
                    "teaches at a school called the "\
                    "College-on-the-Hill, where he serves as the "\
                    "department chair of Hitler studies. He lives in "\
                    "Blacksmith, a quiet college town, with his wife, "\
                    "Babette, and four of their children from earlier "\
                    "marriages: Heinrich, Steffie, Denise, and "\
                    "Wilder. Throughout the novel, various "\
                    "half-siblings and ex-spouses drift in and out "\
                    "of the family’s home.",
                    "sci-fi", "English", 1985, "US", 326, "book",
                    ["culture", "survival", "life", "society"])

        # Assert expected result of the str function
        self.assertEqual(str(book), ("ID: 1 \nTitle: White Noise "\
            "\nCreator: Don DeLillo \nSummary: Delillo's White Noise follows "\
            "narrator Jack Gladney, a professor at a \nsmall Liberal Arts "\
            "college and describes an academic year. Jack teaches \nat ... "\
            "\nGenre: sci-fi \nLanguage: English \nYear: 1985 "\
            "\nCountry: US \nLength: 326p \nType: book "\
            "\nKeywords: culture, life, society, survival\nPublisher: "\
            "Penguin Group \nCity: New York \nCategory: fiction"))
Beispiel #26
0
 def search_for_book(self, book_title):
     b = re.sub("-", " ", book_title)
     self.current_book = Book(b, ("%0.5d" % self.product_number))
     self.product_number += 1
     if (self.fetch_book_page(book_title) == 200):
         self.parse_page(book_title)
         self.download_image(book_title, self.current_book.product_number)
Beispiel #27
0
def Add_book():
    connect = sqlite3.connect(app.config['DATABASE'])
    cursor = connect.cursor()
    global current_user
    if request.form['book_type'] == 'on':
        b = 2
    else:
        b = 1
    check = cursor.execute(
        """select * from BOOK where BOOK_NAME = \"{}\" and Author = \"{}\" and 
                            PUBLISH_YEAR = \"{}\" and BOOK_TYPE = {};""".
        format(request.form['name'], request.form['author'],
               request.form['publish_year'], b)).fetchone()
    if check is None:
        id_ = cursor.execute("SELECT MAX(BOOK_ID) FROM BOOK;").fetchone()
        if id_[0] is None:
            id_ = (0, )
        book = Book(id_[0] + 1, request.form['name'],
                    request.form['rubric_name'], request.form['author'],
                    request.form['publish_year'], request.form['rental_time'],
                    request.form['book_type'])
        current_user.add_book(book)
        return render_template('success_add.html')
    else:
        return render_template('add_book.html',
                               err='Такая книга уже существует')
def init_books(author_file, json_file):
    """initialize book list with texts and save it to disk"""
    with open(author_file) as f:
        authors = list(f)

    authors = [i.strip() for i in authors]

    books = []
    for author in authors:
        s = get_etexts('author', author)
        for i in s:
            try:
                if list(get_metadata('language', i))[0] == 'en':
                    title, etext = list(get_metadata(
                        'title', i))[0], strip_headers(load_etext(i)).strip()
                    b = Book(i, title, etext)
                    books.append(b)
            except UnknownDownloadUriException:
                # this book does not have a load_etext corresponding to it.
                pass

    with open(json_file, 'wb') as f:
        pickle.dump(books, f)

    print(len(books))
Beispiel #29
0
 def removeBook(self, name, author, publish_date, pages):
     b = Book(name, author, publish_date, pages)
     for book in self.books:
         if book == b:
             self.books.remove(b)
             self.different_book_count -= 1
     return b
Beispiel #30
0
 def fillCatalog(self):
     with open('Catalog.csv', mode='r') as csv_file:
         csv_reader = csv.DictReader(csv_file)
         for row in csv_reader:
             self.__Books.append(
                 Book(row["bookId"], row["title"], row["authorName"],
                      row["authorAge"], row["ISBN"]))