예제 #1
0
    def __init__(self, *a, **kwargs):

        # Create a Borrow instance
        self._stock_loan = Borrow(database_name='stock_loan', create_new=False)

        TwythonStreamer.__init__(self, *a, **kwargs)
예제 #2
0
파일: library.py 프로젝트: malzer42/tds
    def borrow_book_by_subscriber(self, sub_id_number, book_quote,
                                  book_return_date) -> bool:
        """
        The method check if it is possible that the book can be borrowed by the subscriber
        if it is possible, then a new borrow is added to the list of borrowers.
        It is possible to borrow a book by a subscriber if the book is available,
        the subscriber as the minimal required age to read the book,
        the subscriber did not already borrow the book
        the subscriber did not exceed the maximal number (2) of books to borrow.
        :param sub_id_number: str
        :param book_quote: str
        :param book_return_date: date
        :return: bool, True in case of success borrow and False otherwise
        """
        success_or_fail: bool = False
        number_of_books_borrowed_by_subscriber: int = 0
        maximal_number_to_borrow: int = 2

        try:
            # Search a book with the given book_quote in the list of books and assign it to tmp_book
            # Check if the book is available in the list of books.
            book_obj = [
                book_elt for book_elt in self.books
                if book_elt.get_quote == book_quote
            ][0]

            if book_obj.get_n_available > 0:
                is_book_available = True
            else:
                print(
                    f"{book_obj.get_quote} is not available {book_obj.get_n_available}"
                )
                return success_or_fail

            # Search a subscriber with the given sub_id_number in the list of subscribers and assign him to tmp_subscriber
            sub_obj = [
                subscriber_elt for subscriber_elt in self.subscribers
                if subscriber_elt.get_id_number == sub_id_number
            ][0]

            # Check if the given subscriber has borrowed the book in the list of borrowers
            # Count the number of time the subscriber occurs in the borrowers list
            has_subscriber_borrowed_the_book: bool = False
            borrow_obj = Borrow(sub_obj, book_obj, book_return_date)
            if borrow_obj in self.borrowers:
                print(
                    f"{borrow_obj.get_book_obj.get_quote} - {borrow_obj.get_sub_obj.get_id_number} exists in the borrowers list"
                )
                return success_or_fail

            for borrow_elt in self.borrowers:
                if borrow_elt.get_sub_obj.get_id_number == sub_id_number:
                    number_of_books_borrowed_by_subscriber = number_of_books_borrowed_by_subscriber + 1
                    if number_of_books_borrowed_by_subscriber >= maximal_number_to_borrow:
                        success_or_fail = False
                        print(
                            f"Number of books borrowed by subscriber {number_of_books_borrowed_by_subscriber}"
                        )
                        print(
                            f"{sub_obj.get_id_number} has reached the limit to borrow a book"
                        )
                        # print("Excess Failure to borrow the book {} by the subscriber {}".format(book_obj, sub_obj))
                        return success_or_fail

                    else:
                        print(
                            f"!!!! {number_of_books_borrowed_by_subscriber}. {borrow_elt.get_book_obj.get_quote} - {borrow_elt.get_sub_obj.get_id_number} !!!!"
                        )

            # Check if the subscriber has the required age to read the book,
            # the subscriber did not exceed the maximal number allowed to borrow.
            has_required_age: bool = False
            if sub_obj.get_age >= book_obj.get_minimal_age:
                has_required_age = True
            else:
                print(
                    f"{sub_obj.get_id_number} does not have the required age to read the book {book_obj.get_quote}"
                )
                return success_or_fail

            # number_of_books_borrowed_by_subscriber = self.borrowers.count(borrow_obj)

            if number_of_books_borrowed_by_subscriber > maximal_number_to_borrow:
                print(
                    f"{sub_obj.get_id_number} has exceed the limit to borrow a book"
                )
                return success_or_fail

            if has_required_age and is_book_available and number_of_books_borrowed_by_subscriber < maximal_number_to_borrow and not has_subscriber_borrowed_the_book:
                if borrow_obj not in self.borrowers:
                    self.borrowers.append(borrow_obj)
                    book_obj.set_n_available(book_obj.get_n_available - 1)
                    number_of_books_borrowed_by_subscriber += 1
                    print(f"{book_quote} borrowed by {sub_id_number}")
                    success_or_fail = True
                    return success_or_fail
                else:
                    print(
                        f"Number of books borrowed by subscriber {number_of_books_borrowed_by_subscriber}"
                    )
                    print(
                        f"Failure to borrow the book {book_obj.get_quote} by the subscriber {sub_obj.get_id_number}"
                    )
                    return success_or_fail

        except Exception as exception__borrow_book:
            print(
                f"{book_obj.get_quote} is not in the library -{exception__borrow_book}"
            )
            raise
        else:
            print(f"Total {len(self.borrowers)} borrow(s) from the Library")
        finally:
            print("Done")
            return success_or_fail
