Best Python code snippet using pytest-bdd_python
r.fill.category.py
Source:r.fill.category.py
1#!/usr/bin/env python2#3############################################################################4#5# MODULE: r.fill.category6# AUTHOR(S): Stefano Gobbi and Paolo Zatelli7# PURPOSE: Replaces the values of pixels of a given category with values8# of the surrounding pixels9#10# COPYRIGHT: (C) 2019 by Stefano Gobbi and Paolo Zatelli11#12# This program is free software under the GNU General Public13# License (>=v2). Read the file COPYING that comes with GRASS14# for details.15#16#############################################################################17# %Module18# % description: Replaces the values of pixels of a given category with values of the surrounding pixels.19# % keyword: raster20# % keyword: algebra21# % keyword: category22# %end23# %flag24# % key: k25# % description: Keep intermediate maps26# %end27# %option G_OPT_R_INPUT28# %end29# %option G_OPT_R_OUTPUT30# %end31# %option32# % key: category33# % type: integer34# % required: yes35# % multiple: no36# % description: Category to replace37# %end38# %option39# % key: nsize40# % type: integer41# % required: no42# % multiple: no43# % description: Neighborhood size in pixel44# % answer: 1945# % guisection: Parameters46# %end47# %option48# % key: maxiter49# % type: integer50# % required: no51# % multiple: no52# % description: Maximum number of iterations53# % answer: 10054# % options: 1-99955# % guisection: Parameters56# %end57# %option G_OPT_F_OUTPUT58# % key: animationfile59# % description: Name for animation output file60# % required: no61# % guisection: Optional62# %end63# %option64# % key: quality65# % type: integer66# % required: no67# % multiple: no68# % description: Quality factor for animation (1 = highest quality, lowest compression)69# % answer: 370# % options: 1-571# % guisection: Optional72# %end73import sys74import os75import atexit76import grass.script as gscript77from grass.exceptions import CalledModuleError78# i18N79import gettext80gettext.install("grassmods", os.path.join(os.getenv("GISBASE"), "locale"))81def main():82 options, flags = gscript.parser()83 keep = flags["k"]84 input = options["input"]85 output = options["output"]86 category = int(options["category"])87 nsize = int(options["nsize"])88 maxiter = int(options["maxiter"])89 animationfile = options["animationfile"]90 quality = int(options["quality"])91 overwrite_flag = ""92 if gscript.overwrite():93 overwrite_flag = "t"94 # keep intermediate maps95 keepintmaps = False96 if flags["k"]:97 keepintmaps = True98 # to generate the animation file, intermediate files must be kept99 # they will be removed at the end of the process if the 'k' flag is not set100 if animationfile:101 keepintmaps = True102 # check if input file exists103 if not gscript.find_file(input)["file"]:104 gscript.fatal(_("Raster map <%s> not found") % input)105 # strip mapset name106 in_name_strip = options["input"].split("@")107 in_name = in_name_strip[0]108 out_name_strip = options["output"].split("@")109 out_name = out_name_strip[0]110 tmp = str(os.getpid())111 # maps to bootstrap the loop112 # create a map containing only the category to replace and NULL113 categorymap = "{}".format(in_name) + "_bin_" + "{}".format(tmp)114 gscript.verbose(_("Category map: <%s>") % categorymap)115 gscript.run_command(116 "r.mapcalc",117 expression="{outmap}=if({inmap}=={cat}, 1, null())".format(118 outmap=categorymap, inmap=input, cat=category119 ),120 quiet=True,121 overwrite="t",122 )123 # create a copy of the input map to be used as a selection map in r.neighbors,124 # it will be replaced by the map with category replacement in the loop125 stepmap_old = "{}".format(in_name) + "_step_000"126 gscript.run_command(127 "g.copy",128 raster="{inmap},{outmap}".format(inmap=input, outmap=stepmap_old),129 quiet=True,130 overwrite="t",131 )132 gscript.verbose(_("Category to remove: %d") % category)133 gscript.verbose(_("Maxiter: %d") % maxiter)134 gscript.verbose(_("Quality for animation: %d") % quality)135 pixel_num = 1136 iteration = 1137 # iterate until no pixel of the category to be replaced is left138 # or the maximum number of iterations is reached139 while (pixel_num > 0) and (iteration <= maxiter):140 stepmap = "{}".format(in_name)141 stepmap += "_step_"142 stepmap += "{:03d}".format(iteration)143 gscript.verbose(_("Step map: <%s>") % stepmap)144 # substitute pixels of the category to remove with the mode of the surrounding pixels145 gscript.run_command(146 "r.neighbors",147 input=stepmap_old,148 selection=categorymap,149 size=nsize,150 output=stepmap,151 method="mode",152 overwrite="true",153 quiet=True,154 )155 # remove intermediate map unless the k flag is set156 if keepintmaps is False:157 gscript.run_command(158 "g.remove", type="raster", name=stepmap_old, flags="f", quiet=True159 )160 # the r.neighbors output map is the input map for the next step161 stepmap_old = stepmap162 # create the new map containing only the category to replace and NULL163 gscript.run_command(164 "r.mapcalc",165 expression="{outmap}=if({inmap}=={cat},1,null())".format(166 outmap=categorymap, inmap=stepmap, cat=category167 ),168 quiet=True,169 overwrite="t",170 )171 # evaluate the number of the remaining pixels of the category to relace172 pixel_stat = gscript.parse_command(173 "r.stats",174 input="{inmap}".format(inmap=stepmap),175 flags="c",176 sep="=",177 quiet=True,178 )179 # parse the output, if the category is not in the list raise an exception and set pixel_num = 0180 try:181 pixel_num = float(pixel_stat["{}".format(category)])182 except KeyError as e:183 pixel_num = 0184 # print(e.message)185 gscript.verbose(186 _("Iteration: %d Remaining pixels: %d") % (iteration, pixel_num)187 )188 iteration = iteration + 1189 # the last value stopped the loop190 iteration = iteration - 1191 # if the loop ended before reaching pixel_num=0192 if pixel_num > 0:193 gscript.warning(194 _(195 "the process stopped after %d iterations with %d pixels of category %d left"196 )197 % (iteration, pixel_num, category)198 )199 # copy the output of the last iteration to the output map200 gscript.run_command(201 "g.copy",202 raster="{inmap},{outmap}".format(inmap=stepmap, outmap=out_name),203 overwrite="{}".format(overwrite_flag),204 quiet=True,205 )206 # remove the last intermediate map unless the k flag is set207 if keepintmaps is False:208 gscript.run_command(209 "g.remove", type="raster", name=stepmap_old, flags="f", quiet=True210 )211 gscript.run_command(212 "g.remove", type="raster", name=categorymap, flags="f", quiet=True213 )214 # optionally create an mpeg animation of the replacement sequence215 if animationfile:216 gscript.message(_("Generating mpeg file %s...") % animationfile)217 gscript.run_command(218 "r.out.mpeg",219 view1="{}_step_[0-9][0-9][0-9]".format(in_name),220 output="{}".format(animationfile),221 quality="{}".format(quality),222 overwrite="{}".format(overwrite_flag),223 )224 # remove intermediate maps if they have been kept for generating the animation225 # but the 'k' flag is not set226 if animationfile and not flags["k"]:227 gscript.message(228 _("Removing intermediate files after generating %s...") % animationfile229 )230 newiter = 0231 while newiter <= iteration:232 stepmap = "{}".format(in_name)233 stepmap += "_step_"234 stepmap += "{:03d}".format(newiter)235 gscript.verbose(_("Removing step map: <%s>") % stepmap)236 gscript.run_command(237 "g.remove", type="raster", name=stepmap, flags="f", quiet=True238 )239 newiter = newiter + 1240if __name__ == "__main__":241 options, flags = gscript.parser()242 # atexit.register(cleanup)...
steppo.py
Source:steppo.py
...89 messages = []90 for msg in track:91 messages.append(str(msg))92 return messages93def create_stepmap(messages: list) -> dict:94 """95 Create a stepmap that contains only the events we need (no meta events).96 """97 index = 098 steps = {}99 for msg in messages:100 filtered = ['meta']101 this_message = Message(msg, filtered_message_types=filtered)102 if not this_message.filtered:103 steps[index] = this_message104 index += 1105 return steps106if __name__ == '__main__':107 total_message_count = 0108 track_list = get_tracks(JINGLE_TEST)109 o = Output()110 for track in track_list:111 message_list = get_messages(track)112 stepmap = create_stepmap(message_list)113 print(len(stepmap))114 o.update_text(stepmap)115 o.strip_final_comma()116 print(o.text)117 with open('/Users/rich/jingle2021.txt', 'w') as fout:...
test_cases.py
Source:test_cases.py
...54 'velocity': '100',55 'time': '15360',56 }57 assert valid_params == note_on.params58def test_create_stepmap():59 messages = get_messages(mido.MidiFile('./midi_files/on_off.mid'))60 stepmap = create_stepmap(messages)61 assert isinstance(stepmap, dict)62 assert len(stepmap) == 863 assert stepmap[0].message_type == 'note_on'64 assert stepmap[7].message_type == 'note_off'...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!