pep8/pyflakes3 cleanups

This commit is contained in:
Juergen E. Fischer 2017-03-03 20:44:03 +01:00
parent a10c890383
commit ecc5bb508e
37 changed files with 177 additions and 187 deletions

View File

@ -64,6 +64,7 @@ def show_console():
return _console
_console_output = None
# hook for python console so all output will be redirected
@ -81,7 +82,7 @@ class PythonConsole(QDockWidget):
QDockWidget.__init__(self, parent)
self.setObjectName("PythonConsole")
self.setWindowTitle(QCoreApplication.translate("PythonConsole", "Python Console"))
#self.setAllowedAreas(Qt.BottomDockWidgetArea)
# self.setAllowedAreas(Qt.BottomDockWidgetArea)
self.console = PythonConsoleWidget(self)
self.setWidget(self.console)
@ -114,7 +115,7 @@ class PythonConsoleWidget(QWidget):
self.shellOut = ShellOutputScintilla(self)
self.tabEditorWidget = EditorTabWidget(self)
##------------ UI -------------------------------
# ------------ UI -------------------------------
self.splitterEditor = QSplitter(self)
self.splitterEditor.setOrientation(Qt.Horizontal)
@ -133,13 +134,13 @@ class PythonConsoleWidget(QWidget):
self.splitter.addWidget(self.shellOutWidget)
self.splitter.addWidget(self.shell)
#self.splitterEditor.addWidget(self.tabEditorWidget)
# self.splitterEditor.addWidget(self.tabEditorWidget)
self.splitterObj = QSplitter(self.splitterEditor)
self.splitterObj.setHandleWidth(3)
self.splitterObj.setOrientation(Qt.Horizontal)
#self.splitterObj.setSizes([0, 0])
#self.splitterObj.setStretchFactor(0, 1)
# self.splitterObj.setSizes([0, 0])
# self.splitterObj.setStretchFactor(0, 1)
self.widgetEditor = QWidget(self.splitterObj)
self.widgetFind = QWidget(self)
@ -151,9 +152,9 @@ class PythonConsoleWidget(QWidget):
self.listClassMethod.setColumnHidden(1, True)
self.listClassMethod.setAlternatingRowColors(True)
#self.splitterEditor.addWidget(self.widgetEditor)
#self.splitterObj.addWidget(self.listClassMethod)
#self.splitterObj.addWidget(self.widgetEditor)
# self.splitterEditor.addWidget(self.widgetEditor)
# self.splitterObj.addWidget(self.listClassMethod)
# self.splitterObj.addWidget(self.widgetEditor)
# Hide side editor on start up
self.splitterObj.hide()
@ -164,13 +165,13 @@ class PythonConsoleWidget(QWidget):
sizes = self.splitter.sizes()
self.splitter.setSizes(sizes)
##----------------Restore Settings------------------------------------
# ----------------Restore Settings------------------------------------
self.restoreSettingsConsole()
##------------------Toolbar Editor-------------------------------------
# ------------------Toolbar Editor-------------------------------------
## Action for Open File
# Action for Open File
openFileBt = QCoreApplication.translate("PythonConsole", "Open Script...")
self.openFileButton = QAction(self)
self.openFileButton.setCheckable(False)
@ -190,7 +191,7 @@ class PythonConsoleWidget(QWidget):
self.openInEditorButton.setIconVisibleInMenu(True)
self.openInEditorButton.setToolTip(openExtEditorBt)
self.openInEditorButton.setText(openExtEditorBt)
## Action for Save File
# Action for Save File
saveFileBt = QCoreApplication.translate("PythonConsole", "Save")
self.saveFileButton = QAction(self)
self.saveFileButton.setCheckable(False)
@ -200,7 +201,7 @@ class PythonConsoleWidget(QWidget):
self.saveFileButton.setIconVisibleInMenu(True)
self.saveFileButton.setToolTip(saveFileBt)
self.saveFileButton.setText(saveFileBt)
## Action for Save File As
# Action for Save File As
saveAsFileBt = QCoreApplication.translate("PythonConsole", "Save As...")
self.saveAsFileButton = QAction(self)
self.saveAsFileButton.setCheckable(False)
@ -210,7 +211,7 @@ class PythonConsoleWidget(QWidget):
self.saveAsFileButton.setIconVisibleInMenu(True)
self.saveAsFileButton.setToolTip(saveAsFileBt)
self.saveAsFileButton.setText(saveAsFileBt)
## Action Cut
# Action Cut
cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut")
self.cutEditorButton = QAction(self)
self.cutEditorButton.setCheckable(False)
@ -220,7 +221,7 @@ class PythonConsoleWidget(QWidget):
self.cutEditorButton.setIconVisibleInMenu(True)
self.cutEditorButton.setToolTip(cutEditorBt)
self.cutEditorButton.setText(cutEditorBt)
## Action Copy
# Action Copy
copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy")
self.copyEditorButton = QAction(self)
self.copyEditorButton.setCheckable(False)
@ -230,7 +231,7 @@ class PythonConsoleWidget(QWidget):
self.copyEditorButton.setIconVisibleInMenu(True)
self.copyEditorButton.setToolTip(copyEditorBt)
self.copyEditorButton.setText(copyEditorBt)
## Action Paste
# Action Paste
pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste")
self.pasteEditorButton = QAction(self)
self.pasteEditorButton.setCheckable(False)
@ -240,7 +241,7 @@ class PythonConsoleWidget(QWidget):
self.pasteEditorButton.setIconVisibleInMenu(True)
self.pasteEditorButton.setToolTip(pasteEditorBt)
self.pasteEditorButton.setText(pasteEditorBt)
## Action Run Script (subprocess)
# Action Run Script (subprocess)
runScriptEditorBt = QCoreApplication.translate("PythonConsole", "Run script")
self.runScriptEditorButton = QAction(self)
self.runScriptEditorButton.setCheckable(False)
@ -250,7 +251,7 @@ class PythonConsoleWidget(QWidget):
self.runScriptEditorButton.setIconVisibleInMenu(True)
self.runScriptEditorButton.setToolTip(runScriptEditorBt)
self.runScriptEditorButton.setText(runScriptEditorBt)
## Action Run Script (subprocess)
# Action Run Script (subprocess)
commentEditorBt = QCoreApplication.translate("PythonConsole", "Comment")
self.commentEditorButton = QAction(self)
self.commentEditorButton.setCheckable(False)
@ -260,7 +261,7 @@ class PythonConsoleWidget(QWidget):
self.commentEditorButton.setIconVisibleInMenu(True)
self.commentEditorButton.setToolTip(commentEditorBt)
self.commentEditorButton.setText(commentEditorBt)
## Action Run Script (subprocess)
# Action Run Script (subprocess)
uncommentEditorBt = QCoreApplication.translate("PythonConsole", "Uncomment")
self.uncommentEditorButton = QAction(self)
self.uncommentEditorButton.setCheckable(False)
@ -270,7 +271,7 @@ class PythonConsoleWidget(QWidget):
self.uncommentEditorButton.setIconVisibleInMenu(True)
self.uncommentEditorButton.setToolTip(uncommentEditorBt)
self.uncommentEditorButton.setText(uncommentEditorBt)
## Action for Object browser
# Action for Object browser
objList = QCoreApplication.translate("PythonConsole", "Object Inspector...")
self.objectListButton = QAction(self)
self.objectListButton.setCheckable(True)
@ -281,7 +282,7 @@ class PythonConsoleWidget(QWidget):
self.objectListButton.setIconVisibleInMenu(True)
self.objectListButton.setToolTip(objList)
self.objectListButton.setText(objList)
## Action for Find text
# Action for Find text
findText = QCoreApplication.translate("PythonConsole", "Find Text")
self.findTextButton = QAction(self)
self.findTextButton.setCheckable(True)
@ -292,9 +293,9 @@ class PythonConsoleWidget(QWidget):
self.findTextButton.setToolTip(findText)
self.findTextButton.setText(findText)
##----------------Toolbar Console-------------------------------------
# ----------------Toolbar Console-------------------------------------
## Action Show Editor
# Action Show Editor
showEditor = QCoreApplication.translate("PythonConsole", "Show Editor")
self.showEditorButton = QAction(self)
self.showEditorButton.setEnabled(True)
@ -304,7 +305,7 @@ class PythonConsoleWidget(QWidget):
self.showEditorButton.setIconVisibleInMenu(True)
self.showEditorButton.setToolTip(showEditor)
self.showEditorButton.setText(showEditor)
## Action for Clear button
# Action for Clear button
clearBt = QCoreApplication.translate("PythonConsole", "Clear Console")
self.clearButton = QAction(self)
self.clearButton.setCheckable(False)
@ -314,7 +315,7 @@ class PythonConsoleWidget(QWidget):
self.clearButton.setIconVisibleInMenu(True)
self.clearButton.setToolTip(clearBt)
self.clearButton.setText(clearBt)
## Action for settings
# Action for settings
optionsBt = QCoreApplication.translate("PythonConsole", "Options...")
self.optionsButton = QAction(self)
self.optionsButton.setCheckable(False)
@ -324,7 +325,7 @@ class PythonConsoleWidget(QWidget):
self.optionsButton.setIconVisibleInMenu(True)
self.optionsButton.setToolTip(optionsBt)
self.optionsButton.setText(optionsBt)
## Action menu for class
# Action menu for class
actionClassBt = QCoreApplication.translate("PythonConsole", "Import Class")
self.actionClass = QAction(self)
self.actionClass.setCheckable(False)
@ -334,7 +335,7 @@ class PythonConsoleWidget(QWidget):
self.actionClass.setIconVisibleInMenu(True)
self.actionClass.setToolTip(actionClassBt)
self.actionClass.setText(actionClassBt)
## Action for Run script
# Action for Run script
runBt = QCoreApplication.translate("PythonConsole", "Run Command")
self.runButton = QAction(self)
self.runButton.setCheckable(False)
@ -344,7 +345,7 @@ class PythonConsoleWidget(QWidget):
self.runButton.setIconVisibleInMenu(True)
self.runButton.setToolTip(runBt)
self.runButton.setText(runBt)
## Help action
# Help action
helpBt = QCoreApplication.translate("PythonConsole", "Help...")
self.helpButton = QAction(self)
self.helpButton.setCheckable(False)
@ -399,7 +400,7 @@ class PythonConsoleWidget(QWidget):
self.toolBarEditor.addSeparator()
self.toolBarEditor.addAction(self.objectListButton)
## Menu Import Class
# Menu Import Class
default_command = {
(QCoreApplication.translate("PythonConsole", "Import Processing Class"),
QgsApplication.getThemeIcon("console/iconProcessingConsole.png")):
@ -444,7 +445,7 @@ class PythonConsoleWidget(QWidget):
self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
##------------ Layout -------------------------------
# ------------ Layout -------------------------------
self.mainLayout = QGridLayout(self)
self.mainLayout.setMargin(0)
@ -462,7 +463,7 @@ class PythonConsoleWidget(QWidget):
self.layoutEditor.addWidget(self.tabEditorWidget, 1, 1, 1, 1)
self.layoutEditor.addWidget(self.widgetFind, 2, 1, 1, 1)
## Layout for the find widget
# Layout for the find widget
self.layoutFind = QGridLayout(self.widgetFind)
self.layoutFind.setContentsMargins(0, 0, 0, 0)
self.lineEditFind = QgsFilterLineEdit()
@ -500,11 +501,11 @@ class PythonConsoleWidget(QWidget):
self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1)
self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1)
##------------ Add first Tab in Editor -------------------------------
# ------------ Add first Tab in Editor -------------------------------
#self.tabEditorWidget.newTabEditor(tabName='first', filename=None)
# self.tabEditorWidget.newTabEditor(tabName='first', filename=None)
##------------ Signal -------------------------------
# ------------ Signal -------------------------------
self.findTextButton.triggered.connect(self._toggleFind)
self.objectListButton.toggled.connect(self.toggleObjectListWidget)
@ -728,6 +729,7 @@ class PythonConsoleWidget(QWidget):
self.splitterEditor.restoreState(self.settings.value("pythonConsole/splitterEditor", QByteArray()))
self.splitterObj.restoreState(self.settings.value("pythonConsole/splitterObj", QByteArray()))
if __name__ == '__main__':
a = QApplication(sys.argv)
console = PythonConsoleWidget()

