Exemplo n.º 1
0
    def do_deactivate(self):
        if self.timeout_update_id != 0:
            GObject.source_remove(self.timeout_update_id)
            self.timeout_update_id = 0

            del self.update_placeholders[:]
            del self.jump_placeholders[:]

        # Always release the reference to the global snippets
        Library().unref(None)
        self.active_placeholder = None

        self.disconnect_signals(self.view)
        self.disconnect_signals(self.view.get_buffer())

        # Remove all active snippets
        for snippet in list(self.active_snippets):
            self.deactivate_snippet(snippet, True)

        completion = self.view.get_completion()

        if completion:
            completion.remove_provider(self.provider)
            completion.remove_provider(self.defaults_provider)

        if self.language_id != 0:
            Library().unref(self.language_id)

        SharedData().unregister_controller(self.view, self)
Exemplo n.º 2
0
 def creat_lib(self):
     lib_name = input("请输入新建的图书馆的名字:").strip()
     flag = None
     while True:
         if lib_name in self.lib_set:
             print(lib_name + "已存在!")
             print("是否打开" + lib_name + ":\n# yes:打开\n# no:返回\n# 其他:退出系统")
             flag = input(">>>").strip()
             if flag == "yes":
                 break
             elif flag == "no":
                 break
             else:
                 self.exit()
         else:
             break
     if flag == "yes":
         self.lib = Library(lib_name)
         print("成功打开" + lib_name + "!")
         while True:
             self.print_options()
             self.lib_operation()
     elif flag == "no":
         self.run()
     else:
         lib_location = input("请输入" + lib_name + "的地址:").strip()
         default_return_book_position = input("请输入" + lib_name +
                                              "的默认还书地点:").strip()
         max_borrow_time_limit = int(
             input("请输入" + lib_name + "的书籍最大借阅期限(天):").strip())
         self.lib = Library(lib_name, lib_location,
                            default_return_book_position,
                            max_borrow_time_limit)
         self.lib_set.add(lib_name)
         print("成功创建" + lib_name + "!")
Exemplo n.º 3
0
def testLibrary():
    lib = Library()
    b1 = Book("Live by Night", "Dennis Lehane")
    b2 = Book("A Time of Gifts", "Patrick Leigh Fermor")
    b3 = Book("Barchester Towers", "Anthony Trollope")
    for b in (b1, b2, b3):
        lib.addBook(b)
    p1 = Patron("Ken")
    p2 = Patron("Joshua")
    p3 = Patron("Sara")
    for p in (p1, p2, p3):
        lib.addPatron(p)
    print("\nThe first library:")
    print(lib)
    lib.save("books.dat", "patrons.dat")
    secondLib = Library("books.dat", "patrons.dat")
    print("\nThe second library (a copy):")
    print(secondLib)
    print("Expect Ken, 0 kooks out:", lib.getPatron("Ken"))
    print("Expect None:", lib.getPatron("Carolyn"))
    print("Expect Live by Night:", lib.getBook("Live by Night").getTitle())
    print("Expect None:", lib.getBook("Mystic River"))
    print("Expect None:", lib.removeBook("Live by Night"))
    print("\nLibrary:")
    print(lib)
    print("Expect Book's title is not in the library:",
          lib.removeBook("Mystic River"))
    print("Expect None:", lib.removePatron("Ken"))
    print("\nLibrary:")
    print(lib)
    print("Expect Patron's name is not in the library:",
          lib.removePatron("Ken"))
def test_parse_hash_code_file():
    sample_books = [
        Book(0, 1),
        Book(1, 2),
        Book(2, 3),
        Book(3, 6),
        Book(4, 5),
        Book(5, 4)
    ]
    sample_libraries = [
        Library(0, 5, 2, 2,
                [Book(0, 1),
                 Book(1, 2),
                 Book(2, 3),
                 Book(3, 6),
                 Book(4, 5)]),
        Library(1, 4, 3, 1,
                [Book(5, 4), Book(2, 3),
                 Book(3, 6), Book(0, 1)])
    ]

    parser = ScenarioParser("a_example")
    d, books, libraries = parser.parse_hash_code_file()
    assert d == 7
    assert [a == b for a, b in zip(books, sample_books)]
    assert [a == b for a, b in zip(libraries, sample_libraries)]
