output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Yields the optional tagfiles that are missing from the manifest.
Can you generate the documentation for the following Python 3 function def missing_optional_tagfiles(self): for tagfilepath in list(self.tagfile_entries().keys()): if not os.path.isfile(os.path.join(self.path, tagfilepath)): yield tagfilepath
As a python code expert, you are capable of creating scripts from specifications.
Checks that the structure and contents are valid.
Make a summary of the following Python 3 code def validate(self, processes=1, fast=False): self._validate_structure() self._validate_bagittxt() self._validate_contents(processes=processes, fast=fast) return True
You are a Python code analyst, evaluating scripts for potential improvements.
def is_valid(self, fast=False): """Returns validation success or failure as boolean. Optional fast parameter passed directly to validate(). """ try: self.validate(fast=fast) except BagError: return False return True
Write a Python 3 script to return validation success or failure as boolean.
You are a Python code architect, reviewing and designing scalable and efficient code
Validate that the actual file contents matches the recorded hashes stored in the manifest files
Explain what the following Python 3 code does def _validate_entries(self, processes): errors = list() # First we'll make sure there's no mismatch between the filesystem # and the list of files in the manifest(s) only_in_manifests, only_on_fs = self.compare_manifests_with_fs() fo...
As a Python code translator, you convert algorithms and pseudocode into Python.
Verify that bagit. txt conforms to specification
Explain what the following Python 3 code does def _validate_bagittxt(self): bagit_file_path = os.path.join(self.path, "bagit.txt") with open(bagit_file_path, 'r') as bagit_file: first_line = bagit_file.readline() if first_line.startswith(BOM): raise BagValidationE...
As a python code expert, you are capable of creating scripts from specifications.
Fix any numpy data types that didn t map back to python data types properly
How would you explain what the following Python 3 function does def _fix_numeric_types(c): try: for var, data in c.items(): for k, v in data.items(): if k in ["hasMeanValue", "hasMaxValue", "hasMinValue", "hasMedianValue"]: if math.isnan(v): ...
As a Python code composer, you craft elegant and concise scripts.
Return the age of the candidate in the table column data.
Can you generate the documentation for the following Python 3 function def _get_age(columns): # Need to check multiple places for age, year, or yrbp # 1. Check the column variable name # 2. Check for an "inferredVariableType age = [] try: # Step 1: # Check for age first (exact matc...
As a python code expert, you are capable of creating scripts from specifications.
Calculates the resolution of the current object.
Can you generate the documentation for the following Python 3 function def _get_resolution(age, values): res = [] try: # Get the nan index from the values and remove from age # age2 = age[np.where(~np.isnan(values))[0]] # res = np.diff(age2) # Make sure that age and values are n...
As a python code expert, you are capable of creating scripts from specifications.
This function calculates the inferred data for a single element of the array v.
Can you generate a brief explanation for the following Python 3 code def __get_inferred_data_res_2(v=None, calc=True): # Base: If something goes wrong, or if there are no values, then use "NaN" placeholders. d = { "hasMinValue": "nan", "hasMaxValue": "nan", "hasMeanValue": "nan", "hasMedianValue...
As a Python code analyst, you investigate and solve complex coding mysteries
Calculate Resolution and m/m for column values.
Can you tell what is the following Python 3 function doing def _get_inferred_data_res(column, age): try: with warnings.catch_warnings(): warnings.simplefilter("ignore") # Get the values for this column values = column["values"] # Make sure that age and values ...
You are a Python code architect, reviewing and designing scalable and efficient code
Calculate the m / m / m for the values of the column.
Can you tell what is the following Python 3 function doing def _get_inferred_data_column(column): try: with warnings.catch_warnings(): warnings.simplefilter("ignore") # Get the values for this column values = column["values"] # Make sure that age and values ar...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_inferred_data_table(table, pc): """ Table level: Dive down, calculate data, then return the new table with the inferred data. :param str pc: paleo or chron :param dict table: Metadata :return dict table: Metadata """ age = None if pc == "paleo": # Get the age values data...
Write a Python 3 script to calculate the inferred data for a specific variable in the metadata table.
As a Python code analyst, you investigate and solve complex coding mysteries
def register_func(env, need_function): """ Registers a new sphinx-needs function for the given sphinx environment. :param env: Sphinx environment :param need_function: Python method :return: None """ if not hasattr(env, 'needs_functions'): env.needs_functions = {} func_name = n...
Create a Python 3 function for registering a new sphinx - needs function for the given sphinx environment.
You are a Python code generator, capable of creating scripts from specifications.
def execute_func(env, need, func_string): """ Executes a given function string. :param env: Sphinx environment :param need: Actual need, which contains the found function string :param func_string: string of the found function. Without [[ ]] :return: return value of executed function """ ...
Write a Python 3 function for executing a given function string.
As a Python code composer, you craft elegant and concise scripts.
def find_and_replace_node_content(node, env, need): """ Search inside a given node and its children for nodes of type Text, if found check if it contains a function string and run/replace it. :param node: Node to analyse :return: None """ new_children = [] if not node.children: ...
Write a Python 3 function for finding a node and its children and replace it with the content of the node.
You are a Python code generator, capable of creating scripts from specifications.
def resolve_dynamic_values(env): """ Resolve dynamic values inside need data. Rough workflow: #. Parse all needs and their data for a string like [[ my_func(a,b,c) ]] #. Extract function name and call parameters #. Execute registered function name with extracted call parameters #. Replace ...
Write a Python 3 function for resolving dynamic values inside need data.
As a Python code translator, you convert algorithms and pseudocode into Python.
Analyze given string of the function and extract the function name arguments keyword arguments and return the function name arguments keyword arguments
Can you generate a brief explanation for the following Python 3 code def _analyze_func_string(func_string): func = ast.parse(func_string) try: func_call = func.body[0].value func_name = func_call.func.id except AttributeError: raise SphinxError("Given dynamic function string is not a...
You are a Python code architect, reviewing and designing scalable and efficient code
Initialize and start objects. This is called automatically when importing the package.
Explain what the following Python 3 code does def run(): # GLOBALS global cwd, files, logger_start, logger_benchmark, settings, _timeseries_data _timeseries_data = {} # files = {".lpd": [ {"full_path", "filename_ext", "filename_no_ext", "dir"} ], ".xls": [...], ".txt": [...]} settings = {"note_updat...
You are a Python code architect, reviewing and designing scalable and efficient code
Read a. LiPD file and return a dict of metadata.
How would you explain what the following Python 3 function does def readLipd(usr_path=""): global cwd, settings, files if settings["verbose"]: __disclaimer(opt="update") start = clock() files[".lpd"] = [] __read(usr_path, ".lpd") _d = __read_lipd_contents() end = clock() logger_b...
You are a Python code architect, reviewing and designing scalable and efficient code
Read Excel file and return current working directory
Given the following Python 3 function, write the documentation def readExcel(usr_path=""): global cwd, files start = clock() files[".xls"] = [] __read(usr_path, ".xls") end = clock() logger_benchmark.info(log_benchmark("readExcel", start, end)) return cwd
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert Excel files to LiPD files.
Explain what the following Python 3 code does def excel(): global files, cwd, settings _d = {} # Turn off verbose. We don't want to clutter the console with extra reading/writing output statements settings["verbose"] = False # Find excel files print("Found " + str(len(files[".xls"])) + " Excel f...
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert between NOAA and LiPD files
Make a summary of the following Python 3 code def noaa(D="", path="", wds_url="", lpd_url="", version=""): global files, cwd # When going from NOAA to LPD, use the global "files" variable. # When going from LPD to NOAA, use the data from the LiPD Library. # Choose the mode _mode = noaa_prompt() ...
As a python code expert, you are capable of creating scripts from specifications.
Validate a single or multiple LiPD files.
Can you generate a brief explanation for the following Python 3 code def validate(D, detailed=True): start = clock() print("\n") # Fetch new results by calling lipd.net/api/validator (costly, may take a while) print("Fetching results from validator at lipd.net/validator... this may take a few moments.\n...
As a python code expert, you are capable of creating scripts from specifications.
Create Pandas DataFrame from TimeSeries object.
Can you generate a brief explanation for the following Python 3 code def tsToDf(tso): dfs = {} try: dfs = ts_to_df(tso) except Exception as e: print("Error: Unable to create data frame") logger_start.warn("ts_to_df: tso malformed: {}".format(e)) return dfs
As a Python code translator, you convert algorithms and pseudocode into Python.
def extractTs(d, whichtables="meas", mode="paleo"): """ Create a time series using LiPD data (uses paleoData by default) | Example : (default) paleoData and meas tables | 1. D = lipd.readLipd() | 2. ts = lipd.extractTs(D) | Example : chronData and all tables | 1. D = lipd.readLipd() | ...
Can you implement a function in Python 3 that extracts a single time series from a LiPD data file.
You are a Python code generator, capable of creating scripts from specifications.
def collapseTs(ts=None): """ Collapse a time series back into LiPD record form. | Example | 1. D = lipd.readLipd() | 2. ts = lipd.extractTs(D) | 3. New_D = lipd.collapseTs(ts) _timeseries_data is sorted by time_id, and then by dataSetName _timeseries_data[10103341]["ODP1098B"] = {data}...
Create a Python 3 function for collapsing a time series into LiPD record form.
You are a Python code architect, reviewing and designing scalable and efficient code
def filterTs(ts, expressions): """ Create a new time series that only contains entries that match the given expression. | Example: | D = lipd.loadLipd() | ts = lipd.extractTs(D) | new_ts = filterTs(ts, "archiveType == marine sediment") | new_ts = filterTs(ts, ["paleoData_variableName == sst...
Can you implement a function in Python 3 that filters the given time series by the given list of expressions.
As a python code expert, you are capable of creating scripts from specifications.
Query the time series for the given expression.
Here you have a function in Python 3, explain what it does def queryTs(ts, expression): # Make a copy of the ts. We're going to work directly on it. _idx = [] # User provided a single query string if isinstance(expressions, str): # Use some magic to turn the given string expression into a machi...
You are a Python code generator, capable of creating scripts from specifications.
def viewTs(ts): """ View the contents of one time series entry in a nicely formatted way | Example | 1. D = lipd.readLipd() | 2. ts = lipd.extractTs(D) | 3. viewTs(ts[0]) :param dict ts: One time series entry :return none: """ _ts = ts if isinstance(ts, list): _ts =...
Write a Python 3 function for viewing the contents of one time series entry in a nicely formatted way
As a Python code composer, you craft elegant and concise scripts.
Display the dataset names of a given LiPD data
Can you generate a brief explanation for the following Python 3 code def showLipds(D=None): if not D: print("Error: LiPD data not provided. Pass LiPD data into the function.") else: print(json.dumps(D.keys(), indent=2)) return
As a Python code translator, you convert algorithms and pseudocode into Python.
def showMetadata(dat): """ Display the metadata specified LiPD in pretty print | Example | showMetadata(D["Africa-ColdAirCave.Sundqvist.2013"]) :param dict dat: Metadata :return none: """ _tmp = rm_values_fields(copy.deepcopy(dat)) print(json.dumps(_tmp, indent=2)) return
Write a Python 3 script to display the metadata specified LiPD in pretty print
You are a Python code architect, reviewing and designing scalable and efficient code
Displays the available data frame names in a given data frame collection
Given the following Python 3 function, write the documentation def showDfs(d): if "metadata" in d: print("metadata") if "paleoData" in d: try: for k, v in d["paleoData"].items(): print(k) except KeyError: pass except AttributeError: ...
As a python code expert, you are capable of creating scripts from specifications.
def getLipdNames(D=None): """ Get a list of all LiPD names in the library | Example | names = lipd.getLipdNames(D) :return list f_list: File list """ _names = [] try: if not D: print("Error: LiPD data not provided. Pass LiPD data into the function.") else: ...
Write a Python 3 script for getting a list of all LiPD names in the library
As a Python code analyst, you investigate and solve complex coding mysteries
Get metadata from a LiPD record in memory
Explain what the following Python 3 code does def getMetadata(L): _l = {} try: # Create a copy. Do not affect the original data. _l = copy.deepcopy(L) # Remove values fields _l = rm_values_fields(_l) except Exception as e: # Input likely not formatted correctly, thoug...
You are a Python code generator, capable of creating scripts from specifications.
def getCsv(L=None): """ Get CSV from LiPD metadata | Example | c = lipd.getCsv(D["Africa-ColdAirCave.Sundqvist.2013"]) :param dict L: One LiPD record :return dict d: CSV data """ _c = {} try: if not L: print("Error: LiPD data not provided. Pass LiPD data into th...
Can you write a function in Python 3 where it gets CSV from LiPD metadata and data set
As a Python code analyst, you investigate and solve complex coding mysteries
def writeLipd(dat, path=""): """ Write LiPD data to file(s) :param dict dat: Metadata :param str path: Destination (optional) :return none: """ global settings start = clock() __write_lipd(dat, path) end = clock() logger_benchmark.info(log_benchmark("writeLipd", start, end))...
Implement a function in Python 3 to write LiPD data to file
You are a Python code architect, reviewing and designing scalable and efficient code
def __universal_read(file_path, file_type): """ Use a file path to create file metadata and load a file in the appropriate way, according to the provided file type. :param str file_path: Path to file :param str file_type: One of approved file types: xls, xlsx, txt, lpd :return none: """ glo...
Can you implement a function in Python 3 that uses a file path to create file metadata and load a file in the appropriate way, according to the provided file type. :param str file_path: Path to file :param str file_type: One of approved file types: xls, xlsx, txt, lpd :return none:
As a python code expert, you are capable of creating scripts from specifications.
Read in a single file in a tree tree.
How would you explain what the following Python 3 function does def __read(usr_path, file_type): # is there a file path specified ? if usr_path: # Is this a URL? Download the file and return the local path is_url = re.match(re_url, usr_path) if is_url: # The usr_path will now...
As a Python code composer, you craft elegant and concise scripts.
def __read_lipd_contents(): """ Use the file metadata to read in the LiPD file contents as a dataset library :return dict: Metadata """ global files, settings _d = {} try: if len(files[".lpd"]) == 1: _d = lipd_read(files[".lpd"][0]["full_path"]) if settings["...
Implement a function in Python 3 to read in the LiPD file contents as a dataset library.
You are a Python code architect, reviewing and designing scalable and efficient code
This function will read a file from the Universal read file system.
Make a summary of the following Python 3 code def __read_file(usr_path, file_type): global files # no path provided. start gui browse if not usr_path: # src files could be a list of one, or a list of many. depending how many files the user selects src_dir, src_files = get_src_or_dst("read",...
You are a Python code architect, reviewing and designing scalable and efficient code
Write LiPD data to file.
Can you tell what is the following Python 3 function doing def __write_lipd(dat, usr_path): global settings # no path provided. start gui browse if not usr_path: # got dir path usr_path, _ignore = get_src_or_dst("write", "directory") # Check if this is a valid directory path valid_pa...
You are a Python code generator, capable of creating scripts from specifications.
Print the disclaimers once.
How would you explain what the following Python 3 function does def __disclaimer(opt=""): global settings if opt is "update": print("Disclaimer: LiPD files may be updated and modified to adhere to standards\n") settings["note_update"] = False if opt is "validate": print("Note: Use li...
You are a Python code analyst, evaluating scripts for potential improvements.
def safe_add_file(filename, app): """ Adds files to builder resources only, if the given filename was not already registered. Needed mainly for tests to avoid multiple registration of the same file and therefore also multiple execution of e.g. a javascript file during page load. :param filename: fi...
How would you implement a function in Python 3 that adds a file to the internal list of resources.
As a Python code composer, you craft elegant and concise scripts.
def safe_remove_file(filename, app): """ Removes a given resource file from builder resources. Needed mostly during test, if multiple sphinx-build are started. During these tests js/cass-files are not cleaned, so a css_file from run A is still registered in run B. :param filename: filename to remov...
Implement a Python 3 function for removing a given file from the resource files list.
As a Python code composer, you craft elegant and concise scripts.
Detects shreds in the current sheet and constructs Shred instances.
Here you have a function in Python 3, explain what it does def get_shreds(self, feature_extractors, sheet_name): if self._shreds is None: shreds = [] _, contours, _ = cv2.findContours(self._foreground_mask, cv2.RETR_EXTERNAL, ...
As a Python code composer, you craft elegant and concise scripts.
Creates a Shred instance from a given contour.
Can you generate the documentation for the following Python 3 function def _make_shred(self, c, name, feature_extractors, sheet_name): height, width, channels = self.orig_img.shape # bounding rect of currrent contour r_x, r_y, r_w, r_h = cv2.boundingRect(c) # Generating simplified cont...
You are a Python code generator, capable of creating scripts from specifications.
def geo_shape(self, sides=5, center=None, distance=None): """ Return a WKT string for a POLYGON with given amount of sides. The polygon is defined by its center (random point if not provided) and the distance (random distance if not provided; in km) of the points to its center. ...
Write a Python 3 function for returning a WKT string for a POLYGON with given amount of sides and center and distance.
As a Python code analyst, you investigate and solve complex coding mysteries
Execute a Toml file and return a list of result_hosts and logfile_result.
Can you tell what is the following Python 3 function doing def run_track(track, result_hosts=None, crate_root=None, output_fmt=None, logfile_info=None, logfile_result=None, failfast=False, sample_mode='reservoir'): """...
You are a Python code generator, capable of creating scripts from specifications.
def main(self): """ Convert a NOAA text file into a lipds file. CSV files will be created if chronology or data sections are available. :return dict: Metadata Dictionary """ logger_noaa_lpd.info("enter main") # Run the file through the parser # Sets self.m...
Write a Python 3 function that can convert a NOAA text file into a lipds file.
As a Python code composer, you craft elegant and concise scripts.
Parse the noaa file and return a compiled dictionary
Explain what the following Python 3 code does def __parse(self): logger_noaa_lpd.info("enter parse") # Strings missing_str = '' data_filename = '' # Counters grant_id = 0 funding_id = 0 data_col_ct = 1 line_num = 0 # Boolean markers ...
You are a Python code analyst, evaluating scripts for potential improvements.
Create a column of paleo data.
Make a summary of the following Python 3 code def __create_paleo_col(l, col_count): # Format: what, material, error, units, seasonality, archive, detail, method, # C or N for Character or Numeric data, direction of relation to climate (positive or negative) d = OrderedDict() d['number'] ...
As a Python code composer, you craft elegant and concise scripts.
def __convert_num(number): """ All path items are automatically strings. If you think it's an int or float, this attempts to convert it. :param str number: :return float or str: """ try: return float(number) except ValueError as e: logger_n...
Can you write a function in Python 3 where it converts a number to a float.
You are a Python code generator, capable of creating scripts from specifications.
Convert underscore naming into camel case naming
Given the following Python 3 function, write the documentation def __camel_case(word): word = word.lower() if '_' in word: split_word = word.split('_') else: split_word = word.split() if len(split_word) > 0: for i, word in enumerate(split_word): ...
As a Python code analyst, you investigate and solve complex coding mysteries
Split a name and unit that are bunched together ( i. e. 250m
Here you have a function in Python 3, explain what it does def __name_unit_regex(word): value = "" unit = "" r = re.findall(re_name_unit, word) try: value = r[0][0] except IndexError as e: logger_noaa_lpd.warn("name_unit_regex: IndexError: value: {}, {}, {...
You are a Python code analyst, evaluating scripts for potential improvements.
Split a string that has value and unit as one.
Can you generate a brief explanation for the following Python 3 code def __split_name_unit(self, line): vals = [] unit = '' if line != '' or line != ' ': # If there are parenthesis, remove them line = line.replace('(', '').replace(')', '') # When value and uni...
As a Python code analyst, you investigate and solve complex coding mysteries
def __str_cleanup(line): """ Remove the unnecessary characters in the line that we don't want :param str line: :return str: """ if '#' in line: line = line.replace("#", "") line = line.strip() if '-----------' in line: line = ''...
Can you write a function in Python 3 where it removes unnecessary characters in the line that we don t want
As a python code expert, you are capable of creating scripts from specifications.
def __slice_key_val(line): """ Get the key and value items from a line by looking for and lines that have a ":" :param str line: :return str str: Key, Value """ position = line.find(":") # If value is -1, that means the item was not found in the string. if...
Implement a Python 3 function for slicing the key and value items from a line.
As a Python code analyst, you investigate and solve complex coding mysteries
Create the coordinates for the current object.
Explain what the following Python 3 code does def __create_coordinates(self, lat, lon, elev): # Sort lat an lon in numerical order lat.sort() lon.sort() geo_dict = {} # 4 coordinate values if len(lat) == 2 and len(lon) == 2: # Matching coordinate pairs. Not 4 ...
As a Python code analyst, you investigate and solve complex coding mysteries
Create a geoJson MultiPoint - type dictionary
Explain what the following Python 3 code does def __geo_multipoint(lat, lon, elev): logger_noaa_lpd.info("enter geo_multipoint") geo_dict = OrderedDict() geometry_dict = OrderedDict() coordinates = [] # bbox = [] temp = [None, None] # 4 unique values # # C...
You are a Python code architect, reviewing and designing scalable and efficient code
Create a geoJson Point - type dictionary
Explain what the following Python 3 code does def __geo_point(lat, lon, elev): logger_noaa_lpd.info("enter geo_point") coordinates = [] geo_dict = OrderedDict() geometry_dict = OrderedDict() for index, point in enumerate(lat): coordinates.append(lat[index]) ...
You are a Python code generator, capable of creating scripts from specifications.
Reorganize the DOI from a dictionary.
Given the following Python 3 function, write the documentation def __reorganize_doi(temp_pub): doi_out = "" doi_list = [] rm = ["doiId", "doi", "doiUrl"] # Check if both entries exist if "doi" and "doiId" in temp_pub: if temp_pub["doi"] == temp_pub["doiId"]: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Create the chron columns from the chron metadata.
Given the following Python 3 function, write the documentation def __create_chron_cols(metadata): chron_col_list = [] chron_col_ct = 1 for variableName, unit in metadata.items(): temp_dict = OrderedDict() temp_dict['column'] = chron_col_ct temp_dict['variableN...
You are a Python code analyst, evaluating scripts for potential improvements.
Reorganize the list of variables given in the chron header.
Can you generate the documentation for the following Python 3 function def __reorganize_chron_header(line): d = {} # Header variables should be tab-delimited. Use regex to split by tabs m = re.split(re_tab_split, line) # If there was an output match from the line, then keep going ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Separate the string of authors and put it into a BibJSON compliant list
Explain what the following Python 3 code does def __reorganize_authors(authors): # String SHOULD be semi-colon separated names. l = [] s = authors.split(";") for author in s: try: l.append({"name": author.strip()}) except AttributeError: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the LiPD version from the metadata dictionary L.
Explain what the following Python 3 code does def get_lipd_version(L): version = 1.0 _keys = ["LipdVersion", "LiPDVersion", "lipdVersion", "liPDVersion"] for _key in _keys: if _key in L: version = L[_key] # Cast the version number to a float try: v...
You are a Python code architect, reviewing and designing scalable and efficient code
def update_lipd_version(L): """ Metadata is indexed by number at this step. Use the current version number to determine where to start updating from. Use "chain versioning" to make it modular. If a file is a few versions behind, convert to EACH version until reaching current. If a file is one versi...
Implement a function in Python 3 to update the metadata of a single lipd version.
You are a Python code analyst, evaluating scripts for potential improvements.
def update_lipd_v1_1(d): """ Update LiPD v1.0 to v1.1 - chronData entry is a list that allows multiple tables - paleoData entry is a list that allows multiple tables - chronData now allows measurement, model, summary, modelTable, ensemble, calibratedAges tables - Added 'lipdVersion' key :pa...
Can you create a Python 3 function that updates LiPD v1. 1 to v1. 0
You are a Python code architect, reviewing and designing scalable and efficient code
Update LiPD v1. 2 to v1. 3.
Can you tell what is the following Python 3 function doing def update_lipd_v1_3(d): # sub routine (recursive): changes all the key names and merges interpretation d = update_lipd_v1_3_names(d) # sub routine: changes ensemble and summary table structure d = update_lipd_v1_3_structure(d) d["lipdVersio...
You are a Python code generator, capable of creating scripts from specifications.
Update the key names and merge interpretations in a list of LiPD v1. 3.
Explain what the following Python 3 code does def update_lipd_v1_3_names(d): try: if isinstance(d, dict): for k, v in d.items(): # dive down for dictionaries d[k] = update_lipd_v1_3_names(v) # see if the key is in the remove list i...
As a Python code composer, you craft elegant and concise scripts.
Update the structure for summary and ensemble tables
Can you tell what is the following Python 3 function doing def update_lipd_v1_3_structure(d): for key in ["paleoData", "chronData"]: if key in d: for entry1 in d[key]: if "model" in entry1: for entry2 in entry1["model"]: for key_table i...
You are a Python code architect, reviewing and designing scalable and efficient code
def merge_csv_metadata(d, csvs): """ Using the given metadata dictionary, retrieve CSV data from CSV files, and insert the CSV values into their respective metadata columns. Checks for both paleoData and chronData tables. :param dict d: Metadata :return dict: Modified metadata dictionary """ ...
Implement a Python 3 function for merging CSV files into a metadata dictionary.
As a python code expert, you are capable of creating scripts from specifications.
Add csv data to all paleo data tables and model data into the metadata tables
Explain what the following Python 3 code does def _merge_csv_section(sections, pc, csvs): logger_csvs.info("enter merge_csv_section") try: # Loop through each table_data in paleoData for _name, _section in sections.items(): if "measurementTable" in _section: section...
As a Python code analyst, you investigate and solve complex coding mysteries
def _merge_csv_model(models, pc, csvs): """ Add csv data to each column in chron model :param dict models: Metadata :return dict models: Metadata """ logger_csvs.info("enter merge_csv_model") try: for _name, _model in models.items(): if "summaryTable" in _model: ...
Write a Python 3 function for adding csv data to each column in chron model
As a Python code analyst, you investigate and solve complex coding mysteries
Add csv data to each column in a list of columns.
Here you have a function in Python 3, explain what it does def _merge_csv_column(table, csvs): # Start putting CSV data into corresponding column "values" key try: ensemble = is_ensemble(table["columns"]) if ensemble: # realization columns if len(table["columns"]) == 1: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def read_csv_from_file(filename): """ Opens the target CSV file and creates a dictionary with one list for each CSV column. :param str filename: :return list of lists: column values """ logger_csvs.info("enter read_csv_from_file") d = {} l = [] try: logger_csvs.info("open fi...
Can you create a Python 3 function that reads the target CSV file and creates a dictionary with one list for each CSV column.
As a Python code composer, you craft elegant and concise scripts.
def write_csv_to_file(d): """ Writes columns of data to a target CSV file. :param dict d: A dictionary containing one list for every data column. Keys: int, Values: list :return None: """ logger_csvs.info("enter write_csv_to_file") try: for filename, data in d.items(): ...
Implement a function in Python 3 to write columns of data to a target CSV file.
You are a Python code architect, reviewing and designing scalable and efficient code
Get all csv from metadata and return new metadata with generated filenames to match files.
Explain what the following Python 3 code does def get_csv_from_metadata(dsn, d): logger_csvs.info("enter get_csv_from_metadata") _csvs = OrderedDict() _d = copy.deepcopy(d) try: if "paleoData" in _d: # Process paleoData section _d["paleoData"], _csvs = _get_csv_from_sect...
You are a Python code analyst, evaluating scripts for potential improvements.
Get the CSVs from the metadata and the measurements and models in the main section.
How would you explain what the following Python 3 function does def _get_csv_from_section(sections, crumbs, csvs): logger_csvs.info("enter get_csv_from_section: {}".format(crumbs)) _idx = 0 try: # Process the tables in section for _name, _section in sections.items(): # Process e...
As a python code expert, you are capable of creating scripts from specifications.
def _get_csv_from_model(models, crumbs, csvs): """ Get csv from model data :param dict models: Metadata :param str crumbs: Crumbs :param dict csvs: Csv :return dict models: Metadata :return dict csvs: Csv """ logger_csvs.info("enter get_csv_from_model: {}".format(crumbs)) _idx =...
Can you write a function in Python 3 where it gets csv from model data
As a Python code composer, you craft elegant and concise scripts.
Search a data tables for column values. Return a dict of column values. ref by var name
Explain what the following Python 3 code does def _get_csv_from_columns(table, filename, csvs): csvs[filename] = OrderedDict() try: if "columns" in table: try: for _name, _column in table["columns"].items(): csvs[filename][_name] = {"number": _column["numb...
You are a Python code architect, reviewing and designing scalable and efficient code
def _get_filename(table): """ Get the filename from a data table. If it doesn't exist, create a new one based on table hierarchy in metadata file. format: <dataSetName>.<section><idx><table><idx>.csv example: ODP1098B.Chron1.ChronMeasurementTable.csv :param dict table: Table data :param str cru...
Write a Python 3 script for getting the filename from a data table.
As a Python code composer, you craft elegant and concise scripts.
Reorder the CSV file d in JSONLD alphabetical order.
Can you generate the documentation for the following Python 3 function def _reorder_csv(d, filename=""): _ensemble = is_ensemble(d) _d2 = [] try: if _ensemble: # 1 column ensemble: realizations if len(d) == 1: for var, data in d.items(): if...
As a python code expert, you are capable of creating scripts from specifications.
def _is_numeric_data(ll): """ List of lists of csv values data :param list ll: :return bool: True, all lists are numeric lists, False, data contains at least one numeric list. """ for l in ll: try: if any(math.isnan(float(i)) or isinstance(i, str) for i in l): ...
How would you code a function in Python 3 to check if the data contains numeric lists.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the format of the LIPD data in the layout that the Lipd. net validator accepts.
Can you generate the documentation for the following Python 3 function def get_validator_format(L): _api_data = [] _j, _csvs = get_csv_from_metadata(L["dataSetName"], L) _j = rm_values_fields(copy.deepcopy(L)) _j = idx_name_to_num(_j) # All the filenames being processed _filenames = ["metadata...
As a Python code analyst, you investigate and solve complex coding mysteries
Create a detailed string output for the file containing the results from the API call.
Here you have a function in Python 3, explain what it does def create_detailed_results(result): string = "" # Validation Response output # string += "VALIDATION RESPONSE\n" string += "STATUS: {}\n".format(result["status"]) if result["feedback"]: string += "WARNINGS: {}\n".format(len(result["...
You are a Python code analyst, evaluating scripts for potential improvements.
def display_results(results, detailed=False): """ Display the results from the validator in a brief or detailed output :param list results: API results, sorted by dataset name (multiple) :param bool detailed: Detailed results on or off :return none: """ # print("\nVALIDATOR RESULTS") # ...
Can you create a Python 3 function that displays the results from the validator in a brief or off state
As a python code expert, you are capable of creating scripts from specifications.
def call_validator_api(dsn, api_data): """ Single call to the lipd.net validator API 'api_data' format: [ {"type": "csv", "filenameFull": /path/to/filename.csv, "data": "", ...}, {"type": "json", "filenameFull": /path/to/metadata.jsonld, "data": "", ...}, ... ] Result f...
Implement a Python 3 function for calling the LiPD. net validator API to get a list of files from one dataset.
As a Python code translator, you convert algorithms and pseudocode into Python.
def procces_filters(all_needs, current_needlist): """ Filters all needs with given configuration :param current_needlist: needlist object, which stores all filters :param all_needs: List of all needs inside document :return: list of needs, which passed the filters """ if current_needlist[...
Can you implement a function in Python 3 that filters all needs with given configuration and returns all needs which pass the filters
You are a Python code analyst, evaluating scripts for potential improvements.
Filters given needs based on a given filter string.
Can you tell what is the following Python 3 function doing def filter_needs(needs, filter_string="", filter_parts=True, merge_part_with_parent=True): if filter_string is None or filter_string == "": return needs found_needs = [] for filter_need in needs: try: if filter_single_...
As a Python code analyst, you investigate and solve complex coding mysteries
def filter_single_need(need, filter_string=""): """ Checks if a single need/need_part passes a filter_string :param need: need or need_part :param filter_string: string, which is used as input for eval() :return: True, if need as passed the filter_string, else False """ filter_context = nee...
Can you create a Python 3 function that checks if a single need passes a filter_string
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns logging level based on boolean
Here you have a function in Python 3, explain what it does def get_logging_level(debug): level = logging.INFO if debug: level = logging.DEBUG return level
You are a Python code architect, reviewing and designing scalable and efficient code
def run_spec(spec, benchmark_hosts, result_hosts=None, output_fmt=None, logfile_info=None, logfile_result=None, action=None, fail_if=None, sample_mode='reservoir'): """Run a spec file, executing the statements on...
How would you implement a function in Python 3 that runs a spec file and return a list of Crate node entries.
You are a Python code generator, capable of creating scripts from specifications.
Download a file from a given URL and save it to a local path.
Can you generate a brief explanation for the following Python 3 code def download_from_url(src_url, dst_dir): dst_path = "" if "MD982181" not in src_url: dsn = input("Please enter the dataset name for this file (Name.Location.Year) : ") dst_path = os.path.join(dst_dir, dsn + ".lpd") try:...
You are a Python code analyst, evaluating scripts for potential improvements.
def process_lpd(name, dir_tmp): """ Opens up json file, invokes doi_resolver, closes file, updates changelog, cleans directory, and makes new bag. :param str name: Name of current .lpd file :param str dir_tmp: Path to tmp directory :return none: """ logger_doi_main.info("enter process_lpd") ...
Create a Python 3 function for processing a single LPD file.
As a Python code analyst, you investigate and solve complex coding mysteries
def prompt_force(): """ Ask the user if they want to force update files that were previously resolved :return bool: response """ logger_doi_main.info("enter prompt_force") count = 0 print("Do you want to force updates for previously resolved files? (y/n)") while True: force = inp...
Can you write a function in Python 3 where it asks the user if they want to force update files that were previously resolved.
You are a Python code architect, reviewing and designing scalable and efficient code
Process all needtables nodes and add them to the target node.
How would you explain what the following Python 3 function does def process_needtables(app, doctree, fromdocname): env = app.builder.env for node in doctree.traverse(Needtable): if not app.config.needs_include_needs: # Ok, this is really dirty. # If we replace a node, docutils c...
As a Python code translator, you convert algorithms and pseudocode into Python.
Gets the hierarchy of the section nodes of the current need and then its parent sections
Here you have a function in Python 3, explain what it does def get_sections(need_info): sections = [] current_node = need_info['target_node'] while current_node: if isinstance(current_node, nodes.section): title = current_node.children[0].astext() # If using auto-section numb...
You are a Python code analyst, evaluating scripts for potential improvements.
Delete all needs for a given docname.
Can you generate the documentation for the following Python 3 function def purge_needs(app, env, docname): if not hasattr(env, 'needs_all_needs'): return env.needs_all_needs = {key: need for key, need in env.needs_all_needs.items() if need['docname'] != docname}
As a Python code analyst, you investigate and solve complex coding mysteries
def add_sections(app, doctree, fromdocname): """Add section titles to the needs as additional attributes that can be used in tables and filters""" needs = getattr(app.builder.env, 'needs_all_needs', {}) for key, need_info in needs.items(): sections = get_sections(need_info) need_info['se...
Can you create a Python 3 function that adds section titles to the needs as additional attributes that can be used in tables and filters
You are a Python code generator, capable of creating scripts from specifications.
Process the need nodes.
Explain what the following Python 3 code does def process_need_nodes(app, doctree, fromdocname): if not app.config.needs_include_needs: for node in doctree.traverse(Need): node.parent.remove(node) return env = app.builder.env # If no needs were defined, we do not need to do any...
You are a Python code architect, reviewing and designing scalable and efficient code