code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def add_user(name, profile='github'):
'''
Add a GitHub user.
name
The user for which to obtain information.
profile
The name of the profile configuration to use. Defaults to ``github``.
CLI Example:
.. code-block:: bash
salt myminion github.add_user github-handle
... | Add a GitHub user.
name
The user for which to obtain information.
profile
The name of the profile configuration to use. Defaults to ``github``.
CLI Example:
.. code-block:: bash
salt myminion github.add_user github-handle |
def actionAngleTorus_xvFreqs_c(pot,jr,jphi,jz,
angler,anglephi,anglez,
tol=0.003):
"""
NAME:
actionAngleTorus_xvFreqs_c
PURPOSE:
compute configuration (x,v) and frequencies of a set of angles on a single torus
INPUT:
pot ... | NAME:
actionAngleTorus_xvFreqs_c
PURPOSE:
compute configuration (x,v) and frequencies of a set of angles on a single torus
INPUT:
pot - Potential object or list thereof
jr - radial action (scalar)
jphi - azimuthal action (scalar)
jz - vertical action (scalar)
ang... |
def to_dict(cls, obj):
'''Serialises the object, by default serialises anything
that isn't prefixed with __, isn't in the blacklist, and isn't
callable.
'''
return {
k: getattr(obj, k)
for k in dir(obj)
if cls.serialisable(k, obj)
} | Serialises the object, by default serialises anything
that isn't prefixed with __, isn't in the blacklist, and isn't
callable. |
def create_folder_structure(self):
"""Creates a folder structure based on the project and batch name.
Project - Batch-name - Raw-data-dir
The info_df JSON-file will be stored in the Project folder.
The summary-files will be saved in the Batch-name folder.
The raw data (includin... | Creates a folder structure based on the project and batch name.
Project - Batch-name - Raw-data-dir
The info_df JSON-file will be stored in the Project folder.
The summary-files will be saved in the Batch-name folder.
The raw data (including exported cycles and ica-data) will be saved ... |
def timed_operation(msg, log_start=False):
"""
Surround a context with a timer.
Args:
msg(str): the log to print.
log_start(bool): whether to print also at the beginning.
Example:
.. code-block:: python
with timed_operation('Good Stuff'):
time.sleep... | Surround a context with a timer.
Args:
msg(str): the log to print.
log_start(bool): whether to print also at the beginning.
Example:
.. code-block:: python
with timed_operation('Good Stuff'):
time.sleep(1)
Will print:
.. code-block:: pytho... |
def mcast_ip_mask(ip_addr_and_mask, return_tuple=True):
"""
Function to check if a address is multicast and that the CIDR mask is good
Args:
ip_addr_and_mask: Multicast IP address and mask in the following format 239.1.1.1/24
return_tuple: Set to True it returns a IP and mask in a tuple, set... | Function to check if a address is multicast and that the CIDR mask is good
Args:
ip_addr_and_mask: Multicast IP address and mask in the following format 239.1.1.1/24
return_tuple: Set to True it returns a IP and mask in a tuple, set to False returns True or False
Returns: see return_tuple for r... |
def join_room(self, room_id_or_alias):
"""Performs /join/$room_id
Args:
room_id_or_alias (str): The room ID or room alias to join.
"""
if not room_id_or_alias:
raise MatrixError("No alias or room ID to join.")
path = "/join/%s" % quote(room_id_or_alias)
... | Performs /join/$room_id
Args:
room_id_or_alias (str): The room ID or room alias to join. |
def split_header_words(header_values):
r"""Parse header values into a list of lists containing key,value pairs.
The function knows how to deal with ",", ";" and "=" as well as quoted
values after "=". A list of space separated tokens are parsed as if they
were separated by ";".
If the header_valu... | r"""Parse header values into a list of lists containing key,value pairs.
The function knows how to deal with ",", ";" and "=" as well as quoted
values after "=". A list of space separated tokens are parsed as if they
were separated by ";".
If the header_values passed as argument contains multiple val... |
def MRA(biomf, sampleIDs=None, transform=None):
"""
Calculate the mean relative abundance percentage.
:type biomf: A BIOM file.
:param biomf: OTU table format.
:type sampleIDs: list
:param sampleIDs: A list of sample id's from BIOM format OTU table.
:param transform: Mathematical function... | Calculate the mean relative abundance percentage.
:type biomf: A BIOM file.
:param biomf: OTU table format.
:type sampleIDs: list
:param sampleIDs: A list of sample id's from BIOM format OTU table.
:param transform: Mathematical function which is used to transform smax to another
... |
def run_shell_command(commands, **kwargs):
"""Run a shell command."""
p = subprocess.Popen(commands,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
**kwargs)
output, error = p.communicate()
return p.returncode, output, error | Run a shell command. |
def xml_filter(self, content):
r"""Filter and preprocess xml content
:param content: xml content
:rtype: str
"""
content = utils.strip_whitespace(content, True) if self.__options['strip'] else content.strip()
if not self.__options['encoding']:
encoding = sel... | r"""Filter and preprocess xml content
:param content: xml content
:rtype: str |
def load_simple_endpoint(category, name):
'''fetches the entry point for a plugin and calls it with the given
aux_info'''
for ep in pkg_resources.iter_entry_points(category):
if ep.name == name:
return ep.load()
raise KeyError(name) | fetches the entry point for a plugin and calls it with the given
aux_info |
def removeTab(self, index):
"""
Removes the view at the inputed index and disconnects it from the \
panel.
:param index | <int>
"""
view = self.widget(index)
if isinstance(view, XView):
try:
view.windowTitleChanged.disconn... | Removes the view at the inputed index and disconnects it from the \
panel.
:param index | <int> |
def readACTIONRECORD(self):
""" Read a SWFActionRecord """
action = None
actionCode = self.readUI8()
if actionCode != 0:
actionLength = self.readUI16() if actionCode >= 0x80 else 0
#print "0x%x"%actionCode, actionLength
action = SWFActionFactory.create... | Read a SWFActionRecord |
def cutR_seq(seq, cutR, max_palindrome):
"""Cut genomic sequence from the right.
Parameters
----------
seq : str
Nucleotide sequence to be cut from the right
cutR : int
cutR - max_palindrome = how many nucleotides to cut from the right.
Negative cutR implies complementary pa... | Cut genomic sequence from the right.
Parameters
----------
seq : str
Nucleotide sequence to be cut from the right
cutR : int
cutR - max_palindrome = how many nucleotides to cut from the right.
Negative cutR implies complementary palindromic insertions.
max_palindrome : int
... |
def to_tgt(self):
"""
Returns the native format of an AS_REP message and the sessionkey in EncryptionKey native format
"""
enc_part = EncryptedData({'etype': 1, 'cipher': b''})
tgt_rep = {}
tgt_rep['pvno'] = krb5_pvno
tgt_rep['msg-type'] = MESSAGE_TYPE.KRB_AS_REP.value
tgt_rep['crealm'] = self.server... | Returns the native format of an AS_REP message and the sessionkey in EncryptionKey native format |
def from_string(cls, link):
"""Return a new SheetUrl instance from parsed URL string.
>>> SheetUrl.from_string('https://docs.google.com/spreadsheets/d/spam')
<SheetUrl id='spam' gid=0>
"""
ma = cls._pattern.search(link)
if ma is None:
raise ValueError(link)
... | Return a new SheetUrl instance from parsed URL string.
>>> SheetUrl.from_string('https://docs.google.com/spreadsheets/d/spam')
<SheetUrl id='spam' gid=0> |
def run_with(self, inputs, options):
""" Store the run parameters (inputs and options)
"""
self._inputs = inputs
self._options = options | Store the run parameters (inputs and options) |
def from_json(cls, data):
"""Create a Design Day from a dictionary.
Args:
data = {
"name": string,
"day_type": string,
"location": ladybug Location schema,
"dry_bulb_condition": ladybug DryBulbCondition schema,
"humidity_condition"... | Create a Design Day from a dictionary.
Args:
data = {
"name": string,
"day_type": string,
"location": ladybug Location schema,
"dry_bulb_condition": ladybug DryBulbCondition schema,
"humidity_condition": ladybug HumidityCondition schema,
... |
def do_b0(self, line):
"""Send the Master a BinaryInput (group 2) value of False at index 6. Command syntax is: b0"""
self.application.apply_update(opendnp3.Binary(False), index=6) | Send the Master a BinaryInput (group 2) value of False at index 6. Command syntax is: b0 |
def get_base(vpc, **conn):
"""
The base will return:
- ARN
- Region
- Name
- Id
- Tags
- IsDefault
- InstanceTenancy
- CidrBlock
- CidrBlockAssociationSet
- Ipv6CidrBlockAssociationSet
- DhcpOptionsId
- Attributes
- _version
:param bucket_name:
:param... | The base will return:
- ARN
- Region
- Name
- Id
- Tags
- IsDefault
- InstanceTenancy
- CidrBlock
- CidrBlockAssociationSet
- Ipv6CidrBlockAssociationSet
- DhcpOptionsId
- Attributes
- _version
:param bucket_name:
:param conn:
:return: |
def attributes(self):
"""List of attributes available for the dataset (cached)."""
if self._attributes is None:
self._filters, self._attributes = self._fetch_configuration()
return self._attributes | List of attributes available for the dataset (cached). |
def _fw_rule_create(self, drvr_name, data, cache):
"""Firewall Rule create routine.
This function updates its local cache with rule parameters.
It checks if local cache has information about the Policy
associated with the rule. If not, it means a restart has happened.
It retriev... | Firewall Rule create routine.
This function updates its local cache with rule parameters.
It checks if local cache has information about the Policy
associated with the rule. If not, it means a restart has happened.
It retrieves the policy associated with the FW by calling
Openst... |
def execute_function(function_request):
"""
Given a request created by
`beanstalk_dispatch.common.create_request_body`, executes the
request. This function is to be run on a beanstalk worker.
"""
dispatch_table = getattr(settings, 'BEANSTALK_DISPATCH_TABLE', None)
if dispatch_table is None... | Given a request created by
`beanstalk_dispatch.common.create_request_body`, executes the
request. This function is to be run on a beanstalk worker. |
def _create_alignment_button(self):
"""Creates vertical alignment button"""
iconnames = ["AlignTop", "AlignCenter", "AlignBottom"]
bmplist = [icons[iconname] for iconname in iconnames]
self.alignment_tb = _widgets.BitmapToggleButton(self, bmplist)
self.alignment_tb.SetToolTipSt... | Creates vertical alignment button |
def heartbeat(self):
"""
Heartbeats update the job's entry in the database with a timestamp
for the latest_heartbeat and allows for the job to be killed
externally. This allows at the system level to monitor what is
actually active.
For instance, an old heartbeat for Sch... | Heartbeats update the job's entry in the database with a timestamp
for the latest_heartbeat and allows for the job to be killed
externally. This allows at the system level to monitor what is
actually active.
For instance, an old heartbeat for SchedulerJob would mean something
is... |
def write(self, data):
"""
Intercepted method for writing data.
:param data:
Data to write
:returns:
Whatever the original method returns
:raises:
Whatever the original method raises
This method updates the internal digest object with... | Intercepted method for writing data.
:param data:
Data to write
:returns:
Whatever the original method returns
:raises:
Whatever the original method raises
This method updates the internal digest object with with the new data
and then proceed... |
def read(self):
'''Read from any of the connections that need it'''
# We'll check all living connections
connections = [c for c in self.connections() if c.alive()]
if not connections:
# If there are no connections, obviously we return no messages, but
# we should... | Read from any of the connections that need it |
def remove_tag(self, tag):
"""Remove tag from existing device tags
:param tag: the tag to be removed from the list
:raises ValueError: If tag does not exist in list
"""
tags = self.get_tags()
tags.remove(tag)
post_data = TAGS_TEMPLATE.format(connectware_id=sel... | Remove tag from existing device tags
:param tag: the tag to be removed from the list
:raises ValueError: If tag does not exist in list |
def write_info(dirs, parallel, config):
"""Write cluster or local filesystem resources, spinning up cluster if not present.
"""
if parallel["type"] in ["ipython"] and not parallel.get("run_local"):
out_file = _get_cache_file(dirs, parallel)
if not utils.file_exists(out_file):
sys... | Write cluster or local filesystem resources, spinning up cluster if not present. |
def set_up(self):
"""Set up your applications and the test environment."""
self.path.profile = self.path.gen.joinpath("profile")
if not self.path.profile.exists():
self.path.profile.mkdir()
self.python = hitchpylibrarytoolkit.project_build(
"strictyaml",
... | Set up your applications and the test environment. |
def check_aggregations_privacy(self, aggregations_params):
""" Check per-field privacy rules in aggregations.
Privacy is checked by making sure user has access to the fields
used in aggregations.
"""
fields = self.get_aggregations_fields(aggregations_params)
fields_dict ... | Check per-field privacy rules in aggregations.
Privacy is checked by making sure user has access to the fields
used in aggregations. |
def Maybe(validator):
"""
Wraps the given validator callable, only using it for the given value if it
is not ``None``.
"""
@wraps(Maybe)
def built(value):
if value != None:
return validator(value)
return built | Wraps the given validator callable, only using it for the given value if it
is not ``None``. |
def pif_list(call=None):
'''
Get a list of Resource Pools
.. code-block:: bash
salt-cloud -f pool_list myxen
'''
if call != 'function':
raise SaltCloudSystemExit(
'This function must be called with -f, --function argument.'
)
ret = {}
session = _get_sess... | Get a list of Resource Pools
.. code-block:: bash
salt-cloud -f pool_list myxen |
def all(self, *, collection, attribute, word, func=None, operation=None):
""" Performs a filter with the OData 'all' keyword on the collection
For example:
q.any(collection='email_addresses', attribute='address',
operation='eq', word='george@best.com')
will transform to a filte... | Performs a filter with the OData 'all' keyword on the collection
For example:
q.any(collection='email_addresses', attribute='address',
operation='eq', word='george@best.com')
will transform to a filter such as:
emailAddresses/all(a:a/address eq 'george@best.com')
:par... |
def get_new_connection(self, connection_params):
"""
Receives a dictionary connection_params to setup
a connection to the database.
Dictionary correct setup is made through the
get_connection_params method.
TODO: This needs to be made more generic to accept
othe... | Receives a dictionary connection_params to setup
a connection to the database.
Dictionary correct setup is made through the
get_connection_params method.
TODO: This needs to be made more generic to accept
other MongoClient parameters. |
def is_tp(self, atol=None, rtol=None):
"""Test if a channel is completely-positive (CP)"""
choi = _to_choi(self.rep, self._data, *self.dim)
return self._is_tp_helper(choi, atol, rtol) | Test if a channel is completely-positive (CP) |
def density(self, *args):
""" Mean density in g/cc
"""
M = self.mass(*args) * MSUN
V = 4./3 * np.pi * (self.radius(*args) * RSUN)**3
return M/V | Mean density in g/cc |
def load_manual_sequence_file(self, ident, seq_file, copy_file=False, outdir=None, set_as_representative=False):
"""Load a manual sequence, given as a FASTA file and optionally set it as the representative sequence.
Also store it in the sequences attribute.
Args:
ident (str): Sequen... | Load a manual sequence, given as a FASTA file and optionally set it as the representative sequence.
Also store it in the sequences attribute.
Args:
ident (str): Sequence ID
seq_file (str): Path to sequence FASTA file
copy_file (bool): If the FASTA file should be copi... |
def kong_61_2007():
r"""Kong 61 pt Hankel filter, as published in [Kong07]_.
Taken from file ``FilterModules.f90`` provided with 1DCSEM_.
License: `Apache License, Version 2.0,
<http://www.apache.org/licenses/LICENSE-2.0>`_.
"""
dlf = DigitalFilter('Kong 61', 'kong_61_2007')
dlf.base = ... | r"""Kong 61 pt Hankel filter, as published in [Kong07]_.
Taken from file ``FilterModules.f90`` provided with 1DCSEM_.
License: `Apache License, Version 2.0,
<http://www.apache.org/licenses/LICENSE-2.0>`_. |
def feed_ssldata(self, data):
"""Feed SSL record level data into the pipe.
The data must be a bytes instance. It is OK to send an empty bytes
instance. This can be used to get ssldata for a handshake initiated by
this endpoint.
Return a (ssldata, appdata) tuple. The ssldata ele... | Feed SSL record level data into the pipe.
The data must be a bytes instance. It is OK to send an empty bytes
instance. This can be used to get ssldata for a handshake initiated by
this endpoint.
Return a (ssldata, appdata) tuple. The ssldata element is a list of
buffers contain... |
def build_from_generator(cls,
generator,
target_size,
max_subtoken_length=None,
reserved_tokens=None):
"""Builds a SubwordTextEncoder from the generated text.
Args:
generator: yields text.
ta... | Builds a SubwordTextEncoder from the generated text.
Args:
generator: yields text.
target_size: int, approximate vocabulary size to create.
max_subtoken_length: Maximum length of a subtoken. If this is not set,
then the runtime and memory use of creating the vocab is quadratic in
... |
async def _get_difference(self, channel_id, pts_date):
"""
Get the difference for this `channel_id` if any, then load entities.
Calls :tl:`updates.getDifference`, which fills the entities cache
(always done by `__call__`) and lets us know about the full entities.
"""
# F... | Get the difference for this `channel_id` if any, then load entities.
Calls :tl:`updates.getDifference`, which fills the entities cache
(always done by `__call__`) and lets us know about the full entities. |
def benchmark(self, func, gpu_args, instance, times, verbose):
"""benchmark the kernel instance"""
logging.debug('benchmark ' + instance.name)
logging.debug('thread block dimensions x,y,z=%d,%d,%d', *instance.threads)
logging.debug('grid dimensions x,y,z=%d,%d,%d', *instance.grid)
... | benchmark the kernel instance |
def rollback(self, dt):
"""
Roll provided date backward to next offset only if not on offset.
"""
if not self.onOffset(dt):
businesshours = self._get_business_hours_by_sec
if self.n >= 0:
dt = self._prev_opening_time(
dt) + time... | Roll provided date backward to next offset only if not on offset. |
def rsa_private_key_pkcs1_to_pkcs8(pkcs1_key):
"""Convert a PKCS1-encoded RSA private key to PKCS8."""
algorithm = RsaAlgorithmIdentifier()
algorithm["rsaEncryption"] = RSA_ENCRYPTION_ASN1_OID
pkcs8_key = PKCS8PrivateKey()
pkcs8_key["version"] = 0
pkcs8_key["privateKeyAlgorithm"] = algorithm
... | Convert a PKCS1-encoded RSA private key to PKCS8. |
def _load_data_alignment(self, chain1, chain2):
"""
Extract the sequences from the PDB file, perform the alignment,
and load the coordinates of the CA of the common residues.
"""
parser = PDB.PDBParser(QUIET=True)
ppb = PDB.PPBuilder()
structure1 = parser.get_str... | Extract the sequences from the PDB file, perform the alignment,
and load the coordinates of the CA of the common residues. |
def export_coreml(self, filename):
"""
Save the model in Core ML format.
See Also
--------
save
Examples
--------
>>> model.export_coreml('./myModel.mlmodel')
"""
import coremltools
from coremltools.proto.FeatureTypes_pb2 import A... | Save the model in Core ML format.
See Also
--------
save
Examples
--------
>>> model.export_coreml('./myModel.mlmodel') |
def splitSymbol(self, index):
"""Give relevant values for computations:
(insertSymbol, copySymbol, dist0flag)
"""
#determine insert and copy upper bits from table
row = [0,0,1,1,2,2,1,3,2,3,3][index>>6]
col = [0,1,0,1,0,1,2,0,2,1,2][index>>6]
#determine inserts an... | Give relevant values for computations:
(insertSymbol, copySymbol, dist0flag) |
def affiliation_history(self):
"""Unordered list of IDs of all affiliations the author was
affiliated with acccording to Scopus.
"""
affs = self._json.get('affiliation-history', {}).get('affiliation')
try:
return [d['@id'] for d in affs]
except TypeError: # N... | Unordered list of IDs of all affiliations the author was
affiliated with acccording to Scopus. |
def import_crud(app):
'''
Import crud module and register all model cruds which it contains
'''
try:
app_path = import_module(app).__path__
except (AttributeError, ImportError):
return None
try:
imp.find_module('crud', app_path)
except ImportError:
return No... | Import crud module and register all model cruds which it contains |
def to_url(self):
"""Serialize as a URL for a GET request."""
base_url = urlparse(self.url)
if PY3:
query = parse_qs(base_url.query)
for k, v in self.items():
query.setdefault(k, []).append(to_utf8_optional_iterator(v))
scheme = base_url.schem... | Serialize as a URL for a GET request. |
def get_activities_for_project(self, module=None, **kwargs):
"""Get the related activities of a project.
:param str module: Stages of a given module
:return: JSON
"""
_module_id = kwargs.get('module', module)
_activities_url = ACTIVITIES_URL.format(module_id=_module_id)... | Get the related activities of a project.
:param str module: Stages of a given module
:return: JSON |
def _options_request(self, url, **kwargs):
''' a method to catch and report http options request connectivity errors '''
# construct request kwargs
request_kwargs = {
'method': 'OPTIONS',
'url': url
}
for key, value in kwargs.items()... | a method to catch and report http options request connectivity errors |
def pathconf(path,
os_name=os.name,
isdir_fnc=os.path.isdir,
pathconf_fnc=getattr(os, 'pathconf', None),
pathconf_names=getattr(os, 'pathconf_names', ())):
'''
Get all pathconf variables for given path.
:param path: absolute fs path
:type path: str
... | Get all pathconf variables for given path.
:param path: absolute fs path
:type path: str
:returns: dictionary containing pathconf keys and their values (both str)
:rtype: dict |
def add_instruction(self, specification):
"""Add an instruction specification
:param specification: a specification with a key
:data:`knittingpattern.Instruction.TYPE`
.. seealso:: :meth:`as_instruction`
"""
instruction = self.as_instruction(specification)
sel... | Add an instruction specification
:param specification: a specification with a key
:data:`knittingpattern.Instruction.TYPE`
.. seealso:: :meth:`as_instruction` |
def _gen_success_message(publish_output):
"""
Generate detailed success message for published applications.
Parameters
----------
publish_output : dict
Output from serverlessrepo publish_application
Returns
-------
str
Detailed success message
"""
application_id... | Generate detailed success message for published applications.
Parameters
----------
publish_output : dict
Output from serverlessrepo publish_application
Returns
-------
str
Detailed success message |
def dfbool2intervals(df,colbool):
"""
ds contains bool values
"""
df.index=range(len(df))
intervals=bools2intervals(df[colbool])
for intervali,interval in enumerate(intervals):
df.loc[interval[0]:interval[1],f'{colbool} interval id']=intervali
df.loc[interval[0]:interval[1],f'{co... | ds contains bool values |
def get_instance(self, payload):
"""
Build an instance of AuthTypeCallsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsInstance
:rtype: twilio.rest.api.v2010.account.sip.do... | Build an instance of AuthTypeCallsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsInstance
:rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.auth_calls_mapping.AuthTypeCallsInsta... |
def evaluate(self, global_state: GlobalState, post=False) -> List[GlobalState]:
"""Performs the mutation for this instruction.
:param global_state:
:param post:
:return:
"""
# Generalize some ops
log.debug("Evaluating {}".format(self.op_code))
op = self.o... | Performs the mutation for this instruction.
:param global_state:
:param post:
:return: |
def safe_version(version):
"""
Convert an arbitrary string to a standard version string
"""
try:
# normalize the version
return str(packaging.version.Version(version))
except packaging.version.InvalidVersion:
version = version.replace(' ', '.')
return re.sub('[^A-Za-z... | Convert an arbitrary string to a standard version string |
def dump_to_stream(self, cnf, stream, **opts):
"""
:param cnf: Configuration data to dump
:param stream: Config file or file like object write to
:param opts: optional keyword parameters
"""
tree = container_to_etree(cnf, **opts)
etree_write(tree, stream) | :param cnf: Configuration data to dump
:param stream: Config file or file like object write to
:param opts: optional keyword parameters |
def save_split_next(self):
"""
Save out blurbs created from "blurb split".
They don't have dates, so we have to get creative.
"""
filenames = []
# the "date" MUST have a leading zero.
# this ensures these files sort after all
# newly created blurbs.
... | Save out blurbs created from "blurb split".
They don't have dates, so we have to get creative. |
def destroy(self):
"""
Destroy and close the App.
:return:
None.
:note:
Once destroyed an App can no longer be used.
"""
# if this is the main_app - set the _main_app class variable to `None`.
if self == App._main_app:
App._m... | Destroy and close the App.
:return:
None.
:note:
Once destroyed an App can no longer be used. |
def get_electron_number(self, charge=0):
"""Return the number of electrons.
Args:
charge (int): Charge of the molecule.
Returns:
int:
"""
atomic_number = constants.elements['atomic_number'].to_dict()
return sum([atomic_number[atom] for atom in se... | Return the number of electrons.
Args:
charge (int): Charge of the molecule.
Returns:
int: |
def measure_impedance(self, sampling_window_ms, n_sampling_windows,
delay_between_windows_ms, interleave_samples, rms,
state):
'''
Measure voltage across load of each of the following control board
feedback circuits:
- Reference _(i.e... | Measure voltage across load of each of the following control board
feedback circuits:
- Reference _(i.e., attenuated high-voltage amplifier output)_.
- Load _(i.e., voltage across DMF device)_.
The measured voltage _(i.e., ``V2``)_ can be used to compute the
impedance of the ... |
def _make_index_list(num_samples, num_params, num_groups=None):
"""Identify indices of input sample associated with each trajectory
For each trajectory, identifies the indexes of the input sample which
is a function of the number of factors/groups and the number of samples
Arguments
... | Identify indices of input sample associated with each trajectory
For each trajectory, identifies the indexes of the input sample which
is a function of the number of factors/groups and the number of samples
Arguments
---------
num_samples : int
The number of traject... |
def write_data(self, buf):
"""Send data to the device.
If the write fails for any reason, an :obj:`IOError` exception
is raised.
:param buf: the data to send.
:type buf: list(int)
:return: success status.
:rtype: bool
"""
result = self.devh.c... | Send data to the device.
If the write fails for any reason, an :obj:`IOError` exception
is raised.
:param buf: the data to send.
:type buf: list(int)
:return: success status.
:rtype: bool |
def SegmentSum(a, ids, *args):
"""
Segmented sum op.
"""
func = lambda idxs: reduce(np.add, a[idxs])
return seg_map(func, a, ids), | Segmented sum op. |
def _readoct(self, length, start):
"""Read bits and interpret as an octal string."""
if length % 3:
raise InterpretError("Cannot convert to octal unambiguously - "
"not multiple of 3 bits.")
if not length:
return ''
# Get main octa... | Read bits and interpret as an octal string. |
def add_prefix(self):
""" Add prefix according to the specification.
The following keys can be used:
vrf ID of VRF to place the prefix in
prefix the prefix to add if already known
family address family (4 or 6)
descripti... | Add prefix according to the specification.
The following keys can be used:
vrf ID of VRF to place the prefix in
prefix the prefix to add if already known
family address family (4 or 6)
description A short description
... |
def _select_list_view(self, model, **kwargs):
"""
:param model:
:param fields_convert_map: it's different from ListView
:param kwargs:
:return:
"""
from uliweb import request
# add download fields process
fields = kwargs.pop('fields', None)
... | :param model:
:param fields_convert_map: it's different from ListView
:param kwargs:
:return: |
def _validate_row_label(label, column_type_map):
"""
Validate a row label column.
Parameters
----------
label : str
Name of the row label column.
column_type_map : dict[str, type]
Dictionary mapping the name of each column in an SFrame to the type of
the values in the c... | Validate a row label column.
Parameters
----------
label : str
Name of the row label column.
column_type_map : dict[str, type]
Dictionary mapping the name of each column in an SFrame to the type of
the values in the column. |
def line(ax, p1, p2, permutation=None, **kwargs):
"""
Draws a line on `ax` from p1 to p2.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
p1: 2-tuple
The (x,y) starting coordinates
p2: 2-tuple
The (x,y) ending coordinates
kwargs:
... | Draws a line on `ax` from p1 to p2.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
p1: 2-tuple
The (x,y) starting coordinates
p2: 2-tuple
The (x,y) ending coordinates
kwargs:
Any kwargs to pass through to Matplotlib. |
def sliced(seq, n):
"""Yield slices of length *n* from the sequence *seq*.
>>> list(sliced((1, 2, 3, 4, 5, 6), 3))
[(1, 2, 3), (4, 5, 6)]
If the length of the sequence is not divisible by the requested slice
length, the last slice will be shorter.
>>> list(sliced((1, 2, 3, 4, 5, 6... | Yield slices of length *n* from the sequence *seq*.
>>> list(sliced((1, 2, 3, 4, 5, 6), 3))
[(1, 2, 3), (4, 5, 6)]
If the length of the sequence is not divisible by the requested slice
length, the last slice will be shorter.
>>> list(sliced((1, 2, 3, 4, 5, 6, 7, 8), 3))
[(1, 2... |
def set_raw_tag_data(filename, data, act=True, verbose=False):
"Replace the ID3 tag in FILENAME with DATA."
check_tag_data(data)
with open(filename, "rb+") as file:
try:
(cls, offset, length) = stagger.tags.detect_tag(file)
except stagger.NoTagError:
(offset, length) ... | Replace the ID3 tag in FILENAME with DATA. |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'from_') and self.from_ is not None:
_dict['from'] = self.from_
if hasattr(self, 'to') and self.to is not None:
_dict['to'] = self.to
if hasattr(self, '... | Return a json dictionary representing this model. |
def get_constantvalue(self):
"""
the constant pool index for this field, or None if this is not a
contant field
reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.2
""" # noqa
buff = self.get_attribute("ConstantValue")
if buff is ... | the constant pool index for this field, or None if this is not a
contant field
reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.2 |
def find_slack_bus(sub_network):
"""Find the slack bus in a connected sub-network."""
gens = sub_network.generators()
if len(gens) == 0:
logger.warning("No generators in sub-network {}, better hope power is already balanced".format(sub_network.name))
sub_network.slack_generator = None
... | Find the slack bus in a connected sub-network. |
def writeClient(self, fd, sdClass=None, **kw):
"""write out client module to file descriptor.
Parameters and Keywords arguments:
fd -- file descriptor
sdClass -- service description class name
imports -- list of imports
readerclass -- class name of ParsedS... | write out client module to file descriptor.
Parameters and Keywords arguments:
fd -- file descriptor
sdClass -- service description class name
imports -- list of imports
readerclass -- class name of ParsedSoap reader
writerclass -- class name of SoapWr... |
def cli_help(context, command_name, general_parser, command_parsers):
"""
Outputs help information.
See :py:mod:`swiftly.cli.help` for context usage information.
See :py:class:`CLIHelp` for more information.
:param context: The :py:class:`swiftly.cli.context.CLIContext` to
use.
:param... | Outputs help information.
See :py:mod:`swiftly.cli.help` for context usage information.
See :py:class:`CLIHelp` for more information.
:param context: The :py:class:`swiftly.cli.context.CLIContext` to
use.
:param command_name: The command_name to output help information
for, or set to ... |
def manage(cls, entity, unit_of_work):
"""
Manages the given entity under the given Unit Of Work.
If `entity` is already managed by the given Unit Of Work, nothing
is done.
:raises ValueError: If the given entity is already under management
by a different Unit Of Work... | Manages the given entity under the given Unit Of Work.
If `entity` is already managed by the given Unit Of Work, nothing
is done.
:raises ValueError: If the given entity is already under management
by a different Unit Of Work. |
def make_value_from_env(self, param, value_type, function):
"""
get environment variable
"""
value = os.getenv(param)
if value is None:
self.notify_user("Environment variable `%s` undefined" % param)
return self.value_convert(value, value_type) | get environment variable |
def acquire(self):
"""
Acquire the lock, if possible. If the lock is in use, it check again
every `delay` seconds. It does this until it either gets the lock or
exceeds `timeout` number of seconds, in which case it throws
an exception.
"""
start_time = time.time()... | Acquire the lock, if possible. If the lock is in use, it check again
every `delay` seconds. It does this until it either gets the lock or
exceeds `timeout` number of seconds, in which case it throws
an exception. |
def snapshot_list(self):
'''
This command will list all the snapshots taken.
'''
NO_SNAPSHOTS_TAKEN = 'No snapshots have been taken yet!'
output = self._run_vagrant_command(['snapshot', 'list'])
if NO_SNAPSHOTS_TAKEN in output:
return []
else:
... | This command will list all the snapshots taken. |
def worker_bonus(self, chosen_hit, auto, amount, reason='',
assignment_ids=None):
''' Bonus worker '''
if self.config.has_option('Shell Parameters', 'bonus_message'):
reason = self.config.get('Shell Parameters', 'bonus_message')
while not reason:
user... | Bonus worker |
def get_field_cache(self, cache_type='es'):
"""Return a list of fields' mappings"""
if cache_type == 'kibana':
try:
search_results = urlopen(self.get_url).read().decode('utf-8')
except HTTPError: # as e:
# self.pr_err("get_field_cache(kibana), HTT... | Return a list of fields' mappings |
def delete_message(self, id, remove):
"""
Delete a message.
Delete messages from this conversation. Note that this only affects this
user's view of the conversation. If all messages are deleted, the
conversation will be as well (equivalent to DELETE)
"""
... | Delete a message.
Delete messages from this conversation. Note that this only affects this
user's view of the conversation. If all messages are deleted, the
conversation will be as well (equivalent to DELETE) |
def rlgt(self, time=None, times=1,
disallow_sibling_lgts=False):
""" Uses class LGT to perform random lateral gene transfer on
ultrametric tree """
lgt = LGT(self.copy())
for _ in range(times):
lgt.rlgt(time, disallow_sibling_lgts)
return lgt.tree | Uses class LGT to perform random lateral gene transfer on
ultrametric tree |
def populate(self, priority, address, rtr, data):
"""
data bytes (high + low)
1 + 2 = current temp
3 + 4 = min temp
5 + 6 = max temp
:return: None
"""
assert isinstance(data, bytes)
self.needs_no_rtr(rtr)
self.needs_data(d... | data bytes (high + low)
1 + 2 = current temp
3 + 4 = min temp
5 + 6 = max temp
:return: None |
def construct_inlines(self):
"""
Returns the inline formset instances
"""
inline_formsets = []
for inline_class in self.get_inlines():
inline_instance = inline_class(self.model, self.request, self.object, self.kwargs, self)
inline_formset = inline_instance... | Returns the inline formset instances |
def _pcca_connected_isa(evec, n_clusters):
"""
PCCA+ spectral clustering method using the inner simplex algorithm.
Clusters the first n_cluster eigenvectors of a transition matrix in order to cluster the states.
This function assumes that the state space is fully connected, i.e. the transition matrix w... | PCCA+ spectral clustering method using the inner simplex algorithm.
Clusters the first n_cluster eigenvectors of a transition matrix in order to cluster the states.
This function assumes that the state space is fully connected, i.e. the transition matrix whose
eigenvectors are used is supposed to have only... |
def all_subclasses(cls):
"""Recursively returns all the subclasses of the provided class.
"""
subclasses = cls.__subclasses__()
descendants = (descendant for subclass in subclasses
for descendant in all_subclasses(subclass))
return set(subclasses) | set(descendants) | Recursively returns all the subclasses of the provided class. |
def generate_daily(day_end_hour, use_dst,
calib_data, hourly_data, daily_data, process_from):
"""Generate daily summaries from calibrated and hourly data."""
start = daily_data.before(datetime.max)
if start is None:
start = datetime.min
start = calib_data.after(start + SECOND)... | Generate daily summaries from calibrated and hourly data. |
def double_ell_distance (mjr0, mnr0, pa0, mjr1, mnr1, pa1, dx, dy):
"""Given two ellipses separated by *dx* and *dy*, compute their separation in
terms of σ. Based on Pineau et al (2011A&A...527A.126P).
The "0" ellipse is taken to be centered at (0, 0), while the "1"
ellipse is centered at (dx, dy).
... | Given two ellipses separated by *dx* and *dy*, compute their separation in
terms of σ. Based on Pineau et al (2011A&A...527A.126P).
The "0" ellipse is taken to be centered at (0, 0), while the "1"
ellipse is centered at (dx, dy). |
def escape(s, quote=True):
"""
Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true (the default), the quotation mark
characters, both double quote (") and single quote (') characters are also
translated.
"""
assert not isinstance(s, bytes), ... | Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true (the default), the quotation mark
characters, both double quote (") and single quote (') characters are also
translated. |
def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
"""Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
by ``tarfile.open()``). See ``unpack_archive()`` for an explanation
of the `progress_filter` a... | Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
by ``tarfile.open()``). See ``unpack_archive()`` for an explanation
of the `progress_filter` argument. |
def add_new_data_port(self):
"""Add a new port with default values and select it"""
try:
new_data_port_ids = gui_helper_state_machine.add_data_port_to_selected_states('OUTPUT', int, [self.model])
if new_data_port_ids:
self.select_entry(new_data_port_ids[self.model... | Add a new port with default values and select it |
def predict(self, pairs):
"""Predicts the learned metric between input pairs. (For now it just
calls decision function).
Returns the learned metric value between samples in every pair. It should
ideally be low for similar samples and high for dissimilar samples.
Parameters
----------
pairs... | Predicts the learned metric between input pairs. (For now it just
calls decision function).
Returns the learned metric value between samples in every pair. It should
ideally be low for similar samples and high for dissimilar samples.
Parameters
----------
pairs : array-like, shape=(n_pairs, 2,... |
def render_latex(latex: str) -> PIL.Image: # pragma: no cover
"""
Convert a single page LaTeX document into an image.
To display the returned image, `img.show()`
Required external dependencies: `pdflatex` (with `qcircuit` package),
and `poppler` (for `pdftocairo`).
Args:
A LaTeX... | Convert a single page LaTeX document into an image.
To display the returned image, `img.show()`
Required external dependencies: `pdflatex` (with `qcircuit` package),
and `poppler` (for `pdftocairo`).
Args:
A LaTeX document as a string.
Returns:
A PIL Image
Raises:
O... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.