def removeBook(self):
        """
            Use the entered information if it is valid in order to remove the
            book after the Add button is pushed.
        """
        data = [self.titleEdit.text(), self.authorEdit.text(), self.yearEdit.text(), self.genre_options.currentText()]

        invalid_data = Validations.check_all(*data)
        if invalid_data == []:
            book = Book(
                self.titleEdit.text(),
                self.authorEdit.text(),
                self.yearEdit.text(),
                self.genre_options.currentText(),
                0,
                0,
            )
            Library.remove_book(book)
            self.label.setText("You removed the book successfully!")
        else:
            message = "Unsuccessful removal!Invalid:\n"
            message += "\n".join(invalid_data)
            self.label.setText(message)
        for edit in (self.titleEdit, self.authorEdit, self.yearEdit):
            edit.clear()
Beispiel #2
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)
 def test_add_book(self):
     Library(self.store, ["Fantasy"])
     Library.add_book(self.books[0])
     self.assertEqual([self.books[0]], Library.books)
     self.add_books([self.books[0], self.books[1]], Library)
     self.assertEqual([self.books[0], self.books[1]], Library.books)
     os.remove(os.path.realpath(self.store))
 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
 def addBook(self):
     """
         Use the entered information if it is valid in order to add the
         book after the Add button is pushed.
     """
     data = [
         self.titleEdit.text(),
         self.authorEdit.text(),
         self.yearEdit.text(),
         self.genre_options.currentText(),
         self.ratingEdit.text(),
         self.copiesEdit.text(),
     ]
     invalid_data = Validations.check_all(*data)
     if invalid_data == []:
         new_book = Book(*data)
         Library.add_book(new_book)
         self.label.setText("You added the book successfully!")
     else:
         message = "Unsuccessful addition!Invalid:\n"
         message += "\n".join(invalid_data)
         self.label.setText(message)
     for gadget in self.gadgets:
         if gadget != self.genre_options:
             gadget.clear()
Beispiel #6
0
def main(args):
    import signal
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    a = QtGui.QApplication(sys.argv)
    library = Library(Config.library_path)
    server = Server('*',
                    Config.req_rep_port,
                    Config.pub_sub_port,
                    library)
    camera = Camera()
    printer = Printer(library)
    slide_show = SlideShow(library)

    server.msg_recieved.connect(camera.process_cmd)
    server.msg_recieved.connect(printer.process_cmd)
    server.msg_recieved.connect(slide_show.process_cmd)
    printer.printing_image.connect(server.printing_image)
    camera.pic_taken.connect(library.add_image)
    camera.count_down_changed.connect(server.count_down_changed)
    camera.live_stream_activated.connect(server.live_stream_activated)
    library.image_added.connect(server.image_added_to_lib)
    
    #qrscanner = QRScanner()
    #camera.new_preview_image.connect(qrscanner.new_preview_image)

    server_thread = Server.startThread(server)
    camera_thread = Camera.startThread(camera)
    
    #camera_thread.started.connect(camera.start_preview)
    #qrscanner_thread = QRScanner.startThread(qrscanner)
    
    def exit_app():
        print 'stopping camera'
        camera.stop()
        print camera_thread.wait()
        print 'stopping server'
        server.stop()
        #print server_thread.wait()
        print 'exit'
        a.quit()
    
    if not args.no_ui:
        #w = Widget(camera,server,library,printer,slide_show)
        w = Widget(slide_show, camera, printer)
        w.grapicsView.scene().take_pic.connect(camera.take_pic)
        w.grapicsView.scene().print_pic.connect(printer.print_pic)
        w.grapicsView.exit_app.connect(exit_app)
        w.show()
        
    
    camera.count_down_started.connect(slide_show.stop)
    library.image_added.connect(slide_show.start)
    for image_name in library.get_all_images():
        slide_show.start(image_name)
        break
        
        
    sys.exit(a.exec_())
 def test_sorting(self):
     testlib = Library()
     testlib.add_book(100.32, 'First Book')
     testlib.add_book(199.3, 'Last Book')
     testlib.add_book(150, 'Middle Book')
     assert testlib.shelves[1].books[0].title == 'First Book'
     assert testlib.shelves[1].books[1].title == 'Middle Book'
     assert testlib.shelves[1].books[2].title == 'Last Book'
 def test_book_information_by_title(self):
     Library(self.store, ["Fantasy", "Thriller"])
     self.add_books([self.books[0], self.books[1], self.books[2]], Library)
     book_birds = Library.book_information_by_title("Birds")
     self.assertEqual([self.books[1], self.books[2]], book_birds)
     book_somewhere = Library.book_information_by_title("Somewhere")
     self.assertEqual([self.books[0]], book_somewhere)
     self.assertEqual([], Library.book_information_by_title("Haha"))
     os.remove(os.path.realpath(self.store))
Beispiel #9
0
        def do_activate(self):
                # Initialize snippets library
                library = Library()

                if platform.system() == 'Windows':
                        snippetsdir = os.path.expanduser('~/gedit/snippets')
                else:
                        snippetsdir = os.path.join(GLib.get_user_config_dir(), 'gedit/snippets')

                library.set_dirs(snippetsdir, self.system_dirs())
