text stringlengths 18 773k |
|---|
def _get_num_locations(d):
"""
Find out how many locations are being parsed. Compare lengths of each
coordinate list and return the max
:param dict d: Geo metadata
:return int: Max number of locations
"""
lengths = []
for key in EXCEL_GEO:
try:
if key != "siteName":
... |
def _parse_geo_location(d):
"""
Parse one geo location
:param d:
:return:
"""
d2 = OrderedDict()
filt = {}
d2['type'] = 'Feature'
# If the necessary keys are missing, put in placeholders so there's no KeyErrors.
for key in EXCEL_GEO:
if key not in d:
d[key] = ... |
def _parse_geo_locations(d, idx):
"""
Parse one geo location
:param d:
:return:
"""
d2 = OrderedDict()
filt = {}
d2['type'] = 'Feature'
# If the necessary keys are missing, put in placeholders so there's no KeyErrors.
for key in EXCEL_GEO:
if key not in d:
d[k... |
def compile_authors(cell):
"""
Split the string of author names into the BibJSON format.
:param str cell: Data from author cell
:return: (list of dicts) Author names
"""
logger_excel.info("enter compile_authors")
author_lst = []
s = cell.split(';')
for w in s:
author_lst.appe... |
def compile_temp(d, key, value):
"""
Compiles temporary dictionaries for metadata. Adds a new entry to an existing dictionary.
:param dict d:
:param str key:
:param any value:
:return dict:
"""
if not value:
d[key] = None
elif len(value) == 1:
d[key] = value[0]
el... |
def compile_fund(workbook, sheet, row, col):
"""
Compile funding entries. Iter both rows at the same time. Keep adding entries until both cells are empty.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:return list of dict: l
"""
logger_excel.info("enter compi... |
def __compare_vars(a1, a2, name):
"""
Check that the metadata variable names are the same as the data header variable names
:param list a1: Variable names
:param list a2: Variable names
:param str name: Sheet name
:return bool: Truth
"""
try:
a1 = [i for i in a1 if i]
a2 ... |
def __get_datasetname(d, filename):
"""
Get the filename based on the dataset name in the metadata
:param str filename: Filename.lpd
:return str: Filename
"""
try:
filename = d["dataSetName"]
except KeyError:
logger_excel.info("get_datasetname: KeyError: No dataSetName found.... |
def __set_sheet_filenames(sheets, n):
"""
Use the dataset name to build the filenames in the sheets metadata
:param list sheets: Sheet metadata
:param str n: Dataset Name
:return list: Sheet metadata
"""
try:
for idx, sheet in enumerate(sheets):
try:
sheet... |
def name_to_jsonld(title_in):
"""
Convert formal titles to camelcase json_ld text that matches our context file
Keep a growing list of all titles that are being used in the json_ld context
:param str title_in:
:return str:
"""
title_out = ''
try:
title_in = title_in.lower()
... |
def instance_str(cell):
"""
Match data type and return string
:param any cell:
:return str:
"""
if isinstance(cell, str):
return 'str'
elif isinstance(cell, int):
return 'int'
elif isinstance(cell, float):
return 'float'
else:
return 'unknown' |
def extract_units(string_in):
"""
Extract units from parenthesis in a string. i.e. "elevation (meters)"
:param str string_in:
:return str:
"""
start = '('
stop = ')'
return string_in[string_in.index(start) + 1:string_in.index(stop)] |
def cells_rt_meta_pub(workbook, sheet, row, col, pub_qty):
"""
Publication section is special. It's possible there's more than one publication.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:param int pub_qty: Number of distinct publication sections in this file
... |
def cells_rt_meta(workbook, sheet, row, col):
"""
Traverse all cells in a row. If you find new data in a cell, add it to the list.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:return list: Cell data for a specific row
"""
logger_excel.info("enter cells_rt_m... |
def cells_dn_meta(workbook, sheet, row, col, final_dict):
"""
Traverse all cells in a column moving downward. Primarily created for the metadata sheet, but may use elsewhere.
Check the cell title, and switch it to.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:p... |
def count_chron_variables(temp_sheet):
"""
Count the number of chron variables
:param obj temp_sheet:
:return int: variable count
"""
total_count = 0
start_row = traverse_to_chron_var(temp_sheet)
while temp_sheet.cell_value(start_row, 0) != '':
total_count += 1
start_row ... |
def get_chron_var(temp_sheet, start_row):
"""
Capture all the vars in the chron sheet (for json-ld output)
:param obj temp_sheet:
:param int start_row:
:return: (list of dict) column data
"""
col_dict = OrderedDict()
out_list = []
column = 1
while (temp_sheet.cell_value(start_ro... |
def traverse_to_chron_data(temp_sheet):
"""
Traverse down to the first row that has chron data
:param obj temp_sheet:
:return int: traverse_row
"""
traverse_row = traverse_to_chron_var(temp_sheet)
reference_var = temp_sheet.cell_value(traverse_row, 0)
# Traverse past all the short_names... |
def traverse_to_chron_var(temp_sheet):
"""
Traverse down to the row that has the first variable
:param obj temp_sheet:
:return int:
"""
row = 0
while row < temp_sheet.nrows - 1:
if 'Parameter' in temp_sheet.cell_value(row, 0):
row += 1
break
row += 1
... |
def get_chron_data(temp_sheet, row, total_vars):
"""
Capture all data in for a specific chron data row (for csv output)
:param obj temp_sheet:
:param int row:
:param int total_vars:
:return list: data_row
"""
data_row = []
missing_val_list = ['none', 'na', '', '-']
for i in range... |
def _remove_geo_placeholders(l):
"""
Remove placeholders from coordinate lists and sort
:param list l: Lat or long list
:return list: Modified list
"""
vals = []
for i in l:
if isinstance(i, list):
for k in i:
if isinstance(k, float) or isinstance(k, int):... |
def read_jsonld():
"""
Find jsonld file in the cwd (or within a 2 levels below cwd), and load it in.
:return dict: Jsonld data
"""
_d = {}
try:
# Find a jsonld file in cwd. If none, fallback for a json file. If neither found, return empty.
_filename = [file for file in os.listdi... |
def read_json_from_file(filename):
"""
Import the JSON data from target file.
:param str filename: Target File
:return dict: JSON data
"""
logger_jsons.info("enter read_json_from_file")
d = OrderedDict()
try:
# Load and decode
d = demjson.decode_file(filename, decode_floa... |
def idx_num_to_name(L):
"""
Switch from index-by-number to index-by-name.
:param dict L: Metadata
:return dict L: Metadata
"""
logger_jsons.info("enter idx_num_to_name")
try:
if "paleoData" in L:
L["paleoData"] = _import_data(L["paleoData"], "paleo")
if "chronDa... |
def _import_data(sections, crumbs):
"""
Import the section metadata and change it to index-by-name.
:param list sections: Metadata
:param str pc: paleo or chron
:return dict _sections: Metadata
"""
logger_jsons.info("enter import_data: {}".format(crumbs))
_sections = OrderedDict()
t... |
def _import_model(models, crumbs):
"""
Change the nested items of the paleoModel data. Overwrite the data in-place.
:param list models: Metadata
:param str crumbs: Crumbs
:return dict _models: Metadata
"""
logger_jsons.info("enter import_model".format(crumbs))
_models = OrderedDict()
... |
def _idx_table_by_name(tables, crumbs):
"""
Import summary, ensemble, or distribution data.
:param list tables: Metadata
:return dict _tables: Metadata
"""
_tables = OrderedDict()
try:
for _idx, _table in enumerate(tables):
# Use "name" as tableName
_name = "... |
def _idx_col_by_name(table):
"""
Iter over columns list. Turn indexed-by-num list into an indexed-by-name dict. Keys are the variable names.
:param dict table: Metadata
:return dict _table: Metadata
"""
_columns = OrderedDict()
# Iter for each column in the list
try:
for _colum... |
def get_csv_from_json(d):
"""
Get CSV values when mixed into json data. Pull out the CSV data and put it into a dictionary.
:param dict d: JSON with CSV values
:return dict: CSV values. (i.e. { CSVFilename1: { Column1: [Values], Column2: [Values] }, CSVFilename2: ... }
"""
logger_jsons.info("ent... |
def _get_csv_from_section(d, pc, csv_data):
"""
Get csv from paleo and chron sections
:param dict d: Metadata
:param str pc: Paleo or chron
:return dict: running csv data
"""
logger_jsons.info("enter get_csv_from_section: {}".format(pc))
for table, table_content in d[pc].items():
... |
def remove_csv_from_json(d):
"""
Remove all CSV data 'values' entries from paleoData table in the JSON structure.
:param dict d: JSON data - old structure
:return dict: Metadata dictionary without CSV values
"""
logger_jsons.info("enter remove_csv_from_json")
# Check both sections
if "p... |
def _remove_csv_from_section(d, pc):
"""
Remove CSV from metadata in this section
:param dict d: Metadata
:param str pc: Paleo or chron
:return dict: Modified metadata
"""
logger_jsons.info("enter remove_csv_from_json: {}".format(pc))
for table, table_content in d[pc].items():
f... |
def write_json_to_file(json_data, filename="metadata"):
"""
Write all JSON in python dictionary to a new json file.
:param dict json_data: JSON data
:param str filename: Target filename (defaults to 'metadata.jsonld')
:return None:
"""
logger_jsons.info("enter write_json_to_file")
json_d... |
def idx_name_to_num(L):
"""
Switch from index-by-name to index-by-number.
:param dict L: Metadata
:return dict: Modified metadata
"""
logger_jsons.info("enter idx_name_to_num")
# Process the paleoData section
if "paleoData" in L:
L["paleoData"] = _export_section(L["paleoData"], ... |
def _export_section(sections, pc):
"""
Switch chron data to index-by-number
:param dict sections: Metadata
:return list _sections: Metadata
"""
logger_jsons.info("enter export_data: {}".format(pc))
_sections = []
for name, section in sections.items():
# Process chron models
... |
def _export_model(models):
"""
Switch model tables to index-by-number
:param dict models: Metadata
:return dict _models: Metadata
"""
logger_jsons.info("enter export_model")
_models = []
try:
for name, model in models.items():
if "summaryTable" in model:
... |
def _idx_table_by_num(tables):
"""
Switch tables to index-by-number
:param dict tables: Metadata
:return list _tables: Metadata
"""
logger_jsons.info("enter idx_table_by_num")
_tables = []
for name, table in tables.items():
try:
# Get the modified table data
... |
def _idx_col_by_num(table):
"""
Index columns by number instead of by name. Use "number" key in column to maintain order
:param dict table: Metadata
:return list _table: Metadata
"""
_columns = []
try:
# Create an empty list that matches the length of the column dictionary
_... |
def make_bag(bag_dir, bag_info=None, processes=1, checksum=None):
"""
Convert a given directory into a bag. You can pass in arbitrary
key/value pairs to put into the bag-info.txt metadata file as
the bag_info dictionary.
"""
bag_dir = os.path.abspath(bag_dir)
logger.info("creating bag for di... |
def _calculate_file_hashes(full_path, f_hashers):
"""
Returns a dictionary of (algorithm, hexdigest) values for the provided
filename
"""
if not os.path.exists(full_path):
raise BagValidationError("%s does not exist" % full_path)
try:
with open(full_path, 'rb') as f:
... |
def _parse_tags(tag_file):
"""Parses a tag file, according to RFC 2822. This
includes line folding, permitting extra-long
field values.
See http://www.faqs.org/rfcs/rfc2822.html for
more information.
"""
tag_name = None
tag_value = None
# Line folding is handled by yi... |
def _can_bag(test_dir):
"""returns (unwriteable files/folders)
"""
unwriteable = []
for inode in os.listdir(test_dir):
if not os.access(os.path.join(test_dir, inode), os.W_OK):
unwriteable.append(os.path.join(os.path.abspath(test_dir), inode))
return tuple(unwriteable) |
def _can_read(test_dir):
"""
returns ((unreadable_dirs), (unreadable_files))
"""
unreadable_dirs = []
unreadable_files = []
for dirpath, dirnames, filenames in os.walk(test_dir):
for dn in dirnames:
if not os.access(os.path.join(dirpath, dn), os.R_OK):
unreada... |
def compare_fetch_with_fs(self):
"""Compares the fetch entries with the files actually
in the payload, and returns a list of all the files
that still need to be fetched.
"""
files_on_fs = set(self.payload_files())
files_in_fetch = set(self.files_to_be_fetched())
... |
def save(self, processes=1, manifests=False):
"""
save will persist any changes that have been made to the bag
metadata (self.info).
If you have modified the payload of the bag (added, modified,
removed files in the data directory) and want to regenerate manifests
set th... |
def missing_optional_tagfiles(self):
"""
From v0.97 we need to validate any tagfiles listed
in the optional tagmanifest(s). As there is no mandatory
directory structure for additional tagfiles we can
only check for entries with missing files (not missing
entries for exist... |
def validate(self, processes=1, fast=False):
"""Checks the structure and contents are valid. If you supply
the parameter fast=True the Payload-Oxum (if present) will
be used to check that the payload files are present and
accounted for, instead of re-calculating fixities and
comp... |
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 |
def _validate_entries(self, processes):
"""
Verify that the actual file contents match the recorded hashes stored in the manifest files
"""
errors = list()
# First we'll make sure there's no mismatch between the filesystem
# and the list of files in the manifest(s)
... |
def _validate_bagittxt(self):
"""
Verify that bagit.txt conforms to specification
"""
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):
... |
def _fix_numeric_types(c):
"""
Fix any numpy data types that didn't map back to python data types properly
:param dict c: Columns of data
:return dict c: Columns of data
"""
try:
for var, data in c.items():
for k, v in data.items():
if k in ["hasMeanValue", "h... |
def _get_age(columns):
"""
Sift through table column data and find the "age" or "year" column. Return its "values" data.
:param dict columns: Column data
:return list age: Age values
"""
# Need to check multiple places for age, year, or yrbp
# 1. Check the column variable name
# 2. Chec... |
def _get_resolution(age, values):
"""
Calculates the resolution (res)
Thanks Deborah!
"""
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 ... |
def __get_inferred_data_res_2(v=None, calc=True):
"""
Use a list of values to calculate m/m/m/m. Resolution values or otherwise.
:param numpy array v: Values
:param bool calc: If false, we don't need calculations
:return dict: Results of calculation
"""
# Base: If something goes wrong, or i... |
def _get_inferred_data_res(column, age):
"""
Calculate Resolution and m/m/m/m for column values.
:param dict column: Column data
:param list age: Age values
:return dict column: Column data - modified
"""
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore"... |
def _get_inferred_data_column(column):
"""
Calculate the m/m/m/m for column values.
:param dict column: Column data
:return dict column: Column data - modified
"""
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Get the values for this colum... |
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... |
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... |
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
"""
... |
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:
... |
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 ... |
def _analyze_func_string(func_string):
"""
Analyze given functiion string an extract:
* function name
* function arguments
* function keyword arguments
All given arguments must by of type string, int/float or list.
:param func_string: string of the function
:return: function name, arg... |
def run():
"""
Initialize and start objects. This is called automatically when importing the package.
:return none:
"""
# GLOBALS
global cwd, files, logger_start, logger_benchmark, settings, _timeseries_data
_timeseries_data = {}
# files = {".lpd": [ {"full_path", "filename_ext", "filen... |
def readLipd(usr_path=""):
"""
Read LiPD file(s).
Enter a file path, directory path, or leave args blank to trigger gui.
:param str usr_path: Path to file / directory (optional)
:return dict _d: Metadata
"""
global cwd, settings, files
if settings["verbose"]:
__disclaimer(opt="u... |
def readExcel(usr_path=""):
"""
Read Excel file(s)
Enter a file path, directory path, or leave args blank to trigger gui.
:param str usr_path: Path to file / directory (optional)
:return str cwd: Current working directory
"""
global cwd, files
start = clock()
files[".xls"] = []
... |
def excel():
"""
Convert Excel files to LiPD files. LiPD data is returned directly from this function.
| Example
| 1: lipd.readExcel()
| 2: D = lipd.excel()
:return dict _d: Metadata
"""
global files, cwd, settings
_d = {}
# Turn off verbose. We don't want to clutter the consol... |
def noaa(D="", path="", wds_url="", lpd_url="", version=""):
"""
Convert between NOAA and LiPD files
| Example: LiPD to NOAA converter
| 1: L = lipd.readLipd()
| 2: lipd.noaa(L, "/Users/someuser/Desktop", "https://www1.ncdc.noaa.gov/pub/data/paleo/pages2k/NAm2kHydro-2017/noaa-templates/data-version... |
def validate(D, detailed=True):
"""
Use the Validator API for lipd.net to validate all LiPD files in the LiPD Library.
Display the PASS/FAIL results. Display detailed results if the option is chosen.
:param dict D: Metadata (single or multiple datasets)
:param bool detailed: Show or hide the detail... |
def tsToDf(tso):
"""
Create Pandas DataFrame from TimeSeries object.
Use: Must first extractTs to get a time series. Then pick one item from time series and pass it through
:param dict tso: Time series entry
:return dict dfs: Pandas dataframes
"""
dfs = {}
try:
dfs = ts_to_df(ts... |
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()
| ... |
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}... |
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... |
def queryTs(ts, expression):
"""
Find the indices of the time series entries that match the given expression.
| Example:
| D = lipd.loadLipd()
| ts = lipd.extractTs(D)
| matches = queryTs(ts, "archiveType == marine sediment")
| matches = queryTs(ts, "geo_meanElev <= 2000")
:param str e... |
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 =... |
def showLipds(D=None):
"""
Display the dataset names of a given LiPD data
| Example
| lipd.showLipds(D)
:pararm dict D: LiPD data
:return none:
"""
if not D:
print("Error: LiPD data not provided. Pass LiPD data into the function.")
else:
print(json.dumps(D.keys(), ... |
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 |
def showDfs(d):
"""
Display the available data frame names in a given data frame collection
:param dict d: Dataframe collection
:return none:
"""
if "metadata" in d:
print("metadata")
if "paleoData" in d:
try:
for k, v in d["paleoData"].items():
p... |
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:
... |
def getMetadata(L):
"""
Get metadata from a LiPD data in memory
| Example
| m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict L: One LiPD record
:return dict d: LiPD record (metadata only)
"""
_l = {}
try:
# Create a copy. Do not affect the original d... |
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... |
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))... |
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... |
def __read(usr_path, file_type):
"""
Determine what path needs to be taken to read in file(s)
:param str usr_path: Path (optional)
:param str file_type: File type to read
:return none:
"""
# is there a file path specified ?
if usr_path:
# Is this a URL? Download the file and re... |
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["... |
def __read_file(usr_path, file_type):
"""
Universal read file. Given a path and a type, it will do the appropriate read actions
:param str usr_path: Path to file
:param str file_type: One of approved file types: xls, xlsx, txt, lpd
:return none:
"""
global files
# no path provided. sta... |
def __read_directory(usr_path, file_type):
"""
Universal read directory. Given a path and a type, it will do the appropriate read actions
:param str usr_path: Path to directory
:param str file_type: .xls, .xlsx, .txt, .lpd
:return none:
"""
# no path provided. start gui browse
if not us... |
def __write_lipd(dat, usr_path):
"""
Write LiPD data to file, provided an output directory and dataset name.
:param dict dat: Metadata
:param str usr_path: Destination path
:param str dsn: Dataset name of one specific file to write
:return none:
"""
global settings
# no path provide... |
def __disclaimer(opt=""):
"""
Print the disclaimers once. If they've already been shown, skip over.
:return none:
"""
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 o... |
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... |
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... |
def get_shreds(self, feature_extractors, sheet_name):
"""Detects shreds in the current sheet and constructs Shred instances.
Caches the results for further invocations.
Args:
feature_extractors: iterable of AbstractShredFeature instances to
use for shreds feature as... |
def _make_shred(self, c, name, feature_extractors, sheet_name):
"""Creates a Shred instances from a given contour.
Args:
c: cv2 contour object.
name: string shred name within a sheet.
feature_extractors: iterable of AbstractShredFeature instances.
Returns:
... |
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.
... |
def run_track(track,
result_hosts=None,
crate_root=None,
output_fmt=None,
logfile_info=None,
logfile_result=None,
failfast=False,
sample_mode='reservoir'):
"""Execute a track file"""
with Logger(output_fmt=output_f... |
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... |
def __parse(self):
"""
Parse
Accept the text file. We'll open it, read it, and return a compiled dictionary to write to a json file
May write a chronology CSV and a data CSV if those sections are available
:return:
"""
logger_noaa_lpd.info("enter parse")
... |
def __create_paleo_col(l, col_count):
"""
Receive split list from separate_data_vars, and turn it into a dictionary for that column
:param list l:
:param int col_count:
:return dict:
"""
# Format: what, material, error, units, seasonality, archive, detail, method,... |
def __separate_data_vars(line):
"""
For the variables section, clean up the line and return a list of each of the 10 items
:param str line:
:return str:
"""
combine = []
if '#' in line:
line = line.replace("#", "")
line = line.lstrip()
... |
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... |
def __camel_case(word):
"""
Convert underscore naming into camel case naming
:param str word:
:return str:
"""
word = word.lower()
if '_' in word:
split_word = word.split('_')
else:
split_word = word.split()
if len(split_wor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.