예제 #3
0
class BorrowStreamer(TwythonStreamer):
    """Twitter Streamer class for responding to tweets at the bot"""
    def __init__(self, *a, **kwargs):

        # Create a Borrow instance
        self._stock_loan = Borrow(database_name='stock_loan', create_new=False)

        TwythonStreamer.__init__(self, *a, **kwargs)

    def on_success(self, data):
        """If the streamer receives a tweet that matches its filter"""
        if 'text' in data:
            # Check that it wasn't one of the bot's own tweets
            if data['user']['screen_name'] != 'IBorrowDesk':
                #Print out the tweet's text, author screename and id
                # and call the respond function
                print(data['text'])
                print(data['user']['screen_name'])
                print(data['id_str'])
                self._respond(data)

    def on_error(self, status_code, data):
        print(status_code)
        print(data)
        print("There was an error")

    def _respond(self, data):

        #
        twitter_rest = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN,
                               OAUTH_TOKEN_SECRET)

        # Grab the tweet's text and try to extract a symbol from it
        text = data['text']
        matches = re.findall(TICKER_MATCH, text)
        print('matches were {} \n'.format(str(matches)))
        if matches:
            summary = self._stock_loan.summary_report(matches)
            print(summary)

            # Confirm the summary report is not empty
            if summary != None:
                for ticker in summary:
                    print(ticker.symbol)

                    #extract the relevant information from the
                    # summary report and build a status string
                    symbol = ticker.symbol
                    name = ticker.name[:20]
                    available = '{:,}'.format(ticker.available)
                    fee = '{:.1%}'.format(ticker.fee / 100)
                    datetime = ticker.datetime
                    url = 'https://www.iborrowdesk.com/report/{}'.format(
                        symbol)
                    screen_name = data['user']['screen_name']

                    status = '@{} ${} {}, Available: {}, Fee: {}, Last Updated: {} '.\
                        format(screen_name, symbol, name, available, fee, datetime)
                    status = status + url

                    # Grab the id of the user that tweeted at the bot
                    id_str = data['id_str']

                    # Update status
                    twitter_rest.update_status(status=status,
                                               in_reply_to_status_id=id_str)

                    print('Match found {} \n'.format(ticker))
                    print('Responded with {} \n'.format(status))

            else:
                print('Invalid symbols matched \n')
        else:
            print('No match found \n')