Beispiel #10
0
  def post(self):
    params = decode(self.request.body)

    if (params ["request_type"] == "lend"): 
      Library.lend_book(self, params["book"])
    else:
      if(params["request_type"] == "return"):
        Library.return_book(self, params["book"])
      else:
        self.request.body("> Invalid operation!")
    def update_table(self):
        """
            Update the table after clicking the Search button.
        """
        self.table.setRowCount(0)
        self.table.setColumnCount(0)
        search = self.searchEdit.text()
        if self.author.isChecked():
            results = Library.book_information_by_author(search)
        elif self.title.isChecked():
            results = Library.book_information_by_title(search)
        else:
            results = Library.book_information_by_title_author(search)
        self.table = QtGui.QTableWidget(len(results), 10, self)
        headers = ("Title", "Author's name", "Published in", "Genre",
                   "Rating", "Copies", "Get", "Return", "Like", " Dislike")
        self.table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.table.setHorizontalHeaderLabels(headers)
        self.table.resizeColumnsToContents()
        self.table.resizeRowsToContents()

        widths = [150, 150, 90, 80, 70, 60, 50, 60, 50, 70]
        for col, width in zip(range(9), widths):
            self.table.setColumnWidth(col, width)

        self.table.horizontalHeader().setStretchLastSection(True)
        for row in range(len(results)):
            book = results[row]
            col = 0
            for column in (book.title, book.author, book.year, book.genre,
                           book.rating, book.number_of_copies):
                item = QtGui.QTableWidgetItem(str(column))
                self.table.setItem(row, col, item)
                col += 1

        for row in range(len(results)):
            get_btn = QtGui.QPushButton("Get")
            get_btn.setMinimumSize(50, 30)
            get_btn.clicked.connect(partial(self.get_a_copy, row))
            self.table.setCellWidget(row, 6, get_btn)
            return_btn = QtGui.QPushButton("Return")
            return_btn.setMinimumSize(50, 30)
            return_btn.clicked.connect(partial(self.return_a_copy, row))
            self.table.setCellWidget(row, 7, return_btn)

            like_btn = QtGui.QPushButton("Like")
            like_btn.setMinimumSize(50, 30)
            like_btn.clicked.connect(partial(self.like_a_book, row))
            self.table.setCellWidget(row, 8, like_btn)
            dislike_btn = QtGui.QPushButton("Dislike")
            dislike_btn.setMinimumSize(50, 30)
            dislike_btn.clicked.connect(partial(self.dislike_a_book, row))
            self.table.setCellWidget(row, 9, dislike_btn)

        self.grid.addWidget(self.table, 1, 0)
 def test_create_genre_dict(self):
     Library(self.store, ["Fantasy", "Thriller"])
     self.add_books([self.books[0], self.books[1], self.books[2]], Library)
     Library.create_genre_dict()
     expected_dict = {"Fantasy": [self.books[1], self.books[0]],
                      "Thriller": [self.books[2]]}
     self.assertEqual(expected_dict, Library.genre_dict)
     Library.add_book(self.books[3])
     expected_dict["Thriller"].append(self.books[3])
     self.assertEqual(expected_dict, Library.genre_dict)
     os.remove(os.path.realpath(self.store))
 def test_book_information_by_author(self):
     Library(self.store, ["Fantasy", "Thriller"])
     self.add_books(self.books, Library)
     book_steven = Library.book_information_by_author("Steve Law")
     self.assertEqual([self.books[0]], book_steven)
     book_john = Library.book_information_by_author("John White")
     self.assertEqual([self.books[1], self.books[4]], book_john)
     book_steve = Library.book_information_by_author("Steve Tyler")
     self.assertEqual([self.books[2], self.books[3]], book_steve)
     self.assertEqual([], Library.book_information_by_author("Haha"))
     os.remove(os.path.realpath(self.store))
Beispiel #14
0
def generate(n):
    lib = Library()

    for i in range(0, n):
        lib.append(Book(
            "Author{0}".format(random.randint(1, n)),
            "Title{0}".format(random.randint(1, n)),
            random.randint(1950, 2015),
            "Publ{0}".format(random.randint(1, n))))

    return lib
 def test_remove_book(self):
     testlib = Library()
     testlib.add_book(576.82, 'A New History of Life')
     testlib.add_book(575.01, 'An Old History of Life')
     assert len(testlib.shelves[5].books) == 2
     testlib.remove_book(576.82)
     assert len(testlib.shelves[5].books) == 1
     # remove nonexistent book
     testlib.remove_book(501.2)
     assert len(testlib.shelves[5].books) == 1
    def makeAssumes(self):
        lib = Library(self)
        lib.load("matrix")
        # lib.load('sort')

        N = self.parameters["N"]

        self.assume("N", N)
        self.assume("inv_sqrt_N", pow(N, -0.5))

        self.assume("A", "(make_matrix N N (mem (lambda (i j) (uniform_continuous 0 1))))")
        self.assume("x", "(make_matrix N 1 (mem (lambda (i j) (if (flip inv_sqrt_N) (normal 0 1) 0))))")
        self.assume("b", "(matrix_prod A x)")
        self.assume("noise", "(inv_gamma 1 1)")