Exemplo n.º 5
0
    def read_file(self):
        with open(self.file_name, "r") as f:
            data = f.readlines()

        self.book_count, self.lib_count, self.no_days = list(
            map(int, data[0].strip().split())
        )
        self.book_scores = list(map(int, data[1].strip().split()))

        if self.init_sort:
            for line in range(2, len(data), 2):
                if not data[line].strip():
                    break

                lib_info = list(map(int, data[line].strip().split()))
                books = sorted(
                    list(map(int, data[line + 1].strip().split())),
                    key=lambda x: self.book_scores[x],
                    reverse=True,
                )
                self.libraries.append(Library(*lib_info, books))
        else:
            for line in range(2, len(data), 2):
                if not data[line].strip():
                    break

                lib_info = list(map(int, data[line].strip().split()))
                books = list(map(int, data[line + 1].strip().split()))
                self.libraries.append(Library(*lib_info, books))
Exemplo n.º 6
0
def add_books_from_lt(filename, json_filename):
    lib = Library(filename, True)
    libthing_lib = Library(json_filename)

    for book in libthing_lib.all_books:
        if book not in lib.all_books:
            print(book)
            lib.all_books.append(book)

    lib.save_to_file(filename)
Exemplo n.º 7
0
def update_isbns_from_lt(filename, json_filename, write_file=''):
    if write_file == '':
        write_file = filename
    lib = Library(filename, True)
    libthing_lib = Library(json_filename)

    for lib_book in libthing_lib.all_books:
        for book in lib.all_books:
            if lib_book == book:
                book.isbn = lib_book.isbn

    lib.save_to_file(write_file)
Exemplo n.º 8
0
        def get_proposals(self, word):
                if self.proposals:
                        proposals = self.proposals
                else:
                        proposals = Library().get_snippets(None)

                        if self.language_id:
                                proposals += Library().get_snippets(self.language_id)

                # Filter based on the current word
                if word:
                        proposals = filter(lambda x: x['tag'].startswith(word), proposals)

                return map(lambda x: Proposal(x), proposals)
Exemplo n.º 9
0
def update_blank_libthing_ids(filename, json_filename, write_file=''):
    if write_file == '':
        write_file = filename

    lib = Library(filename, True)
    libthing_lib = Library(json_filename)

    for book in lib.all_books:
        if not book.libthing_num:
            for other_book in libthing_lib.all_books:
                if other_book.title == book.title:
                    book.libthing_num = other_book.libthing_num

    lib.save_to_file(write_file)
Exemplo n.º 10
0
def update_libthing_ids_and_editors(filename, json_filename, write_file=''):
    if write_file == '':
        write_file = filename

    lib = Library(filename, True)
    libthing_lib = Library(json_filename)

    for book in libthing_lib.all_books:
        for other_book in lib.all_books:
            if other_book.title == book.title and other_book.isbn == book.isbn and other_book == book:
                other_book.libthing_num = book.libthing_num
                other_book.editor = book.editor

    lib.save_to_file(write_file)
Exemplo n.º 11
0
    def mainLoop(self):

        logging.debug("Monitor: started main loop.")
        self.session = self.dm.Session()
        self.library = Library(self.dm.Session)

        observer = Observer()
        self.eventHandler = MonitorEventHandler(self)
        for path in self.paths:
            logging.debug(path)
            if os.path.exists(path):
                observer.schedule(self.eventHandler, path, recursive=True)
        observer.start()

        while True:
            try:
                (msg, args) = self.queue.get(block=True, timeout=1)
            except:
                msg = None

            #dispatch messages
            if msg == "scan":
                self.dofullScan(self.paths)

            if msg == "events":
                self.doEventProcessing(args)

            #time.sleep(1)
            if self.quit:
                break

        self.session.close()
        self.session = None
        observer.stop()
        logging.debug("Monitor: stopped main loop.")
