Jelajahi Sumber

Apply Black to helpers, examples, doc, and others (#1386)

This applies Black 20.8b1 to all Python examples in doc directory, Docker test script, helper files, and all remaining files from already (mostly) formatted directories (accidentally ignored files).

This enables Black checks for all directories except for gui and python/grass/ctypes.
Vaclav Petras 4 tahun lalu
induk
melakukan
ff2c2290d1

+ 74 - 53
display/d.mon/render_cmd.py

@@ -10,20 +10,20 @@ from grass.exceptions import CalledModuleError
 # read environment variables from file
 def read_env_file(env_file):
     width = height = legfile = None
-    fd = open(env_file, 'r')
+    fd = open(env_file, "r")
     if fd is None:
         grass.fatal("Unable to open file '{0}'".format(env_file))
     lines = fd.readlines()
     for l in lines:
-        if l.startswith('#'):
+        if l.startswith("#"):
             continue
-        k, v = l.rstrip('\n').split('#', 1)[0].strip().split('=', 1)
+        k, v = l.rstrip("\n").split("#", 1)[0].strip().split("=", 1)
         os.environ[k] = v
-        if width is None and k == 'GRASS_RENDER_WIDTH':
+        if width is None and k == "GRASS_RENDER_WIDTH":
             width = int(v)
-        if height is None and k == 'GRASS_RENDER_HEIGHT':
+        if height is None and k == "GRASS_RENDER_HEIGHT":
             height = int(v)
-        if legfile is None and k == 'GRASS_LEGEND_FILE':
+        if legfile is None and k == "GRASS_LEGEND_FILE":
             legfile = v
     fd.close()
 
@@ -32,85 +32,106 @@ def read_env_file(env_file):
 
     return width, height, legfile
 
+
 # run display command
 def render(cmd, mapfile):
     env = os.environ.copy()
 
     if mapfile:
-        env['GRASS_RENDER_FILE'] = mapfile
+        env["GRASS_RENDER_FILE"] = mapfile
     try:
         grass.run_command(cmd[0], env=env, **cmd[1])
     except CalledModuleError as e:
         grass.debug("Unable to render: {0}".format(e), 1)
 
+
 # update cmd file
 def update_cmd_file(cmd_file, cmd, mapfile):
-    if cmd[0] in ('d.colorlist', 'd.font', 'd.fontlist',
-                  'd.frame', 'd.info', 'd.mon', 'd.out.file',
-                  'd.redraw', 'd.to.rast', 'd.what.rast',
-                  'd.what.vect', 'd.where'):
+    if cmd[0] in (
+        "d.colorlist",
+        "d.font",
+        "d.fontlist",
+        "d.frame",
+        "d.info",
+        "d.mon",
+        "d.out.file",
+        "d.redraw",
+        "d.to.rast",
+        "d.what.rast",
+        "d.what.vect",
+        "d.where",
+    ):
         return
 
-    mode = 'w' if cmd[0] == 'd.erase' else 'a'
+    mode = "w" if cmd[0] == "d.erase" else "a"
     # update cmd file
     fd = open(cmd_file, mode)
     if fd is None:
         grass.fatal("Unable to open file '{0}'".format(cmd_file))
-    if mode == 'a':
-        frame = os.getenv('GRASS_RENDER_FRAME', None)
+    if mode == "a":
+        frame = os.getenv("GRASS_RENDER_FRAME", None)
         if frame:
-            fd.write('# GRASS_RENDER_FRAME={0}\n'.format(frame))
+            fd.write("# GRASS_RENDER_FRAME={0}\n".format(frame))
         if mapfile:
-            fd.write('# GRASS_RENDER_FILE={0}\n'.format(mapfile))
-        fd.write(' '.join(gtask.cmdtuple_to_list(cmd)))
-        fd.write('\n')
+            fd.write("# GRASS_RENDER_FILE={0}\n".format(mapfile))
+        fd.write(" ".join(gtask.cmdtuple_to_list(cmd)))
+        fd.write("\n")
     else:
-        fd.write('')
+        fd.write("")
     fd.close()
 
+
 # adjust region
 def adjust_region(width, height):
     region = grass.region()
 
     mapwidth = abs(region["e"] - region["w"])
-    mapheight = abs(region['n'] - region['s'])
+    mapheight = abs(region["n"] - region["s"])
 
     region["nsres"] = mapheight / height
     region["ewres"] = mapwidth / width
-    region['rows'] = int(round(mapheight / region["nsres"]))
-    region['cols'] = int(round(mapwidth / region["ewres"]))
-    region['cells'] = region['rows'] * region['cols']
-
-    kwdata = [('proj', 'projection'),
-              ('zone', 'zone'),
-              ('north', 'n'),
-              ('south', 's'),
-              ('east', 'e'),
-              ('west', 'w'),
-              ('cols', 'cols'),
-              ('rows', 'rows'),
-              ('e-w resol', 'ewres'),
-              ('n-s resol', 'nsres')]
-
-    grass_region = ''
+    region["rows"] = int(round(mapheight / region["nsres"]))
+    region["cols"] = int(round(mapwidth / region["ewres"]))
+    region["cells"] = region["rows"] * region["cols"]
+
+    kwdata = [
+        ("proj", "projection"),
+        ("zone", "zone"),
+        ("north", "n"),
+        ("south", "s"),
+        ("east", "e"),
+        ("west", "w"),
+        ("cols", "cols"),
+        ("rows", "rows"),
+        ("e-w resol", "ewres"),
+        ("n-s resol", "nsres"),
+    ]
+
+    grass_region = ""
     for wkey, rkey in kwdata:
-        grass_region += '%s: %s;' % (wkey, region[rkey])
+        grass_region += "%s: %s;" % (wkey, region[rkey])
+
+    os.environ["GRASS_REGION"] = grass_region
 
-    os.environ['GRASS_REGION'] = grass_region
 
 # read any input from stdin and create a temporary file
 def read_stdin(cmd):
     opt = None
 
-    if (cmd[0] == 'd.text' and not 'text' in cmd[1] and
-            (not 'input' in cmd[1] or cmd[1]['input'] == '-')):
+    if (
+        cmd[0] == "d.text"
+        and not "text" in cmd[1]
+        and (not "input" in cmd[1] or cmd[1]["input"] == "-")
+    ):
         if sys.stdin.isatty():
-            sys.stderr.write("\nPlease enter text instructions.  Enter EOF (ctrl-d) on last line to quit\n")
-        opt = 'input'
+            sys.stderr.write(
+                "\nPlease enter text instructions.  Enter EOF (ctrl-d) on last line to quit\n"
+            )
+        opt = "input"
 
     if opt:
-        tmpfile = tempfile.NamedTemporaryFile(dir=path).name + '.txt'
-        fd = open(tmpfile, 'w')
+        tmpfile = tempfile.NamedTemporaryFile(dir=path).name + ".txt"
+        fd = open(tmpfile, "w")
         while 1:
             line = sys.stdin.readline()
             if not line:
@@ -119,20 +140,21 @@ def read_stdin(cmd):
         fd.close()
         cmd[1][opt] = tmpfile
 
+
 if __name__ == "__main__":
     cmd = gtask.cmdstring_to_tuple(sys.argv[1])
-    if not cmd[0] or cmd[0] == 'd.mon':
+    if not cmd[0] or cmd[0] == "d.mon":
         sys.exit(0)
     path = os.path.dirname(os.path.abspath(__file__))
     mon = os.path.split(path)[-1]
 
-    width, height, legfile = read_env_file(os.path.join(path, 'env'))
-    if mon.startswith('wx'):
+    width, height, legfile = read_env_file(os.path.join(path, "env"))
+    if mon.startswith("wx"):
         mapfile = tempfile.NamedTemporaryFile(dir=path).name
-        if cmd[0] in ('d.barscale', 'd.legend', 'd.northarrow', 'd.legend.vect'):
-            mapfile += '.png'
+        if cmd[0] in ("d.barscale", "d.legend", "d.northarrow", "d.legend.vect"):
+            mapfile += ".png"
         else:
-            mapfile += '.ppm'
+            mapfile += ".ppm"
     else:
         mapfile = None
         adjust_region(width, height)
@@ -140,9 +162,8 @@ if __name__ == "__main__":
     read_stdin(cmd)
 
     render(cmd, mapfile)
-    update_cmd_file(os.path.join(path, 'cmd'), cmd, mapfile)
-    if cmd[0] == 'd.erase' and os.path.exists(legfile):
+    update_cmd_file(os.path.join(path, "cmd"), cmd, mapfile)
+    if cmd[0] == "d.erase" and os.path.exists(legfile):
         os.remove(legfile)
 
-
     sys.exit(0)

+ 12 - 7
doc/gui/wxpython/example/dialogs.py

@@ -43,8 +43,9 @@ class ExampleMapDialog(SimpleDialog):
         SimpleDialog.__init__(self, parent, title)
 
         # here is the place to determine element type
-        self.element = gselect.Select(parent=self.panel, type='raster',
-                                      size=globalvar.DIALOG_GSELECT_SIZE)
+        self.element = gselect.Select(
+            parent=self.panel, type="raster", size=globalvar.DIALOG_GSELECT_SIZE
+        )
 
         self._layout()
 
@@ -52,11 +53,15 @@ class ExampleMapDialog(SimpleDialog):
 
     def _layout(self):
         """!Do layout"""
-        self.dataSizer.Add(item=wx.StaticText(parent=self.panel,
-                                              label=_("Name of raster map:")),
-                           proportion=0, flag=wx.ALL, border=1)
-        self.dataSizer.Add(self.element, proportion=0,
-                           flag=wx.EXPAND | wx.ALL, border=1)
+        self.dataSizer.Add(
+            item=wx.StaticText(parent=self.panel, label=_("Name of raster map:")),
+            proportion=0,
+            flag=wx.ALL,
+            border=1,
+        )
+        self.dataSizer.Add(
+            self.element, proportion=0, flag=wx.EXPAND | wx.ALL, border=1
+        )
         self.panel.SetSizer(self.sizer)
         self.sizer.Fit(self)
 

+ 152 - 80
doc/gui/wxpython/example/frame.py

@@ -21,7 +21,7 @@ import wx
 
 # this enables to run application standalone (> python example/frame.py )
 if __name__ == "__main__":
-    sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "gui", "wxpython"))
+    sys.path.append(os.path.join(os.environ["GISBASE"], "etc", "gui", "wxpython"))
 
 # i18n is taken care of in the grass library code.
 # So we need to import it before any of the GUI code.
