Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
13,500 | def zeq_magic(meas_file=, spec_file=,crd=,input_dir_path=, angle=0,
n_plots=5, save_plots=True, fmt="svg", interactive=False, specimen="",
samp_file=, contribution=None,fignum=1):
def plot_interpretations(ZED, spec_container, this_specimen, this_specimen_measurements, datablock):
... | 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... |
13,501 | def before_insert(mapper, conn, target):
target._set_ids()
if target.name and target.vname and target.cache_key and target.fqname and not target.dataset:
return
Partition.before_update(mapper, conn, target) | event.listen method for Sqlalchemy to set the sequence for this
object and create an ObjectNumber value for the id_ |
13,502 | def _get_stddev_deep_soil(self, mag, imt):
if mag > 7:
mag = 7
C = self.COEFFS_SOIL[imt]
return C[] + C[] * mag | Calculate and return total standard deviation for deep soil sites.
Implements formulae from the last column of table 4. |
13,503 | def get_subgraph(self, name):
match = list()
if name in self.obj_dict[]:
sgraphs_obj_dict = self.obj_dict[].get( name )
for obj_dict_list in sgraphs_obj_dict:
match.append( Subgraph( obj_dict = obj_dict_list ) )
... | 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. |
13,504 | def txn(self, overwrite=False, lock=True):
if lock:
self._lock.acquire()
try:
new_state, existing_generation = self.state_and_generation
new_state = copy.deepcopy(new_state)
yield new_state
if overwrite:
existing_genera... | Context manager for a state modification transaction. |
13,505 | def from_env(cls, reactor=None, env=os.environ):
address = env.get(, )
token = env.get(, )
ca_cert = env.get()
tls_server_name = env.get()
client_cert = env.get()
client_key = env.get()
cf = ClientPolicyForHTTPS.from_pem_files(
caKey... | 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:
-... |
13,506 | def io_surface(timestep, time, fid, fld):
fid.write("{} {}".format(timestep, time))
fid.writelines(["%10.2e" % item for item in fld[:]])
fid.writelines(["\n"]) | Output for surface files |
13,507 | def info(self):
ddoc_info = self.r_session.get(
.join([self.document_url, ]))
ddoc_info.raise_for_status()
return response_to_json_dict(ddoc_info) | Retrieves the design document view information data, returns dictionary
GET databasename/_design/{ddoc}/_info |
13,508 | def save(self, acl=None, client=None):
if acl is None:
acl = self
save_to_backend = acl.loaded
else:
save_to_backend = True
if save_to_backend:
self._save(acl, None, client) | 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.
... |
13,509 | def write_input_files(pst):
par = pst.parameter_data
par.loc[:,"parval1_trans"] = (par.parval1 * par.scale) + par.offset
for tpl_file,in_file in zip(pst.template_files,pst.input_files):
write_to_template(pst.parameter_data.parval1_trans,tpl_file,in_file) | 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 ... |
13,510 | def _make_package(binder):
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_blocks=True, lstrip_blocks=True)
items = []
... | Makes an ``.epub.Package`` from a Binder'ish instance. |
13,511 | def check_password_readable(self, section, fields):
if not fields:
return
if len(self.read_ok) != 1:
return
fn = self.read_ok[0]
if fileutil.is_accessable_by_others(fn):
log.warn(LOG_CHECK, "The configuration file %s... | Check if there is a readable configuration file and print a warning. |
13,512 | def classify(self, classifier_name, examples, max_labels=None,
goodness_of_fit=False):
classifier = getattr(self, classifier_name)
texts_vectors = self._make_text_vectors(examples)
return classifier.classes_, classifier.decision_function(texts_vectors) | 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... |
13,513 | def scrnaseq_concatenate_metadata(samples):
barcodes = {}
counts = ""
metadata = {}
has_sample_barcodes = False
for sample in dd.sample_data_iterator(samples):
if dd.get_sample_barcodes(sample):
has_sample_barcodes = True
with open(dd.get_sample_barcodes(sample)... | Create file same dimension than mtx.colnames
with metadata and sample name to help in the
creation of the SC object. |
13,514 | def optimally_align_text(x, y, texts, expand, renderer=None, ax=None,
direction=):
if ax is None:
ax = plt.gca()
if renderer is None:
r = ax.get_figure().canvas.get_renderer()
else:
r = renderer
bboxes = get_bboxes(texts, r, expand)
if not in di... | For all text objects find alignment that causes the least overlap with
points and other texts and apply it |
13,515 | def _set_helper(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=helper.helper, is_container=, presence=False, yang_name="helper", rest_name="helper", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensi... | 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... |
13,516 | def get_supported_types():
from datetime import date, timedelta
editable_types = [int, float, complex, list, set, dict, tuple, date,
timedelta] + list(TEXT_TYPES) + list(INT_TYPES)
try:
from numpy import ndarray, matrix, generic
editable_types += [ndarray, matrix, ... | 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 |
13,517 | def forward_selection(self, data, labels, weights, num_features):
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
best = 0
for feature in r... | Iteratively adds features to the model |
13,518 | def PushSection(self, name, pre_formatters):
if name == :
value = self.stack[-1].context
else:
value = self.stack[-1].context.get(name)
for i, (f, args, formatter_type) in enumerate(pre_formatters):
if formatter_type == ENHANCED_FUNC... | Given a section name, push it on the top of the stack.
Returns:
The new section, or None if there is no such section. |
13,519 | def job_path(cls, project, jobs):
return google.api_core.path_template.expand(
"projects/{project}/jobs/{jobs}", project=project, jobs=jobs
) | Return a fully-qualified job string. |
13,520 | def _check_psutil(self, instance):
custom_tags = instance.get(, [])
if self._collect_cx_state:
self._cx_state_psutil(tags=custom_tags)
self._cx_counters_psutil(tags=custom_tags) | Gather metrics about connections states and interfaces counters
using psutil facilities |
13,521 | def get_readme(self, repo):
readme_contents = repo.readme()
if readme_contents is not None:
self.total_readmes += 1
return
if self.search_limit >= 28:
print
time.sleep(60)
self.search_limit = 0
self.search_limit += 1
... | Checks to see if the given repo has a ReadMe. MD means it has a correct
Readme recognized by GitHub. |
13,522 | def execute(self, sensor_graph, scope_stack):
parent = scope_stack[-1]
alloc = parent.allocator
output = alloc.allocate_stream(DataStream.UnbufferedType, attach=True)
trigger_stream, trigger_cond = parent.trigger_chain()
streamer_const = alloc.allocate_stream... | 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
... |
13,523 | def diffusionCount(source, target, sourceType = "raw", extraValue = None, pandasFriendly = False, compareCounts = False, numAuthors = True, useAllAuthors = True, _ProgBar = None, extraMapping = None):
sourceCountString = "SourceCount"
targetCountString = "TargetCount"
if not isinstance(sourceType, str... | 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... |
13,524 | def cancel_current_route(
payment_state: InitiatorPaymentState,
initiator_state: InitiatorTransferState,
) -> List[Event]:
assert can_cancel(initiator_state),
transfer_description = initiator_state.transfer_description
payment_state.cancelled_channels.append(initiator_state.channel_i... | Cancel current route.
This allows a new route to be tried. |
13,525 | def unlock_file(filename):
log.trace(, filename)
lock = filename +
try:
os.remove(lock)
except OSError as exc:
log.trace(, filename, exc) | Unlock a locked file
Note that these locks are only recognized by Salt Cloud, and not other
programs or platforms. |
13,526 | def rm_auth_key_from_file(user,
source,
config=,
saltenv=,
fingerprint_hash_type=None):
s authorized key file,
using a file as source
CLI Example:
.. code-block:: bash
salt ssh.rm_auth_key... | 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 |
13,527 | def get_valid_time_stamp():
time_stamp = str(datetime.datetime.now())
time_stamp = "time_" + time_stamp.replace("-", "_").replace(":", "_").replace(" ", "_").replace(".", "_")
return 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 |
13,528 | def predict_class(self, features):
if isinstance(features, RDD):
return self.predict_class_distributed(features)
else:
return self.predict_class_local(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] depend on the the type of features. |
13,529 | def spi_configure_mode(self, spi_mode):
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(SPI_POL_FALLING_RISING,
SPI_PHA... | Configure the SPI interface by the well known SPI modes. |
13,530 | def get(self, sid):
return EngagementContext(self._version, flow_sid=self._solution[], sid=sid, ) | Constructs a EngagementContext
:param sid: Engagement Sid.
:returns: twilio.rest.studio.v1.flow.engagement.EngagementContext
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementContext |
13,531 | def get_doctype(self, index, 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 |
13,532 | def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_migrate_time(self, **kwargs):
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
... | Auto Generated Code |
13,533 | def _add_subscribers_for_type(self, callback_type, subscribers, callbacks, **kwargs):
for subscriber in subscribers:
callback_name = + callback_type
if hasattr(subscriber, callback_name):
_function = functools.partial(getattr(subscriber, callback_name), **kwargs... | add a done/queued/progress callback to the appropriate list |
13,534 | def region_path(cls, project, region):
return google.api_core.path_template.expand(
"projects/{project}/regions/{region}", project=project, region=region
) | Return a fully-qualified region string. |
13,535 | def wrpcap(filename, pkt, *args, **kargs):
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 |
13,536 | def rule_command_cmdlist_interface_s_interface_fc_leaf_interface_fibrechannel_leaf(self, **kwargs):
config = ET.Element("config")
rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa")
index_key = ET.SubElement(rule, "index")
index_key.text = kwargs.pop()... | Auto Generated Code |
13,537 | def _check_frames(self, frames, fill_value):
if self.seekable():
remaining_frames = self.frames - self.tell()
if frames < 0 or (frames > remaining_frames and
fill_value is None):
frames = remaining_frames
elif frames < 0:
... | Reduce frames to no more than are available in the file. |
13,538 | def vertex_graph(entities):
graph = nx.Graph()
closed = []
for index, entity in enumerate(entities):
if entity.closed:
closed.append(index)
else:
graph.add_edges_from(entity.nodes,
entity_index=index)
return graph, np.array(cl... | 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... |
13,539 | def setup_logging(log_file=os.devnull):
class RankFilter(logging.Filter):
def __init__(self, rank):
self.rank = rank
def filter(self, record):
record.rank = self.rank
return True
rank = get_rank()
rank_filter = RankFilter(rank)
logging_format =... | 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. |
13,540 | def get_evernote_notes(self, evernote_filter):
data = []
note_store = self.client.get_note_store()
our_note_list = note_store.findNotesMetadata(self.token, evernote_filter, 0, 100,
EvernoteMgr.set_evernote_spec())
for note i... | get the notes related to the filter
:param evernote_filter: filtering
:return: notes |
13,541 | def _ParseFileEntry(self, knowledge_base, file_entry):
root_key = self._GetPlistRootKey(file_entry)
if not root_key:
location = getattr(file_entry.path_spec, , )
raise errors.PreProcessFail((
).format(self.ARTIFACT_DEFINITION_NAME, location))
try:
match = self._G... | 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. |
13,542 | def by(self, technology):
if technology == PluginTechnology.LV2 \
or str(technology).upper() == PluginTechnology.LV2.value.upper():
return self.lv2_builder.all
else:
return [] | Get the plugins registered in PedalPi by technology
:param PluginTechnology technology: PluginTechnology identifier |
13,543 | def node_received_infos(node_id):
exp = Experiment(session)
info_type = request_parameter(
parameter="info_type", parameter_type="known_class", default=models.Info
)
if type(info_type) == Response:
return info_type
node = models.Node.query.get(node_id)
if node is... | 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. |
13,544 | def rank(self):
max_rank = 0
for each in self.hyperedges():
if len(self.edge_links[each]) > max_rank:
max_rank = len(self.edge_links[each])
return max_rank | Return the rank of the given hypergraph.
@rtype: int
@return: Rank of graph. |
13,545 | def _approx_eq_(self, other: Any, atol: Union[int, float]) -> bool:
if not isinstance(other, type(self)):
return NotImplemented
return approx_eq(self.operations, other.operations, atol=atol) | See `cirq.protocols.SupportsApproximateEquality`. |
13,546 | def teardown(self):
for device in self.devices:
self._remove_trustee(device)
self._populate_domain()
self.domain = {} | Teardown trust domain by removing trusted devices. |
13,547 | def _get_cookie(self, name, domain):
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 |
13,548 | def run_migrations_online():
app_conf = dci_config.generate_conf()
connectable = dci_config.get_engine(app_conf)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
)
with context.begin_tra... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. |
13,549 | def _server_rollback():
from os import path, remove
archpath = path.abspath(path.expanduser(settings.archfile))
if path.isfile(archpath) and not args["nolive"]:
vms("Removing archive JSON file at {}.".format(archpath))
remove(archpath)
datapath = path.abspath(path.expandus... | Removes script database and archive files to rollback the CI server
installation. |
13,550 | def add_observer(self, o, component_type=ComponentType):
self.observers[component_type].add(o) | 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
... |
13,551 | def register(self, hash_types):
if not isinstance(hash_types, (list, tuple)):
hash_types = [hash_types]
def _decor_closure(hash_func):
for hash_type in hash_types:
key = (hash_type.__module__, hash_type.__name__)
self.keyed_extens... | 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... |
13,552 | def _prep_window(self, **kwargs):
window = self._get_window()
if isinstance(window, (list, tuple, np.ndarray)):
return com.asarray_tuplesafe(window).astype(float)
elif is_integer(window):
import scipy.signal as sig
def _validate_win_typ... | Provide validation for our window type, return the window
we have already been validated. |
13,553 | def build_getters_support_matrix(app):
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 = {
m: defaultdict(dict)
for m i... | Build the getters support matrix. |
13,554 | def present(self, value):
for k, v in self.special.items():
if v == value:
return k
return .join(self.get_separator(i) + self.format[i].present(v) for i, v in enumerate(value)) | Return a user-friendly representation of a value.
Lookup value in self.specials, or call .to_literal() if absent. |
13,555 | async def spawn_n(self, agent_cls, n, *args, addr=None, **kwargs):
if addr is None:
addr = await self._get_smallest_env()
r_manager = await self.env.connect(addr)
return await r_manager.spawn_n(agent_cls, n, *args, **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:
``qualname`` of the agent class. That is, the name should be in the
form o... |
13,556 | def deserialize_object(buffers, g=None):
bufs = list(buffers)
pobj = buffer_to_bytes_py2(bufs.pop(0))
canned = pickle.loads(pobj)
if istype(canned, sequence_types) and len(canned) < MAX_ITEMS:
for c in canned:
_restore_buffers(c, bufs)
newobj = uncan_sequence(canned, g)
... | 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. |
13,557 | def _get_bucket_endpoint(self):
conn = S3Connection()
bucket = conn.lookup(self.bucket_name)
if not bucket:
raise InputParameterError(t exist' % self.bucket_name)
endpoint = str(bucket.get_location())
return endpoint | Queries S3 to identify the region hosting the provided bucket. |
13,558 | def subslice(inner,outer,section):
if section==: return outer[0],outer[0]+inner[0]
elif section==: return outer[0]+inner[1],outer[1]
elif section==: return outer[0]+inner[0],outer[0]+inner[1]
else: raise ValueError(%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 |
13,559 | def post_card(message,
hook_url=None,
title=None,
theme_color=None):
*
if not hook_url:
hook_url = _get_hook_url()
if not message:
log.error()
payload = {
"text": message,
"title": title,
"themeColor": theme_color
}... | 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... |
13,560 | def edit_prefix(self, auth, spec, attr):
self._logger.debug("edit_prefix called; spec: %s attr: %s" %
(unicode(spec), unicode(attr)))
pool = None
if in attr or in attr:
if in attr:
if attr[] is None:
pool = {
... | 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... |
13,561 | def help_box():
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_widget.page = build_help_html()
dialog_box.ShowModal()
dialog_bo... | A simple HTML help dialog box using the distribution data files. |
13,562 | def remove_network_from_dhcp_agent(self, dhcp_agent, network_id):
return self.delete((self.agent_path + self.DHCP_NETS + "/%s") % (
dhcp_agent, network_id)) | Remove a network from dhcp agent. |
13,563 | def _write_frame(self, data):
assert data is not None and 0 < len(data) < 255,
length = len(data)
frame = bytearray(length+8)
frame[0] = PN532_SPI_DATAWRITE
frame[1] = PN532_PREAMBLE
... | Write a frame to the PN532 with the specified data bytearray. |
13,564 | def form_valid(self, form):
ret = super(ProjectCopy, self).form_valid(form)
self.copy_relations()
messages.add_message(self.request, messages.SUCCESS, % self.object.name)
return ret | After the form is valid lets let people know |
13,565 | def get_scheduling_block_ids():
ids = [key.split()[-1]
for key in DB.keys(pattern=)]
return sorted(ids) | Return list of scheduling block IDs |
13,566 | def cfg_folder_loader(path):
CFG_WILDCARD =
return [load_cfg(filename) for filename in sorted(glob.glob(os.path.join(path, CFG_WILDCARD)))] | :type path: str |
13,567 | def _poll(self):
logger.info("Beginning TrustedAdvisor poll")
tmp = self._get_limit_check_id()
if not self.have_ta:
logger.info()
return {}
if tmp is None:
logger.critical("Unable to find Trusted Advisor "
"check; ... | 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,
... |
13,568 | def Parse(self, conditions, host_data):
result = CheckResult(check_id=self.check_id)
methods = self.SelectChecks(conditions)
result.ExtendAnomalies([m.Parse(conditions, host_data) for m in methods])
return result | 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. |
13,569 | def install(pkg=None,
pkgs=None,
dir=None,
runas=None,
registry=None,
env=None,
dry_run=False,
silent=True):
**
if pkg:
pkgs = [_cmd_quote(pkg)]
elif pkgs:
pkgs = [_cmd_quote(v) for v in pkgs]
else:
... | 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
... |
13,570 | def create_window(self, pane, name=None, set_active=True):
assert isinstance(pane, Pane)
assert name is None or isinstance(name, six.text_type)
taken_indexes = [w.index for w in self.windows]
index = self.base_index
while index in taken_indexes:
in... | 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. |
13,571 | def load_targets(explanatory_rasters):
explanatory_raster_arrays = []
aff = None
shape = None
crs = None
for raster in explanatory_rasters:
logger.debug(raster)
with rasterio.open(raster) as src:
ar = src.read(1)
if not aff:
... | Parameters
----------
explanatory_rasters : List of Paths to GDAL rasters containing explanatory variables
Returns
-------
expl : Array of explanatory variables
raster_info : dict of raster info |
13,572 | def run_cmd(cmd):
try:
p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
stdout, stderr = p.communicate()
except OSError as e:
if DEBUG:
raise
if e.errno == errno.ENOENT:
msg = .format(.join(cmd))
raise _Comman... | Run a command in a subprocess, given as a list of command-line
arguments.
Returns a ``(returncode, stdout, stderr)`` tuple. |
13,573 | def use_federated_bank_view(self):
self._bank_view = FEDERATED
for session in self._get_provider_sessions():
try:
session.use_federated_bank_view()
except AttributeError:
pass | Pass through to provider ItemLookupSession.use_federated_bank_view |
13,574 | 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 (... |
13,575 | def submitter(self):
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 |
13,576 | def load(self, steps_dir=None, step_file=None, step_list=None):
self._closed()
self.steps_library.load(steps_dir=steps_dir, step_file=step_file,
step_list=step_list) | 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
... |
13,577 | def signature_type(self):
if not self.mardata.signatures:
return None
for sig in self.mardata.signatures.sigs:
if sig.algorithm_id == 1:
return
elif sig.algorithm_id == 2:
return
else:
return | Return the signature type used in this MAR.
Returns:
One of None, 'unknown', 'sha1', or 'sha384' |
13,578 | def unfix(self, param):
if param == "delta":
self._unfix("logistic")
else:
self._fix[param] = False | Enable parameter optimization.
Parameters
----------
param : str
Possible values are ``"delta"``, ``"beta"``, and ``"scale"``. |
13,579 | def set_input_data(self, key, value):
if not key in self.input_channels.keys():
self.set_input_channel(key, Channel())
self.input_channels[key].set_value(Data(self.time, 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. |
13,580 | def link_for_image(self, base_dir: str, conf: Config) -> int:
return self.link_types(
base_dir,
[ArtifactType.app, ArtifactType.binary, ArtifactType.gen_py],
conf) | Link all artifacts required for a Docker image under `base_dir` and
return the number of linked artifacts. |
13,581 | def link(self, thing1, thing2):
thing1 = thing1.strip().lower()
thing2 = thing2.strip().lower()
if thing1 == thing2:
raise SameName("Attempted to link two of the same name")
self.change(thing1, 0)
self.change(thing2, 0)
return self._link(thing1, thing2) | Link thing1 and thing2, adding the karma of each into
a single entry.
If any thing does not exist, it is created. |
13,582 | def show_support_save_status_output_show_support_save_status_message(self, **kwargs):
config = ET.Element("config")
show_support_save_status = ET.Element("show_support_save_status")
config = show_support_save_status
output = ET.SubElement(show_support_save_status, "output")
... | Auto Generated Code |
13,583 | def compute_auth_key(userid, password):
import sys
if sys.version_info >= (3, 0):
return hashlib.sha1(b"|".join((userid.encode("ascii"),
password.encode("ascii")))).hexdigest()
return hashlib.sha1("|".join((userid, password))).hexdigest() | 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) |
13,584 | def get_all_profiles(store=):
return {
: get_all_settings(profile=, store=store),
: get_all_settings(profile=, store=store),
: get_all_settings(profile=, store=store)
} | 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... |
13,585 | def storages(self):
return storage.StorageCollection(
self._conn, utils.get_subresource_path_by(self, ),
redfish_version=self.redfish_version) | 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 |
13,586 | def make_psrrates(pkllist, nbins=60, period=0.156):
state = pickle.load(open(pkllist[0], ))
if in state[]:
immaxcol = state[].index()
logger.info()
elif in state[]:
try:
immaxcol = state[].index()
logger.info()
except:
immaxc... | 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). |
13,587 | def Detect(self, baseline, host_data):
result = CheckResult()
for detector in self.detectors:
finding = detector(baseline, host_data)
if finding:
result.ExtendAnomalies([finding])
if result:
return result | 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... |
13,588 | def get_instance(self, payload):
return ConnectAppInstance(self._version, payload, account_sid=self._solution[], ) | 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 |
13,589 | def dqdv_cycle(cycle, splitter=True, **kwargs):
c_first = cycle.loc[cycle["direction"] == -1]
c_last = cycle.loc[cycle["direction"] == 1]
converter = Converter(**kwargs)
converter.set_data(c_first["capacity"], c_first["voltage"])
converter.inspect_data()
converter.pre_process_data()
c... | 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)).
... |
13,590 | def deleteRole(self, *args, **kwargs):
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`` |
13,591 | def filter(self, source_file, encoding):
with codecs.open(source_file, , encoding=encoding) as f:
text = f.read()
return [filters.SourceText(self._filter(text), source_file, encoding, )] | Parse file. |
13,592 | def is_all_field_none(self):
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:
return False
if self._point... | :rtype: bool |
13,593 | def add(self, data_source, module, package=None):
super(Data, self).add(data_source, module, package)
if data_source not in self.layer:
self.layer[data_source] = {: module, : package}
self.objects[data_source] = 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. Can be absolute or
relative. See :func:`importlib.import_... |
13,594 | def clone(self, callable=None, **overrides):
old = {k: v for k, v in self.get_param_values()
if k not in [, ]}
params = dict(old, **overrides)
callable = self.callable if callable is None else callable
return self.__class__(callable, **params) | Clones the Callable optionally with new settings
Args:
callable: New callable function to wrap
**overrides: Parameter overrides to apply
Returns:
Cloned Callable object |
13,595 | def do_hit(self, arg):
if arg[]:
self.hit_create(arg[], arg[],
arg[])
self.update_hit_tally()
elif arg[]:
self.amt_services_wrapper.hit_extend(arg[], arg[], arg[])
elif arg[]:
self.amt_services_wrapper.hit_expi... | 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]... |
13,596 | def single(self, predicate):
result = self.where(predicate).to_list()
count = len(result)
if count == 0:
raise NoMatchingElement("No matching element found")
if count > 1:
raise MoreThanOneMatchingElement(
"More than one matching element f... | 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... |
13,597 | def cmd(send, msg, args):
uid = args[][][]
token = args[][][]
parser = arguments.ArgParser(args[])
parser.add_argument(, action=arguments.ZipParser)
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
req = get("htt... | Gets the location of a ZIP code
Syntax: {command} (zipcode)
Powered by STANDS4, www.stands4.com |
13,598 | def sendCommands(comPort, commands):
mutex.acquire()
try:
try:
port = serial.Serial(port=comPort)
header =
footer =
for command in _translateCommands(commands):
_sendBinaryData(port, header + command + footer)
except serial.S... | 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 ... |
13,599 | def monitor(self, name, cb, request=None, notify_disconnect=False, queue=None):
R = Subscription(self, name, cb, notify_disconnect=notify_disconnect, queue=queue)
R._S = super(Context, self).monitor(name, R._event, request)
return R | 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.