Exemplo n.º 12
0
def lend_book_bid(bid: str, person: str, return_date: str) -> None:
    """
    Lends a book using its unique identifier (bid)

    \b
    :param bid: Book identifier
    :param person: Person to lend the book
    :param return_date: Return date in YYYYMMDD format
    """
    try:
        return_date = datetime.strptime(return_date, '%Y%m%d')
    except ValueError:
        print('Error: Invalid date string. Use YYYYMMDD format.')
        exit()
    with Library(get_workinglib()) as library:
        try:
            book = library.books[bid]
        except KeyError:
            print('Book not found!')
            exit()
        try:
            library.lend_book(book, return_date, person)
            print(
                f'{book} has been lent to {person.title()} until {return_date.strftime("%A %B %d %Y")}'
            )
        except KeyError:
            print('Error: Book already lent')
Exemplo n.º 13
0
def lend_book_name(book_name: str, person: str, return_date: str) -> None:
    """
    Lends the fist book that matches given name to a person until a set date

    \b
    :param book_name: Book name to search
    :param person: Name of the person to lend the book
    :param return_date: Return date in YYYYMMDD format
    """
    try:
        return_date = datetime.strptime(return_date, '%Y%m%d')
    except ValueError:
        print('Error: Invalid date string. Use YYYYMMDD format.')
        exit()
    with Library(get_workinglib()) as library:
        book_name_search = library.search_title(book_name)
        if len(book_name_search) == 0:
            print('Book name not found!')
            exit()
        book = book_name_search[0]
        try:
            library.lend_book(book, return_date, person)
            print(
                f'{book} has been lent to {person.title()} until {return_date.strftime("%A %B %d %Y")}'
            )
        except KeyError:
            print('Error: Book already lent')
Exemplo n.º 14
0
    def get_baseline_histograms(self, params):
        ''' obtain all baseline histograms for all data types

            :param params (dict): values of floating parameters
                                  for weight calculations

            :return  lib     (`Library`): a library instance with weighters set
            :retrun  bhistos (dict)     : baseline histograms from all members
        '''

        ### set up a library to handle baseline members
        lib = Library(self.members,
                      self.ppath,
                      edges=self.edges,
                      verbose=self.verbose)

        ### set up weighters for baseline members
        lib.set_weighters(params, matter=self.matter, oscnc=self.oscnc)
        ### store oscillation probability maps
        self.probmaps = lib.probmaps

        ### collect baseline histograms
        bhistos = lib.collect_base_histograms(params)
        self._print_rates('baseline', bhistos, nyears=params['nyears'])

        return lib, bhistos
Exemplo n.º 15
0
    def handle_login(self):
        self.db = MySQLdb.connect(host='localhost',
                                  user='******',
                                  password='******',
                                  db='library')
        self.cur = self.db.cursor()

        username = self.lineEdit_username.text()
        password = self.lineEdit_password.text()

        sql = ''' SELECT * FROM users'''

        self.cur.execute(sql)
        data = self.cur.fetchall()
        for row in data:
            if username == row[1] and password == row[3]:
                print('user match')
                self.hide()
                window2 = Library()
                window2.show()
                window2.exec_()

            else:
                self.lineEdit_username.setText('')
                self.lineEdit_password.setText('')
                QMessageBox.warning(self, 'Incorrect',
                                    'Please fill all fields correctly',
                                    QMessageBox.Ok)
                self.lineEdit_username.setFocus()
Exemplo n.º 16
0
 def setUp(self):
     self.library = Library()
     self.person = Person("Denys", "Kuznetsov")
     self.author = Person('Albert', "Camus")
     self.author_2 = Person('Jean-Paul', 'Sartre')
     self.book = Book("The Fall", self.author, '/path')
     self.book_2 = Book('The Wall', self.author_2, '/path_2')