View File

@ -83,7 +83,7 @@ class Editor(QsciScintilla):
def __init__(self, parent=None):
super(Editor, self).__init__(parent)
self.parent = parent
## recent modification time
# recent modification time
self.lastModified = 0
self.opening = ['(', '{', '[', "'", '"']
self.closing = [')', '}', ']', "'", '"']
@ -104,7 +104,7 @@ class Editor(QsciScintilla):
self.setFont(font)
self.setMarginsFont(font)
# Margin 0 is used for line numbers
#fm = QFontMetrics(font)
# fm = QFontMetrics(font)
fontmetrics = QFontMetrics(font)
self.setMarginsFont(font)
self.setMarginWidth(0, fontmetrics.width("0000") + 5)
@ -118,7 +118,7 @@ class Editor(QsciScintilla):
self.MARKER_NUM)
self.setMinimumHeight(120)
#self.setMinimumWidth(300)
# self.setMinimumWidth(300)
self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
self.setMatchedBraceBackgroundColor(QColor("#b7f907"))
@ -126,16 +126,16 @@ class Editor(QsciScintilla):
# Folding
self.setFolding(QsciScintilla.PlainFoldStyle)
self.setFoldMarginColors(QColor("#f4f4f4"), QColor("#f4f4f4"))
#self.setWrapMode(QsciScintilla.WrapWord)
# self.setWrapMode(QsciScintilla.WrapWord)
## Edge Mode
# Edge Mode
self.setEdgeMode(QsciScintilla.EdgeLine)
self.setEdgeColumn(80)
self.setEdgeColor(QColor("#FF0000"))
#self.setWrapMode(QsciScintilla.WrapCharacter)
# self.setWrapMode(QsciScintilla.WrapCharacter)
self.setWhitespaceVisibility(QsciScintilla.WsVisibleAfterIndent)
#self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
# self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.settingsEditor()
@ -152,14 +152,14 @@ class Editor(QsciScintilla):
self.setTabWidth(4)
self.setIndentationGuides(True)
## Disable command key
# Disable command key
ctrl, shift = self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl + shift)
## New QShortcut = ctrl+space/ctrl+alt+space for Autocomplete
# New QShortcut = ctrl+space/ctrl+alt+space for Autocomplete
self.newShortcutCS = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Space), self)
self.newShortcutCS.setContext(Qt.WidgetShortcut)
self.redoScut = QShortcut(QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Z), self)
@ -400,8 +400,8 @@ class Editor(QsciScintilla):
if not forward:
line = lineFrom
index = indexFrom
## findFirst(QString(), re bool, cs bool, wo bool, wrap, bool, forward=True)
## re = Regular Expression, cs = Case Sensitive, wo = Whole Word, wrap = Wrap Around
# findFirst(QString(), re bool, cs bool, wo bool, wrap, bool, forward=True)
# re = Regular Expression, cs = Case Sensitive, wo = Whole Word, wrap = Wrap Around
if not self.findFirst(text, re, cs, wo, wrap, forward, line, index):
notFound = True
if notFound:
@ -527,9 +527,9 @@ class Editor(QsciScintilla):
if dir not in sys.path:
sys.path.append(dir)
if name in sys.modules:
reload(sys.modules[name])
reload(sys.modules[name]) # NOQA
try:
## set creationflags for running command without shell window
# set creationflags for running command without shell window
if sys.platform.startswith('win'):
p = subprocess.Popen(['python3', filename], shell=False, stdin=subprocess.PIPE,
stderr=subprocess.PIPE, stdout=subprocess.PIPE, creationflags=0x08000000)
@ -538,7 +538,7 @@ class Editor(QsciScintilla):
stderr=subprocess.PIPE, stdout=subprocess.PIPE)
out, _traceback = p.communicate()
## Fix interrupted system call on OSX
# Fix interrupted system call on OSX
if sys.platform == 'darwin':
status = None
while status is None:
@ -618,7 +618,7 @@ class Editor(QsciScintilla):
self.SendScintilla(QsciScintilla.SCI_SETTARGETEND, len(self.text()))
pos = self.SendScintilla(QsciScintilla.SCI_SEARCHINTARGET, len(objName), objName)
index = pos - self.SendScintilla(QsciScintilla.SCI_GETCURRENTPOS)
#line, _ = self.getCursorPosition()
# line, _ = self.getCursorPosition()
self.setSelection(linenr - 1, index, linenr - 1, index + len(objName))
self.ensureLineVisible(linenr)
self.setFocus()
@ -631,7 +631,7 @@ class Editor(QsciScintilla):
try:
if not filename:
filename = self.parent.tw.currentWidget().path
#source = open(filename, 'r').read() + '\n'
# source = open(filename, 'r').read() + '\n'
if isinstance(source, type(u"")):
source = source.encode('utf-8')
if isinstance(filename, type(u"")):
@ -660,9 +660,9 @@ class Editor(QsciScintilla):
True)
self.annotate(eline, edescr, styleAnn)
self.setCursorPosition(eline, ecolumn - 1)
#self.setSelection(eline, ecolumn, eline, self.lineLength(eline)-1)
# self.setSelection(eline, ecolumn, eline, self.lineLength(eline)-1)
self.ensureLineVisible(eline)
#self.ensureCursorVisible()
# self.ensureCursorVisible()
return False
else:
self.markerDeleteAll()
@ -676,7 +676,7 @@ class Editor(QsciScintilla):
self.autoCloseBracket = self.settings.value("pythonConsole/autoCloseBracketEditor", False, type=bool)
self.autoImport = self.settings.value("pythonConsole/autoInsertionImportEditor", True, type=bool)
txt = self.text(line)[:pos]
## Close bracket automatically
# Close bracket automatically
if t in self.opening and self.autoCloseBracket:
self.beginUndoAction()
i = self.opening.index(t)
@ -698,8 +698,8 @@ class Editor(QsciScintilla):
else:
self.insert(self.closing[i])
self.endUndoAction()
## FIXES #8392 (automatically removes the redundant char
## when autoclosing brackets option is enabled)
# FIXES #8392 (automatically removes the redundant char
# when autoclosing brackets option is enabled)
elif t in [')', ']', '}'] and self.autoCloseBracket:
txt = self.text(line)
try:
@ -726,7 +726,7 @@ class Editor(QsciScintilla):
if pathfile and self.lastModified != QFileInfo(pathfile).lastModified():
self.beginUndoAction()
self.selectAll()
#fileReplaced = self.selectedText()
# fileReplaced = self.selectedText()
self.removeSelectedText()
file = open(pathfile, "r")
fileLines = file.readlines()
@ -823,7 +823,7 @@ class EditorTab(QWidget):
if overwrite:
try:
permis = os.stat(path).st_mode
#self.newEditor.lastModified = QFileInfo(path).lastModified()
# self.newEditor.lastModified = QFileInfo(path).lastModified()
os.chmod(path, permis)
except:
raise
@ -920,7 +920,7 @@ class EditorTabWidget(QTabWidget):
self.restoreTabsButton.clicked.connect(self.restoreTabs)
self.clButton.clicked.connect(self.closeRestore)
## Fixes #7653
# Fixes #7653
if sys.platform != 'darwin':
self.setDocumentMode(True)
@ -1183,7 +1183,7 @@ class EditorTabWidget(QTabWidget):
sys.path.append(pathFile)
found = True
try:
reload(pyclbr)
reload(pyclbr) # NOQA
dictObject = {}
readModule = pyclbr.readmodule(module)
readModuleFunction = pyclbr.readmodule_ex(module)