Beispiel #17
0
  def __run_simulation_process(self):
    # The grid for this simulation.
    self.__grid = automata.Grid(self.__x_size, self.__y_size)
    # The visualization of the grid for this simulation.
    self.__grid_vis = visualization.GridVisualization(
        self.__x_size, self.__y_size)

    # The list of objects on the grid.
    self.__grid_objects = []

    # The frequency for updating the graphics.
    graphics_limiter = PhasedLoop(30)
    # The frequency for updating the simulation.
    # TODO(danielp): Make this rate user-settable.
    simulation_limiter = PhasedLoop(1)

    # Load all the organisms that we needed to load.
    for organism in self.__to_load:
      library_name = organism[0]
      name = organism[1]
      x_pos = organism[2]
      y_pos = organism[3]

      library = Library(library_name)
      organism = library.load_organism(name, self.__grid, (x_pos, y_pos))
      logger.info("Adding new grid object at (%d, %d)." % (x_pos, y_pos))

      self.__grid_objects.append(organism)

      # Add a visualization for the organism.
      visualization.GridObjectVisualization(self.__grid_vis, organism)

    # Update the grid to bake everything in its initial position.
    if not self.__grid.Update():
      logger.log_and_raise(SimulationError, "Initial grid update failed.")

    # Now that the visualization is populated, draw a key for it.
    self.__key = visualization.Key(self.__grid_vis)

    # Now run the simulation.
    while True:
      PhasedLoop.limit_fastest()

      if simulation_limiter.should_run():
        # Run the simulation.
        self.__run_iteration()
      if graphics_limiter.should_run():
        self.__grid_vis.update()
        self.__key.update()
 def test_number_of_books_by_genres(self):
     Library(self.store, ["Fantasy", "Thriller"])
     self.add_books([self.books[0], self.books[1], self.books[2]], Library)
     actual_result = Library.number_of_books_by_genres()
     self.assertEqual({'Fantasy': 2, 'Thriller': 1}, actual_result)
     Library.add_book(self.books[3])
     actual_result = Library.number_of_books_by_genres()
     self.assertEqual({'Fantasy': 2, 'Thriller': 2}, actual_result)
     Library.remove_book(self.books[1])
     actual_result = Library.number_of_books_by_genres()
     self.assertEqual({'Fantasy': 1, 'Thriller': 2}, actual_result)
     Library.remove_book(self.books[0])
     actual_result = Library.number_of_books_by_genres()
     self.assertEqual({'Fantasy': 0, 'Thriller': 2}, actual_result)
     os.remove(os.path.realpath(self.store))
Beispiel #19
0
        def do_deactivate(self):
                if self.accel_group:
                        self.window.remove_accel_group(self.accel_group)

                self.accel_group = None

                self.remove_menu()
                self.unregister_messages()

                library = Library()
                library.remove_accelerator_callback(self.accelerator_activated)

                self.disconnect_signals(self.window)

                SharedData().unregister_window(self)
Beispiel #20
0
class Main():

    def __init__(self, gru_file=None): 
        self.menu = Menu(self, config, game = None)        
        self.library = Library(self, config)
        self.collider = Collider(self.menu, self.library, game=None)
        self.dispatcher = Dispatcher(self.collider, self.library, self.menu, game=None)
        self.clock = pygame.time.Clock()
        self.fps = Fps(self.clock, config)
        if gru_file is not None:
            game = Game(gru_file)
            self.load(game)
        else:
            self.game = None        
        
    def load(self, game):
        self.library.clear()
        self.game = game
        self.collider.game = game
        self.menu.game = game

    def clear(self):
        self.game = None
        self.collider.game = None
        self.menu.game = None

    def draw(self):    
        tick = self.clock.get_time()
        self.menu.draw()    
        if self.game == None:
            self.library.draw()  
        else:           
            self.game.draw(tick)        

                                  
    def start(self):                          
                     
        while 1:      
            self.clock.tick()                   
            mrect = Rect(mouse.get_pos(), (1,1))  
            self.collider.check()          
            self.draw()  
            self.fps.draw()            

            for ev in event.get():
                self.dispatcher.process(ev)               

            display.update()
    def get(self):
        #page for class
        p = Form()
        l = Library()
#print out results
        if self.request.GET:
            temp = int(self.request.GET["temperature"])
            c = l.convert_celuis(temp)
            k = l.convert_kelvin(temp)
            r = l.convert_rankine(temp)
            n = self.request.GET['name']
            z = self.request.GET['city']
            self.response.write( n + ", currently in it's " + str(c) + " degrees Celsius, " +  str(k) + " degrees Kelvin or " + str(r) + " degrees Rankine in " + z)
#show form if its not filled out
        else:
            self.response.write(p.print_out())
Beispiel #22
0
 def GET(self):
     try:
         response = {"status": "ok", "backup": Library.instance().flush()}
     except:
         response = {"status": "error"}
     web.header("Cache-Control", "no-cache")
     return json.dumps(response)