예제 #4
0
파일: main.py 프로젝트: malzer42/lmis_py
def main():
    """
    The main controller for the LMIS.
    Used to create instances of different classes
    Used for integration testing and various implemented methods

    """
    start_time = time.time()
    print(
        "IF YOU FAIL TO PLAN FOR FAILURES, YOU ARE PLANNING TO FAIL AS AN SQA."
    )

    try:
        print("LIBRARY MANAGEMENT INVENTORY SYSTEM")
        print("INTEGRATION TEST PROGRAM")

        print("\nCREATING AND DISPLAYING OF SUBSCRIBERS")
        sub1 = Subscriber('1839456', 'John', 'Doe', 23)
        sub2 = Subscriber('1630236', 'Nicolas', 'Gagnon', 8)
        sub3 = Subscriber('1269348', 'Martin', 'Tremblay', 18)
        print(sub1.info())
        print(sub2.info())
        print(sub3.info())

        print("\nCREATING AND DISPLAYING OF BOOKS")
        book7 = Book("HB514", "Bjh D++", 2010, 9, 3, 4)
        book1 = Book("GA403", "Big C++", 2009, 8, 3, 3)
        book2 = Book("QA203", "Calcul a plusieurs variables partie 1", 2011, 3,
                     2, 2)
        book3 = Book("QA204", "Calcul a plusieurs variables partie 2", 2011, 3,
                     2, 2)
        book4 = Book("AC409", "Le chateau d'Ortrante", 1764, 16, 1, 1)
        book5 = Book("BD302", "Harry Potter et le prisionier d'Azkaban", 1999,
                     3, 1, 1)
        book6 = Book("CE413", "Ibssz Qpuufs et le prisionier c'balbcbo", 2000,
                     4, 2, 2)
        print(book1.info())
        print(book2.info())
        print(book3.info())
        print(book4.info())
        print(book5.info())
        print(book6.info())
        print(book7.info())

        print("\nBORROWING A BOOK BY A SUBSCRIBER")
        borrow1 = Borrow(sub1, book2, 2020)
        borrow2 = Borrow(sub2, book1, 2020)
        print(borrow1.info())
        print(borrow2.info())

        # / ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** * /
        # / *BEGINNING OF TESTS * /
        # / *Les modifications restantes sont a la fin de la fonction main. * /
        # / ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** * /

        print("\nADDING OF BOOKS AND SUBSCRIBERS TO THE LIBRARY")
        subscribers = []
        books = []
        borrowers = []
        lib = Library(subscribers, 0, books, 0, borrowers, 0)
        lib.add_subscriber_to_library(sub1)
        lib.add_subscriber_to_library(sub2)
        lib.add_subscriber_to_library(sub3)
        lib.add_subscriber_to_library(sub1)
        lib.add_book_to_library(book1)
        lib.add_book_to_library(book2)
        lib.add_book_to_library(book3)
        lib.add_book_to_library(book4)
        lib.add_book_to_library(book5)
        lib.add_book_to_library(book6)
        lib.add_book_to_library(book7)
        lib.add_book_to_library(book3)
        lib.add_book_to_library(book1)

        print("\nSEARCH BY TITLE...: Calcul")
        title = "Calcul"
        lib.search_book_title(title)

        title = random.choice([book_obj.get_title for book_obj in lib.books])
        print("\nSEARCH A RANDOM TITLE ...: {}".format(title))
        # print(title)
        lib.search_book_title(title)

        print("\nSEARCH BY QUOTE...: AC409")

        lib.search_book_quote("AC409")
        lib.search_book_quote("BD302")
        lib.search_book_quote("QA204")
        lib.search_book_quote("QA203")
        lib.search_book_quote("AC209")
        quote = random.choice([book_obj.get_quote for book_obj in lib.books])
        # print(quote)
        print("\nSEARCH A RANDOM QUOTE...: {}".format(quote))
        lib.search_book_quote(quote)

        print("\nTESTS OF BORROWING")
        lib.borrow_book_by_subscriber("1630236", "AC409", 2021)
        lib.borrow_book_by_subscriber("1630236", "BD302", 2021)
        lib.borrow_book_by_subscriber('1839456', "GA403", 2021)
        lib.borrow_book_by_subscriber('1839456', "GA403", 2021)
        lib.borrow_book_by_subscriber("1839456", "BD302", 2022)
        lib.borrow_book_by_subscriber("1630236", "QA204", 2024)
        lib.borrow_book_by_subscriber("1630236", "QA203", 2044)
        lib.borrow_book_by_subscriber("1630236", "CE413", 2024)

        print("\nSUBSCRIBER INFORMATION BEFORE RETURNING A BOOK")
        lib.subscriber_info("1630236")

        id_number = random.choice(
            [sub_obj.get_id_number for sub_obj in lib.subscribers])
        print("\nRANDOM SUBSCRIBER INFORMATION BEFORE RETURNING A BOOK...: {}".
              format(id_number))
        lib.subscriber_info(id_number)

        print("\nTEST ON BOOKS RETURN")
        lib.return_book_by_subscriber("1630236", "QA204")
        lib.return_book_by_subscriber("1839456", "QA203")

        print("\nTEST ON RANDOM RETURN...: {} - {}".format(id_number, quote))
        lib.return_book_by_subscriber(id_number, quote)

        print("\nSUBSCRIBER INFORMATION AFTER RETURNING A BOOK")
        lib.subscriber_info("1630236")

        print("\nRANDOM SUBSCRIBER INFORMATION AFTER RETURNING A BOOK...: {}".
              format(id_number))
        lib.subscriber_info(id_number)

        print("\nREMOVING A RANDOM SUBSCRIBER FROM THE LIBRARY:...{}".format(
            id_number))
        lib.remove_subscriber_from_library(id_number)

        id_number_non_existent = "102030"
        print("\nREMOVING A NON EXISTENT SUBSCRIBER FROM THE LIBRARY:...{}".
              format(id_number_non_existent))
        lib.remove_subscriber_from_library(id_number_non_existent)

    except Exception as exception:
        print(exception)
        raise
    else:
        print("\nEND OF INTEGRATION TEST!!!\n")

    finally:
        stop_time = time.time()
        delta_time = stop_time - start_time
        print("{} - {} = {}".format(stop_time, start_time, delta_time))
        print(
            "If you fail to plan, you are planning to fail! Benjamin Franklin")
        print(
            "To be a dancing master is a special thing. But to be a faceless man, that is something else entirely"
        )
        print("PROGRAM ENDED SUCCESSFULLY")