View File

@ -147,9 +147,9 @@ class ShellOutputScintilla(QsciScintilla):
"Python Console \n"
"Use iface to access QGIS API interface or Type help(iface) for more info")
## some translation string for the console header ends without '\n'
## and the first command in console will be appended at the header text.
## The following code add a '\n' at the end of the string if not present.
# some translation string for the console header ends without '\n'
# and the first command in console will be appended at the header text.
# The following code add a '\n' at the end of the string if not present.
if txtInit.endswith('\n'):
self.setText(txtInit)
else:

View File

@ -93,12 +93,12 @@ class ShellScintilla(QsciScintilla, code.InteractiveInterpreter):
self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
# not too small
#self.setMinimumSize(500, 300)
# self.setMinimumSize(500, 300)
self.setWrapMode(QsciScintilla.WrapCharacter)
self.SendScintilla(QsciScintilla.SCI_EMPTYUNDOBUFFER)
## Disable command key
# Disable command key
ctrl, shift = self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl)
@ -107,7 +107,7 @@ class ShellScintilla(QsciScintilla, code.InteractiveInterpreter):
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('Y') + ctrl)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl + shift)
## New QShortcut = ctrl+space/ctrl+alt+space for Autocomplete
# New QShortcut = ctrl+space/ctrl+alt+space for Autocomplete
self.newShortcutCSS = QShortcut(QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Space), self)
self.newShortcutCAS = QShortcut(QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_Space), self)
self.newShortcutCSS.setContext(Qt.WidgetShortcut)
@ -226,7 +226,7 @@ class ShellScintilla(QsciScintilla, code.InteractiveInterpreter):
self.setLexer(self.lexer)
## TODO: show completion list for file and directory
# TODO: show completion list for file and directory
def getText(self):
""" Get the text as a unicode string. """
@ -429,13 +429,13 @@ class ShellScintilla(QsciScintilla, code.InteractiveInterpreter):
self.showPrevious()
elif e.key() == Qt.Key_Up and not self.isListActive():
self.showNext()
## TODO: press event for auto-completion file directory
# TODO: press event for auto-completion file directory
else:
t = e.text()
self.autoCloseBracket = self.settings.value("pythonConsole/autoCloseBracket", False, type=bool)
self.autoImport = self.settings.value("pythonConsole/autoInsertionImport", True, type=bool)
txt = cmd[:index].replace('>>> ', '').replace('... ', '')
## Close bracket automatically
# Close bracket automatically
if t in self.opening and self.autoCloseBracket:
i = self.opening.index(t)
if self.hasSelectedText() and startPos != 0:
@ -444,13 +444,13 @@ class ShellScintilla(QsciScintilla, code.InteractiveInterpreter):
self.insert(self.opening[i] + selText + self.closing[i])
self.setCursorPosition(endLine, endPos + 2)
return
elif t == '(' and (re.match(r'^[ \t]*def \w+$', txt)
or re.match(r'^[ \t]*class \w+$', txt)):
elif t == '(' and (re.match(r'^[ \t]*def \w+$', txt) or
re.match(r'^[ \t]*class \w+$', txt)):
self.insert('):')
else:
self.insert(self.closing[i])
## FIXES #8392 (automatically removes the redundant char
## when autoclosing brackets option is enabled)
# FIXES #8392 (automatically removes the redundant char
# when autoclosing brackets option is enabled)
elif t in [')', ']', '}'] and self.autoCloseBracket:
txt = self.text(line)
try:
@ -531,7 +531,7 @@ class ShellScintilla(QsciScintilla, code.InteractiveInterpreter):
self.move_cursor_to_end()
self.insertFromDropPaste(stringPaste)
## Drag and drop
# Drag and drop
def dropEvent(self, e):
if e.mimeData().hasText():
stringDrag = e.mimeData().text()
@ -595,8 +595,8 @@ class ShellScintilla(QsciScintilla, code.InteractiveInterpreter):
more = self.runsource(src)
if not more:
self.buffer = []
## prevents to commands with more lines to break the console
## in the case they have a eol different from '\n'
# prevents to commands with more lines to break the console
# in the case they have a eol different from '\n'
self.setText('')
self.move_cursor_to_end()
self.displayPrompt(more)
@ -665,8 +665,8 @@ class HistoryDialog(QDialog, Ui_HistoryDialogPythonConsole):
itemsSelected = self.listView.selectionModel().selectedIndexes()
if itemsSelected:
item = itemsSelected[0].row()
## Remove item from the command history (just for the current session)
# Remove item from the command history (just for the current session)
self.parent.history.pop(item)
self.parent.historyIndex -= 1
## Remove row from the command history dialog
# Remove row from the command history dialog
self.model.removeRow(item)