Beispiel #23
0
 def cek_layer_input(self):
     # pendefinisian layer input
     self.layer_a = self.dlg.layerInputA.itemData(self.dlg.layerInputA.currentIndex())
     self.layer_b = self.dlg.layerInputB.itemData(self.dlg.layerInputB.currentIndex())
     self.lib = Library(self.layer_a, self.layer_b, 10)
     if self.layer_a == self.layer_b:
         self.dlg.opp_btnRun.setEnabled(False)
         self.dlg.adj_btnRun.setEnabled(False)
         self.dlg.tabMenu.setEnabled(False)
         self.dlg.labelTitikA.setText("Layer A and Layer B must not same")
         self.dlg.labelTitikB.setText("Layer A and Layer B must not same")
     else:
         self.dlg.opp_btnRun.setEnabled(True)
         self.dlg.adj_btnRun.setEnabled(True)
         self.dlg.tabMenu.setEnabled(True)
         self.cek_terpilih_a()
         self.cek_terpilih_b()
         if len(self.layer_a.selectedFeatures()) != 0:
             self.dlg.checkBox_pilihA.setEnabled(True)
         else:
             self.dlg.checkBox_pilihA.setEnabled(False)
         if len(self.layer_b.selectedFeatures()) != 0:
             self.dlg.checkBox_pilihB.setEnabled(True)
         else:
             self.dlg.checkBox_pilihB.setEnabled(False)
         self.dlg.checkBox_pilihA.stateChanged.connect(self.cek_terpilih_a)
         self.dlg.checkBox_pilihB.stateChanged.connect(self.cek_terpilih_b)
Beispiel #24
0
 def get_data(self):
     """
         Gain access of the data about the books in the library.
     """
     self.data = Library.number_of_books_by_genres()
     self.genres = sorted(self.data.keys())
     self.count = list(self.data[genre] for genre in self. genres)
Beispiel #25
0
 def sblh_deploy(self):
     list_geom_a = [feat.geometry() for feat in self.list_feat_garis_a]
     list_geom_b = [feat.geometry() for feat in self.list_feat_garis_b]
     list_feat = self.list_feat_ttk_a + self.list_feat_ttk_b
     t_awal_a = self.lib.titik_pada_garis(self.dlg.adj_start_a, list_geom_a)
     t_awal_b = self.lib.titik_pada_garis(self.dlg.adj_start_b, list_geom_b)
     list_t_akhir = []
     for a in list_geom_a:
         for b in list_geom_b:
             if a.intersects(b):
                 t_akhir = a.intersection(b)
                 list_t_akhir.append(t_akhir)
             else:
                 pass
     if len(list_t_akhir) == 0:
         raise ValueError("No end point detected")
     elif len(list_t_akhir) > 1:
         raise ValueError("More than one end point detected")
     else:
         g_akhir = list_t_akhir[0]
         ttk_akhir = g_akhir.asPoint()
     jarak_klaim = int(self.dlg.adj_claim_dist.text())*1852
     self.adj_lib = Library(self.layer_a, self.layer_b, 10, jarak_klaim)
     list_g_eq, list_g_cc, list_g_gk = self.adj_lib.proses_sb(t_awal_a,
                                                              t_awal_b,
                                                              ttk_akhir,
                                                              list_feat)
     self.adj_lib.konversi_titik_ke_garis(list_g_cc)
     if self.dlg.checkBox_cLine.isChecked():
         self.lib.buat_layer_garis_k(list_g_gk)
     if self.dlg.checkBox_titikEq.isChecked():
         self.lib.buat_layer_titik(list_g_cc)
 def return_a_copy(self, row):
     """
         Return a copy of a certain book.
     """
     book = Library.return_book(self.generate_book_by_row(row))
     item = QtGui.QTableWidgetItem(str(book.number_of_copies))
     self.table.setItem(row, 5, item)
    def __init__(self, path, photos_path, tmp_db):
        self.path = os.path.abspath(path)
        self.photos_path = photos_path

        db_path = os.path.join(photos_path, "database")
        self.library = Library(db_path, tmp_db)

        self.photos = dict()
Beispiel #28
0
def main():

	# init area
	bet_shemesh = Library("Bet Shemesh")

	# Menu section
	print "welcome to " + bet_shemesh.get_name() + " library"
	print "we have in our library " + str(bet_shemesh.get_books_count()) + " books"
	print "Main Menu:"
	print "1. Enter new author"
	print "2. Enter new book"
	print "3. search for a book by name"
	print "3. search for a book by author"
	print "3. search for a author"
	user_choice = input("Pease enter your choice ==> ")
	if user_choice == 1:
		pass
Beispiel #29
0
def main():
    user_config = load_config()
    set_up_environment(user_config)
    interface = UI(user_config)
    library = Library(user_config.library.database_path)
    if os.path.exists(sys.argv[1]):
        interface.player.set_file(sys.argv[1])
        interface.player.play()
    else:
        # Oh no! There's no file, let's do a search!
        d = library.discover_on_path(user_config.library.index_paths)
        d.addCallback(lambda _: library.search_tracks(sys.argv[1]))
        @d.addCallback
        def search_track(result):
            interface.player.set_file(result[0].file_path)
            interface.player.play()
    interface.run()
Beispiel #30
0
 def test_sorting(self):
     testlib = Library()
     testlib.add_book(100.32, 'First Book')
     testlib.add_book(199.3, 'Last Book')
     testlib.add_book(150, 'Middle Book')
     assert testlib.shelves[1].books[0].title == 'First Book'
     assert testlib.shelves[1].books[1].title == 'Middle Book'
     assert testlib.shelves[1].books[2].title == 'Last Book'