@@ -61,9 +61,16 @@ class ExampleMapFrame(SingleMapFrame):
     @see IClassMapFrame in iclass.frame
     """
 
-    def __init__(self, parent, giface, title=_("Example Tool"),
-                 toolbars=["MiscToolbar", "MapToolbar", "MainToolbar"],
-                 size=(800, 600), name='exampleWindow', **kwargs):
+    def __init__(
+        self,
+        parent,
+        giface,
+        title=_("Example Tool"),
+        toolbars=["MiscToolbar", "MapToolbar", "MainToolbar"],
+        size=(800, 600),
+        name="exampleWindow",
+        **kwargs,
+    ):
         """!Map Frame constructor
 
         @param parent (no parent is expected)
@@ -71,8 +78,9 @@ class ExampleMapFrame(SingleMapFrame):
         @param toolbars list of active toolbars (default value represents all toolbars)
         @param size default size
         """
-        SingleMapFrame.__init__(self, parent=parent, title=title,
-                                name=name, Map=Map(), **kwargs)
+        SingleMapFrame.__init__(
+            self, parent=parent, title=title, name=name, Map=Map(), **kwargs
+        )
 
         # Place debug message where appropriate
         # and set debug level from 1 to 5 (higher to lower level functions).
@@ -85,7 +93,7 @@ class ExampleMapFrame(SingleMapFrame):
         #
         toolbarsCopy = toolbars[:]
         # workaround to have the same toolbar order on all platforms
-        if sys.platform == 'win32':
+        if sys.platform == "win32":
             toolbarsCopy.reverse()
 
         for toolbar in toolbarsCopy:
@@ -94,22 +102,25 @@ class ExampleMapFrame(SingleMapFrame):
         self.mapWindowProperties = MapWindowProperties()
         self.mapWindowProperties.setValuesFromUserSettings()
         self.mapWindowProperties.autoRenderChanged.connect(
-            lambda value: self.OnRender(None) if value else None)
+            lambda value: self.OnRender(None) if value else None
+        )
         #
         # Add statusbar
         #
 
         # choose items in statusbar choice, which makes sense for your application
-        self.statusbarItems = [sb.SbCoordinates,
-                               sb.SbRegionExtent,
-                               sb.SbCompRegionExtent,
-                               sb.SbShowRegion,
-                               sb.SbAlignExtent,
-                               sb.SbResolution,
-                               sb.SbDisplayGeometry,
-                               sb.SbMapScale,
-                               sb.SbGoTo,
-                               sb.SbProjection]
+        self.statusbarItems = [
+            sb.SbCoordinates,
+            sb.SbRegionExtent,
+            sb.SbCompRegionExtent,
+            sb.SbShowRegion,
+            sb.SbAlignExtent,
+            sb.SbResolution,
+            sb.SbDisplayGeometry,
+            sb.SbMapScale,
+            sb.SbGoTo,
+            sb.SbProjection,
+        ]
 
         # create statusbar and its manager
         statusbar = self.CreateStatusBar(number=4, style=0)
@@ -117,16 +128,25 @@ class ExampleMapFrame(SingleMapFrame):
         self.statusbarManager = sb.SbManager(mapframe=self, statusbar=statusbar)
 
         # fill statusbar manager
-        self.statusbarManager.AddStatusbarItemsByClass(self.statusbarItems,
-                                                       mapframe=self, statusbar=statusbar)
-        self.statusbarManager.AddStatusbarItem(sb.SbMask(self, statusbar=statusbar, position=2))
-        self.statusbarManager.AddStatusbarItem(sb.SbRender(self, statusbar=statusbar, position=3))
+        self.statusbarManager.AddStatusbarItemsByClass(
+            self.statusbarItems, mapframe=self, statusbar=statusbar
+        )
+        self.statusbarManager.AddStatusbarItem(
+            sb.SbMask(self, statusbar=statusbar, position=2)
+        )
+        self.statusbarManager.AddStatusbarItem(
+            sb.SbRender(self, statusbar=statusbar, position=3)
+        )
 
         self.statusbarManager.Update()
 
         # create map window
-        self.MapWindow = BufferedMapWindow(parent=self, Map=self.GetMap(),
-                                           properties=self.mapWindowProperties, giface=self)
+        self.MapWindow = BufferedMapWindow(
+            parent=self,
+            Map=self.GetMap(),
+            properties=self.mapWindowProperties,
+            giface=self,
+        )
         self._setUpMapWindow(self.MapWindow)
         self.MapWindow.InitZoomHistory()
 
@@ -179,17 +199,30 @@ class ExampleMapFrame(SingleMapFrame):
         """!Add mapwindow (and other widgets) to aui manager"""
         window = self.GetWindow()
         name = "mainWindow"
-        self._mgr.AddPane(window, wx.aui.AuiPaneInfo().
-                          Name(name).CentrePane().
-                          Dockable(False).CloseButton(False).DestroyOnClose(True).
-                          Layer(0))
+        self._mgr.AddPane(
+            window,
+            wx.aui.AuiPaneInfo()
+            .Name(name)
+            .CentrePane()
+            .Dockable(False)
+            .CloseButton(False)
+            .DestroyOnClose(True)
+            .Layer(0),
+        )
 
         window = self.info.GetControl()
         name = "infoText"
-        self._mgr.AddPane(window, wx.aui.AuiPaneInfo().
-                          Name(name).Caption(_("Raster Info")).MinSize((250, -1)).
-                          Dockable(True).CloseButton(False).
-                          Layer(0).Left())
+        self._mgr.AddPane(
+            window,
+            wx.aui.AuiPaneInfo()
+            .Name(name)
+            .Caption(_("Raster Info"))
+            .MinSize((250, -1))
+            .Dockable(True)
+            .CloseButton(False)
+            .Layer(0)
+            .Left(),
+        )
 
     def AddToolbar(self, name):
         """!Add defined toolbar to the window
