Best Python code snippet using autotest_python
timeseries_meteo.py
Source:timeseries_meteo.py
1# -*- coding: utf-8 -*-2import sys3from netCDF4 import Dataset, num2date, date2index4from math import ceil, floor5from numpy import where, array6from os import unlink78#9# CONFIG10#1112IN_DIR = './'13OUT_DIR = './'1415# Description16# 'fname': input filename (without directory)17# 'value': name of "variable" (inside netCDF container) which contains a needed information18# (air temperature, precipitation, etc)19# 'fn_postfix': tail of output file (with extension)20# 'coef': arithmetic function, that will be applied to each value (you can use any of python arithmetical functions)21# 'group_func': group function, that will be applied for each year (it must be a numpy.ndarray method)22# 'lat_resolution': lat grids resolution23# 'lat_zero': means the lat's grid is started from24# (for example: = 0 if the first value of variables["lat"] is 0)25# 'lon_resolution': lon grids resolution26# 'lon_zero': means the lon's grid is started from27# (for example: = 0 if the first value of variables["lon"] is 0)2829IF = {}3031IF['TAS_HM'] = {32 'fname': 'tas_Amon_HadGEM2-AO_historical_r1i1p1_186001-200512.nc',33 'value': 'tas',34 'fn_postfix': '_tas_mod.txt',35 'coef': ' - 272.15',36 'group_func': 'mean()',37 'lat_resolution': 1.25,38 'lat_zero': 0,39 'lon_resolution': 1.875,40 'lon_zero': 041}4243IF['TAS_PR'] = {44 'fname': 'tas_Amon_HadGEM2-AO_rcp85_r1i1p1_200601-210012.nc',45 'value': 'tas',46 'fn_postfix': '_tas_mod.txt',47 'coef': ' - 272.15',48 'group_func': 'mean()',49 'lat_resolution': 1.25,50 'lat_zero': 0,51 'lon_resolution': 1.875,52 'lon_zero': 053}5455IF['TAS_HO'] = {56 'fname': 'air.mon.mean.v401.nc',57 'value': 'air',58 'fn_postfix': '_tas_obs.txt',59 'coef': '',60 'group_func': 'mean()',61 'lat_resolution': 0.5,62 'lat_zero': 0.25,63 'lon_resolution': 0.5,64 'lon_zero': 0.2565}6667IF['PRE_HM'] = {68 'fname': 'pr_Amon_HadGEM2-AO_historical_r1i1p1_186001-200512.nc',69 'value': 'pr',70 'fn_postfix': '_pre_mod.txt',71 'coef': ' * 2592000',72 'group_func': 'sum()',73 'lat_resolution': 1.25,74 'lat_zero': 0,75 'lon_resolution': 1.875,76 'lon_zero': 077}7879IF['PRE_PR'] = {80 'fname': 'pr_Amon_HadGEM2-AO_rcp85_r1i1p1_200601-210012.nc',81 'value': 'pr',82 'fn_postfix': '_pre_obs.txt',83 'coef': ' * 2592000',84 'group_func': 'sum()',85 'lat_resolution': 1.25,86 'lat_zero': 0,87 'lon_resolution': 1.875,88 'lon_zero': 089}9091IF['PRE_HO'] = {92 'fname': 'precip.mon.total.v401.nc',93 'value': 'precip',94 'fn_postfix': '_pre_obs.txt',95 'coef': ' * 10',96 'group_func': 'sum()',97 'lat_resolution': 0.5,98 'lat_zero': 0.25,99 'lon_resolution': 0.5,100 'lon_zero': 0.25101}102103104#105# END CONFIG106#107108# functions109def to_digit(x):110 try:111 if x.isdigit():112 return int(x)113 return float(x)114 except ValueError:115 return False116117118# Finding nearest grid square119def find_nearest(coord, scale, zero):120 sign = 1121 if coord < 0:122 sign = -1123 coord = abs(coord)124125 node = ceil(coord / scale) if coord - floor(coord / scale) > scale / 2 else floor(coord / scale)126 return (node * scale - zero) * sign127128129# Working with data130def get_data_by_year(t_elem, config, f_lat, f_lon):131 yearsum = {}132 lon = find_nearest(f_lon, config['lon_resolution'], config['lon_zero'])133 lat = find_nearest(f_lat, config['lat_resolution'], config['lat_zero'])134135 idx_lat = where(t_elem.variables["lat"][:] == lat)[0][0]136 idx_lon = where(t_elem.variables["lon"][:] == lon)[0][0]137138 calendar = t_elem.variables["time"].calendar if hasattr(t_elem.variables["time"], 'calendar') else 'standard'139 dates = num2date(t_elem.variables["time"][:], t_elem.variables["time"].units, calendar=calendar)140141 for time in dates:142 time_id = date2index(time, t_elem.variables["time"])143 if time.year not in yearsum:144 yearsum[time.year] = [t_elem.variables[config['value']][time_id][idx_lat][idx_lon]]145 else:146 yearsum[time.year].append(t_elem.variables[config['value']][time_id][idx_lat][idx_lon])147148 for tyear in yearsum:149 yearsum[tyear] = array(yearsum[tyear])150 yearsum[tyear] = eval("yearsum[tyear]." + config['group_func'])151 yearsum[tyear] = eval("yearsum[tyear] " + config['coef'])152 return yearsum, lon, lat153154155# input parameters156if len(sys.argv) < 4:157 print('Use command: python3 timeseries_meteo.py LON LAT ID')158 exit(1)159160LON = to_digit(sys.argv[1])161LAT = to_digit(sys.argv[2])162ID = to_digit(sys.argv[3])163164if not LON or not LAT or not ID:165 print('Use command: python3 timeseries_meteo.py LON LAT ID')166 exit(1)167168if LON > 360 or LAT > 90 or LAT < -90:169 print('Wrong coordinates')170 exit(1)171172# load all data from files173rootgrp = {}174175for i in IF:176 try:177 rootgrp[i] = Dataset(IN_DIR + str(IF[i]['fname']), "r")178 except OSError:179 print("Can't open file: %s" % IN_DIR + str(IF[i]['fname']))180 exit(1)181182# remove old files183for i in IF:184 try:185 unlink('{}{}{}'.format(OUT_DIR, ID, IF[i]['fn_postfix']))186 except OSError:187 continue188189# create new files190for i in rootgrp:191 print(IF[i]['fname'])192 result, grid_lon, grid_lat = get_data_by_year(rootgrp[i], IF[i], LAT, LON)193 if result:194 with open('{}{}{}'.format(OUT_DIR, ID, IF[i]['fn_postfix']), 'a') as file:195 for year in result:
...
history.py
Source:history.py
...21 comm_table[type] = (group_func, { })22def get_history(ch, type):23 '''return the communication history for a character.'''24 group_func, table = comm_table[type]25 key = group_func(ch)26 if not key in table:27 return [ ]28 return table[key]29def add_history(ch, type, mssg):30 group_func, table = comm_table[type]31 key = group_func(ch)32 if key != None:33 if not key in table:34 table[key] = [ ]35 table[key].append(mssg)36 # make sure we don't get too big37 while len(table[key]) > MAX_HISTORY_LEN:38 table[key].pop(0)39################################################################################40# commands41################################################################################42def cmd_history(ch, cmd, arg):43 '''Communication logs are stored as you receive communication. To review44 communication you have used, you can use the history command.'''45 arg = arg.lower()46 if arg == "":47 opts = comm_table.keys()48 opts.sort()49 ch.send("History logs available to you are:")50 ch.send(" " + ", ".join(opts))51 elif not arg in comm_table:52 ch.send("There is no history log for that type of communication.")53 else:54 group_func, table = comm_table[arg]55 key = group_func(ch)56 if not key in table:57 ch.send("Your history is empty.")58 else:59 ch.page("\r\n".join(table[key]) + "\r\n")60################################################################################61# initialization62################################################################################...
cogs.py
Source:cogs.py
...12 if update.message.chat.type == 'private':13 result = await private_func(update, context)14 return result15 else:16 result = await group_func(update, context)17 return result...
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!!