Beispiel #31
0
def handlein(filein, fileout):
    lines = filein.readlines()
    nb_books, nb_libs, days = map(int,lines[0].split(' '))
    books = {}
    book_scores = list(map(int,lines[1].split(' ')))
    for i in range(nb_books):
        books[i] = Book(i, book_scores[i], 0)
    libs = []
    lib_id = 0
    for i in range(2,2+2*nb_libs,2):
        capacity, signup, ship = map(int, lines[i].split(' '))
        libbooks = list(map(lambda x: books[int(x)], lines[i +1].split(' ')))
        libs.append(Library(lib_id,signup, ship, libbooks))
        lib_id = lib_id + 1

    score = 0
    explored_libs=set()
    explored_book =set()
    print('len(explored_libs) :', len(explored_libs))
    while(score < 4) :
        explored_books=0
        score =0
        explored_libs.clear()
        explored_book.clear()
        print('Starting NbrLib Expl',len(explored_libs))
        print('Starting score :', score)
        print('Starting Explored ',explored_books)
        for l in libs:
                l.score = 0
                l.scanned_book=0
                l.booktokeep.clear()
                l.max_score=0
                l.sinupDate=0
                for b in l.unique_books:
                    b.is_scanned=False
        
        process(books, libs, days,explored_libs,explored_book)
    
        print('NbrLib ',len(libs))
        print('NbrBook ',len(books))

        for b in explored_book :
            score += books[b].score
            explored_books +=1
    
        print('Explored ',explored_books)
        print('NbrLib Expl',len(explored_libs))

        print("score: ",score)
        
    generate_output(fileout, explored_libs)
def main():
    
    #declare books and patrons
    book1 = Book("Of Mice and Men", "Steinbeck")
    book2 = Book("The Great Gatsby", "Fitzgerald")
    book3 = Book("1984","Orwell")
    book4 = Book("One Flew Over the Cuckoo's Nest","Kesey")
    patron1 = Patron("Ivan")
    patron2 =Patron("Jimmy")
    patron3 = Patron("Bob")
    
    #add books
    libraryBooks = []
    libraryBooks.append(book1)
    libraryBooks.append(book2)
    libraryBooks.append(book3)
    libraryBooks.append(book4)

    #create Library to store books and patrons
    myLibrary = Library(libraryBooks)
    
    #add patrons to library
    myLibrary.addPatron(patron1)
    myLibrary.addPatron(patron2)
    myLibrary.addPatron(patron3)
    
    #test borrowing features
    myLibrary.borrowBook(book1, patron2)
    myLibrary.borrowBook(book1, patron3)
    
    #Check Print Status
    print(str(myLibrary))
    
    #check return features
    myLibrary.returnBook(book1)
    
    #see if book was returned correctly
    print(str(myLibrary))
Beispiel #33
0
def delete_book_bid(bid: str) -> None:
    """
    Removes the book with given identifier (bid)

    :param bid: Book identifier (bid)
    """
    with Library(get_workinglib()) as library:
        try:
            _book = library.books[bid]
        except KeyError:
            print('Book not found!')
            exit()
        library.delete_book(_book)
        print(f'{_book} has been removed from the library')
Beispiel #34
0
def main():
    try:
        lib = Library(conf.library_dir)

        if conf.action == "clean":
            cleaner = Cleaner(lib)
            print("Removing duplicates..."),
            cleaner.remove_duplicates()
            print("DONE")

            cleaner.report()

            if not conf.test:
                lib.flush()
                print("\nTraktor library updated.")
            else:
                print("\nTest run. No changes made to the library.")
        elif conf.action == "export":
            exporter = Exporter(lib, conf.export_dir)
            exporter.export()

    except Exception as e:
        logger.error(e, exc_info=False)
Beispiel #35
0
def delete_book_name(book_name: str) -> None:
    """
    Removes the first book that matches the book_name string from the library

    :param book_name: Name string of the book
    """
    with Library(get_workinglib()) as library:
        book_name_search = library.search_title(book_name)
        if len(book_name_search) == 0:
            print('Error: Book name not found!')
            exit()
        _book = book_name_search[0]
        library.delete_book(_book)
        print(f'{_book} has been removed from the library')
def set_credentials(username, password):
    if len(libraries) == 1:
        lib = libraries.values()[0]

        if lib.username == username and lib.password == password:
            return

        lib.logout()
        libraries.clear()

    if username is None or password is None:
        return

    Library(username, password)
Beispiel #37
0
def main():
    timestamp = datetime.datetime.now().strftime("%c")
    print("Start:", timestamp)

    gl = gitlab.Gitlab.from_config(config_files=[CONFIG_FILE])

    # Init Library - get versions and make a pam from it
    library = Library(gl, CONFIG_FILE)

    # Read repos form config
    projects = read_project_config(CONFIG_FILE, gl)

    for project in projects:
        project.parse_revisions(library)
Beispiel #38
0
def parseInput(inp):
    itr = (line for line in inp.split('\n'))
    numberOfDifferentBooks, numberOfLibraries, numberOfDays = nl(itr)
    books = {bookID: Book(bookID, bookScore)
             for bookID, bookScore in enumerate(nl(itr))}
    libraries = SortedList()
    for i in range(numberOfLibraries):
        numberOfBooks, signUpTime, capacityOfShipping = nl(itr)
        line = nl(itr)
        libraryBooks = SortedList(books[bookID]
                                  for bookID in line)
        libraries.add(Library(i, numberOfBooks, signUpTime,
                              capacityOfShipping, libraryBooks, numberOfDays))
    return argparse.Namespace(numberOfDifferentBooks=numberOfDifferentBooks, numberOfLibraries=numberOfLibraries, numberOfDays=numberOfDays, books=books, libraries=libraries)
