Best Python code snippet using ATX
components.py
Source:components.py
...67 def __init__(self, tb, list):68 super(ListUI, self).__init__(tb, True)69 self.list = list70 self.start = 071 def _fix_bounds(self):72 if len(self.list) > 0:73 if (self.list.sel - self.start) >= self.h:74 self.start = self.list.sel - self.h + 175 if self.list.sel < self.start:76 self.start = self.list.sel77 self.start = min(max(0, self.start), len(self.list) - 1)78 def _handle_resize(self):79 self._fix_bounds()80 def draw(self):81 length = len(self.list)82 empty = Format("".ljust(self.w))83 for y in xrange(self.h):84 p = y + self.start85 f = self._format(self.list[p], y, p) if p < length else empty86 self.change_cells_format(0, y, f)87 def list_changed(self, l):88 self._fix_bounds()89 def list_selected_changed(self, l):90 self._fix_bounds()91 def search(self, s):92 self.list.search(s)93 def select(self, index, rel=False):94 self.list.select(index, rel)95 def selected(self):96 return self.list.selected()97def playtime_str(time):98 return ", ".join(filter(lambda s: not s.startswith("0"),99 ["%i days" % (time / (24 * 60 * 60)),100 "%i hours" % (time / (60 * 60) % 24),101 "%i minutes" % (time / 60 % 60),102 "%i seconds" % (time % (60))]))103class PlaylistUI(ListUI, StatusListener):104 def __init__(self, tb, status):105 super(PlaylistUI, self).__init__(tb, status.playlist)106 self.status = status107 self.list.add_listener(self)108 def draw(self):109 length = len(self.list)110 numw = 0111 if length > 0:112 numw = int(math.floor(math.log10(len(self.list)))) + 2113 for y in xrange(self.h):114 pos = y + self.start115 if pos < length:116 left, right = format_playlist_song(self.list[pos], pos,117 pos == self.list.sel,118 self.list[pos] == self.status.current,119 self.w, numw)120 self.change_cells_format(0, y, left)121 self.change_cells_format(self.w - len(right.s), y, right)122 def list_search_started(self, unused_ref):123 pass124 def list_search_stopped(self, unused_ref):125 pass126class TextComponent(MainComponent):127 def __init__(self, tb, tlist, title="", show_bar=True):128 super(TextComponent, self).__init__(tb, False)129 self.tlist = tlist130 self.start = 0131 self.title = title132 self.show_bar = show_bar133 def _text_height(self):134 return (self.h - 1) if self.show_bar else self.h135 def _fix_bounds(self):136 if len(self.tlist) > 0:137 self.start = max(0, min((len(self.tlist) - self._text_height(),138 self.start)))139 def _handle_resize(self):140 self._fix_bounds()141 def _format(self, item, y, p, numw):142 f = Format()143 f.add(str(p + 1).rjust(numw), termbox.YELLOW, termbox.BLACK)144 f.add(" %s" % item, termbox.WHITE, termbox.BLACK)145 return f146 def _format_bar(self):147 left, right = Format(), Format()148 left.add(" %s" % self.title, termbox.WHITE, termbox.BLACK)149 if self.h >= len(self.tlist):150 right.add("All ", termbox.WHITE, termbox.BLACK)151 else:152 p = self.start / float((len(self.tlist) - self._text_height()))153 if p == 0.0:154 right.add("Top ", termbox.WHITE, termbox.BLACK)155 elif p == 1.0:156 right.add("Bot ", termbox.WHITE, termbox.BLACK)157 else:158 right.add("%.0f%% " % (p * 100), termbox.WHITE, termbox.BLACK)159 left.set_bold()160 right.set_bold()161 return left, right162 def draw(self):163 length = len(self.tlist)164 nw = 0165 if length > 0:166 nw = int(math.floor(math.log10(length))) + 2167 empty = Format("".ljust(self.w))168 for y in xrange(self._text_height()):169 p = y + self.start170 f = self._format(self.tlist[p], y, p, nw) if p < length else empty171 self.change_cells_format(0, y, f)172 if self.show_bar:173 left, right = self._format_bar()174 self.change_cells_format(0, self.h - 1, left)175 self.change_cells_format(self.w - len(right.s), self.h - 1, right)176 def set_start(self, start, rel=False):177 self.start = (self.start + start) if rel else start178 self._fix_bounds()179class BrowserBar(Component, BrowserListener):180 def __init__(self, tb, browser):181 super(BrowserBar, self).__init__(tb)182 self.browser = browser183 self.browser.add_listener(self)184 def draw(self):185 f = Format()186 f.add(" Browse > ", termbox.WHITE | termbox.BOLD, termbox.BLACK)187 if self.browser.search_active():188 f.add("Filter: ", termbox.WHITE, termbox.BLACK)189 if len(self.node) > 0:190 f.add(self.node.string, termbox.WHITE, termbox.BLACK)191 else:192 f.add(self.node.string, termbox.RED, termbox.BLACK)193 else:194 f.add(self.browser.path_str(" > "), termbox.WHITE, termbox.BLACK)195 self.change_cells_format(0, 0, f)196 def browser_node_changed(self, browser):197 self.node = self.browser.curr_node198 def browser_search_started(self, browser):199 self.node = self.browser.curr_node200 def browser_search_stopped(self, browser):201 self.node = self.browser.curr_node202class PlaylistBar(Component, ListListener):203 def __init__(self, tb, playlist):204 super(PlaylistBar, self).__init__(tb)205 self.playlist = playlist206 self.playlist.add_listener(self)207 self.length_str = ""208 self.search_active = False209 self.search_string = ""210 def draw(self):211 f = Format()212 f.add(" Playlist ", termbox.WHITE | termbox.BOLD, termbox.BLACK)213 if self.search_active:214 f.add("Filter: ", termbox.WHITE, termbox.BLACK)215 if len(self.playlist) > 0:216 f.add(self.search_string, termbox.WHITE, termbox.BLACK)217 else:218 f.add(self.search_string, termbox.RED, termbox.BLACK)219 else:220 f.add(self.length_str, termbox.WHITE, termbox.BLACK)221 self.change_cells_format(0, 0, f)222 def list_changed(self, unused_list):223 self.length_str = "(%i items" % len(self.playlist)224 if self.playlist.playtime > 0:225 self.length_str += ", %s)" % playtime_str(self.playlist.playtime)226 else:227 self.length_str += ")"228 def list_search_started(self, unused_list):229 self.search_active = True230 self.search_string = self.playlist.search_string231 def list_search_stopped(self, unused_list):232 self.search_active = False233class BrowserUI(MainComponent, BrowserListener):234 def __init__(self, tb, browser):235 super(BrowserUI, self).__init__(tb, True)236 self.browser = browser237 self.browser.add_listener(self)238 self.start = 0239 self.node = None240 def _fix_bounds(self):241 if len(self.node) > 0:242 if (self.node.sel - self.start) >= self.h:243 self.start = self.node.sel - self.h + 1244 if self.node.sel < self.start:245 self.start = self.node.sel246 self.start = min(max(0, self.start), len(self.node) - 1)247 def _handle_resize(self):248 self._fix_bounds()249 def draw(self):250 if not self.node:251 return252 length = len(self.node)253 numw = 0254 if length > 0:255 numw = int(math.floor(math.log10(len(self.node)))) + 2256 empty = Format("".ljust(self.w))257 for y in xrange(self.h):258 pos = y + self.start259 if pos < length:260 f = format_browser_item(self.node[pos], pos,261 pos == self.node.sel, self.w, numw)262 self.change_cells_format(0, y, f)263 def browser_node_changed(self, browser):264 self.node = self.browser.curr_node265 self._fix_bounds()266 def browser_selected_changed(self, browser):267 self._fix_bounds()268 def browser_search_started(self, browser):269 self.node = self.browser.curr_node270 self._fix_bounds()271 def browser_search_stopped(self, browser):272 self.node = self.browser.curr_node273 self._fix_bounds()274 def search(self, s):275 self.browser.search(s)276 def select(self, index, rel=False):277 self.browser.select(index, rel)278 def selected(self):279 return self.browser.selected()280class CurrentSongUI(Component, StatusListener):281 def __init__(self, tb, status):282 super(CurrentSongUI, self).__init__(tb)283 self.set_pref_dim(-1, 1)284 self.set_dim(0, 0, tb.width(), 1)285 self.status = status286 status.add_listener(self)287 self.state_changed(status.state)288 def draw(self):289 song_line = self._song_format(self.status.current)290 self.change_cells_format(0, 0, song_line)291 def _song_format(self, song):292 f = Format()293 f.add(" " + symbol_player_states.get(self.status.state, ""),294 termbox.WHITE, termbox.BLACK)295 if song:296 f.add(" %s - %s - %s" % (song.artist, song.title, song.album),297 termbox.WHITE, termbox.BLACK)298 return f299 def state_changed(self, s):300 self.show() if s in ["play", "pause"] else self.hide()301class CommandLineUI(Component, CommandLineListener):302 # TODO: sub of component303 class MatchedWin(object):304 def __init__(self, tb, matched, maxh=5):305 self.tb = tb306 self.matched = matched307 self.start = 0308 self.sel = 0309 self.h = min(maxh, len(matched))310 self.w = tb.width()311 def _fix_bounds(self):312 if len(self.matched) > 0:313 if self.sel < 0:314 self.sel = -1315 self.start = 0316 else:317 self.sel = min(self.sel, len(self.matched) - 1)318 if (self.sel - self.start) >= self.h:319 self.start = self.sel - self.h + 1320 if self.sel < self.start:321 self.start = self.sel322 self.start = min(max(0, self.start),323 len(self.matched) - 1)324 def format(self):325 length = len(self.matched)326 empty = Format("".ljust(self.w))327 for y in xrange(self.h):328 pos = y + self.start329 f = Format()330 if y < length:331 def format_desc(d):332 return "(" + d + ")" if d else ""333 f.add("%3i " % (pos + 1), *color_cmdline_number)334 f.add("%s " % self.matched[pos].name,335 *color_cmdline_name)336 f.add(format_desc(self.matched[pos].description),337 *color_cmdline_description)338 if pos == self.sel:339 f.set_bold()340 yield f341 def select(self, index):342 self.sel = index343 self._fix_bounds()344 def __init__(self, tb, command):345 super(CommandLineUI, self).__init__(tb)346 self.command = command347 self.matched = None348 self.matchedw = None349 self.cl = None350 self.lines = [":"]351 self.set_pref_dim(-1, 1)352 self.set_dim(0, 0, tb.width(), 1)353 def draw(self):354 if self.matchedw:355 clh = self.matchedw.h356 for i, f in enumerate(self.matchedw.format()):357 self.change_cells_format(0, i, f)...
utilities.py
Source:utilities.py
...65 if cube_coord.var_name == 'time':66 logger.info("Fixing time...")67 cube.coord('time').convert_units(68 Unit('days since 1950-1-1 00:00:00', calendar='gregorian'))69 _fix_bounds(cube, cube.coord('time'))70 # fix longitude71 if cube_coord.var_name == 'lon':72 logger.info("Fixing longitude...")73 if cube.coord('longitude').points[0] < 0. and \74 cube.coord('longitude').points[-1] < 181.:75 cube.coord('longitude').points = \76 cube.coord('longitude').points + 180.77 _fix_bounds(cube, cube.coord('longitude'))78 cube.attributes['geospatial_lon_min'] = 0.79 cube.attributes['geospatial_lon_max'] = 360.80 nlon = len(cube.coord('longitude').points)81 _roll_cube_data(cube, int(nlon / 2), -1)82 # fix latitude83 if cube_coord.var_name == 'lat':84 logger.info("Fixing latitude...")85 _fix_bounds(cube, cube.coord('latitude'))86 # fix depth87 if cube_coord.var_name == 'lev':88 logger.info("Fixing depth...")89 _fix_bounds(cube, cube.coord('depth'))90 # fix air_pressure91 if cube_coord.var_name == 'air_pressure':92 logger.info("Fixing air pressure...")93 _fix_bounds(cube, cube.coord('air_pressure'))94 # remove CS95 cube.coord('latitude').coord_system = None96 cube.coord('longitude').coord_system = None97 return cube98def fix_var_metadata(cube, var_info):99 """Fix var metadata from CMOR table."""100 if var_info.standard_name == '':101 cube.standard_name = None102 else:103 cube.standard_name = var_info.standard_name104 cube.var_name = var_info.short_name105 cube.long_name = var_info.long_name106 _set_units(cube, var_info.units)107 return cube108def flip_dim_coord(cube, coord_name):109 """Flip (reverse) dimensional coordinate of cube."""110 logger.info("Flipping dimensional coordinate %s...", coord_name)111 coord = cube.coord(coord_name, dim_coords=True)112 coord_idx = cube.coord_dims(coord)[0]113 coord.points = np.flip(coord.points)114 if coord.bounds is not None:115 coord.bounds = np.flip(coord.bounds, axis=0)116 cube.data = da.flip(cube.core_data(), axis=coord_idx)117def read_cmor_config(dataset):118 """Read the associated dataset-specific config file."""119 reg_path = os.path.join(os.path.dirname(__file__), 'cmor_config',120 dataset + '.yml')121 with open(reg_path, 'r') as file:122 cfg = yaml.safe_load(file)123 cfg['cmor_table'] = \124 CMOR_TABLES[cfg['attributes']['project_id']]125 if 'comment' not in cfg:126 cfg['attributes']['comment'] = ''127 return cfg128def save_variable(cube, var, outdir, attrs, **kwargs):129 """Saver function."""130 # CMOR standard131 cube_time = cube.coord('time')132 reftime = Unit(cube_time.units.origin, cube_time.units.calendar)133 dates = reftime.num2date(cube_time.points[[0, -1]])134 if len(cube_time.points) == 1:135 year = str(dates[0].year)136 time_suffix = '-'.join([year + '01', year + '12'])137 else:138 date1 = str(dates[0].year) + '%02d' % dates[0].month139 date2 = str(dates[1].year) + '%02d' % dates[1].month140 time_suffix = '-'.join([date1, date2])141 file_name = '_'.join([142 'OBS',143 attrs['dataset_id'],144 attrs['modeling_realm'],145 attrs['version'],146 attrs['mip'],147 var,148 time_suffix,149 ]) + '.nc'150 file_path = os.path.join(outdir, file_name)151 logger.info('Saving: %s', file_path)152 status = 'lazy' if cube.has_lazy_data() else 'realized'153 logger.info('Cube has %s data [lazy is preferred]', status)154 iris.save(cube, file_path, fill_value=1e20, **kwargs)155def set_global_atts(cube, attrs):156 """Complete the cmorized file with global metadata."""157 logger.info("Setting global metadata...")158 attrs = dict(attrs)159 cube.attributes.clear()160 timestamp = datetime.datetime.utcnow()161 timestamp_format = "%Y-%m-%d %H:%M:%S"162 now_time = timestamp.strftime(timestamp_format)163 # Necessary attributes164 try:165 glob_dict = {166 'title': (f"{attrs.pop('dataset_id')} data reformatted for "167 f"ESMValTool v{version}"),168 'version':169 attrs.pop('version'),170 'tier':171 str(attrs.pop('tier')),172 'source':173 attrs.pop('source'),174 'reference':175 get_tag_value('references', attrs.pop('reference')),176 'comment':177 attrs.pop('comment'),178 'user':179 os.environ.get("USER", "unknown user"),180 'host':181 os.environ.get("HOSTNAME", "unknown host"),182 'history':183 f'Created on {now_time}',184 'project_id':185 attrs.pop('project_id'),186 }187 except KeyError:188 raise KeyError(189 "All CMORized datasets need the global attributes 'dataset_id', "190 "'version', 'tier', 'source', 'reference', 'comment' and "191 "'project_id' specified in the configuration file")192 # Additional attributes193 glob_dict.update(attrs)194 cube.attributes = glob_dict195def var_name_constraint(var_name):196 """:mod:`iris.Constraint` using `var_name` of an :mod:`iris.cube.Cube`."""197 return iris.Constraint(cube_func=lambda c: c.var_name == var_name)198def _fix_bounds(cube, dim_coord):199 """Reset and fix all bounds."""200 if len(cube.coord(dim_coord).points) > 1:201 if cube.coord(dim_coord).has_bounds():202 cube.coord(dim_coord).bounds = None203 cube.coord(dim_coord).guess_bounds()204 if cube.coord(dim_coord).has_bounds():205 cube.coord(dim_coord).bounds = da.array(206 cube.coord(dim_coord).core_bounds(), dtype='float64')207 return cube208def _fix_dim_coordnames(cube):209 """Perform a check on dim coordinate names."""210 # first check for CMOR standard coord;211 for coord in cube.coords():212 # guess the CMOR-standard x, y, z and t axes if not there...
day13.py
Source:day13.py
1from day import Day2from utils.grid import Grid3class FoldingGrid(Grid):4 fallback = ' '5 def _fix_bounds(self):6 new_x = []7 new_y = []8 for y in self.iter_y():9 for x in self.iter_x():10 if self[(x, y)] == '#':11 new_x.append(x)12 new_y.append(y)13 self.min_x = min(new_x)14 self.max_x = max(new_x)15 self.min_y = min(new_y)16 self.max_y = max(new_y)17 def count(self):18 return len([val for val in self.iter_values() if val == '#'])19 def fold(self, horizontal, position):20 if horizontal:21 self._fold_horizontal(position)22 else:23 self._fold_vertical(position)24 self._fix_bounds()25 def _fold_vertical(self, position):26 for y in range(position, self.max_y + 1):27 new_y = position - (y - position)28 for x in self.iter_x():29 current_new = self[(x, new_y)]30 current_old = self[(x, y)]31 if current_new == current_old == ' ':32 continue33 self[(x, new_y)] = '#'34 self[(x, y)] = ' '35 def _fold_horizontal(self, position):36 for x in range(position, self.max_x + 1):37 new_x = position - (x - position)38 for y in self.iter_y():...
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!!