def getConfigDir(): """ Module function to get the name of the directory storing the config data. @return directory name of the config dir (string) """ if configDir is not None and os.path.exists(configDir): hp = configDir else: if isWindowsPlatform(): cdn = "_eric4" else: cdn = ".eric4" hp = QDir.homePath() dn = QDir(hp) dn.mkdir(cdn) hp.append("/").append(cdn) return unicode(toNativeSeparators(hp))
def getConfigDir(): """ Global function to get the name of the directory storing the config data. @return directory name of the config dir (string) """ if sys.platform.startswith("win"): cdn = "_eric4" else: cdn = ".eric4" hp = QDir.homePath() dn = QDir(hp) dn.mkdir(cdn) hp.append("/").append(cdn) try: return unicode(QDir.toNativeSeparators(hp)) except AttributeError: return unicode(QDir.convertSeparators(hp))
def __init__(self, file='settings'): """ @type file: string @param file: the prefix of the settings files used. Used for testing. """ userDir = QDir(os.path.expanduser('~')) userDir.cd('Application Data') or userDir.cd('AppData') or userDir.cd('Library') if not userDir.cd('BootTunes'): userDir.mkdir('BootTunes') userDir.cd('BootTunes') self.settingsDir = unicode(userDir.absolutePath()) basePath = unicode(userDir.absolutePath()) self.settingsPath = settingsPath = basePath + '/' + file + '-settings' self.defaultsPath = defaultsPath = basePath + '/' + file + '-defaults' self.namesPath = namesPath = basePath + '/' + file + '-names' self.completedPath = completedPath = basePath + '/' + file + '-completed' pathsAndProperties = [ (settingsPath, 'settings'), (defaultsPath, 'artistDefaults'), (namesPath, 'artistNames'), (completedPath, 'completed') ] for pathAndProperty in pathsAndProperties: filePath = pathAndProperty[0] property = pathAndProperty[1] setattr(self, property, {}) if os.path.exists(filePath): fileObj = codecs.open(filePath, 'r') try: setattr(self, property, cPickle.load(fileObj) or {}) except (cPickle.UnpicklingError, AttributeError, EOFError, ImportError, IndexError): pass fileObj.close()
def generate_recovery_filepath(filePath): """ Based on a filePath generate the name for the recovery File. """ # check if sconcho directory in user's home directory exists sconchoDirName = QDir.homePath() + "/.sconcho" sconchoDir = QDir(sconchoDirName) if not sconchoDir.exists(): status = sconchoDir.mkdir(sconchoDirName) recoveryFileInfo = QFileInfo(filePath) recoveryFilePath = sconchoDirName + "/" + \ recoveryFileInfo.fileName() + ".recovery" return recoveryFilePath
def uploadDocument(self,doc_type, fileinfo): """ Upload document in central repository """ self._document_type = doc_type self.fileID = self.generateFileID() self.sourcePath = fileinfo.filePath() root_dir = QDir(self.networkPath) if not root_dir.exists(self._document_type): res = root_dir.mkdir(self._document_type) if res: root_doc_type_path = self.networkPath + "/" + self._document_type else: root_doc_type_path = self.networkPath else: root_doc_type_path = self.networkPath + "/" + self._document_type self.destinationPath = root_doc_type_path + "/" + self.fileID + "." + \ fileinfo.completeSuffix() srcFile = open(self.sourcePath,'rb') destinationFile = open(self.destinationPath,'wb') #srcLen = self.sourceFile.bytesAvailable() totalRead = 0 while True: inbytes = srcFile.read(4096) if not inbytes: break destinationFile.write(inbytes) totalRead += len(inbytes) #Raise signal on each block written self.emit(SIGNAL("blockWritten(int)"),totalRead) self.emit(SIGNAL("completed(QString)"),self.fileID) srcFile.close() destinationFile.close() return self.fileID
def on_pushButton_2_clicked(self): """ Slot documentation goes here. """ PF = '' Result = [] ProgBarValue = 0 # TODO: not implemented yet if self.StationBox.count() == 0: PyQt4.QtGui.QMessageBox.warning(self, "Not select Station or Model yet", "Please select correct Station name and Model Name." ,1, 0) if self.lineEdit_2.text() == '': PyQt4.QtGui.QMessageBox.warning(self, "Missing file name", "Please input the file name." ,1, 0) else: FileName = self.lineEdit_2.text() FolderDir = self.lineEdit.text() CurrentFolder = QDir(FolderDir) ResultFolder = QDir(FolderDir + "\\Result\\" ) ResultFolder2 = FolderDir + "\\Result\\" CurrentFile = QFile(FileName+".xls") # Generate the title according to the configuration file print TitleIndex for item in TitleIndex: if item != "Null": sheet1.write(0,TitleIndex.index(item)+3,item,TitleFormat) sheet1.col(TitleIndex.index(item)+3).width = 4000 ResultFolder.setCurrent(FolderDir) for fileName in glob.glob( '*.csv'): ProgBarValue = ProgBarValue +1 if ProgBarValue == 0: PyQt4.QtGui.QMessageBox.warning(self, "No CSV Files", "This folder contains no CSV files, please select again." ,1, 0) for fileName in glob.glob( '*.csv'): Num = glob.glob( '*.csv').index(fileName)+1 print glob.glob( '*.csv').index(fileName), ":", fileName self.progressBar.setValue(round(float(Num)/float(ProgBarValue)*100)) # Open CSV file and use ',' to seperate the column reader = csv.reader(open(fileName), delimiter=",") # First Column to Save File name instead of Serial No. or Test Time sheet1.row(Num).write(0, fileName, NormalFormat) for row in reader: # search every row in the csv file if row != [] and row[0] == 'Part Number' : PartNumber = row[1] sheet1.row(Num).write(1, PartNumber, NormalFormat) if row != [] and ( row[0] == 'OVERALL RESULT' or row[0] == 'DUT P/F' or row[0] == 'Overall Result' ) : PF = row[1] if (PF.find('F')>0) or (PF.find('f')>0): sheet1.row(Num).write(2, PF, FailFormat) else: sheet1.row(Num).write(2, PF, PassFormat) for item in CellIndex: if item != "Null": if reader.line_num == (StrConversionY(item)): if(row != [] and len(row)>= StrConversionX(item)): #Result.append(row[StrConversionX(item)-1]) TempResult = row[StrConversionX(item)-1] if (TempResult.find('F')>0) or (TempResult.find('f')>0): sheet1.row(Num).write(CellIndex.index(item)+3, TempResult, FailFormat) else: if(str.isalpha(TempResult) or str.istitle(TempResult)): # if the contain is not numbers. sheet1.row(Num).write(CellIndex.index(item)+3, TempResult, NormalFormat) elif(str.isspace(TempResult)): # if the contain is not numbers. sheet1.row(Num).write(CellIndex.index(item)+3, TempResult, NormalFormat) else: if row[StrConversionX(item)].find('F')>0 : sheet1.row(Num).write(CellIndex.index(item)+3, float(TempResult), ItemFailFormat) else: sheet1.row(Num).write(CellIndex.index(item)+3, float(TempResult), NormalFormat) if Result==[] : continue #for i in range(0,len(Result)): # if (Result[i].find('F')>0) or (Result[i].find('f')>0): # sheet1.row(Num).write(i+3, Result[i], FailFormat) # else: # if(str.isalpha(Result[i])): # if the contain is not numbers. # sheet1.row(Num).write(i+3, Result[i], NormalFormat) # elif(str.isspace(Result[i])): # if the contain is not numbers. # sheet1.row(Num).write(i+3, Result[i], NormalFormat) # else: # sheet1.row(Num).write(i+3, float(Result[i]), NormalFormat) #Result = [] self.textEdit.append(fileName) ################################################################## #Save to excel file, Save to the result folder in target directory if not(ResultFolder.exists()): CurrentFolder.mkdir(FolderDir+"\\Result\\") ResultFolder.setCurrent(ResultFolder2) # Set to the working folder!! if CurrentFile.exists(): book.save(FileName+'-'+time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time()))+'.xls') else: book.save(FileName+'.xls') book.save(TemporaryFile()) PyQt4.QtGui.QMessageBox.warning(self, "Done", "Conversion Done!." ,1, 0) sys.exit(app.exec_())
def __init__(self, notebooks): # Index directory of whoosh, located in notebookPath. self.schema = fields.Schema( path = fields.TEXT(stored=True), title = fields.TEXT(stored=True), content = fields.TEXT(stored=True), tags = fields.KEYWORD(commas=True)) self.notebookName = notebooks[0][0] self.notebookPath = notebooks[0][1] self.notePath = os.path.join(self.notebookPath, "notes").replace(os.sep, '/') self.htmlPath = os.path.join(self.notebookPath, "html", "notes").replace(os.sep, '/') self.indexdir = os.path.join(self.notePath, ".indexdir").replace(os.sep, '/') self.attachmentPath = os.path.join(self.notebookPath, "attachments").replace(os.sep, '/') self.configfile = os.path.join(self.notebookPath, "notebook.conf").replace(os.sep, '/') cssPath = os.path.join(self.notebookPath, "css").replace(os.sep, '/') self.cssfile = os.path.join(cssPath, "notebook.css").replace(os.sep, '/') self.searchcssfile = os.path.join(cssPath, "search-window.css").replace(os.sep, '/') self.qsettings = QSettings(self.configfile, QSettings.IniFormat) if os.path.exists(self.configfile): self.extensions = readListFromSettings(self.qsettings, "extensions") self.fileExt = self.qsettings.value("fileExt") self.attachmentImage = self.qsettings.value("attachmentImage") self.attachmentDocument = self.qsettings.value("attachmentDocument") self.version = self.qsettings.value("version") self.geometry = self.qsettings.value("geometry") self.windowstate = self.qsettings.value("windowstate") self.mathjax = self.qsettings.value('mathJax') if 'extensionsConfig' not in set(self.qsettings.childGroups()): self.extcfg = self.qsettings.value('extensionsConfig', defaultValue={}) writeDictToSettings(self.qsettings, 'extensionsConfig', self.extcfg) else: self.extcfg = readDictFromSettings(self.qsettings, 'extensionsConfig') else: self.extensions = [] self.fileExt = "" self.attachmentImage = [] self.attachmentDocument = [] self.version = None self.geometry = None self.windowstate = None self.mathjax = '' self.extcfg = {} self.faulty_exts=[] # Default enabled python-markdown extensions. # http://pythonhosted.org/Markdown/extensions/index.html if not self.extensions: self.extensions = [ 'nl2br' # newline to break , 'strkundr' # bold-italics-underline-delete style , 'codehilite' # code syntax highlight , 'fenced_code' # code block , 'headerid' # add id to headers , 'headerlink' # add anchor to headers , 'footnotes' , 'asciimathml' ] writeListToSettings(self.qsettings, "extensions", self.extensions) while True: print(self.extensions) try: markdown.markdown("",extensions=self.extensions) except AttributeError as e: remove_this = NOT_EXT.findall(e.args[0])[0] if remove_this in self.extensions: print("Found invalid markdown extension",remove_this,". Please consider removing it.") print('If you want to permanently disable this, just hit OK in the Notebook Settings dialog') self.extensions.remove(remove_this) self.faulty_exts.append(remove_this) except ImportError as e: if e.name.startswith('mdx_') and e.name[4:] in self.extensions: print('Found missing markdown extension', e.name[4:], ', temporarily disabling.') print('If you want to permanently disable this, just hit OK in the Notebook Settings dialog') self.extensions.remove(e.name[4:]) self.faulty_exts.append(e.name[4:]) elif e.name in self.extensions: print('Found missing markdown extension', e.name, ', temporarily disabling.') print('If you want to permanently disable this, just hit OK in the Notebook Settings dialog') self.extensions.remove(e.name) self.faulty_exts.append(e.name) else: self.md = markdown.Markdown(self.extensions, extension_configs=self.extcfg) break # Default file extension name if not self.fileExt: self.fileExt = ".md" self.qsettings.setValue("fileExt", self.fileExt) # Image file types that will be copied to attachmentDir # Inserted as image link if not self.attachmentImage: self.attachmentImage = [".jpg", ".jpeg", ".png", ".gif", ".svg"] self.qsettings.setValue("attachmentImage", self.attachmentImage) # Document file types that will be copied to attachmentDir # Inserted as link if not self.attachmentDocument: self.attachmentDocument = [".pdf", ".doc", ".odt"] self.qsettings.setValue("attachmentDocument", self.attachmentDocument) # Migrate notebookPath to v0.3.0 folder structure if not self.version: notebookDir = QDir(self.notebookPath) # move all markdown files to notes/ dirList = notebookDir.entryList(QDir.Dirs | QDir.NoDotAndDotDot) if 'css' in dirList: dirList.remove('css') fileList = notebookDir.entryList(['*.md', '*.mkd', '*.markdown']) notebookDir.mkdir('notes') for d in dirList + fileList: notebookDir.rename(d, os.path.join('notes', d).replace(os.sep, '/')) # remove .indexdir folder oldIndexDir = QDir(os.path.join(self.notebookPath, '.indexdir'.replace(os.sep, '/'))) indexFileList = oldIndexDir.entryList() for f in indexFileList: oldIndexDir.remove(f) notebookDir.rmdir('.indexdir') # rename notes.css to css/notebook.css oldCssFile = os.path.join(self.notebookPath, 'notes.css').replace(os.sep, '/') QDir().mkpath(cssPath) if os.path.exists(oldCssFile): QFile.rename(oldCssFile, self.cssfile) self.version = '0' if not self.mathjax: self.mathjax = 'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML' self.qsettings.setValue('mathJax', self.mathjax)
def _create_uploaded_docs_dir(self): #Creates an 'uploaded' directory where uploaded documents are moved to. uploaded_dir = QDir(self.source_directory) uploaded_dir.mkdir('uploaded')
def create_database (self, dbfile = "freshdb"): ''' This function will create the database and directory if they not exist return 0 if created with success return 1 if error creating database return 2 if database already exists ''' db = None self.db_path = QDir.toNativeSeparators("{home}/.fresh/data".format(home=QDir.homePath()).__str__()) self.db_file_path = QDir.toNativeSeparators("{file_path}/{file}".format(file_path=self.db_path, file=dbfile)).__str__() # Create the directory if not exists if not QDir(self.db_path).exists(): QDir.mkdir(self.db_path) self.d_log.debug('Created the Dir {dir}'.format(dir=self.db_path)) # Create the database file if not QFile(self.db_file_path).exists(): self.d_log.debug("Created database file {file}".format(file=self.db_file_path)) try: self.d_log.debug("Creating database") db = sqlite3.connect(self.db_file_path) # @UndefinedVariable cursor = db.cursor() cursor.execute('pragma foreign_keys=ON') # save keeping enables foreing keys ''' DEVICE SCHEMA id - UNIQUE IDENTIFIER device_addr - TEXT - unique identifier for the device device_id - TEXT - Symbolic identifier device_type - TEXT - device type subscription_id - TEXT - unique identifier of the subscription subscription_timeout - TEXT - timeout of the subscription description - TEXT - string value added_date - TEXT - ISO8601 string ("YYYY-MM-DD HH:MM:SS.SSS") last_update - TEXT - ISO8601 string ("YYYY-MM-DD HH:MM:SS.SSS") is_active - BOOL ''' cursor.execute('DROP TABLE IF EXISTS nodes;') cursor.execute(''' CREATE TABLE IF NOT EXISTS nodes( id INTEGER PRIMARY KEY NOT NULL, device_addr TEXT NOT NULL, device_id TEXT NOT NULL, device_type TEXT NOT NULL, subscription_id TEXT NOT NULL, subscription_timeout TEXT NOT NULL, description TEXT, added_date TEXT, last_update TEXT, is_active INTEGER )''') db.commit() self.d_log.info("Database created with success") return 1 # created with success except sqlite3.Error as e: # @UndefinedVariable self.d_log.error("Database Error: {0}".foramt(e.args[0])) return 0 # Error creating database finally: if db: db.close() ## save keeping - close the database connection else: self.d_log.debug("Database already exists") return 2 # database already exists
def create_new_symbol(symbolPath, data): """ This function creates a new knitting symbol as specified by the user. """ # make sure the user's symbol directory exists. If not we # create it symbolTopDir = QDir(symbolPath) if not symbolTopDir.exists(): if not symbolTopDir.mkdir(symbolPath): QMessageBox.critical(None, msg.failedToCreateDirectoryTitle, msg.failedToCreateDirectoryText % symbolPath, QMessageBox.Close) logger.error(msg.failedToCreateDirectoryText % symbolPath) return False # this should never happen since the manageKnittingSymbolDialog is # supposed to check. We'll check anyways. symbolDirPath = symbolPath + "/" + data["svgName"] symbolDir = QDir(symbolDirPath) if symbolDir.exists(): QMessageBox.critical(None, msg.symbolExistsTitle, msg.symbolExistsText % (data["category"], data["name"]), QMessageBox.Close) logger.error(msg.symbolExistsText % (data["category"], data["name"])) return False symbolDir.mkdir(symbolDirPath) # the following try/except suite attempts to return things back # to the initial state if writing fails for some reason descriptionFilePath = None symbolTargetFilePath = None try: # copy the svg file symbolTargetSvgPath = symbolDirPath + "/" + data["svgName"] + ".svg" if not QFile(data["svgPath"]).copy(symbolTargetSvgPath): QMessageBox.critical(None, msg.failedToCopySvgTitle, msg.failedToCopySvgText % symbolTargetSvgPath, QMessageBox.Close) logger.error(msg.failedToCopySvgText % symbolTargetSvgPath) raise IOError # write the description file descriptionFilePath = symbolDirPath + "/" + "description" descriptionFileHandle = QFile(descriptionFilePath) if not descriptionFileHandle.open(QIODevice.WriteOnly): QMessageBox.critical(None, msg.failedCreateDescriptionFileTitle, msg.failedCreateDescriptionFileText % (data["name"], data["category"]), QMessageBox.Close) logger.error(msg.failedCreateDescriptionFileText % (data["name"], data["category"])) raise IOError # finally try to write the content of the file try: write_description_content(descriptionFileHandle, data) except: raise IOError # this does some cleanup in case writing fails for some reason except IOError: if descriptionFilePath: symbolDir.remove(descriptionFilePath) if symbolTargetSvgPath: symbolDir.remove(symbolTargetSvgPath) symbolDir.rmdir(symbolDirPath) return False return True
def __init__(self, notebooks): # Index directory of whoosh, located in notebookPath. self.schema = fields.Schema( path = fields.TEXT(stored=True), title = fields.TEXT(stored=True), content = fields.TEXT(stored=True)) self.notebookName = notebooks[0][0] self.notebookPath = notebooks[0][1] self.notePath = os.path.join(self.notebookPath, "notes") self.htmlPath = os.path.join(self.notebookPath, "html", "notes") self.indexdir = os.path.join(self.notePath, ".indexdir") self.attachmentPath = os.path.join(self.notebookPath, "attachments") self.configfile = os.path.join(self.notebookPath, "notebook.conf") cssPath = os.path.join(self.notebookPath, "css") self.cssfile = os.path.join(cssPath, "notebook.css") self.qsettings = QSettings(self.configfile, QSettings.NativeFormat) if os.path.exists(self.configfile): self.extensions = readListFromSettings(self.qsettings, "extensions") self.fileExt = self.qsettings.value("fileExt") self.attachmentImage = self.qsettings.value("attachmentImage") self.attachmentDocument = self.qsettings.value("attachmentDocument") self.version = self.qsettings.value("version") self.geometry = self.qsettings.value("geometry") self.windowstate = self.qsettings.value("windowstate") else: self.extensions = [] self.fileExt = "" self.attachmentImage = [] self.attachmentDocument = [] self.version = None self.geometry = None self.windowstate = None # Default enabled python-markdown extensions. # http://pythonhosted.org/Markdown/extensions/index.html if not self.extensions: self.extensions = [ 'nl2br' # newline to break , 'strkundr' # bold-italics-underline-delete style , 'codehilite' # code syntax highlight , 'fenced_code' # code block , 'headerid' # add id to headers , 'headerlink' # add anchor to headers , 'footnotes' ] writeListToSettings(self.qsettings, "extensions", self.extensions) # Default file extension name if not self.fileExt: self.fileExt = ".md" self.qsettings.setValue("fileExt", self.fileExt) # Image file types that will be copied to attachmentDir # Inserted as image link if not self.attachmentImage: self.attachmentImage = [".jpg", ".jpeg", ".png", ".gif", ".svg"] self.qsettings.setValue("attachmentImage", self.attachmentImage) # Document file types that will be copied to attachmentDir # Inserted as link if not self.attachmentDocument: self.attachmentDocument = [".pdf", ".doc", ".odt"] self.qsettings.setValue("attachmentDocument", self.attachmentDocument) # Migrate notebookPath to v0.3.0 folder structure if not self.version: notebookDir = QDir(self.notebookPath) # move all markdown files to notes/ dirList = notebookDir.entryList(QDir.Dirs | QDir.NoDotAndDotDot) if 'css' in dirList: dirList.remove('css') fileList = notebookDir.entryList(['*.md', '*.mkd', '*.markdown']) notebookDir.mkdir('notes') for d in dirList + fileList: notebookDir.rename(d, os.path.join('notes', d)) # remove .indexdir folder oldIndexDir = QDir(os.path.join(self.notebookPath, '.indexdir')) indexFileList = oldIndexDir.entryList() for f in indexFileList: oldIndexDir.remove(f) notebookDir.rmdir('.indexdir') # rename notes.css to css/notebook.css oldCssFile = os.path.join(self.notebookPath, 'notes.css') QDir().mkpath(cssPath) if os.path.exists(oldCssFile): QFile.rename(oldCssFile, self.cssfile) self.version = '0'