def createLibrary(): firstBook = Book.Book() firstBook.setId(0) firstBook.setName("Птица") firstBook.setAuthor(["Пушкин", "Есенин"]) firstBook.setPublishing("Москва") firstBook.setPublicationYear(1234) firstBook.setNumberPage(24) firstBook.setPrice(50) firstBook.setBindingType("картон") secondBook = Book.Book() secondBook.setId(1) secondBook.setName("Медведь") secondBook.setAuthor(["Пушкин"]) secondBook.setPublishing("Минск") secondBook.setPublicationYear(2222) secondBook.setNumberPage(243) secondBook.setPrice(20) secondBook.setBindingType("бумага") thirdBook = Book.Book() thirdBook.setId(2) thirdBook.setName("Галочка") thirdBook.setAuthor(["Булгаков"]) thirdBook.setPublishing("Гомель") thirdBook.setPublicationYear(20) thirdBook.setNumberPage(50) thirdBook.setPrice(10) thirdBook.setBindingType("бумага") library = Library.Library() library.addLibrary(firstBook) library.addLibrary(secondBook) library.addLibrary(thirdBook) return library
def updateStatus(self, changes=None, data=None): # 책 등록 if changes == 'register': book = Book.Book(data[0], data[1], data[2]) self.books.append(book) # 책 대출 if changes == 'borrow': if self.checkBookAvailable(data): self.decreaseNumOfBooks(data) else: print('대출 불가능한 책입니다.') return # 책 반납 if changes == 'return': self.increaseNumOfBooks(data)
def main(): Input_box_lambda print("lamGen= %d" % globcfg.lamGen) print("lamRW= %d" % globcfg.lamRW) Button print("Priority: %s" % globcfg.priority) book = Book.Book() g = Gui() generator = SystemControl.Generator(book, g) scheduler = SystemControl.Scheduler() generator.start() scheduler.start() # start Gui g.animation(50, 50, 5)
def get_book(ISBN): with sqlite3.connect("library.db") as conn: cursor = conn.cursor() cursor.execute( "SELECT title, author, pubDate, username FROM book where ISBN=?", (ISBN, )) tup = cursor.fetchone() if tup is None: return None title = tup[0] author = tup[1] pubDate = tup[2] username = tup[3] book = b.Book(ISBN, title, author, pubDate, username) return book
def createBook(self, id): print("Опишите книгу") name = str(input("Введите имя\n")) author = self.inputAuthor() publishing = str(input("Введите издателя\n")) publicationYear = self.inputYear() numberPage = self.inputPage() price = self.inputPrice() bindingType = str(input("Введите тип обложки\n")) newBook = Book.Book() newBook.setId(id) newBook.setName(name) newBook.setAuthor(author) newBook.setBindingType(bindingType) newBook.setNumberPage(numberPage) newBook.setPublishing(publishing) newBook.setPublicationYear(publicationYear) newBook.setPrice(price) return newBook
def loadCatalog(self, fileName: str): #Graphs self.indexKeys = ChainedHashTable.ChainedHashTable() self.bookCatalog = DLList.DLList() #or arraylist with open(fileName, encoding='utf-8') as f: start_time = time.time() count = 0 #line number for line in f: (key, title, group, rank, similar) = line.split("^") b = Book.Book(key, title, group, rank, similar) self.bookCatalog.append(b) self.indexKeys.add(b.key, count) #self.indexKeys.add(key, line) count += 1 elapsed_time = time.time() - start_time print( f"Loaded {self.bookCatalog.size()} books into bookCatalog in {elapsed_time} seconds" ) #self.similar_graph() #def similar_graph(self,k : int): self.similarGraph = AdjacencyList.AdjacencyList( self.bookCatalog.size()) with open(fileName, encoding='utf-8') as f: start_time = time.time() count = 0 for line in f: (key, title, group, rank, similar) = line.split("^") l = similar.split() for k in range(1, len(l)): j = self.indexKeys.find(l[k]) #print(j) if j != None: #is not self.similarGraph.add_edge(count, j) count += 1 elapsed_time = time.time() - start_time print( f"Loaded {self.similarGraph.n} books into Graph in {elapsed_time} seconds" )
def createBook(): createBookForm = CreateBookForm(request.form) if request.method == 'POST' and createBookForm.validate(): # Image # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also # submit an empty part without filename if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) # added uuid to make the filename unique. Otherwise, file with same names will override. # file.save(os.path.join(app.config['UPLOAD_FOLDER'], str(uuid.uuid4()) + filename)) filedir = str(uuid.uuid4()) + filename file.save(os.path.join(app.config['UPLOAD_FOLDER'], filedir)) bookDict = {} productdb = shelve.open('productstorage.db', 'c') try: bookDict = productdb['Books'] currentID = productdb['currentID'] except: print("Error in retrieving Books from storage.db.") currentID = 0 book = Book.Book(createBookForm.bookName.data, createBookForm.author.data, createBookForm.price.data, createBookForm.genre.data, createBookForm.stock.data, createBookForm.summary.data, filedir, currentID) bookDict[book.get_bookID()] = book currentID = book.get_bookID() productdb['Books'] = bookDict productdb['currentID'] = currentID return redirect(url_for('retrieveBooks')) return render_template('createBook.html', form=createBookForm)
def loadCatalog(self, fileName: str): ''' loadCatalog: Read the file filenName and creates the array list with all books. book records are separated by ^. The order is key, title, group, rank (number of copies sold) and similar books ''' self.bookCatalog = DLList.DLList() with open(fileName) as f: # The following line is the time that the computation starts start_time = time.time() for line in f: (key, title, group, rank, similar) = line.split("^") s = Book.Book(key, title, group, rank, similar) self.bookCatalog.append(s) # The following line is used to calculate the total time # of execution elapsed_time = time.time() - start_time print( f"Loading {self.bookCatalog.size()} books in {elapsed_time} seconds" )
def game_logic(event): global player global game global book if game.time <= 0: set_result("books", get_result("books") + game.books) set_result("kills", get_result("kills") + game.kills) best = get_result("best_score") if best < game.points: set_result("best_score", game.points) save_results() end_game() return 1 if not game.is_on: load_level() game.is_on = True else: if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: game.is_game = False return 6 player.move(event, elements, elfs) action = player.action(event) if action == 9: if book.check(player.pos_x, player.pos_y): book.generated = False game.books = game.books + 1 game.points = game.points + 15 book = Book(elements) game.reflesh_text() return 2
def show_books(): with sqlite3.connect("library.db") as conn: cursor = conn.cursor() cursor.execute( "SELECT ISBN, title, author, pubDate, username FROM book where username is null" ) tups = cursor.fetchall() if tups is None: return None bookList = list() for i in range(len(tups)): ISBN = tups[i][0] title = tups[i][1] author = tups[i][2] pubDate = tups[i][3] username = tups[i][4] book = b.Book(ISBN, title, author, pubDate, username) bookList.append(book) return bookList
def main(): file = open("BooksDatabase.txt", "r") data = file.readlines() update = 1 for isbn in data: isbn.strip() mydb = mysql.connector.connect(user='******', password='******', host='127.0.0.1', database='project') mycursor = mydb.cursor() sql = "SELECT * FROM book WHERE isbn13 = %(value)s" params = {'value': isbn} try: mycursor.execute(sql, params) except Exception as e: print(e) if (mycursor.rowcount == 1): for row in mycursor: lastVisited = row['lastVisited'] refreshPeriod = row['refreshPeriod'] if (time.time() - lastVisited < refreshPeriod): update = 0 if (update == 1): goodreads_data = Goodreads.get_goodreads(isbn[:-1]) if goodreads_data == []: continue amazon_data = Amazon.get_amazon(isbn[:-1]) flipkart_data = Flipkart.get_flipkart(isbn[:-1]) infibeam_data = Infibeam.get_infibeam(isbn[:-1]) snapdeal_data = Snapdeal.get_snapdeal(isbn[:-1]) Book.Book( goodreads_data['isbn'], isbn, goodreads_data['title'], goodreads_data['image'], goodreads_data['authorID'], goodreads_data['rating'], goodreads_data['genre1'], goodreads_data['genre2'], goodreads_data['genre3'], amazon_data['amazon_url'], amazon_data['amazon_price'], flipkart_data['flipkart_url'], flipkart_data['flipkart_price'], infibeam_data['infibeam_url'], infibeam_data['infibeam_price'], snapdeal_data['snapdeal_url'], snapdeal_data['snapdeal_price'])
def captureData(itemType, objectData): """Capture data from specific user input fields. Args: itemType (class type): type of the item. objectData (): user input handler. Returns: tuple: a paired output contains (searchKeyword, isName) """ # check JSON file existence: data = checkFileExistence() # set used variables: if itemType == type(Member()): itemType = "members" fields = ["id", "name"] fieldPlace = [0, 1] elif itemType == type(Borrower()): itemType = "borrowers" fields = ["id", "name"] fieldPlace = [0, 1] elif itemType == type(Book()): itemType = "books" fields = ["isbn", "name"] fieldPlace = [1, 0] # check item's existence then capture its data: for item in data[itemType]: if objectData[fieldPlace[0]].get() == item[fields[0]]: searchKeyword = objectData[fieldPlace[0]].get() isName = False break elif objectData[fieldPlace[1]].get() == item[fields[1]]: searchKeyword = objectData[fieldPlace[1]].get() isName = True break return searchKeyword, isName
def readDatabase(Inventory): #def readDatabase() Reads in the database text file to populate the dictionary #input: The dictionary named Inventory #output: The inventory dictionary with all the books in it #variable for the name of the database file database = raw_input("Enter the name of your database file: ") valid = False while(valid == False): valid = True try: #trying to open the database openDatabase = open(database, "r") except IOError: #if it cant then ask the user again valid = False database = raw_input("Cannot find file please try again: ") for line in openDatabase: #getting every line in the data base and pulling all the essential #information out of it line = line.strip().split("$") #getting the authors name author = line[LAST_NAME]+", "+line[FIRST_NAME] #creating the book object book = Book(line[TITLE], line[QUANTITY], line[PRICE]) #putting it into a list to put into the dictionary bookList = [book] if author not in Inventory.keys(): #if the author isnt in the dictionary make a new key and #and insert the book into that key Inventory[author] = bookList else: #if the author is in the dictionary then put the book under #that author Inventory[author] = Inventory.get(author)+bookList #close the database openDatabase.close() return Inventory
def parseBook(self, child): """Parses the xml data received from the API returns a Book object""" book = Book.Book() book.setGoodreadsID(child[0].text) book.setTitle(child[1].text) for author in child.find("authors").findall("author"): book.setAuthor(author[1].text) book.setIsbn(child[2].text) book.setIsbn13(child[3].text) book.setImageURL(child[5].text) book.setSmallImageURL(child[6].text) book.setPublicationYear(child[7].text) book.setPublicationMonth(child[8].text) book.setPublicationDay(child[9].text) book.setPublisher(child[10].text) book.setLanguageCode(child[11].text) book.setIsEbook(child[12].text) book.setDescription(child[13].text) book.setRating(child[15].text) book.setNbPages(child[16].text) for bl in child.find("book_links").findall("book_link"): book.setLink(bl[1].text, bl[2].text) return book
def parseBook(self, parsedData): books = [] items = parsedData['items'] # If the search is by ISBN this list will always contain 1 book. If the search is by title # there might be multiple books in the result for item in items: book = Book.Book() book.setGoogleBooksID(item['id']) book.setIsEbook(item['saleInfo']['isEbook']) volumeInfo = item['volumeInfo'] book.setTitle(volumeInfo['title']) for author in volumeInfo['authors']: book.setAuthor(author) if ('categories' in volumeInfo): for category in volumeInfo['categories']: book.setGenre(category) if ('averageRating' in volumeInfo): book.setRating(volumeInfo['averageRating']) # For some old books there isn't ISBN10 and ISBN13. For those books the default value # of None is left if ('industryIdentifiers' in volumeInfo and len(volumeInfo['industryIdentifiers']) == 2): book.setIsbn( self.getShorterISBN(volumeInfo['industryIdentifiers'])) book.setIsbn13( self.getLongerISBN(volumeInfo['industryIdentifiers'])) if ('publishedDate' in volumeInfo): book.setPublicationDate(volumeInfo['publishedDate']) # Some old books might not have a 'publisher' key if ('publisher' in volumeInfo): book.setPublisher(volumeInfo['publisher']) # volumeInfo['description'] have a type 'unicode' and it must be parsed to ascii to prevent # UnicodeEncodeError when printing the content of the Book object. # For some books there is no description if ('description' in volumeInfo): u = volumeInfo['description'] description = u.encode('ascii', 'ignore') book.setDescription(description) #if ('imageLinks' in volumeInfo): #book.setImageURL(volumeInfo['imageLinks']['thumbnail']) #book.setSmallImageURL(volumeInfo['imageLinks']['smallThumbnail']) if ('language' in volumeInfo): book.setLanguageCode(volumeInfo['language']) if ('pageCount' in volumeInfo): book.setNbPages(volumeInfo['pageCount']) books.append(book) return books
def load_level(): global book global player global timer global elements global elfs values = {} file_name = "./Assets/Levels/level1.dat" if not os.path.isfile(file_name): return False else: file = open(file_name, "r") for line in file.readlines(): v_n = "" v = "" s = 0 for c in line: if c == '=': s = 1 continue elif c == ' ': continue if s == 0: v_n = v_n + c elif s == 1: v = v + c values[v_n] = v.replace('\n', '') file.close() if not os.path.isfile(values["board"]): return False else: player = Player(int(values["start_x"]), int(values["start_y"])) elements = [] elfs = [] file = open(values["board"], "r") i = 0 for value in file.readlines(): nu = "" co = "" ro = "" s = 0 for c in value: if c == '-': s = s + 1 continue if s == 0: nu = nu + c elif s == 1: co = co + c elif s == 2: ro = ro + c sprite = titles[int(nu)] sprite = pygame.transform.rotate(sprite, 90 * int(ro)) elements.append( Element(i % int(values["size_x"]), int(i / int(values["size_x"])), sprite, int(co))) i = i + 1 file.close() book = Book(elements) for i in range(3): elfs.append(Elf(elements, player)) timer = threading.Thread(target=timer_loop) timer.start()
def addBook(Inventory): #addBook() Allows the user to add a book into the Inventory dictionary #inputs: The inventory dictionary #outputs: the inventory dictionary with a new book in it ############################################################################ #This block of code is getting the authors last and first name and #concatonating them together to form the key used in the dictionary #this is also getting a book title from the user and capitalizing all the #first letters in all the words lastName = raw_input("Enter the author's last name: ") lastName = lastName.strip().lower().capitalize() firstName = raw_input("Enter the author's first name: ") firstName = firstName.strip().lower().capitalize() fullName = lastName+", "+firstName bookTitle = raw_input("Enter the title: ") bookTitle = bookTitle.lower() bookTitle = ' '.join(word[LAST_NAME].upper()+word[FIRST_NAME:] for \ word in bookTitle.split()) ############################################################################## flag = True #checking if the name is in the dictionary if fullName in Inventory.keys(): #looking for books under that name for book in Inventory[fullName]: #check if that book is already in the database if book.getTitle() == bookTitle: flag = False print "That book already exists in the database." #if it isnt in then ask for how many of the book there are if flag == True: quantity = 0 valid = False while(valid == False): try: quantity = input("Enter the quantity: ") except: valid = False print "Invalid input for quantity please try again" valid = True valid = False while(valid == False): #then ask for the price of the book and validate it firstcheck = False while (firstcheck == False): try: firstcheck = True price = input("Enter the price: $") except: firstcheck = False print "Invalid input" if isinstance(price, float) == True or isinstance(price, int)\ == True: valid = True else: print "Invalid input for price please try again." #create the instance of the book with given information newBook = [Book(bookTitle, quantity, price)] #add it to the dictionary if fullName in Inventory.keys(): Inventory[fullName] = Inventory[fullName]+newBook elif fullName not in Inventory.keys(): Inventory[fullName] = newBook
from __future__ import annotations from Library import * from Member import * from Book import * if __name__ == '__main__': Central_Library = Library("Central Library", "123 Fake Address") The_Hunger_Games = Book("The Hunger Games", "Suzanne Collins", [2008, 9, 14]) The_Lightning_Thief = Book("The Lightning Thief", "Rick Riordan", [2005, 6, 28]) print(The_Hunger_Games) print(The_Lightning_Thief) Central_Library.add_book(The_Hunger_Games) Central_Library.add_book(The_Lightning_Thief) name = input("Enter your full name: ") dob_year = input("Enter the year you were born: ") dob_month = input("Enter the month you were born: ") dob_day = input("Enter the day you were born: ") user_name = input("Enter a username: "******"Enter a password: ") test_member = Member(name, [dob_year, dob_month, dob_day], user_name, password)
def test_reminder(self): book.reminder() try: realNames = book.labelBirthday.cget("text").replace( "Today is a birthday of ", "") listNames = realNames.split("', '") contactFile = open(".contacts.csv", "a+") contacts = contactFile.read() contactsSplit = contacts.split(';') except: return i = 0 now = datetime.datetime.now() birthday = "" today = str(now.day) + "." + str(now.month) try: while i < len(contactsSplit) - 1: if contactsSplit[i].replace("\n", "") == listNames[0]: birthday = contactsSplit[i + 2] i = i + 3 except: pass self.assertEqual(birthday, today) book = Book() if __name__ == '__main__': unittest.main()
csvCustomer = Person.customer( count, f'{row["Gender"]}', f'{row["NameSet"]}', f'{row["GivenName"]}', f'{row["Surname"]}', f'{row["StreetAddress"]}', f'{row["ZipCode"]}', f'{row["City"]}', f'{row["EmailAddress"]}', f'{row["Username"]}', f'{row["TelephoneNumber"]}', f'{row["Status"]}') customers.append(csvCustomer) count += 1 if bookssetFileStatus == True: with open('data/booksset.json') as json_file: data = json.load(json_file) for p in data: newbook = Book.Book(p['author'], p['country'], p['imageLink'], p['language'], p['link'], p['pages'], p['title'], p['year']) books.append(newbook) if bookitemFileStatus == True: with open('data/bookitems.json') as getBookItems: check = os.stat('data/bookitems.json').st_size == 0 if check == False: bookData = json.load(getBookItems) for bd in bookData: booktitlename = bookData[bd]["title"] for booklist in books: if booklist.getTitle() == booktitlename:
def decode_qtg_EOBI(fi, levels, day): books = {} # contains books symbols = {} # contains symbols' names _C = 0 print(_C, datetime.now()) _t = datetime.now() for line in fi: # read file line by line _C += 1 if _C % 100000 == 0: print(_C, datetime.now() - _t) _t = datetime.now() l = line.split(':') # get fields from line msg = l[0] # Try to catch bad lines if (len(l) > 1): # just to catch bad lines uid = int(l[1]) else: pass if msg == 'SUBSCRIBE': sname = l[2].rstrip() if sname != 'N/A': symbols[uid] = l[2].rstrip() books[uid] = Book.Book(uid, day, levels) elif uid in books: if msg in [ 'UNSUBSCRIBE', 'END_OPERATION', 'END_PACKET', 'ORDERBOOK_STATE', 'REALTIME' ]: pass else: # dated messages now with recv and exch in common exch = int(l[2]) recv = int(l[3]) if msg == 'CLEAR': books[uid].clear(recv, exch) elif msg == "EXEC_SUMMARY": qty = int(l[7]) price = Decimal(l[8]) books[uid].exec_summary(price, qty, recv, exch) elif msg == 'ADD_ORDER': side = int(l[4].split('/')[0]) - 1 oid = l[4] price = Decimal(l[6]) qty = int(l[7]) if not books[uid].add_order(side, price, oid, qty, recv, exch): logging.error( "Error with ADD_ORDER at line {0} in {1}".format( _C, fi.name)) elif msg == 'REDUCE_ORDER': side = int(l[4].split('/')[0]) - 1 oid = l[4] delta_qty = int(l[5]) price = Decimal(l[6]) order = books[uid].find_order(oid) if order is None: logging.error( "ERROR at line {0}, order does not exist in {1}". format(_C, fi.name)) #logging.error("{} {}".format(l[4],l[5])) #logging.error("{} {}".format(oldoid,newoid)) #logging.error(line) else: oldqty = order.qty if not books[uid].modify_inplace( side, oid, oldqty - delta_qty, recv, exch): logging.error( "Error with REDUCE_ORDER at line {0} in {1}". format(_C, fi.name)) #logging.error(line) elif msg == 'REPLACE_ORDER': side = int(l[4].split('/')[0]) - 1 oldoid = l[4] newoid = l[5] newprice = Decimal(l[6]) newqty = int(l[7]) if not books[uid].replace_order(side, newprice, newoid, newqty, recv, exch, oldoid): logging.error( "Error with REPLACE_ORDER at line {0} in {1}". format(_C, fi.name)) #logging.error("{} {}".format(l[4],l[5])) #logging.error("{} {}".format(oldoid,newoid)) #logging.error(line) elif msg == 'DEL_ORDER': side = int(l[4].split('/')[0]) - 1 oid = l[4] if not books[uid].delete_order(side, -1, oid, recv, exch): logging.error( "Error with DEL_ORDER at line {0} in {1}".format( _C, fi.name)) #logging.error(line) elif msg == 'EXECUTION': price = Decimal(l[6]) qty = int(l[7]) books[uid].report_trade(price, qty, recv, exch) else: pass return books, symbols
def decode_qtg_KOSPI(fi,levels,day): books = {} # contains books symbols = {} # contains symbols' names _C = 0 print(_C,datetime.now()) _t = datetime.now() for line in fi: # read file line by line _C += 1 # Timers for each 100 000 lines if _C%100000==0: print(_C,datetime.now()-_t) _t = datetime.now() l = line.split(':') # get fields from line msg = l[0] # type of message # Try to catch bad lines if(len(l)>1): # just to catch bad lines uid = int(l[1]) # get UID else: continue if msg=='SUBSCRIBE': # same as qtg EOBI sname=l[2].rstrip() if sname != 'N/A': symbols[uid] = l[2].rstrip() books[uid] = Book.Book(uid,day,levels,"level_2") elif uid in books: if msg in ['UNSUBSCRIBE']: pass else: # dated messages now with recv and exch in common if msg=='QUOTE': bid = [ Decimal(l[i*6+4]) for i in range(0,5) ] bidv = [ int(l[i*6+5]) for i in range(0,5) ] nbid = [ int(l[i*6+6]) for i in range(0,5) ] ask = [ Decimal(l[i*6+7]) for i in range(0,5) ] askv = [ int(l[i*6+8]) for i in range(0,5) ] nask = [ int(l[i*6+9]) for i in range(0,5) ] exch = int(l[2]) recv = int(l[3]) if not books[uid].replace_book(bid,ask,bidv,askv,nbid,nask,recv,exch): logging.error("Error with QUOTE at line {0} in {1}".format(_C,fi.name)) elif msg=='TRADE': exch = int(l[2]) recv = int(l[3]) qty = int(l[4]) price= Decimal(l[5]) bid = [ Decimal(l[i*6+6]) for i in range(0,5) ] bidv = [ int(l[i*6+7]) for i in range(0,5) ] nbid = [ int(l[i*6+8]) for i in range(0,5) ] ask = [ Decimal(l[i*6+9]) for i in range(0,5) ] askv = [ int(l[i*6+10]) for i in range(0,5) ] nask = [ int(l[i*6+11]) for i in range(0,5) ] if not books[uid].report_trade(price,qty,recv,exch,-1): logging.error("Error with TRADE at line {0} in {1}".format(_C,fi.name)) if not books[uid].replace_book(bid,ask,bidv,askv,nbid,nask,recv,exch): logging.error("Error with TRADE at line {0} in {1}".format(_C,fi.name)) elif msg=='PARTIAL_TRADE': exch = int(l[2]) recv = int(l[3]) qty = int(l[4]) price=Decimal(l[5]) if not books[uid].report_trade(price,qty,recv,exch,-1): logging.error("Error with PARTIAL_TRADE at line {0} in {1}".format(_C,fi.name)) else: pass return books,symbols
#!/bin/usr/python # # This code has the goal to scrap # the dictionary website DUDEN for # learning purposes using BeautifulSoup # module. # ########################################################### from Dictionary import * from Book import * my_word = 15 book = Book('book.txt') simplelist = [Dictionary(word) for word in book.highlighted_words] print(simplelist[my_word].url_word) simplelist[my_word].getMeaningDuden() simplelist[my_word].printMeaning() #for word_dict in simplelist: # word_dict.getMeaningDuden() # word_dict.saveWord() one_word = Dictionary('zart') one_word.getMeaningDict() #one_word.saveWord() one_word.printMeaning()
def decode_qtg_MDP3(fi, levels, day): books = {} # contains books symbols = {} # contains symbols' names _C = 0 print(_C, datetime.now()) _t = datetime.now() for line in fi: # read file line by line _C += 1 # Timers for each 100 000 lines if _C % 100000 == 0: print(_C, datetime.now() - _t) _t = datetime.now() l = line.split(':') # get fields from line msg = l[0] # type of message # Try to catch bad lines if (len(l) > 1): # just to catch bad lines uid = int(l[1]) # get UID else: continue if msg == 'SUBSCRIBE': # same as qtg EOBI sname = l[2].rstrip() if sname != 'N/A': symbols[uid] = l[2].rstrip() channel_id = int(l[3]) books[uid] = Book.Book(uid, day, levels, "level_2", channel_id) elif msg == 'PACKET_END': channel_id = int(l[1]) exch = int(l[2]) recv = int(l[3]) for uid in books: if books[uid].valid and books[uid].channel_id == channel_id: books[uid].store_update("Q", recv, exch) elif uid in books: if not books[uid].valid: pass elif msg in ['UNSUBSCRIBE', 'FINAL']: pass else: # dated messages now with recv and exch in common if msg == 'RESET': books[uid].clear(0, 0) elif msg == 'ADD': level = int(l[2]) side = int(l[3]) qty = int(l[4]) price = Decimal(l[5]) ord_cnt = int(l[6]) if not books[uid].add_level(level, side, qty, price, ord_cnt): logging.error( "Error with ADD_LEVEL at line {0} in {1}".format( _C, fi.name)) elif msg == 'DELETE': level = int(l[2]) side = int(l[3]) if not books[uid].delete_level(level, side): logging.error( "Error with DELETE_LEVEL at line {0} in {1}". format(_C, fi.name)) elif msg == 'AMEND': level = int(l[2]) side = int(l[3]) qty = int(l[4]) price = Decimal(l[5]) ord_cnt = int(l[6]) if not books[uid].amend_level(level, side, qty, price, ord_cnt): logging.error( "Error with AMEND_LEVEL at line {0} in {1}".format( _C, fi.name)) elif msg == 'TRADE_SUMMARY': price = Decimal(l[2]) side = int(l[3]) qty = int(l[4]) ord_cnt = int(l[5]) if not books[uid].report_trade(price, qty, recv, exch, side): logging.error( "Error with TRADE_WITH_SIDE at line {0} in {1}". format(_C, fi.name)) elif msg == 'SNAP_FINAL': exch = int(l[2]) recv = int(l[3]) books[uid].store_update("Q", recv, exch) else: pass return books, symbols
from Book import * from Comics import * from Magazine import * from Journal import * from Newspaper import * from BookstoreManager import BookstoreManager if __name__ == '__main__': manager = BookstoreManager(BookstoreItem.storage) book1 = Book("Tropic of Cancer", "Henry Miller", "Autobiographical novel", 1934, 318) book2 = Book("1984", "George Orwell", "Novel", 1949, 328) book3 = Book("Junkie", "William S. Burroughs", "Autobiographical novel", 1953, 166) # book4 = Book("Edinburgh", "Alexander Chee", "Autobiographical novel", 2001, 209) book5 = Book("Giovanni's Room", "James Baldwin", "Poem", 1956, 159) book6 = Book("On the Road", "Jack Kerouac", "Autobiographical novel", 1957, 320) comics1 = Comics("Deadpool", "Marvel", "Superhero", 2019, 25) newspaper1 = Newspaper("NYT", "NY", "Weekly", "04.10.2020", 20) journal1 = Journal("ATT", "AT", "Celebrity", "10.20.2021", 14) magazine1 = Magazine("Rolling Stone", "Wenner Media LLC", "Musical", "04.10.2020", 18) magazine2 = Magazine("Esquire", "Hearts Communications Inc", "Fashion", "21.11.2014", 22) magazine3 = Magazine("Vanity Fair", "Conde Nast", "Musical", "15.12.2020", 30)
import Book import Quicksort got = Book.Book('A Game of Thrones', Book.Author('George R. R.', 'Martin'), '978-0553573404', 694) hp = Book.Book('Harry Potter and the Philosophers Stone', Book.Author('Joanne K.', 'Rowling'), '978-1408855652', 331) lotr = Book.Book('Lord of the Rings: The Fellowship of the Rings', Book.Author('John Ronald Reuel', 'Tolkien'), '978-0261102354', 529) library = [got, hp, lotr] Quicksort.quicksort(library) for n in library: print(str(n) + "\n")
def displayFullList(listType, masterFrame, messageRow): """Display full list into new window. Args: listType (class type): the list's type to be displayed. masterFrame (): the frame that the message will be displayed on it. messageRow (int): the place to display the output message. Returns: int: the number of items in the displayed list. """ # check JSON file existence: data = checkFileExistence() count = 0 # used to get total number of items. # set used variables depending on list's type: if listType == type(Member()): objectType = "members" convertTo = type(Member()) elif listType == type(Borrower()): objectType = "borrowers" convertTo = type(Borrower()) elif listType == type(Book()): objectType = "books" convertTo = type(Book()) else: print("Invalid Object!\n") displayMessage(masterFrame, messageRow, ERROR_MESSAGE, "red") # create new window to display data: displayWindow = tk.Tk() window_width = displayWindow.winfo_screenwidth() window_height = displayWindow.winfo_screenheight() displayWindow.geometry("%dx%d" % (window_width / 2, window_height / 2)) titleText = objectType.capitalize() displayWindow.title("{}' Full List".format(titleText)) frameRow = 1 # used to set each frame's place. for item in data[objectType]: # create new frame: itemFrame = tk.Frame(master=displayWindow, relief=tk.RIDGE, borderwidth=5) itemFrame.grid(row=frameRow, column=0, padx=(10, 10), pady=(10, 0)) # set frame's title: tk.Label(master=itemFrame, text="{}'s Data".format(titleText[:-1]), font="Verdana 10 underline bold").grid(row=0, column=1) # display required data depending on list's type: if listType == type(Member()): tk.Label(master=itemFrame, text="ID: ").grid(row=1, column=0) tk.Label(master=itemFrame, text=item["id"]).grid(row=1, column=1) tk.Label(master=itemFrame, text="Name: ").grid(row=2, column=0) tk.Label(master=itemFrame, text=item["name"]).grid(row=2, column=1) tk.Label(master=itemFrame, text="Address: ").grid(row=3, column=0) tk.Label(master=itemFrame, text=item["address"]).grid(row=3, column=1) elif listType == type(Book()): tk.Label(master=itemFrame, text="Name: ").grid(row=1, column=0) tk.Label(master=itemFrame, text=item["name"]).grid(row=1, column=1) tk.Label(master=itemFrame, text="ISBN: ").grid(row=2, column=0) tk.Label(master=itemFrame, text=item["isbn"]).grid(row=2, column=1) tk.Label(master=itemFrame, text="Author: ").grid(row=3, column=0) tk.Label(master=itemFrame, text=item["author"]).grid(row=3, column=1) tk.Label(master=itemFrame, text="Publication Date: ").grid(row=4, column=0) tk.Label(master=itemFrame, text=item["publication_date"]).grid(row=4, column=1) tk.Label(master=itemFrame, text="Publisher: ").grid(row=5, column=0) tk.Label(master=itemFrame, text=item["publisher"]).grid(row=5, column=1) tk.Label(master=itemFrame, text="Pages Number: ").grid(row=6, column=0) tk.Label(master=itemFrame, text=item["pages_number"]).grid(row=6, column=1) tk.Label(master=itemFrame, text="Cover Type: ").grid(row=7, column=0) tk.Label(master=itemFrame, text=item["cover_type"]).grid(row=7, column=1) elif listType == type(Borrower()): tk.Label(master=itemFrame, text="ID: ").grid(row=1, column=0) tk.Label(master=itemFrame, text=item["id"]).grid(row=1, column=1) tk.Label(master=itemFrame, text="Name: ").grid(row=2, column=0) tk.Label(master=itemFrame, text=item["name"]).grid(row=2, column=1) tk.Label(master=itemFrame, text="Address: ").grid(row=3, column=0) tk.Label(master=itemFrame, text=item["address"]).grid(row=3, column=1) tk.Label(master=itemFrame, text="ISBN: ").grid(row=4, column=0) tk.Label(master=itemFrame, text=item["isbn"]).grid(row=4, column=1) tk.Label(master=itemFrame, text="Borrow Date: ").grid(row=5, column=0) tk.Label(master=itemFrame, text=item["borrow_date"]).grid(row=5, column=1) tk.Label(master=itemFrame, text="Return Date: ").grid(row=6, column=0) tk.Label(master=itemFrame, text=item["return_date"]).grid(row=6, column=1) # display item's data on console: objectReturned = convertDictIntoObject(item, convertTo) print(objectReturned) count += 1 frameRow += 1 # display total number of displayed items: tk.Label(master=displayWindow, text="Total: {}".format(count), font="Verdana 15 underline bold").grid(row=0, column=1) # display appropriate message: displayMessage(masterFrame, messageRow, DONE_MESSAGE, "green") return count
ws.title = "All Books" ws['A1'] = "Title" ws['B1'] = "Author" ws['C1'] = "Pages" ws['D1'] = "Published" ws['E1'] = "Rating" ws['F1'] = "Series" ws['G1'] = "Genre" for book in books.book_titles: #for book in test_books: get_to_page(book) temp = None print("Now getting: " + book) try: temp = Book.Book(find_title(), find_author(), find_pages(), find_series(), find_genres(), find_published(), find_rating()) except: sleep_time = 10 get_to_page(book) temp = Book.Book(find_title(), find_author(), find_pages(), find_series(), find_genres(), find_published(), find_rating()) sleep_time = 5 print(temp) book_data.append(temp) browser.close() row = 2 setup_sheet() ws = wb.active for book in book_data: ws["A{0}".format(row)] = book.title
from Library_user import * from Book import * info = ['mjohnson', 'password', 'Matt', 'Johnson', '4 Batchelder Road, Windsor CT', '6094397160'] user1 = Library_user(info) book1 = Book('On Beauty','Zadie Smith') user1.check_out(book1) print(book1.is_out) print(user1.get_book_history())
w = input( "1.Show whole details :\n2.Show detail via enroll \n3.Delete Record \n4.Update record \n5.Show fine\n6.Exit from the admin menu" ) else: print("!!!INCORRECT PASSWORD!!!") if (ch == '4'): w = input("1.Add Book\n2.Show Books\n3.Exit") while (True): if (w == '1'): r = int(input("Enter the number of books:")) for i in range(r): b = Book() b.addb() ba.append(b) with open("book.pkl", 'ab') as f: pickle.dump(ba, f) if (w == '2'): q = Function() q.Showbook("book.pkl") if (w == '3'): break w = input("1.Add Book\n2.Show Books\n3.Exit") if (ch == '5'): print( "\n\n**************THANK YOU FOR USING DIGITAL LIBRARY**************\n\n" ) sleep(1.0)