text stringlengths 81 112k |
|---|
Parses a GIT URL and returns an object. Raises an exception on invalid
URL.
:returns: Parsed object
:raise: :class:`.ParserError`
def parse(self):
"""
Parses a GIT URL and returns an object. Raises an exception on invalid
URL.
:returns: Parsed object
... |
Make a request against AirVisual.
async def _request(
self,
method: str,
url: str,
*,
headers: dict = None,
params: dict = None,
json: dict = None) -> dict:
"""Make a request against AirVisual."""
full_url = '{0}/{1}'.f... |
Add a handler for each of the available HTTP error responses.
def setup_errors(app, error_template="error.html"):
"""Add a handler for each of the available HTTP error responses."""
def error_handler(error):
if isinstance(error, HTTPException):
description = error.get_description(request.en... |
Return all the email addresses found for a given domain.
:param domain: The domain on which to search for emails. Must be
defined if company is not.
:param company: The name of the company on which to search for emails.
Must be defined if domain is not.
:param limit: The maxim... |
Find the email address of a person given its name and company's domain.
:param domain: The domain of the company where the person works. Must
be defined if company is not.
:param company: The name of the company where the person works. Must
be defined if domain is not.
:param ... |
Verify the deliverability of a given email adress.abs
:param email: The email adress to check.
:param raw: Gives back the entire response instead of just the 'data'.
:return: Full payload of the query as a dict.
def email_verifier(self, email, raw=False):
"""
Verify the deliv... |
Give back the number of email adresses Hunter has for this domain/company.
:param domain: The domain of the company where the person works. Must
be defined if company is not. If both 'domain' and 'company' are given,
the 'domain' will be used.
:param company: The name of the company wh... |
Gives the information about the account associated with the api_key.
:param raw: Gives back the entire response instead of just the 'data'.
:return: Full payload of the query as a dict.
def account_information(self, raw=False):
"""
Gives the information about the account associated wi... |
Gives back all the leads saved in your account.
:param offset: Number of leads to skip.
:param limit: Maximum number of leads to return.
:param lead_list_id: Id of a lead list to query leads on.
:param first_name: First name to filter on.
:param last_name: Last name to filte... |
Get a specific lead saved on your account.
:param lead_id: Id of the lead to search. Must be defined.
:return: Lead found as a dict.
def get_lead(self, lead_id):
"""
Get a specific lead saved on your account.
:param lead_id: Id of the lead to search. Must be defined.
... |
Create a lead on your account.
:param first_name: The first name of the lead to create. Must be
defined.
:param last_name: The last name of the lead to create. Must be defined.
:param email: The email of the lead to create.
:param position: The professional position of the le... |
Gives back all the leads lists saved on your account.
:param offset: Number of lists to skip.
:param limit: Maximum number of lists to return.
:return: Leads lists found as a dict.
def get_leads_lists(self, offset=None, limit=None):
"""
Gives back all the leads lists saved on... |
Create a leads list.
:param name: Name of the list to create. Must be defined.
:param team_id: The id of the list to share this list with.
:return: The created leads list as a dict.
def create_leads_list(self, name, team_id=None):
"""
Create a leads list.
:param name... |
Update a leads list.
:param name: Name of the list to update. Must be defined.
:param team_id: The id of the list to share this list with.
:return: 204 Response.
def update_leads_list(self, leads_list_id, name, team_id=None):
"""
Update a leads list.
:param name: Nam... |
Delete a leads list.
:param leads_list_id: The id of the list to delete.
:return: 204 Response.
def delete_leads_list(self, leads_list_id):
"""
Delete a leads list.
:param leads_list_id: The id of the list to delete.
:return: 204 Response.
"""
params ... |
converts a string to an integer
>>> to_int('1_000_000')
1000000
>>> to_int('1e6')
1000000
>>> to_int('1000')
1000
def to_int(s):
""" converts a string to an integer
>>> to_int('1_000_000')
1000000
>>> to_int('1e6')
1000000
>>> to_int('1000')
1000
"""
tr... |
returns a generator producing dicts from json lines
1 JSON object per line is supported:
{"name": "n1"}
{"name": "n2"}
Or 1 JSON object:
{
"name": "n1"
}
Or a list of JSON objects:
[
{"name": "n1"},
{"name": "n2"},
]
... |
Compose any number of unary functions into a single unary function.
>>> import textwrap
>>> from six import text_type
>>> stripped = text_type.strip(textwrap.dedent(compose.__doc__))
>>> compose(text_type.strip, textwrap.dedent)(compose.__doc__) == stripped
True
Compose also allows the innermost function to tak... |
Return a function that will call a named method on the
target object with optional positional and keyword
arguments.
>>> lower = method_caller('lower')
>>> lower('MyString')
'mystring'
def method_caller(method_name, *args, **kwargs):
"""
Return a function that will call a named method on the
target object wit... |
Decorate func so it's only ever called the first time.
This decorator can ensure that an expensive or non-idempotent function
will not be expensive on subsequent calls and is idempotent.
>>> add_three = once(lambda a: a+3)
>>> add_three(3)
6
>>> add_three(9)
6
>>> add_three('12')
6
To reset the stored valu... |
Wrap lru_cache to support storing the cache data in the object instances.
Abstracts the common paradigm where the method explicitly saves an
underscore-prefixed protected property on first call and returns that
subsequently.
>>> class MyClass:
... calls = 0
...
... @method_cache
... def method(sel... |
Because Python treats special methods differently, it's not
possible to use instance attributes to implement the cached
methods.
Instead, install the wrapper method under a different name
and return a simple proxy to that wrapper.
https://github.com/jaraco/jaraco.functools/issues/5
def _special_method_cache(met... |
r"""
Decorate a function with an action function that is
invoked on the results returned from the decorated
function (for its side-effect), then return the original
result.
>>> @result_invoke(print)
... def add_two(a, b):
... return a + b
>>> x = add_two(2, 3)
5
def result_invoke(action):
r"""
Decorate... |
Return a function that when invoked will invoke func1 without
any parameters (for its side-effect) and then invoke func2
with whatever parameters were passed, returning its result.
def first_invoke(func1, func2):
"""
Return a function that when invoked will invoke func1 without
any parameters (for its side-effect... |
Given a callable func, trap the indicated exceptions
for up to 'retries' times, invoking cleanup on the
exception. On the final attempt, allow any exceptions
to propagate.
def retry_call(func, cleanup=lambda: None, retries=0, trap=()):
"""
Given a callable func, trap the indicated exceptions
for up to 'retries' ... |
Decorator wrapper for retry_call. Accepts arguments to retry_call
except func and then returns a decorator for the decorated function.
Ex:
>>> @retry(retries=3)
... def my_func(a, b):
... "this is my funk"
... print(a, b)
>>> my_func.__doc__
'this is my funk'
def retry(*r_args, **r_kwargs):
"""
Dec... |
Convert a generator into a function that prints all yielded elements
>>> @print_yielded
... def x():
... yield 3; yield None
>>> x()
3
None
def print_yielded(func):
"""
Convert a generator into a function that prints all yielded elements
>>> @print_yielded
... def x():
... yield 3; yield None
>>>... |
Wrap func so it's not called if its first param is None
>>> print_text = pass_none(print)
>>> print_text('text')
text
>>> print_text(None)
def pass_none(func):
"""
Wrap func so it's not called if its first param is None
>>> print_text = pass_none(print)
>>> print_text('text')
text
>>> print_text(None)
"""... |
Assign parameters from namespace where func solicits.
>>> def func(x, y=3):
... print(x, y)
>>> assigned = assign_params(func, dict(x=2, z=4))
>>> assigned()
2 3
The usual errors are raised if a function doesn't receive
its required parameters:
>>> assigned = assign_params(func, dict(y=3, z=4))
>>> assi... |
Wrap a method such that when it is called, the args and kwargs are
saved on the method.
>>> class MyClass:
... @save_method_args
... def method(self, a, b):
... print(a, b)
>>> my_ob = MyClass()
>>> my_ob.method(1, 2)
1 2
>>> my_ob._saved_method.args
(1, 2)
>>> my_ob._saved_method.kwargs
{}... |
ensure at least 1/max_rate seconds from last call
def _wait(self):
"ensure at least 1/max_rate seconds from last call"
elapsed = time.time() - self.last_called
must_wait = 1 / self.max_rate - elapsed
time.sleep(max(0, must_wait))
self.last_called = time.time() |
Creates and returns a column.
:param app: current sphinx app
:param fromdocname: current document
:param all_needs: Dictionary of all need objects
:param need_info: need_info object, which stores all related need data
:param need_key: The key to access the needed data from need_info
:param make... |
Upload a file into a blob table
def insert_blob(filename, hosts=None, table=None):
"""Upload a file into a blob table """
conn = connect(hosts)
container = conn.get_blob_container(table)
with open(filename, 'rb') as f:
digest = container.put(f)
return '{server}/_blobs/{table}/{digest}'.form... |
Get DOI publication info for a batch of DOIs. This is LiPD-independent and only requires a CSV file with all DOIs
listed in a single column. The output is LiPD-formatted publication data for each entry.
:param str csv_source: Local path to CSV file
:param bool write_file: Write output data to JSON file (Tr... |
Write all JSON in python dictionary to a new json file.
:param any json_data: JSON data
:param str filename: Target filename (defaults to 'metadata.jsonld')
:return None:
def write_json_to_file(json_data, filename="metadata"):
"""
Write all JSON in python dictionary to a new json file.
:param a... |
Compiles authors "Last, First" into a single list
:param list authors: Raw author data retrieved from doi.org
:return list: Author objects
def compile_authors(authors):
"""
Compiles authors "Last, First" into a single list
:param list authors: Raw author data retrieved from doi.org
:return list... |
Loop over Raw and add selected items to Fetch with proper formatting
:param dict raw: JSON data from doi.org
:param str doi_id:
:return dict:
def compile_fetch(raw, doi_id):
"""
Loop over Raw and add selected items to Fetch with proper formatting
:param dict raw: JSON data from doi.org
:par... |
Resolve DOI and compile all attributes into one dictionary
:param str doi_id:
:param int idx: Publication index
:return dict: Updated publication dictionary
def get_data(doi_id):
"""
Resolve DOI and compile all attributes into one dictionary
:param str doi_id:
:param int idx: Publication in... |
Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215)
:param str doi_string: Raw DOI string value from input file. Often not properly formatted.
:return list: DOI ids. May contain 0, 1, or multiple ids.
def clean_doi(doi_string):
"""
Use regex to extract all DOI ids from string (i.e... |
Log a given function and how long the function takes in seconds
:param str fn: Function name
:param float start: Function start time
:param float end: Function end time
:return none:
def log_benchmark(fn, start, end):
"""
Log a given function and how long the function takes in seconds
:para... |
Create or update the changelog txt file. Prompt for update description.
:return None:
def update_changelog():
"""
Create or update the changelog txt file. Prompt for update description.
:return None:
"""
# description = input("Please enter a short description for this update:\n ")
descripti... |
Creates a logger for function benchmark times
:param str name: Name of the logger
:param str log_file: Filename
:return obj: Logger
def create_benchmark(name, log_file, level=logging.INFO):
"""
Creates a logger for function benchmark times
:param str name: Name of the logger
:param str log_... |
Creates a logger with the below attributes.
:param str name: Name of the logger
:return obj: Logger
def create_logger(name):
"""
Creates a logger with the below attributes.
:param str name: Name of the logger
:return obj: Logger
"""
logging.config.dictConfig({
'version': 1,
... |
Run the given statement a number of times and return the runtime stats
Args:
fail-if: An expression that causes cr8 to exit with a failure if it
evaluates to true.
The expression can contain formatting expressions for:
- runtime_stats
- statement
... |
Determine the OS and the associated download folder.
:return str Download path:
def get_download_path():
"""
Determine the OS and the associated download folder.
:return str Download path:
"""
if os.name == 'nt':
import winreg
sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersio... |
Use the given URL and destination to download and save a file
:param str src_url: Direct URL to lipd file download
:param str dst_path: Local path to download file to, including filename and ext. ex. /path/to/filename.lpd
:return none:
def download_file(src_url, dst_path):
"""
Use the given URL and... |
Wait until predicate returns a truthy value or the timeout is reached.
>>> wait_until(lambda: True, timeout=10)
def wait_until(predicate, timeout=30):
"""Wait until predicate returns a truthy value or the timeout is reached.
>>> wait_until(lambda: True, timeout=10)
"""
not_expired = Timeout(timeo... |
Return the first matching version
>>> _find_matching_version(['1.1.4', '1.0.12', '1.0.5'], '1.0.x')
'1.0.12'
>>> _find_matching_version(['1.1.4', '1.0.6', '1.0.5'], '2.x.x')
def _find_matching_version(versions, version_pattern):
"""
Return the first matching version
>>> _find_matching_versio... |
Build a tarball from src and return the path to it
def _build_tarball(src_repo) -> str:
""" Build a tarball from src and return the path to it """
run = partial(subprocess.run, cwd=src_repo, check=True)
run(['git', 'clean', '-xdff'])
src_repo = Path(src_repo)
if os.path.exists(src_repo / 'es' / 'up... |
Return the path to the crates cache folder
def _crates_cache() -> str:
""" Return the path to the crates cache folder """
return os.environ.get(
'XDG_CACHE_HOME',
os.path.join(os.path.expanduser('~'), '.cache', 'cr8', 'crates')) |
Retrieve a Crate tarball, extract it and return the path.
Args:
version: The Crate version to get.
Can be specified in different ways:
- A concrete version like '0.55.0'
- A version including a `x` as wildcards. Like: '1.1.x' or '1.x.x'.
This will use the ... |
Parse repeatable CLI options
>>> opts = _parse_options(['cluster.name=foo', 'CRATE_JAVA_OPTS="-Dxy=foo"'])
>>> print(json.dumps(opts, sort_keys=True))
{"CRATE_JAVA_OPTS": "\\"-Dxy=foo\\"", "cluster.name": "foo"}
def _parse_options(options: List[str]) -> Dict[str, str]:
""" Parse repeatable CLI options... |
Launch a crate instance.
Supported version specifications:
- Concrete version like "0.55.0" or with wildcard: "1.1.x"
- An alias (one of [latest-nightly, latest-stable, latest-testing])
- A URI pointing to a CrateDB tarball (in .tar.gz format)
- A URI pointing to a checked out Crate... |
Start the process.
This will block until the Crate cluster is ready to process requests.
def start(self):
"""Start the process.
This will block until the Crate cluster is ready to process requests.
"""
log.info('Starting Crate process')
self.process = proc = self.enter... |
Parse protocol and bound address from log message
>>> AddrConsumer._parse('NONE')
(None, None)
>>> AddrConsumer._parse('[INFO ][i.c.p.h.CrateNettyHttpServerTransport] [Widderstein] publish_address {127.0.0.1:4200}, bound_addresses {[fe80::1]:4200}, {[::1]:4200}, {127.0.0.1:4200}')
('ht... |
Adaptively determines image background.
Args:
image: image converted 1-channel image.
mask: 1-channel mask, same size as image.
blocksize: adaptive algorithm parameter.
Returns:
image of same size as input with foreground inpainted with background.
def _calc_block_mean_varianc... |
Applies adaptive thresholding to the given image.
Args:
image: BGRA image.
block_size: optional int block_size to use for adaptive thresholding.
mask: optional mask.
Returns:
Thresholded image.
def threshold(image, block_size=DEFAULT_BLOCKSIZE, mask=None):
"""Applies adapti... |
Find an appropriate version number from version control.
It's much more convenient to be able to use your version control system's
tagging mechanism to derive a version number than to have to duplicate that
information all over the place.
The default behavior is to write out a ``version.txt`` file whi... |
A hook for simplifying ``vcversioner`` use from distutils.
This hook, when installed properly, allows vcversioner to automatically run
when specifying a ``vcversioner`` argument to ``setup``. For example::
from setuptools import setup
setup(
setup_requires=['vcversioner'],
vcv... |
Generate an insert statement using the given table and dictionary.
Args:
table (str): table name
d (dict): dictionary with column names as keys and values as values.
Returns:
tuple of statement and arguments
>>> to_insert('doc.foobar', {'name': 'Marvin'})
('insert into doc.foob... |
Insert JSON lines fed into stdin into a Crate cluster.
If no hosts are specified the statements will be printed.
Args:
table: Target table name.
bulk_size: Bulk size of the insert statements.
concurrency: Number of operations to run concurrently.
hosts: hostname:port pairs of t... |
Picks dominant angle of a set of lines.
Args:
lines: iterable of (x1, y1, x2, y2) tuples that define lines.
domination_type: either MEDIAN or MEAN.
Returns:
Dominant angle value in radians.
Raises:
ValueError: on unknown domination_type.
def _get_dominant_angle(lines, dom... |
Finds an angle that matches the given one modulo step.
Increments and decrements the given value with a given step.
Args:
range: a 2-tuple of min and max target values.
step: tuning step.
Returns:
Normalized value within a given range.
def _normalize_angle(angle, range, step):
... |
Returns a dict of collectors.
Args:
limit (int): number of collectors to return
offset (int): the offset of where the list of collectors should begin from
def get_collectors(self, limit=1000, offset=0):
"""Returns a dict of collectors.
Args:
limit (int): nu... |
Returns a dict of collector's details if found.
Args:
name (str): name of collector searching for
def find(self, name):
"""Returns a dict of collector's details if found.
Args:
name (str): name of collector searching for
"""
collectors = self.get_collec... |
Delete a collector from inventory.
Args:
collector_id (int): id of collector (optional)
def delete(self, collector_id=None):
"""Delete a collector from inventory.
Args:
collector_id (int): id of collector (optional)
"""
cid = self.collector_id
... |
Return a dict of collector.
Args:
collector_id (int): id of collector (optional)
def info(self, collector_id):
"""Return a dict of collector.
Args:
collector_id (int): id of collector (optional)
"""
cid = self.collector_id
if collector_id:
... |
Flattens nested data structures using dot notation.
:param dict d: Original or nested dictionary
:param str key:
:param dict dots: Dotted dictionary so far
:return dict: Dotted dictionary so far
def _dotnotation_for_nested_dictionary(d, key, dots):
"""
Flattens nested data structures using dot ... |
Create a data frame from given nested lists of ensemble data
:param list ensemble: Ensemble data
:return obj: Dataframe
def create_dataframe(ensemble):
"""
Create a data frame from given nested lists of ensemble data
:param list ensemble: Ensemble data
:return obj: Dataframe
"""
logger_... |
Create an organized collection of data frames from LiPD data
:param dict metadata: LiPD data
:param dict csvs: Csv data
:return dict: One data frame per table, organized in a dictionary by name
def lipd_to_df(metadata, csvs):
"""
Create an organized collection of data frames from LiPD data
:par... |
Create a data frame from one TimeSeries object
:param dict metadata: Time Series dictionary
:return dict: One data frame per table, organized in a dictionary by name
def ts_to_df(metadata):
"""
Create a data frame from one TimeSeries object
:param dict metadata: Time Series dictionary
:return d... |
Get variable + values vs year, age, depth (whichever are available)
:param dict ts: TimeSeries dictionary
:return dict: Key: variableName, Value: Panda Series object
def _plot_ts_cols(ts):
"""
Get variable + values vs year, age, depth (whichever are available)
:param dict ts: TimeSeries dictionary
... |
LiPD Version 1.2
Create a data frame for each table for the given key
:param dict csvs: LiPD metadata dictionary
:return dict: paleo data data frames
def _get_dfs(csvs):
"""
LiPD Version 1.2
Create a data frame for each table for the given key
:param dict csvs: LiPD metadata dictionary
... |
Generic function to grab dictionary data by key with error handling
:return:
def _get_key_data(d, key):
"""
Generic function to grab dictionary data by key with error handling
:return:
"""
d2 = ""
try:
d2 = d[key]
except KeyError:
logger_dataframes.info("get_key_data: Ke... |
Main: Get all data frames that match the given expression
:return dict: Filenames and data frames (filtered)
def get_filtered_dfs(lib, expr):
"""
Main: Get all data frames that match the given expression
:return dict: Filenames and data frames (filtered)
"""
logger_dataframes.info("enter get_fi... |
Use the given expression to get all data frames that match the criteria (i.e. "paleo measurement tables")
:param dict lo_meta: Lipd object metadata
:param str expr: Search expression
:param str tt: Table type (chron or paleo)
:return list: All filenames that match the expression
def _match_dfs_expr(lo_... |
Match a list of filenames to their data frame counterparts. Return data frames
:param list filenames: Filenames of data frames to retrieve
:param dict lo_dfs: All data frames
:return dict: Filenames and data frames (filtered)
def _match_filenames_w_dfs(filenames, lo_dfs):
"""
Match a list of filena... |
Split the expression and look to see if there's a specific filename that the user wants to process.
:param str expr: Search expression
:return str: Filename or None
def _check_expr_filename(expr):
"""
Split the expression and look to see if there's a specific filename that the user wants to process.
... |
Loads a LiPD file from local path. Unzip, read, and process data
Steps: create tmp, unzip lipd, read files into memory, manipulate data, move to original dir, delete tmp.
:param str path: Source path
:return none:
def lipd_read(path):
"""
Loads a LiPD file from local path. Unzip, read, and process... |
Saves current state of LiPD object data. Outputs to a LiPD file.
Steps: create tmp, create bag dir, get dsn, splice csv from json, write csv, clean json, write json, create bagit,
zip up bag folder, place lipd in target dst, move to original dir, delete tmp
:param dict _json: Metadata
:param str pa... |
Generate bulk_size until num_records is reached or active becomes false
>>> gen = _bulk_size_generator(155, 50, [True])
>>> list(gen)
[50, 50, 50, 5]
def _bulk_size_generator(num_records, bulk_size, active):
""" Generate bulk_size until num_records is reached or active becomes false
>>> gen = _bu... |
Generate random data and insert it into a table.
This will read the table schema and then find suitable random data providers.
Which provider is choosen depends on the column name and data type.
Example:
A column named `name` will map to the `name` provider.
A column named `x` of type int... |
Main function that gets file(s), creates outputs, and runs all operations.
:return dict: Updated or original data for jsonld file
def main(self):
"""
Main function that gets file(s), creates outputs, and runs all operations.
:return dict: Updated or original data for jsonld file
... |
Take in our Original Pub, and Fetched Pub. For each Fetched entry that has data, overwrite the Original entry
:param pub_dict: (dict) Original pub dictionary
:param fetch_dict: (dict) Fetched pub dictionary from doi.org
:return: (dict) Updated pub dictionary, with fetched data taking precedence
... |
Special instructions for moving noaa data to the correct fields
:param doi_string: (str) NOAA url
:return: None
def noaa_citation(self, doi_string):
"""
Special instructions for moving noaa data to the correct fields
:param doi_string: (str) NOAA url
:return: None
... |
DOI string did not match the regex. Determine what the data is.
:param doi_string: (str) Malformed DOI string
:return: None
def illegal_doi(self, doi_string):
"""
DOI string did not match the regex. Determine what the data is.
:param doi_string: (str) Malformed DOI string
... |
Loop over Raw and add selected items to Fetch with proper formatting
:param dict raw: JSON data from doi.org
:param str doi_id:
:return dict:
def compile_fetch(self, raw, doi_id):
"""
Loop over Raw and add selected items to Fetch with proper formatting
:param dict raw: J... |
Resolve DOI and compile all attributes into one dictionary
:param str doi_id:
:param int idx: Publication index
:return dict: Updated publication dictionary
def get_data(self, doi_id, idx):
"""
Resolve DOI and compile all attributes into one dictionary
:param str doi_id:... |
Recursively search the file for the DOI id. More taxing, but more flexible when dictionary structuring isn't absolute
:param dict curr_dict: Current dictionary being searched
:return dict bool: Recursive - Current dictionary, False flag that DOI was not found
:return str bool: Final - DOI id, Tr... |
Attempt to cast string to float. If error, keep as a string.
:param dict d: Data
:param int idx: Index number
:param str x: Data
:return any:
def cast_values_csvs(d, idx, x):
"""
Attempt to cast string to float. If error, keep as a string.
:param dict d: Data
:param int idx: Index num... |
Attempt to cleanup string or convert to number value.
:param any x:
:return float:
def cast_float(x):
"""
Attempt to cleanup string or convert to number value.
:param any x:
:return float:
"""
try:
x = float(x)
except ValueError:
try:
x = x.strip()
... |
Cast unknown type into integer
:param any x:
:return int:
def cast_int(x):
"""
Cast unknown type into integer
:param any x:
:return int:
"""
try:
x = int(x)
except ValueError:
try:
x = x.strip()
except AttributeError as e:
logger_mis... |
Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215)
:param str doi_string: Raw DOI string value from input file. Often not properly formatted.
:return list: DOI ids. May contain 0, 1, or multiple ids.
def clean_doi(doi_string):
"""
Use regex to extract all DOI ids from string (i.e... |
Change the "precision" of values before writing to CSV. Each value is rounded to 3 numbers.
ex: 300 -> 300
ex: 300.123456 -> 300.123
ex: 3.123456e-25 - > 3.123e-25
:param tuple row: Row of numbers to process
:return list row: Processed row
def decimal_precision(row):
"""
Change the "preci... |
Coordinate decimal degrees calculated by an excel formula are often too long as a repeating decimal.
Round them down to 5 decimals
:param dict d: Metadata
:return dict d: Metadata
def fix_coordinate_decimal(d):
"""
Coordinate decimal degrees calculated by an excel formula are often too long as a r... |
Generate a timestamp to mark when this file was last modified.
:param str fmt: Special format instructions
:return str: YYYY-MM-DD format, or specified format
def generate_timestamp(fmt=None):
"""
Generate a timestamp to mark when this file was last modified.
:param str fmt: Special format instru... |
Generate a TSid string. Use the "PYT" prefix for traceability, and 8 trailing generated characters
ex: PYT9AG234GS
:return str: TSid
def generate_tsid(size=8):
"""
Generate a TSid string. Use the "PYT" prefix for traceability, and 8 trailing generated characters
ex: PYT9AG234GS
:return str: T... |
Append numbers to a name until it no longer conflicts with the other names in a column.
Necessary to avoid overwriting columns and losing data. Loop a preset amount of times to avoid an infinite loop.
There shouldn't ever be more than two or three identical variable names in a table.
:param str name: Varia... |
Take author or investigator data, and convert it to a concatenated string of names.
Author data structure has a few variations, so account for all.
:param any x: Author data
:return str: Author string
def get_authors_as_str(x):
"""
Take author or investigator data, and convert it to a concatenated... |
Get the dataset name from a record
:param dict d: Metadata
:return str: Dataset name
def get_dsn(d):
"""
Get the dataset name from a record
:param dict d: Metadata
:return str: Dataset name
"""
try:
return d["dataSetName"]
except Exception as e:
logger_misc.warn("... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.