Exemplo n.º 17
0
def main():
    lib = Library()
    user1 = Reader("Djinn", "Co", 25)
    user2 = Reader("Artem", "KFC", 48)
    user3 = Reader("Suga", "Rogue", 35)

    book1 = Book("Ubik", "Philip k. Dick", 1969)
    book2 = Book("The Last Wish", "Andrzej Sapkowski", 2007)
    book3 = Book("It", "Stephen King", 1986)
    print(' ')
    lib.add_book_to_lib(book1)
    lib.add_book_to_lib(book2)
    lib.add_book_to_lib(book3)
    print(' ')
    lib.add_user_to_readerslist(user1)
    lib.add_user_to_readerslist(user2)
    lib.add_user_to_readerslist(user3)
    print(' ')

    time.sleep(3)
    lib.give_book_to_user(user1, book1)
    lib.give_book_to_user(user3, book1)
    time.sleep(3)
    print(' ')
    lib.show_books(available=True)
    print(' ')
    lib.show_books(available=False)
    print(' ')
    lib.sort_books('year')
Exemplo n.º 18
0
 def test_duplicate_books(self):
     testlib = Library()
     testlib.add_book(576.82, 'A New History of Life')
     testlib.add_book(576.82, 'A New History of Life')
     assert len(testlib.shelves[5].books) == 2
     testlib.remove_book(576.82)
     assert len(testlib.shelves[5].books) == 1
Exemplo n.º 19
0
    def load_library(self):
        if self.lib.changed:
            confirm = mb.askyesnocancel("Загрузка",
                                        "Сохранить текущую библиотеку?")
            if confirm:
                self.save_library()
            elif confirm is None:
                return

        file_name = fd.askopenfilename(filetypes=(("Library files",
                                                   "*.lbf"), ))
        if not file_name:
            return False
        try:
            with open(file_name, encoding='utf-8') as f:
                data = f.read()
        except:
            mb.showerror("Ошибка", "Ошибка открытия или чтения файла")
            return False

        new_lib = Library()

        if not new_lib.set_data(data):
            del new_lib
            mb.showerror("Ошибка", "В файле неизвестные данные")
            return False

        prev_lib = self.lib
        self.lib = new_lib
        self.lib.file = file_name
        self.view_records()
        root.title(self.lib.file.split('\\')[-1].split('/')[-1])
        del prev_lib
        return True
Exemplo n.º 20
0
    def get_baseline_histograms(self, params):
        ''' obtain all baseline histograms for all data types

            :type  params: dictionary
            :param params: values of floating parameters

            :return  lib: Library instance
                     lib: a library instance with weighters set

            :retrun  bhistos: a dictionary
                     bhistos: baseline histograms from all members
        '''

        ### set up a library to handle baseline members
        lib = Library(self.members,
                      self.ppath,
                      ranges=self.get_ranges(),
                      edges=self.edges,
                      verbose=self.verbose)

        ### set up weighters for baseline members
        lib.set_weighters(params, matter=self.matter, oscnc=self.oscnc)

        ### store and print results
        bhistos = lib.collect_base_histograms(params)
        self.probmaps = lib.probmaps
        self._print_rates('baseline', bhistos, nyears=params['nyears'])

        return lib, bhistos
Exemplo n.º 21
0
 def __init__(self, filename):
     print('file--', filename)
     f = open(filename)
     l = f.readline().split(' ')
     self.filename = filename
     self.nBooks, self.nLibs, self.nDays = int(l[0]), int(l[1]), int(l[2])
     self.books = [
         Book(i, int(score))
         for i, score in enumerate(f.readline().split(' '))
     ]
     sumb = 0
     for b in self.books:
         sumb += b.score
     print(sumb / 1000000)
     self.book2Score = {book.id: int(book.score) for book in self.books}
     self.libs = []
     for libId in range(self.nLibs):
         l = [int(i) for i in f.readline().split(' ')]
         nBooks, nSign, nScan = l[0], l[1], l[2]
         books = [
             Book(int(i), int(self.book2Score[int(i)]))
             for i in f.readline().split(' ')
         ]
         lib = Library(libId, nBooks, nSign, nScan, books)
         self.libs.append(lib)
     self.pri()
