code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def extract_full(rec, sites, flank, fw):
"""
Full extraction of seq flanking the sites.
"""
for s in sites:
newid = "{0}:{1}".format(rec.name, s)
left = max(s - flank, 0)
right = min(s + flank, len(rec))
frag = rec.seq[left:right].strip("Nn")
newrec = SeqRecord(fr... | Full extraction of seq flanking the sites. |
def _get_db_password(dbSystem,db,user):
"""Read through the users .dbrc file to get password for the db/user
combination suplied. If no password is found then prompt for one
"""
import string, getpass, os
dbrc = os.environ['HOME']+"/.dbrc"
password={}
if os.access(dbrc,os.R_OK):
fd=... | Read through the users .dbrc file to get password for the db/user
combination suplied. If no password is found then prompt for one |
def collect_logs(name):
"""
Returns a string representation of the logs from a container.
This is similar to container_logs but uses the `follow` option
and flattens the logs into a string instead of a generator.
:param name: The container name to grab logs for
:return: A string representation ... | Returns a string representation of the logs from a container.
This is similar to container_logs but uses the `follow` option
and flattens the logs into a string instead of a generator.
:param name: The container name to grab logs for
:return: A string representation of the logs |
def service_delete(auth=None, **kwargs):
'''
Delete a service
CLI Example:
.. code-block:: bash
salt '*' keystoneng.service_delete name=glance
salt '*' keystoneng.service_delete name=39cc1327cdf744ab815331554430e8ec
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwar... | Delete a service
CLI Example:
.. code-block:: bash
salt '*' keystoneng.service_delete name=glance
salt '*' keystoneng.service_delete name=39cc1327cdf744ab815331554430e8ec |
def synchronizeLayout(primary, secondary, surface_size):
"""Synchronizes given layouts by normalizing height by using
max height of given layouts to avoid transistion dirty effects.
:param primary: Primary layout used.
:param secondary: Secondary layout used.
:param surface_size: Target surface siz... | Synchronizes given layouts by normalizing height by using
max height of given layouts to avoid transistion dirty effects.
:param primary: Primary layout used.
:param secondary: Secondary layout used.
:param surface_size: Target surface size on which layout will be displayed. |
def get_num_paths(self):
"""
Return the effective number of paths in the tree.
"""
# NB: the algorithm assume a symmetric logic tree for the GSIMs;
# in the future we may relax such assumption
num_branches = self.get_num_branches()
if not sum(num_branches.values()... | Return the effective number of paths in the tree. |
def stop_codon_spliced_offsets(self):
"""
Offsets from start of spliced mRNA transcript
of nucleotides in stop codon.
"""
offsets = [
self.spliced_offset(position)
for position
in self.stop_codon_positions
]
return self._contigu... | Offsets from start of spliced mRNA transcript
of nucleotides in stop codon. |
def loop_until_timeout_or_not_none(timeout_s, function, sleep_s=1): # pylint: disable=invalid-name
"""Loops until the specified function returns non-None or until a timeout.
Args:
timeout_s: The number of seconds to wait until a timeout condition is
reached. As a convenience, this accepts None to mean... | Loops until the specified function returns non-None or until a timeout.
Args:
timeout_s: The number of seconds to wait until a timeout condition is
reached. As a convenience, this accepts None to mean never timeout. Can
also be passed a PolledTimeout object instead of an integer.
function: T... |
def decode (cls, bytes, cmddict=None):
"""Decodes a sequence delay from an array of bytes, according to the
given command dictionary, and returns a new SeqDelay.
"""
delay_s = struct.unpack('>H', bytes[0:2])[0]
delay_ms = struct.unpack('B' , bytes[2:3])[0]
return cls(delay_s + (delay_ms / 255.0... | Decodes a sequence delay from an array of bytes, according to the
given command dictionary, and returns a new SeqDelay. |
def build_headers(self):
'''
Return the list of headers as two-tuples
'''
if not 'Content-Type' in self.headers:
content_type = self.content_type
if self.encoding != DEFAULT_ENCODING:
content_type += '; charset=%s' % self.encoding
self.... | Return the list of headers as two-tuples |
def information(self, message, *args, **kwargs):
"""alias to message at information level"""
self.log("info", message, *args, **kwargs) | alias to message at information level |
def clear_cached_data(self):
"""Clear the internal bluetooth device cache. This is useful if a device
changes its state like name and it can't be detected with the new state
anymore. WARNING: This will delete some files underneath the running user's
~/Library/Preferences/ folder!
... | Clear the internal bluetooth device cache. This is useful if a device
changes its state like name and it can't be detected with the new state
anymore. WARNING: This will delete some files underneath the running user's
~/Library/Preferences/ folder!
See this Stackoverflow question for ... |
def handle(self, key, value):
'''
Processes a vaild zookeeper request
@param key: The key that matched the request
@param value: The value associated with the key
'''
# break down key
elements = key.split(":")
dict = {}
dict['action'] = elements[1... | Processes a vaild zookeeper request
@param key: The key that matched the request
@param value: The value associated with the key |
def model_to_dict(model, sort=False):
"""Convert model to a dict.
Parameters
----------
model : cobra.Model
The model to reformulate as a dict.
sort : bool, optional
Whether to sort the metabolites, reactions, and genes or maintain the
order defined in the model.
Return... | Convert model to a dict.
Parameters
----------
model : cobra.Model
The model to reformulate as a dict.
sort : bool, optional
Whether to sort the metabolites, reactions, and genes or maintain the
order defined in the model.
Returns
-------
OrderedDict
A dicti... |
def gill_murray_wright(mat, eps=1e-16):
"""
Gill-Murray-Wright algorithm for pivoting modified Cholesky decomposition.
Return ``(perm, lowtri, error)`` such that
`perm.T*mat*perm = lowtri*lowtri.T` is approximately correct.
Args:
mat (numpy.ndarray):
Must be a non-singular and ... | Gill-Murray-Wright algorithm for pivoting modified Cholesky decomposition.
Return ``(perm, lowtri, error)`` such that
`perm.T*mat*perm = lowtri*lowtri.T` is approximately correct.
Args:
mat (numpy.ndarray):
Must be a non-singular and symmetric matrix
eps (float):
Er... |
def skip_read_line(fd, no_eof=False):
"""
Read the first non-empty line (if any) from the given file
object. Return an empty string at EOF, if `no_eof` is False. If it
is True, raise the EOFError instead.
"""
ls = ''
while 1:
try:
line = fd.readline()
except EOFE... | Read the first non-empty line (if any) from the given file
object. Return an empty string at EOF, if `no_eof` is False. If it
is True, raise the EOFError instead. |
def full_index_size(*args):
"""Compute the number of records in a full index.
Compute the number of records in a full index without building the index
itself. The result is the maximum number of record pairs possible. This
function is especially useful in measures like the `reduction_ratio`.
Dedup... | Compute the number of records in a full index.
Compute the number of records in a full index without building the index
itself. The result is the maximum number of record pairs possible. This
function is especially useful in measures like the `reduction_ratio`.
Deduplication: Given a DataFrame A with ... |
def attach_to_instance(self, instance, mountpoint):
"""
Attaches this volume to the cloud server instance at the
specified mountpoint. This requires a call to the cloud servers
API; it cannot be done directly.
"""
instance_id = _resolve_id(instance)
try:
... | Attaches this volume to the cloud server instance at the
specified mountpoint. This requires a call to the cloud servers
API; it cannot be done directly. |
def register_webapp(self, webapp_name: str, webapp_args: list, webapp_url: str):
"""Register a new WEBAPP to use with the view URL builder.
:param str webapp_name: name of the web app to register
:param list webapp_args: dynamic arguments to complete the URL.
Typically 'md_id'.
... | Register a new WEBAPP to use with the view URL builder.
:param str webapp_name: name of the web app to register
:param list webapp_args: dynamic arguments to complete the URL.
Typically 'md_id'.
:param str webapp_url: URL of the web app to register with
args tags to replace. E... |
def interpolate_curve(points, degree, **kwargs):
""" Curve interpolation through the data points.
Please refer to Algorithm A9.1 on The NURBS Book (2nd Edition), pp.369-370 for details.
Keyword Arguments:
* ``centripetal``: activates centripetal parametrization method. *Default: False*
:param... | Curve interpolation through the data points.
Please refer to Algorithm A9.1 on The NURBS Book (2nd Edition), pp.369-370 for details.
Keyword Arguments:
* ``centripetal``: activates centripetal parametrization method. *Default: False*
:param points: data points
:type points: list, tuple
:p... |
def add_indicator(self, indicator_data):
"""Add an indicator to Batch Job.
.. code-block:: javascript
{
"type": "File",
"rating": 5.00,
"confidence": 50,
"summary": "53c3609411c83f363e051d455ade78a7
... | Add an indicator to Batch Job.
.. code-block:: javascript
{
"type": "File",
"rating": 5.00,
"confidence": 50,
"summary": "53c3609411c83f363e051d455ade78a7
: 57a49b478310e4313c54c0fee46e4d70a73dd580
... |
def main(args=None, prog=None):
"""Generates a C header file"""
args = args if args is not None else sys.argv[1:]
prog = prog if prog is not None else sys.argv[0]
# Prevent broken pipe exception from being raised.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
stdin = sys.stdin.buffer if hasattr(... | Generates a C header file |
def calc_nbes_inzp_v1(self):
"""Calculate stand precipitation and update the interception storage
accordingly.
Required control parameters:
|NHRU|
|Lnk|
Required derived parameter:
|KInz|
Required flux sequence:
|NKor|
Calculated flux sequence:
|NBes|
Updat... | Calculate stand precipitation and update the interception storage
accordingly.
Required control parameters:
|NHRU|
|Lnk|
Required derived parameter:
|KInz|
Required flux sequence:
|NKor|
Calculated flux sequence:
|NBes|
Updated state sequence:
|Inzp|
... |
def desymbolize(self):
"""
We believe this was a pointer and symbolized it before. Now we want to desymbolize it.
The following actions are performed:
- Reload content from memory
- Mark the sort as 'unknown'
:return: None
"""
self.sort = 'unknown'
... | We believe this was a pointer and symbolized it before. Now we want to desymbolize it.
The following actions are performed:
- Reload content from memory
- Mark the sort as 'unknown'
:return: None |
def make_madry_ngpu(nb_classes=10, input_shape=(None, 28, 28, 1), **kwargs):
"""
Create a multi-GPU model similar to Madry et al. (arXiv:1706.06083).
"""
layers = [Conv2DnGPU(32, (5, 5), (1, 1), "SAME"),
ReLU(),
MaxPool((2, 2), (2, 2), "SAME"),
Conv2DnGPU(64, (5, 5), (1, 1), ... | Create a multi-GPU model similar to Madry et al. (arXiv:1706.06083). |
def metablockLength(self):
"""Read MNIBBLES and meta block length;
if empty block, skip block and return true.
"""
self.MLEN = self.verboseRead(MetablockLengthAlphabet())
if self.MLEN:
return False
#empty block; skip and return False
self.verboseRead(R... | Read MNIBBLES and meta block length;
if empty block, skip block and return true. |
def _set(self):
"""Called internally by Client to indicate this request has finished"""
self.__event.set()
if self._complete_func:
self.__run_completion_func(self._complete_func, self.id_) | Called internally by Client to indicate this request has finished |
def union(self, *sets):
"""
Combines all unique items.
Each items order is defined by its first appearance.
Example:
>>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0])
>>> print(oset)
OrderedSet([3, 1, 4, 5, 2, 0])
>>... | Combines all unique items.
Each items order is defined by its first appearance.
Example:
>>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0])
>>> print(oset)
OrderedSet([3, 1, 4, 5, 2, 0])
>>> oset.union([8, 9])
OrderedSet(... |
def copyHiddenToContext(self):
"""
Uses key to identify the hidden layer associated with each
layer in the self.contextLayers dictionary.
"""
for item in list(self.contextLayers.items()):
if self.verbosity > 2: print('Hidden layer: ', self.getLayer(item[0]).activatio... | Uses key to identify the hidden layer associated with each
layer in the self.contextLayers dictionary. |
def GetHelp(self, prefix='', include_special_flags=True):
"""Generates a help string for all known flags.
Args:
prefix: str, per-line output prefix.
include_special_flags: bool, whether to include description of
_SPECIAL_FLAGS, i.e. --flagfile and --undefok.
Returns:
str, formatt... | Generates a help string for all known flags.
Args:
prefix: str, per-line output prefix.
include_special_flags: bool, whether to include description of
_SPECIAL_FLAGS, i.e. --flagfile and --undefok.
Returns:
str, formatted help message. |
def daily(self, symbol=None):
'''
获取日线数据
:return: pd.dataFrame or None
'''
reader = TdxExHqDailyBarReader()
symbol = self.find_path(symbol)
if symbol is not None:
return reader.get_df(symbol)
return None | 获取日线数据
:return: pd.dataFrame or None |
def retrieve_network_info(self, tenant_id, direc):
"""Retrieve the DCNM Network information.
Retrieves DCNM net dict if already filled, else, it calls
routines to fill the net info and store it in tenant obj.
"""
serv_obj = self.get_service_obj(tenant_id)
net_dict = self... | Retrieve the DCNM Network information.
Retrieves DCNM net dict if already filled, else, it calls
routines to fill the net info and store it in tenant obj. |
def convert_to_msp_crunch(infile, outfile, ref_fai=None, qry_fai=None):
'''Converts a coords file to a file in MSPcrunch format (for use with ACT, most likely).
ACT ignores sequence names in the crunch file, and just looks at the numbers.
To make a compatible file, the coords all must be shifted appro... | Converts a coords file to a file in MSPcrunch format (for use with ACT, most likely).
ACT ignores sequence names in the crunch file, and just looks at the numbers.
To make a compatible file, the coords all must be shifted appropriately, which
can be done by providing both the ref_fai and qry_fai op... |
def get_dispatcher(self):
"""
Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher`
"""
dp = self.request.app[BOT_DISPATCHER_KEY]
try:
from aiogram import Bot, Dispatcher
Dispatcher.set_current(dp)
Bot.set_curre... | Get Dispatcher instance from environment
:return: :class:`aiogram.Dispatcher` |
def extend_hosting_port_info(self, context, port_db, hosting_device,
hosting_info):
"""Get the segmenetation ID and interface
This extends the hosting info attribute with the segmentation ID
and physical interface used on the external router to connect to
... | Get the segmenetation ID and interface
This extends the hosting info attribute with the segmentation ID
and physical interface used on the external router to connect to
the ACI fabric. The segmentation ID should have been set already
by the call to allocate_hosting_port, but if it's not... |
def fcoe_fsb_fcoe_fsb_enable(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_fsb = ET.SubElement(config, "fcoe-fsb", xmlns="urn:brocade.com:mgmt:brocade-fcoe")
fcoe_fsb_enable = ET.SubElement(fcoe_fsb, "fcoe-fsb-enable")
callback = kwargs.p... | Auto Generated Code |
def check_returncode(p, out):
"""Raise exception according to unrar exit code.
"""
code = p.returncode
if code == 0:
return
# map return code to exception class, codes from rar.txt
errmap = [None,
RarWarning, RarFatalError, RarCRCError, RarLockedArchiveError, # 1..4
... | Raise exception according to unrar exit code. |
def parse_obj(obj):
"""
>>> parse_obj('bucket/key')
('bucket', 'key')
>>> parse_obj('my-bucket/path/to/file.txt')
('my-bucket', 'path/to/file.txt')
>>> parse_obj('s3://this_bucket/some/path.txt')
('this_bucket', 'some/path.txt')
>>> parse_obj('https://s3.amazonaws.com/bucket/file.txt')
... | >>> parse_obj('bucket/key')
('bucket', 'key')
>>> parse_obj('my-bucket/path/to/file.txt')
('my-bucket', 'path/to/file.txt')
>>> parse_obj('s3://this_bucket/some/path.txt')
('this_bucket', 'some/path.txt')
>>> parse_obj('https://s3.amazonaws.com/bucket/file.txt')
('bucket', 'file.txt')
>>... |
def tigrprepare(args):
"""
%prog tigrprepare asmbl.fasta asmbl.ids db pasa.terminal_exons.gff3
Run EVM in TIGR-only mode.
"""
p = OptionParser(tigrprepare.__doc__)
opts, args = p.parse_args(args)
if len(args) != 4:
sys.exit(not p.print_help())
fastafile, asmbl_id, db, pasa_db ... | %prog tigrprepare asmbl.fasta asmbl.ids db pasa.terminal_exons.gff3
Run EVM in TIGR-only mode. |
def readfile(filename):
"""readfile"""
fhandle = open(filename, 'rb')
data = fhandle.read()
try:
data = data.decode('ISO-8859-2')
except AttributeError:
pass
fhandle.close()
return data | readfile |
def help(self, level=0):
"""return the usage string for available options """
self.cmdline_parser.formatter.output_level = level
with _patch_optparse():
return self.cmdline_parser.format_help() | return the usage string for available options |
def _output(cls,
tensors: Sequence[tf.Tensor],
dtypes: Sequence[tf.DType]) -> Sequence[tf.Tensor]:
'''Converts `tensors` to the corresponding `dtypes`.'''
outputs = []
for tensor, dtype in zip(tensors, dtypes):
tensor = tensor[0]
if tensor.dtype !=... | Converts `tensors` to the corresponding `dtypes`. |
def amari_alpha(logu, alpha=1., self_normalized=False, name=None):
"""The Amari-alpha Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the Amari-alpha Csiszar-function is:
```none
f(u) = { -log(u) + (u - 1), ... | The Amari-alpha Csiszar-function in log-space.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
When `self_normalized = True`, the Amari-alpha Csiszar-function is:
```none
f(u) = { -log(u) + (u - 1), alpha = 0
{ u log(u) - (u - 1), alpha = 1
{ [(u*... |
def tarbell_newproject(command, args):
"""
Create new Tarbell project.
"""
with ensure_settings(command, args) as settings:
# Set it up and make the directory
name = _get_project_name(args)
puts("Creating {0}".format(colored.cyan(name)))
path = _get_path(name, settings)
... | Create new Tarbell project. |
def next(self):
"""
Get the next item.
@return: A tuple: the next (child, ancestry).
@rtype: (L{SchemaObject}, [L{SchemaObject},..])
@raise StopIteration: A the end.
"""
frame = self.top()
while True:
result = frame.next()
if resu... | Get the next item.
@return: A tuple: the next (child, ancestry).
@rtype: (L{SchemaObject}, [L{SchemaObject},..])
@raise StopIteration: A the end. |
def rectangular_neighbors_from_shape(shape):
"""Compute the neighbors of every pixel as a list of the pixel index's each pixel shares a vertex with.
The uniformity of the rectangular grid's geometry is used to compute this.
"""
pixels = shape[0]*shape[1]
pixel_neighbors = -1 * np.ones(shape=(pix... | Compute the neighbors of every pixel as a list of the pixel index's each pixel shares a vertex with.
The uniformity of the rectangular grid's geometry is used to compute this. |
def tftp_update_bios(server=None, path=None):
'''
Update the BIOS firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the BIOS image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_updat... | Update the BIOS firmware through TFTP.
Args:
server(str): The IP address or hostname of the TFTP server.
path(str): The TFTP path and filename for the BIOS image.
CLI Example:
.. code-block:: bash
salt '*' cimc.tftp_update_bios foo.bar.com HP-SL2.cap |
def edit_filename(filename, prefix='', suffix='', new_ext=None):
"""
Edit a file name by add a prefix, inserting a suffix in front of a file
name extension or replacing the extension.
Parameters
----------
filename : str
The file name.
prefix : str
The prefix to be added.
... | Edit a file name by add a prefix, inserting a suffix in front of a file
name extension or replacing the extension.
Parameters
----------
filename : str
The file name.
prefix : str
The prefix to be added.
suffix : str
The suffix to be inserted.
new_ext : str, optional... |
def get_pushes(self, project, **params):
"""
Gets pushes from project, filtered by parameters
By default this method will just return the latest 10 pushes (if they exist)
:param project: project (repository name) to query data for
:param params: keyword arguments to filter resu... | Gets pushes from project, filtered by parameters
By default this method will just return the latest 10 pushes (if they exist)
:param project: project (repository name) to query data for
:param params: keyword arguments to filter results |
def agnostic_extend(self, new_length):
"""
Unary operation: SignExtend
:param new_length: New length after sign-extension
:return: A new StridedInterval
"""
'''
In a sign-agnostic implementation of strided-intervals a number can be signed or unsigned both.
... | Unary operation: SignExtend
:param new_length: New length after sign-extension
:return: A new StridedInterval |
def get_angles(self, angle_id):
"""Get sun-satellite viewing angles"""
tic = datetime.now()
sunz40km = self._data["ang"][:, :, 0] * 1e-2
satz40km = self._data["ang"][:, :, 1] * 1e-2
azidiff40km = self._data["ang"][:, :, 2] * 1e-2
try:
from geotiepoints.inte... | Get sun-satellite viewing angles |
def on_train_begin(self, pbar:PBar, metrics_names:Collection[str], **kwargs:Any)->None:
"Initialize recording status at beginning of training."
self.pbar = pbar
self.names = ['epoch', 'train_loss'] if self.no_val else ['epoch', 'train_loss', 'valid_loss']
self.metrics_names = metrics_nam... | Initialize recording status at beginning of training. |
def parse(self, msg, name):
"""Parses the message.
We check that the message is properly formatted.
:param msg: a json-encoded value containing a JWS or JWE+JWS token
:raises InvalidMessage: if the message cannot be parsed or validated
:returns: A verified payload
"""... | Parses the message.
We check that the message is properly formatted.
:param msg: a json-encoded value containing a JWS or JWE+JWS token
:raises InvalidMessage: if the message cannot be parsed or validated
:returns: A verified payload |
def update(self, instance, validated_data):
"""
Update an existing video resource.
"""
instance.status = validated_data["status"]
instance.client_video_id = validated_data["client_video_id"]
instance.duration = validated_data["duration"]
instance.save()
#... | Update an existing video resource. |
def add_argument(self, *args, **kwargs):
"""
add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...)
"""
# if no positional args are supplied or only one is supplied and
# it doesn't look like an option string, par... | add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...) |
def _get_upsampling_filter(size):
"""Make a 2D bilinear kernel suitable for upsampling"""
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
filter = (1 - abs(og[0] - center) / factor) * \
(1 - abs(o... | Make a 2D bilinear kernel suitable for upsampling |
def delete_stream(stream_name, region=None, key=None, keyid=None, profile=None):
'''
Delete the stream with name stream_name. This cannot be undone! All data will be lost!!
CLI example::
salt myminion boto_kinesis.delete_stream my_stream region=us-east-1
'''
conn = _get_conn(region=region,... | Delete the stream with name stream_name. This cannot be undone! All data will be lost!!
CLI example::
salt myminion boto_kinesis.delete_stream my_stream region=us-east-1 |
def availableRoles(self):
'''
Some instructors only offer private lessons for certain roles, so we should only allow booking
for the roles that have been selected for the instructor.
'''
if not hasattr(self.instructor,'instructorprivatelessondetails'):
return []
... | Some instructors only offer private lessons for certain roles, so we should only allow booking
for the roles that have been selected for the instructor. |
async def setRemoteDescription(self, sessionDescription):
"""
Changes the remote description associated with the connection.
:param: sessionDescription: An :class:`RTCSessionDescription` created from
information received over the signaling channel.
""... | Changes the remote description associated with the connection.
:param: sessionDescription: An :class:`RTCSessionDescription` created from
information received over the signaling channel. |
def import_ecdsakey_from_pem(pem, scheme='ecdsa-sha2-nistp256'):
"""
<Purpose>
Import either a public or private ECDSA PEM. In contrast to the other
explicit import functions (import_ecdsakey_from_public_pem and
import_ecdsakey_from_private_pem), this function is useful for when it is
not known whe... | <Purpose>
Import either a public or private ECDSA PEM. In contrast to the other
explicit import functions (import_ecdsakey_from_public_pem and
import_ecdsakey_from_private_pem), this function is useful for when it is
not known whether 'pem' is private or public.
<Arguments>
pem:
A string i... |
def _description_columns_json(self, cols=None):
"""
Prepares dict with col descriptions to be JSON serializable
"""
ret = {}
cols = cols or []
d = {k: v for (k, v) in self.description_columns.items() if k in cols}
for key, value in d.items():
ret[k... | Prepares dict with col descriptions to be JSON serializable |
def snapshot(self,
label,
snapshot_type='statevector',
qubits=None,
params=None):
"""Take a statevector snapshot of the internal simulator representation.
Works on all qubits, and prevents reordering (like barrier).
For other types of snapshots use the Sn... | Take a statevector snapshot of the internal simulator representation.
Works on all qubits, and prevents reordering (like barrier).
For other types of snapshots use the Snapshot extension directly.
Args:
label (str): a snapshot label to report the result
snapshot_type (str): the type of the... |
def _handle_dist_server(ds_type, repos_array):
"""Ask user for whether to use a type of dist server."""
if ds_type not in ("JDS", "CDP"):
raise ValueError("Must be JDS or CDP")
prompt = "Does your JSS use a %s? (Y|N): " % ds_type
result = loop_until_valid_response(prompt)
if result:
... | Ask user for whether to use a type of dist server. |
def get_pwm(self, led_num):
"""Generic getter for all LED PWM value"""
self.__check_range('led_number', led_num)
register_low = self.calc_led_register(led_num)
return self.__get_led_value(register_low) | Generic getter for all LED PWM value |
def calc_gs_nu_pk(b, ne, delta, sinth, depth):
"""Calculate the frequency of peak synchrotron emission, ν_pk.
This is Dulk (1985) equation 39, which is a fitting function assuming a
power-law electron population. Arguments are:
b
Magnetic field strength in Gauss
ne
The density of elect... | Calculate the frequency of peak synchrotron emission, ν_pk.
This is Dulk (1985) equation 39, which is a fitting function assuming a
power-law electron population. Arguments are:
b
Magnetic field strength in Gauss
ne
The density of electrons per cubic centimeter with energies greater than 1... |
def find_rel_links(self, rel):
"""
Find any links like ``<a rel="{rel}">...</a>``; returns a list of elements.
"""
rel = rel.lower()
return [el for el in _rel_links_xpath(self)
if el.get('rel').lower() == rel] | Find any links like ``<a rel="{rel}">...</a>``; returns a list of elements. |
async def starttls(
self,
server_hostname: str = None,
validate_certs: bool = None,
client_cert: DefaultStrType = _default,
client_key: DefaultStrType = _default,
cert_bundle: DefaultStrType = _default,
tls_context: DefaultSSLContextType = _default,
timeou... | Puts the connection to the SMTP server into TLS mode.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
If the server supports TLS, this will encrypt the rest of the SMTP
session. If you provide the keyfile and certfile parameters,
... |
def graph_lasso(X, num_folds):
"""Estimate inverse covariance via scikit-learn GraphLassoCV class.
"""
print("GraphLasso (sklearn)")
model = GraphLassoCV(cv=num_folds)
model.fit(X)
print(" lam_: {}".format(model.alpha_))
return model.covariance_, model.precision_, model.alpha_ | Estimate inverse covariance via scikit-learn GraphLassoCV class. |
def dump_results(self):
"""
Save eigenvalue analysis reports
Returns
-------
None
"""
system = self.system
mu = self.mu
partfact = self.part_fact
if system.files.no_output:
return
text = []
header = []
... | Save eigenvalue analysis reports
Returns
-------
None |
def databoxes(ds, xscript=0, yscript=1, eyscript=None, exscript=None, g=None, plotter=xy_data, transpose=False, **kwargs):
"""
Plots the listed databox objects with the specified scripts.
ds list of databoxes
xscript script for x data
yscript script for y data
eyscript script for y ... | Plots the listed databox objects with the specified scripts.
ds list of databoxes
xscript script for x data
yscript script for y data
eyscript script for y error
exscript script for x error
plotter function used to do the plotting
transpose applies databox.transpose() prior t... |
def parse_with_retrieved(self, retrieved):
"""
Parse output data folder, store results in database.
:param retrieved: a dictionary of retrieved nodes, where
the key is the link name
:returns: a tuple with two values ``(bool, node_list)``,
where:
* ``bool``... | Parse output data folder, store results in database.
:param retrieved: a dictionary of retrieved nodes, where
the key is the link name
:returns: a tuple with two values ``(bool, node_list)``,
where:
* ``bool``: variable to tell if the parsing succeeded
* ``node_... |
def get_subject_version(self, subject, version_id):
"""
Retrieves the schema registered under the given subject with
the given version id. Returns the schema as a `dict`.
"""
res = requests.get(self._url('/subjects/{}/versions/{}', subject, version_id))
raise_if_failed(re... | Retrieves the schema registered under the given subject with
the given version id. Returns the schema as a `dict`. |
def dict_has_any_keys(self, keys):
"""
Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has any of the given keys.
Fails on SArrays whose data type is not ``dict``.
... | Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has any of the given keys.
Fails on SArrays whose data type is not ``dict``.
Parameters
----------
keys : li... |
def read(fnames, calculation_mode='', region_constraint='',
ignore_missing_costs=(), asset_nodes=False, check_dupl=True,
tagcol=None, by_country=False):
"""
Call `Exposure.read(fname)` to get an :class:`Exposure` instance
keeping all the assets in memory or
`Exp... | Call `Exposure.read(fname)` to get an :class:`Exposure` instance
keeping all the assets in memory or
`Exposure.read(fname, asset_nodes=True)` to get an iterator over
Node objects (one Node for each asset). |
def solve_factorized_aug(z, Fval, LU, G, A):
M, N=G.shape
P, N=A.shape
"""Total number of inequality constraints"""
m = M
"""Primal variable"""
x = z[0:N]
"""Multiplier for equality constraints"""
nu = z[N:N+P]
"""Multiplier for inequality constraints"""
l = z[N+P:N+P+M]
... | Total number of inequality constraints |
def _github_store_authorization(cls, user, auth):
"""Store an authorization token for the given GitHub user in the git
global config file.
"""
ClHelper.run_command("git config --global github.token.{login} {token}".format(
login=user.login, token=auth.token), log_secret=Tr... | Store an authorization token for the given GitHub user in the git
global config file. |
def parse(
svalue, conf=None, configurable=None, ptype=None,
scope=DEFAULT_SCOPE, safe=DEFAULT_SAFE, besteffort=DEFAULT_BESTEFFORT
):
"""Parser which delegates parsing to expression or format parser."""
result = None
if ptype is None:
ptype = object
compilation = REGEX_EXPR.ma... | Parser which delegates parsing to expression or format parser. |
def run():
"""Run custom scalar demo and generate event files."""
step = tf.compat.v1.placeholder(tf.float32, shape=[])
with tf.name_scope('loss'):
# Specify 2 different loss values, each tagged differently.
summary_lib.scalar('foo', tf.pow(0.9, step))
summary_lib.scalar('bar', tf.pow(0.85, step + 2)... | Run custom scalar demo and generate event files. |
def parallel_graph_evaluation(data, adj_matrix, nb_runs=16,
nb_jobs=None, **kwargs):
"""Parallelize the various runs of CGNN to evaluate a graph."""
nb_jobs = SETTINGS.get_default(nb_jobs=nb_jobs)
if nb_runs == 1:
return graph_evaluation(data, adj_matrix, **kwargs)
... | Parallelize the various runs of CGNN to evaluate a graph. |
def get_create_command(self):
"""Get the command to create the local repository."""
command = ['git', 'clone' if self.remote else 'init']
if self.bare:
command.append('--bare')
if self.remote:
command.append(self.remote)
command.append(self.local)
... | Get the command to create the local repository. |
def create(self, create_info=None, hyperparameter=None, server='local', insights=False):
"""
Creates a new job in git and pushes it.
:param create_info: from the api.create_job_info(id). Contains the config and job info (type, server)
:param hyperparameter: simple nested dict with key->... | Creates a new job in git and pushes it.
:param create_info: from the api.create_job_info(id). Contains the config and job info (type, server)
:param hyperparameter: simple nested dict with key->value, which overwrites stuff from aetros.yml
:param server: if None, the the job will be assigned to... |
def set_result(self, job_id, result):
"""Set the result for a job.
This will overwrite any existing results for the job.
Args:
job_id: The ID of the WorkItem to set the result for.
result: A WorkResult indicating the result of the job.
Raises:
KeyError: ... | Set the result for a job.
This will overwrite any existing results for the job.
Args:
job_id: The ID of the WorkItem to set the result for.
result: A WorkResult indicating the result of the job.
Raises:
KeyError: If there is no work-item with a matching job-id. |
def get_dict_for_forms(self):
"""
Build a dictionnary where searchable_fields are
next to their model to be use in modelform_factory
dico = {
"str(model)" : {
"model" : Model,
"fields" = [] #searchable_fields which are attribut... | Build a dictionnary where searchable_fields are
next to their model to be use in modelform_factory
dico = {
"str(model)" : {
"model" : Model,
"fields" = [] #searchable_fields which are attribute of Model
}
} |
def rmR(kls, path):
"""`rm -R path`. Deletes, but does not recurse into, symlinks.
If the path does not exist, silently return."""
if os.path.islink(path) or os.path.isfile(path):
os.unlink(path)
elif os.path.isdir(path):
walker = os.walk(path, topdown=False, followlinks=False)
for dirpath, dirnames,... | `rm -R path`. Deletes, but does not recurse into, symlinks.
If the path does not exist, silently return. |
def enable_hdfs_auto_failover(self, nameservice, active_fc_name,
standby_fc_name, zk_service):
"""
Enable auto-failover for an HDFS nameservice.
This command is no longer supported with API v6 onwards. Use enable_nn_ha instead.
@param nameservice: Nameservice for which to enable auto-failover.
... | Enable auto-failover for an HDFS nameservice.
This command is no longer supported with API v6 onwards. Use enable_nn_ha instead.
@param nameservice: Nameservice for which to enable auto-failover.
@param active_fc_name: Name of failover controller to create for active node.
@param standby_fc_name: Name ... |
def _validate_subnet_cidr(context, network_id, new_subnet_cidr):
"""Validate the CIDR for a subnet.
Verifies the specified CIDR does not overlap with the ones defined
for the other subnets specified for this network, or with any other
CIDR if overlapping IPs are disabled.
"""
if neutron_cfg.cf... | Validate the CIDR for a subnet.
Verifies the specified CIDR does not overlap with the ones defined
for the other subnets specified for this network, or with any other
CIDR if overlapping IPs are disabled. |
def broaden(self) -> 'List[Language]':
"""
Iterate through increasingly general versions of this parsed language tag.
This isn't actually that useful for matching two arbitrary language tags
against each other, but it is useful for matching them against a known
standardized form... | Iterate through increasingly general versions of this parsed language tag.
This isn't actually that useful for matching two arbitrary language tags
against each other, but it is useful for matching them against a known
standardized form, such as in the CLDR data.
The list of broader ve... |
def contains(self, value, equality_comparer=operator.eq):
'''Determines whether the sequence contains a particular value.
Execution is immediate. Depending on the type of the sequence, all or
none of the sequence may be consumed by this operation.
Note: This method uses immediate execu... | Determines whether the sequence contains a particular value.
Execution is immediate. Depending on the type of the sequence, all or
none of the sequence may be consumed by this operation.
Note: This method uses immediate execution.
Args:
value: The value to test for members... |
def detect(self):
"""Detect IP and return it."""
for theip in self.rips:
LOG.debug("detected %s", str(theip))
self.set_current_value(str(theip))
return str(theip) | Detect IP and return it. |
def new_bool(self, name=None, taint=frozenset(), avoid_collisions=False):
""" Declares a free symbolic boolean in the constraint store
:param name: try to assign name to internal variable representation,
if not unique, a numeric nonce will be appended
:param avoi... | Declares a free symbolic boolean in the constraint store
:param name: try to assign name to internal variable representation,
if not unique, a numeric nonce will be appended
:param avoid_collisions: potentially avoid_collisions the variable to avoid name collisions if Tr... |
def _call(self, x):
"""Return ``self(x)``."""
if abs(x.ufuncs.sum() / self.sum_value - 1) <= self.sum_rtol:
return 0
else:
return np.inf | Return ``self(x)``. |
def get_page_ancestors(self, page_id):
"""
Provide the ancestors from the page (content) id
:param page_id: content_id format
:return: get properties
"""
url = 'rest/api/content/{page_id}?expand=ancestors'.format(page_id=page_id)
return (self.get(path=url) or {}).... | Provide the ancestors from the page (content) id
:param page_id: content_id format
:return: get properties |
def get_item_balances(self, acc: Account) -> list:
"""
Returns balances of items of the invoice.
:param acc: Account
:return: list (AccountEntry, Decimal) in item id order
"""
items = []
entries = self.get_entries(acc)
for item in entries.filter(source_inv... | Returns balances of items of the invoice.
:param acc: Account
:return: list (AccountEntry, Decimal) in item id order |
def run_call(self, func, start_opts=None, *args, **kwds):
""" Run debugger on function call: `func(*args, **kwds)'
See also `run_eval' if what you want to run is an eval'able
expression have that result returned and `run' if you want to
debug a statment via exec.
"""
res... | Run debugger on function call: `func(*args, **kwds)'
See also `run_eval' if what you want to run is an eval'able
expression have that result returned and `run' if you want to
debug a statment via exec. |
def clear_optimizer(self):
"""Cleans query optimizer state"""
self._optimized = False
self._type2decls = {}
self._type2name2decls = {}
self._type2decls_nr = {}
self._type2name2decls_nr = {}
self._all_decls = None
self._all_decls_not_recursive = None
... | Cleans query optimizer state |
def _datetime_key_for_merge(self, logevent):
"""Helper method for ordering log lines correctly during merge."""
if not logevent:
# if logfile end is reached, return max datetime to never
# pick this line
return datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzutc())
... | Helper method for ordering log lines correctly during merge. |
def adddeploykey(self, project_id, title, key):
"""
Creates a new deploy key for a project.
:param project_id: project id
:param title: title of the key
:param key: the key itself
:return: true if success, false if not
"""
data = {'id': project_id, 'title... | Creates a new deploy key for a project.
:param project_id: project id
:param title: title of the key
:param key: the key itself
:return: true if success, false if not |
def _feature_most_common(self, results):
"""
Find the most common country name in ES/Geonames results
Paramaters
----------
results: dict
output of `query_geonames`
Returns
-------
most_common: str
ISO code of most common country,... | Find the most common country name in ES/Geonames results
Paramaters
----------
results: dict
output of `query_geonames`
Returns
-------
most_common: str
ISO code of most common country, or empty string if none |
def stop_led_flash(self):
"""Stops flashing the LED."""
if self._led_flashing:
self._led_flash = (0, 0)
self._led_flashing = False
# Call twice, once to stop flashing...
self._control()
# ...and once more to make sure the LED is on.
... | Stops flashing the LED. |
def post_address_subcommand(search_terms, vcard_list, parsable):
"""Print a contact table. with all postal / mailing addresses
:param search_terms: used as search term to filter the contacts before
printing
:type search_terms: str
:param vcard_list: the vcards to search for matching entries whi... | Print a contact table. with all postal / mailing addresses
:param search_terms: used as search term to filter the contacts before
printing
:type search_terms: str
:param vcard_list: the vcards to search for matching entries which should
be printed
:type vcard_list: list of carddav_objec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.