text stringlengths 18 773k |
|---|
def C_array2dict(C):
"""Convert a 1D array containing C values to a dictionary."""
d = OrderedDict()
i=0
for k in C_keys:
s = C_keys_shape[k]
if s == 1:
j = i+1
d[k] = C[i]
else:
j = i \
+ reduce(operator.mul, s, 1)
d[k] = C[i... |
def C_dict2array(C):
"""Convert an OrderedDict containing C values to a 1D array."""
return np.hstack([np.asarray(C[k]).ravel() for k in C_keys]) |
def symmetrize_nonred(C):
"""Symmetrize the Wilson coefficient arrays.
This function takes into account the symmetry factors
that occur when transitioning from a basis with only non-redundant operators
(like in WCxf) to a basis where the Wilson coefficients are symmetrized
like the operators."""
... |
def unscale_dict(C):
"""Undo the scaling applied in `scale_dict`."""
C_out = {k: _scale_dict[k] * v for k, v in C.items()}
for k in C_symm_keys[8]:
C_out['qqql'] = unscale_8(C_out['qqql'])
return C_out |
def wcxf2arrays_symmetrized(d):
"""Convert a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values to a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values.
In contrast to `wcxf2arrays`, here the numpy ... |
def commit_signal(data_id):
"""Nudge manager at the end of every Data object save event."""
if not getattr(settings, 'FLOW_MANAGER_DISABLE_AUTO_CALLS', False):
immediate = getattr(settings, 'FLOW_MANAGER_SYNC_AUTO_CALLS', False)
async_to_sync(manager.communicate)(data_id=data_id, save_settings=F... |
def manager_post_save_handler(sender, instance, created, **kwargs):
"""Run newly created (spawned) processes."""
if instance.status == Data.STATUS_DONE or instance.status == Data.STATUS_ERROR or created:
# Run manager at the end of the potential transaction. Otherwise
# tasks are send to workers... |
def delete_entity(sender, instance, **kwargs):
"""Delete Entity when last Data object is deleted."""
# 1 means that the last Data object is going to be deleted.
Entity.objects.annotate(num_data=Count('data')).filter(data=instance, num_data=1).delete() |
def delete_relation(sender, instance, **kwargs):
"""Delete the Relation object when the last Entity is removed."""
def process_signal(relation_id):
"""Get the relation and delete it if it has no entities left."""
try:
relation = Relation.objects.get(pk=relation_id)
except Rel... |
async def run_executor():
"""Start the actual execution; instantiate the executor and run."""
parser = argparse.ArgumentParser(description="Run the specified executor.")
parser.add_argument('module', help="The module from which to instantiate the concrete executor.")
args = parser.parse_args()
modu... |
def assert_valid(sysmeta_pyxb, pid):
"""Validate file at {sciobj_path} against schema selected via formatId and raise
InvalidRequest if invalid.
Validation is only performed when:
- SciMeta validation is enabled
- and Object size is below size limit for validation
- and formatId designates obj... |
def ready(self):
"""Perform application initialization."""
# Initialize the type extension composer.
from . composer import composer
composer.discover_extensions()
is_migrating = sys.argv[1:2] == ['migrate']
if is_migrating:
# Do not register signals and ES i... |
def to_internal_value(self, data):
"""Convert to internal value."""
user = getattr(self.context.get('request'), 'user')
queryset = self.get_queryset()
permission = get_full_perm('view', queryset.model)
try:
return get_objects_for_user(
user,
... |
def dumps(dct, as_dict=False, **kwargs):
""" Dump the dict to json in DynamoDB Format
You can use any other simplejson or json options
:param dct - the dict to dump
:param as_dict - returns the result as python dict (useful for DynamoDB boto3 library) or as json sting
:returns: Dynam... |
def object_hook(dct):
""" DynamoDB object hook to return python values """
try:
# First - Try to parse the dct as DynamoDB parsed
if 'BOOL' in dct:
return dct['BOOL']
if 'S' in dct:
val = dct['S']
try:
return datetime.strptime(val, '%Y-... |
def loads(s, as_dict=False, *args, **kwargs):
""" Loads dynamodb json format to a python dict.
:param s - the json string or dict (with the as_dict variable set to True) to convert
:returns python dict object
"""
if as_dict or (not isinstance(s, six.string_types)):
s = json.dumps(s)
... |
def tileSize(self, zoom):
"Returns the size (in meters) of a tile"
assert zoom in range(0, len(self.RESOLUTIONS))
return self.tileSizePx * self.RESOLUTIONS[int(zoom)] |
def tileBounds(self, zoom, tileCol, tileRow):
"Returns the bounds of a tile in LV03 (EPSG:21781)"
assert zoom in range(0, len(self.RESOLUTIONS))
# 0,0 at top left: y axis down and x axis right
tileSize = self.tileSize(zoom)
minX = self.MINX + tileCol * tileSize
maxX = se... |
def tileAddress(self, zoom, point):
"Returns a tile address based on a zoom level and \
a point in the tile"
[x, y] = point
assert x <= self.MAXX and x >= self.MINX
assert y <= self.MAXY and y >= self.MINY
assert zoom in range(0, len(self.RESOLUTIONS))
tileS = se... |
def intersectsExtent(self, extent):
"Determine if an extent intersects this instance extent"
return \
self.extent[0] <= extent[2] and self.extent[2] >= extent[0] and \
self.extent[1] <= extent[3] and self.extent[3] >= extent[1] |
def iterGrid(self, minZoom, maxZoom):
"Yields the tileBounds, zoom, tileCol and tileRow"
assert minZoom in range(0, len(self.RESOLUTIONS))
assert maxZoom in range(0, len(self.RESOLUTIONS))
assert minZoom <= maxZoom
for zoom in xrange(minZoom, maxZoom + 1):
[minRow, m... |
def numberOfXTilesAtZoom(self, zoom):
"Returns the number of tiles over x at a given zoom level"
[minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom)
return maxCol - minCol + 1 |
def numberOfYTilesAtZoom(self, zoom):
"Retruns the number of tiles over y at a given zoom level"
[minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom)
return maxRow - minRow + 1 |
def numberOfTilesAtZoom(self, zoom):
"Returns the total number of tile at a given zoom level"
[minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom)
return (maxCol - minCol + 1) * (maxRow - minRow + 1) |
def totalNumberOfTiles(self, minZoom=None, maxZoom=None):
"Return the total number of tiles for this instance extent"
nbTiles = 0
minZoom = minZoom or 0
if maxZoom:
maxZoom = maxZoom + 1
else:
maxZoom = len(self.RESOLUTIONS)
for zoom in xrange(minZ... |
def getZoom(self, resolution):
"Return the zoom level for a given resolution"
assert resolution in self.RESOLUTIONS
return self.RESOLUTIONS.index(resolution) |
def _getZoomLevelRange(self, resolution, unit='meters'):
"Return lower and higher zoom level given a resolution"
assert unit in ('meters', 'degrees')
if unit == 'meters' and self.unit == 'degrees':
resolution = resolution / self.metersPerUnit
elif unit == 'degrees' and self.u... |
def getClosestZoom(self, resolution, unit='meters'):
"""
Return the closest zoom level for a given resolution
Parameters:
resolution -- max. resolution
unit -- unit for output (default='meters')
"""
lo, hi = self._getZoomLevelRange(resolution, unit)
... |
def getCeilingZoom(self, resolution, unit='meters'):
"""
Return the maximized zoom level for a given resolution
Parameters:
resolution -- max. resolution
unit -- unit for output (default='meters')
"""
if resolution in self.RESOLUTIONS:
return s... |
def getScale(self, zoom):
"""Returns the scale at a given zoom level"""
if self.unit == 'degrees':
resolution = self.getResolution(zoom) * EPSG4326_METERS_PER_UNIT
else:
resolution = self.getResolution(zoom)
return resolution / STANDARD_PIXEL_SIZE |
def getExtentAddress(self, zoom, extent=None, contained=False):
"""
Return the bounding addresses ([minRow, minCol, maxRow, maxCol] based
on the instance's extent or a user defined extent. Generic method
that works with regular and irregular pyramids.
Parameters:
zoom... |
def getParentTiles(self, zoom, col, row, zoomParent):
"""
Return the parent tile(s) for an irregular (not following quadindex)
and regular tiling scheme
Parameters:
zoom -- the zoom level a the child tile
row -- the row of the child tile
col -- the col... |
def enable_loggly(graph):
"""
Enable loggly if it is configured and not debug/testing.
"""
if graph.metadata.debug or graph.metadata.testing:
return False
try:
if not graph.config.logging.loggly.token:
return False
if not graph.config.logging.loggly.environment... |
def make_dict_config(graph):
"""
Build a dictionary configuration from conventions and configuration.
"""
formatters = {}
handlers = {}
loggers = {}
# create the console handler
formatters["ExtraFormatter"] = make_extra_console_formatter(graph)
handlers["console"] = make_stream_han... |
def make_json_formatter(graph):
"""
Create the default json formatter.
"""
return {
"()": graph.config.logging.json_formatter.formatter,
"fmt": graph.config.logging.json_required_keys,
} |
def make_stream_handler(graph, formatter):
"""
Create the stream handler. Used for console/debug output.
"""
return {
"class": graph.config.logging.stream_handler.class_,
"formatter": formatter,
"level": graph.config.logging.level,
"stream": graph.config.logging.stream_h... |
def make_loggly_handler(graph, formatter):
"""
Create the loggly handler.
Used for searchable aggregation.
"""
base_url = graph.config.logging.loggly.base_url
loggly_url = "{}/inputs/{}/tag/{}".format(
base_url,
graph.config.logging.loggly.token,
",".join([
... |
def make_library_levels(graph):
"""
Create third party library logging level configurations.
Tunes down overly verbose logs in commonly used libraries.
"""
# inject the default components; these can, but probably shouldn't, be overridden
levels = {}
for level in ["DEBUG", "INFO", "WARN", "... |
def process_request(self, request):
"""
Redirects the current request if there is a matching Redirect model
with the current request URL as the old_path field.
"""
site = request.site
cache_key = '{prefix}-{site}'.format(prefix=settings.REDIRECT_CACHE_KEY_PREFIX, site=sit... |
def context_logger(context_func, func, parent=None):
"""
The results of context_func will be executed and applied to a ContextLogger
instance for the execution of func. The resulting ContextLogger instance will be
available on parent.logger for the duration of func.
:param context_func: callable wh... |
def patched_get_current(self, request=None):
"""
Monkey patched version of Django's SiteManager.get_current() function.
Returns the current Site based on a given request or the SITE_ID in
the project's settings. If a request is given attempts to match a site
with domain matching request.get_host().... |
def patched_get_site_by_id(self, site_id):
"""
Monkey patched version of Django's SiteManager._get_site_by_id() function.
Adds a configurable timeout to the in-memory SITE_CACHE for each cached Site.
This allows for the use of an in-memory cache for Site models, avoiding one
or more DB hits on ever... |
def patched_get_site_by_request(self, request):
"""
Monkey patched version of Django's SiteManager._get_site_by_request() function.
Adds a configurable timeout to the in-memory SITE_CACHE for each cached Site.
This allows for the use of an in-memory cache for Site models, avoiding one
or more DB hi... |
def str_brief(obj, lim=20, dots='...', use_repr=True):
"""Truncates a string, starting from 'lim' chars. The given object
can be a string, or something that can be casted to a string.
>>> import string
>>> str_brief(string.uppercase)
'ABCDEFGHIJKLMNOPQRST...'
>>> str_brief(2 ** 50, lim=10, dots... |
def get_mirror_resources_by_name_map(self, scope=None):
""" returns a map volume_name -> volume, cg_name->cg
scope is either None or CG or Volume
"""
volumes_mirrors_by_name = dict()
cgs_mirrors_by_name = dict()
if ((scope is None) or (scope.lower() == 'volume')... |
def get_host_port_names(self, host_name):
""" return a list of the port names of XIV host """
port_names = list()
host = self.get_hosts_by_name(host_name)
fc_ports = host.fc_ports
iscsi_ports = host.iscsi_ports
port_names.extend(fc_ports.split(',') if fc_ports != ''... |
def get_cluster_port_names(self, cluster_name):
""" return a list of the port names under XIV CLuster """
port_names = list()
for host_name in self.get_hosts_by_clusters()[cluster_name]:
port_names.extend(self.get_hosts_by_name(host_name))
return port_names |
def flush(self):
"""remove all stale clients from pool"""
now = time.time()
to_remove = []
for k, entry in self.pool.items():
if entry.timestamp < now:
entry.client.close()
to_remove.append(k)
for k in to_remove:
del self.po... |
def get(self, user, password, endpoints):
"""Gets an existing connection or opens a new one
"""
now = time.time()
# endpoints can either be str or list
if isinstance(endpoints, str):
endpoints = [endpoints]
for ep in endpoints:
if ep not in self.po... |
def size(value: int, suffixes: list = None) -> str:
"""
>>> size(1024)
'1 KB'
"""
suffixes = suffixes or [
'bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
order = int(log2(value) / 10) if value else 0
return '{:.4g} {}'.format(value / (1 << (order * 10)), suffixes[order]) |
def parse_size(value):
"""
>>> parse_size('1M')
1048576
>>> parse_size('512K512K')
1048576
>>> parse_size('512K 512K')
1048576
>>> parse_size('512K 512K 4')
1048580
"""
if isinstance(value, (int, float)):
return value
elif not pattern_valid.fullmatch(value):
... |
def parse_duration(value):
"""
>>> parse_duration('1h')
3600
>>> parse_duration('1m')
60
>>> parse_duration('1m 2s')
62
>>> parse_duration('1')
1
"""
if isinstance(value, (int, float)):
return value
elif not pattern_valid.fullmatch(value):
raise ValueErro... |
def send_event(self, action, properties, event_severity=EVENT_SEVERITY):
"""
send css_event and if fails send custom_event instead
Args:
action (ACTIONS): the action causing the event
properties (dict): the action additional properties
event_severity (string):... |
def _create_mirror(self, resource_type, resource_name, target_name,
mirror_type, slave_resource_name, create_slave='no',
remote_pool=None, rpo=None, remote_rpo=None,
schedule=None, remote_schedule=None,
activate_mirror='no')... |
def chained(wrapping_exc):
# pylint: disable=W0212
"""
Embeds the current exception information into the given one (which
will replace the current one).
For example::
try:
...
except OSError as ex:
raise chained(MyError("database not found!"))
"""
t, ... |
def get_user(self, username, *, mode=OsuMode.osu, event_days=31):
"""Get a user profile.
Parameters
----------
username : str or int
A `str` representing the user's username, or an `int` representing the user's id.
mode : :class:`osuapi.enums.OsuMode`
The... |
def get_user_best(self, username, *, mode=OsuMode.osu, limit=50):
"""Get a user's best scores.
Parameters
----------
username : str or int
A `str` representing the user's username, or an `int` representing the user's id.
mode : :class:`osuapi.enums.OsuMode`
... |
def get_user_recent(self, username, *, mode=OsuMode.osu, limit=10):
"""Get a user's most recent scores, within the last 24 hours.
Parameters
----------
username : str or int
A `str` representing the user's username, or an `int` representing the user's id.
mode : :cla... |
def get_scores(self, beatmap_id, *, username=None, mode=OsuMode.osu, mods=None, limit=50):
"""Get the top scores for a given beatmap.
Parameters
----------
beatmap_id
Individual Beatmap ID to lookup.
username : str or int
A `str` representing the user's u... |
def get_beatmaps(self, *, since=None, beatmapset_id=None, beatmap_id=None, username=None, mode=None,
include_converted=False, beatmap_hash=None, limit=500):
"""Get beatmaps.
Parameters
----------
since : datetime
If specified, restrict results to beatmap... |
def get_match(self, match_id):
"""Get a multiplayer match.
Parameters
----------
match_id
The ID of the match to retrieve. This is the ID that you see in a online multiplayer match summary.
This does not correspond the in-game game ID."""
return self._mak... |
async def copy(self, key_source, storage_dest, key_dest):
""" Return True if data are copied
* optimized for http->fs copy
* not supported return_status
"""
from aioworkers.storage.filesystem import FileSystemStorage
if not isinstance(storage_dest, FileSystemStorage):
... |
def import_name(stref: str):
"""
>>> import_name('datetime.datetime.utcnow') is not None
True
>>> import_name('aioworkers.utils.import_name') is not None
True
"""
h = stref
p = []
m = None
try:
r = importlib.util.find_spec(stref)
except (AttributeError, ImportError):
... |
def options(self, **options):
"""A context-manager for setting connection options; the original
values of the options will be restored when the context-manager exits.
For example::
with c.options(gui_mode = False):
c.cmd.vol_list()
"""
self._contexts... |
def set_options(self, **options):
"""Sets the value of the given options (as keyword arguments).
Note that underscored in the option's name will be replaced with
hyphens (i.e., ``c.set_options(gui_mode = True)``
will set the option ``gui-mode``)
"""
opt2 = self._contexts[... |
def connect_ssl(cls, user, password, endpoints,
ca_certs=None, validate=None):
"""
Creates an SSL transport to the first endpoint (aserver) to which
we successfully connect
"""
if isinstance(endpoints, basestring):
endpoints = [endpoints]
t... |
def connect_multiendpoint_ssl(cls, user, password, endpoints,
auto_discover=True, ca_certs=None,
validate=None):
"""
Creates a MultiEndpointTransport, so that if the current endpoint
(aserver) fails, it would automatically move ... |
def execute_remote(self, remote_target, cmd, **kwargs):
"""
Executes the given command (with the given arguments)
on the given remote target of the connected machine
"""
data = self._build_command(cmd, kwargs, self._contexts[-1],
remote_target)
... |
def get_user_client(self, user, password, populate=True):
"""
Returns a new client for the given user. This is a lightweight
client that only uses different credentials and shares the transport
with the underlying client
"""
return XCLIClientForUser(weakproxy(self), user,... |
def get_remote_client(self, target_name, user=None, password=None):
"""
Returns a new client for the remote target. This is a lightweight
client that only uses different credentials and shares the transport
with the underlying client
"""
if user:
base = self.g... |
def as_user(self, user, password):
"""
A context-manager for ``get_user_client``. Allows the execution
of commands as a different user with ease.
Example:
>>> c.cmd.vol_list()
>>> with c.as_user("user", "password"):
... c.cmd.vol_list()
"""
... |
def accuracy(self, mode: OsuMode):
"""Calculated accuracy.
See Also
--------
<https://osu.ppy.sh/help/wiki/Accuracy>
"""
if mode is OsuMode.osu:
return (
(6 * self.count300 + 2 * self.count100 + self.count50) /
(6 * (self.count... |
def create_mirror(self, resource_name, target_name, mirror_type,
slave_resource_name, rpo=None, remote_rpo=None,
schedule=None, remote_schedule=None,
activate_mirror='no'):
'''creates a mirror and returns a mirror object.
target n... |
def get_cg_volumes(self, group_id):
""" return all non snapshots volumes in cg """
for volume in self.xcli_client.cmd.vol_list(cg=group_id):
if volume.snapshot_of == '':
yield volume.name |
def _certificate_required(cls, hostname, port=XCLI_DEFAULT_PORT,
ca_certs=None, validate=None):
'''
returns true if connection should verify certificate
'''
if not ca_certs:
return False
xlog.debug("CONNECT SSL %s:%s, cert_file=%s",
... |
def add_converter(cls, klass, conv, score=0):
""" Add converter
:param klass: class or str
:param conv: callable
:param score:
:return:
"""
if isinstance(klass, str):
klass = import_name(klass)
item = klass, conv, score
cls.converters.a... |
def _populate_bunch_with_element(element):
"""
Helper function to recursively populates a Bunch from an XML tree.
Returns leaf XML elements as a simple value, branch elements are returned
as Bunches containing their subelements as value or recursively generated
Bunch members.
"""
if 'value' ... |
def all(self, element_type=None, response_path=None):
"""
Generates Bunches, each representing a single subelement of the
response. If an element_type is requested, only elements whose
tag matches the element_type are returned. If the response has no
subelements (for example, in ... |
def as_single_element(self):
"""
Processes the response as a single-element response,
like config_get or system_counters_get.
If there is more then one element in the response or no
elements this raises a ResponseError
"""
if self.as_return_etree is None:
... |
def enabled_flags(self):
"""Return the objects for each individual set flag."""
if not self.value:
yield self.__flags_members__[0]
return
val = self.value
while val:
lowest_bit = val & -val
val ^= lowest_bit
yield self.__flags_... |
def contains_any(self, other):
"""Check if any flags are set.
(OsuMod.Hidden | OsuMod.HardRock) in flags # Check if either hidden or hardrock are enabled.
OsuMod.keyMod in flags # Check if any keymod is enabled.
"""
return self.value == other.value or self.value & other.value |
def get_percentage(self):
"""Get the cumulative time percentage of each stopwatch (including the current split).
Returns
-------
cumulative_elapsed_time_percentage : List[float]
"""
cumulative_elapsed_time = self.get_cumulative_elapsed_time()
sum_elapsed_time = s... |
def get_mean_per_split(self):
"""Get the mean elapsed time per split of each stopwatch (excluding the current split).
Returns
-------
mean_elapsed_time_per_split : List[datetime.timedelta]
"""
return [div_timedelta(sum(stopwatch.split_elapsed_time, datetime.timedelta()),... |
def get_statistics(self):
"""Get all statistics as a dictionary.
Returns
-------
statistics : Dict[str, List]
"""
return {
'cumulative_elapsed_time': self.get_cumulative_elapsed_time(),
'percentage': self.get_percentage(),
'n_splits': ... |
def conform_query(cls, query):
"""Converts the query string from a target uri, uses
cls.default_query to populate default arguments.
:param query: Unparsed query string
:type query: urllib.parse.unsplit(uri).query
:returns: Dictionary of parsed values, everything in cls.default_... |
def load_target(cls, scheme, path, fragment, username,
password, hostname, port, query,
load_method, **kwargs):
"""Override this method to use values from the parsed uri to initialize
the expected target.
"""
raise NotImplementedError("load_target... |
def hog(concurrency, requests, limit, timeout,
params, paramfile, headers, headerfile, method, url):
'''Sending multiple `HTTP` requests `ON` `GREEN` thread'''
params = parse_from_list_and_file(params, paramfile)
headers = parse_from_list_and_file(headers, headerfile)
# Running information
... |
def _append_value(self, value, _file, _name):
"""Call this function to write contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
* _name - str, name of current content dict
"""
_tabs = '\t' * self._tctr
... |
def _append_array(self, value, _file):
"""Call this function to write array contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
_tabs = '\t' * self._tctr
_labs = '{tabs}<array>\n'.format(tabs=_tabs)
... |
def _append_dict(self, value, _file):
"""Call this function to write dict contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
_tabs = '\t' * self._tctr
_labs = '{tabs}<dict>\n'.format(tabs=_tabs)
_f... |
def _append_data(self, value, _file):
"""Call this function to write data contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
# binascii.b2a_base64(value) -> plistlib.Data
# binascii.a2b_base64(Data) -> val... |
def _append_date(self, value, _file):
"""Call this function to write date contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
_tabs = '\t' * self._tctr
_text = value.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
... |
def _append_integer(self, value, _file):
"""Call this function to write integer contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
_tabs = '\t' * self._tctr
_text = value
_labs = '{tabs}<integer>{t... |
def register_output_name(self, input_folder, rel_name, rel_output_name):
"""Register proper and improper file mappings."""
self.improper_input_file_mapping[rel_name].add(rel_output_name)
self.proper_input_file_mapping[os.path.join(input_folder, rel_name)] = rel_output_name
self.proper_in... |
def _discover(self):
"""Find and install all extensions"""
for ep in pkg_resources.iter_entry_points('yamlsettings10'):
ext = ep.load()
if callable(ext):
ext = ext()
self.add(ext) |
def get_extension(self, protocol):
"""Retrieve extension for the given protocol
:param protocol: name of the protocol
:type protocol: string
:raises NoProtocolError: no extension registered for protocol
"""
if protocol not in self.registry:
raise NoProtocolE... |
def add(self, extension):
"""Adds an extension to the registry
:param extension: Extension object
:type extension: yamlsettings.extensions.base.YamlSettingsExtension
"""
index = len(self.extensions)
self.extensions[index] = extension
for protocol in extension.pr... |
def _load_first(self, target_uris, load_method, **kwargs):
"""Load first yamldict target found in uri list.
:param target_uris: Uris to try and open
:param load_method: load callback
:type target_uri: list or string
:type load_method: callback
:returns: yamldict
... |
def load(self, target_uris, fields=None, **kwargs):
"""Load first yamldict target found in uri.
:param target_uris: Uris to try and open
:param fields: Fields to filter. Default: None
:type target_uri: list or string
:type fields: list
:returns: yamldict
"""
... |
def load_all(self, target_uris, **kwargs):
'''
Load *all* YAML settings from a list of file paths given.
- File paths in the list gets the priority by their orders
of the list.
'''
yaml_series = self._load_first(
target_uris, yamlsettings.yamldict.loa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.