@@ -203,59 +236,87 @@ class ExampleMapFrame(SingleMapFrame):
         if name == "MapToolbar":
             self.toolbars[name] = ExampleMapToolbar(self, self._toolSwitcher)
 
-            self._mgr.AddPane(self.toolbars[name],
-                              wx.aui.AuiPaneInfo().
-                              Name(name).Caption(_("Map Toolbar")).
-                              ToolbarPane().Top().
-                              LeftDockable(False).RightDockable(False).
-                              BottomDockable(False).TopDockable(True).
-                              CloseButton(False).Layer(1).Row(1).
-                              BestSize((self.toolbars[name].GetBestSize())))
+            self._mgr.AddPane(
+                self.toolbars[name],
+                wx.aui.AuiPaneInfo()
+                .Name(name)
+                .Caption(_("Map Toolbar"))
+                .ToolbarPane()
+                .Top()
+                .LeftDockable(False)
+                .RightDockable(False)
+                .BottomDockable(False)
+                .TopDockable(True)
+                .CloseButton(False)
+                .Layer(1)
+                .Row(1)
+                .BestSize((self.toolbars[name].GetBestSize())),
+            )
 
         if name == "MiscToolbar":
             self.toolbars[name] = ExampleMiscToolbar(self)
 
-            self._mgr.AddPane(self.toolbars[name],
-                              wx.aui.AuiPaneInfo().
-                              Name(name).Caption(_("Misc Toolbar")).
-                              ToolbarPane().Top().
-                              LeftDockable(False).RightDockable(False).
-                              BottomDockable(False).TopDockable(True).
-                              CloseButton(False).Layer(1).Row(1).
-                              BestSize((self.toolbars[name].GetBestSize())))
+            self._mgr.AddPane(
+                self.toolbars[name],
+                wx.aui.AuiPaneInfo()
+                .Name(name)
+                .Caption(_("Misc Toolbar"))
+                .ToolbarPane()
+                .Top()
+                .LeftDockable(False)
+                .RightDockable(False)
+                .BottomDockable(False)
+                .TopDockable(True)
+                .CloseButton(False)
+                .Layer(1)
+                .Row(1)
+                .BestSize((self.toolbars[name].GetBestSize())),
+            )
 
         if name == "MainToolbar":
             self.toolbars[name] = ExampleMainToolbar(self)
 
-            self._mgr.AddPane(self.toolbars[name],
-                              wx.aui.AuiPaneInfo().
-                              Name(name).Caption(_("Main Toolbar")).
-                              ToolbarPane().Top().
-                              LeftDockable(False).RightDockable(False).
-                              BottomDockable(False).TopDockable(True).
-                              CloseButton(False).Layer(1).Row(1).
-                              BestSize((self.toolbars[name].GetBestSize())))
+            self._mgr.AddPane(
+                self.toolbars[name],
+                wx.aui.AuiPaneInfo()
+                .Name(name)
+                .Caption(_("Main Toolbar"))
+                .ToolbarPane()
+                .Top()
+                .LeftDockable(False)
+                .RightDockable(False)
+                .BottomDockable(False)
+                .TopDockable(True)
+                .CloseButton(False)
+                .Layer(1)
+                .Row(1)
+                .BestSize((self.toolbars[name].GetBestSize())),
+            )
 
     def GetMapToolbar(self):
         """!Returns toolbar with zooming tools"""
-        return self.toolbars['MapToolbar']
+        return self.toolbars["MapToolbar"]
 
     def OnHelp(self, event):
         """!Show help page"""
-        RunCommand('g.manual', entry='wxGUI.Example')
+        RunCommand("g.manual", entry="wxGUI.Example")
 
     def OnSelectRaster(self, event):
         """!Opens dialog to select raster map"""
         dlg = ExampleMapDialog(self)
 
         if dlg.ShowModal() == wx.ID_OK:
-            raster = gcore.find_file(name=dlg.GetRasterMap(), element='cell')
-            if raster['fullname']:
-                self.SetLayer(name=raster['fullname'])
+            raster = gcore.find_file(name=dlg.GetRasterMap(), element="cell")
+            if raster["fullname"]:
+                self.SetLayer(name=raster["fullname"])
             else:
                 # show user that the map name is incorrect
-                GError(parent=self,
-                       message=_("Raster map <{raster}> not found").format(raster=dlg.GetRasterMap()))
+                GError(
+                    parent=self,
+                    message=_("Raster map <{raster}> not found").format(
+                        raster=dlg.GetRasterMap()
+                    ),
+                )
 
         dlg.Destroy()
 
@@ -264,23 +325,32 @@ class ExampleMapFrame(SingleMapFrame):
 
         @param name layer (raster) name
         """
-        Debug.msg (3, "ExampleMapFrame.SetLayer(): name=%s" % name)
+        Debug.msg(3, "ExampleMapFrame.SetLayer(): name=%s" % name)
 
         # this simple application enables to keep only one raster
         self.GetMap().DeleteAllLayers()
-        cmdlist = ['d.rast', 'map=%s' % name]
+        cmdlist = ["d.rast", "map=%s" % name]
         # add layer to Map instance (core.render)
-        newLayer = self.GetMap().AddLayer(ltype='raster', command=cmdlist, active=True,
-                                          name=name, hidden=False, opacity=1.0,
-                                          render=True)
-        self.GetWindow().ZoomToMap(layers=[newLayer, ], render=True)
+        newLayer = self.GetMap().AddLayer(
+            ltype="raster",
+            command=cmdlist,
+            active=True,
+            name=name,
+            hidden=False,
+            opacity=1.0,
+            render=True,
+        )
+        self.GetWindow().ZoomToMap(
+            layers=[
+                newLayer,
+            ],
+            render=True,
+        )
         self.currentRaster = name
 
         # change comp. region to match new raster, so that the statistics
         # are computed for the entire raster
-        RunCommand('g.region',
-                   rast=self.currentRaster,
-                   parent=self)
+        RunCommand("g.region", rast=self.currentRaster, parent=self)
 
         self.UpdateStatistics()
 
@@ -290,10 +360,12 @@ class ExampleMapFrame(SingleMapFrame):
         @return statistic in form of dictionary
         """
         # RunCommand enables to run GRASS module
-        res = RunCommand('r.univar',  # module name
-                         flags='g',  # command flags
-                         map=self.currentRaster,  # module parameters
-                         read=True)  # get command output
+        res = RunCommand(
+            "r.univar",  # module name
+            flags="g",  # command flags
+            map=self.currentRaster,  # module parameters
+            read=True,
+        )  # get command output
 
         return gcore.parse_key_val(res, val_type=float)
 
