code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def plot_result(filt, full, prntres=True):
r"""QC the inversion result.
Parameters
----------
- filt, full as returned from fdesign.design with full_output=True
- If prntres is True, it calls fdesign.print_result as well.
r"""
# Check matplotlib (soft dependency)
if not plt:
pr... | r"""QC the inversion result.
Parameters
----------
- filt, full as returned from fdesign.design with full_output=True
- If prntres is True, it calls fdesign.print_result as well.
r |
def selections_group(self):
"""Group all selections"""
cmd.group('Structures', '%s %s %sCartoon' % (self.protname, self.ligname, self.protname))
cmd.group('Interactions', 'Hydrophobic HBonds HalogenBonds WaterBridges PiCation PiStackingP PiStackingT '
'Saltbridg... | Group all selections |
def previous(self):
"""
fetch the chart identified by this chart's previous_id attribute
if the previous_id is either null or not present for this chart return None
returns the new chart instance on sucess"""
try:
if self.previous_id:
return Ch... | fetch the chart identified by this chart's previous_id attribute
if the previous_id is either null or not present for this chart return None
returns the new chart instance on sucess |
def get_itoken(self, env):
"""Returns the current internal token to use for the auth system's own
actions with other services. Each process will create its own
itoken and the token will be deleted and recreated based on the
token_life configuration value. The itoken information is stored... | Returns the current internal token to use for the auth system's own
actions with other services. Each process will create its own
itoken and the token will be deleted and recreated based on the
token_life configuration value. The itoken information is stored in
memcache because the auth ... |
def addRelation(self, link):
'''Appends Relation
'''
if isinstance(link, Relation):
self.internalLinks.append(link)
else:
raise TypeError(
'link Type should be InternalLink, not %s' % type(link)) | Appends Relation |
def _createWorksheet(base, worksheettemplate, analyst):
"""
This function creates a new worksheet takeing advantatge of the analyst
variable. If there isn't an analyst definet, the system will puck up the
the first one obtained in a query.
"""
if not(analyst):
# Get any analyst
a... | This function creates a new worksheet takeing advantatge of the analyst
variable. If there isn't an analyst definet, the system will puck up the
the first one obtained in a query. |
def parameters(self) -> List['Parameter']:
"""Return a list of parameter objects."""
_lststr = self._lststr
_type_to_spans = self._type_to_spans
return [
Parameter(_lststr, _type_to_spans, span, 'Parameter')
for span in self._subspans('Parameter')] | Return a list of parameter objects. |
def serve(service_brokers: Union[List[ServiceBroker], ServiceBroker],
credentials: Union[List[BrokerCredentials], BrokerCredentials, None],
logger: logging.Logger = logging.root,
port=5000,
debug=False):
"""
Starts flask with the given brokers.
You can provide a list ... | Starts flask with the given brokers.
You can provide a list or just one ServiceBroker
:param service_brokers: ServicesBroker for services to provide
:param credentials: Username and password that will be required to communicate with service broker
:param logger: Used for api logs. This will not influen... |
def ntiles(self):
"""The number of tiles in this row
:type: `int`
"""
tcum_mismatch = self.duration * 2 * pi * self.frequency / self.q
return next_power_of_two(tcum_mismatch / self.deltam) | The number of tiles in this row
:type: `int` |
def _generate_SAX_single(self, sections, value):
"""
Generate SAX representation(Symbolic Aggregate approXimation) for a single data point.
Read more about it here: Assumption-Free Anomaly Detection in Time Series(http://alumni.cs.ucr.edu/~ratana/SSDBM05.pdf).
:param dict sections: value... | Generate SAX representation(Symbolic Aggregate approXimation) for a single data point.
Read more about it here: Assumption-Free Anomaly Detection in Time Series(http://alumni.cs.ucr.edu/~ratana/SSDBM05.pdf).
:param dict sections: value sections.
:param float value: value to be categorized.
... |
def put(self, pid, record, key):
"""Handle the file rename through the PUT deposit file.
Permission required: `update_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid.
:param key: Unique identifier for the file in the de... | Handle the file rename through the PUT deposit file.
Permission required: `update_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid.
:param key: Unique identifier for the file in the deposit. |
def safestr(value):
'''Ensure type to string serialization'''
if not value or isinstance(value, (int, float, bool, long)):
return value
elif isinstance(value, (date, datetime)):
return value.isoformat()
else:
return unicode(value) | Ensure type to string serialization |
def opt(self, *, exception=None, record=False, lazy=False, ansi=False, raw=False, depth=0):
r"""Parametrize a logging call to slightly change generated log message.
Parameters
----------
exception : |bool|, |tuple| or |Exception|, optional
If it does not evaluate as ``False`... | r"""Parametrize a logging call to slightly change generated log message.
Parameters
----------
exception : |bool|, |tuple| or |Exception|, optional
If it does not evaluate as ``False``, the passed exception is formatted and added to the
log message. It could be an |Excep... |
def declassify(to_remove, *args, **kwargs):
""" flatten the return values of the mite api.
"""
def argdecorate(fn):
""" enable the to_remove argument to the decorator. """
# wrap the function to get the original docstring
@wraps(fn)
def declassed(*args, **kwargs):
... | flatten the return values of the mite api. |
def address(obj):
"""Return object address as a string: '<classname @ address>'"""
return "<%s @ %s>" % (obj.__class__.__name__,
hex(id(obj)).upper().replace('X', 'x')) | Return object address as a string: '<classname @ address> |
def info(self, media_id):
"""
Получить информацию по файлу
:param media_id:
:rtype: requests.Response
"""
dr = self.__app.native_api_call('media', 'i/' + media_id, {}, self.__options, False, None, False, http_path="/api/meta/v1/", http_method='GET')
return json.lo... | Получить информацию по файлу
:param media_id:
:rtype: requests.Response |
def __update_siblings_active_labels_states(self, active_label):
"""
Updates given **Active_QLabel** Widget siblings states.
:param active_label: Active label.
:type active_label: Active_QLabel
"""
LOGGER.debug("> Clicked 'Active_QLabel': '{0}'.".format(active_label))
... | Updates given **Active_QLabel** Widget siblings states.
:param active_label: Active label.
:type active_label: Active_QLabel |
def init_app(self, app):
"""Setup via Flask."""
host = app.config.get('MONGO_HOST', 'localhost')
port = app.config.get('MONGO_PORT', 27017)
dbname = app.config['MONGO_DBNAME']
log.info("connecting to database: %s:%s/%s", host, port, dbname)
self.setup(app.config['MONGO_DA... | Setup via Flask. |
def _startSchedulesNode(self, name, attrs):
"""Process the start of a node under xtvd/schedules"""
if name == 'schedule':
self._programId = attrs.get('program')
self._stationId = attrs.get('station')
self._time = self._parseDateTime(attrs.get('time'))
sel... | Process the start of a node under xtvd/schedules |
def _get_error_reason(response):
"""Extract error reason from the response. It might be either
the 'reason' or the entire response
"""
try:
body = response.json()
if body and 'reason' in body:
return body['reason']
except ValueError:
... | Extract error reason from the response. It might be either
the 'reason' or the entire response |
def H(self, T):
"""
Calculate the enthalpy of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol] The enthalpy of the compound phase.
"""
result = self.DHref
for Tmax in sorted([float(TT) for TT in self._Cp_reco... | Calculate the enthalpy of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol] The enthalpy of the compound phase. |
def send_venue(
self,
chat_id: Union[int, str],
latitude: float,
longitude: float,
title: str,
address: str,
foursquare_id: str = "",
foursquare_type: str = "",
disable_notification: bool = None,
reply_to_message_id: int = None,
rep... | Use this method to send information about a venue.
Args:
chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.
For your personal cloud (Saved Messages) you can simply use "me" or "self".
For a contact that exists i... |
def change_dir(newdir):
"""Change directory.
Adapted from http://stackoverflow.com/a/24176022
"""
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
yield
finally:
os.chdir(prevdir) | Change directory.
Adapted from http://stackoverflow.com/a/24176022 |
def get_from_clause(self):
"""
Add the JOINS for related multilingual fields filtering.
"""
result = super(MultilingualSQLCompiler, self).get_from_clause()
if not self.query.include_translation_data:
return result
from_ = result[0]
for join in self.q... | Add the JOINS for related multilingual fields filtering. |
def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
if text is None:
return None
m = self.lex_pattern.match(text)
if not m:
raise EvaluateException('Bad Gregorian: %s' %text, ps.Backtrace(elt))
try:
... | convert text into typecode specific data. |
def solid_company(taxonomy, tax_ids):
"""Return a set of non-lonely species tax_ids that will make those in *tax_ids* not lonely."""
res = []
for t in tax_ids:
res.extend(taxonomy.nary_subtree(taxonomy.sibling_of(t), 2) or [])
return res | Return a set of non-lonely species tax_ids that will make those in *tax_ids* not lonely. |
def recordings(self):
"""
:rtype: twilio.rest.video.v1.recording.RecordingList
"""
if self._recordings is None:
self._recordings = RecordingList(self)
return self._recordings | :rtype: twilio.rest.video.v1.recording.RecordingList |
def evaluation_step(self, Xi, training=False):
"""Perform a forward step to produce the output used for
prediction and scoring.
Therefore the module is set to evaluation mode by default
beforehand which can be overridden to re-enable features
like dropout by setting ``training=T... | Perform a forward step to produce the output used for
prediction and scoring.
Therefore the module is set to evaluation mode by default
beforehand which can be overridden to re-enable features
like dropout by setting ``training=True``. |
def relabel(self, qubits: Qubits) -> 'QubitVector':
"""Return a copy of this vector with new qubits"""
qubits = tuple(qubits)
assert len(qubits) == self.qubit_nb
vec = copy(self)
vec.qubits = qubits
return vec | Return a copy of this vector with new qubits |
def set_structure(self, lattice, species, coords, coords_are_cartesian):
"""
Sets up the pymatgen structure for which the coordination geometries have to be identified starting from the
lattice, the species and the coordinates
:param lattice: The lattice of the structure
:param s... | Sets up the pymatgen structure for which the coordination geometries have to be identified starting from the
lattice, the species and the coordinates
:param lattice: The lattice of the structure
:param species: The species on the sites
:param coords: The coordinates of the sites
... |
def random_boggle(n=4):
"""Return a random Boggle board of size n x n.
We represent a board as a linear list of letters."""
cubes = [cubes16[i % 16] for i in range(n*n)]
random.shuffle(cubes)
return map(random.choice, cubes) | Return a random Boggle board of size n x n.
We represent a board as a linear list of letters. |
def chunks(self, shape=256, pad=False):
"""This method returns GeoRaster chunks out of the original raster.
The chunck is evaluated only when fetched from the iterator.
Useful when you want to iterate over a big rasters.
Parameters
----------
shape : int or tuple, optio... | This method returns GeoRaster chunks out of the original raster.
The chunck is evaluated only when fetched from the iterator.
Useful when you want to iterate over a big rasters.
Parameters
----------
shape : int or tuple, optional
The shape of the chunk. Default: 25... |
def connect(self):
"""
connect
"""
_logger.debug("Start connecting to broker")
while True:
try:
self.client.connect(self.broker_host, self.broker_port,
self.broker_keepalive)
break
except ... | connect |
def emit_java_classes(target, source, env):
"""Create and return lists of source java files
and their corresponding target class files.
"""
java_suffix = env.get('JAVASUFFIX', '.java')
class_suffix = env.get('JAVACLASSSUFFIX', '.class')
target[0].must_be_same(SCons.Node.FS.Dir)
classdir = t... | Create and return lists of source java files
and their corresponding target class files. |
def validate(cls, event_info):
"""Validate that provided event information is valid."""
assert 'service_key' in event_info
assert isinstance(event_info['service_key'], six.string_types)
assert 'event_type' in event_info
assert event_info['event_type'] in cls.EVENT_TYPES
i... | Validate that provided event information is valid. |
def prepend_www(url):
"""Changes google.com to www.google.com"""
parsed = urlparse(url)
if parsed.netloc.split(".")[0] != "www":
return parsed.scheme + "://www." + parsed.netloc + parsed.path
else:
return url | Changes google.com to www.google.com |
def is_required(action):
'''_actions which are positional or possessing the `required` flag '''
return not action.option_strings and not isinstance(action, _SubParsersAction) or action.required == True | _actions which are positional or possessing the `required` flag |
def join_path(*path_to_join, **kwargs):
"""Join input path to sample data path (usually in ~/lisa_data)
:param path_to_join: one or more paths
:param get_root: return dataset root path. If false, the path would be into "medical/orig"
:return: joined path
"""
if "get_root" in kwargs:
get... | Join input path to sample data path (usually in ~/lisa_data)
:param path_to_join: one or more paths
:param get_root: return dataset root path. If false, the path would be into "medical/orig"
:return: joined path |
def _set_lossless_priority(self, v, load=False):
"""
Setter method for lossless_priority, mapped from YANG variable /cee_map/remap/lossless_priority (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_lossless_priority is considered as a private
method. Backe... | Setter method for lossless_priority, mapped from YANG variable /cee_map/remap/lossless_priority (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_lossless_priority is considered as a private
method. Backends looking to populate this variable should
do so via ca... |
def enable_component_notification(self, openstack_component):
"""
Check if customer enable openstack component notification.
:param openstack_component: Openstack component type.
"""
openstack_component_mapping = {
Openstack.Nova: self.config.listen_nova_notification... | Check if customer enable openstack component notification.
:param openstack_component: Openstack component type. |
def put_device(self, pin, state, momentary=None, times=None, pause=None):
""" Actuate a device pin """
url = self.base_url + '/device'
payload = {
"pin": pin,
"state": state
}
if momentary is not None:
payload["momentary"] = momentary
... | Actuate a device pin |
def get_message(self):
"""
Gets the latest object from the backend, and handles unpickling
and validation.
"""
try:
m = self.get_from_backend()
if m and m["type"] not in SKIP_TYPES:
return self.decrypt(m["data"])
except AttributeEr... | Gets the latest object from the backend, and handles unpickling
and validation. |
def _parse_irc(self):
"""Parse intrinsic reaction coordinate calculation.
returns a dictionary containing:
geometries : a list of Molecule instances representing each point in the IRC
energies : a list of total energies (Hartree)
distances : distance from the starting point ... | Parse intrinsic reaction coordinate calculation.
returns a dictionary containing:
geometries : a list of Molecule instances representing each point in the IRC
energies : a list of total energies (Hartree)
distances : distance from the starting point in mass-weighted coords (bohr \sq... |
def _calc_all_possible_moves(self, input_color):
"""
Returns list of all possible moves
:type: input_color: Color
:rtype: list
"""
for piece in self:
# Tests if square on the board is not empty
if piece is not None and piece.color == input_color:... | Returns list of all possible moves
:type: input_color: Color
:rtype: list |
def write_metadata(self, output_path):
"""Build a JSON-LD dataset for LSST Projectmeta.
Parameters
----------
output_path : `str`
File path where the ``metadata.jsonld`` should be written for the
build.
"""
if self._config.lsstdoc is None:
... | Build a JSON-LD dataset for LSST Projectmeta.
Parameters
----------
output_path : `str`
File path where the ``metadata.jsonld`` should be written for the
build. |
def add_cli_populate(main: click.Group) -> click.Group: # noqa: D202
"""Add a ``populate`` command to main :mod:`click` function."""
@main.command()
@click.option('--reset', is_flag=True, help='Nuke database first')
@click.option('--force', is_flag=True, help='Force overwrite if already populated')
... | Add a ``populate`` command to main :mod:`click` function. |
def single_encode(input, errors='strict'):
"""Transliterate to 8 bit using only single letter replacements.
For example, \u2639 WHITE FROWNING FACE ``☹`` will be passed
through unchanged.
"""
if not isinstance(input, text_type):
input = text_type(input, sys.getdefaultencoding(), errors)
... | Transliterate to 8 bit using only single letter replacements.
For example, \u2639 WHITE FROWNING FACE ``☹`` will be passed
through unchanged. |
def results( self ):
"""Return a list of all the results currently available. This
excludes pending results. Results are returned as a single flat
list, so any repetition structure is lost.
:returns: a list of results"""
rs = []
for k in self._results.keys():
... | Return a list of all the results currently available. This
excludes pending results. Results are returned as a single flat
list, so any repetition structure is lost.
:returns: a list of results |
def _setup(self, word) -> List[str]:
"""
Prepares a word for syllable processing.
If the word starts with a prefix, process it separately.
:param word:
:return:
"""
if len(word) == 1:
return [word]
for prefix in self.constants.PREFIXES:
... | Prepares a word for syllable processing.
If the word starts with a prefix, process it separately.
:param word:
:return: |
def get_sparql_dataframe( self ):
''' Iterates through the sparql table and condenses it into a Pandas DataFrame '''
self.result = self.g.query(self.query)
cols = set() # set(['qname'])
indx = set()
data = {}
curr_subj = None # place marker for first subj to be processed
... | Iterates through the sparql table and condenses it into a Pandas DataFrame |
def get_topic(self):
""" Returns the considered topic if applicable. """
pk = self.kwargs.get(self.topic_pk_url_kwarg, None)
if not pk:
return
if not hasattr(self, '_topic'):
self._topic = get_object_or_404(Topic, pk=pk)
return self._topic | Returns the considered topic if applicable. |
def _apply_filter(self, filters, candidates):
""" Apply vector filters if specified and return filtered list """
if filters:
filter_input = candidates
for fetch_vector_filter in filters:
filter_input = fetch_vector_filter.filter_vectors(filter_input)
... | Apply vector filters if specified and return filtered list |
def set_value(hive,
key,
vname=None,
vdata=None,
vtype='REG_SZ',
use_32bit_registry=False,
volatile=False):
'''
Sets a value in the registry. If ``vname`` is passed, it will be the value
for that value name, otherwise it wil... | Sets a value in the registry. If ``vname`` is passed, it will be the value
for that value name, otherwise it will be the default value for the
specified key
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
... |
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_id_from_name(self, name):
"""List placement group ids which match the given name."""
_filter = {
'placementGroups': {
'name': {'operation': name}
}
}
mask = "mask[id, name]"
results = self.client.call('Account', 'getPlacementGroups... | List placement group ids which match the given name. |
def map_ids(x, indices, map_fn):
"""Apply a function to each coordinate ids of a multidimensional tensor.
This allows to process each sequence of a batch independently. This is
similar to tf.map_fn but with tensor where the batch dim has been flatten.
Warning: The indices ids have to be contiguous and ordered... | Apply a function to each coordinate ids of a multidimensional tensor.
This allows to process each sequence of a batch independently. This is
similar to tf.map_fn but with tensor where the batch dim has been flatten.
Warning: The indices ids have to be contiguous and ordered in memory as the
output vector for ... |
def vdp_vlan_change(self, vsw_cb_data, vdp_vlan, fail_reason):
"""Callback Function from VDP when provider VLAN changes.
This will be called only during error cases when switch
reloads or when compute reloads.
"""
LOG.debug("In VDP VLAN change VLAN %s" % vdp_vlan)
try:
... | Callback Function from VDP when provider VLAN changes.
This will be called only during error cases when switch
reloads or when compute reloads. |
def on_channel_open(self, channel):
"""
Invoked by pika when the channel has been opened.
The channel object is passed in so we can make use of it.
Since the channel is now open, we'll declare the exchange to use.
:param pika.channel.Channel channel: The channel object
... | Invoked by pika when the channel has been opened.
The channel object is passed in so we can make use of it.
Since the channel is now open, we'll declare the exchange to use.
:param pika.channel.Channel channel: The channel object |
def from_iris(cube):
""" Convert a Iris cube into an DataArray
"""
import iris.exceptions
from xarray.core.pycompat import dask_array_type
name = _name(cube)
if name == 'unknown':
name = None
dims = []
for i in range(cube.ndim):
try:
dim_coord = cube.coord(di... | Convert a Iris cube into an DataArray |
def _getDone(self, done, undone):
"""Parses the done|undone state.
:done: Done marking pattern.
:undone: Not done marking pattern.
:returns: Pattern for done|undone or None if neither were specified.
"""
if done:
return self._getPattern(done, True)
i... | Parses the done|undone state.
:done: Done marking pattern.
:undone: Not done marking pattern.
:returns: Pattern for done|undone or None if neither were specified. |
async def deploy(
self, entity_url, application_name=None, bind=None, budget=None,
channel=None, config=None, constraints=None, force=False,
num_units=1, plan=None, resources=None, series=None, storage=None,
to=None, devices=None):
"""Deploy a new service or bundl... | Deploy a new service or bundle.
:param str entity_url: Charm or bundle url
:param str application_name: Name to give the service
:param dict bind: <charm endpoint>:<network space> pairs
:param dict budget: <budget name>:<limit> pairs
:param str channel: Charm store channel from ... |
def get_doc_from_docid(self, docid, doc_type_name=None, inst=True):
"""
Try to find a document based on its document id. if inst=True, if it
hasn't been instantiated yet, it will be.
"""
assert(docid is not None)
if docid in self._docs_by_id:
return self._docs... | Try to find a document based on its document id. if inst=True, if it
hasn't been instantiated yet, it will be. |
def discover():
"""
Import all experiments listed in PLUGINS_EXPERIMENTS.
Tests:
>>> from benchbuild.settings import CFG
>>> from benchbuild.experiments import discover
>>> import logging as lg
>>> import sys
>>> l = lg.getLogger('benchbuild')
>>> lg.getLogge... | Import all experiments listed in PLUGINS_EXPERIMENTS.
Tests:
>>> from benchbuild.settings import CFG
>>> from benchbuild.experiments import discover
>>> import logging as lg
>>> import sys
>>> l = lg.getLogger('benchbuild')
>>> lg.getLogger('benchbuild').setLevel(lg.... |
def get_value(self, query):
"""Converts a dimension/category list of dicts into a data value \
in three steps.
Args:
query(list): list of dicts with the desired query.
Returns:
value(float): numeric data value.
"""
indices = self.get_dimension_ind... | Converts a dimension/category list of dicts into a data value \
in three steps.
Args:
query(list): list of dicts with the desired query.
Returns:
value(float): numeric data value. |
def get_vertical_orientation_property(value, is_bytes=False):
"""Get `VO` property."""
obj = unidata.ascii_vertical_orientation if is_bytes else unidata.unicode_vertical_orientation
if value.startswith('^'):
negated = value[1:]
value = '^' + unidata.unicode_alias['verticalorientation'].get... | Get `VO` property. |
def bulk_update(manager, model_objs, fields_to_update):
"""
Bulk updates a list of model objects that are already saved.
:type model_objs: list of :class:`Models<django:django.db.models.Model>`
:param model_objs: A list of model objects that have been updated.
fields_to_update: A list of fields... | Bulk updates a list of model objects that are already saved.
:type model_objs: list of :class:`Models<django:django.db.models.Model>`
:param model_objs: A list of model objects that have been updated.
fields_to_update: A list of fields to be updated. Only these fields will be updated
:signals: Em... |
def d_enable(
state, host, name,
start_priority=20, stop_priority=80,
start_levels=(2, 3, 4, 5), stop_levels=(0, 1, 6),
):
'''
Manually enable /etc/init.d scripts by creating /etc/rcX.d/Y links.
+ name: name of the service to enable
+ start_priority: priority to start the service
+ stop... | Manually enable /etc/init.d scripts by creating /etc/rcX.d/Y links.
+ name: name of the service to enable
+ start_priority: priority to start the service
+ stop_priority: priority to stop the service
+ start_levels: which runlevels should the service run when enabled
+ stop_levels: which runlevels ... |
def convert_to_picos(sdp, duplicate_moment_matrix=False):
"""Convert an SDP relaxation to a PICOS problem such that the exported
.dat-s file is extremely sparse, there is not penalty imposed in terms of
SDP variables or number of constraints. This conversion can be used for
imposing extra constraints on... | Convert an SDP relaxation to a PICOS problem such that the exported
.dat-s file is extremely sparse, there is not penalty imposed in terms of
SDP variables or number of constraints. This conversion can be used for
imposing extra constraints on the moment matrix, such as partial transpose.
:param sdp: T... |
def Kdp(scatterer):
"""
Specific differential phase (K_dp) for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
K_dp [deg/km].
NOTE: This only returns the correct value if the particle diameter and
wavelength are given in [mm]. The scatterer object should be ... | Specific differential phase (K_dp) for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
K_dp [deg/km].
NOTE: This only returns the correct value if the particle diameter and
wavelength are given in [mm]. The scatterer object should be set to
forward scattering g... |
def signedMDS(cdm, W=None):
""" Find the set of points from a cdm.
"""
N = cdm.shape[0]
D_sym = (cdm - cdm.T)
D_sym /= 2
if W is None:
x_est = np.mean(D_sym, axis=1)
x_est -= np.min(x_est)
return x_est
W_sub = W[1:, 1:]
sum_W = np.sum(W[1:, :], axis=1)
# ... | Find the set of points from a cdm. |
def enable_nn_ha(self, active_name, standby_host_id, nameservice, jns,
standby_name_dir_list=None, qj_name=None, standby_name=None,
active_fc_name=None, standby_fc_name=None, zk_service_name=None,
force_init_znode=True, clear_existing_standby_name_dirs=True, clear_existing_jn_edits_dir=True):
"""
... | Enable High Availability (HA) with Auto-Failover for an HDFS NameNode.
@param active_name: Name of Active NameNode.
@param standby_host_id: ID of host where Standby NameNode will be created.
@param nameservice: Nameservice to be used while enabling HA.
Optional if Active NameNode alr... |
def usb(
ctx, enable, disable, list, enable_all, touch_eject, no_touch_eject,
autoeject_timeout, chalresp_timeout, lock_code, force):
"""
Enable or disable applications over USB.
"""
def ensure_not_all_disabled(ctx, usb_enabled):
for app in APPLICATION:
if app & usb_... | Enable or disable applications over USB. |
def _normalize_slice(self, index, pipe=None):
"""Given a :obj:`slice` *index*, return a 4-tuple
``(start, stop, step, fowrward)``. The first three items can be used
with the ``range`` function to retrieve the values associated with the
slice; the last item indicates the direction.
... | Given a :obj:`slice` *index*, return a 4-tuple
``(start, stop, step, fowrward)``. The first three items can be used
with the ``range`` function to retrieve the values associated with the
slice; the last item indicates the direction. |
def _upload_s3(self, zip_file):
'''
Uploads the lambda package to s3
'''
s3_client = self._aws_session.client('s3')
transfer = boto3.s3.transfer.S3Transfer(s3_client)
transfer.upload_file(zip_file, self._config.s3_bucket,
self._config.s3_packa... | Uploads the lambda package to s3 |
def _fw_update(self, drvr_name, data):
"""Update routine for the Firewall.
Check if FW is already cfgd using the below function
if self.fwid_attr[tenant_id].is_fw_complete() or
is_fw_drvr_create_needed():
The above two functions will take care of whether FW is already
cf... | Update routine for the Firewall.
Check if FW is already cfgd using the below function
if self.fwid_attr[tenant_id].is_fw_complete() or
is_fw_drvr_create_needed():
The above two functions will take care of whether FW is already
cfgd or about to be cfgd in case of error.
I... |
def write_octet(self, n, pack=Struct('B').pack):
"""
Write an integer as an unsigned 8-bit value.
"""
if 0 <= n <= 255:
self._output_buffer.append(pack(n))
else:
raise ValueError('Octet %d out of range 0..255', n)
return self | Write an integer as an unsigned 8-bit value. |
def pyvcf_calls_to_sample_info_list(calls):
"""
Given pyvcf.model._Call instances, return a dict mapping each sample
name to its per-sample info:
sample name -> field -> value
"""
return OrderedDict(
(call.sample, call.data._asdict()) for call in calls) | Given pyvcf.model._Call instances, return a dict mapping each sample
name to its per-sample info:
sample name -> field -> value |
def api_request(self, url, **params):
"""
Make a trello API request. This takes an absolute url (without protocol
and host) and a list of argumnets and return a GET request with the
key and token from the configuration
"""
params['key'] = self.config.get('api_key'),
... | Make a trello API request. This takes an absolute url (without protocol
and host) and a list of argumnets and return a GET request with the
key and token from the configuration |
def has_add_permission(self, request):
"""
Returns True if the requesting user is allowed to add an object, False otherwise.
"""
perm_string = '%s.add_%s' % (self.model._meta.app_label,
self.model._meta.object_name.lower()
)
return request.user.has_perm(perm_s... | Returns True if the requesting user is allowed to add an object, False otherwise. |
def _sanitize_windows_name(cls, arcname, pathsep):
"""Replace bad characters and remove trailing dots from parts."""
table = cls._windows_illegal_name_trans_table
if not table:
illegal = ':<>|"?*'
table = str.maketrans(illegal, '_' * len(illegal))
cls._windows... | Replace bad characters and remove trailing dots from parts. |
def decode_mntp(mntp):
''' Mount point strings have a unique encoding for whitespace. :-/
https://stackoverflow.com/a/13576641/450917
https://stackoverflow.com/a/6117124/450917
'''
import re
replacements = {
r'\\040': ' ',
r'\\011': '\t',
r'\\012': '\n',
r... | Mount point strings have a unique encoding for whitespace. :-/
https://stackoverflow.com/a/13576641/450917
https://stackoverflow.com/a/6117124/450917 |
def check_and_del_zombie_workers(self): # pragma: no cover, not with unit tests...
# pylint: disable= not-callable
"""Check if worker are fine and kill them if not.
Dispatch the actions in the worker to another one
TODO: see if unit tests would allow to check this code?
:retur... | Check if worker are fine and kill them if not.
Dispatch the actions in the worker to another one
TODO: see if unit tests would allow to check this code?
:return: None |
def crc16_ccitt(data, crc=0):
"""Calculate the crc16 ccitt checksum of some data
A starting crc value may be specified if desired. The input data
is expected to be a sequence of bytes (string) and the output
is an integer in the range (0, 0xFFFF). No packing is done to the
resultant crc value. T... | Calculate the crc16 ccitt checksum of some data
A starting crc value may be specified if desired. The input data
is expected to be a sequence of bytes (string) and the output
is an integer in the range (0, 0xFFFF). No packing is done to the
resultant crc value. To check the value a checksum, just pa... |
def get_role(self, request: Request):
"""
None roles are stored as empty strings, so the role returned as None
by this function means that corresponding DID is not stored in a ledger.
"""
idr = request.identifier
return self._get_role(idr) | None roles are stored as empty strings, so the role returned as None
by this function means that corresponding DID is not stored in a ledger. |
def dialect_class(self, adapter):
"""Get dialect sql class by adapter"""
if self.dialects.get(adapter):
return self.dialects[adapter]
try:
class_prefix = getattr(
__import__('db.' + adapter, globals(), locals(),
['__class_prefix_... | Get dialect sql class by adapter |
def target_partname(self):
"""
|PackURI| instance containing partname targeted by this relationship.
Raises ``ValueError`` on reference if target_mode is ``'External'``.
Use :attr:`target_mode` to check before referencing.
"""
if self.is_external:
msg = ('targ... | |PackURI| instance containing partname targeted by this relationship.
Raises ``ValueError`` on reference if target_mode is ``'External'``.
Use :attr:`target_mode` to check before referencing. |
def get_exception_message(instance):
'''Try to get the exception message or the class name.'''
args = getattr(instance, 'args', None)
if args:
return str(instance)
try:
return type(instance).__name__
except AttributeError:
return str(instance) | Try to get the exception message or the class name. |
def print_report_on_all_logs() -> None:
"""
Use :func:`print` to report information on all logs.
"""
d = {}
# noinspection PyUnresolvedReferences
for name, obj in logging.Logger.manager.loggerDict.items():
d[name] = get_log_report(obj)
rootlogger = logging.getLogger()
d['(root lo... | Use :func:`print` to report information on all logs. |
def firmware_download_input_protocol_type_scp_protocol_scp_password(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware_download = ET.Element("firmware_download")
config = firmware_download
input = ET.SubElement(firmware_download, "input")
... | Auto Generated Code |
def run(self, stat_name, criticity, commands, repeat, mustache_dict=None):
"""Run the commands (in background).
- stats_name: plugin_name (+ header)
- criticity: criticity of the trigger
- commands: a list of command line with optional {{mustache}}
- If True, then repeat the act... | Run the commands (in background).
- stats_name: plugin_name (+ header)
- criticity: criticity of the trigger
- commands: a list of command line with optional {{mustache}}
- If True, then repeat the action
- mustache_dict: Plugin stats (can be use within {{mustache}})
Re... |
def diff_record(self, record):
"""Return the removed and added diffs"""
rec = self.get_record(record._record_type, record.host)
if rec is not None and record is not None:
return {'removed': tuple(set(rec.results) - set(record.results)),
'added': tuple(set(record.r... | Return the removed and added diffs |
def _notify_remove(self, slice_):
"""Notify about a RemoveChange."""
change = RemoveChange(self, slice_)
self.notify_observers(change) | Notify about a RemoveChange. |
def get_condition(self):
"""
Determines the condition to be used in the condition part of the join sql.
:return: The condition for the join clause
:rtype: str or None
"""
if self.condition:
return self.condition
if type(self.right_table) is ModelTabl... | Determines the condition to be used in the condition part of the join sql.
:return: The condition for the join clause
:rtype: str or None |
def lt(computation: BaseComputation) -> None:
"""
Lesser Comparison
"""
left, right = computation.stack_pop(num_items=2, type_hint=constants.UINT256)
if left < right:
result = 1
else:
result = 0
computation.stack_push(result) | Lesser Comparison |
def filter_int(n: Node, query: str) -> int:
"""
Filter and ensure that the returned value is of type int.
"""
return _scalariter2item(n, query, int) | Filter and ensure that the returned value is of type int. |
def has_overflow(self, params):
""" detect inf and nan """
is_not_finite = 0
for param in params:
if param.grad_req != 'null':
grad = param.list_grad()[0]
is_not_finite += mx.nd.contrib.isnan(grad).sum()
is_not_finite += mx.nd.contrib.i... | detect inf and nan |
def range_is_obj(rng, rdfclass):
""" Test to see if range for the class should be an object
or a litteral
"""
if rng == 'rdfs_Literal':
return False
if hasattr(rdfclass, rng):
mod_class = getattr(rdfclass, rng)
for item in mod_class.cls_defs['rdf_type']:
try:
... | Test to see if range for the class should be an object
or a litteral |
def relative_to_absolute_name(self, modname, level):
"""Get the absolute module name for a relative import.
The relative import can be implicit or explicit.
:param modname: The module name to convert.
:type modname: str
:param level: The level of relative import.
:type... | Get the absolute module name for a relative import.
The relative import can be implicit or explicit.
:param modname: The module name to convert.
:type modname: str
:param level: The level of relative import.
:type level: int
:returns: The absolute module name.
... |
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
root
use root as top level directory (default: "/")
CLI examples:
... | List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
root
use root as top level directory (default: "/")
CLI examples:
.. code-block:: bash
salt '*' lowpk... |
def _fill_and_verify_padding(padding, n):
"""Verifies that the provided padding is supported and expands to size n.
Args:
padding: One of ALLOWED_PADDINGS, or an iterable of them.
n: An integer, the size of the desired output list.
Returns:
If `padding` is one of ALLOWED_PADDINGS, a tuple of size `n... | Verifies that the provided padding is supported and expands to size n.
Args:
padding: One of ALLOWED_PADDINGS, or an iterable of them.
n: An integer, the size of the desired output list.
Returns:
If `padding` is one of ALLOWED_PADDINGS, a tuple of size `n` containing `n`
copies of `padding`.
I... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.