View File

@ -265,7 +265,7 @@ class optionsDialog(QDialog, Ui_SettingsDialogPythonConsole):
elif settings.value("pythonConsole/autoCompleteSourceEditor") == 'fromDocAPI':
self.autoCompFromDocAPIEditor.setChecked(True)
## Setting font lexer color
# Setting font lexer color
self.defaultFontColor.setColor(QColor(settings.value("pythonConsole/defaultFontColor", QColor(Qt.black))))
self.defaultFontColorEditor.setColor(QColor(settings.value("pythonConsole/defaultFontColorEditor", QColor(Qt.black))))
self.keywordFontColor.setColor(QColor(settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen))))

View File

@ -27,7 +27,7 @@ from builtins import object
#
###############################################################################
#avoid PendingDeprecationWarning from PyQt4.uic
# avoid PendingDeprecationWarning from PyQt4.uic
import warnings
warnings.filterwarnings("ignore", category=PendingDeprecationWarning)

View File

@ -400,18 +400,18 @@ class ORTable(Table):
for idx in indexes:
if idx.isUnique and len(idx.columns) == 1:
fld = idx.fields()[idx.columns[0]]
if (fld.dataType == u"NUMBER"
and not fld.modifier
and fld.notNull
and fld not in ret):
if (fld.dataType == u"NUMBER" and
not fld.modifier and
fld.notNull and
fld not in ret):
ret.append(fld)
# and finally append the other suitable fields
for fld in self.fields():
if (fld.dataType == u"NUMBER"
and not fld.modifier
and fld.notNull
and fld not in ret):
if (fld.dataType == u"NUMBER" and
not fld.modifier and
fld.notNull and
fld not in ret):
ret.append(fld)
if onlyOne:
@ -511,15 +511,15 @@ class ORTableField(TableField):
# find out whether fields are part of primary key
for con in self.table().constraints():
if (con.type == ORTableConstraint.TypePrimaryKey
and self.name == con.column):
if (con.type == ORTableConstraint.TypePrimaryKey and
self.name == con.column):
self.primaryKey = True
break
def type2String(self):
if (u"TIMESTAMP" in self.dataType
or self.dataType in [u"DATE", u"SDO_GEOMETRY",
u"BINARY_FLOAT", u"BINARY_DOUBLE"]):
if (u"TIMESTAMP" in self.dataType or
self.dataType in [u"DATE", u"SDO_GEOMETRY",
u"BINARY_FLOAT", u"BINARY_DOUBLE"]):
return u"{}".format(self.dataType)
if self.charMaxLen in [None, -1]:
return u"{}".format(self.dataType)

View File

@ -296,7 +296,7 @@ class Database(DbItemObject):
def registerSubPluginActions(self, mainWindow):
# load plugins!
try:
exec (u"from .%s.plugins import load" % self.dbplugin().typeName(), globals())
exec(u"from .%s.plugins import load" % self.dbplugin().typeName(), globals())
except ImportError:
pass
else:

View File

@ -77,7 +77,7 @@ class LayerPreview(QgsMapCanvas):
def _clear(self):
""" remove any layers from preview canvas """
if self.item is not None:
## skip exception on RuntimeError fixes #6892
# skip exception on RuntimeError fixes #6892
try:
self.item.aboutToChange.disconnect(self.setDirty)
except RuntimeError:

View File

@ -128,16 +128,16 @@ class SqlEdit(QsciScintilla):
# Disable some shortcuts
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl
+ shift)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl +
shift)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl)
# self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl)
#self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl)
# self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl)
# Use Ctrl+Space for autocompletion
self.shortcutAutocomplete = QShortcut(QKeySequence(Qt.CTRL
+ Qt.Key_Space), self)
self.shortcutAutocomplete = QShortcut(QKeySequence(Qt.CTRL +
Qt.Key_Space), self)
self.shortcutAutocomplete.setContext(Qt.WidgetShortcut)
self.shortcutAutocomplete.activated.connect(self.autoComplete)

View File

@ -43,7 +43,7 @@ from processing.core.ProcessingLog import ProcessingLog
from processing.tools.system import isWindows, isMac
try:
from osgeo import gdal
from osgeo import gdal # NOQA
gdalAvailable = True
except:
gdalAvailable = False
@ -64,7 +64,7 @@ class GdalUtils(object):
isDarwin = False
try:
isDarwin = platform.system() == 'Darwin'
except IOError: # https://travis-ci.org/m-kuhn/QGIS#L1493-L1526
except IOError: # https://travis-ci.org/m-kuhn/QGIS#L1493-L1526
pass
if isDarwin and os.path.isfile(os.path.join(QgsApplication.prefixPath(), "bin", "gdalinfo")):
# Looks like there's a bundled gdal. Let's use it.
@ -85,7 +85,7 @@ class GdalUtils(object):
feedback.pushInfo('GDAL command output:')
success = False
retry_count = 0
while success == False:
while not success:
loglines = []
loglines.append('GDAL execution console output')
try:
@ -133,11 +133,11 @@ class GdalUtils(object):
continue
shortName = driver.ShortName
metadata = driver.GetMetadata()
#===================================================================
# ===================================================================
# if gdal.DCAP_CREATE not in metadata \
# or metadata[gdal.DCAP_CREATE] != 'YES':
# continue
#===================================================================
# ===================================================================
if gdal.DMD_EXTENSION in metadata:
extensions = metadata[gdal.DMD_EXTENSION].split('/')
if extensions:

View File

@ -138,8 +138,8 @@ class RUtils(object):
]
else:
os.chmod(RUtils.getRScriptFilename(), stat.S_IEXEC | stat.S_IREAD
| stat.S_IWRITE)
os.chmod(RUtils.getRScriptFilename(), stat.S_IEXEC | stat.S_IREAD |
stat.S_IWRITE)
command = 'R CMD BATCH --vanilla ' + RUtils.getRScriptFilename() \
+ ' ' + RUtils.getConsoleOutputFilename()

View File

@ -42,7 +42,7 @@ from processing.gui.ParametersPanel import ParametersPanel
from processing.core.ProcessingLog import ProcessingLog
from processing.core.ProcessingConfig import ProcessingConfig
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
from processing.core.parameters import ParameterRaster, ParameterVector, ParameterMultipleInput, ParameterTable, Parameter, ParameterExtent
from processing.core.parameters import ParameterRaster, ParameterVector, ParameterMultipleInput, ParameterTable, Parameter
from processing.core.outputs import OutputVector, OutputRaster, OutputTable, OutputHTML, Output
from processing.algs.gdal.GdalUtils import GdalUtils
from processing.tools import dataobjects, vector

View File

@ -36,9 +36,9 @@ import processing.tools.dataobjects
class SettingsWatcher(QObject):
settingsChanged = pyqtSignal()
settingsWatcher = SettingsWatcher()

View File

@ -102,9 +102,9 @@ class AlgorithmDialogBase(BASE, WIDGET):
self.setWindowTitle(self.alg.displayName())
#~ desktop = QDesktopWidget()
#~ if desktop.physicalDpiX() > 96:
#~ self.txtHelp.setZoomFactor(desktop.physicalDpiX() / 96)
# desktop = QDesktopWidget()
# if desktop.physicalDpiX() > 96:
# self.txtHelp.setZoomFactor(desktop.physicalDpiX() / 96)
algHelp = self.alg.shortHelp()
if algHelp is None:
@ -137,7 +137,7 @@ class AlgorithmDialogBase(BASE, WIDGET):
rq = QNetworkRequest(algHelp)
self.reply = QgsNetworkAccessManager.instance().get(rq)
self.reply.finished.connect(self.requestFinished)
except Exception as e:
except Exception:
self.tabWidget.removeTab(2)
else:
self.tabWidget.removeTab(2)

View File

@ -56,7 +56,7 @@ from processing.core.ProcessingConfig import (ProcessingConfig,
Setting)
from processing.core.Processing import Processing
from processing.gui.DirectorySelectorDialog import DirectorySelectorDialog
from processing.gui.menus import defaultMenuEntries, updateMenus, menusSettingsGroup
from processing.gui.menus import defaultMenuEntries, menusSettingsGroup
pluginPath = os.path.split(os.path.dirname(__file__))[0]

View File

@ -138,16 +138,16 @@ class ScriptEdit(QsciScintilla):
# Disable some shortcuts
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl
+ shift)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl +
shift)
self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl)
#self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl)
#self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl)
# self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl)
# self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl)
# Use Ctrl+Space for autocompletion
self.shortcutAutocomplete = QShortcut(QKeySequence(Qt.CTRL
+ Qt.Key_Space), self)
self.shortcutAutocomplete = QShortcut(QKeySequence(Qt.CTRL +
Qt.Key_Space), self)
self.shortcutAutocomplete.setContext(Qt.WidgetShortcut)
self.shortcutAutocomplete.activated.connect(self.autoComplete)

View File

@ -82,7 +82,7 @@ from processing.core.parameters import (ParameterBoolean,
_resolveLayers)
from processing.core.ProcessingConfig import ProcessingConfig
from processing.gui.FileSelectionPanel import FileSelectionPanel
from processing.core.outputs import (OutputFile, OutputRaster, OutputVector, OutputNumber,
from processing.core.outputs import (OutputFile, OutputRaster, OutputVector,
OutputString, OutputTable, OutputExtent)
from processing.tools import dataobjects
from processing.gui.MultipleInputPanel import MultipleInputPanel

View File

@ -140,10 +140,6 @@ class ModelerDialog(BASE, WIDGET):
QGraphicsView.enterEvent(self.view, e)
self.view.viewport().setCursor(Qt.ArrowCursor)
def _mousePressEvent(e):
QGraphicsView.mousePressEvent(self.view, e)
self.view.viewport().setCursor(Qt.ArrowCursor)
def _mouseReleaseEvent(e):
QGraphicsView.mouseReleaseEvent(self.view, e)
self.view.viewport().setCursor(Qt.ArrowCursor)
@ -171,7 +167,6 @@ class ModelerDialog(BASE, WIDGET):
self.view.wheelEvent = _wheelEvent
self.view.enterEvent = _enterEvent
self.view.mousePressEvent = _mousePressEvent
self.view.mousePressEvent = _mousePressEvent
self.view.mouseMoveEvent = _mouseMoveEvent
def _mimeDataInput(items):
@ -572,8 +567,8 @@ class ModelerDialog(BASE, WIDGET):
dlg.alg.pos = QPointF(pos)
from processing.modeler.ModelerGraphicItem import ModelerGraphicItem
for i, out in enumerate(dlg.alg.outputs):
dlg.alg.outputs[out].pos = dlg.alg.pos + QPointF(ModelerGraphicItem.BOX_WIDTH, (i + 1.5)
* ModelerGraphicItem.BOX_HEIGHT)
dlg.alg.outputs[out].pos = dlg.alg.pos + QPointF(ModelerGraphicItem.BOX_WIDTH, (i + 1.5) *
ModelerGraphicItem.BOX_HEIGHT)
self.alg.addAlgorithm(dlg.alg)
self.repaintModel()
self.hasChanged = True
@ -586,8 +581,8 @@ class ModelerDialog(BASE, WIDGET):
maxX = max([alg.pos.x() for alg in list(self.alg.algs.values())])
maxY = max([alg.pos.y() for alg in list(self.alg.algs.values())])
newX = min(MARGIN + BOX_WIDTH + maxX, self.CANVAS_SIZE - BOX_WIDTH)
newY = min(MARGIN + BOX_HEIGHT + maxY, self.CANVAS_SIZE
- BOX_HEIGHT)
newY = min(MARGIN + BOX_HEIGHT + maxY, self.CANVAS_SIZE -
BOX_HEIGHT)
else:
newX = MARGIN + BOX_WIDTH / 2
newY = MARGIN * 2 + BOX_HEIGHT + BOX_HEIGHT / 2

View File

@ -75,5 +75,5 @@ class AddScriptFromFileAction(ToolboxAction):
if wrongAlgs:
QMessageBox.warning(self.toolbox,
self.tr('Error reading scripts', 'AddScriptFromFileAction'),
self.tr('The following files do not contain a valid script:\n-', 'AddScriptFromFileAction')
+ "\n-".join(wrongAlgs))
self.tr('The following files do not contain a valid script:\n-', 'AddScriptFromFileAction') +
"\n-".join(wrongAlgs))

View File