Beispiel #39
0
def library_list():
    if request.method == 'PUT':
        data = json.loads(request.get_data().decode("utf8"))
        Library.add(data['name'], data['path'], data['lib_type'],'','','')
        return json_return(
            {
                'message': "添加成功"
            }
        )

    full = request.args.get("full", "false") == 'true'
    with Database() as db:
        rows = db.select(
            "select id,name,lib_type,dir,status,version from library order by id", dict_result=True)
        if not full:
            return json_return(rows)
        result = {
            row['id']: {
                'id': row['id'],
                'name': row['name'],
                'lib_type': row['lib_type'],
                'dir': row['dir'],
                'status': row['status'],
                'version': row['version'],
                'count': 0,
                'next_count': 0
            } for row in rows}
        item_sql = "select library_id,version,count(1) c from item group by library_id,version"
        item_rows = db.select(item_sql, dict_result=True)
        for row in item_rows:
            if row['version'] == result[row['library_id']]['version']:
                result[row['library_id']]['count'] = row['c']
            else:
                result[row['library_id']]['next_count'] = row['c']
        return json_return(
            [item for item in result.values()]
        )
Beispiel #40
0
def main():
    # def __init__(self, title, call_no, author, num_copies):
    # issue, publisher):
    # def __init__(self, title, call_no, author, num_copies, name,
    #              issue, publisher):
    b1 = Book("Provenance", "342.2", "Anne Leckie", 20)
    b2 = Book("Ancillary Justice", "342.2A", "Anne Leckie", 1)
    j1 = Journal("Individual Psychology", "123.4", "Gabriela Pap", 1,
                 "Journal of Psychology", 23, "SAGE Publications")
    d1 = Dvd("Mad Max: Fury Road", "789.0", "George Miller", 8, "May 15, 2015",
             "1")
    cat = Catalogue({
        "342.2":
        Book("Provenance", "342.2", "Anne Leckie", 20),
        "342.2A":
        Book("Ancillary Justice", "342.2A", "Anne Leckie", 1),
        "123.4":
        Journal("Individual Psychology", "123.4", "Gabriela Pap", 1,
                "Journal of Psychology", 23, "SAGE Publications"),
        "789.0":
        Dvd("Mad Max: Fury Road", "789.0", "George Miller", 8, "May 15, 2015",
            "1")
    })
    vpl = Library(cat)

    display_menu = True

    while display_menu:
        print("What would you like to do?")
        print("1. Find item by title (String)")
        print("2. Add item to catalogue")
        print("3. Remove item from catalogue (call no)")
        print("4. Check out a copy (call no)")
        print("5. Return your copy (call no)")
        print("6. Display library catalogue")
        print("7. Quit menu")

        choice = int(input("Select action: "))

        if choice == 2:
            vpl.get_cat().add_item()
        elif choice == 6:
            vpl.display_available_books()
        elif choice == 7:
            display_menu = False
        elif choice not in range(1, 6):
            print("\nInvalid input.  Try again.\n")
        else:
            par = input("Enter parameter: ")
            input_dict = {
                1: vpl.search,
                3: cat.remove_item,
                4: vpl.check_out,
                5: vpl.return_item
            }

            print(input_dict.get(choice)(par))
Beispiel #41
0
def read_input(fname):
    with open(f"data/{fname}") as f:
        lines = f.readlines()
    metadata = lines[0].split(" ")
    B = int(metadata[0])
    L = int(metadata[1])
    D = int(metadata[2])
    books_score = [int(i) for i in lines[1].strip().split(" ")]
    all_books = {i: books_score[i] for i in range(len(books_score))}
    all_books_list = []
    problem = Problem(n_books=B, n_libraries=L, n_days=D, scores=books_score)
    for i, group in enumerate(grouper(2, lines[2:])):
        l1, l2 = group[0], group[1]
        if l2 is None:
            break
        library = Library(i, *[int(i) for i in l1.strip().split(" ")])
        # import ipdb
        #
        # ipdb.set_trace()
        books = {(int(i)): all_books[int(i)] for i in l2.strip().split(" ")}
        all_books_list.append(books)
        library.add_books(books)
        problem.add_library(library)
    return problem, all_books, all_books_list
Beispiel #42
0
def search():
    # url(?key=value)
    s = request.args.get('search', '')

    filename = 'new_lib_info.json'
    lib = Library(filename, True)

    # will want to get right from search in future
    results = []
    if s:
        books = lib.search(s)
        for book in books:
            results.append(str(book))
        if results == []:
            results = -1

    num_results = 0
    if type(results) != int:
        num_results = len(results)

    return render_template('index.html',
                           query=s,
                           results=results,
                           num_results=num_results)
Beispiel #43
0
    def GET(self):
        if librarian.is_traktor_running():
            response = {
                "status": "error",
                "message": "Please quit Traktor first."
            }
        else:
            cleaner = Cleaner(Library.instance())
            cleaner.remove_duplicates()
            logger.debug(u"Duplicate removal complete")

            response = cleaner.get_result()
            response["status"] = "ok"
        web.header("Cache-Control", "no-cache")
        return json.dumps(response)
