INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Save the tabarray to a single flat separated variable ( CSV ) text file. Method wraps:: | def saveSV(self, fname, comments=None, metadata=None, printmetadict=None,
dialect = None, delimiter=None, doublequote=True,
lineterminator='\n', escapechar = None, quoting=csv.QUOTE_MINIMAL,
quotechar='"', skipinitialspace=False,
... |
Save the tabarray to a numpy binary archive (. npz ). Save the tabarray to a. npz zipped file containing. npy binary files for data plus optionally coloring and/ or rowdata or simply to a. npy binary file containing the data but no coloring or rowdata. | def savebinary(self, fname, savecoloring=True):
"""
Save the tabarray to a numpy binary archive (``.npz``).
Save the tabarray to a ``.npz`` zipped file containing ``.npy`` binary
files for data, plus optionally coloring and/or rowdata or simply to a
``.npy`` binary fil... |
Horizontal stacking for tabarrays. | def colstack(self, new, mode='abort'):
"""
Horizontal stacking for tabarrays.
Stack tabarray(s) in `new` to the right of `self`.
**See also**
:func:`tabular.tabarray.tab_colstack`,
:func:`tabular.spreadsheet.colstack`
"""
if isinstance... |
Vertical stacking for tabarrays. | def rowstack(self, new, mode='nulls'):
"""
Vertical stacking for tabarrays.
Stack tabarray(s) in `new` below `self`.
**See also**
:func:`tabular.tabarray.tab_rowstack`,
:func:`tabular.spreadsheet.rowstack`
"""
if isinstance(new,list):
... |
Aggregate a tabarray on columns for given functions. | def aggregate(self, On=None, AggFuncDict=None, AggFunc=None, AggList =
None, returnsort=False,KeepOthers=True, keyfuncdict=None):
"""
Aggregate a tabarray on columns for given functions.
Method wraps::
tabular.spreadsheet.aggregate(self, On, AggFuncDict, AggFu... |
Aggregate a tabarray and include original data in the result. | def aggregate_in(self, On=None, AggFuncDict=None, AggFunc=None,
AggList=None, interspersed=True):
"""
Aggregate a tabarray and include original data in the result.
See the :func:`aggregate` method.
Method wraps::
tabular.summarize.aggregate_in(self, On... |
Pivot with a as the row axis and b values as the column axis. | def pivot(self, a, b, Keep=None, NullVals=None, order = None, prefix='_'):
"""
Pivot with `a` as the row axis and `b` values as the column axis.
Method wraps::
tabular.spreadsheet.pivot(X, a, b, Keep)
"""
[data,coloring] = spreadsheet.pivot(X=self, a=a, b=b, Ke... |
Wrapper for spreadsheet. join but handles coloring attributes. | def join(self, ToMerge, keycols=None, nullvals=None,
renamer=None, returnrenaming=False, selfname=None, Names=None):
"""
Wrapper for spreadsheet.join, but handles coloring attributes.
The `selfname` argument allows naming of `self` to be used if `ToMerge`
is a dictionary.... |
Returns the indices that would sort an array. | def argsort(self, axis=-1, kind='quicksort', order=None):
"""
Returns the indices that would sort an array.
.. note::
This method wraps `numpy.argsort`. This documentation is
modified from that of `numpy.argsort`.
Perform an indirect sort along the gi... |
Takes an obj that is a collection object. retain_deprecated if False then obj may be modified to replace deprecated constructs with new syntax. If it is True the obj will not be modified. Returns the pair: errors adaptor errors is a simple list of error messages adaptor will be an instance of collections. validation. a... | def validate_collection(obj, retain_deprecated=True, **kwargs):
"""Takes an `obj` that is a collection object.
`retain_deprecated` if False, then `obj` may be modified to replace
deprecated constructs with new syntax. If it is True, the `obj` will
not be modified.
Returns the pair:
e... |
Determine whether txt matches pattern | def matches(self, txt: str) -> bool:
"""Determine whether txt matches pattern
:param txt: text to check
:return: True if match
"""
# rval = ref.getText()[1:-1].encode('utf-8').decode('unicode-escape')
if r'\\u' in self.pattern_re.pattern:
txt = txt.encode('ut... |
Return web - safe hex triplets. | def Point2HexColor(a, lfrac, tfrac):
"""
Return web-safe hex triplets.
"""
[H,S,V] = [math.floor(360 * a), lfrac, tfrac]
RGB = hsvToRGB(H, S, V)
H = [hex(int(math.floor(255 * x))) for x in RGB]
HEX = [a[a.find('x') + 1:] for a in H]
HEX = ['0' + h if len(h) == 1 else h for h in HEX]... |
Convert HSV ( hue saturation value ) color space to RGB ( red green blue ) color space. | def hsvToRGB(h, s, v):
"""
Convert HSV (hue, saturation, value) color space to RGB (red, green blue)
color space.
**Parameters**
**h** : float
Hue, a number in [0, 360].
**s** : float
Saturation, a number in [0, 1].
**v... |
Returns a logger with name set as given. See _read_logging_config for a description of the env var/ config file cascade that controls configuration of the logger. | def get_logger(name="peyotl"):
"""Returns a logger with name set as given. See _read_logging_config for a description of the env var/config
file cascade that controls configuration of the logger.
"""
logger = logging.getLogger(name)
if len(logger.handlers) == 0:
log_init_warnings = []
... |
Only to be used in this file and peyotl. utility. get_config | def warn_from_util_logger(msg):
"""Only to be used in this file and peyotl.utility.get_config"""
global _LOG
# This check is necessary to avoid infinite recursion when called from get_config, because
# the _read_logging_conf can require reading a conf file.
if _LOG is None and _LOGGING_CONF is Non... |
Returns a dictionary that is empty or has a logging key that refers to the ( up to 3 ) key - value pairs that pertain to logging and are read from the env. This is mainly a convenience function for ConfigWrapper so that it can accurately report the source of the logging settings without | def _logging_env_conf_overrides(log_init_warnings=None):
"""Returns a dictionary that is empty or has a "logging" key that refers to
the (up to 3) key-value pairs that pertain to logging and are read from the env.
This is mainly a convenience function for ConfigWrapper so that it can accurately
repo... |
Returns a dictionary ( should be treated as immutable ) of settings needed to configure a logger. If PEYOTL_LOGGING_LEVEL PEYOTL_LOGGING_FORMAT and PEYOTL_LOG_FILE_PATH are all in the env then no config file will be read. If PEYOTL_LOG_FILE_PATH is set to an empty string then stderr will be used. Otherwise the config w... | def _read_logging_config(log_init_warnings=None):
"""Returns a dictionary (should be treated as immutable) of settings needed to configure a logger.
If PEYOTL_LOGGING_LEVEL, PEYOTL_LOGGING_FORMAT, and PEYOTL_LOG_FILE_PATH are all in the env, then
no config file will be read.
If PEYOTL_LOG_FILE_PATH ... |
Given a selector ( defaults to all ) return a list of lights. Without a selector provided return list of all lights. | def list_lights(self, selector='all'):
"""Given a selector (defaults to all), return a list of lights.
Without a selector provided, return list of all lights.
"""
return self.client.perform_request(
method='get', endpoint='lights/{}',
endpoint_args=[selector], pa... |
Given a selector ( defaults to all ) set the state of a light. Selector can be based on id scene_id group_id label etc. Returns list of lightbulb statuses if successful. See http:// api. developer. lifx. com/ v1/ docs/ selectors | def set_state(self, selector='all',
power=None, color=None, brightness=None, duration=None):
"""Given a selector (defaults to all), set the state of a light.
Selector can be based on id, scene_id, group_id, label, etc.
Returns list of lightbulb statuses if successful.
See http://... |
Given a state delta apply the modifications to lights state over a given period of time. | def state_delta(self, selector='all',
power=None, duration=1.0, infrared=None, hue=None,
saturation=None, brightness=None, kelvin=None):
"""Given a state delta, apply the modifications to lights' state
over a given period of time.
selector: required String
The select... |
Given a selector and transition duration toggle lights ( on/ off ) | def toggle_power(self, selector='all', duration=1.0):
"""Given a selector and transition duration, toggle lights (on/off)"""
argument_tuples = [
("duration", duration)
]
return self.client.perform_request(
method='post', endpoint='lights/{}/toggle',
... |
Perform breathe effect on lights. | def breathe_lights(self, color, selector='all',
from_color=None, period=1.0, cycles=1.0,
persist=False, power_on=True, peak=0.5):
"""Perform breathe effect on lights.
selector: String
The selector to limit which lights will run the effect.
default: all
c... |
Cycle through list of effects. | def cycle_lights(self, states,
defaults, direction='forward', selector='all'):
"""Cycle through list of effects.
Provide array states as a list of dictionaries with set_state arguments.
See http://api.developer.lifx.com/docs/cycle
selector: String
The selector to li... |
Activate a scene. | def activate_scene(self, scene_uuid, duration=1.0):
"""Activate a scene.
See http://api.developer.lifx.com/docs/activate-scene
scene_uuid: required String
The UUID for the scene you wish to activate
duration: Double
The time in seconds to spend performing the s... |
valueTypeExpr: JSON_STRING | JSON_NUMBER | JSON_INT | JSON_BOOL | JSON_NULL | JSON_ARRAY | JSON_OBJECT | def visitBuiltinValueType(self, ctx: jsgParser.BuiltinValueTypeContext):
""" valueTypeExpr: JSON_STRING | JSON_NUMBER | JSON_INT | JSON_BOOL | JSON_NULL | JSON_ARRAY | JSON_OBJECT """
self._value_type_text = ctx.getText()
self._typeinfo = self.parserTypeToImplClass[self._value_type_text] |
Returns the number of trees summed across all tree groups. | def count_num_trees(nexson, nexson_version=None):
"""Returns the number of trees summed across all tree
groups.
"""
if nexson_version is None:
nexson_version = detect_nexson_version(nexson)
nex = get_nexml_el(nexson)
num_trees_by_group = []
if _is_by_id_hbf(nexson_version):
f... |
Factory function for a _TreeCollectionStore object. | def TreeCollectionStore(repos_dict=None,
repos_par=None,
with_caching=True,
assumed_doc_version=None,
git_ssh=None,
pkey=None,
git_action_class=TreeCollectionsGitAction,
... |
Validate and save this JSON. Ensure ( and return ) a unique collection id | def add_new_collection(self,
owner_id,
json_repr,
auth_info,
collection_id=None,
commit_msg=''):
"""Validate and save this JSON. Ensure (and return) a unique collection id"""
... |
Validate and save this JSON. Ensure ( and return ) a unique collection id | def update_existing_collection(self,
owner_id,
collection_id=None,
json_repr=None,
auth_info=None,
parent_sha=None,
... |
Parse the JSON find its name return a slug of its name | def _slugify_internal_collection_name(self, json_repr):
"""Parse the JSON, find its name, return a slug of its name"""
collection = self._coerce_json_to_collection(json_repr)
if collection is None:
return None
internal_name = collection['name']
return slugify(internal... |
Call the primary validator for a quick test | def _is_valid_collection_json(self, json_repr):
"""Call the primary validator for a quick test"""
collection = self._coerce_json_to_collection(json_repr)
if collection is None:
# invalid JSON, definitely broken
return False
aa = validate_collection(collection)
... |
Use to ensure that a JSON string ( if found ) is parsed to the equivalent dict in python. If the incoming value is already parsed do nothing. If a string fails to parse return None. | def _coerce_json_to_collection(self, json_repr):
"""Use to ensure that a JSON string (if found) is parsed to the equivalent dict in python.
If the incoming value is already parsed, do nothing. If a string fails to parse, return None."""
if isinstance(json_repr, dict):
collection = js... |
HTTP REQUEST | def address(address=None, begin=None, end=None):
'''
HTTP REQUEST
GET https://api.nasa.gov/planetary/earth/temperature/address
QUERY PARAMETERS
Parameter Type Default Description
text string n/a Address string
begin int 1880 beginning year for date range, inclusive
end int 2014 end ye... |
HTTP REQUEST | def coordinate(lon=None, lat=None, begin=None, end=None):
'''
HTTP REQUEST
GET https://api.nasa.gov/planetary/earth/temperature/coords
QUERY PARAMETERS
Parameter Type Default Description
lat float n/a Latitude
lon float n/a Longitude
begin int 1880 beginning year for date range, inclu... |
Search LAN for available Roku devices. Returns a Roku object. | def discover_roku():
""" Search LAN for available Roku devices. Returns a Roku object. """
print("Searching for Roku devices within LAN ...")
rokus = Roku.discover()
if not rokus:
print("Unable to discover Roku devices. " +
"Try again, or manually specify the IP address with " +
... |
Uses a peyotl wrapper around an Open Tree web service to get a list of OTT IDs matching the name_list. The tnrs_wrapper can be None ( in which case the default wrapper from peyotl. sugar will be used. All other arguments correspond to the arguments of the web - service call. A ValueError will be raised if the context_n... | def ot_tnrs_match_names(name_list,
context_name=None,
do_approximate_matching=True,
include_dubious=False,
include_deprecated=True,
tnrs_wrapper=None):
"""Uses a peyotl wrapper around an Open Tree... |
Writes out data from taxon to the output stream to demonstrate the attributes of a taxon object. ( currently some lines are commented out until the web - services call returns more info. See: https:// github. com/ OpenTreeOfLife/ taxomachine/ issues/ 85 ). If include_anc is True then ancestor information was requested ... | def write_taxon_info(taxon, include_anc, output):
"""Writes out data from `taxon` to the `output` stream to demonstrate
the attributes of a taxon object.
(currently some lines are commented out until the web-services call returns more info. See:
https://github.com/OpenTreeOfLife/taxomachine/issues/8... |
Demonstrates how to read the response from a match_names query when peyotl s wrap_response option is used. | def match_and_print(name_list, context_name, do_approximate_matching, include_dubious, include_deprecated,
include_subtree, output):
"""Demonstrates how to read the response from a match_names query when peyotl's wrap_response option is
used.
If the context_name is not recognized, the a... |
This function sets up a command - line option parser and then calls match_and_print to do all of the real work. | def main(argv):
"""This function sets up a command-line option parser and then calls match_and_print
to do all of the real work.
"""
import argparse
description = 'Uses Open Tree of Life web services to try to find a taxon ID for each name supplied. ' \
'Using a --context-name=NAME... |
Make value suitable for a binding object. | def _objectify(field, value, ns_info):
"""Make `value` suitable for a binding object.
If `value` is an Entity, call to_obj() on it. Otherwise, pass it
off to the TypedField for an appropriate value.
"""
if (getattr(field.type_, "_treat_none_as_empty_list", False) and
value is None):
... |
Make value suitable for a dictionary. | def _dictify(field, value):
"""Make `value` suitable for a dictionary.
* If `value` is an Entity, call to_dict() on it.
* If value is a timestamp, turn it into a string value.
* If none of the above are satisfied, return the input value
"""
if value is None:
return None
elif field.t... |
Create an instance of the class associated with the key ( xsi: type ) and initialize it with the * args and ** kwargs. | def instance(cls, key, *args, **kwargs):
"""Create an instance of the class associated with the `key` (xsi:type)
and initialize it with the *args and **kwargs.
Args:
key: A class lookup key (see entity_class()).
Returns:
An instance of the class associated with ... |
Parse the dictionary and return an Entity instance. | def from_dict(cls, cls_dict, fallback_xsi_type=None):
"""Parse the dictionary and return an Entity instance.
This will attempt to extract type information from the input
dictionary and pass it to entity_class to resolve the correct class
for the type.
Args:
cls_dict... |
Parse the generateDS object and return an Entity instance. | def from_obj(cls, cls_obj):
"""Parse the generateDS object and return an Entity instance.
This will attempt to extract type information from the input
object and pass it to entity_class to resolve the correct class
for the type.
Args:
cls_obj: A generateDS object.
... |
Return a tuple of this entity s TypedFields. | def typed_fields(cls):
"""Return a tuple of this entity's TypedFields."""
# Checking cls._typed_fields could return a superclass _typed_fields
# value. So we check our class __dict__ which does not include
# inherited attributes.
klassdict = cls.__dict__
try:
... |
Return a list of ( TypedField attribute name TypedField object ) tuples for this Entity. | def typed_fields_with_attrnames(cls):
"""Return a list of (TypedField attribute name, TypedField object)
tuples for this Entity.
"""
# Checking cls._typed_fields could return a superclass _typed_fields
# value. So we check our class __dict__ which does not include
# inher... |
Convert to a GenerateDS binding object. | def to_obj(self, ns_info=None):
"""Convert to a GenerateDS binding object.
Subclasses can override this function.
Returns:
An instance of this Entity's ``_binding_class`` with properties
set from this Entity.
"""
if ns_info:
ns_info.collect(s... |
Convert to a dict | def to_dict(self):
"""Convert to a ``dict``
Subclasses can override this function.
Returns:
Python dict with keys set from this Entity.
"""
entity_dict = {}
for field, val in six.iteritems(self._fields):
if field.multiple:
if val... |
Serializes a: class: Entity instance to an XML string. | def to_xml(self, include_namespaces=True, namespace_dict=None,
pretty=True, encoding="utf-8"):
"""Serializes a :class:`Entity` instance to an XML string.
The default character encoding is ``utf-8`` and can be set via the
`encoding` parameter.
If `encoding` is ``None``, a... |
Parse a JSON string and build an entity. | def from_json(cls, json_doc):
"""Parse a JSON string and build an entity."""
try:
d = json.load(json_doc)
except AttributeError: # catch the read() error
d = json.loads(json_doc)
return cls.from_dict(d) |
Return the multiple TypedField associated with this EntityList. | def _multiple_field(cls):
"""Return the "multiple" TypedField associated with this EntityList.
This also lazily sets the ``_entitylist_multiplefield`` value if it
hasn't been set yet. This is set to a tuple containing one item because
if we set the class attribute to the TypedField, we ... |
Attempts to resolve issues where our samples use http:// example. com/ for our example namespace but python - stix uses http:// example. com by removing the former. | def _fix_example_namespace(self):
"""Attempts to resolve issues where our samples use
'http://example.com/' for our example namespace but python-stix uses
'http://example.com' by removing the former.
"""
example_prefix = 'example' # Example ns prefix
idgen_prefix = idgen... |
Returns a dictionary of namespaces to be exported with an XML document. | def _finalize_namespaces(self, ns_dict=None):
"""Returns a dictionary of namespaces to be exported with an XML
document.
This loops over all the namespaces that were discovered and built
during the execution of ``collect()`` and
``_parse_collected_classes()`` and attempts to mer... |
Determine whether element conforms to etype | def element_conforms(element, etype) -> bool:
""" Determine whether element conforms to etype"""
from pyjsg.jsglib import Empty
if isinstance(element, etype):
return True
# This catches the Optional[] idiom
if (element is None or element is Empty) and issubclass(etype, type(None)):
... |
Determine whether element conforms to etype | def conforms(element, etype, namespace: Dict[str, Any]) -> bool:
""" Determine whether element conforms to etype
:param element: Element to test for conformance
:param etype: Type to test against
:param namespace: Namespace to use to resolve forward references
:return:
"""
etype = proc_forw... |
Upgrade database. | def upgrade():
"""Upgrade database."""
op.create_table(
'communities_community',
sa.Column('created', sa.DateTime(), nullable=False),
sa.Column('updated', sa.DateTime(), nullable=False),
sa.Column('id', sa.String(length=100), nullable=False),
sa.Column('id_user', sa.Integ... |
Get a list of all the communities. | def get(self, query, sort, page, size):
"""Get a list of all the communities.
.. http:get:: /communities/(string:id)
Returns a JSON list with all the communities.
**Request**:
.. sourcecode:: http
GET /communities HTTP/1.1
Accept: appl... |
Get the details of the specified community. | def get(self, community_id):
"""Get the details of the specified community.
.. http:get:: /communities/(string:id)
Returns a JSON dictionary with the details of the specified
community.
**Request**:
.. sourcecode:: http
GET /communities/co... |
Factory function for a _Phylesystem object. | def Phylesystem(repos_dict=None,
repos_par=None,
with_caching=True,
repo_nexml2json=None,
git_ssh=None,
pkey=None,
git_action_class=PhylesystemGitAction,
mirror_info=None,
new_study_prefix=Non... |
Type - specific configuration for backward compatibility | def write_configuration(self, out, secret_attrs=False):
"""Type-specific configuration for backward compatibility"""
key_order = ['repo_nexml2json',
'number_of_shards',
'initialization', ]
cd = self.get_configuration_dict(secret_attrs=secret_attrs)
... |
Type - specific configuration for backward compatibility | def get_configuration_dict(self, secret_attrs=False):
"""Type-specific configuration for backward compatibility"""
cd = {'repo_nexml2json': self.repo_nexml2json,
'number_of_shards': len(self._shards),
'initialization': self._filepath_args,
'shards': [],
... |
Converts HTML5 character references within text_string to their corresponding unicode characters and returns converted string as type str. | def convert_html_entities(text_string):
'''
Converts HTML5 character references within text_string to their corresponding unicode characters
and returns converted string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-str... |
Coverts Latin character references within text_string to their corresponding unicode characters and returns converted string as type str. | def convert_ligatures(text_string):
'''
Coverts Latin character references within text_string to their corresponding unicode characters
and returns converted string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a string or No... |
Splits string and converts words not found within a pre - built dictionary to their most likely actual word based on a relative probability dictionary. Returns edited string as type str. | def correct_spelling(text_string):
'''
Splits string and converts words not found within a pre-built dictionary to their
most likely actual word based on a relative probability dictionary. Returns edited
string as type str.
Keyword argument:
- text_string: string instance
Exceptions raise... |
Splits text_string into a list of sentences based on NLTK s english. pickle tokenizer and returns said list as type list of str. | def create_sentence_list(text_string):
'''
Splits text_string into a list of sentences based on NLTK's english.pickle tokenizer, and
returns said list as type list of str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-string argumen... |
Extracts keywords from text_string using NLTK s list of English stopwords ignoring words of a length smaller than 3 and returns the new string as type str. | def keyword_tokenize(text_string):
'''
Extracts keywords from text_string using NLTK's list of English stopwords, ignoring words of a
length smaller than 3, and returns the new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs sh... |
Returns base from of text_string using NLTK s WordNetLemmatizer as type str. | def lemmatize(text_string):
'''
Returns base from of text_string using NLTK's WordNetLemmatizer as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-string argument be passed
'''
if text_string is None ... |
Converts text_string into lowercase and returns the converted string as type str. | def lowercase(text_string):
'''
Converts text_string into lowercase and returns the converted string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-string argument be passed
'''
if text_string is None or text_string ... |
Given each function within function_list applies the order of functions put forward onto text_string returning the processed string as type str. | def preprocess_text(text_string, function_list):
'''
Given each function within function_list, applies the order of functions put forward onto
text_string, returning the processed string as type str.
Keyword argument:
- function_list: list of functions available in preprocessing.text
- text_st... |
Removes any escape character within text_string and returns the new string as type str. | def remove_esc_chars(text_string):
'''
Removes any escape character within text_string and returns the new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-string argument be passed
'''
if text_string is None or... |
Removes any digit value discovered within text_string and returns the new string as type str. | def remove_numbers(text_string):
'''
Removes any digit value discovered within text_string and returns the new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-string argument be passed
'''
if text_string is Non... |
Removes any integer represented as a word within text_string and returns the new string as type str. | def remove_number_words(text_string):
'''
Removes any integer represented as a word within text_string and returns the new string as
type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-string argument be passed
'''
if te... |
Removes any word associated to time ( day week month etc. ) within text_string and returns the new string as type str. | def remove_time_words(text_string):
'''
Removes any word associated to time (day, week, month, etc.) within text_string and returns the
new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-string argument be passed
... |
Removes all punctuation unattached from a non - whitespace or attached to another punctuation character unexpectedly ( e. g.. ; ; ) within text_string and returns the new string as type str. | def remove_unbound_punct(text_string):
'''
Removes all punctuation unattached from a non-whitespace or attached to another punctuation
character unexpectedly (e.g. ".;';") within text_string and returns the new string as type str.
Keyword argument:
- text_string: string instance
Exceptions ra... |
Removes all URLs within text_string and returns the new string as type str. | def remove_urls(text_string):
'''
Removes all URLs within text_string and returns the new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-string argument be passed
'''
if text_string is None or text_string == "... |
Removes all whitespace found within text_string and returns new string as type str. | def remove_whitespace(text_string):
'''
Removes all whitespace found within text_string and returns new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a string or NoneType not be passed as an argument
'''
if text_st... |
This is the primary method to override to ensure logging with extra options gets correctly specified. | def log(self, level, message, *args, **kwargs):
"""
This is the primary method to override to ensure logging with extra
options gets correctly specified.
"""
extra = self.extras.copy()
extra.update(kwargs.pop('extra', {}))
kwargs['extra'] = extra
self.log... |
Specialized warnings system. If a warning subclass is passed into the keyword arguments and raise_warnings is True - the warnning will be passed to the warnings module. | def warning(self, message, *args, **kwargs):
"""
Specialized warnings system. If a warning subclass is passed into
the keyword arguments and raise_warnings is True - the warnning will
be passed to the warnings module.
"""
warncls = kwargs.pop('warning', None)
if w... |
Provide current user as extra context to the logger | def log(self, level, message, *args, **kwargs):
"""
Provide current user as extra context to the logger
"""
extra = kwargs.pop('extra', {})
extra.update({
'user': self.user
})
kwargs['extra'] = extra
super(ServiceLogger, self).log(level, messa... |
Instantiates and returns a ServiceLogger instance | def logger(self):
"""
Instantiates and returns a ServiceLogger instance
"""
if not hasattr(self, '_logger') or not self._logger:
self._logger = ServiceLogger()
return self._logger |
Uses a peyotl wrapper around an Open Tree web service to get a list of studies including values value for a given property to be searched on porperty. | def ot_find_studies(arg_dict, exact=True, verbose=False, oti_wrapper=None):
"""Uses a peyotl wrapper around an Open Tree web service to get a list of studies
including values `value` for a given property to be searched on `porperty`.
The oti_wrapper can be None (in which case the default wrapper from peyot... |
This function sets up a command - line option parser and then calls print_matching_trees to do all of the real work. | def main(argv):
"""This function sets up a command-line option parser and then calls print_matching_trees
to do all of the real work.
"""
import argparse
description = 'Uses Open Tree of Life web services to try to find a tree with the value property pair specified. ' \
'setting --... |
This function sets up a command - line option parser and then calls to do all of the real work. | def main(argv):
"""This function sets up a command-line option parser and then calls
to do all of the real work.
"""
import argparse
import codecs
# have to be ready to deal with utf-8 names
out = codecs.getwriter('utf-8')(sys.stdout)
description = '''Takes a series of at least 2 OTT ids... |
Searchers for JSON files in this repo and returns a map of collection id == > ( tag dir collection filepath ) where tag is typically the shard name | def create_id2collection_info(path, tag):
"""Searchers for JSON files in this repo and returns
a map of collection id ==> (`tag`, dir, collection filepath)
where `tag` is typically the shard name
"""
d = {}
for triple in os.walk(path):
root, files = triple[0], triple[2]
for filen... |
Generic configuration may be overridden by type - specific version | def write_configuration(self, out, secret_attrs=False):
"""Generic configuration, may be overridden by type-specific version"""
key_order = ['name', 'path', 'git_dir', 'doc_dir', 'assumed_doc_version',
'git_ssh', 'pkey', 'has_aliases', 'number of collections']
cd = self.get_... |
Overrides superclass method and renames some properties | def get_configuration_dict(self, secret_attrs=False):
"""Overrides superclass method and renames some properties"""
cd = super(TreeCollectionsShard, self).get_configuration_dict(secret_attrs=secret_attrs)
# "rename" some keys in the dict provided
cd['number of collections'] = cd.pop('num... |
Returns a set of all of the prefixes seen in the main document dir | def _diagnose_prefixes(self):
"""Returns a set of all of the prefixes seen in the main document dir
"""
from peyotl.collections_store import COLLECTION_ID_PATTERN
p = set()
for owner_dirname in os.listdir(self.doc_dir):
example_collection_name = "{n}/xxxxx".format(n=o... |
Checks out master branch as a side effect | def create_git_action_for_new_collection(self, new_collection_id=None):
"""Checks out master branch as a side effect"""
ga = self.create_git_action()
assert new_collection_id is not None
# id should have been sorted out by the caller
self.register_doc_id(ga, new_collection_id)
... |
Determine if a value is a sequence type. | def is_sequence(value):
"""Determine if a value is a sequence type.
Returns:
``True`` if `value` is a sequence type (e.g., ``list``, or ``tuple``).
String types will return ``False``.
NOTE: On Python 3, strings have the __iter__ defined, so a simple hasattr
check is insufficient.
"""
... |
Import the class referred to by the fully qualified class path. | def import_class(classpath):
"""Import the class referred to by the fully qualified class path.
Args:
classpath: A full "foo.bar.MyClass" path to a class definition.
Returns:
The class referred to by the classpath.
Raises:
ImportError: If an error occurs while importing the mo... |
Attempt to return a Python class for the input class reference. | def resolve_class(classref):
"""Attempt to return a Python class for the input class reference.
If `classref` is a class or None, return it. If `classref` is a
python classpath (e.g., "foo.bar.MyClass") import the class and return
it.
Args:
classref: A fully-qualified Python path to class,... |
Function decorator which checks that the decorated function is called with a set of required kwargs. | def needkwargs(*argnames):
"""Function decorator which checks that the decorated function is called
with a set of required kwargs.
Args:
*argnames: String keyword argument names.
Raises:
ValueError: If a required kwarg is missing in the decorated function
call.
"""
... |
Connect to the APCUPSd NIS and request its status. | def get(host="localhost", port=3551, timeout=30):
"""
Connect to the APCUPSd NIS and request its status.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
sock.connect((host, port))
sock.send(CMD_STATUS)
buffr = ""
while not buffr.endswith(EOF):
... |
Split the output from get_status () into lines clean it up and return it as an OrderedDict. | def parse(raw_status, strip_units=False):
"""
Split the output from get_status() into lines, clean it up and return it as
an OrderedDict.
"""
lines = split(raw_status)
if strip_units:
lines = strip_units_from_lines(lines)
# Split each line on the SEP character, strip extraneous white... |
Removes all units from the ends of the lines. | def strip_units_from_lines(lines):
"""
Removes all units from the ends of the lines.
"""
for line in lines:
for unit in ALL_UNITS:
if line.endswith(" %s" % unit):
line = line[:-1-len(unit)]
yield line |
Print the status to stdout in the same format as the original apcaccess. | def print_status(raw_status, strip_units=False):
"""
Print the status to stdout in the same format as the original apcaccess.
"""
lines = split(raw_status)
if strip_units:
lines = strip_units_from_lines(lines)
for line in lines:
print(line) |
Takes a name and optional contextName returns a list of matches. wrap_response can be True to return a TNRSResponse object None to return the raw response dict or a function/ class that takes ( response query_data = dict ) as its arguments. | def TNRS(self,
names,
context_name=None,
id_list=None,
fuzzy_matching=False,
include_deprecated=False,
include_dubious=False,
do_approximate_matching=None,
wrap_response=None):
"""Takes a name and optional co... |
Takes a name and optional context_name returns a list of matches. Each match is a dict with: higher boolean DEF??? exact boolean for exact match ottId int name name ( or uniqname??? ) for the taxon in OTT nodeId int ID of not in the taxomachine db. probably not of use to anyone... | def autocomplete(self, name, context_name=None, include_dubious=False):
"""Takes a name and optional context_name returns a list of matches.
Each match is a dict with:
'higher' boolean DEF???
'exact' boolean for exact match
'ottId' int
'name' name (or uniqnam... |
delegates a call to TNRS ( same arguments as that function ). | def names_to_ott_ids_perfect(self, names, **kwargs):
"""delegates a call to TNRS (same arguments as that function).
Returns a list of (non-dubious) OTT IDs in the same order as the original names.
Raises a ValueError if each name does not have exactly one perfect, non-dubious
(score = 1... |
If the taxa are being cached this call will create a the lineage spike for taxon child_taxon | def get_cached_parent_for_taxon(self, child_taxon):
"""If the taxa are being cached, this call will create a the lineage "spike" for taxon child_taxon
Expecting child_taxon to have a non-empty _taxonomic_lineage with response dicts that can create
an ancestral TaxonWrapper.
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.