@@ -313,10 +385,10 @@ class ExampleInfoTextManager:
     """
 
     def __init__(self, parent):
-        """!Creates wx.TextCtrl for displaying information.
-        """
-        self.textCtrl = wx.TextCtrl(parent, id=wx.ID_ANY,
-                                    style=wx.TE_MULTILINE | wx.TE_RICH2 | wx.TE_READONLY)
+        """!Creates wx.TextCtrl for displaying information."""
+        self.textCtrl = wx.TextCtrl(
+            parent, id=wx.ID_ANY, style=wx.TE_MULTILINE | wx.TE_RICH2 | wx.TE_READONLY
+        )
         self.textCtrl.SetInsertionPoint(0)
         self.font = self.textCtrl.GetFont()
 

+ 14 - 11
doc/gui/wxpython/example/g.gui.example.py

@@ -38,8 +38,8 @@ import wx
 # So we need to import it before any of the GUI code.
 import grass.script.core as gcore
 
-if __name__ == '__main__':
-    wxbase = os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython')
+if __name__ == "__main__":
+    wxbase = os.path.join(os.getenv("GISBASE"), "etc", "gui", "wxpython")
     if wxbase not in sys.path:
         sys.path.append(wxbase)
 
@@ -52,17 +52,19 @@ from example.frame import ExampleMapFrame
 
 def main():
     options, flags = gcore.parser()
-    if options['input']:
-        map_name = gcore.find_file(name=options['input'], element='cell')['fullname']
+    if options["input"]:
+        map_name = gcore.find_file(name=options["input"], element="cell")["fullname"]
         if not map_name:
-            gcore.fatal(_("Raster map <{raster}> not found").format(raster=options['input']))
+            gcore.fatal(
+                _("Raster map <{raster}> not found").format(raster=options["input"])
+            )
 
     # define display driver (avoid 'no graphics device selected' error at start up)
-    driver = UserSettings.Get(group='display', key='driver', subkey='type')
-    if driver == 'png':
-        os.environ['GRASS_RENDER_IMMEDIATE'] = 'png'
+    driver = UserSettings.Get(group="display", key="driver", subkey="type")
+    if driver == "png":
+        os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
     else:
-        os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'
+        os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo"
 
     # launch application
     app = wx.App()
@@ -72,12 +74,13 @@ def main():
     # show main frame
     giface = StandaloneGrassInterface()
     frame = ExampleMapFrame(parent=None, giface=giface)
-    if options['input']:
+    if options["input"]:
         giface.WriteLog(_("Loading raster map <{raster}>...").format(raster=map_name))
         frame.SetLayer(map_name)
 
     frame.Show()
     app.MainLoop()
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     GuiModuleMain(main)

+ 30 - 43
doc/gui/wxpython/example/toolbars.py

@@ -23,12 +23,10 @@ from icons.icon import MetaIcon
 
 
 class ExampleMapToolbar(BaseToolbar):
-    """!Map toolbar (to control map zoom and rendering)
-    """
+    """!Map toolbar (to control map zoom and rendering)"""
 
     def __init__(self, parent, toolSwitcher):
-        """!Map toolbar constructor
-        """
+        """!Map toolbar constructor"""
         BaseToolbar.__init__(self, parent, toolSwitcher)
 
         self.InitToolbar(self._toolbarData())
@@ -39,7 +37,7 @@ class ExampleMapToolbar(BaseToolbar):
         self._default = self.pan
 
         for tool in (self.pan, self.zoomIn, self.zoomOut):
-            self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
+            self.toolSwitcher.AddToolToGroup(group="mouseUse", toolbar=self, tool=tool)
 
         self.EnableTool(self.zoomBack, False)
 
@@ -48,37 +46,27 @@ class ExampleMapToolbar(BaseToolbar):
         # BaseIcons are a set of often used icons. It is possible
         # to reuse icons in ./trunk/gui/icons/grass or add new ones there.
         icons = BaseIcons
-        return self._getToolbarData((("displaymap", icons["display"],
-                                      self.parent.OnDraw),
-                                     ("rendermap", icons["render"],
-                                      self.parent.OnRender),
-                                     ("erase", icons["erase"],
-                                      self.parent.OnErase),
-                                     (None, ),  # creates separator
-                                     ("pan", icons["pan"],
-                                      self.parent.OnPan,
-                                      wx.ITEM_CHECK),  # toggle tool
-                                     ("zoomIn", icons["zoomIn"],
-                                      self.parent.OnZoomIn,
-                                      wx.ITEM_CHECK),
-                                     ("zoomOut", icons["zoomOut"],
-                                      self.parent.OnZoomOut,
-                                      wx.ITEM_CHECK),
-                                     (None, ),
-                                     ("zoomBack", icons["zoomBack"],
-                                      self.parent.OnZoomBack),
-                                     ("zoomToMap", icons["zoomExtent"],
-                                      self.parent.OnZoomToMap),
-                                     ))
+        return self._getToolbarData(
+            (
+                ("displaymap", icons["display"], self.parent.OnDraw),
+                ("rendermap", icons["render"], self.parent.OnRender),
+                ("erase", icons["erase"], self.parent.OnErase),
+                (None,),  # creates separator
+                ("pan", icons["pan"], self.parent.OnPan, wx.ITEM_CHECK),  # toggle tool
+                ("zoomIn", icons["zoomIn"], self.parent.OnZoomIn, wx.ITEM_CHECK),
+                ("zoomOut", icons["zoomOut"], self.parent.OnZoomOut, wx.ITEM_CHECK),
+                (None,),
+                ("zoomBack", icons["zoomBack"], self.parent.OnZoomBack),
+                ("zoomToMap", icons["zoomExtent"], self.parent.OnZoomToMap),
+            )
+        )
 
 
 class ExampleMainToolbar(BaseToolbar):
-    """!Toolbar with tools related to application functionality
-    """
+    """!Toolbar with tools related to application functionality"""
 
     def __init__(self, parent):
-        """!Toolbar constructor
-        """
+        """!Toolbar constructor"""
         BaseToolbar.__init__(self, parent)
 
         self.InitToolbar(self._toolbarData())
@@ -88,18 +76,16 @@ class ExampleMainToolbar(BaseToolbar):
 
     def _toolbarData(self):
         """!Toolbar data"""
-        return self._getToolbarData((("addRaster", BaseIcons['addRast'],
-                                      self.parent.OnSelectRaster),
-                                     ))
+        return self._getToolbarData(
+            (("addRaster", BaseIcons["addRast"], self.parent.OnSelectRaster),)
+        )
 
 
 class ExampleMiscToolbar(BaseToolbar):
-    """!Toolbar with miscellaneous tools related to app
-    """
+    """!Toolbar with miscellaneous tools related to app"""
 
     def __init__(self, parent):
-        """!Toolbar constructor
-        """
+        """!Toolbar constructor"""
         BaseToolbar.__init__(self, parent)
 
         self.InitToolbar(self._toolbarData())
@@ -109,8 +95,9 @@ class ExampleMiscToolbar(BaseToolbar):
     def _toolbarData(self):
         """!Toolbar data"""
         icons = BaseIcons
-        return self._getToolbarData((("help", icons['help'],
-                                      self.parent.OnHelp),
-                                     ("quit", icons['quit'],
-                                      self.parent.OnCloseWindow),
-                                     ))
+        return self._getToolbarData(
+            (
+                ("help", icons["help"], self.parent.OnHelp),
+                ("quit", icons["quit"], self.parent.OnCloseWindow),
+            )
+        )

+ 8 - 6
doc/python/m.distance.py

@@ -51,8 +51,9 @@ import grass.script as gs
 
 from grass.lib.gis import *
 
+
 def main():
-    G_gisinit('m.distance')
+    G_gisinit("m.distance")
 
     # calc distance
 
@@ -65,18 +66,18 @@ def main():
     # toast, so no way to check if option was given. So it hangs if
     # --q was the only option given and there is no data from stdin.
     coords = []
-    if flags['i']:
+    if flags["i"]:
         # read line by line from stdin
         while True:
             line = sys.stdin.readline().strip()
-            if not line: # EOF
+            if not line:  # EOF
                 break
             else:
-                coords.append(line.split(','))
+                coords.append(line.split(","))
     else:
         # read from coord= command line option
         p = None
-        for c in options['coord'].split(','):
+        for c in options["coord"].split(","):
             if not p:
                 p = [c]
             else:
@@ -117,7 +118,7 @@ def main():
             x[i] = float(coords[i][0])
             y[i] = float(coords[i][1])
 
-        segment_distance = G_distance(x[i-1], y[i-1], x[i], y[i])
+        segment_distance = G_distance(x[i - 1], y[i - 1], x[i], y[i])
         overall_distance += segment_distance
 
         print("segment %d distance is %.2f meters" % (i, segment_distance))
@@ -146,6 +147,7 @@ def main():
 
     return 0
 
+
 if __name__ == "__main__":
     options, flags = gs.parser()
     sys.exit(main())

+ 9 - 8
doc/python/raster_example_ctypes.py

@@ -18,7 +18,7 @@ cols=5`
 import os
 import sys
 
-from grass.lib.gis    import *
+from grass.lib.gis import *
 from grass.lib.raster import *
 
 # check if GRASS is running or not
@@ -32,10 +32,10 @@ else:
     input = raw_input("Name of raster map? ")
 
 # initialize GRASS library
-G_gisinit('')
+G_gisinit("")
 
 # find map in search path
-mapset = G_find_raster2(input, '')
+mapset = G_find_raster2(input, "")
 if not mapset:
     sys.exit("Raster map <%s> not found" % input)
 
@@ -44,17 +44,17 @@ data_type = Rast_map_type(input, mapset)
 
 if data_type == CELL_TYPE:
     ptype = POINTER(c_int)
-    type_name = 'CELL'
+    type_name = "CELL"
 elif data_type == FCELL_TYPE:
     ptype = POINTER(c_float)
-    type_name = 'FCELL'
+    type_name = "FCELL"
 elif data_type == DCELL_TYPE:
     ptype = POINTER(c_double)
-    type_name = 'DCELL'
+    type_name = "DCELL"
 
 print("Raster map <%s> contains data type %s." % (input, type_name))
 
-in_fd   = Rast_open_old(input, mapset)
+in_fd = Rast_open_old(input, mapset)
 in_rast = Rast_allocate_buf(data_type)
 in_rast = cast(c_void_p(in_rast), ptype)
 
@@ -74,7 +74,8 @@ for row_n in range(rows):
 Rast_close(in_fd)
 G_free(in_rast)
 
+
 def check_null(value):
     if math.isnan(value):
-        return 'null'
+        return "null"
     return value

+ 7 - 8
doc/python/script/r.example.py

@@ -20,18 +20,17 @@ from grass.exceptions import CalledModuleError
 
 def main():
     options, flags = gs.parser()
-    input_raster = options['input']
-    output_raster = options['output']
+    input_raster = options["input"]
+    output_raster = options["output"]
 
     try:
-        stats = gs.parse_command('r.univar', map=input_raster, flags='g')
+        stats = gs.parse_command("r.univar", map=input_raster, flags="g")
     except CalledModuleError as e:
-        gs.fatal('{0}'.format(e))
-    raster_mean = float(stats['mean'])
-    raster_stddev = float(stats['stddev'])
+        gs.fatal("{0}".format(e))
+    raster_mean = float(stats["mean"])
+    raster_stddev = float(stats["stddev"])
     raster_high = raster_mean + raster_stddev
-    gs.mapcalc('{r} = {i} > {v}'.format(r=output_raster, i=input_raster,
-                                        v=raster_high))
+    gs.mapcalc("{r} = {i} > {v}".format(r=output_raster, i=input_raster, v=raster_high))
     return 0
 
 

+ 15 - 15
doc/python/vector_example_ctypes.py

@@ -8,7 +8,7 @@ interface
 import os
 import sys
 
-from grass.lib.gis    import *
+from grass.lib.gis import *
 from grass.lib.vector import *
 
 if not os.environ.has_key("GISBASE"):
@@ -20,7 +20,7 @@ else:
     input = raw_input("Name of vector map? ")
 
 # initialize GRASS library
-G_gisinit('')
+G_gisinit("")
 
 # find vector map in the search path
 mapset = G_find_vector2(input, "")
@@ -37,25 +37,25 @@ Vect_set_open_level(2)
 Vect_open_old(map_info, input, mapset)
 
 # query
-print('Vector map        :', Vect_get_full_name(map_info))
-print('Vector is 3D      :', Vect_is_3d(map_info))
-print('Vector DB links   :', Vect_get_num_dblinks(map_info))
-print('Map Scale         : 1:%d' % Vect_get_scale(map_info))
+print("Vector map        :", Vect_get_full_name(map_info))
+print("Vector is 3D      :", Vect_is_3d(map_info))
+print("Vector DB links   :", Vect_get_num_dblinks(map_info))
+print("Map Scale         : 1:%d" % Vect_get_scale(map_info))
 
 # vector box tests
 box = bound_box()
-c_easting1  = 599505.0
-c_northing  = 4921010.0
-c_easting2  = 4599505.0
+c_easting1 = 599505.0
+c_northing = 4921010.0
+c_easting2 = 4599505.0
 
 Vect_get_map_box(map_info, byref(box))
-print('Position 1 in box ?', Vect_point_in_box(c_easting1, c_northing, 0, byref(box)))
-print('Position 2 in box ?', Vect_point_in_box(c_easting2, c_northing, 0, byref(box)))
+print("Position 1 in box ?", Vect_point_in_box(c_easting1, c_northing, 0, byref(box)))
+print("Position 2 in box ?", Vect_point_in_box(c_easting2, c_northing, 0, byref(box)))
 
-print('Number of features:', Vect_get_num_lines(map_info))
-print('Number of points  :', Vect_get_num_primitives(map_info, GV_POINT))
-print('Number of lines   :', Vect_get_num_primitives(map_info, GV_LINE))
-print('Number of areas   :', Vect_get_num_areas(map_info))
+print("Number of features:", Vect_get_num_lines(map_info))
+print("Number of points  :", Vect_get_num_primitives(map_info, GV_POINT))
+print("Number of lines   :", Vect_get_num_primitives(map_info, GV_LINE))
+print("Number of areas   :", Vect_get_num_areas(map_info))
 
 # close map
 Vect_close(map_info)

+ 12 - 2
docker/testdata/test_grass_session.py

@@ -2,8 +2,18 @@
 from grass_session import Session
 import grass.script as gs
 
-with Session(gisdb="/grassdata/", location="test", mapset="PERMANENT", create_opts='EPSG:25832'):
+with Session(
+    gisdb="/grassdata/", location="test", mapset="PERMANENT", create_opts="EPSG:25832"
+):
     print("Tests for PROJ, GDAL, PDAL, GRASS")
 
     # simple test: just scan the LAZ file
-    gs.run_command('r.in.pdal', input="/tmp/simple.laz", output='count_1', method='n', flags="s", resolution=1, overwrite=True)
+    gs.run_command(
+        "r.in.pdal",
+        input="/tmp/simple.laz",
+        output="count_1",
+        method="n",
+        flags="s",
+        resolution=1,
+        overwrite=True,
+    )

+ 7 - 4
general/g.parser/test.py

@@ -30,15 +30,17 @@ import atexit
 
 import grass.script as gs
 
+
 def cleanup():
     # add some cleanup code
     gs.message(_("Inside cleanup function..."))
 
+
 def main():
-    flag_f = flags['f']
-    option1 = options['option1']
-    raster = options['raster']
-    vector = options['vector']
+    flag_f = flags["f"]
+    option1 = options["option1"]
+    raster = options["raster"]
+    vector = options["vector"]
 
     #### add your code here ####
     exitcode = 0
@@ -59,6 +61,7 @@ def main():
 
     sys.exit(exitcode)
 
+
 if __name__ == "__main__":
     options, flags = gs.parser()
     atexit.register(cleanup)

+ 100 - 68
imagery/i.atcorr/create_iwave.py

@@ -29,6 +29,7 @@ import sys
 import numpy as np
 from scipy import interpolate
 
+
 def usage():
     """How to use this..."""
     print("create_iwave.py <csv file>")
@@ -47,6 +48,7 @@ def usage():
     print("This script will interpolate the filter functions to 2.5 nm steps")
     print("and output a cpp template file in the IWave format to be added to iwave.cpp")
 
+
 def read_input(csvfile):
     """
     Function to read input file