Beispiel #44
0
def return_book_name(book_name: str) -> None:
    """
    Returns to the library the first book that matches book_name

    :param book_name: Name string of the book
    """
    with Library(get_workinglib()) as library:
        book_name_search = library.search_title(book_name)
        if len(book_name_search) == 0:
            print('Error: Book name not found!')
            exit()
        book = book_name_search[0]
        try:
            library.return_book(book)
            print(f'{book} has been returned')
        except KeyError:
            print(f'Error: {book} has not been lent')
Beispiel #45
0
def return_book_bid(bid: str) -> None:
    """
    Mark book with given bid as returned

    :param bid: Book unique identifier
    """
    with Library(get_workinglib()) as library:
        try:
            book = library.books[bid]
        except KeyError:
            print('Book not found!')
            exit()
        try:
            library.return_book(book)
            print(f'{book} has been returned')
        except KeyError:
            print(f'Error: {book} has not been lent')
Beispiel #46
0
def ep_del_keystore(library, name):
    """Remove a new keystore from a library.

    Arguments:
        library: The path to the library to use.
        name: The name of the keystore to remove.
    """
    logging.debug("Loading library: {}".format(library))
    lib = Library(path=library)
    logging.info("Removing keystore: {}".format(name))
    lib.remove_keystore(name)
    lib.save()
Beispiel #47
0
def read(file_name):
    with open(file_name, 'r') as f:
        line = f.readline()
        num_books, num_libs, num_days = [int(l) for l in line.split()]
        line = f.readline()
        books = {i: Book(i, int(v)) for i, v in enumerate(line.split())}
        libs = []
        for i in range(num_libs):
            line = f.readline()
            nb, su, bpd = [int(l) for l in line.split()]
            line = f.readline()
            book_ids = [int(l) for l in line.split()]
            lb = {j: books[j] for j in book_ids}
            for b in lb.values():
                b.register_copy()
            libs.append(Library(i, lb, su, bpd))

    return num_days, libs
def input_parser(filename):
    with open(filename, "r") as myfile:
        line1 = myfile.readline()
        line2 = myfile.readline()
        [books_num, libs_num, days_num] = line1.split()
        book_scores = line2.split()
        libs = dict()
        for i in range(int(libs_num)):
            firstline = myfile.readline()
            secondline = myfile.readline()

            [lib_books_num, lib_signup_days,
             books_per_day] = firstline.split(" ")
            libs[i] = Library(i, firstline.split()[1], firstline.split()[2])
            lib_book_ids = secondline.split()
            for book in lib_book_ids:
                libs[i].add_book(int(book), int(book_scores[int(book)]))
    return books_num, days_num, book_scores, libs
Beispiel #49
0
def get_input(file_path):
	with open(file_path) as f:
		num_of_books, num_of_libs, days_of_scan = f.readline().split()
		list_of_scored = [int(s) for s in f.readline().split()]

		librarys = []

		for lib in range(int(num_of_libs)):
			book_of_lib, time, books_per_day = f.readline().split()

			books = f.readline().split()
			actual_books = []
			for book_id in books:
				actual_books.append(Book(int(book_id), list_of_scored[int(book_id)]))
			
			librarys.append(Library(lib, actual_books, int(time), int(books_per_day)))

	return InputCluster(librarys, num_of_books ,days_of_scan)
Beispiel #50
0
    def accelerator_activate(self, keyval, mod):
        if not self.view or not self.view.get_editable():
            return False

        accelerator = Gtk.accelerator_name(keyval, mod)
        snippets = Library().from_accelerator(accelerator, \
                        self.language_id)

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

        return True
Beispiel #51
0
def add_book(ctx: click.Context, title: str, author: str) -> None:
    """
    Adds a book to the library. Additional arguments can be added.
    \b
    Example: add-book "Fahrenheit 491" "Ray Bradbury" -year 1953

    \b
    :param title: Title of the book
    :param author: Author of the book
    :param ctx: Context of the click command line
    """
    kwargs = {
        ctx.args[i][1:]: ctx.args[i + 1]
        for i in range(0, len(ctx.args), 2)
    }
    _book = Book(title, author, **kwargs)
    with Library(get_workinglib()) as library:
        library.add_book(_book)
        print(f'{_book} has been added to the library with {_book.bid} as bid')
Beispiel #52
0
def ep_add_keystore(library, name, type, uri):
    """Add a new keystore to a library.

    Arguments:
        library: The path to the library to use.
        name: A name to register this keystore under.
        type: The type of keystore to link to.
        uri: The URI to the new keystore.
    """
    logging.debug("Loading library: {}".format(library))
    lib = Library(path=library)
    logging.info("Adding new keystore: {}".format(name))
    lib.add_keystore(name, type, uri)
    lib.save()
Beispiel #53
0
    def parse_hash_code_file(self) -> tuple:
        """
        Parsing the input data

        @return: tuple -- d: the number of days, libraries: the list containing the libraries objects
        """
        path = "scenarios/{}.txt".format(self.file_name)

        # Check if the path exists
        if not os.path.isfile(path):
            raise Exception('Didn\'t found the file: {}'.format(path))

        b, l, d = None, None, None
        book_scores, books_obj = [], []
        n, t, m = None, None, None
        libraries = []

        with open(path) as fp:
            cnt = 0
            for i, line in enumerate(fp):
                if line == '\n':
                    continue

                if i == 0:
                    b, l, d = line.strip().split(' ')
                elif i == 1:
                    book_scores = list(line.strip().split(' '))
                    books_obj = self.create_books(
                        book_scores
                    )  # from the books_scores create an array of books objects
                elif i % 2 == 0:
                    n, t, m = line.strip().split(' ')
                else:
                    lib_books = list(line.strip().split(' '))
                    books = self.create_books_list(
                        lib_books,
                        books_obj)  # create the library's books list
                    libraries.append(
                        Library(cnt, int(n), int(t), int(m), books))
                    cnt += 1

        return int(d), books_obj, libraries
