output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def add_ticks_to_x(ax, newticks, newnames):
"""Add new ticks to an axis.
I use this for the right-hand plotting of resonance names in my plots.
"""
ticks = list(ax.get_xticks())
ticks.extend(newticks)
ax.set_xticks(ticks)
names = list(ax.get_xticklabels())
names.extend(newnames)
ax... | How would you code a function in Python 3 to
add new ticks to an axis. | As a python code expert, you are capable of creating scripts from specifications. |
def create(self, set):
"""
Creates a new Set.
"""
target_url = self.client.get_url('SET', 'POST', 'create')
r = self.client.request('POST', target_url, json=set._serialize())
return set._deserialize(r.json(), self) | How would you implement a function in Python 3 that
creates a new Set. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def set_metadata(self, set_id, fp):
"""
Set the XML metadata on a set.
:param file fp: file-like object to read the XML metadata from.
"""
base_url = self.client.get_url('SET', 'GET', 'single', {'id': set_id})
self._metadata.set(base_url, fp) | Write a Python 3 script for
setting the XML metadata on a set. | As a Python code analyst, you investigate and solve complex coding mysteries |
Set the XML metadata on a set. | Can you generate the documentation for the following Python 3 function
def set_metadata(self, fp):
base_url = self._client.get_url('SET', 'GET', 'single', {'id': self.id})
self._manager._metadata.set(base_url, fp)
# reload myself
r = self._client.request('GET', base_url)
return ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Set the XML metadata for the current object. | Make a summary of the following Python 3 code
def set(self, parent_url, fp):
url = parent_url + self.client.get_url_path('METADATA', 'POST', 'set', {})
r = self.client.request('POST', url, data=fp, headers={'Content-Type': 'text/xml'})
if r.status_code not in [200, 201]:
raise except... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_xml(self, fp, format=FORMAT_NATIVE):
"""
Returns the XML metadata for this source, converted to the requested format.
Converted metadata may not contain all the same information as the native format.
:param file fp: A path, or an open file-like object which the content should be... | Write a Python 3 function for
returning the XML metadata for this source converted to the requested format. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the available format names for this metadata | Can you tell what is the following Python 3 function doing
def get_formats(self):
formats = []
for key in (self.FORMAT_DC, self.FORMAT_FGDC, self.FORMAT_ISO):
if hasattr(self, key):
formats.append(key)
return formats | You are a Python code architect, reviewing and designing scalable and efficient code |
Decorator that asserts the model instance is bound. | Here you have a function in Python 3, explain what it does
def is_bound(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if not self._is_bound:
raise ValueError("%r must be bound to call %s()" % (self, method.__name__))
return method(self, *args, **kwargs)
re... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Query OPUS via the image_id. This method returns a list of URLs into the database_path attribute. | Can you tell what is the following Python 3 function doing
def query_image_id(self, image_id):
myquery = {"primaryfilespec": image_id}
self.create_files_request(myquery, fmt="json")
self.unpack_json_response()
return self.obsids | As a Python code composer, you craft elegant and concise scripts. |
def create_request_with_query(self, kind, query, size="thumb", fmt="json"):
"""api/data.[fmt], api/images/[size].[fmt] api/files.[fmt]
kind = ['data', 'images', 'files']
"""
if kind == "data" or kind == "files":
url = "{}/{}.{}".format(base_url, kind, fmt)
elif kin... | Implement a Python 3 function for
creating a request to get the relevant data from the API. | You are a Python code generator, capable of creating scripts from specifications. |
Query OPUS data between times t1 and t2. | Given the following Python 3 function, write the documentation
def get_between_times(self, t1, t2, target=None):
try:
# checking if times have isoformat() method (datetimes have)
t1 = t1.isoformat()
t2 = t2.isoformat()
except AttributeError:
# if not, shou... | As a Python code composer, you craft elegant and concise scripts. |
Shows preview images using the Jupyter notebook HTML display. | Explain what the following Python 3 code does
def show_images(self, size="small"):
d = dict(small=256, med=512, thumb=100, full=1024)
try:
width = d[size]
except KeyError:
print("Allowed keys:", d.keys())
return
img_urls = [i._get_img_url(size) for i i... | As a Python code composer, you craft elegant and concise scripts. |
def download_results(self, savedir=None, raw=True, calib=False, index=None):
"""Download the previously found and stored Opus obsids.
Parameters
==========
savedir: str or pathlib.Path, optional
If the database root folder as defined by the config.ini should not be used,
... | How would you code a function in Python 3 to
download the previously found and stored Opus obsids. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Download preview files for previously found Opus obsids. | Explain what the following Python 3 code does
def download_previews(self, savedir=None):
for obsid in self.obsids:
pm = io.PathManager(obsid.img_id, savedir=savedir)
pm.basepath.mkdir(exist_ok=True)
basename = Path(obsid.medium_img_url).name
print("Downloading", b... | As a python code expert, you are capable of creating scripts from specifications. |
Find which swap situtation we are in by time. | Make a summary of the following Python 3 code
def which_epi_janus_resonance(name, time):
t1 = Time('2002-01-21').to_datetime()
delta = Time(time).to_datetime() - t1
yearfraction = delta.days / 365
if int(yearfraction / 4) % 2 == 0:
return name + '2'
else:
return name + '1' | You are a Python code analyst, evaluating scripts for potential improvements. |
A filterable list views of layers returning the draft version of each layer or table. | Explain what the following Python 3 code does
def list_drafts(self):
target_url = self.client.get_url('LAYER', 'GET', 'multidraft')
return base.Query(self, target_url) | As a python code expert, you are capable of creating scripts from specifications. |
Filterable list of versions of a layer. | How would you explain what the following Python 3 function does
def list_versions(self, layer_id):
target_url = self.client.get_url('VERSION', 'GET', 'multi', {'layer_id': layer_id})
return base.Query(self, target_url, valid_filter_attributes=('data',), valid_sort_attributes=()) | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_version(self, layer_id, version_id, expand=[]):
"""
Get a specific version of a layer.
"""
target_url = self.client.get_url('VERSION', 'GET', 'single', {'layer_id': layer_id, 'version_id': version_id})
return self._get(target_url, expand=expand) | Can you write a function in Python 3 where it
gets a specific version of a layer. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the current draft version of a layer. | Make a summary of the following Python 3 code
def get_draft(self, layer_id, expand=[]):
target_url = self.client.get_url('VERSION', 'GET', 'draft', {'layer_id': layer_id})
return self._get(target_url, expand=expand) | As a python code expert, you are capable of creating scripts from specifications. |
def get_published(self, layer_id, expand=[]):
"""
Get the latest published version of this layer.
:raises NotFound: if there is no published version.
"""
target_url = self.client.get_url('VERSION', 'GET', 'published', {'layer_id': layer_id})
return self._get(target_url, e... | Write a Python 3 function for
getting the latest published version of this layer. | You are a Python code architect, reviewing and designing scalable and efficient code |
Creates a new draft version for the given layer. | Can you generate a brief explanation for the following Python 3 code
def create_draft(self, layer_id):
target_url = self.client.get_url('VERSION', 'POST', 'create', {'layer_id': layer_id})
r = self.client.request('POST', target_url, json={})
return self.create_from_result(r.json()) | As a python code expert, you are capable of creating scripts from specifications. |
Starts importing the specified draft version. | Can you tell what is the following Python 3 function doing
def start_import(self, layer_id, version_id):
target_url = self.client.get_url('VERSION', 'POST', 'import', {'layer_id': layer_id, 'version_id': version_id})
r = self.client.request('POST', target_url, json={})
return self.create_from_re... | You are a Python code architect, reviewing and designing scalable and efficient code |
Start importing a new version of the layer. | Make a summary of the following Python 3 code
def start_update(self, layer_id):
target_url = self.client.get_url('LAYER', 'POST', 'update', {'layer_id': layer_id})
r = self.client.request('POST', target_url, json={})
return self.parent.create_from_result(r.json()) | You are a Python code architect, reviewing and designing scalable and efficient code |
Set the XML metadata on a layer draft version. | Make a summary of the following Python 3 code
def set_metadata(self, layer_id, version_id, fp):
base_url = self.client.get_url('VERSION', 'GET', 'single', {'layer_id': layer_id, 'version_id': version_id})
self._metadata.set(base_url, fp) | As a python code expert, you are capable of creating scripts from specifications. |
Return True if this version is the published version of a layer | How would you explain what the following Python 3 function does
def is_published_version(self):
pub_ver = getattr(self, 'published_version', None)
this_ver = getattr(self, 'this_version', None)
return this_ver and pub_ver and (this_ver == pub_ver) | As a python code expert, you are capable of creating scripts from specifications. |
def is_draft_version(self):
""" Return if this version is the draft version of a layer """
pub_ver = getattr(self, 'published_version', None)
latest_ver = getattr(self, 'latest_version', None)
this_ver = getattr(self, 'this_version', None)
return this_ver and latest_ver and (this... | How would you code a function in Python 3 to
return True if this version is the draft version of a layer | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a list of versions of a specific version of the layer. | How would you explain what the following Python 3 function does
def list_versions(self):
target_url = self._client.get_url('VERSION', 'GET', 'multi', {'layer_id': self.id})
return base.Query(self._manager, target_url, valid_filter_attributes=('data',), valid_sort_attributes=()) | You are a Python code generator, capable of creating scripts from specifications. |
def get_version(self, version_id, expand=[]):
"""
Get a specific version of this layer
"""
target_url = self._client.get_url('VERSION', 'GET', 'single', {'layer_id': self.id, 'version_id': version_id})
return self._manager._get(target_url, expand=expand) | Can you write a function in Python 3 where it
gets a specific version of this layer. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_draft_version(self, expand=[]):
"""
Get the current draft version of this layer.
:raises NotFound: if there is no draft version.
"""
target_url = self._client.get_url('VERSION', 'GET', 'draft', {'layer_id': self.id})
return self._manager._get(target_url, expand=ex... | Implement a Python 3 function for
getting the current draft version of this layer. | As a python code expert, you are capable of creating scripts from specifications. |
Starts importing this draft layerversion. | Given the following Python 3 function, write the documentation
def start_import(self, version_id=None):
if not version_id:
version_id = self.version.id
target_url = self._client.get_url('VERSION', 'POST', 'import', {'layer_id': self.id, 'version_id': version_id})
r = self._client.re... | You are a Python code generator, capable of creating scripts from specifications. |
A shortcut to create a new version and start importing it. | How would you explain what the following Python 3 function does
def start_update(self):
target_url = self._client.get_url('LAYER', 'POST', 'update', {'layer_id': self.id})
r = self._client.request('POST', target_url, json={})
return self._manager.create_from_result(r.json()) | As a python code expert, you are capable of creating scripts from specifications. |
Creates a publish task just for this version which publishes as soon as any import is complete. | Can you tell what is the following Python 3 function doing
def publish(self, version_id=None):
if not version_id:
version_id = self.version.id
target_url = self._client.get_url('VERSION', 'POST', 'publish', {'layer_id': self.id, 'version_id': version_id})
r = self._client.request('P... | As a Python code composer, you craft elegant and concise scripts. |
Save this draft layerversion. | How would you explain what the following Python 3 function does
def save(self, with_data=False):
target_url = self._client.get_url('VERSION', 'PUT', 'edit', {'layer_id': self.id, 'version_id': self.version.id})
r = self._client.request('PUT', target_url, json=self._serialize(with_data=with_data))
... | As a python code expert, you are capable of creating scripts from specifications. |
Deletes this draft version. | Explain what the following Python 3 code does
def delete_version(self, version_id=None):
if not version_id:
version_id = self.version.id
target_url = self._client.get_url('VERSION', 'DELETE', 'single', {'layer_id': self.id, 'version_id': version_id})
r = self._client.request('DELETE... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the model class matching a URL | Can you generate the documentation for the following Python 3 function
def _get_item_class(self, url):
if '/layers/' in url:
return Layer
elif '/tables/' in url:
return Table
elif '/sets/' in url:
return Set
# elif '/documents/' in url:
# r... | As a Python code composer, you craft elegant and concise scripts. |
def get_year_since_resonance(ringcube):
"Calculate the fraction of the year since moon swap."
t0 = dt(2006, 1, 21)
td = ringcube.imagetime - t0
return td.days / 365.25 | How would you implement a function in Python 3 that
calculates the fraction of the year since moon swap. | You are a Python code generator, capable of creating scripts from specifications. |
def create_polynoms():
"""Create and return poly1d objects.
Uses the parameters from Morgan to create poly1d objects for
calculations.
"""
fname = pr.resource_filename('pyciss', 'data/soliton_prediction_parameters.csv')
res_df = pd.read_csv(fname)
polys = {}
for resorder, row in zip('65... | Write a Python 3 function for
creating and return a dict of all the polynomal objects for the current order of the solar prediction. | As a Python code composer, you craft elegant and concise scripts. |
Workhorse function. Returns a dict with all solitons found in a single ISS image. | Make a summary of the following Python 3 code
def check_for_soliton(img_id):
pm = io.PathManager(img_id)
try:
ringcube = RingCube(pm.cubepath)
except FileNotFoundError:
ringcube = RingCube(pm.undestriped)
polys = create_polynoms()
minrad = ringcube.minrad.to(u.km)
maxrad = ringcu... | You are a Python code generator, capable of creating scripts from specifications. |
Return the manager instance for the given model. | Explain what the following Python 3 code does
def get_manager(self, model):
if isinstance(model, six.string_types):
# undocumented string lookup
for k, m in self._manager_map.items():
if k.__name__ == model:
return m
else:
r... | You are a Python code analyst, evaluating scripts for potential improvements. |
Assemble the headers for the current request. | How would you explain what the following Python 3 function does
def _assemble_headers(self, method, user_headers=None):
headers = copy.deepcopy(user_headers or {})
if method not in ('GET', 'HEAD'):
headers.setdefault('Content-Type', 'application/json')
return headers | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a dictionary of parameters extracted from a populated URL. | Can you generate a brief explanation for the following Python 3 code
def reverse_url(self, datatype, url, verb='GET', urltype='single', api_version=None):
api_version = api_version or 'v1'
templates = getattr(self, 'URL_TEMPLATES__%s' % api_version)
# this is fairly simplistic, if necessary we ... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a fully formed url for the current session. | Explain what the following Python 3 code does
def get_url(self, datatype, verb, urltype, params={}, api_host=None, api_version=None):
api_version = api_version or 'v1'
api_host = api_host or self.host
subst = params.copy()
subst['api_host'] = api_host
subst['api_version'] = api_... | You are a Python code architect, reviewing and designing scalable and efficient code |
Turn CDMRemote variable into something like a numpy. ndarray. | Can you generate a brief explanation for the following Python 3 code
def open_store_variable(self, name, var):
data = indexing.LazilyOuterIndexedArray(CDMArrayWrapper(name, self))
return Variable(var.dimensions, data, {a: getattr(var, a) for a in var.ncattrs()}) | You are a Python code generator, capable of creating scripts from specifications. |
def get_attrs(self):
"""Get the global attributes from underlying data set."""
return FrozenOrderedDict((a, getattr(self.ds, a)) for a in self.ds.ncattrs()) | Can you implement a function in Python 3 that
gets the global attributes from underlying data set. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the dimensions from underlying data set. | Can you generate the documentation for the following Python 3 function
def get_dimensions(self):
return FrozenOrderedDict((k, len(v)) for k, v in self.ds.dimensions.items()) | You are a Python code generator, capable of creating scripts from specifications. |
Identify the base URL of the THREDDS server from the catalog URL. | Make a summary of the following Python 3 code
def _find_base_tds_url(catalog_url):
url_components = urlparse(catalog_url)
if url_components.path:
return catalog_url.split(url_components.path)[0]
else:
return catalog_url | As a Python code composer, you craft elegant and concise scripts. |
Filter keys for an item closest to the desired time. | How would you explain what the following Python 3 function does
def filter_time_nearest(self, time, regex=None):
return min(self._get_datasets_with_times(regex),
key=lambda i: abs((i[0] - time).total_seconds()))[-1] | You are a Python code analyst, evaluating scripts for potential improvements. |
def filter_time_range(self, start, end, regex=None):
"""Filter keys for all items within the desired time range.
Loops over all keys in the collection and uses `regex` to extract and build
`datetime`s. From the collection of `datetime`s, all values within `start` and `end`
(inclusive) a... | Create a Python 3 function for
filtering keys for all items within the specified time range. | You are a Python code generator, capable of creating scripts from specifications. |
def pop(self, key, *args, **kwargs):
"""Remove and return the value associated with case-insensitive ``key``."""
return super(CaseInsensitiveDict, self).pop(CaseInsensitiveStr(key)) | Write a Python 3 script for
removing and return the value associated with case - insensitive key. | As a Python code composer, you craft elegant and concise scripts. |
Convert key set to lowercase. | Can you generate the documentation for the following Python 3 function
def _keys_to_lower(self):
for k in list(self.keys()):
val = super(CaseInsensitiveDict, self).__getitem__(k)
super(CaseInsensitiveDict, self).__delitem__(k)
self.__setitem__(CaseInsensitiveStr(k), val) | As a python code expert, you are capable of creating scripts from specifications. |
Resolve the url of the dataset when reading latest. xml. | Here you have a function in Python 3, explain what it does
def resolve_url(self, catalog_url):
if catalog_url != '':
resolver_base = catalog_url.split('catalog.xml')[0]
resolver_url = resolver_base + self.url_path
resolver_xml = session_manager.urlopen(resolver_url)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def make_access_urls(self, catalog_url, all_services, metadata=None):
"""Make fully qualified urls for the access methods enabled on the dataset.
Parameters
----------
catalog_url : str
The top level server url
all_services : List[SimpleService]
list of :... | Can you write a function in Python 3 where it
makes fully qualified urls for the access methods enabled on the dataset. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create an access method from a catalog element. | Can you generate the documentation for the following Python 3 function
def add_access_element_info(self, access_element):
service_name = access_element.attrib['serviceName']
url_path = access_element.attrib['urlPath']
self.access_element_info[service_name] = url_path | As a Python code analyst, you investigate and solve complex coding mysteries |
def download(self, filename=None):
"""Download the dataset to a local file.
Parameters
----------
filename : str, optional
The full path to which the dataset will be saved
"""
if filename is None:
filename = self.name
with self.remote_ope... | Can you create a Python 3 function that
downloads the dataset to a local file. | You are a Python code generator, capable of creating scripts from specifications. |
Open the remote dataset and get a netCDF4 - compatible Dataset object providing index - based subsetting capabilities. | Can you tell what is the following Python 3 function doing
def remote_access(self, service=None, use_xarray=None):
if service is None:
service = 'CdmRemote' if 'CdmRemote' in self.access_urls else 'OPENDAP'
if service not in (CaseInsensitiveStr('CdmRemote'), CaseInsensitiveStr('OPENDAP')):
... | You are a Python code generator, capable of creating scripts from specifications. |
Subset the dataset.
Open the remote dataset and get a client for talking to ``service``.
Parameters
----------
service : str, optional
The name of the service for subsetting the dataset. Defaults to 'NetcdfSubset'
or 'NetcdfServer', in that order, depending on t... | Make a summary of the following Python 3 code
def subset(self, service=None):
if service is None:
for serviceName in self.ncssServiceNames:
if serviceName in self.access_urls:
service = serviceName
break
else:
raise ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Access the dataset using a particular service. | Can you tell what is the following Python 3 function doing
def access_with_service(self, service, use_xarray=None):
service = CaseInsensitiveStr(service)
if service == 'CdmRemote':
if use_xarray:
from .cdmr.xarray_support import CDMRemoteStore
try:
... | As a Python code composer, you craft elegant and concise scripts. |
def _get_metadata(self):
"""Get header information and store as metadata for the endpoint."""
self.metadata = self.fetch_header()
self.variables = {g.name for g in self.metadata.grids} | Can you implement a function in Python 3 that
gets header information and store as metadata for the endpoint. | As a Python code composer, you craft elegant and concise scripts. |
def fetch_header(self):
"""Make a header request to the endpoint."""
query = self.query().add_query_parameter(req='header')
return self._parse_messages(self.get_query(query).content)[0] | Create a Python 3 function for
making a header request to the endpoint. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Request the featureType from the endpoint. | Can you generate a brief explanation for the following Python 3 code
def fetch_feature_type(self):
query = self.query().add_query_parameter(req='featureType')
return self.get_query(query).content | You are a Python code analyst, evaluating scripts for potential improvements. |
def fetch_coords(self, query):
"""Pull down coordinate data from the endpoint."""
q = query.add_query_parameter(req='coord')
return self._parse_messages(self.get_query(q).content) | Implement a function in Python 3 to
pull down coordinate data from the endpoint. | As a Python code analyst, you investigate and solve complex coding mysteries |
Process the IGRA2 text file for observations at site_id matching time. | Can you generate the documentation for the following Python 3 function
def _get_data(self):
# Split the list of times into begin and end dates. If only
# one date is supplied, set both begin and end dates equal to that date.
body, header, dates_long, dates = self._get_data_raw()
params... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _get_data_raw(self):
"""Download observations matching the time range.
Returns a tuple with a string for the body, string for the headers,
and a list of dates.
"""
# Import need to be here so we can monkeypatch urlopen for testing and avoid
# downloading live data fo... | Implement a function in Python 3 to
download observations matching the time range. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _select_date_range(self, lines):
"""Identify lines containing headers within the range begin_date to end_date.
Parameters
-----
lines: list
list of lines from the IGRA2 data file.
"""
headers = []
num_lev = []
dates = []
# Get in... | How would you implement a function in Python 3 that
selects the time range of the IGRA2 data file. | As a Python code composer, you craft elegant and concise scripts. |
Return a dictionary with names colspecs and dtype for IGRA2 data. | Can you generate a brief explanation for the following Python 3 code
def _get_fwf_params(self):
def _cdec(power=1):
"""Make a function to convert string 'value*10^power' to float."""
def _cdec_power(val):
if val in ['-9999', '-8888', '-99999']:
return ... | As a python code expert, you are capable of creating scripts from specifications. |
def _clean_body_df(self, df):
"""Format the dataframe, remove empty rows, and add units attribute."""
if self.suffix == '-drvd.txt':
df = df.dropna(subset=('temperature', 'reported_relative_humidity',
'u_wind', 'v_wind'), how='all').reset_index(drop=True)
... | Can you create a Python 3 function that
formats the dataframe remove empty rows and add units attribute. | As a python code expert, you are capable of creating scripts from specifications. |
def _clean_header_df(self, df):
"""Format the header dataframe and add units."""
if self.suffix == '-drvd.txt':
df.units = {'release_time': 'second',
'precipitable_water': 'millimeter',
'inv_pressure': 'hPa',
'inv_height... | Create a Python 3 function to
format the header dataframe and add units. | You are a Python code architect, reviewing and designing scalable and efficient code |
Retrieve the realtime buoy data from NDBC. | Can you tell what is the following Python 3 function doing
def realtime_observations(cls, buoy, data_type='txt'):
endpoint = cls()
parsers = {'txt': endpoint._parse_met,
'drift': endpoint._parse_drift,
'cwind': endpoint._parse_cwind,
'spec': endpo... | As a Python code composer, you craft elegant and concise scripts. |
def _parse_met(content):
"""Parse standard meteorological data from NDBC buoys.
Parameters
----------
content : str
Data to parse
Returns
-------
:class:`pandas.DataFrame` containing the data
"""
col_names = ['year', 'month', 'da... | Write a Python 3 script to
parse the standard meteorological data from NDBC buoys. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Parse supplemental measurements data. | Can you generate a brief explanation for the following Python 3 code
def _parse_supl(content):
col_names = ['year', 'month', 'day', 'hour', 'minute',
'hourly_low_pressure', 'hourly_low_pressure_time',
'hourly_high_wind', 'hourly_high_wind_direction',
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _check_if_url_valid(url):
"""Check if a url is valid (returns 200) or not.
Parameters
----------
url : str
URL to check
Returns
-------
bool if url is valid
"""
r = requests.head(url)
if r.status_code == 200:
... | How would you code a function in Python 3 to
check if a url is valid or not. | You are a Python code analyst, evaluating scripts for potential improvements. |
def buoy_data_types(cls, buoy):
"""Determine which types of data are available for a given buoy.
Parameters
----------
buoy : str
Buoy name
Returns
-------
dict of valid file extensions and their descriptions
"""
endpoint = cls()... | Implement a function in Python 3 to
determine which types of data are available for a given buoy. | As a Python code analyst, you investigate and solve complex coding mysteries |
Retrieve the raw buoy data from NDBC. | Can you tell what is the following Python 3 function doing
def raw_buoy_data(cls, buoy, data_type='txt'):
endpoint = cls()
resp = endpoint.get_path('data/realtime2/{}.{}'.format(buoy, data_type))
return resp.text | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a new HTTP session with our user - agent set. | Can you tell what is the following Python 3 function doing
def create_session(self):
ret = requests.Session()
ret.headers['User-Agent'] = self.user_agent
for k, v in self.options.items():
setattr(ret, k, v)
return ret | As a Python code composer, you craft elegant and concise scripts. |
A thin wrapper around requests. Session. get that returns a file - like object that is wrapped around the resulting content. | Can you generate a brief explanation for the following Python 3 code
def urlopen(self, url, **kwargs):
return BytesIO(self.create_session().get(url, **kwargs).content) | You are a Python code generator, capable of creating scripts from specifications. |
def lonlat_box(self, west, east, south, north):
"""Add a latitude/longitude bounding box to the query.
This adds a request for a spatial bounding box, bounded by ('north', 'south')
for latitude and ('east', 'west') for the longitude. This modifies the query
in-place, but returns `self` ... | Implement a function in Python 3 to
add a latitude and longitude bounding box to the query. | As a python code expert, you are capable of creating scripts from specifications. |
Add a latitude point to the query. | How would you explain what the following Python 3 function does
def lonlat_point(self, lon, lat):
self._set_query(self.spatial_query, longitude=lon, latitude=lat)
return self | As a python code expert, you are capable of creating scripts from specifications. |
Add a request for a specific time to the query. | Can you generate the documentation for the following Python 3 function
def time(self, time):
self._set_query(self.time_query, time=self._format_time(time))
return self | You are a Python code analyst, evaluating scripts for potential improvements. |
Add a request for a time range to the query. | Here you have a function in Python 3, explain what it does
def time_range(self, start, end):
self._set_query(self.time_query, time_start=self._format_time(start),
time_end=self._format_time(end))
return self | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_query(self, query):
"""Make a GET request, including a query, to the endpoint.
The path of the request is to the base URL assigned to the endpoint.
Parameters
----------
query : DataQuery
The query to pass when making the request
Returns
---... | Create a Python 3 function for
making a GET request including a query to the endpoint. | As a Python code composer, you craft elegant and concise scripts. |
Make a GET request optionally including a query to a relative path. | Make a summary of the following Python 3 code
def get_path(self, path, query=None):
return self.get(self.url_path(path), query) | As a python code expert, you are capable of creating scripts from specifications. |
def get(self, path, params=None):
"""Make a GET request, optionally including a parameters, to a path.
The path of the request is the full URL.
Parameters
----------
path : str
The URL to request
params : DataQuery, optional
The query to pass whe... | How would you code a function in Python 3 to
make a GET request to the server. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the full path to the Group including any parent Groups. | Make a summary of the following Python 3 code
def path(self):
# If root, return '/'
if self.dataset is self:
return ''
else: # Otherwise recurse
return self.dataset.path + '/' + self.name | You are a Python code analyst, evaluating scripts for potential improvements. |
Load a Group from an NCStream object. | How would you explain what the following Python 3 function does
def load_from_stream(self, group):
self._unpack_attrs(group.atts)
self.name = group.name
for dim in group.dims:
new_dim = Dimension(self, dim.name)
self.dimensions[dim.name] = new_dim
new_dim.loa... | As a python code expert, you are capable of creating scripts from specifications. |
Populate the Variable from an NCStream object. | Explain what the following Python 3 code does
def load_from_stream(self, var):
dims = []
for d in var.shape:
dim = Dimension(None, d.name)
dim.load_from_stream(d)
dims.append(dim)
self.dimensions = tuple(dim.name for dim in dims)
self.shape = tuple(di... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Load from an NCStream object. | Here you have a function in Python 3, explain what it does
def load_from_stream(self, dim):
self.unlimited = dim.isUnlimited
self.private = dim.isPrivate
self.vlen = dim.isVlen
if not self.vlen:
self.size = dim.length | As a python code expert, you are capable of creating scripts from specifications. |
Get the needed header information to initialize dataset. | How would you explain what the following Python 3 function does
def _read_header(self):
self._header = self.cdmrf.fetch_header()
self.load_from_stream(self._header) | As a Python code composer, you craft elegant and concise scripts. |
Populate the CoverageDataset from the protobuf information. | Can you generate a brief explanation for the following Python 3 code
def load_from_stream(self, header):
self._unpack_attrs(header.atts)
self.name = header.name
self.lon_lat_domain = header.latlonRect
self.proj_domain = header.projRect
self.date_range = header.dateRange
s... | As a python code expert, you are capable of creating scripts from specifications. |
def request_data(cls, time, site_id, **kwargs):
"""Retrieve upper air observations from Iowa State's archive for a single station.
Parameters
----------
time : datetime
The date and time of the desired observation.
site_id : str
The three letter ICAO ide... | Create a Python 3 function for
requesting data from Iowa State s archive for a single station. | You are a Python code architect, reviewing and designing scalable and efficient code |
Request all data from the Iowa State s archive for all stations. | Can you tell what is the following Python 3 function doing
def request_all_data(cls, time, pressure=None, **kwargs):
endpoint = cls()
df = endpoint._get_data(time, None, pressure, **kwargs)
return df | As a Python code composer, you craft elegant and concise scripts. |
Download data from Iowa State s upper air archive. | Can you generate the documentation for the following Python 3 function
def _get_data(self, time, site_id, pressure=None):
json_data = self._get_data_raw(time, site_id, pressure)
data = {}
for profile in json_data['profiles']:
for pt in profile['profile']:
for field in... | You are a Python code generator, capable of creating scripts from specifications. |
def _get_data_raw(self, time, site_id, pressure=None):
r"""Download data from the Iowa State's upper air archive.
Parameters
----------
time : datetime
Date and time for which data should be downloaded
site_id : str
Site id for which data should be downlo... | Write a Python 3 function for
downloading data from the Iowa State s upper air archive. | You are a Python code architect, reviewing and designing scalable and efficient code |
def parse_station_table(root):
"""Parse station list XML file."""
stations = [parse_xml_station(elem) for elem in root.findall('station')]
return {st.id: st for st in stations} | How would you implement a function in Python 3 that
parses station list XML file. | As a Python code composer, you craft elegant and concise scripts. |
Create a : class : Station instance from an XML tag. | Make a summary of the following Python 3 code
def parse_xml_station(elem):
stid = elem.attrib['id']
name = elem.find('name').text
lat = float(elem.find('latitude').text)
lon = float(elem.find('longitude').text)
elev = float(elem.find('elevation').text)
return Station(id=stid, elevation=elev, lat... | You are a Python code analyst, evaluating scripts for potential improvements. |
Set one or more stations for the query. | How would you explain what the following Python 3 function does
def stations(self, *stns):
self._set_query(self.spatial_query, stn=stns)
return self | As a Python code composer, you craft elegant and concise scripts. |
def validate_query(self, query):
"""Validate a query.
Determines whether `query` is well-formed. This includes checking for all
required parameters, as well as checking parameters for valid values.
Parameters
----------
query : RadarQuery
The query to valida... | Write a Python 3 script for
validating a query. Determines whether `query` is well-formed. This includes checking for all required parameters, as well as checking parameters for valid values. Parameters ---------- query : RadarQuery The query to validate Returns ------- valid : bool Whether `query` is valid. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_catalog(self, query):
"""Fetch a parsed THREDDS catalog from the radar server.
Requests a catalog of radar data files data from the radar server given the
parameters in `query` and returns a :class:`~siphon.catalog.TDSCatalog` instance.
Parameters
----------
que... | How would you code a function in Python 3 to
fetch a parsed THREDDS catalog from the radar server given the parameters in query and returns a TDSCatalog instance. | As a Python code analyst, you investigate and solve complex coding mysteries |
This function is used to make a request to the ACIS Web Services API for data based on a given method and parameters. | Explain what the following Python 3 code does
def acis_request(method, params):
base_url = 'http://data.rcc-acis.org/' # ACIS Web API URL
timeout = 300 if method == 'MultiStnData' else 60
try:
response = session_manager.create_session().post(base_url + method, json=params,
... | As a Python code composer, you craft elegant and concise scripts. |
def parse_xml(data, handle_units):
"""Parse XML data returned by NCSS."""
root = ET.fromstring(data)
return squish(parse_xml_dataset(root, handle_units)) | How would you implement a function in Python 3 that
parses XML data returned by NCSS. | You are a Python code architect, reviewing and designing scalable and efficient code |
Parse an XML point tag. | Can you generate a brief explanation for the following Python 3 code
def parse_xml_point(elem):
point = {}
units = {}
for data in elem.findall('data'):
name = data.get('name')
unit = data.get('units')
point[name] = float(data.text) if name != 'date' else parse_iso_date(data.text)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.