positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def bayes_risk(self, expparams):
r"""
Calculates the Bayes risk for hypothetical experiments, assuming the
quadratic loss function defined by the current model's scale matrix
(see :attr:`qinfer.abstract_model.Simulatable.Q`).
:param expparams: The experiments at which to compute... | r"""
Calculates the Bayes risk for hypothetical experiments, assuming the
quadratic loss function defined by the current model's scale matrix
(see :attr:`qinfer.abstract_model.Simulatable.Q`).
:param expparams: The experiments at which to compute the risk.
:type expparams: :clas... |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._monetary_account_id is not None:
return False
if self._alias is not None:
return False
if self._counterparty_alias is not None:
return False
if self._amount_guarante... | :rtype: bool |
def getChanges(self, request):
"""
Reponds only to POST events and starts the build process
:arguments:
request
the http request object
"""
expected_secret = isinstance(self.options, dict) and self.options.get('secret')
if expected_secret:
... | Reponds only to POST events and starts the build process
:arguments:
request
the http request object |
def _guess_vc(self):
"""
Locate Visual C for 2017
"""
if self.vc_ver <= 14.0:
return
default = r'VC\Tools\MSVC'
guess_vc = os.path.join(self.VSInstallDir, default)
# Subdir with VC exact version as name
try:
vc_exact_ver = os.listd... | Locate Visual C for 2017 |
def get(self):
"""
Constructs a WorkflowCumulativeStatisticsContext
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumul... | Constructs a WorkflowCumulativeStatisticsContext
:returns: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics.WorkflowCumulativeStatisticsContext |
def get_node(conn, name):
'''
Return a libcloud node for the named VM
'''
nodes = conn.list_nodes()
for node in nodes:
if node.name == name:
__utils__['cloud.cache_node'](salt.utils.data.simple_types_filter(node.__dict__), __active_provider_name__, __opts__)
return no... | Return a libcloud node for the named VM |
def _load_settings_from_source(self, source):
"""
Loads the relevant settings from the specified ``source``.
:returns: a standard :func:`dict` containing the settings from the source
:rtype: dict
"""
if not source:
pass
elif source == 'env_settings_ur... | Loads the relevant settings from the specified ``source``.
:returns: a standard :func:`dict` containing the settings from the source
:rtype: dict |
def enable_event(self, event_type, mechanism, context=None):
"""Enable event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be enabled.
(Consta... | Enable event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be enabled.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR)
:param context: Not... |
def get_r(self):
"""Returns the right border of the cell"""
start_point, end_point = self._get_right_line_coordinates()
width = self._get_right_line_width()
color = self._get_right_line_color()
return CellBorder(start_point, end_point, width, color) | Returns the right border of the cell |
def send_to_kinesis_stream(events, stream_name, partition_key=None,
packer=None, serializer=json.dumps):
"""Sends events to a Kinesis stream."""
if not events:
logger.info("No events provided: nothing delivered to Firehose")
return
records = []
for event in ev... | Sends events to a Kinesis stream. |
def get_escalation_policies(profile='pagerduty', subdomain=None, api_key=None):
'''
List escalation_policies belonging to this account
CLI Example:
salt myminion pagerduty.get_escalation_policies
'''
return _list_items(
'escalation_policies',
'id',
profile=profile,... | List escalation_policies belonging to this account
CLI Example:
salt myminion pagerduty.get_escalation_policies |
def get(self, obj, key):
"""
Retrieve 'key' from an instance of a class which previously exposed it.
@param key: a hashable object, previously passed to L{Exposer.expose}.
@return: the object which was exposed with the given name on obj's key.
@raise MethodNotExposed: when the... | Retrieve 'key' from an instance of a class which previously exposed it.
@param key: a hashable object, previously passed to L{Exposer.expose}.
@return: the object which was exposed with the given name on obj's key.
@raise MethodNotExposed: when the key in question was not exposed with
... |
def ttl_cache(maxage, maxsize=128):
""" A time-to-live caching decorator that follows after the style of
lru_cache. The `maxage` argument is time-to-live in seconds for each
cache result. Any cache entries over the maxage are lazily replaced. """
def decorator(inner_func):
wrapper = make_ttl_... | A time-to-live caching decorator that follows after the style of
lru_cache. The `maxage` argument is time-to-live in seconds for each
cache result. Any cache entries over the maxage are lazily replaced. |
def to_dictionary(pw, print_list):
"""
- convert list of comparisons to dictionary
- print list of pidents (if requested) to stderr
"""
pairs = {}
for p in pw:
a, b, pident = p
if a not in pairs:
pairs[a] = {a: '-'}
if b not in pairs:
pairs[b] = {b... | - convert list of comparisons to dictionary
- print list of pidents (if requested) to stderr |
def close(self):
"""Close the tough cursor.
It will not complain if you close it more than once.
"""
if not self._closed:
try:
self._cursor.close()
except Exception:
pass
self._closed = True | Close the tough cursor.
It will not complain if you close it more than once. |
def libvlc_media_library_media_list(p_mlib):
'''Get media library subitems.
@param p_mlib: media library object.
@return: media list subitems.
'''
f = _Cfunctions.get('libvlc_media_library_media_list', None) or \
_Cfunction('libvlc_media_library_media_list', ((1,),), class_result(MediaList),... | Get media library subitems.
@param p_mlib: media library object.
@return: media list subitems. |
def __extract_modules(self, loader, name, is_pkg):
""" if module found load module and save all attributes in the module found """
mod = loader.find_module(name).load_module(name)
""" find the attribute method on each module """
if hasattr(mod, '__method__'):
""" register ... | if module found load module and save all attributes in the module found |
def mail(ui, repo, *pats, **opts):
"""mail a change for review
Uploads a patch to the code review server and then sends mail
to the reviewer and CC list asking for a review.
"""
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
cl, err = CommandLineCL(ui, repo, pats, opts, op="mail", defaultcc=... | mail a change for review
Uploads a patch to the code review server and then sends mail
to the reviewer and CC list asking for a review. |
def daemonize(self):
"""Double fork and set the pid."""
self._double_fork()
# Write pidfile.
self.pid = os.getpid()
LOG.info(
"Succesfully daemonized process {0}.".format(self.pid)
) | Double fork and set the pid. |
def get_indexer_nd(index, labels, method=None, tolerance=None):
""" Call pd.Index.get_indexer(labels). """
kwargs = _index_method_kwargs(method, tolerance)
flat_labels = np.ravel(labels)
flat_indexer = index.get_indexer(flat_labels, **kwargs)
indexer = flat_indexer.reshape(labels.shape)
return ... | Call pd.Index.get_indexer(labels). |
def set_attribute_label(series, resource_labels, attribute_key,
canonical_key=None, label_value_prefix=''):
"""Set a label to timeseries that can be used for monitoring
:param series: TimeSeries object based on view data
:param resource_labels: collection of labels
:param attribu... | Set a label to timeseries that can be used for monitoring
:param series: TimeSeries object based on view data
:param resource_labels: collection of labels
:param attribute_key: actual label key
:param canonical_key: exporter specific label key, Optional
:param label_value_prefix: exporter specific l... |
def global_config(cls, key, *args):
''' This reads or sets the global settings stored in class.settings. '''
if args:
cls.settings[key] = args[0]
else:
return cls.settings[key] | This reads or sets the global settings stored in class.settings. |
def id_request(self, device_id):
"""Get the device for the ID. ID request can return device type (cat/subcat),
firmware ver, etc. Cat is status['is_high'], sub cat is status['id_mid']"""
self.logger.info("\nid_request for device %s", device_id)
device_id = device_id.upper()
self... | Get the device for the ID. ID request can return device type (cat/subcat),
firmware ver, etc. Cat is status['is_high'], sub cat is status['id_mid'] |
def init_properties(env='dev', app='unnecessary', **_):
"""Make sure _application.properties_ file exists in S3.
For Applications with Archaius support, there needs to be a file where the
cloud environment variable points to.
Args:
env (str): Deployment environment/account, i.e. dev, stage, pr... | Make sure _application.properties_ file exists in S3.
For Applications with Archaius support, there needs to be a file where the
cloud environment variable points to.
Args:
env (str): Deployment environment/account, i.e. dev, stage, prod.
app (str): GitLab Project name.
Returns:
... |
def _add_edge(self, idx, from_idx, from_lvec, to_idx, to_lvec):
"""
Add information about an edge linking two critical points.
This actually describes two edges:
from_idx ------ idx ------ to_idx
However, in practice, from_idx and to_idx will typically be
atom nuclei, ... | Add information about an edge linking two critical points.
This actually describes two edges:
from_idx ------ idx ------ to_idx
However, in practice, from_idx and to_idx will typically be
atom nuclei, with the center node (idx) referring to a bond
critical point. Thus, it will... |
def new_log_level(level, name, logger_name=None):
"""
Quick way to create a custom log level that behaves like the default levels in the logging module.
:param level: level number
:param name: level name
:param logger_name: optional logger name
"""
@CustomLogLevel(level, name, logger_name)
... | Quick way to create a custom log level that behaves like the default levels in the logging module.
:param level: level number
:param name: level name
:param logger_name: optional logger name |
def delete_cached_branch_info(self):
'''
Deletes cached branch_info file
'''
if os.path.isfile(constants.cached_branch_info):
logger.debug('Deleting cached branch_info file...')
os.remove(constants.cached_branch_info)
else:
logger.debug('Ca... | Deletes cached branch_info file |
def add2(self, target, path_settings, method):
"""
add() with reordered paameters
"""
return self.add(method, path_settings, target) | add() with reordered paameters |
def save(self):
"""Save the index data back to the wily cache."""
data = [i.asdict() for i in self._revisions.values()]
logger.debug("Saving data")
cache.store_archiver_index(self.config, self.archiver, data) | Save the index data back to the wily cache. |
def get_cached(self, link, default=None):
'''Retrieves a cached navigator from the id_map.
Either a Link object or a bare uri string may be passed in.'''
if hasattr(link, 'uri'):
return self.id_map.get(link.uri, default)
else:
return self.id_map.get(link, default... | Retrieves a cached navigator from the id_map.
Either a Link object or a bare uri string may be passed in. |
def get_nendo ():
"""今は何年度?"""
y, m = map(int, time.strftime("%Y %m").split())
return y if m >= 4 else y - 1 | 今は何年度? |
def do_add_signature(input_file, output_file, signature_file):
"""Add a signature to the MAR file."""
signature = open(signature_file, 'rb').read()
if len(signature) == 256:
hash_algo = 'sha1'
elif len(signature) == 512:
hash_algo = 'sha384'
else:
raise ValueError()
with... | Add a signature to the MAR file. |
def warn(self, msg, *args, **kwargs):
"""Log an warning message."""
self.log(self.WARN, msg, *args, **kwargs) | Log an warning message. |
def _compute_iso_color(self):
""" compute LineVisual color from level index and corresponding level
color
"""
level_color = []
colors = self._lc
for i, index in enumerate(self._li):
level_color.append(np.zeros((index, 4)) + colors[i])
self._cl = np.vst... | compute LineVisual color from level index and corresponding level
color |
def get_style_attribute(style_attribute, html_element):
'''
::param: style_directive \
The attribute value of the given style sheet.
Example: display: none
::param: html_element: \
The HtmlElement to which the given style is applied
::returns:
... | ::param: style_directive \
The attribute value of the given style sheet.
Example: display: none
::param: html_element: \
The HtmlElement to which the given style is applied
::returns:
A HtmlElement that merges the given element with
the style attri... |
def build_penalties(self):
"""
builds the GAM block-diagonal penalty matrix in quadratic form
out of penalty matrices specified for each feature.
each feature penalty matrix is multiplied by a lambda for that feature.
so for m features:
P = block_diag[lam0 * P0, lam1 * ... | builds the GAM block-diagonal penalty matrix in quadratic form
out of penalty matrices specified for each feature.
each feature penalty matrix is multiplied by a lambda for that feature.
so for m features:
P = block_diag[lam0 * P0, lam1 * P1, lam2 * P2, ... , lamm * Pm]
Param... |
def records(rec_type=None, fields=None, clean=True):
'''
Return DMI records from SMBIOS
type
Return only records of type(s)
The SMBIOS specification defines the following DMI types:
==== ======================================
Type Information
==== ===============... | Return DMI records from SMBIOS
type
Return only records of type(s)
The SMBIOS specification defines the following DMI types:
==== ======================================
Type Information
==== ======================================
0 BIOS
1 System
... |
def filter_values(self, pattern, flags=0):
"""
| Filters the :meth:`PlistFileParser.elements` class property elements using given pattern.
| Will return a list of matching elements values, if you want to get only one element value, use
the :meth:`PlistFileParser.get_value` method ins... | | Filters the :meth:`PlistFileParser.elements` class property elements using given pattern.
| Will return a list of matching elements values, if you want to get only one element value, use
the :meth:`PlistFileParser.get_value` method instead.
Usage::
>>> plist_file_parser = Pli... |
def data_sessions(self):
"""
Access the data_sessions
:returns: twilio.rest.wireless.v1.sim.data_session.DataSessionList
:rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionList
"""
if self._data_sessions is None:
self._data_sessions = DataSessionList... | Access the data_sessions
:returns: twilio.rest.wireless.v1.sim.data_session.DataSessionList
:rtype: twilio.rest.wireless.v1.sim.data_session.DataSessionList |
def load_rules(self, filename):
"""
Load rules from YAML configuration in the given stream object
:param filename: Filename of rule YAML file
:return: rules object
"""
self.logger.debug('Reading rules from %s', filename)
try:
in_file = open(filename)
... | Load rules from YAML configuration in the given stream object
:param filename: Filename of rule YAML file
:return: rules object |
def derive_link_fields(self, context):
"""
Used to derive which fields should be linked. This should return a set() containing
the names of those fields which should be linkable.
"""
if self.link_fields is not None:
return self.link_fields
else:
... | Used to derive which fields should be linked. This should return a set() containing
the names of those fields which should be linkable. |
def serialize_table(ctx, document, table, root):
"""Serializes table element.
"""
# What we should check really is why do we pass None as root element
# There is a good chance some content is missing after the import
if root is None:
return root
if ctx.ilvl != None:
root = clo... | Serializes table element. |
def append(self, map):
"""
Appends new elements to this map.
:param map: a map with elements to be added.
"""
if isinstance(map, dict):
for (k, v) in map.items():
key = StringConverter.to_string(k)
value = v
self.put(ke... | Appends new elements to this map.
:param map: a map with elements to be added. |
def _inject(self, fileobj, padding_func):
"""Write tag data into the Vorbis comment packet/page."""
# Find the old pages in the file; we'll need to remove them,
# plus grab any stray setup packet data out of them.
fileobj.seek(0)
page = OggPage(fileobj)
while not page.pa... | Write tag data into the Vorbis comment packet/page. |
def get_nfkd_quick_check_property(value, is_bytes=False):
"""Get `NFKD QUICK CHECK` property."""
obj = unidata.ascii_nfkd_quick_check if is_bytes else unidata.unicode_nfkd_quick_check
if value.startswith('^'):
negated = value[1:]
value = '^' + unidata.unicode_alias['nfkdquickcheck'].get(ne... | Get `NFKD QUICK CHECK` property. |
def update(self, portfolio, date, perfs=None):
'''
Actualizes the portfolio universe with the alog state
'''
# Make the manager aware of current simulation
self.portfolio = portfolio
self.perfs = perfs
self.date = date | Actualizes the portfolio universe with the alog state |
def _ref_covered_by_at_least_one_full_length_contig(nucmer_hits, percent_threshold, max_nt_extend):
'''Returns true iff there exists a contig that completely
covers the reference sequence
nucmer_hits = hits made by self._parse_nucmer_coords_file.'''
for l in nucmer_hits.values():
... | Returns true iff there exists a contig that completely
covers the reference sequence
nucmer_hits = hits made by self._parse_nucmer_coords_file. |
def decrement(self, key, value=1):
"""
Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool
"""
self._store.decrement(self.tagged_item_key(ke... | Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool |
def filter(self, table, vg_snapshots, filter_string):
"""Naive case-insensitive search."""
query = filter_string.lower()
return [vg_snapshot for vg_snapshot in vg_snapshots
if query in vg_snapshot.name.lower()] | Naive case-insensitive search. |
def produceResource(self, request, segments, webViewer):
"""
Return a C{(resource, subsegments)} tuple or None, depending on whether
I wish to return an L{IResource} provider for the given set of segments
or not.
"""
def thunk():
cr = getattr(self, 'createReso... | Return a C{(resource, subsegments)} tuple or None, depending on whether
I wish to return an L{IResource} provider for the given set of segments
or not. |
def triad(note, key):
"""Return the triad on note in key as a list.
Examples:
>>> triad('E', 'C')
['E', 'G', 'B']
>>> triad('E', 'B')
['E', 'G#', 'B']
"""
return [note, intervals.third(note, key), intervals.fifth(note, key)] | Return the triad on note in key as a list.
Examples:
>>> triad('E', 'C')
['E', 'G', 'B']
>>> triad('E', 'B')
['E', 'G#', 'B'] |
def list_files(path):
"""Recursively collects a list of files at a path."""
files = []
if os.path.isdir(path):
for stats in os.walk(path):
for f in stats[2]:
files.append(os.path.join(stats[0], f))
elif os.path.isfile(path):
files = [path]
return files | Recursively collects a list of files at a path. |
def order_mod( x, m ):
"""Return the order of x in the multiplicative group mod m.
"""
# Warning: this implementation is not very clever, and will
# take a long time if m is very large.
if m <= 1: return 0
assert gcd( x, m ) == 1
z = x
result = 1
while z != 1:
z = ( z * x ) % m
result = re... | Return the order of x in the multiplicative group mod m. |
def start(self):
"""The event's start time, as a timezone-aware datetime object"""
if self.start_time is None:
time = datetime.time(hour=19, tzinfo=CET)
else:
time = self.start_time.replace(tzinfo=CET)
return datetime.datetime.combine(self.date, time) | The event's start time, as a timezone-aware datetime object |
def evaluate_all(ctx, model):
"""Evaluate POS taggers on WSJ and GENIA."""
click.echo('chemdataextractor.pos.evaluate_all')
click.echo('Model: %s' % model)
ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle'... | Evaluate POS taggers on WSJ and GENIA. |
def get(self, key):
"""
Retrieve an item from the cache by key.
:param key: The cache key
:type key: str
:return: The cache value
"""
value = self._redis.get(self._prefix + key)
if value is not None:
return self.unserialize(value) | Retrieve an item from the cache by key.
:param key: The cache key
:type key: str
:return: The cache value |
def _flush(self):
"""
Flush metadata to the backing file
:return:
"""
with open(self.metadata_file, 'w') as f:
json.dump(self.metadata, f) | Flush metadata to the backing file
:return: |
def get_text_position(fig, ax, ha='left', va='top', pad_scale=1.0):
"""Return text position inside of the given axis"""
## Check and preprocess input arguments
try: pad_scale = float(pad_scale)
except: raise TypeError("'pad_scale should be of type 'float'")
for arg in [va, ha]:
ass... | Return text position inside of the given axis |
def processpool_map(task, args, message, concurrency, batchsize=1, nargs=None):
"""
See http://stackoverflow.com/a/16071616
"""
njobs = get_njobs(nargs, args)
show_progress = bool(message)
batches = grouper(batchsize, tupleise(args))
def batched_task(*batch):
return [task(*job) for j... | See http://stackoverflow.com/a/16071616 |
def GetSubkeyByPath(self, key_path):
"""Retrieves a subkey by path.
Args:
key_path (str): path of the subkey.
Returns:
WinRegistryKey: Windows Registry subkey or None if not found.
"""
if not self._registry_key and self._registry:
self._GetKeyFromRegistry()
subkey = self
... | Retrieves a subkey by path.
Args:
key_path (str): path of the subkey.
Returns:
WinRegistryKey: Windows Registry subkey or None if not found. |
def remove_component(self, entity: int, component_type: Any) -> int:
"""Remove a Component instance from an Entity, by type.
A Component instance can be removed by providing it's type.
For example: world.delete_component(enemy_a, Velocity) will remove
the Velocity instance from the Enti... | Remove a Component instance from an Entity, by type.
A Component instance can be removed by providing it's type.
For example: world.delete_component(enemy_a, Velocity) will remove
the Velocity instance from the Entity enemy_a.
Raises a KeyError if either the given entity or Component t... |
def send_query(self, query):
"""Sends a query to the Riemann server
:returns: The response message from Riemann
"""
message = riemann_client.riemann_pb2.Msg()
message.query.string = query
return self.transport.send(message) | Sends a query to the Riemann server
:returns: The response message from Riemann |
def get_revoked_certs(self):
"""
Returns revoked certificates of this CA
(does not include expired certificates)
"""
now = timezone.now()
return self.cert_set.filter(revoked=True,
validity_start__lte=now,
... | Returns revoked certificates of this CA
(does not include expired certificates) |
def get_json(request, token):
"""Return matching results as JSON"""
result = []
searchtext = request.GET['q']
if len(searchtext) >= 3:
pickled = _simple_autocomplete_queryset_cache.get(token, None)
if pickled is not None:
app_label, model_name, query = pickle.loads(pickled)
... | Return matching results as JSON |
def coffee(input, output, **kw):
"""Process CoffeeScript files"""
subprocess.call([current_app.config.get('COFFEE_BIN'),
'-c', '-o', output, input]) | Process CoffeeScript files |
def p_commands_list(p):
"""commands : commands command"""
p[0] = p[1]
# section 3.2: REQUIRE command must come before any other commands
if p[2].RULE_IDENTIFIER == 'REQUIRE':
if any(command.RULE_IDENTIFIER != 'REQUIRE'
for command in p[0].commands):
print("REQUIRE com... | commands : commands command |
def normalize(path_name, override=None):
"""
Prepares a path name to be worked with. Path name must not be empty. This
function will return the 'normpath'ed path and the identity of the path.
This function takes an optional overriding argument for the identity.
ONLY PROVIDE OVERRIDE IF:
1) ... | Prepares a path name to be worked with. Path name must not be empty. This
function will return the 'normpath'ed path and the identity of the path.
This function takes an optional overriding argument for the identity.
ONLY PROVIDE OVERRIDE IF:
1) YOU AREWORKING WITH A FOLDER THAT HAS AN EXTENSION IN... |
def add(self, label):
"""
Add a label to the end of the list.
Args:
label (Label): The label to add.
"""
label.label_list = self
self.label_tree.addi(label.start, label.end, label) | Add a label to the end of the list.
Args:
label (Label): The label to add. |
def stop_process(self):
"""
Stop the process.
:raises: EnvironmentError if stopping fails due to unknown environment
TestStepError if process stops with non-default returncode and return code is not ignored.
"""
if self.read_thread is not None:
self.logger.de... | Stop the process.
:raises: EnvironmentError if stopping fails due to unknown environment
TestStepError if process stops with non-default returncode and return code is not ignored. |
def check_sig(self, other):
"""Check overlap insignificance with another spectrum.
Also see :ref:`pysynphot-command-checko`.
.. note::
Only use when :meth:`check_overlap` returns "partial".
Parameters
----------
other : `SourceSpectrum` or `SpectralElement`... | Check overlap insignificance with another spectrum.
Also see :ref:`pysynphot-command-checko`.
.. note::
Only use when :meth:`check_overlap` returns "partial".
Parameters
----------
other : `SourceSpectrum` or `SpectralElement`
The other spectrum.
... |
def compile_action_preconditions_checking(self,
state: Sequence[tf.Tensor],
action: Sequence[tf.Tensor]) -> tf.Tensor:
'''Combines the action preconditions into an applicability checking op.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
ac... | Combines the action preconditions into an applicability checking op.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
action (Sequence[tf.Tensor]): The action fluents.
Returns:
A boolean tensor for checking if `action` is application in `state`. |
def install_translations(config):
"""Add check translations according to ``config`` as a fallback to existing translations"""
if not config:
return
from . import _translation
checks_translation = gettext.translation(domain=config["domain"],
localedi... | Add check translations according to ``config`` as a fallback to existing translations |
def __leaf(i, j, first, maxfirst, prevleaf, ancestor):
"""
Determine if j is leaf of i'th row subtree.
"""
jleaf = 0
if i<=j or first[j] <= maxfirst[i]: return -1, jleaf
maxfirst[i] = first[j]
jprev = prevleaf[i]
prevleaf[i] = j
if jprev == -1: jleaf = 1
else: jleaf = 2
if jl... | Determine if j is leaf of i'th row subtree. |
def _node_set(self) -> List["InstanceNode"]:
"""XPath - return the list of all receiver's nodes."""
return list(self) if isinstance(self.value, ArrayValue) else [self] | XPath - return the list of all receiver's nodes. |
def equi(map_axis, centerlon, centerlat, radius, color, alpha=1.0):
"""
This function enables A95 error ellipses to be drawn in cartopy around
paleomagnetic poles in conjunction with shoot
(modified from: http://www.geophysique.be/2011/02/20/matplotlib-basemap-tutorial-09-drawing-circles/).
"""
... | This function enables A95 error ellipses to be drawn in cartopy around
paleomagnetic poles in conjunction with shoot
(modified from: http://www.geophysique.be/2011/02/20/matplotlib-basemap-tutorial-09-drawing-circles/). |
def create_package_node(self, team, user, package, dry_run=False):
"""
Creates a new package and initializes its contents. See `install_package`.
"""
contents = RootNode(dict())
if dry_run:
return contents
self.check_name(team, user, package)
assert c... | Creates a new package and initializes its contents. See `install_package`. |
def _trim_tree(state):
"""Trim empty leaf nodes from the tree.
- To simplify the tree conversion, empty nodes are added before it is known if they
will contain items that connect back to the authenticated subject. If there are
no connections, the nodes remain empty, which causes them to be removed ... | Trim empty leaf nodes from the tree.
- To simplify the tree conversion, empty nodes are added before it is known if they
will contain items that connect back to the authenticated subject. If there are
no connections, the nodes remain empty, which causes them to be removed here.
- Removing a leaf n... |
def iso_abund(self, cycle, stable=False, amass_range=None,
mass_range=None, ylim=[0,0], ref=-1, show=True,
log_logic=True, decayed=False, color_plot=True,
grid=False, point_set=1, include_title=False,
data_provided=False,thedata=None, verbose=True,... | plot the abundance of all the chemical species
Parameters
----------
cycle : string, integer or list
The cycle of interest. If it is a list of cycles, this
method will do a plot for each cycle and save them to a
file.
stable : boolean, optional
... |
def combine_context_errors(self):
"""Each alignment contributes some information to the error report. These reports for each alignment need to be gone through and combined into one report.
:returns: Dictionary containing the error counts on context base
:rtype: dict()
"""
r = {}
if self._tar... | Each alignment contributes some information to the error report. These reports for each alignment need to be gone through and combined into one report.
:returns: Dictionary containing the error counts on context base
:rtype: dict() |
def most_by_uncertain(self, y):
""" Extracts the predicted classes which correspond to the selected class (y) and have probabilities nearest to 1/number_of_classes (eg. 0.5 for 2 classes, 0.33 for 3 classes) for the selected class.
Arguments:
y (int): the selected class
... | Extracts the predicted classes which correspond to the selected class (y) and have probabilities nearest to 1/number_of_classes (eg. 0.5 for 2 classes, 0.33 for 3 classes) for the selected class.
Arguments:
y (int): the selected class
Returns:
idxs (numpy.ndarra... |
def reset(self):
"""
Reset the Quantum Abstract Machine to its initial state, which is particularly useful
when it has gotten into an unwanted state. This can happen, for example, if the QAM
is interrupted in the middle of a run.
"""
self._variables_shim = {}
self... | Reset the Quantum Abstract Machine to its initial state, which is particularly useful
when it has gotten into an unwanted state. This can happen, for example, if the QAM
is interrupted in the middle of a run. |
def reset_course(self, course_id):
"""
Reset a course.
Deletes the current course, and creates a new equivalent course with
no content, but all sections and users moved over.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - cour... | Reset a course.
Deletes the current course, and creates a new equivalent course with
no content, but all sections and users moved over. |
def determine_encoding(buf):
"""Return the appropriate encoding for the given CSS source, according to
the CSS charset rules.
`buf` may be either a string or bytes.
"""
# The ultimate default is utf8; bravo, W3C
bom_encoding = 'UTF-8'
if not buf:
# What
return bom_encoding
... | Return the appropriate encoding for the given CSS source, according to
the CSS charset rules.
`buf` may be either a string or bytes. |
def update_stat(self, mode='open', infostr='', stat=''):
""" write operation stats to log
:param mode: 'open', 'saveas', 'listtree'
:param infostr: string to put into info_st
:param stat: 'OK' or 'ERR'
"""
self._update_stat[mode](mode, infostr, stat) | write operation stats to log
:param mode: 'open', 'saveas', 'listtree'
:param infostr: string to put into info_st
:param stat: 'OK' or 'ERR' |
def _key_deploy_run(self, host, target, re_run=True):
'''
The ssh-copy-id routine
'''
argv = [
'ssh.set_auth_key',
target.get('user', 'root'),
self.get_pubkey(),
]
single = Single(
self.opts,
argv,
... | The ssh-copy-id routine |
def from_dict(data, ctx):
"""
Instantiate a new UnitsAvailableDetails from a dict (generally from
loading a JSON response). The data used to instantiate the
UnitsAvailableDetails is a shallow copy of the dict passed in, with any
complex child types instantiated appropriately.
... | Instantiate a new UnitsAvailableDetails from a dict (generally from
loading a JSON response). The data used to instantiate the
UnitsAvailableDetails is a shallow copy of the dict passed in, with any
complex child types instantiated appropriately. |
def do_login(self, line):
"login aws-acces-key aws-secret"
if line:
args = self.getargs(line)
self.connect(args[0], args[1])
else:
self.connect()
self.do_tables('') | login aws-acces-key aws-secret |
def _release_line(c):
"""
Examine current repo state to determine what type of release to prep.
:returns:
A two-tuple of ``(branch-name, line-type)`` where:
- ``branch-name`` is the current branch name, e.g. ``1.1``, ``master``,
``gobbledygook`` (or, usually, ``HEAD`` if not on a... | Examine current repo state to determine what type of release to prep.
:returns:
A two-tuple of ``(branch-name, line-type)`` where:
- ``branch-name`` is the current branch name, e.g. ``1.1``, ``master``,
``gobbledygook`` (or, usually, ``HEAD`` if not on a branch).
- ``line-type`` ... |
def __parse_tag(self, tag, count):
"""Raises IOError and APEBadItemError"""
fileobj = cBytesIO(tag)
for i in xrange(count):
tag_data = fileobj.read(8)
# someone writes wrong item counts
if not tag_data:
break
if len(tag_data) != 8... | Raises IOError and APEBadItemError |
def _produce_output(report, failed, setup):
'''
Produce output from the report dictionary generated by _generate_report
'''
report_format = setup.get('report_format', 'yaml')
log.debug('highstate output format: %s', report_format)
if report_format == 'json':
report_text = salt.utils.js... | Produce output from the report dictionary generated by _generate_report |
def plot_margins(*, fig=None, inches=1., centers=True, edges=True):
"""Add lines onto a figure indicating the margins, centers, and edges.
Useful for ensuring your figure design scripts work as intended, and for laying
out figures.
Parameters
----------
fig : matplotlib.figure.Figure object (o... | Add lines onto a figure indicating the margins, centers, and edges.
Useful for ensuring your figure design scripts work as intended, and for laying
out figures.
Parameters
----------
fig : matplotlib.figure.Figure object (optional)
The figure to plot onto. If None, gets current figure. Def... |
def generate_file_from_template(self, template, destination):
"""Generate a file from a Jinja2 `template` and writes it to
`destination` using `params`.
`overwrite` allows to overwrite existing files. It is passed to
the `generate` method.
This is used by the different init imp... | Generate a file from a Jinja2 `template` and writes it to
`destination` using `params`.
`overwrite` allows to overwrite existing files. It is passed to
the `generate` method.
This is used by the different init implementations to generate
init scripts/configs and deploy them to ... |
def difference(self, instrument1, instrument2, bounds, data_labels,
cost_function):
"""
Calculates the difference in signals from multiple
instruments within the given bounds.
Parameters
----------
instrument1 : Instrument
Information must ... | Calculates the difference in signals from multiple
instruments within the given bounds.
Parameters
----------
instrument1 : Instrument
Information must already be loaded into the
instrument.
instrument2 : Instrument
Information must already b... |
def create(self, name, instance_dir=None, config='solrconfig.xml', schema='schema.xml'):
"""http://wiki.apache.org/solr/CoreAdmin#head-7ca1b98a9df8b8ca0dcfbfc49940ed5ac98c4a08"""
params = {
'action': 'CREATE',
'name': name,
'config': config,
'schema': sche... | http://wiki.apache.org/solr/CoreAdmin#head-7ca1b98a9df8b8ca0dcfbfc49940ed5ac98c4a08 |
def team_absent(name, profile="github", **kwargs):
'''
Ensure a team is absent.
Example:
.. code-block:: yaml
ensure team test is present in github:
github.team_absent:
- name: 'test'
The following parameters are required:
name
This is the name o... | Ensure a team is absent.
Example:
.. code-block:: yaml
ensure team test is present in github:
github.team_absent:
- name: 'test'
The following parameters are required:
name
This is the name of the team in the organization.
.. versionadded:: 2016.11.... |
def GetOrderKey(self):
"""Return a tuple that can be used to sort problems into a consistent order.
Returns:
A list of values.
"""
context_attributes = ['_type']
context_attributes.extend(ExceptionWithContext.CONTEXT_PARTS)
context_attributes.extend(self._GetExtraOrderAttributes())
t... | Return a tuple that can be used to sort problems into a consistent order.
Returns:
A list of values. |
def get_verba_link_for_schedule(self, schedule):
"""
Returns a link to verba. The link varies by campus and schedule.
Multiple calls to this with the same schedule may result in
different urls.
"""
dao = Book_DAO()
url = self.get_verba_url(schedule)
res... | Returns a link to verba. The link varies by campus and schedule.
Multiple calls to this with the same schedule may result in
different urls. |
def _slice_mostly_sorted(array, keep, rest, ind=None):
"""Slice dask array `array` that is almost entirely sorted already.
We perform approximately `2 * len(keep)` slices on `array`.
This is OK, since `keep` is small. Individually, each of these slices
is entirely sorted.
Parameters
----------... | Slice dask array `array` that is almost entirely sorted already.
We perform approximately `2 * len(keep)` slices on `array`.
This is OK, since `keep` is small. Individually, each of these slices
is entirely sorted.
Parameters
----------
array : dask.array.Array
keep : ndarray[Int]
... |
def get_capabilities_by_type(self, strict_type_matching: bool = False) -> Dict[Type, Dict[str, Dict[str, Parser]]]:
"""
For all types that are supported,
lists all extensions that can be parsed into such a type.
For each extension, provides the list of parsers supported. The order is "mo... | For all types that are supported,
lists all extensions that can be parsed into such a type.
For each extension, provides the list of parsers supported. The order is "most pertinent first"
This method is for monitoring and debug, so we prefer to not rely on the cache, but rather on the query eng... |
def rasterToPolygon(raster_file, polygon_file):
"""
Converts watershed raster to polygon and then dissolves it.
It dissolves features based on the LINKNO attribute.
"""
log("Process: Raster to Polygon ...")
time_start = datetime.utcnow()
temp_polygon_file = \
... | Converts watershed raster to polygon and then dissolves it.
It dissolves features based on the LINKNO attribute. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.