code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def zeq_magic(meas_file='measurements.txt', spec_file='',crd='s',input_dir_path='.', angle=0,
n_plots=5, save_plots=True, fmt="svg", interactive=False, specimen="",
samp_file='samples.txt', contribution=None,fignum=1):
"""
zeq_magic makes zijderveld and equal area plots for magic for... | zeq_magic makes zijderveld and equal area plots for magic formatted measurements files.
Parameters
----------
meas_file : str
input measurement file
spec_file : str
input specimen interpretation file
samp_file : str
input sample orientations file
crd : str
coordin... |
def before_insert(mapper, conn, target):
"""event.listen method for Sqlalchemy to set the sequence for this
object and create an ObjectNumber value for the id_"""
target._set_ids()
if target.name and target.vname and target.cache_key and target.fqname and not target.dataset:
... | event.listen method for Sqlalchemy to set the sequence for this
object and create an ObjectNumber value for the id_ |
def _get_stddev_deep_soil(self, mag, imt):
"""
Calculate and return total standard deviation for deep soil sites.
Implements formulae from the last column of table 4.
"""
# footnote from table 4 says that stderr for magnitudes over 7
# is equal to one of magnitude 7.
... | Calculate and return total standard deviation for deep soil sites.
Implements formulae from the last column of table 4. |
def get_subgraph(self, name):
"""Retrieved a subgraph from the graph.
Given a subgraph's name the corresponding
Subgraph instance will be returned.
If one or more subgraphs exist with the same name, a list of
Subgraph instances is returned.
An empty list is returned oth... | Retrieved a subgraph from the graph.
Given a subgraph's name the corresponding
Subgraph instance will be returned.
If one or more subgraphs exist with the same name, a list of
Subgraph instances is returned.
An empty list is returned otherwise. |
def txn(self, overwrite=False, lock=True):
"""Context manager for a state modification transaction."""
if lock:
self._lock.acquire()
try:
new_state, existing_generation = self.state_and_generation
new_state = copy.deepcopy(new_state)
yield new_stat... | Context manager for a state modification transaction. |
def from_env(cls, reactor=None, env=os.environ):
"""
Create a Vault client with configuration from the environment. Supports
a limited number of the available config options:
https://www.vaultproject.io/docs/commands/index.html#environment-variables
https://github.com/hashicorp/v... | Create a Vault client with configuration from the environment. Supports
a limited number of the available config options:
https://www.vaultproject.io/docs/commands/index.html#environment-variables
https://github.com/hashicorp/vault/blob/v0.11.3/api/client.go#L28-L40
Supported:
-... |
def io_surface(timestep, time, fid, fld):
"""Output for surface files"""
fid.write("{} {}".format(timestep, time))
fid.writelines(["%10.2e" % item for item in fld[:]])
fid.writelines(["\n"]) | Output for surface files |
def info(self):
"""
Retrieves the design document view information data, returns dictionary
GET databasename/_design/{ddoc}/_info
"""
ddoc_info = self.r_session.get(
'/'.join([self.document_url, '_info']))
ddoc_info.raise_for_status()
return response_... | Retrieves the design document view information data, returns dictionary
GET databasename/_design/{ddoc}/_info |
def save(self, acl=None, client=None):
"""Save this ACL for the current bucket.
If :attr:`user_project` is set, bills the API request to that project.
:type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list.
:param acl: The ACL object to save. If left blank, this will s... | Save this ACL for the current bucket.
If :attr:`user_project` is set, bills the API request to that project.
:type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list.
:param acl: The ACL object to save. If left blank, this will save
current entries.
... |
def write_input_files(pst):
"""write parameter values to a model input files using a template files with
current parameter values (stored in Pst.parameter_data.parval1).
This is a simple implementation of what PEST does. It does not
handle all the special cases, just a basic function...user beware
... | write parameter values to a model input files using a template files with
current parameter values (stored in Pst.parameter_data.parval1).
This is a simple implementation of what PEST does. It does not
handle all the special cases, just a basic function...user beware
Parameters
----------
pst ... |
def _make_package(binder):
"""Makes an ``.epub.Package`` from a Binder'ish instance."""
package_id = binder.id
if package_id is None:
package_id = hash(binder)
package_name = "{}.opf".format(package_id)
extensions = get_model_extensions(binder)
template_env = jinja2.Environment(trim_... | Makes an ``.epub.Package`` from a Binder'ish instance. |
def check_password_readable(self, section, fields):
"""Check if there is a readable configuration file and print a warning."""
if not fields:
return
# The information which of the configuration files
# included which option is not available. To avoid false positives,
... | Check if there is a readable configuration file and print a warning. |
def classify(self, classifier_name, examples, max_labels=None,
goodness_of_fit=False):
"""Usar un clasificador SVM para etiquetar textos nuevos.
Args:
classifier_name (str): Nombre del clasidicador a usar.
examples (list or str): Se espera un ejemplo o una lista... | Usar un clasificador SVM para etiquetar textos nuevos.
Args:
classifier_name (str): Nombre del clasidicador a usar.
examples (list or str): Se espera un ejemplo o una lista de
ejemplos a clasificar en texto plano o en ids.
max_labels (int, optional): Cantidad... |
def scrnaseq_concatenate_metadata(samples):
"""
Create file same dimension than mtx.colnames
with metadata and sample name to help in the
creation of the SC object.
"""
barcodes = {}
counts = ""
metadata = {}
has_sample_barcodes = False
for sample in dd.sample_data_iterator(samp... | Create file same dimension than mtx.colnames
with metadata and sample name to help in the
creation of the SC object. |
def optimally_align_text(x, y, texts, expand, renderer=None, ax=None,
direction='xy'):
"""
For all text objects find alignment that causes the least overlap with
points and other texts and apply it
"""
if ax is None:
ax = plt.gca()
if renderer is None:
r ... | For all text objects find alignment that causes the least overlap with
points and other texts and apply it |
def _set_helper(self, v, load=False):
"""
Setter method for helper, mapped from YANG variable /rbridge_id/ipv6/router/ospf/graceful_restart/helper (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_helper is considered as a private
method. Backends looking t... | Setter method for helper, mapped from YANG variable /rbridge_id/ipv6/router/ospf/graceful_restart/helper (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_helper is considered as a private
method. Backends looking to populate this variable should
do so via call... |
def get_supported_types():
"""
Return a dictionnary containing types lists supported by the
namespace browser.
Note:
If you update this list, don't forget to update variablexplorer.rst
in spyder-docs
"""
from datetime import date, timedelta
editable_types = [int, float, complex, lis... | Return a dictionnary containing types lists supported by the
namespace browser.
Note:
If you update this list, don't forget to update variablexplorer.rst
in spyder-docs |
def forward_selection(self, data, labels, weights, num_features):
"""Iteratively adds features to the model"""
clf = Ridge(alpha=0, fit_intercept=True, random_state=self.random_state)
used_features = []
for _ in range(min(num_features, data.shape[1])):
max_ = -100000000
... | Iteratively adds features to the model |
def PushSection(self, name, pre_formatters):
"""Given a section name, push it on the top of the stack.
Returns:
The new section, or None if there is no such section.
"""
if name == '@':
value = self.stack[-1].context
else:
value = self.stack[-1].context.get... | Given a section name, push it on the top of the stack.
Returns:
The new section, or None if there is no such section. |
def job_path(cls, project, jobs):
"""Return a fully-qualified job string."""
return google.api_core.path_template.expand(
"projects/{project}/jobs/{jobs}", project=project, jobs=jobs
) | Return a fully-qualified job string. |
def _check_psutil(self, instance):
"""
Gather metrics about connections states and interfaces counters
using psutil facilities
"""
custom_tags = instance.get('tags', [])
if self._collect_cx_state:
self._cx_state_psutil(tags=custom_tags)
self._cx_count... | Gather metrics about connections states and interfaces counters
using psutil facilities |
def get_readme(self, repo):
"""
Checks to see if the given repo has a ReadMe. MD means it has a correct
Readme recognized by GitHub.
"""
readme_contents = repo.readme()
if readme_contents is not None:
self.total_readmes += 1
return 'MD'
if ... | Checks to see if the given repo has a ReadMe. MD means it has a correct
Readme recognized by GitHub. |
def execute(self, sensor_graph, scope_stack):
"""Execute this statement on the sensor_graph given the current scope tree.
This adds a single node to the sensor graph with the trigger_streamer function
as is processing function.
Args:
sensor_graph (SensorGraph): The sensor g... | Execute this statement on the sensor_graph given the current scope tree.
This adds a single node to the sensor graph with the trigger_streamer function
as is processing function.
Args:
sensor_graph (SensorGraph): The sensor graph that we are building or
modifying
... |
def diffusionCount(source, target, sourceType = "raw", extraValue = None, pandasFriendly = False, compareCounts = False, numAuthors = True, useAllAuthors = True, _ProgBar = None, extraMapping = None):
"""Takes in two [RecordCollections](../classes/RecordCollection.html#metaknowledge.RecordCollection) and produces ... | Takes in two [RecordCollections](../classes/RecordCollection.html#metaknowledge.RecordCollection) and produces a `dict` counting the citations of _source_ by the [Records](../classes/Record.html#metaknowledge.Record) of _target_. By default the `dict` uses `Record` objects as keys but this can be changed with the _sour... |
def cancel_current_route(
payment_state: InitiatorPaymentState,
initiator_state: InitiatorTransferState,
) -> List[Event]:
""" Cancel current route.
This allows a new route to be tried.
"""
assert can_cancel(initiator_state), 'Cannot cancel a route after the secret is revealed'
tra... | Cancel current route.
This allows a new route to be tried. |
def unlock_file(filename):
'''
Unlock a locked file
Note that these locks are only recognized by Salt Cloud, and not other
programs or platforms.
'''
log.trace('Removing lock for %s', filename)
lock = filename + '.lock'
try:
os.remove(lock)
except OSError as exc:
log... | Unlock a locked file
Note that these locks are only recognized by Salt Cloud, and not other
programs or platforms. |
def rm_auth_key_from_file(user,
source,
config='.ssh/authorized_keys',
saltenv='base',
fingerprint_hash_type=None):
'''
Remove an authorized key from the specified user's authorized key file,
using a file... | Remove an authorized key from the specified user's authorized key file,
using a file as source
CLI Example:
.. code-block:: bash
salt '*' ssh.rm_auth_key_from_file <user> salt://ssh_keys/<user>.id_rsa.pub |
def get_valid_time_stamp():
"""
Get a valid time stamp without illegal characters.
Adds time_ to make the time stamp a valid table name in sql.
:return: String, extracted timestamp
"""
time_stamp = str(datetime.datetime.now())
time_stamp = "time_" + time_stamp.replace("-", "_").replace(":", ... | Get a valid time stamp without illegal characters.
Adds time_ to make the time stamp a valid table name in sql.
:return: String, extracted timestamp |
def predict_class(self, features):
"""
Model inference base on the given data which returning label
:param features: it can be a ndarray or list of ndarray for locally inference
or RDD[Sample] for running in distributed fashion
:return: ndarray or RDD[Sample] dep... | Model inference base on the given data which returning label
:param features: it can be a ndarray or list of ndarray for locally inference
or RDD[Sample] for running in distributed fashion
:return: ndarray or RDD[Sample] depend on the the type of features. |
def spi_configure_mode(self, spi_mode):
"""Configure the SPI interface by the well known SPI modes."""
if spi_mode == SPI_MODE_0:
self.spi_configure(SPI_POL_RISING_FALLING,
SPI_PHASE_SAMPLE_SETUP, SPI_BITORDER_MSB)
elif spi_mode == SPI_MODE_3:
self.spi... | Configure the SPI interface by the well known SPI modes. |
def get(self, sid):
"""
Constructs a EngagementContext
:param sid: Engagement Sid.
:returns: twilio.rest.studio.v1.flow.engagement.EngagementContext
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext
"""
return EngagementContext(self._version, flow_... | Constructs a EngagementContext
:param sid: Engagement Sid.
:returns: twilio.rest.studio.v1.flow.engagement.EngagementContext
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext |
def get_doctype(self, index, name):
"""
Returns a doctype given an index and a name
"""
if index not in self.indices:
self.get_all_indices()
return self.indices.get(index, {}).get(name, None) | Returns a doctype given an index and a name |
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_migrate_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(ge... | Auto Generated Code |
def _add_subscribers_for_type(self, callback_type, subscribers, callbacks, **kwargs):
''' add a done/queued/progress callback to the appropriate list '''
for subscriber in subscribers:
callback_name = 'on_' + callback_type
if hasattr(subscriber, callback_name):
_f... | add a done/queued/progress callback to the appropriate list |
def region_path(cls, project, region):
"""Return a fully-qualified region string."""
return google.api_core.path_template.expand(
"projects/{project}/regions/{region}", project=project, region=region
) | Return a fully-qualified region string. |
def wrpcap(filename, pkt, *args, **kargs):
"""Write a list of packets to a pcap file
gz: set to 1 to save a gzipped capture
linktype: force linktype value
endianness: "<" or ">", force endianness"""
with PcapWriter(filename, *args, **kargs) as pcap:
pcap.write(pkt) | Write a list of packets to a pcap file
gz: set to 1 to save a gzipped capture
linktype: force linktype value
endianness: "<" or ">", force endianness |
def rule_command_cmdlist_interface_s_interface_fc_leaf_interface_fibrechannel_leaf(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa")
index_key = ET.SubElement(rule, "index")
... | Auto Generated Code |
def _check_frames(self, frames, fill_value):
"""Reduce frames to no more than are available in the file."""
if self.seekable():
remaining_frames = self.frames - self.tell()
if frames < 0 or (frames > remaining_frames and
fill_value is None):
... | Reduce frames to no more than are available in the file. |
def vertex_graph(entities):
"""
Given a set of entity objects generate a networkx.Graph
that represents their vertex nodes.
Parameters
--------------
entities : list
Objects with 'closed' and 'nodes' attributes
Returns
-------------
graph : networkx.Graph
Graph where... | Given a set of entity objects generate a networkx.Graph
that represents their vertex nodes.
Parameters
--------------
entities : list
Objects with 'closed' and 'nodes' attributes
Returns
-------------
graph : networkx.Graph
Graph where node indexes represent vertices
clo... |
def setup_logging(log_file=os.devnull):
"""
Configures logging.
By default logs from all workers are printed to the console, entries are
prefixed with "N: " where N is the rank of the worker. Logs printed to the
console don't include timestaps.
Full logs with timestamps are saved to the log_file... | Configures logging.
By default logs from all workers are printed to the console, entries are
prefixed with "N: " where N is the rank of the worker. Logs printed to the
console don't include timestaps.
Full logs with timestamps are saved to the log_file file. |
def get_evernote_notes(self, evernote_filter):
"""
get the notes related to the filter
:param evernote_filter: filtering
:return: notes
"""
data = []
note_store = self.client.get_note_store()
our_note_list = note_store.findNotesMetadata(self.t... | get the notes related to the filter
:param evernote_filter: filtering
:return: notes |
def _ParseFileEntry(self, knowledge_base, file_entry):
"""Parses artifact file system data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_entry (dfvfs.FileEntry): file entry that contains the artifact
value data.
Rais... | Parses artifact file system data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_entry (dfvfs.FileEntry): file entry that contains the artifact
value data.
Raises:
errors.PreProcessFail: if the preprocessing fails. |
def by(self, technology):
"""
Get the plugins registered in PedalPi by technology
:param PluginTechnology technology: PluginTechnology identifier
"""
if technology == PluginTechnology.LV2 \
or str(technology).upper() == PluginTechnology.LV2.value.upper():
ret... | Get the plugins registered in PedalPi by technology
:param PluginTechnology technology: PluginTechnology identifier |
def node_received_infos(node_id):
"""Get all the infos a node has been sent and has received.
You must specify the node id in the url.
You can also pass the info type.
"""
exp = Experiment(session)
# get the parameters
info_type = request_parameter(
parameter="info_type", parameter... | Get all the infos a node has been sent and has received.
You must specify the node id in the url.
You can also pass the info type. |
def rank(self):
"""
Return the rank of the given hypergraph.
@rtype: int
@return: Rank of graph.
"""
max_rank = 0
for each in self.hyperedges():
if len(self.edge_links[each]) > max_rank:
max_rank = len(self.edge_links... | Return the rank of the given hypergraph.
@rtype: int
@return: Rank of graph. |
def _approx_eq_(self, other: Any, atol: Union[int, float]) -> bool:
"""See `cirq.protocols.SupportsApproximateEquality`."""
if not isinstance(other, type(self)):
return NotImplemented
return approx_eq(self.operations, other.operations, atol=atol) | See `cirq.protocols.SupportsApproximateEquality`. |
def teardown(self):
'''Teardown trust domain by removing trusted devices.'''
for device in self.devices:
self._remove_trustee(device)
self._populate_domain()
self.domain = {} | Teardown trust domain by removing trusted devices. |
def _get_cookie(self, name, domain):
''' Return the cookie "name" for "domain" if found
If there are mote than one, only the first is returned
'''
for c in self.session.cookies:
if c.name==name and c.domain==domain:
return c
return None | Return the cookie "name" for "domain" if found
If there are mote than one, only the first is returned |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
app_conf = dci_config.generate_conf()
connectable = dci_config.get_engine(app_conf)
with connectable.connect() as connection:
... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. |
def _server_rollback():
"""Removes script database and archive files to rollback the CI server
installation.
"""
#Remove the data and archive files specified in settings. The cron
#gets remove by the _setup_server() script if -rollback is specified.
from os import path, remove
archpath = pat... | Removes script database and archive files to rollback the CI server
installation. |
def add_observer(self, o, component_type=ComponentType):
"""
Add a callback that will get invoked after each component is called.
Args:
o (func): the callback function
Keyword Args:
component_type (ComponentType): the :class:`ComponentType` to observe.
... | Add a callback that will get invoked after each component is called.
Args:
o (func): the callback function
Keyword Args:
component_type (ComponentType): the :class:`ComponentType` to observe.
The callback will fire any time an instance of the class or its
... |
def register(self, hash_types):
"""
Registers a function to generate a hash for data of the appropriate
types. This can be used to register custom classes. Internally this is
used to define how to hash non-builtin objects like ndarrays and uuids.
The registered function should r... | Registers a function to generate a hash for data of the appropriate
types. This can be used to register custom classes. Internally this is
used to define how to hash non-builtin objects like ndarrays and uuids.
The registered function should return a tuple of bytes. First a small
prefix... |
def _prep_window(self, **kwargs):
"""
Provide validation for our window type, return the window
we have already been validated.
"""
window = self._get_window()
if isinstance(window, (list, tuple, np.ndarray)):
return com.asarray_tuplesafe(window).astype(float... | Provide validation for our window type, return the window
we have already been validated. |
def build_getters_support_matrix(app):
"""Build the getters support matrix."""
status = subprocess.call("./test.sh", stdout=sys.stdout, stderr=sys.stderr)
if status != 0:
print("Something bad happened when processing the test reports.")
sys.exit(-1)
drivers = set()
matrix = {
... | Build the getters support matrix. |
def present(self, value):
"""Return a user-friendly representation of a value.
Lookup value in self.specials, or call .to_literal() if absent.
"""
for k, v in self.special.items():
if v == value:
return k
return ''.join(self.get_separator(i) +... | Return a user-friendly representation of a value.
Lookup value in self.specials, or call .to_literal() if absent. |
async def spawn_n(self, agent_cls, n, *args, addr=None, **kwargs):
"""Same as :meth:`~creamas.mp.MultiEnvironment.spawn`, but allows
spawning multiple agents with the same initialization parameters
simultaneously into **one** slave environment.
:param str agent_cls:
``qualna... | Same as :meth:`~creamas.mp.MultiEnvironment.spawn`, but allows
spawning multiple agents with the same initialization parameters
simultaneously into **one** slave environment.
:param str agent_cls:
``qualname`` of the agent class. That is, the name should be in the
form o... |
def deserialize_object(buffers, g=None):
"""Reconstruct an object serialized by serialize_object from data buffers.
Parameters
----------
bufs : list of buffers/bytes
g : globals to be used when uncanning
Returns
-------
(newobj, bufs) : unpacked object, and the list of remaining un... | Reconstruct an object serialized by serialize_object from data buffers.
Parameters
----------
bufs : list of buffers/bytes
g : globals to be used when uncanning
Returns
-------
(newobj, bufs) : unpacked object, and the list of remaining unused buffers. |
def _get_bucket_endpoint(self):
"""
Queries S3 to identify the region hosting the provided bucket.
"""
conn = S3Connection()
bucket = conn.lookup(self.bucket_name)
if not bucket:
# TODO: Make the bucket here?
raise InputParameterError('The provided... | Queries S3 to identify the region hosting the provided bucket. |
def subslice(inner,outer,section):
'helper for rediff\
outer is a slice (2-tuple, not an official python slice) in global coordinates\
inner is a slice (2-tuple) on that slice\
returns the result of sub-slicing outer by inner'
# todo: think about constraints here. inner and outer ordered, inner[1] less t... | helper for rediff\
outer is a slice (2-tuple, not an official python slice) in global coordinates\
inner is a slice (2-tuple) on that slice\
returns the result of sub-slicing outer by inner |
def post_card(message,
hook_url=None,
title=None,
theme_color=None):
'''
Send a message to an MS Teams channel.
:param message: The message to send to the MS Teams channel.
:param hook_url: The Teams webhook URL, if not specified in the configuration.
... | Send a message to an MS Teams channel.
:param message: The message to send to the MS Teams channel.
:param hook_url: The Teams webhook URL, if not specified in the configuration.
:param title: Optional title for the posted card
:param theme_color: Optional hex color highlight for the poste... |
def edit_prefix(self, auth, spec, attr):
""" Update prefix matching `spec` with attributes `attr`.
* `auth` [BaseAuth]
AAA options.
* `spec` [prefix_spec]
Specifies the prefix to edit.
* `attr` [prefix_attr]
Prefix attributes.
... | Update prefix matching `spec` with attributes `attr`.
* `auth` [BaseAuth]
AAA options.
* `spec` [prefix_spec]
Specifies the prefix to edit.
* `attr` [prefix_attr]
Prefix attributes.
Note that there are restrictions on when... |
def help_box():
"""A simple HTML help dialog box using the distribution data files."""
style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
dialog_box = wx.Dialog(None, wx.ID_ANY, HELP_TITLE,
style=style, size=(620, 450))
html_widget = HtmlHelp(dialog_box, wx.ID_ANY)
html_wi... | A simple HTML help dialog box using the distribution data files. |
def remove_network_from_dhcp_agent(self, dhcp_agent, network_id):
"""Remove a network from dhcp agent."""
return self.delete((self.agent_path + self.DHCP_NETS + "/%s") % (
dhcp_agent, network_id)) | Remove a network from dhcp agent. |
def _write_frame(self, data):
"""Write a frame to the PN532 with the specified data bytearray."""
assert data is not None and 0 < len(data) < 255, 'Data must be array of 1 to 255 bytes.'
# Build frame to send as:
# - SPI data write (0x01)
# - Preamble (0x00)
# - Start cod... | Write a frame to the PN532 with the specified data bytearray. |
def form_valid(self, form):
"""After the form is valid lets let people know"""
ret = super(ProjectCopy, self).form_valid(form)
self.copy_relations()
# Good to make note of that
messages.add_message(self.request, messages.SUCCESS, 'Project %s copied' % self.object.name)
... | After the form is valid lets let people know |
def get_scheduling_block_ids():
"""Return list of scheduling block IDs"""
ids = [key.split('/')[-1]
for key in DB.keys(pattern='scheduling_block/*')]
return sorted(ids) | Return list of scheduling block IDs |
def cfg_folder_loader(path):
"""
:type path: str
"""
CFG_WILDCARD = '*.yaml'
return [load_cfg(filename) for filename in sorted(glob.glob(os.path.join(path, CFG_WILDCARD)))] | :type path: str |
def _poll(self):
"""
Poll Trusted Advisor (Support) API for limit checks.
Return a dict of service name (string) keys to nested dict vals, where
each key is a limit name and each value the current numeric limit.
e.g.:
::
{
'EC2': {
... | Poll Trusted Advisor (Support) API for limit checks.
Return a dict of service name (string) keys to nested dict vals, where
each key is a limit name and each value the current numeric limit.
e.g.:
::
{
'EC2': {
'SomeLimit': 10,
... |
def Parse(self, conditions, host_data):
"""Runs methods that evaluate whether collected host_data has an issue.
Args:
conditions: A list of conditions to determine which Methods to trigger.
host_data: A map of artifacts and rdf data.
Returns:
A CheckResult populated with Anomalies if an ... | Runs methods that evaluate whether collected host_data has an issue.
Args:
conditions: A list of conditions to determine which Methods to trigger.
host_data: A map of artifacts and rdf data.
Returns:
A CheckResult populated with Anomalies if an issue exists. |
def install(pkg=None,
pkgs=None,
dir=None,
runas=None,
registry=None,
env=None,
dry_run=False,
silent=True):
'''
Install an NPM package.
If no directory is specified, the package will be installed globally. If
no packag... | Install an NPM package.
If no directory is specified, the package will be installed globally. If
no package is specified, the dependencies (from package.json) of the
package in the given directory will be installed.
pkg
A package name in any format accepted by NPM, including a version
... |
def create_window(self, pane, name=None, set_active=True):
"""
Create a new window that contains just this pane.
:param pane: The :class:`.Pane` instance to put in the new window.
:param name: If given, name for the new window.
:param set_active: When True, focus the new window.... | Create a new window that contains just this pane.
:param pane: The :class:`.Pane` instance to put in the new window.
:param name: If given, name for the new window.
:param set_active: When True, focus the new window. |
def load_targets(explanatory_rasters):
"""
Parameters
----------
explanatory_rasters : List of Paths to GDAL rasters containing explanatory variables
Returns
-------
expl : Array of explanatory variables
raster_info : dict of raster info
"""
explanatory_raster_arrays = []
a... | Parameters
----------
explanatory_rasters : List of Paths to GDAL rasters containing explanatory variables
Returns
-------
expl : Array of explanatory variables
raster_info : dict of raster info |
def run_cmd(cmd):
"""
Run a command in a subprocess, given as a list of command-line
arguments.
Returns a ``(returncode, stdout, stderr)`` tuple.
"""
try:
p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
# XXX: May block if either stdout or stderr fill their buffers;
#... | Run a command in a subprocess, given as a list of command-line
arguments.
Returns a ``(returncode, stdout, stderr)`` tuple. |
def use_federated_bank_view(self):
"""Pass through to provider ItemLookupSession.use_federated_bank_view"""
self._bank_view = FEDERATED
# self._get_provider_session('item_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
try:... | Pass through to provider ItemLookupSession.use_federated_bank_view |
def install(name=None,
fromrepo=None,
pkgs=None,
sources=None,
jail=None,
chroot=None,
root=None,
orphan=False,
force=False,
glob=False,
local=False,
dryrun=False,
quiet=False,... | Install package(s) from a repository
name
The name of the package to install
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
jail
Install the package into the specified jail
chroot
Install the package into the specified chroot (... |
def submitter(self):
"""
| Comment: The user who submitted the ticket. The submitter always becomes the author of the first comment on the ticket
"""
if self.api and self.submitter_id:
return self.api._get_user(self.submitter_id) | | Comment: The user who submitted the ticket. The submitter always becomes the author of the first comment on the ticket |
def load(self, steps_dir=None, step_file=None, step_list=None):
"""Load CWL steps into the WorkflowGenerator's steps library.
Adds steps (command line tools and workflows) to the
``WorkflowGenerator``'s steps library. These steps can be used to
create workflows.
Args:
... | Load CWL steps into the WorkflowGenerator's steps library.
Adds steps (command line tools and workflows) to the
``WorkflowGenerator``'s steps library. These steps can be used to
create workflows.
Args:
steps_dir (str): path to directory containing CWL files. All CWL in
... |
def signature_type(self):
"""Return the signature type used in this MAR.
Returns:
One of None, 'unknown', 'sha1', or 'sha384'
"""
if not self.mardata.signatures:
return None
for sig in self.mardata.signatures.sigs:
if sig.algorithm_id == 1:
... | Return the signature type used in this MAR.
Returns:
One of None, 'unknown', 'sha1', or 'sha384' |
def unfix(self, param):
"""
Enable parameter optimization.
Parameters
----------
param : str
Possible values are ``"delta"``, ``"beta"``, and ``"scale"``.
"""
if param == "delta":
self._unfix("logistic")
else:
self._fix... | Enable parameter optimization.
Parameters
----------
param : str
Possible values are ``"delta"``, ``"beta"``, and ``"scale"``. |
def set_input_data(self, key, value):
"""
set_input_data will automatically create an input channel if necessary.
Automatic channel creation is intended for the case where users are trying to set initial values on a block
whose input channels aren't subscribed to anything in the graph.
... | set_input_data will automatically create an input channel if necessary.
Automatic channel creation is intended for the case where users are trying to set initial values on a block
whose input channels aren't subscribed to anything in the graph. |
def link_for_image(self, base_dir: str, conf: Config) -> int:
"""Link all artifacts required for a Docker image under `base_dir` and
return the number of linked artifacts."""
return self.link_types(
base_dir,
[ArtifactType.app, ArtifactType.binary, ArtifactType.gen_py]... | Link all artifacts required for a Docker image under `base_dir` and
return the number of linked artifacts. |
def link(self, thing1, thing2):
"""
Link thing1 and thing2, adding the karma of each into
a single entry.
If any thing does not exist, it is created.
"""
thing1 = thing1.strip().lower()
thing2 = thing2.strip().lower()
if thing1 == thing2:
raise SameName("Attempted to link two of the same name")
sel... | Link thing1 and thing2, adding the karma of each into
a single entry.
If any thing does not exist, it is created. |
def show_support_save_status_output_show_support_save_status_message(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_support_save_status = ET.Element("show_support_save_status")
config = show_support_save_status
output = ET.SubElement(show_s... | Auto Generated Code |
def compute_auth_key(userid, password):
"""
Compute the authentication key for freedns.afraid.org.
This is the SHA1 hash of the string b'userid|password'.
:param userid: ascii username
:param password: ascii password
:return: ascii authentication key (SHA1 at this point)
"""
import sys... | Compute the authentication key for freedns.afraid.org.
This is the SHA1 hash of the string b'userid|password'.
:param userid: ascii username
:param password: ascii password
:return: ascii authentication key (SHA1 at this point) |
def get_all_profiles(store='local'):
'''
Gets all properties for all profiles in the specified store
Args:
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
... | Gets all properties for all profiles in the specified store
Args:
store (str):
The store to use. This is either the local firewall policy or the
policy defined by local group policy. Valid options are:
- lgpo
- local
Default is ``local``
R... |
def storages(self):
"""This property gets the list of instances for Storages
This property gets the list of instances for Storages
:returns: a list of instances of Storages
"""
return storage.StorageCollection(
self._conn, utils.get_subresource_path_by(self, 'Storage... | This property gets the list of instances for Storages
This property gets the list of instances for Storages
:returns: a list of instances of Storages |
def make_psrrates(pkllist, nbins=60, period=0.156):
""" Visualize cands in set of pkl files from pulsar observations.
Input pkl list assumed to start with on-axis pulsar scan, followed by off-axis scans.
nbins for output histogram. period is pulsar period in seconds (used to find single peak for cluster of ... | Visualize cands in set of pkl files from pulsar observations.
Input pkl list assumed to start with on-axis pulsar scan, followed by off-axis scans.
nbins for output histogram. period is pulsar period in seconds (used to find single peak for cluster of detections). |
def Detect(self, baseline, host_data):
"""Run host_data through detectors and return them if a detector triggers.
Args:
baseline: The base set of rdf values used to evaluate whether an issue
exists.
host_data: The rdf values passed back by the filters.
Returns:
A CheckResult mess... | Run host_data through detectors and return them if a detector triggers.
Args:
baseline: The base set of rdf values used to evaluate whether an issue
exists.
host_data: The rdf values passed back by the filters.
Returns:
A CheckResult message containing anomalies if any detectors iden... |
def get_instance(self, payload):
"""
Build an instance of ConnectAppInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance
:rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance
""... | Build an instance of ConnectAppInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance
:rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppInstance |
def dqdv_cycle(cycle, splitter=True, **kwargs):
"""Convenience functions for creating dq-dv data from given capacity and
voltage cycle.
Returns the a DataFrame with a 'voltage' and a 'incremental_capacity'
column.
Args:
cycle (pandas.DataFrame): the cycle data ('voltage', 'capacity... | Convenience functions for creating dq-dv data from given capacity and
voltage cycle.
Returns the a DataFrame with a 'voltage' and a 'incremental_capacity'
column.
Args:
cycle (pandas.DataFrame): the cycle data ('voltage', 'capacity',
'direction' (1 or -1)).
... |
def deleteRole(self, *args, **kwargs):
"""
Delete Role
Delete a role. This operation will succeed regardless of whether or not
the role exists.
This method is ``stable``
"""
return self._makeApiCall(self.funcinfo["deleteRole"], *args, **kwargs) | Delete Role
Delete a role. This operation will succeed regardless of whether or not
the role exists.
This method is ``stable`` |
def filter(self, source_file, encoding): # noqa A001
"""Parse file."""
with codecs.open(source_file, 'r', encoding=encoding) as f:
text = f.read()
return [filters.SourceText(self._filter(text), source_file, encoding, 'context')] | Parse file. |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._color is not None:
return False
if self._alias is not None:
return False
if self._description is not None:
return False
if self._attachment is not None:
... | :rtype: bool |
def add(self, data_source, module, package=None):
"""
Add data_source to model. Tries to import module, then looks for data
source class definition.
:param data_source: Name of data source to add.
:type data_source: str
:param module: Module in which data source resides.... | Add data_source to model. Tries to import module, then looks for data
source class definition.
:param data_source: Name of data source to add.
:type data_source: str
:param module: Module in which data source resides. Can be absolute or
relative. See :func:`importlib.import_... |
def clone(self, callable=None, **overrides):
"""Clones the Callable optionally with new settings
Args:
callable: New callable function to wrap
**overrides: Parameter overrides to apply
Returns:
Cloned Callable object
"""
old = {k: v for k, v ... | Clones the Callable optionally with new settings
Args:
callable: New callable function to wrap
**overrides: Parameter overrides to apply
Returns:
Cloned Callable object |
def do_hit(self, arg):
"""
Usage:
hit create [<numWorkers> <reward> <duration>]
hit extend <HITid> [(--assignments <number>)] [(--expiration <minutes>)]
hit expire (--all | <HITid> ...)
hit dispose (--all | <HITid> ...)
hit delete (--all | <HITid> ...)
... | Usage:
hit create [<numWorkers> <reward> <duration>]
hit extend <HITid> [(--assignments <number>)] [(--expiration <minutes>)]
hit expire (--all | <HITid> ...)
hit dispose (--all | <HITid> ...)
hit delete (--all | <HITid> ...)
hit list [--active | --reviewable]... |
def single(self, predicate):
"""
Returns single element that matches given predicate.
Raises:
* NoMatchingElement error if no matching elements are found
* MoreThanOneMatchingElement error if more than one matching
element is found
:param predicate: pr... | Returns single element that matches given predicate.
Raises:
* NoMatchingElement error if no matching elements are found
* MoreThanOneMatchingElement error if more than one matching
element is found
:param predicate: predicate as a lambda expression
:return: M... |
def cmd(send, msg, args):
"""Gets the location of a ZIP code
Syntax: {command} (zipcode)
Powered by STANDS4, www.stands4.com
"""
uid = args['config']['api']['stands4uid']
token = args['config']['api']['stands4token']
parser = arguments.ArgParser(args['config'])
parser.add_argument('zipco... | Gets the location of a ZIP code
Syntax: {command} (zipcode)
Powered by STANDS4, www.stands4.com |
def sendCommands(comPort, commands):
"""Send X10 commands using the FireCracker on comPort
comPort should be the name of a serial port on the host platform. On
Windows, for example, 'com1'.
commands should be a string consisting of X10 commands separated by
commas. For example. 'A1 On, A Dim, A Di... | Send X10 commands using the FireCracker on comPort
comPort should be the name of a serial port on the host platform. On
Windows, for example, 'com1'.
commands should be a string consisting of X10 commands separated by
commas. For example. 'A1 On, A Dim, A Dim, A Dim, A Lamps Off'. The
letter is a ... |
def monitor(self, name, cb, request=None, notify_disconnect=False, queue=None):
"""Create a subscription.
:param str name: PV name string
:param callable cb: Processing callback
:param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default.
... | Create a subscription.
:param str name: PV name string
:param callable cb: Processing callback
:param request: A :py:class:`p4p.Value` or string to qualify this request, or None to use a default.
:param bool notify_disconnect: In additional to Values, the callback may also be call with ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.