Beispiel #54
0
def read_input(filename):

    with open(filename, 'r') as f:

        #for index, line in enumerate(f):

        libraries = []

        data = f.readline()
        nbooks, nlibraries, days = list(map(int, data.split(" ")))

        scores = list(map(int, f.readline().split(" ")))

        for i in range(nlibraries):
            info = list(map(int, f.readline().split(" ")))

            books = list(map(int, f.readline().split(" ")))
            lib = Library(books, info[1], info[2], i)
            libraries.append(lib)

        return scores, libraries, days
Beispiel #55
0
def create_dataset(n_qubits=8):
    """
    Generates easy, hard and random datasets and saves them as .npz files

    Args:
        n_qubits: Number of qubits
    Returns:
    Raises:
    """

    np.random.seed(123456789)

    if not os.path.exists('data/'):
        os.makedirs('data/')
    library = Library('data/')

    easy = RandomStateGenerator()
    easy_d = easy.make_dset_easy(n_qubits)
    easy_d = sample(easy_d, n_qubits)
    library.writer(easy_d, 'easy_dataset')
    del easy_d, easy
    print("Finished generating easy dataset.")

    rand = RandomStateGenerator()
    rand_d = rand.make_dset_hard(n_qubits)  # 18qubits is too big to handle
    rand_d = sample(rand_d, n_qubits)
    library.writer(rand_d, 'random_dataset')
    del rand_d, rand
    print("Finished generating random dataset.")

    # 3,4 is the correct inputs for 18 qubit state acc to authors
    hard = HardStateGenerator(3, 4)
    hard_d = hard.get_hard_distribution()
    hard_d = sample(hard_d, n_qubits)
    library.writer(hard_d, 'hard_dataset')
    del hard_d, hard
    print("Finished generating hard dataset.")
Beispiel #56
0
    def update_language(self, controller):
        if not self.window:
            return

        if controller:
            langid = controller.language_id
        else:
            langid = None

        if langid != None:
            accelgroup = Library().get_accel_group(langid)
        else:
            accelgroup = None

        if accelgroup != self.current_language_accel_group:
            if self.current_language_accel_group:
                self.window.remove_accel_group(
                    self.current_language_accel_group)

            if accelgroup:
                self.window.add_accel_group(accelgroup)

        self.current_language_accel_group = accelgroup
Beispiel #57
0
    def load_data_set(self):
        input_filename = "data/" + self.data_set_name + ".txt"

        with open(input_filename) as file:

            def get_int_list_from_line():
                return [int(x) for x in file.readline().split()]

            self.n_books, self.n_libraries, self.n_days = get_int_list_from_line(
            )
            self.book_scores = get_int_list_from_line()

            for lib_id in range(self.n_libraries):
                lib_n_books, lib_signup_time, lib_books_per_day = get_int_list_from_line(
                )
                lib_books = get_int_list_from_line()

                library = Library(lib_id, lib_n_books, lib_signup_time,
                                  lib_books_per_day, lib_books)
                self.libraries.append(library)

        self.selected_libraries = []
        self.is_book_id_selected = [False] * self.n_books
Beispiel #58
0
    def __init__(self, controller, ui):

        super().__init__()

        self.controller = controller
        self.ui = ui

        # TODO: load asynchronously, especially the storage code that calls an API.
        self.libraries = {}

        folders = os.getenv('RD_LIBRARY')
        if not folders:
            return
        for folder in folders.split(':'):

            new_library = Library(folder)

            self.libraries[new_library.name] = new_library

            self.load_track_list(new_library)

        self.storage_thread = StorageThread()
        self.storage_thread.initialized.connect(self.storage_initialized)
        self.storage_thread.start()
Beispiel #59
0
def main():
    if len(sys.argv) != 2:
        print("Usage: main.py conf_file")
        sys.exit()

    # Read configuration from file.
    logger.info("Reading configuration from '%s'." % (sys.argv[1]))
    config_file = open(sys.argv[1])
    config = yaml.load(config_file, Loader=Loader)
    config_file.close()

    # Load all the organisms specified.
    if "Organisms" not in config:
        logger.fatal("Invalid config, needs 'Organisms' section.")

    if ("GridXSize" not in config and "GridYSize" not in config):
        logger.fatal("Invalid config, needs GridXSize and GridYSize")
    if "IterationTime" not in config:
        logger.fatal("Invalid config, needs IterationTime.")
    simulation = Simulation(config["GridXSize"], config["GridYSize"],
                            config["IterationTime"])

    # Add them to the simulation.
    for organism in config["Organisms"]:
        for i in range(0, organism["Quantity"]):
            library = Library(organism["Library"])
            simulation.add_organism(organism["Library"], organism["Name"])

    # Start it running.
    logger.info("Delegating to simulation process.")
    simulation.start()

    # Wait forever.
    select.select([], [], [])

    logger.critical("Exiting main.py.")
Beispiel #60
-1
    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:
            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.")