Exemplo n.º 22
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)
Exemplo n.º 23
0
    def run_snippet_trigger(self, trigger, bounds):
        if not self.view:
            return False

        if not self.view.get_editable():
            return False

        buf = self.view.get_buffer()

        if buf.get_has_selection():
            return False

        snippets = Library().from_tag(trigger, self.language_id)

        if snippets:
            if len(snippets) == 1:
                return self.apply_snippet(snippets[0], bounds[0], bounds[1])
            else:
                # Do the fancy completion dialog
                self.provider.set_proposals(snippets)
                cm = self.view.get_completion()

                cm.show([self.provider], cm.create_context())
                return True

        return False
Exemplo n.º 24
0
 def test_request_book_not_present(self):
     """Tests scenario where requested book is not in Library"""
     books = ["book1", "book2", "book3", "book4"]
     library_obj = Library(books)
     user = User("Satish Hiremath")
     self.assertRaises(BookNotPresentInLibrary, user.request_book, "book6",
                       library_obj)
Exemplo n.º 25
0
 def actualSetBlacklist(self, comic_id, pagenum):
     if comic_id is not None:
         library = Library(self.dm.Session)
         if pagenum == 'clear':
             library.comicBlacklist(comic_id)
         else:
             library.comicBlacklist(comic_id, pagenum)
Exemplo n.º 26
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)
Exemplo n.º 27
0
def main():
    """
    Creates a library with dummy data and prompts the user for input.
    """
    book_list = generate_test_books()
    my_epic_library = Library(book_list)
    my_epic_library.display_library_menu()
Exemplo n.º 28
0
    def init_rooms(self, frame):
        study = Study(frame)
        study.grid(row=0, column=0)

        hall = Hall(frame)
        hall.grid(row=0, column=9)

        lounge = Lounge(frame)
        lounge.grid(row=0, column=17)

        library = Library(frame)
        library.grid(row=6, column=0)

        stairs = Stairs(frame)
        stairs.grid(row=8, column=9)

        dining_room = DiningRoom(frame)
        dining_room.grid(row=9, column=16)

        billiard_room = BilliardRoom(frame)
        billiard_room.grid(row=12, column=0)

        conservatory = Conservatory(frame)
        conservatory.grid(row=19, column=0)

        ball_room = BallRoom(frame)
        ball_room.grid(row=17, column=8)

        kitchen = Kitchen(frame)
        kitchen.grid(row=18, column=18)
Exemplo n.º 29
0
def ep_render_template(library, store, template, output=None):
    """Render a template using the given store from the gien library.

    If output is not provided, the path identified in the template will be
    used as the output target.

    Arguments:
        library: A open file pointer to the library.
        store: The name of the keystore.
        template: A open file pointer to the template to render.
        output: A optional open file pointer to write the rendered template to.
    """
    logging.debug("Loading library: {}".format(library.name))
    lib = Library(fp=library)
    logging.debug("Loading keystore: {}".format(store))
    ks = lib.get_keystore(store)
    logging.debug("Loading template: {}".format(template.name))
    tmpl = TemplateProcessor(template)

    if output:
        logging.info("Rendering template with override: {} => {}".format(
            template.name, output))
        tmpl.render_fp(ks, output)
    else:
        logging.info("Rendering template: {} => {}".format(
            template.name, tmpl.target_path))
        tmpl.render_file(ks)
Exemplo n.º 30
0
    def on_drag_data_received(self, view, context, x, y, data, info,
                              timestamp):
        if not self.view.get_editable():
            return

        uris = drop_get_uris(data)
        if not uris:
            return

        if not self.in_bounds(x, y):
            return

        uris.reverse()
        stop = False

        for uri in uris:
            try:
                mime = Gio.content_type_guess(uri)
            except:
                mime = None

            if not mime:
                continue

            snippets = Library().from_drop_target(mime, self.language_id)

            if snippets:
                stop = True
                self.apply_uri_snippet(snippets[0], mime, uri)

        if stop:
            context.finish(True, False, timestamp)
            view.stop_emission('drag-data-received')
            view.get_toplevel().present()
            view.grab_focus()