Search is not available for this dataset
text
stringlengths
75
104k
def split (s, delimter, trim = True, limit = 0): # pragma: no cover """ Split a string using a single-character delimter @params: `s`: the string `delimter`: the single-character delimter `trim`: whether to trim each part. Default: True @examples: ```python ret = split("'a,b',c", ",") # ret ==...
def render(self, **context): """ Render this template by applying it to `context`. @params: `context`: a dictionary of values to use in this rendering. @returns: The rendered string """ # Make the complete context we'll use. localns = self.envs.copy() localns.update(context) try: exec(str(se...
def addLine(self, line): """ Add a line of source to the code. Indentation and newline will be added for you, don't provide them. @params: `line`: The line to add """ if not isinstance(line, LiquidLine): line = LiquidLine(line) line.ndent = self.ndent self.codes.append(line)
def level(self, lvl=None): '''Get or set the logging level.''' if not lvl: return self._lvl self._lvl = self._parse_level(lvl) self.stream.setLevel(self._lvl) logging.root.setLevel(self._lvl)
def get_rate_from_db(currency: str) -> Decimal: """ Fetch currency conversion rate from the database """ from .models import ConversionRate try: rate = ConversionRate.objects.get_rate(currency) except ConversionRate.DoesNotExist: # noqa raise ValueError('No conversion rate for %...
def get_conversion_rate(from_currency: str, to_currency: str) -> Decimal: """ Get conversion rate to use in exchange """ reverse_rate = False if to_currency == BASE_CURRENCY: # Fetch exchange rate for base currency and use 1 / rate for conversion rate_currency = from_currency ...
def exchange_currency( base: T, to_currency: str, *, conversion_rate: Decimal=None) -> T: """ Exchanges Money, TaxedMoney and their ranges to the specified currency. get_rate parameter is a callable taking single argument (target currency) that returns proper conversion rate """ if base....
def normalize(location_name, preserve_commas=False): """Normalize *location_name* by stripping punctuation and collapsing runs of whitespace, and return the normalized name.""" def replace(match): if preserve_commas and ',' in match.group(0): return ',' return ' ' return NORM...
def calc_precipitation_stats(self, months=None, avg_stats=True, percentile=50): """ Calculates precipitation statistics for the cascade model while aggregating hourly observations Parameters ---------- months : Months for each seasons to be used for statistics (array of n...
def calc_wind_stats(self): """ Calculates statistics in order to derive diurnal patterns of wind speed """ a, b, t_shift = melodist.fit_cosine_function(self.data.wind) self.wind.update(a=a, b=b, t_shift=t_shift)
def calc_humidity_stats(self): """ Calculates statistics in order to derive diurnal patterns of relative humidity. """ a1, a0 = melodist.calculate_dewpoint_regression(self.data, return_stats=False) self.hum.update(a0=a0, a1=a1) self.hum.kr = 12 self.hum.month_hou...
def calc_temperature_stats(self): """ Calculates statistics in order to derive diurnal patterns of temperature """ self.temp.max_delta = melodist.get_shift_by_data(self.data.temp, self._lon, self._lat, self._timezone) self.temp.mean_course = melodist.util.calculate_mean_daily_cou...
def calc_radiation_stats(self, data_daily=None, day_length=None, how='all'): """ Calculates statistics in order to derive solar radiation from sunshine duration or minimum/maximum temperature. Parameters ---------- data_daily : DataFrame, optional Daily data ...
def to_json(self, filename=None): """ Exports statistical data to a JSON formatted file Parameters ---------- filename: output file that holds statistics data """ def json_encoder(obj): if isinstance(obj, pd.DataFrame) or isinstance(obj, pd.Series)...
def from_json(cls, filename): """ Imports statistical data from a JSON formatted file Parameters ---------- filename: input file that holds statistics data """ def json_decoder(d): if 'p01' in d and 'pxx' in d: # we assume this is a CascadeStatist...
def disaggregate_radiation(data_daily, sun_times=None, pot_rad=None, method='pot_rad', angstr_a=0.25, angstr_b=0.5, bristcamp_a=0.75, ...
def potential_radiation(dates, lon, lat, timezone, terrain_slope=0, terrain_slope_azimuth=0, cloud_fraction=0, split=False): """ Calculate potential shortwave radiation for a specific location and time. This routine calculates global radiation as described in: Liston, G. E...
def bristow_campbell(tmin, tmax, pot_rad_daily, A, C): """calculates potential shortwave radiation based on minimum and maximum temperature This routine calculates global radiation as described in: Bristow, Keith L., and Gaylon S. Campbell: On the relationship between incoming solar radiation and ...
def fit_bristow_campbell_params(tmin, tmax, pot_rad_daily, obs_rad_daily): """ Fit the A and C parameters for the Bristow & Campbell (1984) model using observed daily minimum and maximum temperature and mean daily (e.g. aggregated from hourly values) solar radiation. Parameters ---------...
def angstroem(ssd, day_length, pot_rad_daily, a, b): """ Calculate mean daily radiation from observed sunshine duration according to Angstroem (1924). Parameters ---------- ssd : Series Observed daily sunshine duration. day_length : Series Day lengths as calculated by...
def fit_angstroem_params(ssd, day_length, pot_rad_daily, obs_rad_daily): """ Fit the a and b parameters for the Angstroem (1924) model using observed daily sunshine duration and mean daily (e.g. aggregated from hourly values) solar radiation. Parameters ---------- ssd : Series ...
def register(name): """Return a decorator that registers the decorated class as a resolver with the given *name*.""" def decorator(class_): if name in known_resolvers: raise ValueError('duplicate resolver name "%s"' % name) known_resolvers[name] = class_ return decorator
def get_resolver(order=None, options=None, modules=None): """Return a location resolver. The *order* argument, if given, should be a list of resolver names; results from resolvers named earlier in the list are preferred over later ones. For a list of built-in resolver names, see :doc:`/resolvers`. Th...
def load_locations(self, location_file=None): """Load locations into this resolver from the given *location_file*, which should contain one JSON object per line representing a location. If *location_file* is not specified, an internal location database is used.""" if location_fi...
def canonical(self): """Return a tuple containing a canonicalized version of this location's country, state, county, and city names.""" try: return tuple(map(lambda x: x.lower(), self.name())) except: return tuple([x.lower() for x in self.name()])
def name(self): """Return a tuple containing this location's country, state, county, and city names.""" try: return tuple( getattr(self, x) if getattr(self, x) else u'' for x in ('country', 'state', 'county', 'city')) except: return...
def parent(self): """Return a location representing the administrative unit above the one represented by this location.""" if self.city: return Location( country=self.country, state=self.state, county=self.county) if self.county: return Location(co...
def disaggregate_humidity(data_daily, method='equal', temp=None, a0=None, a1=None, kr=None, month_hour_precip_mean=None, preserve_daily_mean=False): """general function for humidity disaggregation Args: daily_data: daily values method: keyword...
def _cosine_function(x, a, b, t_shift): """genrates a diurnal course of windspeed accroding to the cosine function Args: x: series of euqally distributed windspeed values a: parameter a for the cosine function b: parameter b for the cosine function t_shift: parameter t_shift for...
def disaggregate_wind(wind_daily, method='equal', a=None, b=None, t_shift=None): """general function for windspeed disaggregation Args: wind_daily: daily values method: keyword specifying the disaggregation method to be used a: parameter a for the cosine function b: parameter b ...
def fit_cosine_function(wind): """fits a cosine function to observed hourly windspeed data Args: wind: observed hourly windspeed data Returns: parameters needed to generate diurnal features of windspeed using a cosine function """ wind_daily = wind.groupby(wind.index.date)....
def read_smet(filename, mode): """Reads smet data and returns the data in required dataformat (pd df) See https://models.slf.ch/docserver/meteoio/SMET_specifications.pdf for further details on the specifications of this file format. Parameters ---- filename : SMET file to read mode : "...
def read_dwd(filename, metadata, mode="d", skip_last=True): """Reads dwd (German Weather Service) data and returns the data in required dataformat (pd df) Parameters ---- filename : DWD file to read (full path) / list of hourly files (RR+TU+FF) metadata : corresponding DWD metadata file to rea...
def write_smet(filename, data, metadata, nodata_value=-999, mode='h', check_nan=True): """writes smet files Parameters ---- filename : filename/loction of output data : data to write as pandas df metadata: header to write input as dict nodata_value: Nodata Value to write/use ...
def read_single_knmi_file(filename): """reads a single file of KNMI's meteorological time series data availability: www.knmi.nl/nederland-nu/klimatologie/uurgegevens Args: filename: the file to be opened Returns: pandas data frame including time series """ hourly_data_obs_raw ...
def read_knmi_dataset(directory): """Reads files from a directory and merges the time series Please note: For each station, a separate directory must be provided! data availability: www.knmi.nl/nederland-nu/klimatologie/uurgegevens Args: directory: directory including the files Returns: ...
def calc_sun_times(self): """ Computes the times of sunrise, solar noon, and sunset for each day. """ self.sun_times = melodist.util.get_sun_times(self.data_daily.index, self.lon, self.lat, self.timezone)
def disaggregate_wind(self, method='equal'): """ Disaggregate wind speed. Parameters ---------- method : str, optional Disaggregation method. ``equal`` Mean daily wind speed is duplicated for the 24 hours of the day. (Default) ...
def disaggregate_humidity(self, method='equal', preserve_daily_mean=False): """ Disaggregate relative humidity. Parameters ---------- method : str, optional Disaggregation method. ``equal`` Mean daily humidity is duplicated for the 24 hou...
def disaggregate_temperature(self, method='sine_min_max', min_max_time='fix', mod_nighttime=False): """ Disaggregate air temperature. Parameters ---------- method : str, optional Disaggregation method. ``sine_min_max`` Hourly temperatures...
def disaggregate_precipitation(self, method='equal', zerodiv='uniform', shift=0, master_precip=None): """ Disaggregate precipitation. Parameters ---------- method : str, optional Disaggregation method. ``equal`` Daily precipitation is dis...
def disaggregate_radiation(self, method='pot_rad', pot_rad=None): """ Disaggregate solar radiation. Parameters ---------- method : str, optional Disaggregation method. ``pot_rad`` Calculates potential clear-sky hourly radiation and scales...
def interpolate(self, column_hours, method='linear', limit=24, limit_direction='both', **kwargs): """ Wrapper function for ``pandas.Series.interpolate`` that can be used to "disaggregate" values using various interpolation methods. Parameters ---------- column_hours : di...
def _query_helper(self, by=None): """ Internal helper for preparing queries. """ if by is None: primary_keys = self.table.primary_key.columns.keys() if len(primary_keys) > 1: warnings.warn("WARNING: MORE THAN 1 PRIMARY KEY FOR TABLE %s. " ...
def head(self, n=10, by=None, **kwargs): """ Get the first n entries for a given Table/Column. Additional keywords passed to QueryDb.query(). Requires that the given table has a primary key specified. """ col, id_col = self._query_helper(by=by) select = ("SELECT...
def last(self, n=10, by=None, **kwargs): """ Alias for .tail(). """ return self.tail(n=n, by=by, **kwargs)
def where(self, where_string, **kwargs): """ Select from a given Table or Column with the specified WHERE clause string. Additional keywords are passed to ExploreSqlDB.query(). For convenience, if there is no '=', '>', '<', 'like', or 'LIKE' clause in the WHERE statement .where()...
def query(self, sql_query, return_as="dataframe"): """ Execute a raw SQL query against the the SQL DB. Args: sql_query (str): A raw SQL query to execute. Kwargs: return_as (str): Specify what type of object should be returned. The following are accep...
def _set_metadata(self): """ Internal helper to set metadata attributes. """ meta = QueryDbMeta() with self._engine.connect() as conn: meta.bind = conn meta.reflect() self._meta = meta # Set an inspect attribute, whose subattributes ...
def _to_df(self, query, conn, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None): """ Internal convert-to-DataFrame convenience wrapper. """ return pd.io.sql.read_sql(str(query), conn, index_col=index_col, coer...
def disaggregate_temperature(data_daily, method='sine_min_max', min_max_time='fix', mod_nighttime=False, max_delta=None, mean_course=None, sun_tim...
def get_shift_by_data(temp_hourly, lon, lat, time_zone): '''function to get max temp shift (monthly) by hourly data Parameters ---- hourly_data_obs : observed hourly data lat : latitude in DezDeg lon : longitude in DezDeg time_zone: timezone ''' d...
def distribute_equally(daily_data, divide=False): """Obtains hourly values by equally distributing the daily values. Args: daily_data: daily values divide: if True, divide resulting values by the number of hours in order to preserve the daily sum (required e.g. for precipitation). ...
def vapor_pressure(temp, hum): """ Calculates vapor pressure from temperature and humidity after Sonntag (1990). Args: temp: temperature values hum: humidity value(s). Can be scalar (e.g. for calculating saturation vapor pressure). Returns: Vapor pressure in hPa. """ i...
def dewpoint_temperature(temp, hum): """computes the dewpoint temperature Parameters ---- temp : temperature [K] hum : relative humidity Returns dewpoint temperature in K """ assert(temp.shape == hum.shape) vap_press = vapor_pressure(temp, hum) positiv...
def linregress(x, y, return_stats=False): """linear regression calculation Parameters ---- x : independent variable (series) y : dependent variable (series) return_stats : returns statistical values as well if required (bool) Returns ---- list of parameters (an...
def get_sun_times(dates, lon, lat, time_zone): """Computes the times of sunrise, solar noon, and sunset for each day. Parameters ---- dates: datetime lat : latitude in DecDeg lon : longitude in DecDeg time_zone : timezone Returns ---- DataFrame: [sunrise,...
def detect_gaps(dataframe, timestep, print_all=False, print_max=5, verbose=True): """checks if a given dataframe contains gaps and returns the number of gaps This funtion checks if a dataframe contains any gaps for a given temporal resolution that needs to be specified in seconds. The number of gaps de...
def drop_incomplete_days(dataframe, shift=0): """truncates a given dataframe to full days only This funtion truncates a given pandas dataframe (time series) to full days only, thus dropping leading and tailing hours of incomplete days. Please note that this methodology only applies to hourly time serie...
def daily_from_hourly(df): """Aggregates data (hourly to daily values) according to the characteristics of each variable (e.g., average for temperature, sum for precipitation) Args: df: dataframe including time series with one hour time steps Returns: dataframe (daily) """ df_...
def disagg_prec(dailyData, method='equal', cascade_options=None, hourly_data_obs=None, zerodiv="uniform", shift=0): """The disaggregation function for precipitation. Parameters ---------- dailyData : pd.Series daily...
def disagg_prec_cascade(precip_daily, cascade_options, hourly=True,level=9, shift=0, test=False): """Precipitation disaggregation with cascade model (Olsson, 1998) Parameters ---------- precip_daily : pd.Series daily data ...
def precip_master_station(precip_daily, master_precip_hourly, zerodiv): """Disaggregate precipitation based on the patterns of a master station Parameters ----------- precip_daily : pd.Series daily data master_precip_hourly : pd.Series ...
def aggregate_precipitation(vec_data,hourly=True, percentile=50): """Aggregates highly resolved precipitation data and creates statistics Parameters ---------- vec_data : pd.Series hourly (hourly=True) OR 5-min values Returns ------- output : cascade object representing st...
def seasonal_subset(dataframe, months='all'): '''Get the seasonal data. Parameters ---------- dataframe : pd.DataFrame months: int, str Months to use for statistics, or 'all' for 1-12 (default='all') ''' if isinstance(months, str) and months == 'all': mo...
def build_casc(ObsData, hourly=True,level=9, months=None, avg_stats=True, percentile=50): '''Builds the cascade statistics of observed data for disaggregation Parameters ----------- ObsData : pd.Series hourly=True -> hourly obs data else -> 5...
def fill_with_sample_data(self): """This function fills the corresponding object with sample data.""" # replace these sample data with another dataset later # this function is deprecated as soon as a common file format for this # type of data will be available self.p01 = np.array...
def names(cls): """A list of all emoji names without file extension.""" if not cls._files: for f in os.listdir(cls._image_path): if(not f.startswith('.') and os.path.isfile(os.path.join(cls._image_path, f))): cls._files.append(os.path.sp...
def replace(cls, replacement_string): """Add in valid emojis in a string where a valid emoji is between ::""" e = cls() def _replace_emoji(match): val = match.group(1) if val in e: return e._image_string(match.group(1)) else: r...
def replace_unicode(cls, replacement_string): """This method will iterate over every character in ``replacement_string`` and see if it mathces any of the unicode codepoints that we recognize. If it does then it will replace that codepoint with an image just like ``replace``. NOT...
def replace_html_entities(cls, replacement_string): """Replaces HTML escaped unicode entities with their unicode equivalent. If the setting `EMOJI_REPLACE_HTML_ENTITIES` is `True` then this conversation will always be done in `replace_unicode` (default: True). """ def _h...
def _convert_to_unicode(string): """This method should work with both Python 2 and 3 with the caveat that they need to be compiled with wide unicode character support. If there isn't wide unicode character support it'll blow up with a warning. """ codepoints = [] for character in string.sp...
def _delete_file(configurator, path): """ remove file and remove it's directories if empty """ path = os.path.join(configurator.target_directory, path) os.remove(path) try: os.removedirs(os.path.dirname(path)) except OSError: pass
def _insert_manifest_item(configurator, key, item): """ Insert an item in the list of an existing manifest key """ with _open_manifest(configurator) as f: manifest = f.read() if item in ast.literal_eval(manifest).get(key, []): return pattern = """(["']{}["']:\\s*\\[)""".format(key) r...
def _read_requirements(filename): """Parses a file for pip installation requirements.""" with open(filename) as requirements_file: contents = requirements_file.read() return [line.strip() for line in contents.splitlines() if _is_requirement(line)]
def assign_perm(perm, group): """ Assigns a permission to a group """ if not isinstance(perm, Permission): try: app_label, codename = perm.split('.', 1) except ValueError: raise ValueError("For global permissions, first argument must be in" ...
def remove_perm(perm, group): """ Removes a permission from a group """ if not isinstance(perm, Permission): try: app_label, codename = perm.split('.', 1) except ValueError: raise ValueError("For global permissions, first argument must be in" ...
def get_list_class(context, list): """ Returns the class to use for the passed in list. We just build something up from the object type for the list. """ return "list_%s_%s" % (list.model._meta.app_label, list.model._meta.model_name)
def format_datetime(time): """ Formats a date, converting the time to the user timezone if one is specified """ user_time_zone = timezone.get_current_timezone() if time.tzinfo is None: time = time.replace(tzinfo=pytz.utc) user_time_zone = pytz.timezone(getattr(settings, 'USER_TIME_ZO...
def get_value_from_view(context, field): """ Responsible for deriving the displayed value for the passed in 'field'. This first checks for a particular method on the ListView, then looks for a method on the object, then finally treats it as an attribute. """ view = context['view'] obj = Non...
def get_class(context, field, obj=None): """ Looks up the class for this field """ view = context['view'] return view.lookup_field_class(field, obj, "field_" + field)
def get_label(context, field, obj=None): """ Responsible for figuring out the right label for the passed in field. The order of precedence is: 1) if the view has a field_config and a label specified there, use that label 2) check for a form in the view, if it contains that field, use it's val...
def get_field_link(context, field, obj=None): """ Determine what the field link should be for the given field, object pair """ view = context['view'] return view.lookup_field_link(context, field, obj)
def get_permissions_app_name(): """ Gets the app after which smartmin permissions should be installed. This can be specified by PERMISSIONS_APP in the Django settings or defaults to the last app with models """ global permissions_app_name if not permissions_app_name: permissions_app_nam...
def check_role_permissions(role, permissions, current_permissions): """ Checks the the passed in role (can be user, group or AnonymousUser) has all the passed in permissions, granting them if necessary. """ role_permissions = [] # get all the current permissions, we'll remove these as we verif...
def check_all_group_permissions(sender, **kwargs): """ Checks that all the permissions specified in our settings.py are set for our groups. """ if not is_permissions_app(sender): return config = getattr(settings, 'GROUP_PERMISSIONS', dict()) # for each of our items for name, permis...
def add_permission(content_type, permission): """ Adds the passed in permission to that content type. Note that the permission passed in should be a single word, or verb. The proper 'codename' will be generated from that. """ # build our permission slug codename = "%s_%s" % (content_type.model...
def check_all_permissions(sender, **kwargs): """ This syncdb checks our PERMISSIONS setting in settings.py and makes sure all those permissions actually exit. """ if not is_permissions_app(sender): return config = getattr(settings, 'PERMISSIONS', dict()) # for each of our items ...
def save(self, commit=True): """ Overloaded so we can save any new password that is included. """ is_new_user = self.instance.pk is None user = super(UserForm, self).save(commit) # new users should be made active by default if is_new_user: user.is_ac...
def smart_url(url, obj=None): """ URLs that start with @ are reversed, using the passed in arguments. Otherwise a straight % substitution is applied. """ if url.find("@") >= 0: (args, value) = url.split('@') if args: val = getattr(obj, args, None) return rev...
def derive_single_object_url_pattern(slug_url_kwarg, path, action): """ Utility function called by class methods for single object views """ if slug_url_kwarg: return r'^%s/%s/(?P<%s>[^/]+)/$' % (path, action, slug_url_kwarg) else: return r'^%s/%s/(?P<pk>\d+)/$' % (path, action)
def has_permission(self, request, *args, **kwargs): """ Figures out if the current user has permissions for this view. """ self.kwargs = kwargs self.args = args self.request = request if not getattr(self, 'permission', None): return True else:...
def dispatch(self, request, *args, **kwargs): """ Overloaded to check permissions if appropriate """ def wrapper(request, *args, **kwargs): if not self.has_permission(request, *args, **kwargs): path = urlquote(request.get_full_path()) login_url...
def lookup_obj_attribute(self, obj, field): """ Looks for a field's value from the passed in obj. Note that this will strip leading attributes to deal with subelements if possible """ curr_field = field.encode('ascii', 'ignore').decode("utf-8") rest = None if fi...
def lookup_field_value(self, context, obj, field): """ Looks up the field value for the passed in object and field name. Note that this method is actually called from a template, but this provides a hook for subclasses to modify behavior if they wish to do so. This may be used ...
def lookup_field_label(self, context, field, default=None): """ Figures out what the field label should be for the passed in field name. Our heuristic is as follows: 1) we check to see if our field_config has a label specified 2) if not, then we derive a field value from...
def lookup_field_help(self, field, default=None): """ Looks up the help text for the passed in field. """ help = None # is there a label specified for this field if field in self.field_config and 'help' in self.field_config[field]: help = self.field_config[fi...
def lookup_field_class(self, field, obj=None, default=None): """ Looks up any additional class we should include when rendering this field """ css = "" # is there a class specified for this field if field in self.field_config and 'class' in self.field_config[field]: ...
def get_template_names(self): """ Returns the name of the template to use to render this request. Smartmin provides default templates as fallbacks, so appends it's own templates names to the end of whatever list is built by the generic views. Subclasses can override this by set...
def derive_fields(self): """ Default implementation """ fields = [] if self.fields: fields.append(self.fields) return fields