output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def _strip_metadata(self, my_dict): """ Create a copy of dict and remove not needed data """ new_dict = copy.deepcopy(my_dict) if const.START in new_dict: del new_dict[const.START] if const.END in new_dict: del new_dict[const.END] if const....
Write a Python 3 function for removing not needed metadata from a dictionary.
As a python code expert, you are capable of creating scripts from specifications.
def lookup_callsign(self, callsign=None, timestamp=timestamp_now): """ Returns lookup data if an exception exists for a callsign Args: callsign (string): Amateur radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: ...
How would you code a function in Python 3 to return the data for a specific callsign.
You are a Python code analyst, evaluating scripts for potential improvements.
Retrieve the data of an item from redis and put it in an index and data dictionary to match the common query interface.
Can you generate a brief explanation for the following Python 3 code def _get_dicts_from_redis(self, name, index_name, redis_prefix, item): r = self._redis data_dict = {} data_index_dict = {} if redis_prefix is None: raise KeyError ("redis_prefix is missing") if r.s...
As a Python code analyst, you investigate and solve complex coding mysteries
Checks if the data for the given item is found in the index and returns the data that is stored in the index.
Can you generate a brief explanation for the following Python 3 code def _check_data_for_date(self, item, timestamp, data_dict, data_index_dict): if item in data_index_dict: for item in data_index_dict[item]: # startdate < timestamp if const.START in data_dict[item]...
As a Python code analyst, you investigate and solve complex coding mysteries
def _check_inv_operation_for_date(self, item, timestamp, data_dict, data_index_dict): """ Checks if the callsign is marked as an invalid operation for a given timestamp. In case the operation is invalid, True is returned. Otherwise a KeyError is raised. """ if item in data_index...
Can you create a Python 3 function that checks if the callsign is invalid for a given timestamp.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the lookup data for a specific prefix
Here you have a function in Python 3, explain what it does def lookup_prefix(self, prefix, timestamp=timestamp_now): prefix = prefix.strip().upper() if self._lookuptype == "clublogxml" or self._lookuptype == "countryfile": return self._check_data_for_date(prefix, timestamp, self._prefixes...
As a Python code analyst, you investigate and solve complex coding mysteries
def is_invalid_operation(self, callsign, timestamp=datetime.utcnow().replace(tzinfo=UTC)): """ Returns True if an operations is known as invalid Args: callsign (string): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Ret...
How would you implement a function in Python 3 that checks if an operation is known as invalid for a given callsign.
You are a Python code generator, capable of creating scripts from specifications.
Checks the index and data for a cq - zone exception for the specified date.
Can you generate the documentation for the following Python 3 function def _check_zone_exception_for_date(self, item, timestamp, data_dict, data_index_dict): if item in data_index_dict: for item in data_index_dict[item]: # startdate < timestamp if const.START in data...
As a Python code composer, you craft elegant and concise scripts.
def lookup_zone_exception(self, callsign, timestamp=datetime.utcnow().replace(tzinfo=UTC)): """ Returns a CQ Zone if an exception exists for the given callsign Args: callsign (string): Amateur radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) ...
Write a Python 3 function for returning a CQ Zone exception for the given callsign at the given time.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _lookup_clublogAPI(self, callsign=None, timestamp=timestamp_now, url="https://secure.clublog.org/dxcc", apikey=None): """ Set up the Lookup object for Clublog Online API """ params = {"year" : timestamp.strftime("%Y"), "month" : timestamp.strftime("%m"), "day" : time...
Can you write a function in Python 3 where it gets the lookup object for Clublog Online API
As a Python code translator, you convert algorithms and pseudocode into Python.
Perform a QRZ callsign lookup against the QRZ. com XML API.
Here you have a function in Python 3, explain what it does def _lookup_qrz_callsign(self, callsign=None, apikey=None, apiv="1.3.3"): if apikey is None: raise AttributeError("Session Key Missing") callsign = callsign.upper() response = self._request_callsign_info_from_qrz(callsign,...
As a python code expert, you are capable of creating scripts from specifications.
def _load_clublogXML(self, url="https://secure.clublog.org/cty.php", apikey=None, cty_file=None): """ Load and process the ClublogXML file either as a download or from file """ if self._download: cty_file = self...
Write a Python 3 function for loading and process the ClublogXML file.
As a python code expert, you are capable of creating scripts from specifications.
Loads and processes the ClublogXML file for the current locale.
Can you tell what is the following Python 3 function doing def _load_countryfile(self, url="https://www.country-files.com/cty/cty.plist", country_mapping_filename="countryfilemapping.json", cty_file=None): """ Load and process the Clublo...
You are a Python code architect, reviewing and designing scalable and efficient code
def _download_file(self, url, apikey=None): """ Download lookup files either from Clublog or Country-files.com """ import gzip import tempfile cty = {} cty_date = "" cty_file_path = None filename = None # download file if apikey: # clubl...
Write a Python 3 script to download lookup files either from Clublog or Country - files. com and return the filename of the downloaded file.
As a Python code analyst, you investigate and solve complex coding mysteries
Extract the header of the Clublog XML File
How would you explain what the following Python 3 function does def _extract_clublog_header(self, cty_xml_filename): cty_header = {} try: with open(cty_xml_filename, "r") as cty: raw_header = cty.readline() cty_date = re.search("date='.+'", raw_header) ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _remove_clublog_xml_header(self, cty_xml_filename): """ remove the header of the Clublog XML File to make it properly parseable for the python ElementTree XML parser """ import tempfile try: with open(cty_xml_filename, "r") as f: c...
Can you implement a function in Python 3 that removes the header of the Clublog XML File to make it properly parseable for the python ElementTree XML parser
As a Python code composer, you craft elegant and concise scripts.
Parse the content of a clublog XML file and return the dictionary of the ADIF Country Entity IDs and their values.
Given the following Python 3 function, write the documentation def _parse_clublog_xml(self, cty_xml_filename): entities = {} call_exceptions = {} prefixes = {} invalid_operations = {} zone_exceptions = {} call_exceptions_index = {} prefixes_index = {} in...
You are a Python code architect, reviewing and designing scalable and efficient code
Parse the content of a PLIST file from country - files. com and return the parsed values in dictionaries.
Here you have a function in Python 3, explain what it does def _parse_country_file(self, cty_file, country_mapping_filename=None): import plistlib cty_list = None entities = {} exceptions = {} prefixes = {} exceptions_index = {} prefixes_index = {} exc...
You are a Python code generator, capable of creating scripts from specifications.
Generates a random word of the given length.
Explain what the following Python 3 code does def _generate_random_word(self, length): return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))
As a Python code composer, you craft elegant and concise scripts.
Checks if the response from the API Key is OK and if it is not raise LookupError
Explain what the following Python 3 code does def _check_html_response(self, response): error1 = "Access to this form requires a valid API key. For more info see: http://www.clublog.org/need_api.php" error2 = "Invalid or missing API Key" if response.status_code == requests.codes.ok: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Serialize a Dictionary into JSON
Here you have a function in Python 3, explain what it does def _serialize_data(self, my_dict): new_dict = {} for item in my_dict: if isinstance(my_dict[item], datetime): new_dict[item] = my_dict[item].strftime('%Y-%m-%d%H:%M:%S') else: new_dict[ite...
As a Python code composer, you craft elegant and concise scripts.
def get_methods(*objs): """ Return the names of all callable attributes of an object""" return set( attr for obj in objs for attr in dir(obj) if not attr.startswith('_') and callable(getattr(obj, attr)) )
Can you create a Python 3 function that returns the names of all callable attributes of an object
As a Python code composer, you craft elegant and concise scripts.
def from_file(cls, filename, *, strict=True): """ Create a new Config object from a configuration file. Args: filename (str): The location and name of the configuration file. strict (bool): If true raises a ConfigLoadError when the configuration cannot be found. ...
Write a Python 3 function for creating a new Config object from a configuration file.
You are a Python code analyst, evaluating scripts for potential improvements.
Loads the configuration from a file.
How would you explain what the following Python 3 function does def load_from_file(self, filename=None, *, strict=True): self.set_to_default() if filename: self._update_from_file(filename) else: if LIGHTFLOW_CONFIG_ENV not in os.environ: if os.path.isfile...
As a Python code translator, you convert algorithms and pseudocode into Python.
Load the configuration from a dictionary.
Here you have a function in Python 3, explain what it does def load_from_dict(self, conf_dict=None): self.set_to_default() self._update_dict(self._config, conf_dict) self._update_python_paths()
You are a Python code analyst, evaluating scripts for potential improvements.
Updates the dictionary with the values from a file.
Given the following Python 3 function, write the documentation def _update_from_file(self, filename): if os.path.exists(filename): try: with open(filename, 'r') as config_file: yaml_dict = yaml.safe_load(config_file.read()) if yaml_dict is not ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Append the workflow and libraries paths to the PYTHONPATH.
Explain what the following Python 3 code does def _update_python_paths(self): for path in self._config['workflows'] + self._config['libraries']: if os.path.isdir(os.path.abspath(path)): if path not in sys.path: sys.path.append(path) else: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Decode a single character spot into pieces and return a dict with the spot data
Here you have a function in Python 3, explain what it does def decode_char_spot(raw_string): data = {} # Spotter callsign if re.match('[A-Za-z0-9\/]+[:$]', raw_string[6:15]): data[const.SPOTTER] = re.sub(':', '', re.match('[A-Za-z0-9\/]+[:$]', raw_string[6:15]).group(0)) else: raise Va...
You are a Python code architect, reviewing and designing scalable and efficient code
def decode_pc11_message(raw_string): """Decode PC11 message, which usually contains DX Spots""" data = {} spot = raw_string.split("^") data[const.FREQUENCY] = float(spot[1]) data[const.DX] = spot[2] data[const.TIME] = datetime.fromtimestamp(mktime(strptime(spot[3]+" "+spot[4][:-1], "%d-%b-%Y %H...
Implement a Python 3 function for decoding PC11 message which usually contains DX Spots
As a Python code analyst, you investigate and solve complex coding mysteries
Decode PC23 Message which usually contains WCY
How would you explain what the following Python 3 function does def decode_pc23_message(raw_string): data = {} wcy = raw_string.split("^") data[const.R] = int(wcy[1]) data[const.expk] = int(wcy[2]) data[const.CALLSIGN] = wcy[3] data[const.A] = wcy[4] data[const.SFI] = wcy[5] data[const....
As a Python code composer, you craft elegant and concise scripts.
This method is called by the internal run method of the internal run method. It wraps the run method to make sure that the data object passed to the internal run method is passed to the internal run method.
Given the following Python 3 function, write the documentation def _run(self, data, store, signal, context, *, success_callback=None, stop_callback=None, abort_callback=None): """ The internal run method that decorates the public run method. This method makes sure data is being passed to a...
As a Python code analyst, you investigate and solve complex coding mysteries
Converts WGS84 coordinates into Maidenhead Locator
Make a summary of the following Python 3 code def latlong_to_locator (latitude, longitude): if longitude >= 180 or longitude <= -180: raise ValueError if latitude >= 90 or latitude <= -90: raise ValueError longitude += 180; latitude +=90; locator = chr(ord('A') + int(longitude / ...
You are a Python code generator, capable of creating scripts from specifications.
Converts a Maidenhead locator in the corresponding WGS84 coordinates into a Latitude and Longitude tuple.
Can you generate the documentation for the following Python 3 function def locator_to_latlong (locator): locator = locator.upper() if len(locator) == 5 or len(locator) < 4: raise ValueError if ord(locator[0]) > ord('R') or ord(locator[0]) < ord('A'): raise ValueError if ord(locator[1...
As a Python code composer, you craft elegant and concise scripts.
def calculate_distance(locator1, locator2): """calculates the (shortpath) distance between two Maidenhead locators Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Distance in km ...
Write a Python 3 function that can calculate the distance between two Maidenhead locators in km
You are a Python code architect, reviewing and designing scalable and efficient code
def calculate_distance_longpath(locator1, locator2): """calculates the (longpath) distance between two Maidenhead locators Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Distance in...
Can you write a function in Python 3 where it calculates the longpath distance between two Maidenhead locators in km
You are a Python code analyst, evaluating scripts for potential improvements.
Calculates the heading from the first to the second locator and returns the heading in degree.
Can you tell what is the following Python 3 function doing def calculate_heading(locator1, locator2): lat1, long1 = locator_to_latlong(locator1) lat2, long2 = locator_to_latlong(locator2) r_lat1 = radians(lat1) r_lon1 = radians(long1) r_lat2 = radians(lat2) r_lon2 = radians(long2) d_lon ...
As a Python code composer, you craft elegant and concise scripts.
calculates the long path heading from the first to the second locator
Explain what the following Python 3 code does def calculate_heading_longpath(locator1, locator2): heading = calculate_heading(locator1, locator2) lp = (heading + 180)%360 return lp
As a Python code composer, you craft elegant and concise scripts.
Calculates the next sunset and sunrise for a Maidenhead locator at a give date & time.
Can you generate the documentation for the following Python 3 function def calculate_sunrise_sunset(locator, calc_date=datetime.utcnow()): morning_dawn = None sunrise = None evening_dawn = None sunset = None latitude, longitude = locator_to_latlong(locator) if type(calc_date) != datetime: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def cloudpickle_dumps(obj, dumper=cloudpickle.dumps): """ Encode Python objects into a byte stream using cloudpickle. """ return dumper(obj, protocol=serialization.pickle_protocol)
Create a Python 3 function for encoding Python objects into a byte stream using cloudpickle.
As a python code expert, you are capable of creating scripts from specifications.
Monkey patch Celery to use cloudpickle instead of pickle.
Explain what the following Python 3 code does def patch_celery(): registry = serialization.registry serialization.pickle = cloudpickle registry.unregister('pickle') registry.register('pickle', cloudpickle_dumps, cloudpickle_loads, content_type='application/x-python-serialize', ...
As a Python code analyst, you investigate and solve complex coding mysteries
def connect(self): """ Connects to the redis database. """ self._connection = StrictRedis( host=self._host, port=self._port, db=self._database, password=self._password)
Can you create a Python 3 function that connects to the redis database.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a single request from the list of requests and returns it.
Explain what the following Python 3 code does def receive(self): pickled_request = self._connection.connection.lpop(self._request_key) return pickle.loads(pickled_request) if pickled_request is not None else None
You are a Python code generator, capable of creating scripts from specifications.
Send a response back to the client that issued a request.
Can you tell what is the following Python 3 function doing def send(self, response): self._connection.connection.set('{}:{}'.format(SIGNAL_REDIS_PREFIX, response.uid), pickle.dumps(response))
As a python code expert, you are capable of creating scripts from specifications.
Push the request back onto the queue.
Can you generate the documentation for the following Python 3 function def restore(self, request): self._connection.connection.rpush(self._request_key, pickle.dumps(request))
You are a Python code architect, reviewing and designing scalable and efficient code
Send a request to the server and wait for its response.
Can you generate a brief explanation for the following Python 3 code def send(self, request): self._connection.connection.rpush(self._request_key, pickle.dumps(request)) resp_key = '{}:{}'.format(SIGNAL_REDIS_PREFIX, request.uid) while True: if self._connection.polling_time > 0.0: ...
As a Python code composer, you craft elegant and concise scripts.
Verifies if pattern for matching and finding fulfill expected structure.
Can you generate the documentation for the following Python 3 function def verify_pattern(pattern): regex = re.compile("^!?[a-zA-Z]+$|[*]{1,2}$") def __verify_pattern__(__pattern__): if not __pattern__: return False elif __pattern__[0] == "!": return __verify_pattern__(...
You are a Python code generator, capable of creating scripts from specifications.
Prints a tree of sentences using token_attr from token
Can you tell what is the following Python 3 function doing def print_tree(sent, token_attr): def __print_sent__(token, attr): print("{", end=" ") [__print_sent__(t, attr) for t in token.lefts] print(u"%s->%s(%s)" % (token,token.dep_,token.tag_ if not attr else getattr(token, attr)), end="") ...
You are a Python code architect, reviewing and designing scalable and efficient code
def match_tree(sentence, pattern): """Matches given sentence with provided pattern. :param sentence: sentence from Spacy(see: http://spacy.io/docs/#doc-spans-sents) representing complete statement :param pattern: pattern to which sentence will be compared :return: True if sentence match to...
How would you implement a function in Python 3 that matches given sentence with given pattern.
As a Python code translator, you convert algorithms and pseudocode into Python.
Find all tokens from parts of sentence fitted to pattern.
Make a summary of the following Python 3 code def find_tokens(sentence, pattern): if not verify_pattern(pattern): raise PatternSyntaxException(pattern) def _match_node(t, p, tokens): pat_node = p.pop(0) if p else "" res = not pat_node or (_match_token(t, pat_node, False) and (not p or ...
You are a Python code generator, capable of creating scripts from specifications.
def split (s, delimter, trim = True, limit = 0): # pragma: no cover """ Split a string using a single-character delimter @params: `s`: the string `delimter`: the single-character delimter `trim`: whether to trim each part. Default: True @examples: ```python ret = split("'a,b',c", ",") # ret ==...
How would you implement a function in Python 3 that splits a string using a single - character delimter.
As a python code expert, you are capable of creating scripts from specifications.
def render(self, **context): """ Render this template by applying it to `context`. @params: `context`: a dictionary of values to use in this rendering. @returns: The rendered string """ # Make the complete context we'll use. localns = self.envs.copy() localns.update(context) try: exec(str(se...
Write a Python 3 function for rendering this template by applying it to context.
You are a Python code generator, capable of creating scripts from specifications.
def addLine(self, line): """ Add a line of source to the code. Indentation and newline will be added for you, don't provide them. @params: `line`: The line to add """ if not isinstance(line, LiquidLine): line = LiquidLine(line) line.ndent = self.ndent self.codes.append(line)
Can you create a Python 3 function that adds a line of source to the code.
As a Python code translator, you convert algorithms and pseudocode into Python.
def level(self, lvl=None): '''Get or set the logging level.''' if not lvl: return self._lvl self._lvl = self._parse_level(lvl) self.stream.setLevel(self._lvl) logging.root.setLevel(self._lvl)
Write a Python 3 function for getting or set the logging level.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_rate_from_db(currency: str) -> Decimal: """ Fetch currency conversion rate from the database """ from .models import ConversionRate try: rate = ConversionRate.objects.get_rate(currency) except ConversionRate.DoesNotExist: # noqa raise ValueError('No conversion rate for %...
Can you implement a function in Python 3 that fetches currency conversion rate from the database
You are a Python code analyst, evaluating scripts for potential improvements.
def get_conversion_rate(from_currency: str, to_currency: str) -> Decimal: """ Get conversion rate to use in exchange """ reverse_rate = False if to_currency == BASE_CURRENCY: # Fetch exchange rate for base currency and use 1 / rate for conversion rate_currency = from_currency ...
Can you create a Python 3 function that gets conversion rate for a given currency
As a Python code analyst, you investigate and solve complex coding mysteries
Exchange currency from base to another currency.
Here you have a function in Python 3, explain what it does def exchange_currency( base: T, to_currency: str, *, conversion_rate: Decimal=None) -> T: """ Exchanges Money, TaxedMoney and their ranges to the specified currency. get_rate parameter is a callable taking single argument (target currency) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Normalize a location name by stripping punctuation and collapsing runs of whitespace and returning the normalized name.
Can you generate a brief explanation for the following Python 3 code def normalize(location_name, preserve_commas=False): def replace(match): if preserve_commas and ',' in match.group(0): return ',' return ' ' return NORMALIZATION_RE.sub(replace, location_name).strip().lower()
As a Python code analyst, you investigate and solve complex coding mysteries
def calc_precipitation_stats(self, months=None, avg_stats=True, percentile=50): """ Calculates precipitation statistics for the cascade model while aggregating hourly observations Parameters ---------- months : Months for each seasons to be used for statistics (array of n...
Write a Python 3 script for calculating precipitation statistics for the cascade model while aggregating hourly observations
You are a Python code generator, capable of creating scripts from specifications.
def calc_wind_stats(self): """ Calculates statistics in order to derive diurnal patterns of wind speed """ a, b, t_shift = melodist.fit_cosine_function(self.data.wind) self.wind.update(a=a, b=b, t_shift=t_shift)
How would you implement a function in Python 3 that calculates statistics in order to derive diurnal patterns of wind speed
You are a Python code analyst, evaluating scripts for potential improvements.
def calc_humidity_stats(self): """ Calculates statistics in order to derive diurnal patterns of relative humidity. """ a1, a0 = melodist.calculate_dewpoint_regression(self.data, return_stats=False) self.hum.update(a0=a0, a1=a1) self.hum.kr = 12 self.hum.month_hou...
How would you code a function in Python 3 to calculate statistics in order to derive diurnal patterns of relative humidity.
As a Python code translator, you convert algorithms and pseudocode into Python.
Calculates statistics in order to derive diurnal patterns of temperature
How would you explain what the following Python 3 function does def calc_temperature_stats(self): self.temp.max_delta = melodist.get_shift_by_data(self.data.temp, self._lon, self._lat, self._timezone) self.temp.mean_course = melodist.util.calculate_mean_daily_course_by_month(self.data.temp, normalize=Tr...
You are a Python code architect, reviewing and designing scalable and efficient code
def calc_radiation_stats(self, data_daily=None, day_length=None, how='all'): """ Calculates statistics in order to derive solar radiation from sunshine duration or minimum/maximum temperature. Parameters ---------- data_daily : DataFrame, optional Daily data ...
Write a Python 3 function for calculating statistics in order to derive solar radiation from sunshine duration or solar temperature.
You are a Python code architect, reviewing and designing scalable and efficient code
Exports statistical data to a JSON formatted file
Can you generate the documentation for the following Python 3 function def to_json(self, filename=None): def json_encoder(obj): if isinstance(obj, pd.DataFrame) or isinstance(obj, pd.Series): if isinstance(obj.index, pd.core.index.MultiIndex): obj = obj.reset_inde...
As a Python code translator, you convert algorithms and pseudocode into Python.
Imports statistical data from a JSON formatted file containing statistics.
Can you tell what is the following Python 3 function doing def from_json(cls, filename): def json_decoder(d): if 'p01' in d and 'pxx' in d: # we assume this is a CascadeStatistics object return melodist.cascade.CascadeStatistics.from_dict(d) return d with open(...
As a Python code composer, you craft elegant and concise scripts.
function to disaggregate radiation by day
Make a summary of the following Python 3 code def disaggregate_radiation(data_daily, sun_times=None, pot_rad=None, method='pot_rad', angstr_a=0.25, angstr_b=0.5, ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def potential_radiation(dates, lon, lat, timezone, terrain_slope=0, terrain_slope_azimuth=0, cloud_fraction=0, split=False): """ Calculate potential shortwave radiation for a specific location and time. This routine calculates global radiation as described in: Liston, G. E...
Implement a Python 3 function for returning a DataFrame containing the total potential radiation for a specific location and time.
As a Python code composer, you craft elegant and concise scripts.
def bristow_campbell(tmin, tmax, pot_rad_daily, A, C): """calculates potential shortwave radiation based on minimum and maximum temperature This routine calculates global radiation as described in: Bristow, Keith L., and Gaylon S. Campbell: On the relationship between incoming solar radiation and ...
Write a Python 3 function that can calculate potential shortwave radiation based on minimum and maximum temperature This routine calculates global radiation as described in: Bristow, Keith L., and Gaylon S. Campbell: On the relationship between incoming solar radiation and daily maximum and minimum temperature. Agricul...
As a python code expert, you are capable of creating scripts from specifications.
Fits the A and C parameters for the Bristow & Campbell model using observed daily solar radiation and observed daily radiation.
Can you generate the documentation for the following Python 3 function def fit_bristow_campbell_params(tmin, tmax, pot_rad_daily, obs_rad_daily): def bc_absbias(ac): return np.abs(np.mean(bristow_campbell(df.tmin, df.tmax, df.pot, ac[0], ac[1]) - df.obs)) df = pd.DataFrame(data=dict(tmin=tmin, tmax...
As a Python code translator, you convert algorithms and pseudocode into Python.
Calculates mean daily radiation from observed sunshine duration according to Angstroem model.
Make a summary of the following Python 3 code def angstroem(ssd, day_length, pot_rad_daily, a, b): if isinstance(a, pd.Series): months = ssd.index.month a = a.loc[months].values b = b.loc[months].values glob_day = (a + b * ssd / day_length) * pot_rad_daily return glob_day
You are a Python code architect, reviewing and designing scalable and efficient code
Fits the a and b parameters for the Angstroem model using observed daily solar radiation and mean daily.
Can you tell what is the following Python 3 function doing def fit_angstroem_params(ssd, day_length, pot_rad_daily, obs_rad_daily): df = pd.DataFrame(data=dict(ssd=ssd, day_length=day_length, pot=pot_rad_daily, obs=obs_rad_daily)).dropna(how='any') def angstroem_opt(x, a, b): return angstroem(x[0],...
As a Python code translator, you convert algorithms and pseudocode into Python.
Return a decorator that registers the decorated class as a CTYPE resolver with the given name.
Explain what the following Python 3 code does def register(name): def decorator(class_): if name in known_resolvers: raise ValueError('duplicate resolver name "%s"' % name) known_resolvers[name] = class_ return decorator
As a Python code translator, you convert algorithms and pseudocode into Python.
Return a location resolver.
Can you tell what is the following Python 3 function doing def get_resolver(order=None, options=None, modules=None): if not known_resolvers: from . import resolvers as carmen_resolvers modules = [carmen_resolvers] + (modules or []) for module in modules: for loader, name, _ in pk...
As a Python code composer, you craft elegant and concise scripts.
Load locations into this resolver from the given location_file which should contain one JSON object per line containing a location.
Can you generate the documentation for the following Python 3 function def load_locations(self, location_file=None): if location_file is None: contents = pkgutil.get_data(__package__, 'data/locations.json') contents_string = contents.decode("ascii") locations = contents_strin...
You are a Python code architect, reviewing and designing scalable and efficient code
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()])
Can you write a function in Python 3 where it returns a tuple containing a canonicalized version of this location s country state county and city names.
You are a Python code generator, capable of creating scripts from specifications.
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...
Create a Python 3 function to return a tuple containing this location s country state county and city names.
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Create a Python 3 function for returning a location representing the administrative unit above the one represented by this location.
You are a Python code architect, reviewing and designing scalable and efficient code
disaggregation of daily values of relative humidity.
Explain what the following Python 3 code does 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: da...
As a Python code composer, you craft elegant and concise scripts.
This function calculates the cosine function of the windspeed accroding to the cosine function CTYPE
Can you generate a brief explanation for the following Python 3 code def _cosine_function(x, a, b, t_shift): mean_wind, t = x return a * mean_wind * np.cos(np.pi * (t - t_shift) / 12) + b * mean_wind
You are a Python code generator, capable of creating scripts from specifications.
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)....
Create a Python 3 function to fit a cosine function to observed hourly windspeed data AttributeNames is a list of dicts where each dictionary contains the key and the value of the observed hourly windspeed is the observed hourly windspeed of the wind.
You are a Python code analyst, evaluating scripts for potential improvements.
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 : "...
Can you implement a function in Python 3 that reads smet data and returns the data in required dataformat.
You are a Python code generator, capable of creating scripts from specifications.
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...
How would you code a function in Python 3 to read the DWD file and returns the data in required dataformat
You are a Python code generator, capable of creating scripts from specifications.
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 ...
Implement a Python 3 function for writing a smet file
You are a Python code architect, reviewing and designing scalable and efficient code
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 ...
Implement a Python 3 function for reading a single KNMI s meteorological time series file and returns pandas data frame including time series
As a python code expert, you are capable of creating scripts from specifications.
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: ...
Can you create a Python 3 function that reads files from a directory and merges the time series with the time series.
As a Python code composer, you craft elegant and concise scripts.
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)
Implement a function in Python 3 to calculate sunrise sunset for each day.
You are a Python code generator, capable of creating scripts from specifications.
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...
Make a summary of the following Python 3 code def disaggregate_wind(self, method='equal'): self.data_disagg.wind = melodist.disaggregate_wind(self.data_daily.wind, method=method, **self.statistics.wind)
You are a Python code generator, capable of creating scripts from specifications.
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`...
Make a summary of the following Python 3 code def disaggregate_temperature(self, method='sine_min_max', min_max_time='fix', mod_nighttime=False): self.data_disagg.temp = melodist.disaggregate_temperature( self.data_daily, method=method, min_max_time=min_max_time, ...
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
How would you explain what the following Python 3 function does 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 method != 'mean_course': pot_rad = melodist.potential_radiation(self.data_dis...
As a Python code composer, you craft elegant and concise scripts.
Wrapper function for pandas. Series. interpolate that can be used to disaggregate values for the daily calendar.
Explain what the following Python 3 code does def interpolate(self, column_hours, method='linear', limit=24, limit_direction='both', **kwargs): kwargs = dict(kwargs, method=method, limit=limit, limit_direction=limit_direction) data = melodist.util.prepare_interpolation_data(self.data_daily, column_hours...
As a Python code analyst, you investigate and solve complex coding mysteries
Get the first n entries for a given Table or Column.
How would you explain what the following Python 3 function does 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 LIMIT %d" % (col, self.table.name, id_col, n)) return self._db.query(select, **kwargs)
As a Python code composer, you craft elegant and concise scripts.
Return the last n entries in the set.
Can you tell what is the following Python 3 function doing def last(self, n=10, by=None, **kwargs): return self.tail(n=n, by=by, **kwargs)
You are a Python code analyst, evaluating scripts for potential improvements.
Select from a given Table or Column with the specified WHERE clause.
Here you have a function in Python 3, explain what it does def where(self, where_string, **kwargs): col, id_col = self._query_helper(by=None) where_string = str(where_string) # Coerce here, for .__contains___ where_operators = ["=", ">", "<", "LIKE", "like"] if np.any([where_string.__c...
You are a Python code generator, capable of creating scripts from specifications.
Executes a raw SQL query against the SQL database and returns the result as a DataFrame or None.
Given the following Python 3 function, write the documentation def query(self, sql_query, return_as="dataframe"): if isinstance(sql_query, str): pass elif isinstance(sql_query, unicode): sql_query = str(sql_query) else: raise QueryDbError("query() requires a s...
As a python code expert, you are capable of creating scripts from specifications.
Set the metadata of the current object.
Can you generate a brief explanation for the following Python 3 code def _set_metadata(self): meta = QueryDbMeta() with self._engine.connect() as conn: meta.bind = conn meta.reflect() self._meta = meta # Set an inspect attribute, whose subattributes #...
As a python code expert, you are capable of creating scripts from specifications.
function to get max temp shift by observed hourly data
Can you tell what is the following Python 3 function doing 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 : longi...
As a Python code analyst, you investigate and solve complex coding mysteries
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). ...
Write a Python 3 function that can return the daily values in a single hour by equally distributing the daily values.
As a Python code composer, you craft elegant and concise scripts.
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...
Write a Python 3 function for calculating vapor pressure from temperature and humidity after Sonntag 1990.
You are a Python code architect, reviewing and designing scalable and efficient code
computes the dewpoint temperature in the Konch tree
Can you tell what is the following Python 3 function doing def dewpoint_temperature(temp, hum): assert(temp.shape == hum.shape) vap_press = vapor_pressure(temp, hum) positives = np.array(temp >= 273.15) dewpoint_temp = temp.copy() * np.nan dewpoint_temp[positives] = 243.12 * np.log(vap_press[posit...
As a python code expert, you are capable of creating scripts from specifications.
linear regression calculation of x and y
Can you generate the documentation for the following Python 3 function def linregress(x, y, return_stats=False): a1, a0, r_value, p_value, stderr = scipy.stats.linregress(x, y) retval = a1, a0 if return_stats: retval += r_value, p_value, stderr return retval
You are a Python code analyst, evaluating scripts for potential improvements.
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,...
Can you write a function in Python 3 where it computes the times of sunrise sunnoon and sunset for each day.
You are a Python code generator, capable of creating scripts from specifications.