예제 #5
0
    def __init__(self, *a, **kwargs):

        # Create a Borrow instance
        self._stock_loan = Borrow(database_name='stock_loan', create_new=False)

        TwythonStreamer.__init__(self, *a, **kwargs)
예제 #6
0
class BorrowStreamer(TwythonStreamer):
    """Twitter Streamer class for responding to tweets at the bot"""
    def __init__(self, *a, **kwargs):

        # Create a Borrow instance
        self._stock_loan = Borrow(database_name='stock_loan', create_new=False)

        TwythonStreamer.__init__(self, *a, **kwargs)

    def on_success(self, data):
        """If the streamer receives a tweet that matches its filter"""
        if 'text' in data:
            # Check that it wasn't one of the bot's own tweets
            if data['user']['screen_name'] != 'IBorrowDesk':
                #Print out the tweet's text, author screename and id
                # and call the respond function
                print(data['text'])
                print(data['user']['screen_name'])
                print(data['id_str'])
                self._respond(data)


    def on_error(self, status_code, data):
        print(status_code)
        print(data)
        print("There was an error")

    def _respond(self, data):

        #
        twitter_rest = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

        # Grab the tweet's text and try to extract a symbol from it
        text = data['text']
        matches = re.findall(TICKER_MATCH, text)
        print('matches were {} \n'.format(str(matches)))
        if matches:
            summary = self._stock_loan.summary_report(matches)
            print(summary)

            # Confirm the summary report is not empty
            if summary != None:
                for ticker in summary:
                    print(ticker.symbol)

                    #extract the relevant information from the
                    # summary report and build a status string
                    symbol = ticker.symbol
                    name = ticker.name[:20]
                    available = '{:,}'.format(ticker.available)
                    fee = '{:.1%}'.format(ticker.fee/100)
                    datetime = ticker.datetime
                    url = 'https://www.iborrowdesk.com/report/{}'.format(symbol)
                    screen_name = data['user']['screen_name']

                    status = '@{} ${} {}, Available: {}, Fee: {}, Last Updated: {} '.\
                        format(screen_name, symbol, name, available, fee, datetime)
                    status = status + url

                    # Grab the id of the user that tweeted at the bot
                    id_str = data['id_str']

                    # Update status
                    twitter_rest.update_status(status=status, in_reply_to_status_id=id_str)

                    print('Match found {} \n'.format(ticker))
                    print('Responded with {} \n'.format(status))

            else:
                print('Invalid symbols matched \n')
        else:
            print('No match found \n')
예제 #7
0
    # Clear the cache
    mc.flush_all()


def clean_db():
    """Helper function for cleaning the database"""
    stock_loan.clean_dbase()


# Perform scheduled updates to the Borrow DB
if __name__ == '__main__':
    # Use blocking scheduler as this is run as a daemon
    apsched = BlockingScheduler()
    mc = memcache.Client(['127.0.0.1:11211'], debug=0)

    stock_loan = Borrow()

    # Add a job for updating the entire database (940am weekdays EST to be stored for historical reports -
    # won't collide with other updates)
    apsched.add_job(update_database_all,
                    'cron',
                    day_of_week='mon-fri',
                    minute='40',
                    hour='9',
                    timezone='America/New_York')

    # Add a job for cleaning the database
    apsched.add_job(clean_db,
                    'cron',
                    day_of_week='mon-fri',
                    minute='5',