@ -75,7 +75,7 @@ def getSupportedOutputVectorLayerExtensions():
if extension.lower() != 'shp':
exts.append(extension)
exts.sort()
exts.insert(0, 'shp') # shp is the default, should be the first
exts.insert(0, 'shp') # shp is the default, should be the first
return exts
@ -86,7 +86,7 @@ def getSupportedOutputRasterLayerExtensions():
if ext != 'tif' and ext not in allexts:
allexts.append(ext)
allexts.sort()
allexts.insert(0, 'tif') # tif is the default, should be the first
allexts.insert(0, 'tif') # tif is the default, should be the first
return allexts
@ -216,8 +216,8 @@ def load(fileName, name=None, crs=None, style=None):
else:
if prjSetting:
settings.setValue('/Projections/defaultBehavior', prjSetting)
raise RuntimeError('Could not load layer: ' + str(fileName)
+ '\nCheck the processing framework log to look for errors')
raise RuntimeError('Could not load layer: ' + str(fileName) +
'\nCheck the processing framework log to look for errors')
if prjSetting:
settings.setValue('/Projections/defaultBehavior', prjSetting)
@ -320,7 +320,6 @@ def exportVectorLayer(layer, supported=None):
output = getTempFilenameInTempFolder(basename)
else:
output = getTempFilename("shp")
provider = layer.dataProvider()
useSelection = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED)
if useSelection and layer.selectedFeatureCount() != 0:
writer = QgsVectorFileWriter(output, systemEncoding,
@ -388,7 +387,7 @@ def exportTable(table):
or str(table.source()).endswith('shp')
if not isDbf or not isASCII:
writer = QgsVectorFileWriter(output, systemEncoding,
layer.fields(), QgsWkbTypes.NullGeometry,
table.fields(), QgsWkbTypes.NullGeometry,
QgsCoordinateReferenceSystem('4326'))
for feat in table.getFeatures():
writer.addFeature(feat)

View File

@ -160,8 +160,8 @@ class TableField(object):
ALTER TABLE command.
"""
data_type = (self.data_type if not self.modifier or self.modifier
< 0 else '%s(%d)' % (self.data_type, self.modifier))
data_type = (self.data_type if not self.modifier or self.modifier <
0 else '%s(%d)' % (self.data_type, self.modifier))
txt = '%s %s %s' % (self._quote(self.name), data_type,
self.is_null_txt())
if self.default and len(self.default) > 0:

View File

@ -19,7 +19,6 @@
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import map
from builtins import str
from builtins import range
from builtins import object
@ -778,5 +777,5 @@ class TableWriter(object):
def addRecords(self, records):
with open(self.fileName, 'a', newline='', encoding=self.encoding) as f:
self.writer = cvs.writer(f)
self.writer = csv.writer(f)
self.writer.writerows(records)

View File

@ -568,14 +568,13 @@ class QgsPluginInstaller(QObject):
except:
error = True
infoString = (self.tr("Plugin installation failed"),
self.tr("Failed to unzip the plugin package\n{}.\nProbably it is broken".format(zipFilePath)))
self.tr("Failed to unzip the plugin package\n{}.\nProbably it is broken".format(filePath)))
if infoString is None:
updateAvailablePlugins()
loadPlugin(pluginName)
plugins.getAllInstalled(testLoad=True)
plugins.rebuild()
plugin = plugins.all()[pluginName]
if settings.contains('/PythonPlugins/' + pluginName):
if settings.value('/PythonPlugins/' + pluginName, False, bool):

View File

@ -45,7 +45,7 @@ try:
except ImportError:
from imp import reload
import qgis.utils
from qgis.core import Qgis, QgsNetworkAccessManager, QgsAuthManager, QgsWkbTypes
from qgis.core import Qgis, QgsNetworkAccessManager, QgsAuthManager
from qgis.gui import QgsMessageBar
from qgis.utils import iface, plugin_paths
from .version_compare import compareVersions, normalizeVersion, isCompatible
@ -236,10 +236,10 @@ class Repositories(QObject):
# ----------------------------------------- #
def urlParams(self):
""" return GET parameters to be added to every request """
v = str(Qgis.QGIS_VERSION_INT)
# v = str(Qgis.QGIS_VERSION_INT)
# TODO: make this proper again after 3.0 release, by uncommenting
# the line below and removing the other return line:
#return "?qgis=%d.%d" % (int(v[0]), int(v[1:3]))
# return "?qgis=%d.%d" % (int(v[0]), int(v[1:3]))
return "?qgis=3.0"
# ----------------------------------------- #
@ -354,8 +354,8 @@ class Repositories(QObject):
""" start fetching the repository given by key """
self.mRepositories[key]["state"] = 1
url = QUrl(self.mRepositories[key]["url"] + self.urlParams())
#v=str(Qgis.QGIS_VERSION_INT)
#url.addQueryItem('qgis', '.'.join([str(int(s)) for s in [v[0], v[1:3]]]) ) # don't include the bugfix version!
# v=str(Qgis.QGIS_VERSION_INT)
# url.addQueryItem('qgis', '.'.join([str(int(s)) for s in [v[0], v[1:3]]]) ) # don't include the bugfix version!
self.mRepositories[key]["QRequest"] = QNetworkRequest(url)
authcfg = self.mRepositories[key]["authcfg"]
@ -475,10 +475,10 @@ class Repositories(QObject):
qgisMaximumVersion = pluginNodes.item(i).firstChildElement("qgis_maximum_version").text().strip()
if not qgisMaximumVersion:
qgisMaximumVersion = qgisMinimumVersion[0] + ".99"
#if compatible, add the plugin to the list
# if compatible, add the plugin to the list
if not pluginNodes.item(i).firstChildElement("disabled").text().strip().upper() in ["TRUE", "YES"]:
if isCompatible(Qgis.QGIS_VERSION, qgisMinimumVersion, qgisMaximumVersion):
#add the plugin to the cache
# add the plugin to the cache
plugins.addFromRepository(plugin)
self.mRepositories[reposName]["state"] = 2
else:
@ -625,7 +625,7 @@ class Plugins(QObject):
qgisMaximumVersion = pluginMetadata("qgisMaximumVersion").strip()
if not qgisMaximumVersion:
qgisMaximumVersion = qgisMinimumVersion[0] + ".99"
#if compatible, add the plugin to the list
# if compatible, add the plugin to the list
if not isCompatible(Qgis.QGIS_VERSION, qgisMinimumVersion, qgisMaximumVersion):
error = "incompatible"
errorDetails = "%s - %s" % (qgisMinimumVersion, qgisMaximumVersion)

View File

@ -311,7 +311,7 @@ ACCEPTABLE_MISSING_DOCS = {
"QgsValueMapWidgetWrapper": ["QgsValueMapWidgetWrapper(QgsVectorLayer *vl, int fieldIdx, QWidget *editor=nullptr, QWidget *parent=nullptr)"],
"QgsRuleBasedRenderer::Rule": ["label() const ", "createFromSld(QDomElement &element, QgsWkbTypes::GeometryType geomType)", "scaleMaxDenom() const ", "scaleMinDenom() const ", "initFilter()", "dependsOnScale() const ", "toSld(QDomDocument &doc, QDomElement &element, QgsStringMap props) const ", "save(QDomDocument &doc, QgsSymbolMap &symbolMap) const ", "setLabel(const QString &label)", "symbol()"],
"QgsExpression::NodeUnaryOperator": ["op() const ", "NodeUnaryOperator(UnaryOperator op, Node *operand)", "operand() const "],
"QgsLegendModel": ["QgsLegendModel(QgsLayerTreeGroup *rootNode, QObject *parent=nullptr)"],
"QgsLegendModel": ["QgsLegendModel(QgsLayerTreeGroup *rootNode, QObject *parent=nullptr)", "ItemType", "addLayer(QgsMapLayer *mapLayer, double scaleDenominator=-1, const QString &rule=\"\", QStandardItem *parentItem=nullptr)", "setLayerSet(const QStringList &layerIds, double scaleDenominator=-1, const QString &rule=\"\")", "updateRasterClassificationItem(QStandardItem *classificationItem)", "readXML(const QDomElement &legendModelElem, const QDomDocument &doc)", "removeLayer(const QString &layerId)", "writeXML(QDomElement &composerLegendElem, QDomDocument &doc) const ", "setAutoUpdate(bool autoUpdate)", "layersChanged()", "autoUpdate()"],
"QgsAction": ["QgsAction(ActionType type, const QString &name, const QString &action, const QString &icon, bool capture)", "ActionType", "QgsAction(ActionType type, const QString &name, const QString &action, bool capture)"],
"QgsSimpleFillSymbolLayerWidget": ["setBrushStyle()", "create(const QgsVectorLayer *vl)", "offsetChanged()", "QgsSimpleFillSymbolLayerWidget(const QgsVectorLayer *vl, QWidget *parent=nullptr)", "strokeWidthChanged()", "setStrokeColor(const QColor &color)", "setColor(const QColor &color)", "strokeStyleChanged()"],
"QgsValueRelationWidgetWrapper": ["orderByKeyLessThan(const QgsValueRelationWidgetWrapper::ValueRelationItem &p1, const QgsValueRelationWidgetWrapper::ValueRelationItem &p2)", "orderByValueLessThan(const QgsValueRelationWidgetWrapper::ValueRelationItem &p1, const QgsValueRelationWidgetWrapper::ValueRelationItem &p2)", "QgsValueRelationWidgetWrapper(QgsVectorLayer *vl, int fieldIdx, QWidget *editor=nullptr, QWidget *parent=nullptr)", "createCache(const QVariantMap &config)", "None"],
@ -532,7 +532,6 @@ ACCEPTABLE_MISSING_DOCS = {
"QgsVectorFileWriter::Option": ["Option(const QString &docString, OptionType type)"],
"QgsValueMapConfigDlg": ["updateMap(const QMap< QString, QVariant > &map, bool insertNull)", "QgsValueMapConfigDlg(QgsVectorLayer *vl, int fieldIdx, QWidget *parent)"],
"QgsActionMenu": ["ActionType", "reinit()"],
"QgsLegendModel": ["ItemType", "addLayer(QgsMapLayer *mapLayer, double scaleDenominator=-1, const QString &rule=\"\", QStandardItem *parentItem=nullptr)", "setLayerSet(const QStringList &layerIds, double scaleDenominator=-1, const QString &rule=\"\")", "updateRasterClassificationItem(QStandardItem *classificationItem)", "readXML(const QDomElement &legendModelElem, const QDomDocument &doc)", "removeLayer(const QString &layerId)", "writeXML(QDomElement &composerLegendElem, QDomDocument &doc) const ", "setAutoUpdate(bool autoUpdate)", "layersChanged()", "autoUpdate()"],
"QgsRasterFormatSaveOptionsWidget": ["validateOptions(bool gui=true, bool reportOk=true)", "setFormat(const QString &format)", "setRasterLayer(QgsRasterLayer *rasterLayer)", "setPyramidsFormat(QgsRaster::RasterPyramidsFormat format)", "QgsRasterFormatSaveOptionsWidget(QWidget *parent=nullptr, const QString &format=\"GTiff\", QgsRasterFormatSaveOptionsWidget::Type type=Default, const QString &provider=\"gdal\")", "options() const ", "setProvider(const QString &provider)", "setRasterFileName(const QString &file)", "updateProfiles()", "helpOptions()", "apply()", "Type", "setType(QgsRasterFormatSaveOptionsWidget::Type type=Default)", "optionsChanged()"],
"QgsSpatialIndexCopyVisitor": ["QgsSpatialIndexCopyVisitor(SpatialIndex::ISpatialIndex *newIndex)"],
"QgsCurvePolygon": ["numInteriorRings() const ", "QgsCurvePolygon(const QgsCurvePolygon &p)", "exteriorRing() const ", "interiorRing(int i) const ", "toPolygon() const "],

View File

@ -264,7 +264,7 @@ class TestPyQgsDBManagerGpkg(unittest.TestCase):
self.assertEqual(table.name, 'testLayer')
model = table.tableDataModel(None)
self.assertEqual(model.rowCount(), 1)
self.assertEqual(model.getData(0, 0), 1) # fid
self.assertEqual(model.getData(0, 0), 1) # fid
self.assertEqual(model.getData(0, 1), 'LINESTRING (1 2,3 4)')
self.assertEqual(model.getData(0, 2), 'foo')
@ -420,12 +420,13 @@ class TestPyQgsDBManagerGpkg(unittest.TestCase):
db = connection.database()
self.assertIsNotNone(db)
tables = db.tables()
for i in range(len(tables)):
table = tables[i]
info = table.info()
# tables = db.tables()
# for i in range(len(tables)):
# table = tables[i]
# info = table.info()
connection.remove()
if __name__ == '__main__':
unittest.main()

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
"""QGIS Unit tests for the MS SQL provider.
"""QGIS Unit tests for the DB2 provider.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by

View File

@ -83,5 +83,6 @@ class TestPyQgsMssqlProvider(unittest.TestCase, ProviderTestCase):
self.assertEqual(f.attributes()[datetime_idx], QDateTime(
QDate(2004, 3, 4), QTime(13, 41, 52)))
if __name__ == '__main__':
unittest.main()

View File

@ -154,5 +154,6 @@ class TestPyQgsOracleProvider(unittest.TestCase, ProviderTestCase):
self.assertEqual(self.provider.defaultValue(1), NULL)
self.assertEqual(self.provider.defaultValue(2), "'qgis'")
if __name__ == '__main__':
unittest.main()

View File

@ -19,14 +19,10 @@ import psycopg2
import os
from qgis.core import (
QgsGeometry,
QgsPoint,
QgsVectorLayer,
QgsVectorLayerImport,
QgsFeatureRequest,
QgsFeature,
QgsTransactionGroup,
QgsField,
QgsFieldConstraints,
QgsDataProvider,
NULL,
@ -224,7 +220,7 @@ class TestPyQgsPostgresProvider(unittest.TestCase, ProviderTestCase):
uri += ' estimatedmetadata="true"'
test_layer(ql, att, val, fidval)
#### --- INT16 ----
# --- INT16 ----
# zero
test(self.dbconn, '(SELECT 0::int2 i, NULL::geometry(Point) g)', 'i', 0, 0)
# low positive
@ -236,7 +232,7 @@ class TestPyQgsPostgresProvider(unittest.TestCase, ProviderTestCase):
# max negative signed 16bit integer
test(self.dbconn, '(SELECT (-32768)::int2 i, NULL::geometry(Point) g)', 'i', -32768, 4294934528)
#### --- INT32 ----
# --- INT32 ----
# zero
test(self.dbconn, '(SELECT 0::int4 i, NULL::geometry(Point) g)', 'i', 0, 0)
# low positive
@ -248,7 +244,7 @@ class TestPyQgsPostgresProvider(unittest.TestCase, ProviderTestCase):
# max negative signed 32bit integer
test(self.dbconn, '(SELECT (-2147483648)::int4 i, NULL::geometry(Point) g)', 'i', -2147483648, 2147483648)
#### --- INT64 (FIDs are always 1 because assigned ex-novo) ----
# --- INT64 (FIDs are always 1 because assigned ex-novo) ----
# zero
test(self.dbconn, '(SELECT 0::int8 i, NULL::geometry(Point) g)', 'i', 0, 1)
# low positive
@ -289,7 +285,7 @@ class TestPyQgsPostgresProvider(unittest.TestCase, ProviderTestCase):
it = self.vl.getFeatures()
f = next(it)
f['pk'] = NULL
self.vl.addFeature(f) # Should not deadlock during an active iteration
self.vl.addFeature(f) # Should not deadlock during an active iteration
f = next(it)
def testDomainTypes(self):
@ -734,5 +730,6 @@ class TestPyQgsPostgresProviderCompoundKey(unittest.TestCase, ProviderTestCase):
def partiallyCompiledFilters(self):
return set([])
if __name__ == '__main__':
unittest.main()

View File

@ -232,7 +232,7 @@ class TestPyQgsShapefileProvider(unittest.TestCase, ProviderTestCase):
self.assertTrue(caps & QgsVectorDataProvider.CreateSpatialIndex)
self.assertTrue(caps & QgsVectorDataProvider.SelectAtId)
self.assertTrue(caps & QgsVectorDataProvider.ChangeGeometries)
#self.assertTrue(caps & QgsVectorDataProvider.ChangeFeatures)
# self.assertTrue(caps & QgsVectorDataProvider.ChangeFeatures)
# We should be really opened in read-only mode even if write capabilities are declared
self.assertEqual(vl.dataProvider().property("_debug_open_mode"), "read-only")
@ -446,7 +446,7 @@ class TestPyQgsShapefileProvider(unittest.TestCase, ProviderTestCase):
feature_count = vl.featureCount()
# Start an iterator that will open a new connection
iterator = vl.getFeatures()
f = next(iterator)
next(iterator)
# Delete a feature
self.assertTrue(vl.startEditing())
@ -549,5 +549,6 @@ class TestPyQgsShapefileProvider(unittest.TestCase, ProviderTestCase):
self.assertTrue(ds.GetLayer(0).GetFeatureCount(), original_feature_count - 1)
ds = None
if __name__ == '__main__':
unittest.main()

View File

@ -43,8 +43,8 @@ from providertestbase import ProviderTestCase
def sanitize(endpoint, x):
if len(endpoint + x) > 256:
ret = endpoint + hashlib.md5(x.encode()).hexdigest()
#print('Before: ' + endpoint + x)
#print('After: ' + ret)
# print('Before: ' + endpoint + x)
# print('After: ' + ret)
return ret
return endpoint + x.replace('?', '_').replace('&', '_').replace('<', '_').replace('>', '_').replace('"', '_').replace("'", '_').replace(' ', '_').replace(':', '_').replace('/', '_').replace('\n', '_')
@ -2363,5 +2363,6 @@ class TestPyQgsWFSProvider(unittest.TestCase, ProviderTestCase):
self.assertNotEqual(vl.dataProvider().capabilities() & vl.dataProvider().EditingCapabilities, vl.dataProvider().NoCapabilities)
self.assertEqual(vl.wkbType(), QgsWkbTypes.Point)
if __name__ == '__main__':
unittest.main()

View File

@ -13,7 +13,6 @@ __copyright__ = 'Copyright 2016, Even Rouault'
__revision__ = '$Format:%H$'
import hashlib
import os
import sys
import tempfile
import shutil
@ -88,7 +87,7 @@ class TestPyQgsWFSProviderGUI(unittest.TestCase):
# This test is quite fragile as it depends on windows manager behavior
# regarding focus, so not surprising it doesn't pass
# on other platforms than Linux.
#if 'TRAVIS_OS_NAME' in os.environ and os.environ['TRAVIS_OS_NAME'] == 'osx':
# if 'TRAVIS_OS_NAME' in os.environ and os.environ['TRAVIS_OS_NAME'] == 'osx':
# return
main_dialog = QgsProviderRegistry.instance().selectWidget("WFS")
@ -296,12 +295,13 @@ class TestPyQgsWFSProviderGUI(unittest.TestCase):
self.assertEqual(self.addWfsLayer_uri, ' restrictToRequestBBOX=\'1\' srsname=\'EPSG:4326\' typename=\'my:typename\' url=\'' + "http://" + expected_endpoint + '\' version=\'auto\' table="" sql=SELECT * FROM typename WHERE 1 = 1')
self.assertEqual(self.addWfsLayer_layer_name, 'my:typename')
#main_dialog.setProperty("hideDialogs", None)
#main_dialog.exec_()
# main_dialog.setProperty("hideDialogs", None)
# main_dialog.exec_()
def slotAddWfsLayer(self, uri, layer_name):
self.addWfsLayer_uri = uri
self.addWfsLayer_layer_name = layer_name
if __name__ == '__main__':
unittest.main()

View File

@ -14,14 +14,11 @@ __revision__ = '$Format:%H$'
import qgis # NOQA
from qgis.core import (QgsFeature, QgsGeometry, QgsPoint,
QgsProject, QgsRelation, QgsVectorLayer, NULL, QgsField,
from qgis.core import (QgsFeature, QgsProject, QgsRelation, QgsVectorLayer,
QgsValueMapFieldFormatter, QgsValueRelationFieldFormatter,
QgsRelationReferenceFieldFormatter)
QgsRelationReferenceFieldFormatter, QgsSettings)
from qgis.testing import start_app, unittest
from qgis.PyQt.QtCore import QVariant
from qgis.PyQt.QtWidgets import QTextEdit
start_app()
@ -31,6 +28,7 @@ class TestQgsValueMapFieldFormatter(unittest.TestCase):
VALUEMAP_NULL_TEXT = "{2839923C-8B7D-419E-B84B-CA2FE9B80EC7}"
def test_representValue(self):
QgsSettings().setValue("qgis/nullValue", "NULL")
layer = QgsVectorLayer("none?field=number1:integer&field=number2:double&field=text1:string&field=number3:integer&field=number4:double&field=text2:string",
"layer", "memory")
self.assertTrue(layer.isValid())
@ -198,5 +196,6 @@ class TestQgsRelationReferenceFieldFormatter(unittest.TestCase):
QgsProject.instance().removeAllMapLayers()
if __name__ == '__main__':
unittest.main()

View File

@ -12,9 +12,7 @@ __copyright__ = 'Copyright 2016, Even Rouault'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import hashlib
import os
import sys
import tempfile
import shutil
@ -273,5 +271,6 @@ class TestPyQgsNewGeoPackageLayerDialog(unittest.TestCase):
def accepted_slot(self):
self.accepted = True
if __name__ == '__main__':
unittest.main()

View File

@ -33,11 +33,7 @@ from utilities import mapSettingsString
from qgis_local_server import getLocalServer
from test_qgspallabeling_base import TestQgsPalLabeling, runSuite
from test_qgspallabeling_tests import (
TestPointBase,
TestLineBase,
suiteTests
)
from test_qgspallabeling_tests import TestPointBase, TestLineBase, suiteTests
MAPSERV = getLocalServer()
@ -237,6 +233,7 @@ class TestServerVsCanvasLine(TestServerBaseLine, TestLineBase):
super(TestServerVsCanvasLine, self).setUp()
self.configTest('pal_canvas_line', 'sp')
if __name__ == '__main__':
# NOTE: unless PAL_SUITE env var is set all test class methods will be run
# SEE: test_qgspallabeling_tests.suiteTests() to define suite