@@ -58,10 +60,10 @@ def read_input(csvfile):
     first column is wavelength
     values are those of the discrete band filter functions
     """
-    infile = open(csvfile, 'r')
+    infile = open(csvfile, "r")
 
     # get number of bands and band names
-    bands = infile.readline().split(',')
+    bands = infile.readline().split(",")
     bands.remove(bands[0])
     bands[-1] = bands[-1].strip()
     print(" > Number of bands found: %d" % len(bands))
@@ -71,13 +73,14 @@ def read_input(csvfile):
     # fix nodata or \n
     conv = {}
     for b in range(len(bands)):
-        conv[b+1] = lambda s: float(s or 0)
+        conv[b + 1] = lambda s: float(s or 0)
 
-    values = np.loadtxt(csvfile, delimiter=',', skiprows=1, converters = conv)
+    values = np.loadtxt(csvfile, delimiter=",", skiprows=1, converters=conv)
 
     return (bands, values)
 
-def interpolate_band(values, step = 2.5):
+
+def interpolate_band(values, step=2.5):
     """
     Receive wavelength and response for one band
     interpolate at 2.5 nm steps
@@ -87,12 +90,14 @@ def interpolate_band(values, step = 2.5):
     """
 
     # removing nodata and invalid values
-    w = values[:,1] >= 0
+    w = values[:, 1] >= 0
     values_clean = values[w]
 
-    wavelengths = values_clean[:,0]  # 1st column of input array
-    responses = values_clean[:,1]  # 2nd column
-    assert len(wavelengths) == len(responses), "Number of wavelength slots and spectral responses are not equal!"
+    wavelengths = values_clean[:, 0]  # 1st column of input array
+    responses = values_clean[:, 1]  # 2nd column
+    assert len(wavelengths) == len(
+        responses
+    ), "Number of wavelength slots and spectral responses are not equal!"
 
     # spectral responses are written out with .4f in pretty_print()
     # anything smaller than 0.0001 will become 0.0000 -> discard with ...
@@ -136,13 +141,16 @@ def interpolate_band(values, step = 2.5):
 
     # how many spectral responses?
     expected = np.ceil((stop - start) / step)
-    assert len(filter_f) == expected, "Number of interpolated spectral responses not equal to expected number of interpolations"
+    assert (
+        len(filter_f) == expected
+    ), "Number of interpolated spectral responses not equal to expected number of interpolations"
 
     # convert limits from nanometers to micrometers
-    lowerlimit = start/1000
-    upperlimit = stop/1000
+    lowerlimit = start / 1000
+    upperlimit = stop / 1000
+
+    return (filter_f, (lowerlimit, upperlimit))
 
-    return(filter_f, (lowerlimit, upperlimit))
 
 def plot_filter(values):
     """Plot wl response values and interpolated
