def writecomments( self ): #function to be called when user submits review or rating for a book library = Library() if str(self.book.title) in self.user.readingHistory.keys( ): #if user have read the book then he can comment/rate it comm = str(self.comments_input.toPlainText() ) #reading the comments from inputbox rates = str(self.rate_lineEdit.text() ) #reading the rate number from input box self.book.comments.append( comm) #appending the comment to book comments list self.book.rate.append( rates) #appending the rate to book rating list if self.user.commentsHistory[str( self.book.title )] > 15: #if user have read a book for 15 minutes his review has a confident weightage self.book.comment_type.append("Confident") else: #else the review have a doubdtful weightage self.book.comment_type.append("Doubdtful") library.update_book_data( self.book) #updating comments and rates in book data self.set_rate_reviews_table( ) #calling the display function to dynamically insert new reviews else: self.CantComment.setText( _fromUtf8("Read the book first, then you can add a comment"))
def convertLib(): fileName=askopenfilename(title = "Input Library",filetypes=[('Eagle V6 Library', '.lbr'), ('all files', '.*')], defaultextension='.lbr') modFileName=asksaveasfilename(title="Module Output Filename", filetypes=[('KiCad Module', '.mod'), ('all files', '.*')], defaultextension='.mod') symFileName=asksaveasfilename(title="Symbol Output Filename", filetypes=[('KiCad Symbol', '.lib'), ('all files', '.*')], defaultextension='.lib') logFile.write("*******************************************\n") logFile.write("Converting Lib: "+fileName+"\n") logFile.write("Module Output: "+modFileName+"\n") logFile.write("Symbol Output: "+symFileName+"\n") name=fileName.replace("/","\\") name=name.split("\\")[-1] name=name.split(".")[0] logFile.write("Lib name: "+name+"\n") try: node = getRootNode(fileName) node=node.find("drawing").find("library") lib=Library(node,name) modFile=open(modFileName,"a") symFile=open(symFileName,"a") lib.writeLibrary(modFile,symFile) except Exception as e: showerror("Error",str(e)+"\nSee Log.txt for more info") logFile.write("Conversion Failed\n\n") logFile.write(traceback.format_exc()) logFile.write("*******************************************\n\n\n") return logFile.write("Conversion Successfull\n") logFile.write("*******************************************\n\n\n") showinfo("Library Complete","The Modules and Symbols Have Finished Converting \n Check Console for Errors")
def test_Unitarias(): m1 = [[0, 1], [1, 0]] m2 = [[0.7, 0.7], [0.7, -0.7]] print("\n-----4.4.1-----------") print("Matriz 1 Unitaria: ", l.isUnitary(m1)) print("Matriz 2 Unitaria: ", l.isUnitary(m2)) print("Producto de Matrices Unitario: ", o.unitary_matrix(m1, m2))
def varianza(m1, vk): valor = valorEsperado(m1, vk) vNor = normalizarVector(vk) resultado = l.scalarToMatrix(valor, matrizIdentidad(len(m1), len(m1[0]))) resta = l.restMatrix(m1, resultado) restaCuadrada = l.productMatrix(resta, resta) return (valorEsperado(restaCuadrada, vNor))
def __init__(self): self.app = QtGui.QApplication(sys.argv) self.win = MyWidget() QtCore.QObject.connect(self.win.ui.btnGenerate, QtCore.SIGNAL('clicked()'), self.generate) QtCore.QObject.connect(self.win.ui.btnAddDep, QtCore.SIGNAL('clicked()'), self.addDep) QtCore.QObject.connect(self.win.ui.btnAddStreamIn, QtCore.SIGNAL('clicked()'), lambda: self.addStream(self.win.ui.tblStreamIn)) QtCore.QObject.connect(self.win.ui.btnRemoveStreamIn, QtCore.SIGNAL('clicked()'), lambda: self.remStream(self.win.ui.tblStreamIn)) QtCore.QObject.connect(self.win.ui.btnAddStreamOut, QtCore.SIGNAL('clicked()'), lambda: self.addStream(self.win.ui.tblStreamOut)) QtCore.QObject.connect(self.win.ui.btnRemoveStreamOut, QtCore.SIGNAL('clicked()'), lambda: self.remStream(self.win.ui.tblStreamOut)) QtCore.QObject.connect(self.win.ui.btnAddProp, QtCore.SIGNAL('clicked()'), self.addProp) QtCore.QObject.connect(self.win.ui.btnRemoveProp, QtCore.SIGNAL('clicked()'), self.remProp) self.app.connect(self.app, QtCore.SIGNAL("lastWindowClosed()"), self.app, QtCore.SLOT("quit()")) self.app.connect(self.win.ui.btnCancel, QtCore.SIGNAL('clicked()'), self.app, QtCore.SLOT("quit()")) self.win.ui.btnBrowseDCL.hide() self.win.ui.btnAddHandler.clicked.connect(self.addHandler) self.win.ui.tblStreamIn.itemChanged.connect(self.processStreams) self.win.ui.lstHandlers.currentItemChanged.connect(self.getCurrentHandler) self.win.ui.lstHandlers.itemChanged.connect(self.changeHandler) self.win.ui.rdAct.toggled.connect(self.changeHandlerProps) self.win.ui.rdPas.toggled.connect(self.changeHandlerProps) self.win.ui.rdTri.toggled.connect(self.changeHandlerProps) self.win.ui.lstHandDeps.itemChanged.connect(self.changeHandlerDeps) self.currentHandler = None self.processHandlers() self.libs = LibraryWidget(None) self.libs.setSelectedCb(self.addLibraryDep) libs = [] lib = Library() lib.name="OpenCV" lib.desc="Open source compute vision library" lib.pckg="OpenCV" lib.libs="${OpenCV_LIBS}" lib.incl="opencv2/opencv.hpp" libs.append(lib) lib = Library() lib.name="Pointcloud" libs.append(lib) self.libs.setLibraries(libs) self.loadDCL() self.handlers=[] self.deps=[] #self.showMessage("Error!", "E") self.showMessage("", "")
def toLibrary(self, checked): config.progress.rooms_visited += 1 if self.ly is None: self.ly = Library() self.ly.show() else: self.ly.close() self.ly = None
def test_name(): marconi = Library("IIS Marconi Library", "CIVMA") assert (marconi.name == "IIS Marconi Library") assert(marconi.sbn_code != "") assert len(marconi.catalog) == 0 harry_potter = Book("Harry Potter e la Pietra Filosofale", "J.K Rownling", "Salani Editore", 1997, 294, 990239089128 ) marconi.add_book(harry_potter)
def setup(self, args): try: dirFile = open('mlm.config', 'r') dir = dirFile.readline() self.myLibrary = Library(dir) except: directoryInput = input( 'Please enter the absolute pathway to your music library: ') self.myLibrary = Library(directoryInput)
def test_etagere_addBook(self): etagere = Library() etagere.biblio = {} livre = Book("John", "Grisham", "The Racketeer", "International Bestseller", 2013, "Novel", 382, "Chambre de Cyril", 4, "Et voici un autre commentaire blablab abbla.", "The Racketeer.jpg") etagere.addBook(livre) self.assertEqual(len(etagere.dLibrary), 1)
def build_old_library(old_file): library = Library() with open(old_file, newline='') as csvfile: filereader = csv.DictReader(csvfile) for row in filereader: title = row['Title'] catalog_number = row['Catalog #'] author = row['Author'] entry = Zine(title, catalog_number, author, "") library.add_entry(entry) return library
def complaint(self): """ This function will call when user submit the complaint, it will write complaint reason to book object and save to book database. :return: """ complaint_reason = str(self.complaint_input.text()) self.book.complaint.append(complaint_reason) library = Library() library.update_book_data(self.book) self.complaint_button.setDisabled(True)
def do_activate(self): library = Library() library.add_accelerator_callback(self.accelerator_activated) snippetsdir = os.path.join(GLib.get_user_config_dir(), '/pluma/snippets') library.set_dirs(snippetsdir, self.system_dirs()) self._helper = WindowHelper(self) window = self.object self._helper.run(window)
def dynamic(uns, init): """ Recibo Vector de Matrices complejas vector estado inicial Pasos hasta donde llega el sistema """ ur = [] for n in range(len(uns)): if n == 0: ur = uns[0] else: ur = l.productMatrix(uns[n], ur) return l.matrixOnVector(ur, init)
def build_new_library(new_file): library = Library() with open(new_file, newline='') as csvfile: filereader = csv.DictReader(csvfile) for row in filereader: title = row['Title'] catalog_number = "" author = row['Creator(s)'] keywords = row['Keywords'] entry = Zine(title, catalog_number, author, keywords) library.add_entry(entry) return library
def test_all(): marconi = Library("IIS Marconi", "CIVMA") harry_potter = Book("Harry Potter", "JKR", "Salani", 1997, 300, 1234) assert marconi.name == "IIS Marconi" assert marconi.sbn_code == "CIVMA" assert marconi.last_update != "" assert len(marconi.catalogue) == 0 marconi.add_book(harry_potter) assert len(marconi.catalogue) == 1
def test_all(): marconi = Library("BIBLIOTECA IIS Marconi", "CIVMA") harry_potter = Book("Harry Potter e la pietra filosofale", "J. K. Rowling", "Salani Editore", 1997, 294, 8877827025) assert marconi.name == "BIBLIOTECA IIS Marconi" assert marconi.sbn_code == "8877827025" assert marconi.last_update == "" assert len(marconi.catalogue) == "0" marconi.add_book(harry_potter) assert len(marconi.catalogue) == "1"
def __init__(self): gedit.Plugin.__init__(self) self.dlg = None library = Library() library.set_accelerator_callback(self.accelerator_activated) if platform.platform() == 'Windows': userdir = os.path.expanduser('~/gedit/snippets') else: userdir = os.path.expanduser('~/.gnome2/gedit/snippets') library.set_dirs(userdir, self.system_dirs())
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)
def __init__(self): self.app = QtGui.QApplication(sys.argv) self.win = MyWidget() QtCore.QObject.connect(self.win.ui.btnGenerate, QtCore.SIGNAL('clicked()'), self.generate) QtCore.QObject.connect(self.win.ui.btnAddDep, QtCore.SIGNAL('clicked()'), self.addDep) QtCore.QObject.connect(self.win.ui.btnAddStreamIn, QtCore.SIGNAL('clicked()'), lambda: self.addStream(self.win.ui.tblStreamIn)) QtCore.QObject.connect(self.win.ui.btnRemoveStreamIn, QtCore.SIGNAL('clicked()'), lambda: self.remStream(self.win.ui.tblStreamIn)) QtCore.QObject.connect(self.win.ui.btnAddStreamOut, QtCore.SIGNAL('clicked()'), lambda: self.addStream(self.win.ui.tblStreamOut)) QtCore.QObject.connect(self.win.ui.btnRemoveStreamOut, QtCore.SIGNAL('clicked()'), lambda: self.remStream(self.win.ui.tblStreamOut)) QtCore.QObject.connect(self.win.ui.btnAddProp, QtCore.SIGNAL('clicked()'), self.addProp) QtCore.QObject.connect(self.win.ui.btnRemoveProp, QtCore.SIGNAL('clicked()'), self.remProp) self.app.connect(self.app, QtCore.SIGNAL("lastWindowClosed()"), self.app, QtCore.SLOT("quit()")) self.app.connect(self.win.ui.btnCancel, QtCore.SIGNAL('clicked()'), self.app, QtCore.SLOT("quit()")) self.win.ui.btnBrowseDCL.hide() self.win.ui.btnAddHandler.clicked.connect(self.addHandler) self.win.ui.tblStreamIn.itemChanged.connect(self.processStreams) self.win.ui.lstHandlers.currentItemChanged.connect(self.getCurrentHandler) self.win.ui.lstHandlers.itemChanged.connect(self.changeHandler) self.win.ui.rdAct.toggled.connect(self.changeHandlerProps) self.win.ui.rdPas.toggled.connect(self.changeHandlerProps) self.win.ui.rdTri.toggled.connect(self.changeHandlerProps) self.win.ui.lstHandDeps.itemChanged.connect(self.changeHandlerProps) self.currentHandler = None self.processHandlers() self.libs = LibraryWidget(None) self.libs.setSelectedCb(self.addLibraryDep) libs = [] lib = Library() lib.name="OpenCV" lib.desc="Open source compute vision library" lib.pckg="OpenCV" lib.libs="${OpenCV_LIBS}" lib.incl="opencv2/opencv.hpp" libs.append(lib) lib = Library() lib.name="Pointcloud" libs.append(lib) self.libs.setLibraries(libs) self.loadDCL() self.handlers=[] self.deps=[] #self.showMessage("Error!", "E") self.showMessage("", "")
def probabilidadTransitoSistema(observable, vectorB): valoresP, vectoresP = np.linalg.eigh(observable) vectoresTP = l.transposedMatrix(vectoresP) print("Valores Propios:", valoresP) print("Vectores Propios: ", vectoresTP) amplitudesT = [0 for j in range(len(vectoresTP))] for i in range(len(vectoresTP)): normvB = normalizarVector(vectorB) normVTP = normalizarVector(vectoresTP[1]) amplitudesT[i] = l.internalProduct(normvB, normVTP) print("Vector propio a transitar:", vectoresTP[1]) probabilidades = [0 for j in range(len(amplitudesT))] for i in range(len(amplitudesT)): probabilidades[i] = l.norm(amplitudesT[i])**2 return probabilidades
class ShapeLibraryWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): #creating the window super(ShapeLibraryWindow, self).__init__(parent) self.library = Library(DIRECTORY) self.setWindowFlags(QtCore.Qt.Tool) self.ui = shape_ui.Ui_form_main() self.ui.setupUi(self, self.library) self.display_type = "All" #connecting the buttons self.ui.btn_open.clicked.connect(self.load_shape) self.ui.btn_save.clicked.connect(self.open_save_dialog) #connecting the combo box self.ui.vombo_box_shape_type.currentIndexChanged.connect( self.set_display_type) def set_display_type(self): """ Gets the value of the 'type' combo box and stores it in the attribute 'self.display_type' """ display_type = self.ui.vombo_box_shape_type.currentText() self.display_type = display_type self.ui.populate_list(self.library) def load_shape(self): """ Loads the selected shape in the scene """ selected_shape = self.ui.list_view_shapes.currentItem() if selected_shape: name = selected_shape.text() self.library.load(name) def open_save_dialog(self): """ Opens a new dialog window to save new shapes """ my_dial = ShapeLibraryDialog(parent=self) my_dial.show() def update_shapes(self): """ Refreshes the list of shapes in the main window """ self.ui.populate_list(self.library)
def Manage(filename): #construction code content = Parsec(filename) daysToLive = content[0] booksDictionary = content[1] Library.bookValues = booksDictionary libraries = {} for i in range(len(content[2])): libraries[i] = Library(content[2][i][0], content[2][i][1], content[2][i][2]) #iterating code day = 0 libNum = 0 libValues = [] while day < daysToLive and libNum < len(libraries): maxLib = (0, 0) for i in libraries.keys(): libScore = libraries[i].libraryScore(daysToLive - day + 1) if libScore > maxLib[1]: maxLib = (i, libScore) sentBooks = libraries[maxLib[0]].getBooks() day += libraries[maxLib[0]].getSignupTime() del libraries[maxLib[0]] libNum += 1 for i in range(len(sentBooks[0])): Library.bookValues[sentBooks[0][i]] = 0 libValues.append(([maxLib[0], len(sentBooks[0])], sentBooks[0])) WriteResult(filename, libNum, libValues) print(filename)
def main(self, libraryOption="~/Music/iTunes/iTunes Music Library.xml", playlist='', shuffleFlag=False, repeatFlag=False, skipArtistsOption='', uniqueFlag=False): libpath = expanduser(libraryOption) libpath = expandvars(libpath) self._lib = Library(libpath) self._skip_weights = {} if skipArtistsOption: t = [x.strip() for x in skipArtistsOption.split(',')] for skippattern in t: if ':' in skippattern: newskippattern,skipweight = skippattern.rsplit(':') self._skip_weights[newskippattern] = int(skipweight) else: # default to skipping 10 times out of 10, i.e. always self._skip_weights[skippattern] = 10 #print self._skip_weights if playlist == '': self.print_playlists() return 0 else: return self.play_playlist(playlist, shuffleFlag, repeatFlag, uniqueFlag)
def parse(self, id): regs = { 'name': r'<h1 class="entity-heading_title">(.*?)</h1>', 'type': r'<div class="attributes_block"><div class="attributes_label"><span class="text text__underline">Тип места</span>: </div><div class="attributes_value">(.*?)</div></div>', 'region': r'<div class="attributes_block"><div class="attributes_label"><span class="text text__underline">Регион</span>: </div><div class="attributes_value">(.*?)</div></div>', 'location': r'<div class="attributes_block"><div class="attributes_label"><span class="text text__underline">Местоположение</span>: </div><div class="attributes_value">(.*?)</div></div>', 'adress': r'<div class="attributes_block"><div class="attributes_label"><span class="text text__underline">Адрес</span>: </div><div class="attributes_value">(.*?)</div></div>', 'latitude': r'<div class="attributes_block"><div class="attributes_label"><span class="text text__underline">Широта</span>: </div><div class="attributes_value">(.*?)</div></div>', 'longitude': r'<div class="attributes_block"><div class="attributes_label"><span class="text text__underline">Долгота</span>: </div><div class="attributes_value">(.*?)</div></div>', 'number': r'<div class="attributes_block"><div class="attributes_label"><span class="text text__underline">Телефон</span>: </div><div class="attributes_value"><div class="attributes_value">(.*?)</div></div></div>', 'site': r'<div class="attributes_block"><div class="attributes_label"><span class="text text__underline">Сайт</span>: </div><a href="(.*?)" target="blank" rel="nofollow" class="attributes_value">', 'email': r'<div class="attributes_block"><div class="attributes_label"><span class="text text__underline">Email</span>: </div><a href="mailto:(.*?)" target="blank" rel="nofollow" class="attributes_value">', 'time_work': r'<div class="attributes_block"><div class="attributes_label"><span class="text text__underline">Часы работы</span>: </div><div class="attributes_value">(.*?)</div></div>' } passport = self.text.parse_passport(regs) passport['social_networks'] = self.social_networks passport['content'] = self.content passport['img_url'] = self.img_url return Library(passport)
def __init__(self, parent=None): #creating the window super(ShapeLibraryWindow, self).__init__(parent) self.library = Library(DIRECTORY) self.setWindowFlags(QtCore.Qt.Tool) self.ui = shape_ui.Ui_form_main() self.ui.setupUi(self, self.library) self.display_type = "All" #connecting the buttons self.ui.btn_open.clicked.connect(self.load_shape) self.ui.btn_save.clicked.connect(self.open_save_dialog) #connecting the combo box self.ui.vombo_box_shape_type.currentIndexChanged.connect( self.set_display_type)
async def get_present_libraries(self, target: BuildTarget) -> List[str]: present_libraries = [] for file in target.all_dependency_files: if file.endswith('.so') or '.so.' in file: if Library.find_library_in_list(file, self.libraries): present_libraries.append(file) return present_libraries
def populate_libraries(self, book_score_list, libraries): my_libraries = [] # Distributing books to libraries repeated_queue = [] for l_id, library in enumerate(tqdm(libraries)): prop, books = library desirable_books_list = [] repeated_objs = [b.b_id for b in repeated_queue] for book_id in books: if book_id not in repeated_objs: book_score = book_score_list[book_id] book_obj = Book(b_id=book_id, b_score=book_score) desirable_books_list.append(book_obj) repeated_queue.append(book_obj) else: for book_obj in repeated_queue: if book_obj.b_id == book_id: desirable_books_list.append(book_obj) # print("LIB", l_id, "completer") _, buff_time, capacity = prop my_libraries.append( Library(l_id, buff_time, capacity, desirable_books_list)) return my_libraries
def listAuthorsByEditorial(editorial): print("#### Autores por editorial: " + editorial + " ####") __listedAuthorsByEditorial = [] for book in Library().books: if book.editorial == editorial: if book.author not in __listedAuthorsByEditorial: print(book.author)
def on_drag_data_received(self, view, context, x, y, data, info, timestamp): 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()
def __init__(self, lexer, state, memory): self.lexer = lexer self.current_token = self.lexer.get_next_token() self.state = state self.memory = memory self.activeVars = [] self.lib = Library()
def position_transition(V, p, V2): raiz = 0 for i in V: raiz += (i.real**2) + (i.imag**2) prob = ((V[p].real**2) + (V[p].imag**2)) / raiz total = complex(0, 0) norm1 = 0 norm2 = 0 V1 = V for z, y in zip(V1, V2): total = l.sum(total, l.product(z, y)) norm1 += (z.real**2) + (z.imag**2) norm2 += (y.real**2) + (y.imag**2) norm1f = norm1**(1 / 2) norm2f = norm2**(1 / 2) deno = norm1f * norm2f return [prob, complex((total.real / deno), (total.imag / deno))]
def __init__(self): """A constructor that initializes a Library class object, thereby generating a JSON file to store library data and tools for interacting with the library. Initialize indents in the main menu and the main program switch. """ self.Library = Library() self.__menu_indent = " " * 30 self.__indent = " " * 20 self.program_switch = { 1: self.SearchCase, 2: self.AddCase, 3: self.DeleteCase, 4: self.ReturnCase, 5: self.TakeCase, 6: self.PrintCase }
def update_language(self): if not self.window: return if self.current_language: accel_group = Library().get_accel_group( \ self.current_language) self.window.remove_accel_group(accel_group) if self.current_controller: self.current_language = self.current_controller.language_id if self.current_language != None: accel_group = Library().get_accel_group( \ self.current_language) self.window.add_accel_group(accel_group) else: self.current_language = None
def __init__(self): pluma.Plugin.__init__(self) self.dlg = None library = Library() library.set_accelerator_callback(self.accelerator_activated) if platform.platform() == 'Windows': snippetsdir = os.path.expanduser('~/pluma/snippets') else: userdir = os.getenv('MATE22_USER_DIR') if userdir: snippetsdir = os.path.join(userdir, 'pluma/snippets') else: snippetsdir = os.path.expanduser('~/.config/pluma/snippets') library.set_dirs(snippetsdir, self.system_dirs())
def Ex2(): lib = Library(1, "51 Some str., NY") lib += Book("Leo Tolstoi", "War and Peace") lib += Book("Charles Dickens", "David Copperfield") for book in lib: # вывод в виде: [1] L.Tolstoi "War and Peace" print(book) # вывод в виде: ["War", "Peace"] print(book.tag())
def probability(state_vector1, state_vector2, observable, position): v1 = observable[position] normalized_observable = T.normalizarVector(v1) #e1 normalized_state1 = T.normalizarVector(state_vector1) ampl1 = transition_amplitude(normalized_state1, normalized_observable) # e2 normalized_state2 = T.normalizarVector(state_vector2) ampl2 = transition_amplitude(normalized_state2, normalized_observable) return l.sum(ampl1, ampl2)
def __init__(self, filename, library=None): self._handle = None self._filename = filename if not library: library = Library.for_file(filename) self._lib = library (handle, info) = self._lib._open_file(filename) self._handle = handle self._info = info self._eproxy = EntityProxy(self)
def __populateLibrary(self,tokens,name): assert isinstance (name,str) library=Library(tokens,name[name.rfind("\\")+1:]) path=name[:name.rfind("\\")+1] gen=library.populate() try: typ,val=gen.next() while True: try: if typ=='imp': self.__import([path+v for v in val]) typ,val=gen.next() elif typ=='inp': typ,val=gen.send(self.__getPartition(val)) else: raise SemanticException('Unknown request %s\n'%typ) except SemanticException, ex: gen.throw(ex) except StopIteration: pass self.inheritedPartitions.update(library.inheritedPartitions)
def convertLib(fileName,symFileName,modFileName): logFile.write("*******************************************\n") logFile.write("Converting Lib: "+fileName+"\n") logFile.write("Module Output: "+modFileName+"\n") logFile.write("Symbol Output: "+symFileName+"\n") name=fileName.replace("/","\\") name=name.split("\\")[-1] name=name.split(".")[0] logFile.write("Lib Name: "+name+"\n") try: node = getRootNode(fileName) node=node.find("drawing").find("library") lib=Library(node,name) open(modFileName,'w').close() open(symFileName,'w').close() modFile=open(modFileName,"a") symFile=open(symFileName,"a") lib.writeLibrary(modFile,symFile) modFile.close() symFile.close() except BaseException as e: logFile.write("Conversion Failed\n\n") logFile.write(traceback.format_exc()) logFile.write("*******************************************\n\n\n") return False, "Error Converting Library: '"+name+"'\n"+str(e)+"\nSee Log.txt for more info" logFile.write("Conversion Successfull\n") logFile.write("*******************************************\n\n\n") return True, "Conversion of Library '"+name+"' Complete"
def testPointers(self): l = Library() # Basic C types pointerTypes = [ "void*", "char*", "short*", "int*", "long*", "float*", "double*", "unsigned char*", "unsigned short*", "unsigned int*", "unsigned long*", "signed char*", "signed short*", "signed int*", "signed long*", "const void*", "const char*", "const short*", "const int*", "const long*", "const unsigned char*", "const unsigned short*", "const unsigned int*", "const unsigned long*", "const signed char*", "const signed short*", "const signed int*", "const signed long*", ] for cType in pointerTypes: self.assertEquals(l.getNativeType(Type(cType)), "pointer")
def testNativeTypes(self): l = Library() # Basic C types typePairs = [ ("void", "void"), ("char", "byte"), ("short", "short"), ("int", "int"), ("long", "long"), ("float", "float"), ("double", "double"), ("enum", "int"), ("unsigned char", "byte"), ("unsigned short", "short"), ("unsigned int", "int"), ("unsigned long", "long"), ("signed char", "byte"), ("signed short", "short"), ("signed int", "int"), ("signed long", "long"), ("const char", "byte"), ("const short", "short"), ("const int", "int"), ("const long", "long"), ("const unsigned char", "byte"), ("const unsigned short", "short"), ("const unsigned int", "int"), ("const unsigned long", "long"), ("const signed char", "byte"), ("const signed short", "short"), ("const signed int", "int"), ("const signed long", "long"), ] for cType, nativeType in typePairs: self.assertEquals(l.getNativeType(Type(cType)), nativeType)
def main(src_dir, dst_dir=None): if not dst_dir: dst_dir = src_dir # used for logging purposes start = default_timer() library = Library(src_dir, dst_dir) library.read_all() library.make_new_dir() library.copy_src_to_dst() library.delete_old_folders() # used for logging purposes stop = default_timer() print 'Execution time: ', stop - start, ' sec'
def on_view_key_press(self, view, event): library = Library() if not (event.state & gdk.CONTROL_MASK) and \ not (event.state & gdk.MOD1_MASK) and \ event.keyval in self.TAB_KEY_VAL: if not event.state & gdk.SHIFT_MASK: return self.run_snippet() else: return self.skip_to_previous_placeholder() elif not library.loaded and \ library.valid_accelerator(event.keyval, event.state): library.ensure_files() library.ensure(self.language_id) self.accelerator_activate(event.keyval, \ event.state & gtk.accelerator_get_default_mod_mask()) return False
def test_etagere_addBook(self): etagere = Library() etagere.biblio = {} livre = Book("John","Grisham","The Racketeer","International Bestseller",2013,"Novel",382,"Chambre de Cyril",4,"Et voici un autre commentaire blablab abbla.","The Racketeer.jpg") etagere.addBook(livre) self.assertEqual(len(etagere.dLibrary), 1)
def __init__(self, parent): wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES) self.principalFrame = parent self.defaultFont = self.GetFont() self.styledFont = createMyFont() self.SetFont(self.styledFont) self.selectedItem = 0 self.selectedID = '' self.visuLivreFrame = False self.modifLivreFrame = False # --- Initialisation de la classe Etagere, avec chargement de la liste de livre self.maBiblio = Library(self.principalFrame.pathLibrary) # --- Ajout des icônes self.il = wx.ImageList(32, 16) # Icônes de triages et de notes données aux livres triage={'sm_up':'GO_UP_B.png', 'sm_dn':'GO_DOWN_B.png', 'note_a':'note_a.jpg', 'note_b':'note_b.jpg', 'note_c':'note_c.jpg', 'note_d':'note_d.jpg', 'note_f':'note_f.jpg'} for k,v in triage.items(): img = wx.Image(self.principalFrame.pathIcone+v, wx.BITMAP_TYPE_ANY) img = img.Scale(32, 16, wx.IMAGE_QUALITY_HIGH) img = img.ConvertToBitmap() s="self.%s= self.il.Add(img)" %k exec(s) # a={"sm_up":"GO_UP","sm_dn":"GO_DOWN"} # for k,v in a.items(): # s="self.%s= self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_%s,wx.ART_TOOLBAR,(32,16)))" % (k,v) # exec(s) self.SetImageList(self.il, wx.IMAGE_LIST_SMALL) # --- Ajout de couleurs de fond pour différencier les lignes self.listColor = [] self.listColor.append(wx.ListItemAttr()) self.listColor[-1].SetBackgroundColour("#B3FFFA") # Bleu pâle self.listColor.append(wx.ListItemAttr()) self.listColor[-1].SetBackgroundColour("#FAB3FF") # Rose pâle self.listColor.append(wx.ListItemAttr()) self.listColor[-1].SetBackgroundColour("#FFFAB3") # Jaune pâle self.listColor.append(wx.ListItemAttr()) self.listColor[-1].SetBackgroundColour("#FFFFFF") # Blanc self.listColor.append(wx.ListItemAttr()) self.listColor[-1].SetBackgroundColour("#DDDDDD") # Gris claire self.currentColor = 0 # Iterateur de couleur # --- Initialisation des colonnes self.columnList={0:['Auteur',140], 1:['Titre',320], 2:['Editeur',130], 3:['Parution',95], 4:['Genre',140], 5:['Pages',70], 6:['Lieu',140], 7:['Note',0]} for k,v in self.columnList.items(): if k in [3,5]: s="self.InsertColumn(%i, '%s', wx.LIST_FORMAT_CENTER, width=%i)" % (k,v[0],v[1]) else: s="self.InsertColumn(%i, '%s', width=%i)" % (k,v[0],v[1]) exec(s) # --- Initialisation des premiers items (nombre d'items = nombre d'éléments dans le dictionnaire) self.itemDataMap = self.convertToDataMap() self.itemIndexMap = range(1,len(self.itemDataMap)+1) self.SetItemCount(len(self.itemDataMap)) # self.itemsColor = [-1]*len(self.itempDataMap) # Couleur pour chaque item # --- Initialisation des modules mixins listmix.ListCtrlAutoWidthMixin.__init__(self) listmix.ColumnSorterMixin.__init__(self, len(self.columnList)) # --- On définit le trie par défaut sur 'Genre' (colonne 4) A->Z ordre alphabétique (1) self.currentSorter = 4 # Numéro courant de la colonne triante self.SortListItems(self.currentSorter, 1) # --- Initialisation du menu popup self.initPopupMenu() # --- Définition des events self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected) self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated) self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected) self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnItemRightClick) self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)
class VirtualList(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.ColumnSorterMixin): """ Widget contrôlant la liste des livres: c'est d'ici qu'on accède à l'objet Etagere, et donc aux objets Livre. """ def __init__(self, parent): wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT|wx.LC_VIRTUAL|wx.LC_HRULES|wx.LC_VRULES) self.principalFrame = parent self.defaultFont = self.GetFont() self.styledFont = createMyFont() self.SetFont(self.styledFont) self.selectedItem = 0 self.selectedID = '' self.visuLivreFrame = False self.modifLivreFrame = False # --- Initialisation de la classe Etagere, avec chargement de la liste de livre self.maBiblio = Library(self.principalFrame.pathLibrary) # --- Ajout des icônes self.il = wx.ImageList(32, 16) # Icônes de triages et de notes données aux livres triage={'sm_up':'GO_UP_B.png', 'sm_dn':'GO_DOWN_B.png', 'note_a':'note_a.jpg', 'note_b':'note_b.jpg', 'note_c':'note_c.jpg', 'note_d':'note_d.jpg', 'note_f':'note_f.jpg'} for k,v in triage.items(): img = wx.Image(self.principalFrame.pathIcone+v, wx.BITMAP_TYPE_ANY) img = img.Scale(32, 16, wx.IMAGE_QUALITY_HIGH) img = img.ConvertToBitmap() s="self.%s= self.il.Add(img)" %k exec(s) # a={"sm_up":"GO_UP","sm_dn":"GO_DOWN"} # for k,v in a.items(): # s="self.%s= self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_%s,wx.ART_TOOLBAR,(32,16)))" % (k,v) # exec(s) self.SetImageList(self.il, wx.IMAGE_LIST_SMALL) # --- Ajout de couleurs de fond pour différencier les lignes self.listColor = [] self.listColor.append(wx.ListItemAttr()) self.listColor[-1].SetBackgroundColour("#B3FFFA") # Bleu pâle self.listColor.append(wx.ListItemAttr()) self.listColor[-1].SetBackgroundColour("#FAB3FF") # Rose pâle self.listColor.append(wx.ListItemAttr()) self.listColor[-1].SetBackgroundColour("#FFFAB3") # Jaune pâle self.listColor.append(wx.ListItemAttr()) self.listColor[-1].SetBackgroundColour("#FFFFFF") # Blanc self.listColor.append(wx.ListItemAttr()) self.listColor[-1].SetBackgroundColour("#DDDDDD") # Gris claire self.currentColor = 0 # Iterateur de couleur # --- Initialisation des colonnes self.columnList={0:['Auteur',140], 1:['Titre',320], 2:['Editeur',130], 3:['Parution',95], 4:['Genre',140], 5:['Pages',70], 6:['Lieu',140], 7:['Note',0]} for k,v in self.columnList.items(): if k in [3,5]: s="self.InsertColumn(%i, '%s', wx.LIST_FORMAT_CENTER, width=%i)" % (k,v[0],v[1]) else: s="self.InsertColumn(%i, '%s', width=%i)" % (k,v[0],v[1]) exec(s) # --- Initialisation des premiers items (nombre d'items = nombre d'éléments dans le dictionnaire) self.itemDataMap = self.convertToDataMap() self.itemIndexMap = range(1,len(self.itemDataMap)+1) self.SetItemCount(len(self.itemDataMap)) # self.itemsColor = [-1]*len(self.itempDataMap) # Couleur pour chaque item # --- Initialisation des modules mixins listmix.ListCtrlAutoWidthMixin.__init__(self) listmix.ColumnSorterMixin.__init__(self, len(self.columnList)) # --- On définit le trie par défaut sur 'Genre' (colonne 4) A->Z ordre alphabétique (1) self.currentSorter = 4 # Numéro courant de la colonne triante self.SortListItems(self.currentSorter, 1) # --- Initialisation du menu popup self.initPopupMenu() # --- Définition des events self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected) self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated) self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected) self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnItemRightClick) self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick) #--------------------------------------------------- # --- Initialisation def initPopupMenu(self): """ Initialise le menu popup qui s'ouvrira suite à l'événement clique droit sur un item de la liste """ self.popupmenu = wx.Menu() for text in ["Modifier","Supprimer"]: item = self.popupmenu.Append(-1, text) self.Bind(wx.EVT_MENU, self.OnPopupItemSelected, item) #--------------------------------------------------- # --- Events def OnItemSelected(self, evt): """ Evenement lors de la sélection d'un livre """ self.selectedItem = evt.m_itemIndex # Correspond au numéro de la ligne printLogText('OnItemSelected: "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s"' % (self.selectedItem, self.GetItemText(self.selectedItem), self.getColumnText(self.selectedItem, 1), self.getColumnText(self.selectedItem, 2), self.getColumnText(self.selectedItem, 3), self.getColumnText(self.selectedItem, 4), self.getColumnText(self.selectedItem, 5), self.getColumnText(self.selectedItem, 6), self.getColumnText(self.selectedItem, 7))) self.vboxActu() print("OnItemSelected", self.selectedItem) def OnItemActivated(self, evt): """ Evenement double clique sur item: ouvre la fenêtre de visualisation d'un livre """ self.selectedItem = evt.m_itemIndex printLogText("OnItemActivated: %s -- TopItem: %s" % (self.GetItemText(self.selectedItem), self.GetTopItem())) if self.visuLivreFrame : self.visuLivreFrame.SetFocus() self.visuLivreFrame.actuPage(self.selectedItem) else: self.visuLivreFrame = DisplayBook(self, wx.ID_PREVIEW, self.selectedItem) self.visuLivreFrame.Show(True) self.visuLivreFrame.CentreOnParent() print "itemIndexMap", self.itemIndexMap[self.selectedItem] print "itemDataMap", self.itemDataMap[self.itemIndexMap[self.selectedItem]] def OnItemDeselected(self, evt): """ **USELESS** Evenement de déselection d'un item """ printLogText("OnItemDeselected: %s" % evt.m_itemIndex) def OnItemRightClick(self, evt): """ Evenement du clique droit sur un item """ self.selectedID = self.itemIndexMap[evt.m_itemIndex] printLogText("OnItemRightClick: %s" % (self.selectedID)) printLogText("Path: %s" % (self.principalFrame.pathRoot)) click = evt.GetPosition() frame = self.principalFrame.GetPosition() liste = self.GetPosition() pos = (click[0] + frame[0] + liste[0], click[1] + frame[1] + liste[1]+52) pos = self.ScreenToClient(pos) self.PopupMenu(self.popupmenu, pos) def OnColClick(self, evt): """ Evenement du clique sur colonne """ print "OnCOlClick" evt.Skip() x,y = evt.GetPosition() # On prend la position du clique print "col",evt.GetPosition() print "eventType",evt.GetEventType() self.majColumnWidth() # On actualise la largeur des colonnes self.currentSorter = self.getColumnNumber(x) # On met à jour le numéro de colonne triante printLogText("OnColClick: %s" % self.currentSorter) # self.itemsColor = [ -1 for i in range(len(self.itemsColor))] def OnPopupItemSelected(self, evt): """ Evenement de choix d'une action du menu popup """ item = self.popupmenu.FindItemById(evt.GetId()) choix = item.GetText() if choix=="Modifier": values = self.maBiblio.dLibrary[self.selectedID].__dict__ if self.modifLivreFrame: self.modifLivreFrame.SetFocus() else: self.modifLivreFrame = BookFormular(self.principalFrame, -1, title="Modification d'un livre", state=self.selectedID, defValue=values) self.modifLivreFrame.Show(True) self.modifLivreFrame.CentreOnParent() elif choix=="Supprimer": mess = 'Êtes-vous sûre de vouloir supprimer ce livre ?\n\n'.decode('utf-8') + self.maBiblio.dLibrary[self.selectedID].__repr__() supp = wx.MessageDialog(self, message=mess, caption='Supprimer un livre', style=wx.YES_NO|wx.STAY_ON_TOP|wx.ICON_EXCLAMATION) rep = supp.ShowModal() # Attend une réponse de l'utilisateur if rep == wx.ID_YES: EGL = [('editeur', self.maBiblio.dLibrary[self.selectedID].editeur), ('genre', self.maBiblio.dLibrary[self.selectedID].genre), ('lieu', self.maBiblio.dLibrary[self.selectedID].lieu)] self.maBiblio.removeBook(self.selectedID) self.listActu() self.maBiblio.updateEGL() #--------------------------------------------------- # --- Fonctions sur les colonnes def getColumnText(self, index, col): """ Retourne le texte contenu dans la colonne de la ligne sélectionnée (ligne=item) """ item = self.GetItem(index, col) return item.GetText() def getColumnNumber(self,x): """ Retourne le numéro de la colonne à la position verticale 'x' (pixel) """ col = 0 # Numéro de la colonne courante curseur = self.columnList[col][1] # Position du curseur en pixel au niveau vertical # Tant que le clique est supérieur au curseur, ou que la dernière colonne n'est pas atteinte, on continue while x > curseur and col < len(self.columnList)-1: col += 1 curseur += self.columnList[col][1] print("Col:",col,"width:",self.GetColumnWidth(col)) return col def majColumnWidth(self): """ Actualise la largeur des colonnes dans la variable 'columnList', au cas où celles-ci auraient été modifiée """ for i in self.columnList.keys(): w = self.GetColumnWidth(i) if self.columnList[i][1] != w: self.columnList[i][1] = w #--------------------------------------------------- # Fonctions nécessaire pour les callback des thèmes # LC_REPORT et LC_VIRTUAL def OnGetItemText(self, item, col): index=self.itemIndexMap[item] s = self.itemDataMap[index][col] return s def OnGetItemColumnImage(self, item, col): """ Ajoute une petite icone pour les notes """ # Si ce n'est pas la colonne de note, on zappe if col!=7: return -1 index=self.itemIndexMap[item] note=self.itemDataMap[index][col] if note==5: return self.note_a elif note==4: return self.note_b elif note==3: return self.note_c elif note==2: return self.note_d elif note==1: return self.note_f else: return -1 # res = -1 # exec("res = self.note_%s"%note) # return res def OnGetItemAttr(self, item): """ Modifie la couleur de chaque item suivant l'item précédent et la colonne triante """ # # ---------------------------------- # # --- Test 1: 2 couleurs alternées if item%2 == 0: self.currentColor = 3 else: self.currentColor = 4 return self.listColor[self.currentColor] # # ---------------------------------- # # --- Test 2: 3 couleurs, alternées par groupe # indexA = self.itemIndexMap[item] # if item > 0: # indexB = self.itemIndexMap[item-1] # else: # indexB = self.itemIndexMap[item] # # colA = self.itemDataMap[indexA][self.currentSorter] # colB = self.itemDataMap[indexB][self.currentSorter] # # if colA != colB: # self.currentColor = (self.currentColor + 1)%3 # return self.listColor[self.currentColor] # # ---------------------------------- # # --- Test 3: 3 couleurs alternées, par groupe prenant en compte la couleur qui précède # # Première initialisation de itemsColor # if -1 in self.itemsColor: # if colA != colB: # self.currentColor = (self.currentColor + 1)%3 # # itemsColor déjà initialisé # else: # if item > 0: # if self.itemsColor[item] == self.itemsColor[item-1]: # self.currentColor = self.itemsColor[item] # if colA!=colB: # self.currentColor = (self.currentColor + 1)%3 # else: # if colA==colB: # self.currentColor = self.itemsColor[item-1] # self.itemsColor[item] = self.currentColor # print item, self.itemsColor # return self.listColor[self.currentColor] #--------------------------------------------------- # Fonctions à définir obligatoirement pour le triage def SortItems(self,sorter=cmp): """ Trie les items """ #FIXME Bug lors d'un trie décroissant, si clique sur la liste: retrie automatiquement dans l'ordre croissant. print "SortItems", self.currentSorter # print help(sorter) items = list(self.itemDataMap.keys()) items.sort(sorter) self.itemIndexMap = items # Actualise la liste triée self.Refresh() # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py def GetListCtrl(self): return self # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py def GetSortImages(self): return (self.sm_dn, self.sm_up) def getItem(self, index): """ Return the item corresponding to the ID at the index in the list. """ return self.maBiblio.dLibrary[self.itemIndexMap[index]] #--------------------------------------------------- # Fonctions d'actualisation def vboxActu(self): """ Actualise la page de couverture et le commentaire correspondant au livre sélectionné """ index = self.itemIndexMap[self.selectedItem] comm = self.maBiblio.dLibrary[index].commentaire couv = self.maBiblio.dLibrary[index].couverture self.principalFrame.vboxActu(comm, couv) def convertToDataMap(self): """ Convert the list of books into a readble dictionary for ListCtrl. """ dataMap = {} for k,v in self.maBiblio.dLibrary.items(): dataMap[k] = (v.auteurPrenom + ' ' + v.auteurNom, v.titre , v.editeur , v.parution , v.genre , v.nbPage , v.lieu , v.note , v.commentaire, v.ISBN) return dataMap def listActu(self): """ Actualise la liste des livres à afficher """ if self.itemDataMap == None or (self.GetItemCount() == len(self.maBiblio.dLibrary)-1): # La liste est vide ou on vient de supprimer un item self.itemDataMap = self.convertToDataMap() self.itemIndexMap = range(1,len(self.itemDataMap)+1) self.SetItemCount(len(self.itemDataMap)) self.SortListItems(self.currentSorter, 1) self.calcStatistiques() self.Refresh() def keyWordsActu(self, keyWords): """ Recherche tous les items contenant les mots-clés recherchés, et les stock dans 'itemDataMap' Recherche dans tous les champs sauf le champs 'commentaire' (et 'couverture' car non représenté dans 'itemDataMap') """ # S'il n'y a aucun mots-clés, on retourne None if not keyWords: self.itemDataMap = None return itemsSelected = {} # Dico contenant les items recherchés found = False # Booléen pour sortir des boucles for k,v in self.itemDataMap.items(): for w in keyWords: # On cherche dans tous les champs sauf 'commentaire', le dernier de la liste for s in v[:-1]: # On vérifie le type de la valeur pour déterminer l'encodage if type(s) == str or type(s) == unicode: s_encoded = s.encode('utf-8') else: s_encoded = str(s) # Puis on cherche le mot-clé, sans prendre compte des Majuscules/minuscules (on met tout en minuscule) if s_encoded.lower().find(w.lower()) >= 0: found = True itemsSelected[k] = v break if found: found = False break self.itemDataMap = itemsSelected #--------------------------------------------------- # Autres fonctions def calcStatistiques(self): """ Calcul de statistiques sur les livres """ page = 0 # Nombre moyen de pages par livre note = 0 # Note moyenne Genre = {} # Nombre de livres par genre Lieu = {} # Nombre de livres par lieu Auteur = [] # Nombre d'auteurs tot = self.GetItemCount() # Nombre de livres total if tot == 0: # S'il n'y a aucun livre de sélectionné, on retourne ce message self.principalFrame.rawStatMess = "Bibliothèque vide.".decode('utf-8') return for k,v in self.itemDataMap.items(): if v[5] > 0: page += v[5] if v[7] > 0: note += v[7] if v[4]: if not Genre.has_key(v[4]): Genre[v[4]] = 0 Genre[v[4]] += 1 if v[6]: if not Lieu.has_key(v[6]): Lieu[v[6]] = 0 Lieu[v[6]] += 1 if v[0] not in Auteur: Auteur.append(v[0]) page /= float(tot) note /= float(tot) note = round(note,1) mAutre = 'Nombre de livres: '+str(tot)+' Nombre de pages moyen: '+str(int(page))+' Note moyenne: '+str(note) mGenre = ' '.join([ i + ': ' + str(Genre[i]) for i in Genre.keys()]) mLieu = ' '.join([ i + ': ' + str(Lieu[i]) for i in Lieu.keys()]) self.principalFrame.rawStatMess = [mAutre, mGenre, mLieu] return def calcStatistiques2(self): """ Compute statistics on selected books (and all books). """ dArray = {'':[], 'Selected':[], 'All':[]} spacement = "\n\n%s\n" %("-"*60) # --- Get dictionaries of All books and Selected books. dAll = self.principalFrame.list.maBiblio.dLibrary dSelected = {i:self.principalFrame.list.maBiblio.dLibrary[i] for i in self.itemDataMap.keys()} def getLAttr(lib, attr): return [lib[b].getAttr(attr) for b in sorted(lib.keys())] # --- Compute basic stats: # Number of books dArray[''].append('Nombre de livres') dArray['Selected'].append(len(dSelected)) dArray['All'].append(len(dAll)) # Mean note dArray[''].append('Note moyenne') dArray['Selected'].append(str(round(np.mean([getLAttr(dSelected, 'note')]),2))) dArray['All'].append(str(round(np.mean([getLAttr(dAll, 'note')]),2))) # Mean page number dArray[''].append('Nb page moyen') dArray['Selected'].append(str(round(np.mean([getLAttr(dSelected, 'nbPage')]),2))) dArray['All'].append(str(round(np.mean([getLAttr(dAll, 'nbPage')]),2))) # --- Format output message = "\t\t\t\tSélectionnés\t\tTous\n".decode('utf-8') message += '\n'.join( ["%s\t%s\t%s" %(dArray[''][i], dArray['Selected'][i], dArray['All'][i]) for i in range(len(dArray['']))] ) message += spacement # Authors message += "Liste des auteurs\tNb livres\n\n" lAuthor = [i.getAuteur() for i in dSelected.values()] message += '\n'.join(["%s\t%s"%(i, lAuthor.count(i)) for i in sorted(set(lAuthor))]) message += spacement # Genre message += "Liste des genre\tNb livres\n\n" lGenre = getLAttr(dSelected, 'genre') message += '\n'.join(["%s\t%s"%(i, lGenre.count(i)) for i in sorted(set(lGenre))]) message += spacement return message
def testObjects(self): l = Library() l.typeMap[Type("Window*")] = "object" l.typeMap[Type("const Window*")] = "object" self.assertEquals(l.getNativeType(Type("Window*")), "object") self.assertEquals(l.getNativeType(Type("const Window*")), "object")
class pytunes(OptionMatcher): def __init__(self): super(pytunes,self).__init__() self.setAliases({ 'r':'repeat', 's':'shuffle', 'u':'unique', 'k':'skip-artists' }) self.setUsageInfo( {'skip-artists':""" Comma separated list of artists to skip, using shell-style case-insensitive matching. Adding a suffix of :n where n=0...10 will skip the artist with n out of 10 times. e.g. *Sarah*:5 will skip artists who match *Sarah* 5 times out of 10""".strip().replace('\n','').replace(' ',''), 'unique':'If given, duplicate entries in playlists will be removed'}, None) @optmatcher def main(self, libraryOption="~/Music/iTunes/iTunes Music Library.xml", playlist='', shuffleFlag=False, repeatFlag=False, skipArtistsOption='', uniqueFlag=False): libpath = expanduser(libraryOption) libpath = expandvars(libpath) self._lib = Library(libpath) self._skip_weights = {} if skipArtistsOption: t = [x.strip() for x in skipArtistsOption.split(',')] for skippattern in t: if ':' in skippattern: newskippattern,skipweight = skippattern.rsplit(':') self._skip_weights[newskippattern] = int(skipweight) else: # default to skipping 10 times out of 10, i.e. always self._skip_weights[skippattern] = 10 #print self._skip_weights if playlist == '': self.print_playlists() return 0 else: return self.play_playlist(playlist, shuffleFlag, repeatFlag, uniqueFlag) def print_playlists(self): playlists = self._lib.playlists() print 'Playlists:' for pl in playlists: print '\t',pl def play_playlist(self, playlistname, shuffle, repeat, unique): def _filter(track, det=False): """ det stands for deterministic. When it is true, all tracks that match are skipped. Otherwise skip weight is used to randomly determine if a track should be skipped """ artist = track.get('Artist') if not artist: artist = '' skip = False for skippattern in self._skip_weights.keys(): if fnmatch.fnmatch(artist.lower(),skippattern.lower()): if det: skip = True else: skipweight = self._skip_weights[skippattern] if skipweight and random.random()*10<skipweight: skip = True break return not skip def _filterdet(track): return _filter(track, True) pl = self._lib.get_playlist(playlistname) if not pl: print 'No such playlist (%s) or empty playlist'%(playlistname) return -1 else: # check whether the user has filtered out all tracks pl = self._lib.get_playlist(playlistname, _filterdet) # if pl is empty, then all tracks match something. At this point we need # to make sure SOME weights are smaller than 10 if not pl: if min(self._skip_weights.values()) >= 10: print 'All tracks in playlist are to be skipped' return -2 while True: # otherwise, we either have some songs that will never be skipped, or # some song have a probability of not being skipped. Iterate until we # have a non-empty playlist pl = [] while not pl: pl=self._lib.get_playlist(playlistname, _filter) if unique: pl = set(pl) pl = list(pl) if shuffle: print 'Shuffling playlist %s...'%(playlistname) random.shuffle(pl) for idx,ttuple in enumerate(pl): trackid = ttuple[0] trackpath = ttuple[1] track = self._lib.get_track(trackid) artist = track.get('Artist') if artist: artist = artist[0:24] else: artist = 'Unknown' print '[%3d/%3d] %-24s %s'%(idx+1, len(pl), artist, track['Name']) call(MUSIC_PLAYER+[trackpath]) if not repeat: break return 0
def do_deactivate(self): library = Library() library.remove_accelerator_callback(self.accelerator_activated) self._helper.stop() self._helper = None
def testTypedefs(self): l = Library() l.typeDefs[Type("GLbyte")] = Type("char") self.assertEquals(l.getNativeType(Type("GLbyte")), "byte") self.assertEquals(l.getNativeType(Type("const GLbyte")), "byte")