repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
mdredze/carmen-python | carmen/resolver.py | get_resolver | 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... | python | 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",
"get_resolver",
"(",
"order",
"=",
"None",
",",
"options",
"=",
"None",
",",
"modules",
"=",
"None",
")",
":",
"if",
"not",
"known_resolvers",
":",
"from",
".",
"import",
"resolvers",
"as",
"carmen_resolvers",
"modules",
"=",
"[",
"carmen_resolvers",
... | 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`. The *options*
argument can be used to pass configuration option... | [
"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... | 070b974222b5407f7aae2518ffbdf9df198b8e96 | https://github.com/mdredze/carmen-python/blob/070b974222b5407f7aae2518ffbdf9df198b8e96/carmen/resolver.py#L115-L149 | train |
mdredze/carmen-python | carmen/resolver.py | AbstractResolver.load_locations | 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... | python | 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",
"load_locations",
"(",
"self",
",",
"location_file",
"=",
"None",
")",
":",
"if",
"location_file",
"is",
"None",
":",
"contents",
"=",
"pkgutil",
".",
"get_data",
"(",
"__package__",
",",
"'data/locations.json'",
")",
"contents_string",
"=",
"contents",
... | 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. | [
"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",
"spe... | 070b974222b5407f7aae2518ffbdf9df198b8e96 | https://github.com/mdredze/carmen-python/blob/070b974222b5407f7aae2518ffbdf9df198b8e96/carmen/resolver.py#L22-L40 | train |
mdredze/carmen-python | carmen/location.py | Location.canonical | 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()]) | python | 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",
"canonical",
"(",
"self",
")",
":",
"try",
":",
"return",
"tuple",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"lower",
"(",
")",
",",
"self",
".",
"name",
"(",
")",
")",
")",
"except",
":",
"return",
"tuple",
"(",
"[",
"x",
".",
"l... | Return a tuple containing a canonicalized version of this
location's country, state, county, and city names. | [
"Return",
"a",
"tuple",
"containing",
"a",
"canonicalized",
"version",
"of",
"this",
"location",
"s",
"country",
"state",
"county",
"and",
"city",
"names",
"."
] | 070b974222b5407f7aae2518ffbdf9df198b8e96 | https://github.com/mdredze/carmen-python/blob/070b974222b5407f7aae2518ffbdf9df198b8e96/carmen/location.py#L79-L85 | train |
mdredze/carmen-python | carmen/location.py | Location.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... | python | 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",
"name",
"(",
"self",
")",
":",
"try",
":",
"return",
"tuple",
"(",
"getattr",
"(",
"self",
",",
"x",
")",
"if",
"getattr",
"(",
"self",
",",
"x",
")",
"else",
"u''",
"for",
"x",
"in",
"(",
"'country'",
",",
"'state'",
",",
"'county'",
",",... | Return a tuple containing this location's country, state,
county, and city names. | [
"Return",
"a",
"tuple",
"containing",
"this",
"location",
"s",
"country",
"state",
"county",
"and",
"city",
"names",
"."
] | 070b974222b5407f7aae2518ffbdf9df198b8e96 | https://github.com/mdredze/carmen-python/blob/070b974222b5407f7aae2518ffbdf9df198b8e96/carmen/location.py#L87-L97 | train |
mdredze/carmen-python | carmen/location.py | Location.parent | 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... | python | 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",
"parent",
"(",
"self",
")",
":",
"if",
"self",
".",
"city",
":",
"return",
"Location",
"(",
"country",
"=",
"self",
".",
"country",
",",
"state",
"=",
"self",
".",
"state",
",",
"county",
"=",
"self",
".",
"county",
")",
"if",
"self",
".",
... | Return a location representing the administrative unit above
the one represented by this location. | [
"Return",
"a",
"location",
"representing",
"the",
"administrative",
"unit",
"above",
"the",
"one",
"represented",
"by",
"this",
"location",
"."
] | 070b974222b5407f7aae2518ffbdf9df198b8e96 | https://github.com/mdredze/carmen-python/blob/070b974222b5407f7aae2518ffbdf9df198b8e96/carmen/location.py#L99-L109 | train |
kristianfoerster/melodist | melodist/humidity.py | disaggregate_humidity | 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... | python | 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",
"disaggregate_humidity",
"(",
"data_daily",
",",
"method",
"=",
"'equal'",
",",
"temp",
"=",
"None",
",",
"a0",
"=",
"None",
",",
"a1",
"=",
"None",
",",
"kr",
"=",
"None",
",",
"month_hour_precip_mean",
"=",
"None",
",",
"preserve_daily_mean",
"=",... | general function for humidity disaggregation
Args:
daily_data: daily values
method: keyword specifying the disaggregation method to be used
temp: hourly temperature time series (necessary for some methods)
kr: parameter for linear_dewpoint_variation method (6 or 12)
month_ho... | [
"general",
"function",
"for",
"humidity",
"disaggregation"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/humidity.py#L33-L109 | train |
kristianfoerster/melodist | melodist/wind.py | _cosine_function | 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... | python | 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",
"_cosine_function",
"(",
"x",
",",
"a",
",",
"b",
",",
"t_shift",
")",
":",
"mean_wind",
",",
"t",
"=",
"x",
"return",
"a",
"*",
"mean_wind",
"*",
"np",
".",
"cos",
"(",
"np",
".",
"pi",
"*",
"(",
"t",
"-",
"t_shift",
")",
"/",
"12",
"... | 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 the cosine function
Returns:
... | [
"genrates",
"a",
"diurnal",
"course",
"of",
"windspeed",
"accroding",
"to",
"the",
"cosine",
"function"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/wind.py#L33-L47 | train |
kristianfoerster/melodist | melodist/wind.py | disaggregate_wind | 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 ... | python | 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",
"disaggregate_wind",
"(",
"wind_daily",
",",
"method",
"=",
"'equal'",
",",
"a",
"=",
"None",
",",
"b",
"=",
"None",
",",
"t_shift",
"=",
"None",
")",
":",
"assert",
"method",
"in",
"(",
"'equal'",
",",
"'cosine'",
",",
"'random'",
")",
",",
"... | 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 for the cosine function
t_shift: parameter t_shift for the cosine function
... | [
"general",
"function",
"for",
"windspeed",
"disaggregation"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/wind.py#L50-L75 | train |
kristianfoerster/melodist | melodist/wind.py | fit_cosine_function | 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).... | python | 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",
"fit_cosine_function",
"(",
"wind",
")",
":",
"wind_daily",
"=",
"wind",
".",
"groupby",
"(",
"wind",
".",
"index",
".",
"date",
")",
".",
"mean",
"(",
")",
"wind_daily_hourly",
"=",
"pd",
".",
"Series",
"(",
"index",
"=",
"wind",
".",
"index",
... | 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 | [
"fits",
"a",
"cosine",
"function",
"to",
"observed",
"hourly",
"windspeed",
"data"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/wind.py#L78-L94 | train |
kristianfoerster/melodist | melodist/data_io.py | read_smet | 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 : "... | python | 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_smet",
"(",
"filename",
",",
"mode",
")",
":",
"# dictionary",
"# based on smet spec V.1.1 and self defined",
"# daily data",
"dict_d",
"=",
"{",
"'TA'",
":",
"'tmean'",
",",
"'TMAX'",
":",
"'tmax'",
",",
"# no spec",
"'TMIN'",
":",
"'tmin'",
",",
"... | 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 : "d" for daily and "h" for hourly input
... | [
"Reads",
"smet",
"data",
"and",
"returns",
"the",
"data",
"in",
"required",
"dataformat",
"(",
"pd",
"df",
")"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/data_io.py#L33-L113 | train |
kristianfoerster/melodist | melodist/data_io.py | read_dwd | 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... | python | 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",
"read_dwd",
"(",
"filename",
",",
"metadata",
",",
"mode",
"=",
"\"d\"",
",",
"skip_last",
"=",
"True",
")",
":",
"def",
"read_single_dwd",
"(",
"filename",
",",
"metadata",
",",
"mode",
",",
"skip_last",
")",
":",
"# Param names {'DWD':'dissag_def'}",
... | 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 read
mode : "d" for daily and "h" for hourly input
skip_las... | [
"Reads",
"dwd",
"(",
"German",
"Weather",
"Service",
")",
"data",
"and",
"returns",
"the",
"data",
"in",
"required",
"dataformat",
"(",
"pd",
"df",
")"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/data_io.py#L116-L233 | train |
kristianfoerster/melodist | melodist/data_io.py | write_smet | 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
... | python | 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",
"write_smet",
"(",
"filename",
",",
"data",
",",
"metadata",
",",
"nodata_value",
"=",
"-",
"999",
",",
"mode",
"=",
"'h'",
",",
"check_nan",
"=",
"True",
")",
":",
"# dictionary",
"# based on smet spec V.1.1 and selfdefined",
"# daily data",
"dict_d",
"=... | 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
mode: defines if to write daily ("d") or continuos data (default 'h')
check_nan... | [
"writes",
"smet",
"files"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/data_io.py#L236-L320 | train |
kristianfoerster/melodist | melodist/data_io.py | read_single_knmi_file | 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 ... | python | 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_single_knmi_file",
"(",
"filename",
")",
":",
"hourly_data_obs_raw",
"=",
"pd",
".",
"read_csv",
"(",
"filename",
",",
"parse_dates",
"=",
"[",
"[",
"'YYYYMMDD'",
",",
"'HH'",
"]",
"]",
",",
"date_parser",
"=",
"lambda",
"yyyymmdd",
",",
"hh",
... | 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 | [
"reads",
"a",
"single",
"file",
"of",
"KNMI",
"s",
"meteorological",
"time",
"series"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/data_io.py#L323-L367 | train |
kristianfoerster/melodist | melodist/data_io.py | read_knmi_dataset | 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:
... | python | 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",
"read_knmi_dataset",
"(",
"directory",
")",
":",
"filemask",
"=",
"'%s*.txt'",
"%",
"directory",
"filelist",
"=",
"glob",
".",
"glob",
"(",
"filemask",
")",
"columns_hourly",
"=",
"[",
"'temp'",
",",
"'precip'",
",",
"'glob'",
",",
"'hum'",
",",
"'w... | 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:
pandas data frame including time s... | [
"Reads",
"files",
"from",
"a",
"directory",
"and",
"merges",
"the",
"time",
"series"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/data_io.py#L370-L397 | train |
kristianfoerster/melodist | melodist/station.py | Station.calc_sun_times | 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) | python | 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",
"calc_sun_times",
"(",
"self",
")",
":",
"self",
".",
"sun_times",
"=",
"melodist",
".",
"util",
".",
"get_sun_times",
"(",
"self",
".",
"data_daily",
".",
"index",
",",
"self",
".",
"lon",
",",
"self",
".",
"lat",
",",
"self",
".",
"timezone",
... | Computes the times of sunrise, solar noon, and sunset for each day. | [
"Computes",
"the",
"times",
"of",
"sunrise",
"solar",
"noon",
"and",
"sunset",
"for",
"each",
"day",
"."
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/station.py#L174-L179 | train |
kristianfoerster/melodist | melodist/station.py | Station.disaggregate_wind | 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)
... | python | 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_wind",
"(",
"self",
",",
"method",
"=",
"'equal'",
")",
":",
"self",
".",
"data_disagg",
".",
"wind",
"=",
"melodist",
".",
"disaggregate_wind",
"(",
"self",
".",
"data_daily",
".",
"wind",
",",
"method",
"=",
"method",
",",
"*",
"*"... | Disaggregate wind speed.
Parameters
----------
method : str, optional
Disaggregation method.
``equal``
Mean daily wind speed is duplicated for the 24 hours of the day. (Default)
``cosine``
Distributes daily mean wind speed us... | [
"Disaggregate",
"wind",
"speed",
"."
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/station.py#L181-L201 | train |
kristianfoerster/melodist | melodist/station.py | Station.disaggregate_humidity | 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... | python | 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_humidity",
"(",
"self",
",",
"method",
"=",
"'equal'",
",",
"preserve_daily_mean",
"=",
"False",
")",
":",
"self",
".",
"data_disagg",
".",
"hum",
"=",
"melodist",
".",
"disaggregate_humidity",
"(",
"self",
".",
"data_daily",
",",
"temp",
... | Disaggregate relative humidity.
Parameters
----------
method : str, optional
Disaggregation method.
``equal``
Mean daily humidity is duplicated for the 24 hours of the day. (Default)
``minimal``:
Calculates humidity from dail... | [
"Disaggregate",
"relative",
"humidity",
"."
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/station.py#L203-L243 | train |
kristianfoerster/melodist | melodist/station.py | Station.disaggregate_temperature | 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... | python | 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_temperature",
"(",
"self",
",",
"method",
"=",
"'sine_min_max'",
",",
"min_max_time",
"=",
"'fix'",
",",
"mod_nighttime",
"=",
"False",
")",
":",
"self",
".",
"data_disagg",
".",
"temp",
"=",
"melodist",
".",
"disaggregate_temperature",
"(",... | Disaggregate air temperature.
Parameters
----------
method : str, optional
Disaggregation method.
``sine_min_max``
Hourly temperatures follow a sine function preserving daily minimum
and maximum values. (Default)
``sine_mean`... | [
"Disaggregate",
"air",
"temperature",
"."
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/station.py#L245-L296 | train |
kristianfoerster/melodist | melodist/station.py | Station.disaggregate_precipitation | 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... | python | 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_precipitation",
"(",
"self",
",",
"method",
"=",
"'equal'",
",",
"zerodiv",
"=",
"'uniform'",
",",
"shift",
"=",
"0",
",",
"master_precip",
"=",
"None",
")",
":",
"if",
"method",
"==",
"'equal'",
":",
"precip_disagg",
"=",
"melodist",
... | Disaggregate precipitation.
Parameters
----------
method : str, optional
Disaggregation method.
``equal``
Daily precipitation is distributed equally over the 24 hours of the day. (Default)
``cascade``
Hourly precipitation val... | [
"Disaggregate",
"precipitation",
"."
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/station.py#L298-L338 | train |
kristianfoerster/melodist | melodist/station.py | Station.disaggregate_radiation | 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... | python | 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",
"disaggregate_radiation",
"(",
"self",
",",
"method",
"=",
"'pot_rad'",
",",
"pot_rad",
"=",
"None",
")",
":",
"if",
"self",
".",
"sun_times",
"is",
"None",
":",
"self",
".",
"calc_sun_times",
"(",
")",
"if",
"pot_rad",
"is",
"None",
"and",
"metho... | Disaggregate solar radiation.
Parameters
----------
method : str, optional
Disaggregation method.
``pot_rad``
Calculates potential clear-sky hourly radiation and scales it according to the
mean daily radiation. (Default)
``po... | [
"Disaggregate",
"solar",
"radiation",
"."
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/station.py#L340-L383 | train |
kristianfoerster/melodist | melodist/station.py | Station.interpolate | 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... | python | 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",
"interpolate",
"(",
"self",
",",
"column_hours",
",",
"method",
"=",
"'linear'",
",",
"limit",
"=",
"24",
",",
"limit_direction",
"=",
"'both'",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"dict",
"(",
"kwargs",
",",
"method",
"=",
"method... | Wrapper function for ``pandas.Series.interpolate`` that can be used to
"disaggregate" values using various interpolation methods.
Parameters
----------
column_hours : dict
Dictionary containing column names in ``data_daily`` and the hour
values they should be ass... | [
"Wrapper",
"function",
"for",
"pandas",
".",
"Series",
".",
"interpolate",
"that",
"can",
"be",
"used",
"to",
"disaggregate",
"values",
"using",
"various",
"interpolation",
"methods",
"."
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/station.py#L385-L412 | train |
boydgreenfield/query | query/core.py | QueryDbOrm._query_helper | 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. "
... | python | 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",
"_query_helper",
"(",
"self",
",",
"by",
"=",
"None",
")",
":",
"if",
"by",
"is",
"None",
":",
"primary_keys",
"=",
"self",
".",
"table",
".",
"primary_key",
".",
"columns",
".",
"keys",
"(",
")",
"if",
"len",
"(",
"primary_keys",
")",
">",
... | Internal helper for preparing queries. | [
"Internal",
"helper",
"for",
"preparing",
"queries",
"."
] | 03aa43b746b43832af3f0403265e648a5617b62b | https://github.com/boydgreenfield/query/blob/03aa43b746b43832af3f0403265e648a5617b62b/query/core.py#L72-L99 | train |
boydgreenfield/query | query/core.py | QueryDbOrm.head | 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... | python | 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",
"head",
"(",
"self",
",",
"n",
"=",
"10",
",",
"by",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"col",
",",
"id_col",
"=",
"self",
".",
"_query_helper",
"(",
"by",
"=",
"by",
")",
"select",
"=",
"(",
"\"SELECT %s FROM %s ORDER BY %s ASC L... | 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. | [
"Get",
"the",
"first",
"n",
"entries",
"for",
"a",
"given",
"Table",
"/",
"Column",
".",
"Additional",
"keywords",
"passed",
"to",
"QueryDb",
".",
"query",
"()",
"."
] | 03aa43b746b43832af3f0403265e648a5617b62b | https://github.com/boydgreenfield/query/blob/03aa43b746b43832af3f0403265e648a5617b62b/query/core.py#L101-L113 | train |
boydgreenfield/query | query/core.py | QueryDbOrm.last | def last(self, n=10, by=None, **kwargs):
"""
Alias for .tail().
"""
return self.tail(n=n, by=by, **kwargs) | python | def last(self, n=10, by=None, **kwargs):
"""
Alias for .tail().
"""
return self.tail(n=n, by=by, **kwargs) | [
"def",
"last",
"(",
"self",
",",
"n",
"=",
"10",
",",
"by",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"tail",
"(",
"n",
"=",
"n",
",",
"by",
"=",
"by",
",",
"*",
"*",
"kwargs",
")"
] | Alias for .tail(). | [
"Alias",
"for",
".",
"tail",
"()",
"."
] | 03aa43b746b43832af3f0403265e648a5617b62b | https://github.com/boydgreenfield/query/blob/03aa43b746b43832af3f0403265e648a5617b62b/query/core.py#L134-L138 | train |
boydgreenfield/query | query/core.py | QueryDbOrm.where | 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()... | python | 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",
"where",
"(",
"self",
",",
"where_string",
",",
"*",
"*",
"kwargs",
")",
":",
"col",
",",
"id_col",
"=",
"self",
".",
"_query_helper",
"(",
"by",
"=",
"None",
")",
"where_string",
"=",
"str",
"(",
"where_string",
")",
"# Coerce here, for .__contains... | 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() tries to match the input string
against the primary ... | [
"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",
... | 03aa43b746b43832af3f0403265e648a5617b62b | https://github.com/boydgreenfield/query/blob/03aa43b746b43832af3f0403265e648a5617b62b/query/core.py#L140-L170 | train |
boydgreenfield/query | query/core.py | QueryDb.query | 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... | python | 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",
"query",
"(",
"self",
",",
"sql_query",
",",
"return_as",
"=",
"\"dataframe\"",
")",
":",
"if",
"isinstance",
"(",
"sql_query",
",",
"str",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"sql_query",
",",
"unicode",
")",
":",
"sql_query",
"=",
"str"... | 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 acceptable types:
- "dataframe": pandas.DataFrame or None if no ... | [
"Execute",
"a",
"raw",
"SQL",
"query",
"against",
"the",
"the",
"SQL",
"DB",
"."
] | 03aa43b746b43832af3f0403265e648a5617b62b | https://github.com/boydgreenfield/query/blob/03aa43b746b43832af3f0403265e648a5617b62b/query/core.py#L298-L335 | train |
boydgreenfield/query | query/core.py | QueryDb._set_metadata | 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
... | python | 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",
"_set_metadata",
"(",
"self",
")",
":",
"meta",
"=",
"QueryDbMeta",
"(",
")",
"with",
"self",
".",
"_engine",
".",
"connect",
"(",
")",
"as",
"conn",
":",
"meta",
".",
"bind",
"=",
"conn",
"meta",
".",
"reflect",
"(",
")",
"self",
".",
"_met... | Internal helper to set metadata attributes. | [
"Internal",
"helper",
"to",
"set",
"metadata",
"attributes",
"."
] | 03aa43b746b43832af3f0403265e648a5617b62b | https://github.com/boydgreenfield/query/blob/03aa43b746b43832af3f0403265e648a5617b62b/query/core.py#L337-L373 | train |
boydgreenfield/query | query/core.py | QueryDb._to_df | 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... | python | 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",
"_to_df",
"(",
"self",
",",
"query",
",",
"conn",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"params",
"=",
"None",
",",
"parse_dates",
"=",
"None",
",",
"columns",
"=",
"None",
")",
":",
"return",
"pd",
".",
"io",
... | Internal convert-to-DataFrame convenience wrapper. | [
"Internal",
"convert",
"-",
"to",
"-",
"DataFrame",
"convenience",
"wrapper",
"."
] | 03aa43b746b43832af3f0403265e648a5617b62b | https://github.com/boydgreenfield/query/blob/03aa43b746b43832af3f0403265e648a5617b62b/query/core.py#L375-L382 | train |
kristianfoerster/melodist | melodist/temperature.py | disaggregate_temperature | def disaggregate_temperature(data_daily,
method='sine_min_max',
min_max_time='fix',
mod_nighttime=False,
max_delta=None,
mean_course=None,
sun_tim... | python | 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",
"disaggregate_temperature",
"(",
"data_daily",
",",
"method",
"=",
"'sine_min_max'",
",",
"min_max_time",
"=",
"'fix'",
",",
"mod_nighttime",
"=",
"False",
",",
"max_delta",
"=",
"None",
",",
"mean_course",
"=",
"None",
",",
"sun_times",
"=",
"None",
")... | The disaggregation function for temperature
Parameters
----
data_daily : daily data
method : method to disaggregate
min_max_time: "fix" - min/max temperature at fixed times 7h/14h,
"sun_loc" - min/max calculated by sunrise/sunnoon + 2h,
... | [
"The",
"disaggregation",
"function",
"for",
"temperature"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/temperature.py#L33-L212 | train |
kristianfoerster/melodist | melodist/temperature.py | get_shift_by_data | 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... | python | 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",
"get_shift_by_data",
"(",
"temp_hourly",
",",
"lon",
",",
"lat",
",",
"time_zone",
")",
":",
"daily_index",
"=",
"temp_hourly",
".",
"resample",
"(",
"'D'",
")",
".",
"mean",
"(",
")",
".",
"index",
"sun_times",
"=",
"melodist",
".",
"util",
".",
... | 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 | [
"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_z... | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/temperature.py#L215-L235 | train |
kristianfoerster/melodist | melodist/util/util.py | distribute_equally | 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).
... | python | 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",
"distribute_equally",
"(",
"daily_data",
",",
"divide",
"=",
"False",
")",
":",
"index",
"=",
"hourly_index",
"(",
"daily_data",
".",
"index",
")",
"hourly_data",
"=",
"daily_data",
".",
"reindex",
"(",
"index",
")",
"hourly_data",
"=",
"hourly_data",
... | 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).
Returns:
Equally distributed hourly values. | [
"Obtains",
"hourly",
"values",
"by",
"equally",
"distributing",
"the",
"daily",
"values",
"."
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L50-L70 | train |
kristianfoerster/melodist | melodist/util/util.py | vapor_pressure | 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... | python | 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",
"vapor_pressure",
"(",
"temp",
",",
"hum",
")",
":",
"if",
"np",
".",
"isscalar",
"(",
"hum",
")",
":",
"hum",
"=",
"np",
".",
"zeros",
"(",
"temp",
".",
"shape",
")",
"+",
"hum",
"assert",
"(",
"temp",
".",
"shape",
"==",
"hum",
".",
"s... | 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. | [
"Calculates",
"vapor",
"pressure",
"from",
"temperature",
"and",
"humidity",
"after",
"Sonntag",
"(",
"1990",
")",
"."
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L73-L95 | train |
kristianfoerster/melodist | melodist/util/util.py | dewpoint_temperature | 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... | python | 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",
"dewpoint_temperature",
"(",
"temp",
",",
"hum",
")",
":",
"assert",
"(",
"temp",
".",
"shape",
"==",
"hum",
".",
"shape",
")",
"vap_press",
"=",
"vapor_pressure",
"(",
"temp",
",",
"hum",
")",
"positives",
"=",
"np",
".",
"array",
"(",
"temp",
... | computes the dewpoint temperature
Parameters
----
temp : temperature [K]
hum : relative humidity
Returns
dewpoint temperature in K | [
"computes",
"the",
"dewpoint",
"temperature"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L98-L119 | train |
kristianfoerster/melodist | melodist/util/util.py | linregress | 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... | python | 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",
"linregress",
"(",
"x",
",",
"y",
",",
"return_stats",
"=",
"False",
")",
":",
"a1",
",",
"a0",
",",
"r_value",
",",
"p_value",
",",
"stderr",
"=",
"scipy",
".",
"stats",
".",
"linregress",
"(",
"x",
",",
"y",
")",
"retval",
"=",
"a1",
","... | 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 (and statistics) | [
"linear",
"regression",
"calculation"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L122-L142 | train |
kristianfoerster/melodist | melodist/util/util.py | get_sun_times | 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,... | python | 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",
"get_sun_times",
"(",
"dates",
",",
"lon",
",",
"lat",
",",
"time_zone",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"index",
"=",
"dates",
",",
"columns",
"=",
"[",
"'sunrise'",
",",
"'sunnoon'",
",",
"'sunset'",
",",
"'daylength'",
"]",
... | 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, sunnoon, sunset, day length] in dec hours | [
"Computes",
"the",
"times",
"of",
"sunrise",
"solar",
"noon",
"and",
"sunset",
"for",
"each",
"day",
"."
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L145-L221 | train |
kristianfoerster/melodist | melodist/util/util.py | detect_gaps | 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... | python | 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",
"detect_gaps",
"(",
"dataframe",
",",
"timestep",
",",
"print_all",
"=",
"False",
",",
"print_max",
"=",
"5",
",",
"verbose",
"=",
"True",
")",
":",
"gcount",
"=",
"0",
"msg_counter",
"=",
"0",
"warning_printed",
"=",
"False",
"try",
":",
"n",
"... | 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
detected in the dataframe is returned.
Args:
dataframe: A pandas dataframe obj... | [
"checks",
"if",
"a",
"given",
"dataframe",
"contains",
"gaps",
"and",
"returns",
"the",
"number",
"of",
"gaps"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L224-L265 | train |
kristianfoerster/melodist | melodist/util/util.py | drop_incomplete_days | 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... | python | 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",
"drop_incomplete_days",
"(",
"dataframe",
",",
"shift",
"=",
"0",
")",
":",
"dropped",
"=",
"0",
"if",
"shift",
">",
"23",
"or",
"shift",
"<",
"0",
":",
"print",
"(",
"\"Invalid shift parameter setting! Using defaults.\"",
")",
"shift",
"=",
"0",
"fir... | 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 series.
Args:
dataframe: A pandas dataframe o... | [
"truncates",
"a",
"given",
"dataframe",
"to",
"full",
"days",
"only"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L268-L320 | train |
kristianfoerster/melodist | melodist/util/util.py | daily_from_hourly | 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_... | python | 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",
"daily_from_hourly",
"(",
"df",
")",
":",
"df_daily",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"if",
"'temp'",
"in",
"df",
":",
"df_daily",
"[",
"'temp'",
"]",
"=",
"df",
".",
"temp",
".",
"resample",
"(",
"'D'",
")",
".",
"mean",
"(",
")",
... | 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) | [
"Aggregates",
"data",
"(",
"hourly",
"to",
"daily",
"values",
")",
"according",
"to",
"the",
"characteristics",
"of",
"each",
"variable",
"(",
"e",
".",
"g",
".",
"average",
"for",
"temperature",
"sum",
"for",
"precipitation",
")"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L340-L380 | train |
kristianfoerster/melodist | melodist/precipitation.py | disagg_prec | 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... | python | 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",
"(",
"dailyData",
",",
"method",
"=",
"'equal'",
",",
"cascade_options",
"=",
"None",
",",
"hourly_data_obs",
"=",
"None",
",",
"zerodiv",
"=",
"\"uniform\"",
",",
"shift",
"=",
"0",
")",
":",
"if",
"method",
"not",
"in",
"(",
"'equ... | The disaggregation function for precipitation.
Parameters
----------
dailyData : pd.Series
daily data
method : str
method to disaggregate
cascade_options : cascade object
including statistical parameters for the cascade model
hourly_data_obs : pd.Series
observed ... | [
"The",
"disaggregation",
"function",
"for",
"precipitation",
"."
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/precipitation.py#L45-L87 | train |
kristianfoerster/melodist | melodist/precipitation.py | disagg_prec_cascade | 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
... | python | 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",
"disagg_prec_cascade",
"(",
"precip_daily",
",",
"cascade_options",
",",
"hourly",
"=",
"True",
",",
"level",
"=",
"9",
",",
"shift",
"=",
"0",
",",
"test",
"=",
"False",
")",
":",
"if",
"len",
"(",
"precip_daily",
")",
"<",
"2",
":",
"raise",
... | Precipitation disaggregation with cascade model (Olsson, 1998)
Parameters
----------
precip_daily : pd.Series
daily data
hourly: Boolean (for an hourly resolution disaggregation)
if False, then returns 5-min disaggregated precipitation
(disaggregation level depending on the "le... | [
"Precipitation",
"disaggregation",
"with",
"cascade",
"model",
"(",
"Olsson",
"1998",
")"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/precipitation.py#L90-L357 | train |
kristianfoerster/melodist | melodist/precipitation.py | precip_master_station | 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
... | python | 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",
"precip_master_station",
"(",
"precip_daily",
",",
"master_precip_hourly",
",",
"zerodiv",
")",
":",
"precip_hourly",
"=",
"pd",
".",
"Series",
"(",
"index",
"=",
"melodist",
".",
"util",
".",
"hourly_index",
"(",
"precip_daily",
".",
"index",
")",
")",... | Disaggregate precipitation based on the patterns of a master station
Parameters
-----------
precip_daily : pd.Series
daily data
master_precip_hourly : pd.Series
observed hourly data of the master station
zerodiv : str
method to deal with zero division by key "uniform" --> u... | [
"Disaggregate",
"precipitation",
"based",
"on",
"the",
"patterns",
"of",
"a",
"master",
"station"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/precipitation.py#L359-L400 | train |
kristianfoerster/melodist | melodist/precipitation.py | aggregate_precipitation | 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... | python | 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",
"aggregate_precipitation",
"(",
"vec_data",
",",
"hourly",
"=",
"True",
",",
"percentile",
"=",
"50",
")",
":",
"cascade_opt",
"=",
"cascade",
".",
"CascadeStatistics",
"(",
")",
"cascade_opt",
".",
"percentile",
"=",
"percentile",
"# length of input time s... | 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 statistics of the cascade model | [
"Aggregates",
"highly",
"resolved",
"precipitation",
"data",
"and",
"creates",
"statistics"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/precipitation.py#L403-L586 | train |
kristianfoerster/melodist | melodist/precipitation.py | seasonal_subset | 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... | python | 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",
"seasonal_subset",
"(",
"dataframe",
",",
"months",
"=",
"'all'",
")",
":",
"if",
"isinstance",
"(",
"months",
",",
"str",
")",
"and",
"months",
"==",
"'all'",
":",
"months",
"=",
"np",
".",
"arange",
"(",
"12",
")",
"+",
"1",
"for",
"month_nu... | Get the seasonal data.
Parameters
----------
dataframe : pd.DataFrame
months: int, str
Months to use for statistics, or 'all' for 1-12 (default='all') | [
"Get",
"the",
"seasonal",
"data",
"."
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/precipitation.py#L589-L611 | train |
kristianfoerster/melodist | melodist/precipitation.py | build_casc | 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... | python | 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",
"build_casc",
"(",
"ObsData",
",",
"hourly",
"=",
"True",
",",
"level",
"=",
"9",
",",
"months",
"=",
"None",
",",
"avg_stats",
"=",
"True",
",",
"percentile",
"=",
"50",
")",
":",
"list_seasonal_casc",
"=",
"list",
"(",
")",
"if",
"months",
"... | Builds the cascade statistics of observed data for disaggregation
Parameters
-----------
ObsData : pd.Series
hourly=True -> hourly obs data
else -> 5min data (disaggregation level=9 (default), 10, 11)
months : numpy array of ints
Months for each seasons to be used for stati... | [
"Builds",
"the",
"cascade",
"statistics",
"of",
"observed",
"data",
"for",
"disaggregation"
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/precipitation.py#L614-L690 | train |
kristianfoerster/melodist | melodist/cascade.py | CascadeStatistics.fill_with_sample_data | 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... | python | 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",
"fill_with_sample_data",
"(",
"self",
")",
":",
"# 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",
"(",
"[",
"[... | This function fills the corresponding object with sample data. | [
"This",
"function",
"fills",
"the",
"corresponding",
"object",
"with",
"sample",
"data",
"."
] | ddc155c77b65f791be0021dbbaf68c6bac42ecbd | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/cascade.py#L54-L81 | train |
gaqzi/django-emoji | emoji/models.py | Emoji.names | 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... | python | 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",
"names",
"(",
"cls",
")",
":",
"if",
"not",
"cls",
".",
"_files",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"cls",
".",
"_image_path",
")",
":",
"if",
"(",
"not",
"f",
".",
"startswith",
"(",
"'.'",
")",
"and",
"os",
".",
"path",... | A list of all emoji names without file extension. | [
"A",
"list",
"of",
"all",
"emoji",
"names",
"without",
"file",
"extension",
"."
] | 08625d14f5b4251f4784bb5abf2620cb46bbdcab | https://github.com/gaqzi/django-emoji/blob/08625d14f5b4251f4784bb5abf2620cb46bbdcab/emoji/models.py#L114-L122 | train |
gaqzi/django-emoji | emoji/models.py | Emoji.replace | 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... | python | 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",
"(",
"cls",
",",
"replacement_string",
")",
":",
"e",
"=",
"cls",
"(",
")",
"def",
"_replace_emoji",
"(",
"match",
")",
":",
"val",
"=",
"match",
".",
"group",
"(",
"1",
")",
"if",
"val",
"in",
"e",
":",
"return",
"e",
".",
"_im... | Add in valid emojis in a string where a valid emoji is between :: | [
"Add",
"in",
"valid",
"emojis",
"in",
"a",
"string",
"where",
"a",
"valid",
"emoji",
"is",
"between",
"::"
] | 08625d14f5b4251f4784bb5abf2620cb46bbdcab | https://github.com/gaqzi/django-emoji/blob/08625d14f5b4251f4784bb5abf2620cb46bbdcab/emoji/models.py#L125-L136 | train |
gaqzi/django-emoji | emoji/models.py | Emoji.replace_unicode | 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... | python | 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_unicode",
"(",
"cls",
",",
"replacement_string",
")",
":",
"e",
"=",
"cls",
"(",
")",
"output",
"=",
"[",
"]",
"surrogate_character",
"=",
"None",
"if",
"settings",
".",
"EMOJI_REPLACE_HTML_ENTITIES",
":",
"replacement_string",
"=",
"cls",
".",... | 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``.
NOTE: This will only work with Python versions built with wi... | [
"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",
"replac... | 08625d14f5b4251f4784bb5abf2620cb46bbdcab | https://github.com/gaqzi/django-emoji/blob/08625d14f5b4251f4784bb5abf2620cb46bbdcab/emoji/models.py#L139-L188 | train |
gaqzi/django-emoji | emoji/models.py | Emoji.replace_html_entities | 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... | python | 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",
"replace_html_entities",
"(",
"cls",
",",
"replacement_string",
")",
":",
"def",
"_hex_to_unicode",
"(",
"hex_code",
")",
":",
"if",
"PYTHON3",
":",
"hex_code",
"=",
"'{0:0>8}'",
".",
"format",
"(",
"hex_code",
")",
"as_int",
"=",
"struct",
".",
"unpa... | 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). | [
"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",
"(",
... | 08625d14f5b4251f4784bb5abf2620cb46bbdcab | https://github.com/gaqzi/django-emoji/blob/08625d14f5b4251f4784bb5abf2620cb46bbdcab/emoji/models.py#L198-L234 | train |
gaqzi/django-emoji | bin/generate-unicode-aliases.py | _convert_to_unicode | 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... | python | 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",
"_convert_to_unicode",
"(",
"string",
")",
":",
"codepoints",
"=",
"[",
"]",
"for",
"character",
"in",
"string",
".",
"split",
"(",
"'-'",
")",
":",
"if",
"character",
"in",
"BLACKLIST_UNICODE",
":",
"next",
"codepoints",
".",
"append",
"(",
"'\\U{0... | 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. | [
"This",
"method",
"should",
"work",
"with",
"both",
"Python",
"2",
"and",
"3",
"with",
"the",
"caveat",
"that",
"they",
"need",
"to",
"be",
"compiled",
"with",
"wide",
"unicode",
"character",
"support",
"."
] | 08625d14f5b4251f4784bb5abf2620cb46bbdcab | https://github.com/gaqzi/django-emoji/blob/08625d14f5b4251f4784bb5abf2620cb46bbdcab/bin/generate-unicode-aliases.py#L32-L49 | train |
acsone/bobtemplates.odoo | bobtemplates/odoo/hooks.py | _delete_file | 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 | python | 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",
"_delete_file",
"(",
"configurator",
",",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"configurator",
".",
"target_directory",
",",
"path",
")",
"os",
".",
"remove",
"(",
"path",
")",
"try",
":",
"os",
".",
"removedirs",
... | remove file and remove it's directories if empty | [
"remove",
"file",
"and",
"remove",
"it",
"s",
"directories",
"if",
"empty"
] | 6e8c3cb12747d8b5af5a9821f995f285251e4d4d | https://github.com/acsone/bobtemplates.odoo/blob/6e8c3cb12747d8b5af5a9821f995f285251e4d4d/bobtemplates/odoo/hooks.py#L34-L41 | train |
acsone/bobtemplates.odoo | bobtemplates/odoo/hooks.py | _insert_manifest_item | 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... | python | 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",
"_insert_manifest_item",
"(",
"configurator",
",",
"key",
",",
"item",
")",
":",
"with",
"_open_manifest",
"(",
"configurator",
")",
"as",
"f",
":",
"manifest",
"=",
"f",
".",
"read",
"(",
")",
"if",
"item",
"in",
"ast",
".",
"literal_eval",
"(",
... | Insert an item in the list of an existing manifest key | [
"Insert",
"an",
"item",
"in",
"the",
"list",
"of",
"an",
"existing",
"manifest",
"key"
] | 6e8c3cb12747d8b5af5a9821f995f285251e4d4d | https://github.com/acsone/bobtemplates.odoo/blob/6e8c3cb12747d8b5af5a9821f995f285251e4d4d/bobtemplates/odoo/hooks.py#L58-L68 | train |
nyaruka/smartmin | setup.py | _read_requirements | 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)] | python | 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",
"_read_requirements",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"requirements_file",
":",
"contents",
"=",
"requirements_file",
".",
"read",
"(",
")",
"return",
"[",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
... | Parses a file for pip installation requirements. | [
"Parses",
"a",
"file",
"for",
"pip",
"installation",
"requirements",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/setup.py#L17-L21 | train |
nyaruka/smartmin | smartmin/perms.py | assign_perm | 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"
... | python | 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",
"assign_perm",
"(",
"perm",
",",
"group",
")",
":",
"if",
"not",
"isinstance",
"(",
"perm",
",",
"Permission",
")",
":",
"try",
":",
"app_label",
",",
"codename",
"=",
"perm",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"except",
"ValueError",
":... | Assigns a permission to a group | [
"Assigns",
"a",
"permission",
"to",
"a",
"group"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/perms.py#L4-L17 | train |
nyaruka/smartmin | smartmin/perms.py | remove_perm | 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"
... | python | 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",
"remove_perm",
"(",
"perm",
",",
"group",
")",
":",
"if",
"not",
"isinstance",
"(",
"perm",
",",
"Permission",
")",
":",
"try",
":",
"app_label",
",",
"codename",
"=",
"perm",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"except",
"ValueError",
":... | Removes a permission from a group | [
"Removes",
"a",
"permission",
"from",
"a",
"group"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/perms.py#L20-L33 | train |
nyaruka/smartmin | smartmin/templatetags/smartmin.py | get_list_class | 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) | python | 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",
"get_list_class",
"(",
"context",
",",
"list",
")",
":",
"return",
"\"list_%s_%s\"",
"%",
"(",
"list",
".",
"model",
".",
"_meta",
".",
"app_label",
",",
"list",
".",
"model",
".",
"_meta",
".",
"model_name",
")"
] | Returns the class to use for the passed in list. We just build something up
from the object type for the list. | [
"Returns",
"the",
"class",
"to",
"use",
"for",
"the",
"passed",
"in",
"list",
".",
"We",
"just",
"build",
"something",
"up",
"from",
"the",
"object",
"type",
"for",
"the",
"list",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/templatetags/smartmin.py#L24-L29 | train |
nyaruka/smartmin | smartmin/templatetags/smartmin.py | format_datetime | 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... | python | 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",
"format_datetime",
"(",
"time",
")",
":",
"user_time_zone",
"=",
"timezone",
".",
"get_current_timezone",
"(",
")",
"if",
"time",
".",
"tzinfo",
"is",
"None",
":",
"time",
"=",
"time",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
... | Formats a date, converting the time to the user timezone if one is specified | [
"Formats",
"a",
"date",
"converting",
"the",
"time",
"to",
"the",
"user",
"timezone",
"if",
"one",
"is",
"specified"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/templatetags/smartmin.py#L32-L42 | train |
nyaruka/smartmin | smartmin/templatetags/smartmin.py | get_value_from_view | 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... | python | 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_value_from_view",
"(",
"context",
",",
"field",
")",
":",
"view",
"=",
"context",
"[",
"'view'",
"]",
"obj",
"=",
"None",
"if",
"'object'",
"in",
"context",
":",
"obj",
"=",
"context",
"[",
"'object'",
"]",
"value",
"=",
"view",
".",
"looku... | 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. | [
"Responsible",
"for",
"deriving",
"the",
"displayed",
"value",
"for",
"the",
"passed",
"in",
"field",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/templatetags/smartmin.py#L46-L64 | train |
nyaruka/smartmin | smartmin/templatetags/smartmin.py | get_class | 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) | python | 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_class",
"(",
"context",
",",
"field",
",",
"obj",
"=",
"None",
")",
":",
"view",
"=",
"context",
"[",
"'view'",
"]",
"return",
"view",
".",
"lookup_field_class",
"(",
"field",
",",
"obj",
",",
"\"field_\"",
"+",
"field",
")"
] | Looks up the class for this field | [
"Looks",
"up",
"the",
"class",
"for",
"this",
"field"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/templatetags/smartmin.py#L84-L89 | train |
nyaruka/smartmin | smartmin/templatetags/smartmin.py | get_label | 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... | python | 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_label",
"(",
"context",
",",
"field",
",",
"obj",
"=",
"None",
")",
":",
"view",
"=",
"context",
"[",
"'view'",
"]",
"return",
"view",
".",
"lookup_field_label",
"(",
"context",
",",
"field",
",",
"obj",
")"
] | 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 value | [
"Responsible",
"for",
"figuring",
"out",
"the",
"right",
"label",
"for",
"the",
"passed",
"in",
"field",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/templatetags/smartmin.py#L93-L102 | train |
nyaruka/smartmin | smartmin/templatetags/smartmin.py | get_field_link | 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) | python | 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_field_link",
"(",
"context",
",",
"field",
",",
"obj",
"=",
"None",
")",
":",
"view",
"=",
"context",
"[",
"'view'",
"]",
"return",
"view",
".",
"lookup_field_link",
"(",
"context",
",",
"field",
",",
"obj",
")"
] | Determine what the field link should be for the given field, object pair | [
"Determine",
"what",
"the",
"field",
"link",
"should",
"be",
"for",
"the",
"given",
"field",
"object",
"pair"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/templatetags/smartmin.py#L106-L111 | train |
nyaruka/smartmin | smartmin/management/__init__.py | get_permissions_app_name | 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... | python | 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",
"get_permissions_app_name",
"(",
")",
":",
"global",
"permissions_app_name",
"if",
"not",
"permissions_app_name",
":",
"permissions_app_name",
"=",
"getattr",
"(",
"settings",
",",
"'PERMISSIONS_APP'",
",",
"None",
")",
"if",
"not",
"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 | [
"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"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/management/__init__.py#L15-L30 | train |
nyaruka/smartmin | smartmin/management/__init__.py | check_role_permissions | 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... | python | 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_role_permissions",
"(",
"role",
",",
"permissions",
",",
"current_permissions",
")",
":",
"role_permissions",
"=",
"[",
"]",
"# get all the current permissions, we'll remove these as we verify they should still be granted",
"for",
"permission",
"in",
"permissions",
... | Checks the the passed in role (can be user, group or AnonymousUser) has all the passed
in permissions, granting them if necessary. | [
"Checks",
"the",
"the",
"passed",
"in",
"role",
"(",
"can",
"be",
"user",
"group",
"or",
"AnonymousUser",
")",
"has",
"all",
"the",
"passed",
"in",
"permissions",
"granting",
"them",
"if",
"necessary",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/management/__init__.py#L40-L95 | train |
nyaruka/smartmin | smartmin/management/__init__.py | check_all_group_permissions | 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... | python | 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",
"check_all_group_permissions",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"is_permissions_app",
"(",
"sender",
")",
":",
"return",
"config",
"=",
"getattr",
"(",
"settings",
",",
"'GROUP_PERMISSIONS'",
",",
"dict",
"(",
")",
")",
... | Checks that all the permissions specified in our settings.py are set for our groups. | [
"Checks",
"that",
"all",
"the",
"permissions",
"specified",
"in",
"our",
"settings",
".",
"py",
"are",
"set",
"for",
"our",
"groups",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/management/__init__.py#L98-L114 | train |
nyaruka/smartmin | smartmin/management/__init__.py | add_permission | 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... | python | 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",
"add_permission",
"(",
"content_type",
",",
"permission",
")",
":",
"# build our permission slug",
"codename",
"=",
"\"%s_%s\"",
"%",
"(",
"content_type",
".",
"model",
",",
"permission",
")",
"# sys.stderr.write(\"Checking %s permission for %s\\n\" % (permission, cont... | 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. | [
"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"... | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/management/__init__.py#L117-L131 | train |
nyaruka/smartmin | smartmin/management/__init__.py | check_all_permissions | 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
... | python | 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",
"check_all_permissions",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"is_permissions_app",
"(",
"sender",
")",
":",
"return",
"config",
"=",
"getattr",
"(",
"settings",
",",
"'PERMISSIONS'",
",",
"dict",
"(",
")",
")",
"# for each... | This syncdb checks our PERMISSIONS setting in settings.py and makes sure all those permissions
actually exit. | [
"This",
"syncdb",
"checks",
"our",
"PERMISSIONS",
"setting",
"in",
"settings",
".",
"py",
"and",
"makes",
"sure",
"all",
"those",
"permissions",
"actually",
"exit",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/management/__init__.py#L135-L164 | train |
nyaruka/smartmin | smartmin/users/views.py | UserForm.save | 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... | python | 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",
"save",
"(",
"self",
",",
"commit",
"=",
"True",
")",
":",
"is_new_user",
"=",
"self",
".",
"instance",
".",
"pk",
"is",
"None",
"user",
"=",
"super",
"(",
"UserForm",
",",
"self",
")",
".",
"save",
"(",
"commit",
")",
"# new users should be mad... | Overloaded so we can save any new password that is included. | [
"Overloaded",
"so",
"we",
"can",
"save",
"any",
"new",
"password",
"that",
"is",
"included",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/users/views.py#L39-L58 | train |
nyaruka/smartmin | smartmin/views.py | smart_url | 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... | python | 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",
"smart_url",
"(",
"url",
",",
"obj",
"=",
"None",
")",
":",
"if",
"url",
".",
"find",
"(",
"\"@\"",
")",
">=",
"0",
":",
"(",
"args",
",",
"value",
")",
"=",
"url",
".",
"split",
"(",
"'@'",
")",
"if",
"args",
":",
"val",
"=",
"getattr... | URLs that start with @ are reversed, using the passed in arguments.
Otherwise a straight % substitution is applied. | [
"URLs",
"that",
"start",
"with",
"@",
"are",
"reversed",
"using",
"the",
"passed",
"in",
"arguments",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L31-L49 | train |
nyaruka/smartmin | smartmin/views.py | derive_single_object_url_pattern | 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) | python | 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",
"derive_single_object_url_pattern",
"(",
"slug_url_kwarg",
",",
"path",
",",
"action",
")",
":",
"if",
"slug_url_kwarg",
":",
"return",
"r'^%s/%s/(?P<%s>[^/]+)/$'",
"%",
"(",
"path",
",",
"action",
",",
"slug_url_kwarg",
")",
"else",
":",
"return",
"r'^%s/%... | Utility function called by class methods for single object views | [
"Utility",
"function",
"called",
"by",
"class",
"methods",
"for",
"single",
"object",
"views"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L390-L397 | train |
nyaruka/smartmin | smartmin/views.py | SmartView.has_permission | 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:... | python | 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",
"has_permission",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"kwargs",
"=",
"kwargs",
"self",
".",
"args",
"=",
"args",
"self",
".",
"request",
"=",
"request",
"if",
"not",
"getattr",
"(",
... | Figures out if the current user has permissions for this view. | [
"Figures",
"out",
"if",
"the",
"current",
"user",
"has",
"permissions",
"for",
"this",
"view",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L88-L99 | train |
nyaruka/smartmin | smartmin/views.py | SmartView.dispatch | 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... | python | 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",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"has_permission",
"(",
"request",
... | Overloaded to check permissions if appropriate | [
"Overloaded",
"to",
"check",
"permissions",
"if",
"appropriate"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L101-L118 | train |
nyaruka/smartmin | smartmin/views.py | SmartView.lookup_obj_attribute | 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... | python | 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_obj_attribute",
"(",
"self",
",",
"obj",
",",
"field",
")",
":",
"curr_field",
"=",
"field",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"rest",
"=",
"None",
"if",
"field",
".",
"find",
"(",... | Looks for a field's value from the passed in obj. Note that this will strip
leading attributes to deal with subelements if possible | [
"Looks",
"for",
"a",
"field",
"s",
"value",
"from",
"the",
"passed",
"in",
"obj",
".",
"Note",
"that",
"this",
"will",
"strip",
"leading",
"attributes",
"to",
"deal",
"with",
"subelements",
"if",
"possible"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L130-L152 | train |
nyaruka/smartmin | smartmin/views.py | SmartView.lookup_field_value | 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 ... | python | 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_value",
"(",
"self",
",",
"context",
",",
"obj",
",",
"field",
")",
":",
"curr_field",
"=",
"field",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"# if this isn't a subfield, check the view to se... | 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 for example to change the display value of a variable depending on
... | [
"Looks",
"up",
"the",
"field",
"value",
"for",
"the",
"passed",
"in",
"object",
"and",
"field",
"name",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L154-L173 | train |
nyaruka/smartmin | smartmin/views.py | SmartView.lookup_field_label | 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... | python | 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_label",
"(",
"self",
",",
"context",
",",
"field",
",",
"default",
"=",
"None",
")",
":",
"# if this is a subfield, strip off everything but the last field name",
"if",
"field",
".",
"find",
"(",
"'.'",
")",
">=",
"0",
":",
"return",
"self",
... | 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 the field name | [
"Figures",
"out",
"what",
"the",
"field",
"label",
"should",
"be",
"for",
"the",
"passed",
"in",
"field",
"name",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L175-L207 | train |
nyaruka/smartmin | smartmin/views.py | SmartView.lookup_field_help | 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... | python | 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_help",
"(",
"self",
",",
"field",
",",
"default",
"=",
"None",
")",
":",
"help",
"=",
"None",
"# is there a label specified for this field",
"if",
"field",
"in",
"self",
".",
"field_config",
"and",
"'help'",
"in",
"self",
".",
"field_config"... | Looks up the help text for the passed in field. | [
"Looks",
"up",
"the",
"help",
"text",
"for",
"the",
"passed",
"in",
"field",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L209-L230 | train |
nyaruka/smartmin | smartmin/views.py | SmartView.lookup_field_class | 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]:
... | python | 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",
"lookup_field_class",
"(",
"self",
",",
"field",
",",
"obj",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"css",
"=",
"\"\"",
"# is there a class specified for this field",
"if",
"field",
"in",
"self",
".",
"field_config",
"and",
"'class'",
"in",... | Looks up any additional class we should include when rendering this field | [
"Looks",
"up",
"any",
"additional",
"class",
"we",
"should",
"include",
"when",
"rendering",
"this",
"field"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L232-L246 | train |
nyaruka/smartmin | smartmin/views.py | SmartView.get_template_names | 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... | python | 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",
"get_template_names",
"(",
"self",
")",
":",
"templates",
"=",
"[",
"]",
"if",
"getattr",
"(",
"self",
",",
"'template_name'",
",",
"None",
")",
":",
"templates",
".",
"append",
"(",
"self",
".",
"template_name",
")",
"if",
"getattr",
"(",
"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 setting a 'template_name' variable on the class. | [
"Returns",
"the",
"name",
"of",
"the",
"template",
"to",
"use",
"to",
"render",
"this",
"request",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L263-L281 | train |
nyaruka/smartmin | smartmin/views.py | SmartView.derive_fields | def derive_fields(self):
"""
Default implementation
"""
fields = []
if self.fields:
fields.append(self.fields)
return fields | python | def derive_fields(self):
"""
Default implementation
"""
fields = []
if self.fields:
fields.append(self.fields)
return fields | [
"def",
"derive_fields",
"(",
"self",
")",
":",
"fields",
"=",
"[",
"]",
"if",
"self",
".",
"fields",
":",
"fields",
".",
"append",
"(",
"self",
".",
"fields",
")",
"return",
"fields"
] | Default implementation | [
"Default",
"implementation"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L283-L291 | train |
nyaruka/smartmin | smartmin/views.py | SmartView.get_context_data | def get_context_data(self, **kwargs):
"""
We supplement the normal context data by adding our fields and labels.
"""
context = super(SmartView, self).get_context_data(**kwargs)
# derive our field config
self.field_config = self.derive_field_config()
# add our fi... | python | def get_context_data(self, **kwargs):
"""
We supplement the normal context data by adding our fields and labels.
"""
context = super(SmartView, self).get_context_data(**kwargs)
# derive our field config
self.field_config = self.derive_field_config()
# add our fi... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"SmartView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"# derive our field config",
"self",
".",
"field_config",
"=",
"s... | We supplement the normal context data by adding our fields and labels. | [
"We",
"supplement",
"the",
"normal",
"context",
"data",
"by",
"adding",
"our",
"fields",
"and",
"labels",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L309-L364 | train |
nyaruka/smartmin | smartmin/views.py | SmartView.render_to_response | def render_to_response(self, context, **response_kwargs):
"""
Overloaded to deal with _format arguments.
"""
# should we actually render in json?
if '_format' in self.request.GET and self.request.GET['_format'] == 'json':
return JsonResponse(self.as_json(context), saf... | python | def render_to_response(self, context, **response_kwargs):
"""
Overloaded to deal with _format arguments.
"""
# should we actually render in json?
if '_format' in self.request.GET and self.request.GET['_format'] == 'json':
return JsonResponse(self.as_json(context), saf... | [
"def",
"render_to_response",
"(",
"self",
",",
"context",
",",
"*",
"*",
"response_kwargs",
")",
":",
"# should we actually render in json?",
"if",
"'_format'",
"in",
"self",
".",
"request",
".",
"GET",
"and",
"self",
".",
"request",
".",
"GET",
"[",
"'_format... | Overloaded to deal with _format arguments. | [
"Overloaded",
"to",
"deal",
"with",
"_format",
"arguments",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L373-L383 | train |
nyaruka/smartmin | smartmin/views.py | SmartReadView.derive_fields | def derive_fields(self):
"""
Derives our fields. We first default to using our 'fields' variable if available,
otherwise we figure it out from our object.
"""
if self.fields:
return list(self.fields)
else:
fields = []
for field in sel... | python | def derive_fields(self):
"""
Derives our fields. We first default to using our 'fields' variable if available,
otherwise we figure it out from our object.
"""
if self.fields:
return list(self.fields)
else:
fields = []
for field in sel... | [
"def",
"derive_fields",
"(",
"self",
")",
":",
"if",
"self",
".",
"fields",
":",
"return",
"list",
"(",
"self",
".",
"fields",
")",
"else",
":",
"fields",
"=",
"[",
"]",
"for",
"field",
"in",
"self",
".",
"object",
".",
"_meta",
".",
"fields",
":",... | Derives our fields. We first default to using our 'fields' variable if available,
otherwise we figure it out from our object. | [
"Derives",
"our",
"fields",
".",
"We",
"first",
"default",
"to",
"using",
"our",
"fields",
"variable",
"if",
"available",
"otherwise",
"we",
"figure",
"it",
"out",
"from",
"our",
"object",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L435-L454 | train |
nyaruka/smartmin | smartmin/views.py | SmartDeleteView.get_context_data | def get_context_data(self, **kwargs):
""" Add in the field to use for the name field """
context = super(SmartDeleteView, self).get_context_data(**kwargs)
context['name_field'] = self.name_field
context['cancel_url'] = self.get_cancel_url()
return context | python | def get_context_data(self, **kwargs):
""" Add in the field to use for the name field """
context = super(SmartDeleteView, self).get_context_data(**kwargs)
context['name_field'] = self.name_field
context['cancel_url'] = self.get_cancel_url()
return context | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"SmartDeleteView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"context",
"[",
"'name_field'",
"]",
"=",
"self",
".",
... | Add in the field to use for the name field | [
"Add",
"in",
"the",
"field",
"to",
"use",
"for",
"the",
"name",
"field"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L498-L503 | train |
nyaruka/smartmin | smartmin/views.py | SmartListView.derive_title | def derive_title(self):
"""
Derives our title from our list
"""
title = super(SmartListView, self).derive_title()
if not title:
return force_text(self.model._meta.verbose_name_plural).title()
else:
return title | python | def derive_title(self):
"""
Derives our title from our list
"""
title = super(SmartListView, self).derive_title()
if not title:
return force_text(self.model._meta.verbose_name_plural).title()
else:
return title | [
"def",
"derive_title",
"(",
"self",
")",
":",
"title",
"=",
"super",
"(",
"SmartListView",
",",
"self",
")",
".",
"derive_title",
"(",
")",
"if",
"not",
"title",
":",
"return",
"force_text",
"(",
"self",
".",
"model",
".",
"_meta",
".",
"verbose_name_plu... | Derives our title from our list | [
"Derives",
"our",
"title",
"from",
"our",
"list"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L531-L540 | train |
nyaruka/smartmin | smartmin/views.py | SmartListView.derive_link_fields | def derive_link_fields(self, context):
"""
Used to derive which fields should be linked. This should return a set() containing
the names of those fields which should be linkable.
"""
if self.link_fields is not None:
return self.link_fields
else:
... | python | def derive_link_fields(self, context):
"""
Used to derive which fields should be linked. This should return a set() containing
the names of those fields which should be linkable.
"""
if self.link_fields is not None:
return self.link_fields
else:
... | [
"def",
"derive_link_fields",
"(",
"self",
",",
"context",
")",
":",
"if",
"self",
".",
"link_fields",
"is",
"not",
"None",
":",
"return",
"self",
".",
"link_fields",
"else",
":",
"link_fields",
"=",
"set",
"(",
")",
"if",
"self",
".",
"fields",
":",
"f... | Used to derive which fields should be linked. This should return a set() containing
the names of those fields which should be linkable. | [
"Used",
"to",
"derive",
"which",
"fields",
"should",
"be",
"linked",
".",
"This",
"should",
"return",
"a",
"set",
"()",
"containing",
"the",
"names",
"of",
"those",
"fields",
"which",
"should",
"be",
"linkable",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L542-L558 | train |
nyaruka/smartmin | smartmin/views.py | SmartListView.lookup_field_orderable | def lookup_field_orderable(self, field):
"""
Returns whether the passed in field is sortable or not, by default all 'raw' fields, that
is fields that are part of the model are sortable.
"""
try:
self.model._meta.get_field_by_name(field)
return True
... | python | def lookup_field_orderable(self, field):
"""
Returns whether the passed in field is sortable or not, by default all 'raw' fields, that
is fields that are part of the model are sortable.
"""
try:
self.model._meta.get_field_by_name(field)
return True
... | [
"def",
"lookup_field_orderable",
"(",
"self",
",",
"field",
")",
":",
"try",
":",
"self",
".",
"model",
".",
"_meta",
".",
"get_field_by_name",
"(",
"field",
")",
"return",
"True",
"except",
"Exception",
":",
"# that field doesn't exist, so not sortable",
"return"... | Returns whether the passed in field is sortable or not, by default all 'raw' fields, that
is fields that are part of the model are sortable. | [
"Returns",
"whether",
"the",
"passed",
"in",
"field",
"is",
"sortable",
"or",
"not",
"by",
"default",
"all",
"raw",
"fields",
"that",
"is",
"fields",
"that",
"are",
"part",
"of",
"the",
"model",
"are",
"sortable",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L566-L576 | train |
nyaruka/smartmin | smartmin/views.py | SmartListView.get_context_data | def get_context_data(self, **kwargs):
"""
Add in what fields are linkable
"""
context = super(SmartListView, self).get_context_data(**kwargs)
# our linkable fields
self.link_fields = self.derive_link_fields(context)
# stuff it all in our context
context[... | python | def get_context_data(self, **kwargs):
"""
Add in what fields are linkable
"""
context = super(SmartListView, self).get_context_data(**kwargs)
# our linkable fields
self.link_fields = self.derive_link_fields(context)
# stuff it all in our context
context[... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"SmartListView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"# our linkable fields",
"self",
".",
"link_fields",
"=",
"se... | Add in what fields are linkable | [
"Add",
"in",
"what",
"fields",
"are",
"linkable"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L578-L604 | train |
nyaruka/smartmin | smartmin/views.py | SmartListView.derive_queryset | def derive_queryset(self, **kwargs):
"""
Derives our queryset.
"""
# get our parent queryset
queryset = super(SmartListView, self).get_queryset(**kwargs)
# apply any filtering
search_fields = self.derive_search_fields()
search_query = self.request.GET.get... | python | def derive_queryset(self, **kwargs):
"""
Derives our queryset.
"""
# get our parent queryset
queryset = super(SmartListView, self).get_queryset(**kwargs)
# apply any filtering
search_fields = self.derive_search_fields()
search_query = self.request.GET.get... | [
"def",
"derive_queryset",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# get our parent queryset",
"queryset",
"=",
"super",
"(",
"SmartListView",
",",
"self",
")",
".",
"get_queryset",
"(",
"*",
"*",
"kwargs",
")",
"# apply any filtering",
"search_fields",
... | Derives our queryset. | [
"Derives",
"our",
"queryset",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L609-L635 | train |
nyaruka/smartmin | smartmin/views.py | SmartListView.get_queryset | def get_queryset(self, **kwargs):
"""
Gets our queryset. This takes care of filtering if there are any
fields to filter by.
"""
queryset = self.derive_queryset(**kwargs)
return self.order_queryset(queryset) | python | def get_queryset(self, **kwargs):
"""
Gets our queryset. This takes care of filtering if there are any
fields to filter by.
"""
queryset = self.derive_queryset(**kwargs)
return self.order_queryset(queryset) | [
"def",
"get_queryset",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"queryset",
"=",
"self",
".",
"derive_queryset",
"(",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"order_queryset",
"(",
"queryset",
")"
] | Gets our queryset. This takes care of filtering if there are any
fields to filter by. | [
"Gets",
"our",
"queryset",
".",
"This",
"takes",
"care",
"of",
"filtering",
"if",
"there",
"are",
"any",
"fields",
"to",
"filter",
"by",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L637-L644 | train |
nyaruka/smartmin | smartmin/views.py | SmartListView.derive_ordering | def derive_ordering(self):
"""
Returns what field should be used for ordering (using a prepended '-' to indicate descending sort).
If the default order of the queryset should be used, returns None
"""
if '_order' in self.request.GET:
return self.request.GET['_order']... | python | def derive_ordering(self):
"""
Returns what field should be used for ordering (using a prepended '-' to indicate descending sort).
If the default order of the queryset should be used, returns None
"""
if '_order' in self.request.GET:
return self.request.GET['_order']... | [
"def",
"derive_ordering",
"(",
"self",
")",
":",
"if",
"'_order'",
"in",
"self",
".",
"request",
".",
"GET",
":",
"return",
"self",
".",
"request",
".",
"GET",
"[",
"'_order'",
"]",
"elif",
"self",
".",
"default_order",
":",
"return",
"self",
".",
"def... | Returns what field should be used for ordering (using a prepended '-' to indicate descending sort).
If the default order of the queryset should be used, returns None | [
"Returns",
"what",
"field",
"should",
"be",
"used",
"for",
"ordering",
"(",
"using",
"a",
"prepended",
"-",
"to",
"indicate",
"descending",
"sort",
")",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L646-L657 | train |
nyaruka/smartmin | smartmin/views.py | SmartListView.order_queryset | def order_queryset(self, queryset):
"""
Orders the passed in queryset, returning a new queryset in response. By default uses the _order query
parameter.
"""
order = self.derive_ordering()
# if we get our order from the request
# make sure it is a valid field in ... | python | def order_queryset(self, queryset):
"""
Orders the passed in queryset, returning a new queryset in response. By default uses the _order query
parameter.
"""
order = self.derive_ordering()
# if we get our order from the request
# make sure it is a valid field in ... | [
"def",
"order_queryset",
"(",
"self",
",",
"queryset",
")",
":",
"order",
"=",
"self",
".",
"derive_ordering",
"(",
")",
"# if we get our order from the request",
"# make sure it is a valid field in the list",
"if",
"'_order'",
"in",
"self",
".",
"request",
".",
"GET"... | Orders the passed in queryset, returning a new queryset in response. By default uses the _order query
parameter. | [
"Orders",
"the",
"passed",
"in",
"queryset",
"returning",
"a",
"new",
"queryset",
"in",
"response",
".",
"By",
"default",
"uses",
"the",
"_order",
"query",
"parameter",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L659-L679 | train |
nyaruka/smartmin | smartmin/views.py | SmartListView.derive_fields | def derive_fields(self):
"""
Derives our fields.
"""
if self.fields:
return self.fields
else:
fields = []
for field in self.object_list.model._meta.fields:
if field.name != 'id':
fields.append(field.name)
... | python | def derive_fields(self):
"""
Derives our fields.
"""
if self.fields:
return self.fields
else:
fields = []
for field in self.object_list.model._meta.fields:
if field.name != 'id':
fields.append(field.name)
... | [
"def",
"derive_fields",
"(",
"self",
")",
":",
"if",
"self",
".",
"fields",
":",
"return",
"self",
".",
"fields",
"else",
":",
"fields",
"=",
"[",
"]",
"for",
"field",
"in",
"self",
".",
"object_list",
".",
"model",
".",
"_meta",
".",
"fields",
":",
... | Derives our fields. | [
"Derives",
"our",
"fields",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L681-L693 | train |
nyaruka/smartmin | smartmin/views.py | SmartListView.render_to_response | def render_to_response(self, context, **response_kwargs):
"""
Overloaded to deal with _format arguments.
"""
# is this a select2 format response?
if self.request.GET.get('_format', 'html') == 'select2':
results = []
for obj in context['object_list']:
... | python | def render_to_response(self, context, **response_kwargs):
"""
Overloaded to deal with _format arguments.
"""
# is this a select2 format response?
if self.request.GET.get('_format', 'html') == 'select2':
results = []
for obj in context['object_list']:
... | [
"def",
"render_to_response",
"(",
"self",
",",
"context",
",",
"*",
"*",
"response_kwargs",
")",
":",
"# is this a select2 format response?",
"if",
"self",
".",
"request",
".",
"GET",
".",
"get",
"(",
"'_format'",
",",
"'html'",
")",
"==",
"'select2'",
":",
... | Overloaded to deal with _format arguments. | [
"Overloaded",
"to",
"deal",
"with",
"_format",
"arguments",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L707-L729 | train |
nyaruka/smartmin | smartmin/views.py | SmartFormMixin.get_form | def get_form(self):
"""
Returns an instance of the form to be used in this view.
"""
self.form = super(SmartFormMixin, self).get_form()
fields = list(self.derive_fields())
# apply our field filtering on our form class
exclude = self.derive_exclude()
excl... | python | def get_form(self):
"""
Returns an instance of the form to be used in this view.
"""
self.form = super(SmartFormMixin, self).get_form()
fields = list(self.derive_fields())
# apply our field filtering on our form class
exclude = self.derive_exclude()
excl... | [
"def",
"get_form",
"(",
"self",
")",
":",
"self",
".",
"form",
"=",
"super",
"(",
"SmartFormMixin",
",",
"self",
")",
".",
"get_form",
"(",
")",
"fields",
"=",
"list",
"(",
"self",
".",
"derive_fields",
"(",
")",
")",
"# apply our field filtering on our fo... | Returns an instance of the form to be used in this view. | [
"Returns",
"an",
"instance",
"of",
"the",
"form",
"to",
"be",
"used",
"in",
"this",
"view",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L825-L865 | train |
nyaruka/smartmin | smartmin/views.py | SmartFormMixin.customize_form_field | def customize_form_field(self, name, field):
"""
Allows views to customize their form fields. By default, Smartmin replaces the plain textbox
date input with it's own DatePicker implementation.
"""
if isinstance(field, forms.fields.DateField) and isinstance(field.widget, forms.w... | python | def customize_form_field(self, name, field):
"""
Allows views to customize their form fields. By default, Smartmin replaces the plain textbox
date input with it's own DatePicker implementation.
"""
if isinstance(field, forms.fields.DateField) and isinstance(field.widget, forms.w... | [
"def",
"customize_form_field",
"(",
"self",
",",
"name",
",",
"field",
")",
":",
"if",
"isinstance",
"(",
"field",
",",
"forms",
".",
"fields",
".",
"DateField",
")",
"and",
"isinstance",
"(",
"field",
".",
"widget",
",",
"forms",
".",
"widgets",
".",
... | Allows views to customize their form fields. By default, Smartmin replaces the plain textbox
date input with it's own DatePicker implementation. | [
"Allows",
"views",
"to",
"customize",
"their",
"form",
"fields",
".",
"By",
"default",
"Smartmin",
"replaces",
"the",
"plain",
"textbox",
"date",
"input",
"with",
"it",
"s",
"own",
"DatePicker",
"implementation",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L867-L879 | train |
nyaruka/smartmin | smartmin/views.py | SmartFormMixin.lookup_field_label | def lookup_field_label(self, context, field, default=None):
"""
Figures out what the field label should be for the passed in field name.
We overload this so as to use our form to see if there is label set there. If so
then we'll pass that as the default instead of having our parent der... | python | def lookup_field_label(self, context, field, default=None):
"""
Figures out what the field label should be for the passed in field name.
We overload this so as to use our form to see if there is label set there. If so
then we'll pass that as the default instead of having our parent der... | [
"def",
"lookup_field_label",
"(",
"self",
",",
"context",
",",
"field",
",",
"default",
"=",
"None",
")",
":",
"default",
"=",
"None",
"for",
"form_field",
"in",
"self",
".",
"form",
":",
"if",
"form_field",
".",
"name",
"==",
"field",
":",
"default",
... | Figures out what the field label should be for the passed in field name.
We overload this so as to use our form to see if there is label set there. If so
then we'll pass that as the default instead of having our parent derive
the field from the name. | [
"Figures",
"out",
"what",
"the",
"field",
"label",
"should",
"be",
"for",
"the",
"passed",
"in",
"field",
"name",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L881-L896 | train |
nyaruka/smartmin | smartmin/views.py | SmartFormMixin.lookup_field_help | def lookup_field_help(self, field, default=None):
"""
Looks up the help text for the passed in field.
This is overloaded so that we can check whether our form has help text set
explicitely. If so, we will pass this as the default to our parent function.
"""
default = No... | python | def lookup_field_help(self, field, default=None):
"""
Looks up the help text for the passed in field.
This is overloaded so that we can check whether our form has help text set
explicitely. If so, we will pass this as the default to our parent function.
"""
default = No... | [
"def",
"lookup_field_help",
"(",
"self",
",",
"field",
",",
"default",
"=",
"None",
")",
":",
"default",
"=",
"None",
"for",
"form_field",
"in",
"self",
".",
"form",
":",
"if",
"form_field",
".",
"name",
"==",
"field",
":",
"default",
"=",
"form_field",
... | Looks up the help text for the passed in field.
This is overloaded so that we can check whether our form has help text set
explicitely. If so, we will pass this as the default to our parent function. | [
"Looks",
"up",
"the",
"help",
"text",
"for",
"the",
"passed",
"in",
"field",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L898-L912 | train |
nyaruka/smartmin | smartmin/views.py | SmartFormMixin.derive_readonly | def derive_readonly(self):
"""
Figures out what fields should be readonly. We iterate our field_config to find all
that have a readonly of true
"""
readonly = list(self.readonly)
for key, value in self.field_config.items():
if 'readonly' in value and value['r... | python | def derive_readonly(self):
"""
Figures out what fields should be readonly. We iterate our field_config to find all
that have a readonly of true
"""
readonly = list(self.readonly)
for key, value in self.field_config.items():
if 'readonly' in value and value['r... | [
"def",
"derive_readonly",
"(",
"self",
")",
":",
"readonly",
"=",
"list",
"(",
"self",
".",
"readonly",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"field_config",
".",
"items",
"(",
")",
":",
"if",
"'readonly'",
"in",
"value",
"and",
"value",
... | Figures out what fields should be readonly. We iterate our field_config to find all
that have a readonly of true | [
"Figures",
"out",
"what",
"fields",
"should",
"be",
"readonly",
".",
"We",
"iterate",
"our",
"field_config",
"to",
"find",
"all",
"that",
"have",
"a",
"readonly",
"of",
"true"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L914-L924 | train |
nyaruka/smartmin | smartmin/views.py | SmartFormMixin.derive_fields | def derive_fields(self):
"""
Derives our fields.
"""
if self.fields is not None:
fields = list(self.fields)
else:
form = self.form
fields = []
for field in form:
fields.append(field.name)
# this is sligh... | python | def derive_fields(self):
"""
Derives our fields.
"""
if self.fields is not None:
fields = list(self.fields)
else:
form = self.form
fields = []
for field in form:
fields.append(field.name)
# this is sligh... | [
"def",
"derive_fields",
"(",
"self",
")",
":",
"if",
"self",
".",
"fields",
"is",
"not",
"None",
":",
"fields",
"=",
"list",
"(",
"self",
".",
"fields",
")",
"else",
":",
"form",
"=",
"self",
".",
"form",
"fields",
"=",
"[",
"]",
"for",
"field",
... | Derives our fields. | [
"Derives",
"our",
"fields",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L926-L949 | train |
nyaruka/smartmin | smartmin/views.py | SmartFormMixin.get_form_class | def get_form_class(self):
"""
Returns the form class to use in this view
"""
if self.form_class:
form_class = self.form_class
else:
if self.model is not None:
# If a model has been explicitly provided, use it
model = self.m... | python | def get_form_class(self):
"""
Returns the form class to use in this view
"""
if self.form_class:
form_class = self.form_class
else:
if self.model is not None:
# If a model has been explicitly provided, use it
model = self.m... | [
"def",
"get_form_class",
"(",
"self",
")",
":",
"if",
"self",
".",
"form_class",
":",
"form_class",
"=",
"self",
".",
"form_class",
"else",
":",
"if",
"self",
".",
"model",
"is",
"not",
"None",
":",
"# If a model has been explicitly provided, use it",
"model",
... | Returns the form class to use in this view | [
"Returns",
"the",
"form",
"class",
"to",
"use",
"in",
"this",
"view"
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L951-L975 | train |
nyaruka/smartmin | smartmin/views.py | SmartFormMixin.get_factory_kwargs | def get_factory_kwargs(self):
"""
Let's us specify any extra parameters we might want to call for our form factory.
These can include: 'form', 'fields', 'exclude' or 'formfield_callback'
"""
params = dict()
exclude = self.derive_exclude()
exclude += self.derive_... | python | def get_factory_kwargs(self):
"""
Let's us specify any extra parameters we might want to call for our form factory.
These can include: 'form', 'fields', 'exclude' or 'formfield_callback'
"""
params = dict()
exclude = self.derive_exclude()
exclude += self.derive_... | [
"def",
"get_factory_kwargs",
"(",
"self",
")",
":",
"params",
"=",
"dict",
"(",
")",
"exclude",
"=",
"self",
".",
"derive_exclude",
"(",
")",
"exclude",
"+=",
"self",
".",
"derive_readonly",
"(",
")",
"if",
"self",
".",
"fields",
":",
"fields",
"=",
"l... | Let's us specify any extra parameters we might want to call for our form factory.
These can include: 'form', 'fields', 'exclude' or 'formfield_callback' | [
"Let",
"s",
"us",
"specify",
"any",
"extra",
"parameters",
"we",
"might",
"want",
"to",
"call",
"for",
"our",
"form",
"factory",
"."
] | 488a676a4960555e4d216a7b95d6e01a4ad4efd8 | https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L977-L999 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.