@@ -153,40 +161,42 @@ def plot_filter(values):
     filter_f, limits = interpolate_band(values)
 
     # removing nodata
-    w = values[:,1] >= 0
+    w = values[:, 1] >= 0
     response = values[w]
 
-    plot(response[:,0],response[:,1], 'ro')
+    plot(response[:, 0], response[:, 1], "ro")
     plot(arange(limits[0], limits[1], 2.5), filter_f)
 
     return
 
+
 def pretty_print(filter_f):
     """
     Create pretty string out of filter function
     8 values per line, with spaces, commas and all the rest
     """
-    pstring = ''
-    for i in range(len(filter_f)+1):
-        if i %8 is 0:
+    pstring = ""
+    for i in range(len(filter_f) + 1):
+        if i % 8 is 0:
             if i is not 0:
-                value_wo_leading_zero = ('%.4f' % (filter_f[i-1])).lstrip('0')
+                value_wo_leading_zero = ("%.4f" % (filter_f[i - 1])).lstrip("0")
                 pstring += value_wo_leading_zero
             if i > 1 and i < len(filter_f):
-                pstring += ', '
+                pstring += ", "
             if i is not 1:
                 # trim the trailing whitespace at the end of line
                 pstring = pstring.rstrip()
             pstring += "\n        "
         else:
-            value_wo_leading_zero = ('%.4f' % (filter_f[i-1])).lstrip('0')
+            value_wo_leading_zero = ("%.4f" % (filter_f[i - 1])).lstrip("0")
             pstring += value_wo_leading_zero
             if i < len(filter_f):
-                pstring += ', '
+                pstring += ", "
     # trim starting \n and trailing ,
     pstring = pstring.lstrip("\n").rstrip(", ")
     return pstring
 
