def _writeXML(self, output, outputDictionary): """ Defines the method for writing the post-processor to a .csv file @ In, output, File object, file to write to @ In, outputDictionary, dict, dictionary stores importance ranking outputs @ Out, None """ if output.isOpen(): output.close() if self.dynamic: outFile = Files.returnInstance('DynamicXMLOutput', self) else: outFile = Files.returnInstance('StaticXMLOutput', self) outFile.initialize(output.getFilename(), self.messageHandler, path=output.getPath()) outFile.newTree('ImportanceRankPP', pivotParam=self.pivotParameter) outputResults = [outputDictionary ] if not self.dynamic else outputDictionary.values() for step, outputDict in enumerate(outputResults): pivotVal = outputDictionary.keys()[step] self._localPrintXML(outFile, outputDict, pivotVal) if step == 0: self._localPrintPCAInformation(outFile, outputDict, pivotVal) outFile.writeFile() self.raiseAMessage('ImportanceRank XML printed to "' + output.getFilename() + '"!')
def changeTo(self, game): print("Chaneg") Files.readOptions() print("reading options") if Sound.musicChannel.get_sound() != Files.getSound("m_menu"): Sound.playMusic("m_menu")
def __init__( self, ID=None, groupID=None ): #groupID is the GroupMe groupID, not internal (ID is internal) self.groupID = groupID self.name = None #The owner is not necessary, but if there are multiple users with tokens, this will resolve issues self.owner = None #The owner is a token of the owner user self.bot = None #This is the group's bot id that it uses to post messages #These are just save objects to be used by other modules self.analytics = {} self.commands = {} self.markedForDeletion = False #Groups can get deleted. I want to delete the ones that don't exist, just not during initialization groupRegister(self, ID) #If no ID, will assign an id automatically self.folderPath = Files.getGroupFolder(self) self.filePath = Files.getFileName( Files.join(self.folderPath, SAVE_FILE_NAME)) #This UserList should be empty and just a reference to the object #Users should be loaded in postInit once we have gotten user data from internet self.users = Users.UserList(self) self.handler = Network.GroupMeHandler(self) self.commandBuilder = Commands.CommandBuilder(self)
def train(): ''' Print some messages, initialize a time counter and call main Train method. :return: trained: boolean True if the network could be trained. ''' txtIf.printMessage(txtIf.MESSAGES.TRAINING_NETWORK) import Trainer import time ''' Count the time the training lasts for researcher purposes. ''' tic = time.time() trained, numImages = Trainer.train() toc = time.time() if numImages >= 2: txtIf.printMessage(txtIf.MESSAGES.TRAIN_TIME, numImages, round(toc - tic, 2)) if not trained: txtIf.printError(txtIf.ERRORS.CANNOT_TRAIN_NETWORK) ''' If the network is trained, the new resources are used. ''' if trained: txtIf.printMessage(txtIf.MESSAGES.YML_USED, files.ymlFile, trained) txtIf.printMessage( txtIf.MESSAGES.LOADING_FILE, files.xmlFolderPath + files.delimiter + files.xmlFile) files.getLoadedXml() return trained
def loadGroup(folder): if type(folder) == int: folder = "Group " + str(folder) try: loadedGroup = _folderCache[folder] log.group("Group already loaded, returning group:", loadedGroup) return loadedGroup except KeyError: pass #Just continue loading try: groupNumber = int(re.search("\d+", folder).group()) log.group("Loading Group:", groupNumber) except AttributeError: raise RuntimeError("Group Folder '" + folder + "' does not have a group number") try: with open(Files.getFileName(Files.join(folder, SAVE_FILE_NAME))) as file: groupType = Files.read(file) log.group("Group Type:", groupType) newGroup = globals()[groupType](groupNumber).load( file) #Load arbitrary class _folderCache[ folder] = newGroup #Save it to a cache so we cannot load twice return newGroup #except (KeyError, TypeError, AttributeError) as Error: #I actually think I want this to be a halting error. # log.error("Failed to properly load group file:", Error) except FileNotFoundError: #The group was improperly initialized/saved log.group.error("Group had no load file. Deleting folder") Files.deleteFolder(folder)
def _writeXML(self,output,outputDictionary): """ Defines the method for writing the post-processor to a .csv file @ In, output, File object, file to write to @ In, outputDictionary, dict, dictionary stores importance ranking outputs @ Out, None """ if output.isOpen(): output.close() if self.dynamic: outputInstance = Files.returnInstance('DynamicXMLOutput', self) else: outputInstance = Files.returnInstance('StaticXMLOutput', self) outputInstance.initialize(output.getFilename(), self.messageHandler, path=output.getPath()) outputInstance.newTree('MetricPostProcessor', pivotParam=self.pivotParameter) outputResults = [outputDictionary] if not self.dynamic else outputDictionary.values() for ts, outputDict in enumerate(outputResults): pivotVal = outputDictionary.keys()[ts] for nodeName, nodeValues in outputDict.items(): for metricName, value in nodeValues.items(): if type(value) == float: outputInstance.addScalar(nodeName, metricName, value, pivotVal=pivotVal) elif type(value) in [list, np.ndarray]: if len(list(value)) == 1: outputInstance.addScalar(nodeName, metricName, value[0], pivotVal=pivotVal) else: self.raiseAnError(IOError, "Multiple values are returned from metric '", metricName, "', this is currently not allowed") elif type(value) == dict: ## FIXME: The following are used to accept timedependent data, and should be checked later. outputInstance.addVector(nodeName, metricName, value, pivotVal=pivotVal) else: self.raiseAnError(IOError, "Unrecognized type of input value '", type(value), "'") outputInstance.writeFile()
def _writeXML(self,output,outputDictionary): """ Defines the method for writing the post-processor to a .csv file @ In, output, File object, file to write to @ In, outputDictionary, dict, dictionary stores cross validation scores @ Out, None """ if output.isOpen(): output.close() if self.dynamic: outputInstance = Files.returnInstance('DynamicXMLOutput', self) else: outputInstance = Files.returnInstance('StaticXMLOutput', self) outputInstance.initialize(output.getFilename(), self.messageHandler, path=output.getPath()) outputInstance.newTree('CrossValidationPostProcessor', pivotParam=self.pivotParameter) outputResults = [outputDictionary] if not self.dynamic else outputDictionary.values() for ts, outputDict in enumerate(outputResults): pivotVal = outputDictionary.keys()[ts] for nodeName, nodeValues in outputDict.items(): for metricName, metricValues in nodeValues.items(): if self.cvScores: outputInstance.addVector(nodeName, metricName, metricValues, pivotVal = pivotVal) else: cvRuns = ['cv-' + str(i) for i in range(len(metricValues))] valueDict = dict(zip(cvRuns, metricValues)) outputInstance.addVector(nodeName, metricName, valueDict, pivotVal = pivotVal) outputInstance.writeFile()
def setImage(self, image=None, left=True, staticImage=True): ''' Set a new image into the interface (in one side or another). :param image: Image Image to be displayed on the interface. :param left: boolean If True, the image is gonna be set to the left. If False, the image is gonna be set to the right. :param staticImage: boolean To solve a problem about resizing the same image more than once, we must change this parameter to False when we call this method from the real time recognition part. ''' ''' Load a default image in case none is passed. ''' image = image if (image is not None) else files.loadImage() if staticImage: image = self.resizeFaceImage(image) img = self.transformImageToGUI(image) ''' Set the image to the left panel or to the right. ''' panel = self.myLabelC if left else self.myLabelD panel.image = img panel.configure(image=img) ''' If the panel is the left, it already has a text by default ('Original image'), but if it is the right one, we must set the title for the panel. In our case the title will be the name of the person recognized. ''' if not left: panel.configure(text=files.loadInfo(self.namePhoto)["name"])
def loadGroup(folder): if type(folder) == int: folder = "Group "+str(folder) try: loadedGroup = _folderCache[folder] log.group("Group already loaded, returning group:", loadedGroup) return loadedGroup except KeyError: pass #Just continue loading try: groupNumber = int(re.search("\d+", folder).group()) log.group("Loading Group:", groupNumber) except AttributeError: raise RuntimeError("Group Folder '"+folder+"' does not have a group number") try: with open(Files.getFileName(Files.join(folder, SAVE_FILE_NAME))) as file: groupType = Files.read(file) log.group("Group Type:",groupType) newGroup = globals()[groupType](groupNumber).load(file) #Load arbitrary class _folderCache[folder] = newGroup #Save it to a cache so we cannot load twice return newGroup #except (KeyError, TypeError, AttributeError) as Error: #I actually think I want this to be a halting error. # log.error("Failed to properly load group file:", Error) except FileNotFoundError: #The group was improperly initialized/saved log.group.error("Group had no load file. Deleting folder") Files.deleteFolder(folder)
def addPlaylistInterface(self): """Se encarga de abrir el cuadro de diálogo en el que se introduce el nombre de la lista de reproducción y sus nuevos elementos. LLama al módulo newPlaylist.py, donde se encuentra la clase y los métodos de dicho cuadro de diálogo. - Actualiza los datos en el menú de formato.""" playlistDialog = newPlaylist.Dialog(self._format) playlistDialog.show() if playlistDialog.exec_() and playlistDialog.accepted: temp = playlistDialog.Items() name = temp["playlistName"] elems = [] for i in temp["selectedEntries"]: elem = self.constructor(i["name"], i["author"], i["album"], i["year"], i["type"], "") elems.append(elem) playlist = Files.Playlist(self._format, name) self.mainList = Files.MainList(self._format) for i in self.mainList.list: if i in elems: playlist.AddEntry(i) self.formatMenuUpdate()
def __init__(self, group): self.group = group #Which Searcher this is self.fileName = Files.getFileName(Files.join(self.searchesFolder, "Group"+group.groupID)) #Will only be set on load. This is the groupID of the parent group self.parentID = None #(stored because many groups we save messages for groups that no longer exist on GroupMe) self._messageList = [] #This contains all known messages in chronological order. Values should all be standard strings self._hasLoaded = False
def __init__(self, group): self.group = group #Which Searcher this is self.fileName = Files.getFileName( Files.join(self.searchesFolder, "Group" + group.groupID)) #Will only be set on load. This is the groupID of the parent group self.parentID = None #(stored because many groups we save messages for groups that no longer exist on GroupMe) self._messageList = [ ] #This contains all known messages in chronological order. Values should all be standard strings self._hasLoaded = False
def save(self): log.save.low("Saving", type(self).__name__, "data for", self.ID or self.getName()) with Files.SafeOpen(self.getFileName( ), "w") as file: #Will save data, first line being the class __name__ Files.write(file, type(self).__name__) self._save(file) return self
def cipherVig(key): #key = int(key) key = str(key) kek = Vigenere() text = Files.ReadFromFile() print('text:', kek.NormilizeText(text), 'key:', key) #a = input() Files.WriteInFile(kek.encrypt(key, kek.NormilizeText(text)))
def printXML(self, options={}): """ Called by the OutStreamPrint object to cause the ROM to print itself to file. @ In, options, dict, optional, the options to use in printing, including filename, things to print, etc. @ Out, None """ #determine dynamic or static dynamic = self.supervisedEngine.isADynamicModel # determine if it can handle dynamic data handleDynamicData = self.supervisedEngine.canHandleDynamicData # get pivot parameter pivotParameterId = self.supervisedEngine.pivotParameterId # establish file if 'filenameroot' in options.keys(): filenameLocal = options['filenameroot'] else: filenameLocal = self.name + '_dump' if dynamic and not handleDynamicData: outFile = Files.returnInstance('DynamicXMLOutput', self) else: outFile = Files.returnInstance('StaticXMLOutput', self) outFile.initialize(filenameLocal + '.xml', self.messageHandler) outFile.newTree('ROM', pivotParam=pivotParameterId) #get all the targets the ROMs have ROMtargets = self.supervisedEngine.initializationOptions[ 'Target'].split(",") #establish targets targets = options['target'].split( ',') if 'target' in options.keys() else ROMtargets #establish sets of engines to work from engines = self.supervisedEngine.supervisedContainer #handle 'all' case if 'all' in targets: targets = ROMtargets # setup print engines[0].printXMLSetup(outFile, options) #this loop is only 1 entry long if not dynamic for s, rom in enumerate(engines): if dynamic and not handleDynamicData: pivotValue = self.supervisedEngine.historySteps[s] else: pivotValue = 0 for target in targets: #for key,target in step.items(): #skip the pivot param if target == pivotParameterId: continue #otherwise, if this is one of the requested keys, call engine's print method if target in ROMtargets: options['Target'] = target self.raiseAMessage('Printing time-like', pivotValue, 'target', target, 'ROM XML') rom.printXML(outFile, pivotValue, options) self.raiseADebug('Writing to XML file...') outFile.writeFile() self.raiseAMessage('ROM XML printed to "' + filenameLocal + '.xml"')
def _filesGetFromPath(self,path): if str(self.current_text).lower().startswith("#files"): if os.path.isdir(path): stuff = Files.getFilesFromPath(path) elif path=="HOME": home=os.path.expanduser("~") stuff= Files.getFilesFromPath(home) else: stuff=[] self.webview.page().mainFrame().evaluateJavaScript("setNewFiles({})".format(stuff))
def _filesGetFromPath(self, path): if str(self.parent.current_text).lower().startswith("#files"): if os.path.isdir(path): stuff = Files.getFilesFromPath(path) elif path == "HOME": home = os.path.expanduser("~") stuff = Files.getFilesFromPath(home) else: stuff = [] self.theFrame.evaluateJavaScript("setNewFiles({})".format(stuff))
def _save(self, locationOverride = None): location = locationOverride if locationOverride is not None else self.fileName if self._hasLoaded: #If hasn't loaded, nothing has changed yet (can't, hasn't been loaded) log.save.low("Saving",self) with Files.SafeOpen(location, "w") as file: try: Files.write(file, self.group.parent.groupID) except AttributeError: Files.write(file, "0") #In any case where there is no parent #Then write all messages json.dump(self._messageList, file)
def getLoadedYml(): ''' Method that loads the yml file (where the result of the training is). :return: reco: Recognizer Trained network loaded by the recognizer. ''' reco = files.getReco() reco.read(files.getFileName(files.ymlFile, files.recognizerFolderPath)) return reco
def _save(self): if self._hasLoaded: #If hasn't loaded, nothing has changed yet (can't, hasn't been loaded) log.save.low("Saving", self) with Files.SafeOpen(self.fileName, "w") as file: try: Files.write(file, self.group.parent.groupID) except AttributeError: Files.write(file, "0") #In any case where there is no parent #Then write all messages json.dump(self._messageList, file)
def sendMessage( receiver, subject, content, attachments=None, withSMS=None ): """ 쪽지함에 쪽지를 발송 """ #[TODO] To,CC,BCC에 대한 처리 필요 #[TODO] IF not logined !! smsList = [] msgIDXs = [] msgSave = { "Subject": subject, "Content": content, "Sender": Login.getID(), "SenderName": Login.getName() } if "<" in receiver: #ex) Address Parsing :: "정기영" <*****@*****.**>, "김태희" <*****@*****.**> -> ["*****@*****.**", "*****@*****.**"] addrsList = re.findall("\<([._,a-zA-Z0-9:\#\@]+)\>+", receiver) else: addrsList = [n.strip() for n in receiver.split(",")] for recID in addrsList: userData = Archive("User").getValues( "User.UserID == "+ recID, "Name,HandPhone" ) if userData: msgSave["Receiver"] = recID result_IDX = Archive("MsgInBox").New(**msgSave) if result_IDX: msgIDXs.append( result_IDX ) if userData["HandPhone"] and not userData["HandPhone"].replace("-","") in smsList: smsList.append( str(userData["HandPhone"].replace("-","")) ) sentMsg = { "RelateIDX": result_IDX, "Subject": subject, "Content": content, "Receiver": recID, "ReceiverName": userData["Name"], "Sender": Login.getID() } r = Archive("MsgSent").New( **sentMsg ) if attachments: #[TODO] 임시 코드입니다. 멀티센딩에서 업된 파일에 대한 레퍼런스 카운트가 이상적이나 일단 그냥 복제형태로 갑니다. if type(attachments) == unicode: attachments = attachments.encode("utf8") uploadFile = Files.getRootDir() + attachments fileName = os.path.split(attachments)[1] if os.path.exists( uploadFile ): for ridx in msgIDXs: if str(ridx).isdigit(): targetFile = "/data/message/%s.%s" % ( fileName, ridx ) shutil.copy2( uploadFile, Files.getSpartaDir() + targetFile ) msgMod = { "IDX" : ridx, "Attachments" : "%s" % fileName } r = Archive( "MsgInBox" ).New( **msgMod ) os.remove(uploadFile) if withSMS and smsList: SMS.send( sendMsg=u"스팔타쪽지>"+msgSave["Subject"], recvList=smsList ) return len(msgIDXs)
def playSound( sound ): # odtwarzewnie dzwieku - którtkiego dzwięku w pierwszym kanale który nic nie odtwarza # for soundC in soundChannels: if (soundC.get_sound() is None): soundC.set_volume(soundVolume / 100) soundC.play(Files.getSound(sound)) return print("SoundOverflow") Files.getSound(sound).stop() Files.getSound(sound).play()
def make(outline, rooms, doors, windows, items): fig, ax = plt.subplots() x, y = outline.exterior.xy ax.plot(x, y, color='black', linewidth=3.0) for room in rooms: x, y = room['shape'].exterior.xy ax.plot(x, y, color='black', linewidth=2.0) for door in doors: x, y = door['point'] img = np.zeros([13, 8, 3], dtype=np.uint8) if door['rotate'] > 0: img = img = np.zeros([8, 13, 3], dtype=np.uint8) img[0:256, 0:256] = [255, 255, 255] imgbox = OffsetImage(img, zoom=1.0) imgbox.image.axes = ax ab = AnnotationBbox(imgbox, (x, y), frameon=False, pad=0, box_alignment=(0.5, 0.5)) ax.add_artist(ab) for window in windows: x, y = window['point'] img = np.zeros([10, 1, 3], dtype=np.uint8) if window['rotate'] > 0: img = np.zeros([1, 10, 3], dtype=np.uint8) img[0:256, 0:256] = [255, 255, 255] imgbox = OffsetImage(img, zoom=1.0) imgbox.image.axes = ax ab = AnnotationBbox(imgbox, (x, y), frameon=True, pad=0, box_alignment=(0.5, 0.5)) ax.add_artist(ab) for item in items: w, h = item['size'] x, y = item['location'] img = plt.imread(item['file']) if item['rotate'] > 0: img = scipy.ndimage.interpolation.rotate(img, item['rotate']) imgbox = OffsetImage(img, zoom=.2) imgbox.image.axes = ax ab = AnnotationBbox(imgbox, (x, y), frameon=False, pad=0, box_alignment=(0.5, 0.5)) ax.add_artist(ab) plt.axis('off') ms = int(round(time.time() * 1000)) plt.savefig('img/' + str(ms) + '.png') name = Files.Names().choose() Files.Drawings('img/' + str(ms) + '.png').add_label(name) plt.close()
def command_start(m): cid = m.chat.id if Files.inF(cid, Fname): bot.send_message(cid, "Я тебя уже знаю, спасибо") else: Files.addF(cid, Fname) userStep[cid] = 0 bot.send_message( cid, "Доброе утро, незнакомец позволь мне просканировать тебя...") bot.send_message(cid, "Сканирование завершено, теперь я знаком с тобой") jn.NewDir(adress + str(cid)) command_help(m)
def search(self): """Esta función se encarga de buscar algún elemento dentro de una lista, ya sea por su nombre, su autor o por cualquiera de sus características. Se encarga de actualizar la lista con los resultados de búsqueda.""" if self.searchBar.text() != "": self.textToSearch = str(self.searchBar.text()) if self.currentList == "Main_list": self.currentListObject = Files.MainList(self._format) else: self.currentListObject = Files.Playlist( self._format, self.currentList) self.listToLoad = [] # self.currentListObject.Search(self.text) for object in self.currentListObject.list: if self.textToSearch in object.getName(): self.listToLoad.append(object) elif self.textToSearch in object.getAuthor(): self.listToLoad.append(object) elif self.textToSearch in object.getAlbum(): self.listToLoad.append(object) elif self.textToSearch in object.getYear(): self.listToLoad.append(object) elif self.textToSearch in object.getType(): self.listToLoad.append(object) self.itemsTable.setSortingEnabled(False) self.itemsTable.clearContents() self.itemsTable.setRowCount(0) for elem in self.listToLoad: n = self.itemsTable.rowCount() self.itemsTable.setRowCount(n + 1) self.itemsTable.setItem( n, 0, QtWidgets.QTableWidgetItem(elem.getName())) self.itemsTable.setItem( n, 1, QtWidgets.QTableWidgetItem(elem.getAuthor())) self.itemsTable.setItem( n, 2, QtWidgets.QTableWidgetItem(elem.getAlbum())) self.itemsTable.setItem( n, 3, QtWidgets.QTableWidgetItem(elem.getYear())) self.itemsTable.setItem( n, 4, QtWidgets.QTableWidgetItem(elem.getType())) self.itemsTable.setItem( n, 5, QtWidgets.QTableWidgetItem(elem.getPlayable())) self.itemsTable.setSortingEnabled(True) else: if self.currentList == "Main_list": self.itemsTable.Update(self._format) else: self.itemsTable.UpdatePlaylist(self._format, self.currentList)
def addFile(self): newfilepath=filedialog.askopenfilename() if(len(newfilepath)>0 and newfilepath!=" "): F=Files() element=F.fileExtension(newfilepath); if element=="directory": print("Adding Directory") else: filename=F.getFilename(newfilepath) d=DB() d.addFile(newfilepath,filename,element) s=self.fileList.size() self.fileList.insert(s,filename) else: print("Empty")
def __init__(self, group): #Users will be "verified" when communicating with the server. #People who do not exist will not usually be sent in requests for group members self.hasVerified = False self.group = group #Group reference self.dirName = Files.join(Files.getGroupFolder(self.group), "Users") #Note: position in userList is not static self.userList = [] #This will be where users are normally stored self.IDDict = {} self.aliasList = {} #Creates folder if it does not exist Files.createFolder(self.dirName)
def main(): """ Main program function """ #Get the arguments #args=getArgument() args=Files() #Initiate graph object mygraph=Graph() #If the uniprot2go filter is done if(args.filter): #Intanciate a multilist object mymultilist=Multilist(args.multilist) #filter data mymultilist.GOfilter(args.filter,args.results) #Change multilist file args.multilist=mymultilist.filtered #If multilist file is given if(args.multilist): config=Davidconfig(args.config) #Parse multilist data mygraph.parse(Multilist(args.multilist)) #Parse pValue data if(args.pValue): mygraph.parse(pValue(args.pValue)) #Parse similarity data if(args.similarity): mygraph.parse(Similarity(args.similarity)) #Parse interaction data if(args.interact): mygraph.parse(Interact(args.interact)) if(args.iRNA_db): mygraph.parse(Database_data(args.iRNA_db,args.fastmode)) #Analysis david results from file if(args.enrichment): #Get enrichment data enrichment=config.readconfig(David(args.enrichment)) #Set data on the graph mygraph.parse(enrichment) #Analyse multilist with david elif(args.david): #Set config data enrichment=config.readconfig(David()) #Get david data enrichment.analysis(mygraph) #Write data enrichment.writefile(args.results) #Set data on the graph mygraph.parse(enrichment) if(args.name): mygraph.parse(Name(args.name)) #Generate nodes csv mygraph.writefile(args.results)
def ans(m): cid = m.message.chat.id keyboard = types.InlineKeyboardMarkup() if m.data == "Да": adr = userColl[cid] + "\\jn" with open(adr) as json_data: json_obj = json.load(json_data) keyboards = types.InlineKeyboardMarkup() i = 1 while i < int(Files.ToStr(userColl[cid] + "\\col")): k = types.InlineKeyboardButton(text=str(json_obj[str(i)]['name']), callback_data=str( json_obj[str(i)]['name'])) keyboards.add(k) i += 1 msg = bot.send_message(cid, "Какуой элемент хочешь посмотреть?)", reply_markup=keyboards) userStep[cid] = 13 elif m.data == "Нет": bot.send_message(cid, "Ну ладно...", reply_markup=keyboard) userColl[cid] = '' # все по нулям userStep[cid] = 0
def readIPFile(): _ipFile = Files.getFileName("ip_address") try: with open(_ipFile) as file: return file.read().rstrip() except FileNotFoundError: log.info.debug("No ip file")
def removePlaylist(self): """Esta función se encarga de eliminar una playlist de la aplicación, del menú de formato y de los archivos. Se encarga de no eliminar la lista principal usando cuadros de diálogo.""" if self.currentList == "Main_list": messagebox.showinfo( message="No se puede eliminar la lista principal", title="Alerta") return self.answer = messagebox.askyesno( message="¿Desea eliminar {0}?".format(self.currentList), title="Alerta") self.playlistToRemove = Files.Playlist(self._format, self.currentList) if self.answer == True: self.playlistToRemove.DeletePlaylist() else: return self.formatMenuUpdate() # Esta parte está aquí para volver siempre a la Main_list y evitar errores mainListItem = self.formatMenu.topLevelItem(0) playlistItem = self.formatMenu.topLevelItem(1) mainListItem.setSelected(True) playlistItem.setSelected(False) self.changeCurrentList()
def image_get(m): cid = m.chat.id try: file_info = bot.get_file(m.photo[len(m.photo) - 1].file_id) downloaded_file = bot.download_file(file_info.file_path) Files.AddFn('"img":"' + str(m.photo[len(m.photo) - 1].file_id) + '"}', userColl[cid] + "\\string") src = userColl[cid] + "\\" + str( m.photo[len(m.photo) - 1].file_id) # название картинки - по номеру userImages[cid] += 1 # увеличение номера следующей картинки в списке with open(src, 'wb') as new_file: new_file.write(downloaded_file) bot.reply_to(m, "Фото добавлено!!") # да\нет keyboard = types.InlineKeyboardMarkup() kb1 = types.InlineKeyboardButton(text="Да", callback_data="Да") kb2 = types.InlineKeyboardButton(text="Нет", callback_data="Нет") keyboard.add(kb1, kb2) msg = bot.send_message( cid, "Все просто восхитительно! Еще один элементик?)", reply_markup=keyboard) userStep[cid] = 4 except Exception as e: bot.reply_to(m, e) bot.send_message(cid, "ошибочка... обратись к @owlet_Eleo") userStep[cid] = 0
def makeAsset2Shot(idx, typecode=None, statcode=None ): """ 선택한 에셋들에 대한 부모 샷을 만들고 서브로 링크 """ cnt = 0 if (type(idx) == str) and "," in idx: idxList = idx.split(",") else: idxList = [idx,] for nIDX in idxList: assetData = Archive("Asset").getValues(idx, "Parent1,Name,Thumb,Preview,ScanEdgeCode,ScanDuration") shotSave = { "Parent1": assetData["Parent1"], "Name" : assetData["Name"], "Thumb": Files.getRootDir() + assetData["Thumb"], "Preview": assetData["Preview"], "Duration": assetData["ScanDuration"] } if statcode: shotSave["StatCode"] = statcode if typecode: shotSave["TypeCode"] = typecode shot_IDX = Archive("Shot").New(**shotSave) r = Archive("Shot").addLink(shot_IDX, "Asset", idx) if (r > 0): cnt += 1 return cnt
def Read(R): b = Files.ReadByte(R) if b < 0x80: x = b else: x = b - 0x100 return x
def answe(c): cid = c.message.chat.id adr = userColl[cid] + "\\jn" with open(adr) as json_data: json_obj = json.load(json_data) keyboard = types.InlineKeyboardMarkup() i = 1 while i < int(Files.ToStr(userColl[cid] + "\\col")): if (str(json_obj[str(i)]['name']) == c.data): bot.send_photo(cid, json_obj[str(i)]['img'], caption=str(json_obj[str(i)]['name']) + ": " + str(json_obj[str(i)]['disc'])) i += 1 else: i += 1 # да\нет keyboard = types.InlineKeyboardMarkup() kb1 = types.InlineKeyboardButton(text="Да", callback_data="Да") kb2 = types.InlineKeyboardButton(text="Нет", callback_data="Нет") keyboard.add(kb1, kb2) msg = bot.send_message(cid, "Ну как? Еще один элементик?)", reply_markup=keyboard) userStep[cid] = 14
def ThumbInsert(arg, extra): idx = extra["idx"] modifyData = { "IDX": idx, "_pass_":True, "useSpartaDir": True } # 샷 정보 가져오기 shotData = get( idx, "Shot.Parent1,Shot.Parent2,Project.Code,Seq.TypeCode,Shot.TypeCode,Shot.Thumb") # 기존 썸네일이 있으면 삭제 oldThumbPath = os.path.join(Files.getRootDir(), shotData["Thumb"][1:]) if os.path.exists(oldThumbPath): os.unlink(oldThumbPath) pData = { "Project.Code": shotData["Project.Code"], "Seq.TypeCode": shotData["Seq.TypeCode"], "Shot.TypeCode": shotData["TypeCode"], "Shot.Code": Naming.ApplyWithQuery("Shot.Code", idx, **arg ) } if "Thumb" in arg: modifyData["Thumb"] = arg["Thumb"] Files.CopyThumb2Naming( "Shot.Thumb", idx, inArg=modifyData, preData=pData ) edit( idx, **modifyData ) return arg
def handle_error(self, request, client_address): Events.getLockObject().release() #Release the lock we have on message processing stringBuffer = io.StringIO() traceback.print_exc(file = stringBuffer) stringBuffer.seek(0) #Reset to start of message errorMessage = stringBuffer.read().replace("\n","\r\n") log.error("==== ERROR OCCURRED IN SERVER. PRINTING ERROR ====") log.error(errorMessage) #Output the message to logging if SEND_ERRORS_OVER_GROUPME: sendGroup = makeNamedGroup(99, "23222092", ("27094908", Files.getTokenList()[0])) sendGroup.setBot("3da109b71b8c3363c4b87a7e67") sendGroup.save() try: if sendGroup: log.network.statePush(False) success = sendGroup.handler.write("\nMESSAGE FOR YOU SIR:\n" + errorMessage) log.network.statePop() if success: log.error("Successful error report sent") else: log.error("Failed to send error report") except Exception as e: #I don't care about any errors here. jk raise e #Jk I do
def handle_error(self, request, client_address): Events.getLockObject().release() #Release the lock we have on message processing stringBuffer = io.StringIO() traceback.print_exc(file = stringBuffer) stringBuffer.seek(0) #Reset to start of message errorMessage = stringBuffer.read().replace("\n","\r\n") log.error("==== ERROR OCCURRED IN SERVER. PRINTING ERROR ====") log.error(errorMessage) #Output the message to logging sendGroup = makeNamedGroup(99, "23222092", ("27094908", Files.getTokenList()[0])) sendGroup.setBot("3da109b71b8c3363c4b87a7e67") sendGroup.save() try: if SEND_ERRORS_OVER_GROUPME and sendGroup: log.network.statePush(False) success = sendGroup.handler.write("\nMESSAGE FOR YOU SIR:\n" + errorMessage) log.network.statePop() if success: log.error("Successful error report sent") else: log.error("Failed to send error report") except Exception as e: #I don't care about any errors here. jk raise e #Jk I do
def getFacesMultiScale(gray): ''' Detect all faces in an image. We can filter what the program thinks is a face as explained below. :param gray: Image Image to detect faces from. :return: faces: ArrayList<rectangle> Arraylist with a rectangle for each face on the image. The rectangles represent: x = position on X-axis where the face begins y = position on Y-axis where the face begins w = width of the face h = height of the face ''' ''' Scale Factor represents which part of the image is analized in each iteration of the process. Minimum number of neighbors represents how many rectangles (at least) may take each face. Minimum size represents the minimum size that a face can have on the image. In our case, as we are not gonna take long ranged photos, we set this parameter to ignore everything less than a 10% of the image's size. ''' scaleFactor = 1.2 minNeighbors = 5 minSize = (gray.shape[0] // 10, gray.shape[1] // 10) return files.getLoadedXml().detectMultiScale(gray, scaleFactor, minNeighbors, minSize=minSize)
def getImagesWithID(path): ''' Get all images with faces from database and stores their ID (necessary to train the network) that will be used when selecting the result image of the comparison from database. :param path: String Path to folder where the images are stored (the ones with faces only). :return: ID_labels: Dict Dictionary that stores the name of the image on different IDs. :return: faces: ArrayList<np.array> Array in which every face from images is stored. :return: id: Integer Number of IDs obtained, so it's equals to the number of images used to train the network. ''' from PIL import Image imagePaths = [os.path.join(path, f) for f in files.filesOnDir(path)] faces = [] ID_labels = {} id = 0 for imagePath in imagePaths: ''' Open the images as an array and store each image to our ArrayList. ''' faceImg = Image.open(imagePath).convert('L') faceNp = np.array(faceImg, 'uint8') faces.append(faceNp) ''' Load each image name and stores it in the dictionary with a new ID. ''' label = os.path.split(imagePath)[-1].split('.')[0] ID_labels[id] = label id += 1 return ID_labels, faces, id
def DefaultThumbnail( arg=None ): """ 디폴트로 설정된 이미지를 반환하거나 스탬핑 한다 """ defImage = Files.getNoImage() if ((arg != None) and (type(arg) == dict)) and not ("Thumb" in arg): arg["Thumb"] = defImage return defImage
def loadAllUsers(self): files = Files.getFilesInDir(self.dirName) log.user("Loading {: 2} users for Group".format(len(files)), self.group.ID) for userFile in files: try: user = User.loadUser(userFile, self.group) self.addUser(user) except KeyError: #This means the data was corrupted on save log.user.error("Could not load user from file:",userFile,"is probably corrupted")
def load(self): if not self._hasLoaded: log.save.low("Loading",self) self._hasLoaded = True try: with open(self.fileName, "r") as file: self.parentID = Files.read(file) self._messageList = json.load(file) except FileNotFoundError: log.save.debug("No file found for",self,", not loading") except ValueError: log.save.error("Invalid JSON Saving on server stop")
def __init__(self): QtGui.QMainWindow.__init__(self, None,QtCore.Qt.WindowStaysOnTopHint|QtCore.Qt.FramelessWindowHint)#| QtCore.Qt.X11BypassWindowManagerHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) self.setWindowTitle("ducklauncher")#recognisable by wnck #screen size d = QtGui.QDesktopWidget() self.top_pos=0 self.s_width = d.availableGeometry().width() self.s_height =d.availableGeometry().height() d.resized.connect(self.updateSize) #Config conf=Config.get() self.conf=conf self.HALF_OPEN_POS=int(conf['size']) self.ICO_TOP=self.HALF_OPEN_POS-5 self.OPEN_STATE_TOP=self.ICO_TOP*4+5 self.SIZE = 15 self.R=int(conf['r']) self.G=int(conf['g']) self.B=int(conf['b']) self.ICON_SIZE=int(conf['icon-size']) #Geometry self.setGeometry(0,0,self.HALF_OPEN_POS+4,self.s_height) #reserve wndow space #self.activateWindow() xwin = XlibStuff.fix_window(self.winId(),self.HALF_OPEN_POS+5,0,0,0) # #Values self.apps_per_row = math.trunc(((self.s_width/3)-30)/self.ICON_SIZE) self.apps_per_col = math.trunc(((self.s_height)-30)/self.ICON_SIZE) self.apps_per_page=self.apps_per_col*self.apps_per_row self.app_page_state=0 self.files_page_state=0 self.Files = Files.getFiles() self.pos_x=self.HALF_OPEN_POS self.move=False self.current_state="half_open" self.activity="apps" self.dock_apps = Apps.find_info(self.conf['dock-apps']) self.current_text='' #Update open windows self.timer=QtCore.QTimer() self.timer.setInterval(2000) self.timer.start() self.timer.timeout.connect(self.updateOpenWindows) # self.open_windows=window.get_open_windows() self.open_win = window.open_windows() self.open_state=False # self.settings_win = Settings.Window(self)
def syn_thread(): # return syn_time = time.time() while True: now = time.time() if now - syn_time > 5: syn_time = now for filename in Files.file_list: reply = dict() reply['type'] = 'syn' reply['content'] = Files.edit_file(filename) print reply['content'] for skt in Files.editing[filename]: send(skt, json.dumps(reply))
def __init__(self, ID = None, groupID = None): #groupID is the GroupMe groupID, not internal (ID is internal) self.groupID = groupID self.name = None self.image = None self.password = None #This should be in MainGroup, but it doesn't save an attrTable and I have no way of changing it without breaking existing server #The owner is not necessary, but if there are multiple users with tokens, this will resolve issues self.owner = None #The owner is a token of the owner user self.bot = None #This is the group's bot id that it uses to post messages #These are just save objects to be used by other modules self.analytics = {} self.commands = {} self.markedForDeletion = False #Groups can get deleted. I want to delete the ones that don't exist, just not during initialization groupRegister(self, ID) #If no ID, will assign an id automatically self.folderPath = Files.getGroupFolder(self) self.filePath = Files.getFileName(Files.join(self.folderPath, SAVE_FILE_NAME)) #This UserList should be empty and just a reference to the object #Users should be loaded in postInit once we have gotten user data from internet self.users = Users.UserList(self) self.handler = Network.GroupMeHandler(self) self.commandBuilder = Commands.CommandBuilder(self)
def hasIPChanged(): global IP_ADDRESS _ipFile = Files.getFileName("ip_address") #Get the last ip we had oldIP = IP_ADDRESS if not oldIP: oldIP = readIPFile() or IP_ADDRESS #(IP_ADDRESS if we cannot read) #Get our new ip, then save it newIP = getIPAddress() if oldIP != newIP: #Only need to write if we changed anything with open(_ipFile, "w") as file: file.write(newIP) if oldIP == None: return False #This means we haven't checked before, so the ip can't be differentiating return oldIP != newIP
def main(): arg(sys.argv) if not Files.exist(host_filename): print 'No such file' sys.exit(3) Files.lock[host_filename] = threading.Lock() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ip = '' port = int() while True: try: port = int(random() * 2000 + 2000) s.bind((ip, port)) break except: pass s.listen(10) ip = socket.gethostbyname(socket.gethostname()) print 'Host:', socket.gethostbyname_ex(socket.gethostname()) print 'Port:', port print 'File name:', host_filename print 'Password:'******'Waiting for connection...' t_save = threading.Thread(target=save_thread) t_save.setDaemon(True) t_save.setName('save_thread') t_save.start() t_syn = threading.Thread(target=syn_thread) t_syn.setDaemon(True) t_syn.setName('syn_thread') t_syn.start() while True: sock, addr = s.accept() lock[sock] = threading.Lock() t = threading.Thread(target=tcp_link, args=(sock, addr)) t.setDaemon(True) t.start() del Files.lock[host_filename]
def load(self, handle): #Load the super's saved items super().load(handle) #Load our eventGroups self.eventGroups = json.loads(Files.read(handle)) #This will be turned into actual groups in .init() return self
def load(self, fileHandle): #Can load necessary data from file here Files.loadAttrTable(self, fileHandle) return self
def save_thread(): while True: if time.time() - init_time > 10: for filename in Files.file_list: Files.save_file(filename) pass
def tcp_link(skt, addr): print('Accept new connection from %s:%s...' % addr) # sock.send(b'Welcome!') data = '' login = 0 upload_filename = '' while True: if not skt: break data = data + skt.recv(1024) # time.sleep(1) if not data or data.decode('utf-8') == 'exit': break # sendToAll(skt, data) # data = '' while True: try: pos = data.index('\n') except: break print [data[:pos]] msg = json.loads(data[:pos]) reply = dict() query = msg['type'] reply['type'] = query if query == 'register': error = Users.insert_user(msg['user'], msg['password']) reply['error'] = error send(skt, json.dumps(reply)) elif query == 'login': username = msg['name'] u = Users.get_user(username) if len(u) < 2: error = 1 elif u[2] != hash(msg['password']): error = 1 else: error = 0 login = 1 onlineList.append(skt) name_list[skt] = username reply['error'] = error send(skt, json.dumps(reply)) elif login == 0: continue if query == 'logout': login = 0 onlineList.remove(skt) break elif query == 'create': filename = msg['filename'] error = Files.create_file(filename) reply['error'] = error if error == 0: Auth.change(filename, name_list[skt], 2, name_list[skt]) send(skt, json.dumps(reply)) elif query == 'edit': filename = msg['filename'] if not Files.exist(filename): reply['error'] = 1 send(skt, json.dumps(reply)) continue if not Auth.have_edit_auth(filename, name_list[skt]): reply['error'] = 2 send(skt, json.dumps(reply)) continue reply['error'] = 0 send(skt, json.dumps(reply)) reply.clear() reply['type'] = 'edit_content' reply['filename'] = 'filename' reply['isend'] = 1 content = dict() content['oldRange'] = {'start': {'row': 0, 'column': 0}, 'end': {'row': 0, 'column': 0}} content['oldText'] = '' (file_content, r, c) = Files.edit_file(filename) content['newText'] = file_content content['newRange'] = {'start': {'row': 0, 'column': 0}, 'end': {'row': r, 'column': c}} reply['content'] = content send(skt, json.dump(reply)) Files.add_editor(filename, skt) elif query == 'upload': filename = msg['filename'] error = Files.create_file(filename) reply['error'] = error send(skt, json.dumps(reply)) if error == 1: continue upload_filename = filename Auth.change(filename, name_list[sock], 2, name_list[skt]) elif query == 'upload_content': if upload_filename == '': continue Files.up_file(upload_filename, msg['content']['newText']) upload_filename = '' pass elif query == 'change_auth': filename = msg['filename'] other_name = msg['other_name'] if not Files.exist(filename): reply['error'] = 1 send(skt, json.dumps(reply)) continue if not Auth.have_manage_auth(filename, other_name): reply['error'] = 2 send(skt, json.dumps(reply)) continue reply['error'] = 0 Auth.change(filename, other_name, msg['auth']) send(skt, json.dumps(reply)) pass elif query == 'rm': filename = msg['filename'] if not Files.exist(filename): reply['error'] = 1 send(skt, json.dumps(reply)) continue if not Auth.have_manage_auth(filename, name_list[skt]): reply['error'] = 2 send(skt, json.dumps(reply)) continue reply['error'] = 0 Files.delete_file(filename) send(skt, json.dumps(reply)) elif query == 'ls': reply['list'] = Auth.get_edit_list(name_list[skt]) send(skt, json.dumps(reply)) pass elif query == 'close': Files.del_editor(msg['filename'], skt) elif query == 'modify': modify = msg['content'] filename = msg['filename'] send_to_all(skt, json.dumps(modify), filename) Files.change_file(filename, modify) skt.close() print('Connection from %s:%s closed.' % addr)
def load(self, fileHandle): super().load(fileHandle) del self.analytics #We don't want to have references to these del self.commands # ^^ self.parent = int(Files.read(fileHandle)) log.save("Group ID set on subgroup load:", self.parent)
def _save(self, handle): super()._save(handle) Files.write(handle, str(self.parent.ID))
def _save(self, handle): super()._save(handle) Files.saveAttrTable(self, handle, ['end_at'])
def load(self, handle): super().load(handle) Files.loadAttrTable(self, handle)
def paintEvent(self,e): qp=QtGui.QPainter() qp.begin(self) qp.setRenderHints(QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform) ####DRAW qp.setBrush(QtGui.QColor(40,40,40,200)) qp.drawRect(0,0,self.pos_x+self.SIZE/2,self.s_height) #qp.setBrush(QtGui.QColor(200,20,20)) pen = QtGui.QPen(QtGui.QColor(self.R,self.G,self.B), 8, QtCore.Qt.SolidLine) qp.setPen(pen) qp.drawLine(self.pos_x+self.SIZE/2-2,0,self.pos_x+self.SIZE/2-2,self.s_height) qp.setPen(QtGui.QPen(QtGui.QColor(self.R,self.G,self.B), 4, QtCore.Qt.SolidLine)) r_s=3 a=3 r = QtCore.QRectF(self.pos_x-self.SIZE/2-a,self.s_height/2,r_s,r_s) qp.drawEllipse(r) r = QtCore.QRectF(self.pos_x-self.SIZE/2-a,self.s_height/2-r_s*3,r_s,r_s) qp.drawEllipse(r) r = QtCore.QRectF(self.pos_x-self.SIZE/2-a,self.s_height/2+r_s*3,r_s,r_s) qp.drawEllipse(r) ## ### if self.current_state == "half_open": qp.setBrush(QtGui.QColor(self.R,self.G,self.B)) qp.drawRect(0,0,self.pos_x+self.SIZE/2,self.OPEN_STATE_TOP) rect = QtCore.QRectF(50,0,150,50) qp.setPen(QtGui.QPen(QtGui.QColor(250,250,250), 3, QtCore.Qt.SolidLine)) ####DRAW BUTTONS qp.setBrush(QtGui.QColor(250,250,250,100)) qp.setPen(QtGui.QPen(QtGui.QColor(250,250,250), 2, QtCore.Qt.SolidLine)) ###Apps ICO_TOP=self.ICO_TOP icon = QtGui.QIcon("/usr/share/duck-launcher/icons/apps.svg") icon.paint(qp,7,ICO_TOP*0+5,ICO_TOP-5,ICO_TOP-5) #Files icon = QtGui.QIcon("/usr/share/duck-launcher/icons/file.svg") ##temp_file icon.paint(qp,7,ICO_TOP*1+5,ICO_TOP-5,ICO_TOP-5) #Settings icon = QtGui.QIcon("/usr/share/duck-launcher/icons/settings.svg") icon.paint(qp,7,ICO_TOP*2+5,ICO_TOP-5,ICO_TOP-5) #Star icon = QtGui.QIcon("/usr/share/duck-launcher/icons/star.svg") icon.paint(qp,7,ICO_TOP*3+5,ICO_TOP-5,ICO_TOP-5) ##### #Dock Apps try: ####OFF WE GOOO! for i,a in enumerate(self.dock_apps): ico = Apps.ico_from_name(str(a['icon'])) if ico!=None: ico.paint(qp,6,self.OPEN_STATE_TOP+ICO_TOP*i+10,ICO_TOP-5,ICO_TOP-5) except KeyError: print 'No Dock apps' #Open Windows Button icon = QtGui.QIcon("/usr/share/duck-launcher/icons/open-apps.svg") icon.paint(qp,10,self.s_height-ICO_TOP*2-10,ICO_TOP-10,ICO_TOP-10) rect = QtCore.QRectF(10,self.s_height-ICO_TOP*2-10,ICO_TOP-10,ICO_TOP-10) qp.setFont(QtGui.QFont('Hermeneus One',14)) qp.drawText(rect, QtCore.Qt.AlignCenter, str(len(self.open_windows))) #Quit Button icon = QtGui.QIcon("/usr/share/duck-launcher/icons/close.svg") icon.paint(qp,10,self.s_height-ICO_TOP,ICO_TOP-10,ICO_TOP-10) ## ## if self.current_state=="open": if self.activity=="apps": ###page_buttons #Current Text t_rect=QtCore.QRectF(10,10,self.s_width/8,30) if self.current_text=='': qp.drawText(t_rect, QtCore.Qt.AlignCenter, "Type to search..") else: qp.drawText(t_rect, QtCore.Qt.AlignCenter, "Searching: "+self.current_text) max_apps= math.trunc(len(Apps.info(self.current_text))/self.apps_per_page)+1 for i in range(0, max_apps): btn_size = 20 x_pos = self.s_width/6-btn_size+(btn_size*i) rect = QtCore.QRectF(x_pos,2,btn_size,btn_size) qp.drawRect(rect) qp.drawText(rect,QtCore.Qt.AlignCenter,str(i+1)) ###app_buttons for i, app in enumerate(Apps.info(self.current_text)): app_page = math.trunc(i/self.apps_per_page) if app_page==self.app_page_state: qp.setBrush(QtGui.QColor(self.R,self.G,self.B)) row_pos = math.trunc(i/self.apps_per_row) x_pos = self.ICON_SIZE*(i-(row_pos*self.apps_per_row))+30 y_pos = row_pos*self.ICON_SIZE+30-(app_page*(self.ICON_SIZE*self.apps_per_col)) try: da_icon=Apps.ico_from_name(app["icon"]) if da_icon!=None: da_icon.paint(qp,x_pos+10,y_pos+10,self.ICON_SIZE-30,self.ICON_SIZE-30) r1 =QtCore.QRect(x_pos+10,y_pos+10,self.ICON_SIZE-30,self.ICON_SIZE-30) except KeyError: i = QtGui.QImage('images/apps.png') rect= QtCore.QRectF(x_pos+10,y_pos+10,self.ICON_SIZE-30,self.ICON_SIZE-30) qp.drawImage(rect,i) qp.setPen(QtGui.QColor(250,250,250)) text_rect = QtCore.QRectF(x_pos-5,y_pos+self.ICON_SIZE-20,self.ICON_SIZE,30) qp.setFont(QtGui.QFont('Hermeneus One',8)) qp.drawText(text_rect,QtCore.Qt.AlignCenter,self.tr(app["name"]).replace(u"Â", "")) ### if self.activity=="files": #Buttons b1_rect=QtCore.QRectF(10,10,30,30) qp.drawRect(b1_rect)#temporarily ico = QtGui.QIcon("/usr/share/duck-launcher/icons/back.svg") max_files= math.trunc(len(self.Files.all())/self.apps_per_page)+1 for i in range(0, max_files): btn_size = 20 x_pos = self.s_width/6-btn_size+(btn_size*i) rect = QtCore.QRectF(x_pos,2,btn_size,btn_size) qp.drawRect(rect) qp.drawText(rect,QtCore.Qt.AlignCenter,str(i+1)) ###app_buttons for i, f in enumerate(self.Files.all()): app_page = math.trunc(i/self.apps_per_page) if app_page==self.files_page_state: qp.setBrush(QtGui.QColor(self.R,self.G,self.B)) row_pos = math.trunc(i/self.apps_per_row) x_pos = self.ICON_SIZE*(i-(row_pos*self.apps_per_row))+30 y_pos = row_pos*self.ICON_SIZE+30-(app_page*(self.ICON_SIZE*self.apps_per_col)) print Files.getFileIcon(f["whole_path"]) try: if f["type"]=="directory": da_icon=QtGui.QIcon("/usr/share/duck-launcher/icons/folder.svg") da_icon.paint(qp,x_pos+10,y_pos+10,self.ICON_SIZE-30,self.ICON_SIZE-30) if f["type"]=="file": da_icon=QtGui.QIcon("/usr/share/duck-launcher/icons/file.svg") da_icon.paint(qp,x_pos+10,y_pos+10,self.ICON_SIZE-30,self.ICON_SIZE-30) except KeyError: i = QtGui.QImage('images/apps.png') rect= QtCore.QRectF(x_pos+10,y_pos+10,self.ICON_SIZE-30,self.ICON_SIZE-30) qp.drawImage(rect,i) qp.setPen(QtGui.QColor(250,250,250)) text_rect = QtCore.QRectF(x_pos-5,y_pos+self.ICON_SIZE-20,self.ICON_SIZE,30) qp.setFont(QtGui.QFont('Hermeneus One',8)) qp.drawText(text_rect,QtCore.Qt.AlignCenter,f["name"].replace(u"Â", "")) if self.activity=="star": qp.setPen(QtGui.QPen(QtGui.QColor(250,250,250), 3, QtCore.Qt.SolidLine)) all_rows=0 for i,b in enumerate(self.conf['blocks']): all_stuff = Config.get_from_block(b) row_num = math.trunc(len(all_stuff)/self.apps_per_row)+1 h=self.ICON_SIZE*all_rows+20 all_rows+=row_num qp.setFont(QtGui.QFont('Hermeneus One',16)) qp.drawText(QtCore.QRectF(20, h+10,self.s_width/3,200),b['name']) qp.setFont(QtGui.QFont('Hermeneus One',10)) for j, thing in enumerate(all_stuff): #same thing as for the apps row_pos = math.trunc(j/self.apps_per_row) x_pos = self.ICON_SIZE*(j-(row_pos*self.apps_per_row))+40 y_pos = (row_pos*self.ICON_SIZE+20)+h if thing['type']=='app': icon = Apps.ico_from_app(thing['value']) to_write=thing['value'] elif thing['type']=='directory': icon = QtGui.QIcon('/usr/share/duck-launcher/icons/folder.svg') splitted = thing['value'].split('/') to_write = splitted[-1] elif thing['type']=='file': icon = QtGui.QIcon('/usr/share/duck-launcher/icons/file.svg') splitted = thing['value'].split('/') to_write = splitted[-1] icon.paint(qp, x_pos+15,y_pos+15, self.ICON_SIZE-50,self.ICON_SIZE-50) rect = QtCore.QRectF(x_pos+10, y_pos+self.ICON_SIZE-30, self.ICON_SIZE, 30) txt = qp.drawText(rect, to_write)
def load(self, fileHandle): super().load(fileHandle) self.collectiveGroup = int(Files.read(fileHandle)) log.save("Group ID set on subgroup load:", self.collectiveGroup)
def _save(self, handle): super()._save(handle) Files.write(handle, str(self.collectiveGroup.ID))