+
 def write_cpp(bands, values, sensor, folder):
     """
     from bands, values and sensor name
@@ -224,7 +234,7 @@ def write_cpp(bands, values, sensor, folder):
         filter_f = []
         limits = []
         for b in range(len(bands)):
-            fi, li = interpolate_band(values[:,[0,b+1]])
+            fi, li = interpolate_band(values[:, [0, b + 1]])
             filter_f.append(fi)
             limits.append(li)
 
@@ -243,68 +253,80 @@ def write_cpp(bands, values, sensor, folder):
             print("   %s (%inm - %inm)" % (bands[b], min_wavelength, max_wavelength))
 
     # writing...
-    outfile = open(os.path.join(folder, sensor+"_cpp_template.txt"), 'w')
-    outfile.write('/* Following filter function created using create_iwave.py */\n\n')
+    outfile = open(os.path.join(folder, sensor + "_cpp_template.txt"), "w")
+    outfile.write("/* Following filter function created using create_iwave.py */\n\n")
 
     if len(bands) == 1:
-        outfile.write('void IWave::%s()\n{\n\n' % (sensor.lower()))
+        outfile.write("void IWave::%s()\n{\n\n" % (sensor.lower()))
     else:
-        outfile.write('void IWave::%s(int iwa)\n{\n\n' % (sensor.lower()))
+        outfile.write("void IWave::%s(int iwa)\n{\n\n" % (sensor.lower()))
 
     # single band case
     if len(bands) == 1:
-        outfile.write('    /* %s of %s */\n' % (bands[0], sensor))
-        outfile.write('    static const float sr[%i] = {' % (len(filter_f)))
+        outfile.write("    /* %s of %s */\n" % (bands[0], sensor))
+        outfile.write("    static const float sr[%i] = {" % (len(filter_f)))
         filter_text = pretty_print(filter_f)
         outfile.write(filter_text)
 
         # calculate wl slot for band start
         # slots range from 250 to 4000 at 2.5 increments (total 1500)
-        s_start = int((limits[0]*1000 - 250)/2.5)
-
-        outfile.write('\n')
-        outfile.write('    ffu.wlinf = %.4ff;\n' % (limits[0]))
-        outfile.write('    ffu.wlsup = %.4ff;\n' % (limits[1]))
-        outfile.write('    int i = 0;\n')
-        outfile.write('    for(i = 0; i < %i; i++)\tffu.s[i] = 0;\n' % (s_start))
-        outfile.write('    for(i = 0; i < %i; i++)\tffu.s[%i+i] = sr[i];\n' % (len(filter_f), s_start))
-        outfile.write('    for(i = %i; i < 1501; i++)\tffu.s[i] = 0;\n' % (s_start + len(filter_f)))
-        outfile.write('}\n')
-
-    else: # more than 1 band
+        s_start = int((limits[0] * 1000 - 250) / 2.5)
+
+        outfile.write("\n")
+        outfile.write("    ffu.wlinf = %.4ff;\n" % (limits[0]))
+        outfile.write("    ffu.wlsup = %.4ff;\n" % (limits[1]))
+        outfile.write("    int i = 0;\n")
+        outfile.write("    for(i = 0; i < %i; i++)\tffu.s[i] = 0;\n" % (s_start))
+        outfile.write(
+            "    for(i = 0; i < %i; i++)\tffu.s[%i+i] = sr[i];\n"
+            % (len(filter_f), s_start)
+        )
+        outfile.write(
+            "    for(i = %i; i < 1501; i++)\tffu.s[i] = 0;\n"
+            % (s_start + len(filter_f))
+        )
+        outfile.write("}\n")
+
+    else:  # more than 1 band
         # writing bands
         for b in range(len(bands)):
-            outfile.write('    /* %s of %s */\n' % (bands[b], sensor))
-            outfile.write('    static const float sr%i[%i] = {\n' % (b+1,len(filter_f[b])))
+            outfile.write("    /* %s of %s */\n" % (bands[b], sensor))
+            outfile.write(
+                "    static const float sr%i[%i] = {\n" % (b + 1, len(filter_f[b]))
+            )
             filter_text = pretty_print(filter_f[b])
-            outfile.write(filter_text+'\n    };\n\t\n')
+            outfile.write(filter_text + "\n    };\n\t\n")
 
         # writing band limits
         for b in range(len(bands)):
             inf = ", ".join(["%.4f" % i[0] for i in limits])
             sup = ", ".join(["%.4f" % i[1] for i in limits])
 
-        outfile.write('    static const float wli[%i] = {%s};\n' % (len(bands), inf))
-        outfile.write('    static const float wls[%i] = {%s};\n' % (len(bands), sup))
+        outfile.write("    static const float wli[%i] = {%s};\n" % (len(bands), inf))
+        outfile.write("    static const float wls[%i] = {%s};\n" % (len(bands), sup))
 
-        outfile.write('\n')
-        outfile.write('    ffu.wlinf = (float)wli[iwa-1];\n')
-        outfile.write('    ffu.wlsup = (float)wls[iwa-1];\n\n')
+        outfile.write("\n")
+        outfile.write("    ffu.wlinf = (float)wli[iwa-1];\n")
+        outfile.write("    ffu.wlsup = (float)wls[iwa-1];\n\n")
 
-        outfile.write('    int i;\n')
-        outfile.write('    for(i = 0; i < 1501; i++) ffu.s[i] = 0;\n\n')
+        outfile.write("    int i;\n")
+        outfile.write("    for(i = 0; i < 1501; i++) ffu.s[i] = 0;\n\n")
 
-        outfile.write('    switch(iwa)\n    {\n')
+        outfile.write("    switch(iwa)\n    {\n")
 
         # now start of case part...
         for b in range(len(bands)):
-            s_start = int((limits[b][0]*1000 - 250)/2.5)
-            outfile.write('    case %i: for(i = 0; i < %i; i++)  ffu.s[%i+i] = sr%i[i];\n' % ((b+1), len(filter_f[b]), s_start, (b+1)))
-            outfile.write('        break;\n')
-        outfile.write('    }\n}\n')
+            s_start = int((limits[b][0] * 1000 - 250) / 2.5)
+            outfile.write(
+                "    case %i: for(i = 0; i < %i; i++)  ffu.s[%i+i] = sr%i[i];\n"
+                % ((b + 1), len(filter_f[b]), s_start, (b + 1))
+            )
+            outfile.write("        break;\n")
+        outfile.write("    }\n}\n")
 
     return
 
+
 def main():
     """ control function """
 
@@ -330,20 +352,20 @@ def main():
         hiwl = 0
         maxr = 0
         maxi = 0
-        for i in range(len(values[:,0])):
-            if maxr < values[i,b]:
-                maxr = values[i,b]
+        for i in range(len(values[:, 0])):
+            if maxr < values[i, b]:
+                maxr = values[i, b]
                 maxi = i
 
         i = maxi
-        while i >= 0 and values[i,b] > rthresh:
-            lowl = values[i,0]
+        while i >= 0 and values[i, b] > rthresh:
+            lowl = values[i, 0]
             i -= 1
 
         i = maxi
-        nvalues = len(values[:,0])
-        while i < nvalues and values[i,b] > rthresh:
-            hiwl = values[i,0]
+        nvalues = len(values[:, 0])
+        while i < nvalues and values[i, b] > rthresh:
+            hiwl = values[i, 0]
             i += 1
 
         print("   %s (%inm - %inm)" % (bands[b - 1], lowl, hiwl))
@@ -352,14 +374,24 @@ def main():
     write_cpp(bands, values, sensor, os.path.dirname(inputfile))
 
     print
-    print(" > Filter functions exported to %s" % ("sensors_csv/"+sensor+"_cpp_template.txt"))
-    print(" > Please check this file for possible errors before inserting the code into file iwave.cpp")
-    print(" > Don't forget to add the necessary data to the files iwave.h, geomcond.h, geomcond.cpp, and to i.atcorr.html")
+    print(
+        " > Filter functions exported to %s"
+        % ("sensors_csv/" + sensor + "_cpp_template.txt")
+    )
+    print(
+        " > Please check this file for possible errors before inserting"
+        " the code into file iwave.cpp"
+    )
+    print(
+        " > Don't forget to add the necessary data to the files"
+        " iwave.h, geomcond.h, geomcond.cpp, and to i.atcorr.html"
+    )
     print
 
     return
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     if len(sys.argv) == 1:
         usage()
         sys.exit()

+ 25 - 15
imagery/i.segment/testsuite/test_isegment.py

@@ -10,34 +10,44 @@ Licence:    This program is free software under the GNU General Public
 """
 from grass.gunittest.case import TestCase
 
-class TestReport(TestCase):
 
+class TestReport(TestCase):
     @classmethod
     def setUpClass(cls):
         """Use temporary region settings"""
-        map_input = 'ortho_2001_t792_1m'
-        cls.runModule("g.region", n=220000, s=219456, w=637033, e=638000, align=map_input)
+        map_input = "ortho_2001_t792_1m"
+        cls.runModule(
+            "g.region", n=220000, s=219456, w=637033, e=638000, align=map_input
+        )
         cls.use_temp_region()
 
     @classmethod
     def tearDownClass(cls):
-        map_output = 'test'
-        group = 'ortho'
-        cls.runModule("g.remove", flags='f', type='raster', name=map_output)
-        cls.runModule("g.remove", flags='f', type='group', name=group)
+        map_output = "test"
+        group = "ortho"
+        cls.runModule("g.remove", flags="f", type="raster", name=map_output)
+        cls.runModule("g.remove", flags="f", type="group", name=group)
         cls.del_temp_region()
 
     def test_isegment(self):
         """Testing i.segment"""
-        map_input = 'ortho_2001_t792_1m'
-        map_output = 'test'
-        group = 'ortho'
+        map_input = "ortho_2001_t792_1m"
+        map_output = "test"
+        group = "ortho"
 
-        self.assertModule('i.group', group=group, input=map_input)
-        self.assertModule('i.segment', group=group, threshold=0.01, minsize=1, output=map_output)
-        self.assertRasterMinMax(map=map_output, refmin=1, refmax=500000,
-                                msg="Number of segments must be > 0")
+        self.assertModule("i.group", group=group, input=map_input)
+        self.assertModule(
+            "i.segment", group=group, threshold=0.01, minsize=1, output=map_output
+        )
+        self.assertRasterMinMax(
+            map=map_output,
+            refmin=1,
+            refmax=500000,
+            msg="Number of segments must be > 0",
+        )
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     from grass.gunittest.main import test
+
     test()

+ 117 - 57
imagery/i.vi/testsuite/test_vi.py

@@ -12,96 +12,156 @@ from grass.gunittest.case import TestCase
 
 
 class TestReport(TestCase):
-    blue = 'lsat5_1987_10@landsat'
-    green = 'lsat5_1987_20@landsat'
-    red = 'lsat5_1987_30@landsat'
-    nir = 'lsat5_1987_40@landsat'
+    blue = "lsat5_1987_10@landsat"
+    green = "lsat5_1987_20@landsat"
+    red = "lsat5_1987_30@landsat"
+    nir = "lsat5_1987_40@landsat"
 
     @classmethod
     def setUpClass(cls):
         """Use temporary region settings"""
-        cls.runModule("g.region", raster='lsat5_1987_30@landsat')
+        cls.runModule("g.region", raster="lsat5_1987_30@landsat")
         cls.use_temp_region()
 
     @classmethod
     def tearDownClass(cls):
-        cls.runModule("g.remove", flags='f', type="raster", name="ipvi")
-        cls.runModule("g.remove", flags='f', type="raster", name="ndwi")
-        cls.runModule("g.remove", flags='f', type="raster", name="dvi")
-        cls.runModule("g.remove", flags='f', type="raster", name="sr")
-        cls.runModule("g.remove", flags='f', type="raster", name="evi")
-        cls.runModule("g.remove", flags='f', type="raster", name="evi2")
-        cls.runModule("g.remove", flags='f', type="raster", name="gari")
-        cls.runModule("g.remove", flags='f', type="raster", name="gemi")
+        cls.runModule("g.remove", flags="f", type="raster", name="ipvi")
+        cls.runModule("g.remove", flags="f", type="raster", name="ndwi")
+        cls.runModule("g.remove", flags="f", type="raster", name="dvi")
+        cls.runModule("g.remove", flags="f", type="raster", name="sr")
+        cls.runModule("g.remove", flags="f", type="raster", name="evi")
+        cls.runModule("g.remove", flags="f", type="raster", name="evi2")
+        cls.runModule("g.remove", flags="f", type="raster", name="gari")
+        cls.runModule("g.remove", flags="f", type="raster", name="gemi")
         cls.del_temp_region()
 
     def test_vinameipvi(self):
         """Testing viname ipvi"""
-        map_output = 'ipvi'
-        self.assertModule('i.vi', red=self.red, nir=self.nir,
-                          output=map_output, viname='ipvi')
-        self.assertRasterMinMax(map=map_output, refmin=0.0454545454545,
-                                refmax=0.9066667,
-                                msg="ipvi in degrees must be between 0.0454545 and 0.9066667")
+        map_output = "ipvi"
+        self.assertModule(
+            "i.vi", red=self.red, nir=self.nir, output=map_output, viname="ipvi"
+        )
+        self.assertRasterMinMax(
+            map=map_output,
+            refmin=0.0454545454545,
+            refmax=0.9066667,
+            msg="ipvi in degrees must be between 0.0454545 and 0.9066667",
+        )
 
     def test_vinamendwi(self):
         """Testing viname ndwi"""
-        map_output = 'ndwi'
-        self.assertModule('i.vi', red=self.red, green=self.green, nir=self.nir, viname='ndwi',
-                          output=map_output)
-        self.assertRasterMinMax(map=map_output, refmin=-0.71, refmax=0.93,
-                                msg="ndwi in percent must be between -0.71 and 0.93")
+        map_output = "ndwi"
+        self.assertModule(
+            "i.vi",
+            red=self.red,
+            green=self.green,
+            nir=self.nir,
+            viname="ndwi",
+            output=map_output,
+        )
+        self.assertRasterMinMax(
+            map=map_output,
+            refmin=-0.71,
+            refmax=0.93,
+            msg="ndwi in percent must be between -0.71 and 0.93",
+        )
 
     def test_vinamedvi(self):
         """Testing viname dvi"""
-        map_output = 'dvi'
-        self.assertModule('i.vi', red=self.red, nir=self.nir, viname='dvi',
-                          output=map_output)
-        self.assertRasterMinMax(map=map_output, refmin=-0.33, refmax=0.56,
-                                msg="dvi in percent must be between -0.32 and 0.52")
+        map_output = "dvi"
+        self.assertModule(
+            "i.vi", red=self.red, nir=self.nir, viname="dvi", output=map_output
+        )
+        self.assertRasterMinMax(
+            map=map_output,
+            refmin=-0.33,
+            refmax=0.56,
+            msg="dvi in percent must be between -0.32 and 0.52",
+        )
 
     def test_vinamesr(self):
         """Testing viname sr"""
-        map_output = 'sr'
-        self.assertModule('i.vi', red=self.red, nir=self.nir, blue=self.blue,
-                          output=map_output, viname='sr')
-        self.assertRasterMinMax(map=map_output, refmin=0.04, refmax=9.73,
-                                msg="sr in percent must be between 0.04 and 9.72")
+        map_output = "sr"
+        self.assertModule(
+            "i.vi",
+            red=self.red,
+            nir=self.nir,
+            blue=self.blue,
+            output=map_output,
+            viname="sr",
+        )
+        self.assertRasterMinMax(
+            map=map_output,
+            refmin=0.04,
+            refmax=9.73,
+            msg="sr in percent must be between 0.04 and 9.72",
+        )
 
     def test_vinameevi(self):
         """Testing viname evi"""
-        map_output = 'evi'
-        self.assertModule('i.vi', red=self.red, nir=self.nir, blue=self.blue,
-                          output=map_output, viname='evi')
-        self.assertRasterMinMax(map=map_output, refmin=-8.12414050428e+16,
-                                refmax=4.45061610234e+17,
-                                msg="evi in degrees must be between -8.12 and 4.45061610234e+17")
+        map_output = "evi"
+        self.assertModule(
+            "i.vi",
+            red=self.red,
+            nir=self.nir,
+            blue=self.blue,
+            output=map_output,
+            viname="evi",
+        )
+        self.assertRasterMinMax(
+            map=map_output,
+            refmin=-8.12414050428e16,
+            refmax=4.45061610234e17,
+            msg="evi in degrees must be between -8.12 and 4.45061610234e+17",
+        )
 
     def test_vinameevi2(self):
         """Testing viname evi2"""
-        map_output = 'evi2'
-        self.assertModule('i.vi', red=self.red, nir=self.nir,
-                          output=map_output, viname='evi2')
-        self.assertRasterMinMax(map=map_output, refmin=-0.33, refmax=0.74,
-                                msg="evi2 in degrees must be between -0.33 and 0.74")
+        map_output = "evi2"
+        self.assertModule(
+            "i.vi", red=self.red, nir=self.nir, output=map_output, viname="evi2"
+        )
+        self.assertRasterMinMax(
+            map=map_output,
+            refmin=-0.33,
+            refmax=0.74,
+            msg="evi2 in degrees must be between -0.33 and 0.74",
+        )
 
     def test_vinamegari(self):
         """Testing viname gari"""
-        map_output = 'gari'
-        self.assertModule('i.vi', red=self.red, nir=self.nir, blue=self.blue,
-                          green=self.green, output=map_output, viname='gari')
-        self.assertRasterMinMax(map=map_output, refmin=-1.58244128083e+17,
-                                refmax=float('inf'),
-                                msg="gari in degrees must be between -1.58")
+        map_output = "gari"
+        self.assertModule(
+            "i.vi",
+            red=self.red,
+            nir=self.nir,
+            blue=self.blue,
+            green=self.green,
+            output=map_output,
+            viname="gari",
+        )
+        self.assertRasterMinMax(
+            map=map_output,
+            refmin=-1.58244128083e17,
+            refmax=float("inf"),
+            msg="gari in degrees must be between -1.58",
+        )
 
     def test_vinamegemi(self):
         """Testing viname gemi"""
-        map_output = 'gemi'
-        self.assertModule('i.vi', red=self.red, nir=self.nir,
-                          output=map_output, viname='gemi')
-        self.assertRasterMinMax(map=map_output, refmin=-221.69, refmax=0.97,
-                                msg="gemi in degrees must be between -221.69 and 0.97")
+        map_output = "gemi"
+        self.assertModule(
+            "i.vi", red=self.red, nir=self.nir, output=map_output, viname="gemi"
+        )
+        self.assertRasterMinMax(
+            map=map_output,
+            refmin=-221.69,
+            refmax=0.97,
+            msg="gemi in degrees must be between -221.69 and 0.97",
+        )
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     from grass.gunittest.main import test
+
     test()

+ 2 - 8
pyproject.toml

@@ -18,18 +18,12 @@ exclude = '''
         | bin\.
         | dist\.
     )/
-    | python/grass/ctypes
+    | python/grass/ctypes/
     # Bug in Black related to tab escape prevents these from being formatted correctly.
     # https://github.com/psf/black/issues/1970
     | python/grass/imaging/images2gif.py
     | python/grass/pygrass/raster/category.py
     # Directories and files not yet under Black
-    | db
-    | doc
-    | general
-    | gui
-    | imagery
-    | docker/testdata/test_grass_session.py
-    | display/d.mon/render_cmd.py
+    | gui/
 )
 '''

+ 1 - 1
scripts/db.in.ogr/db.in.ogr.py

@@ -117,7 +117,7 @@ def main():
             output=output,
             layer=layer,
             quiet=True,
-            **vopts
+            **vopts,
         )
     except CalledModuleError:
         if db_table: