code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def loadFiles(self, fileNames, rtiClass=None):
""" Loads files into the repository as repo tree items of class rtiClass.
Auto-detects using the extensions when rtiClass is None
"""
for fileName in fileNames:
self.repo.loadFile(fileName, rtiClass=rtiClass) | Loads files into the repository as repo tree items of class rtiClass.
Auto-detects using the extensions when rtiClass is None |
def create_target_group(name,
protocol,
port,
vpc_id,
region=None,
key=None,
keyid=None,
profile=None,
health_check_protocol='HT... | Create target group if not present.
name
(string) - The name of the target group.
protocol
(string) - The protocol to use for routing traffic to the targets
port
(int) - The port on which the targets receive traffic. This port is used unless
you specify a port override when ... |
def isclose(a, b, align=False, rtol=1.e-5, atol=1.e-8):
"""Compare two molecules for numerical equality.
Args:
a (Cartesian):
b (Cartesian):
align (bool): a and b are
prealigned along their principal axes of inertia and moved to their
barycenters before comparing... | Compare two molecules for numerical equality.
Args:
a (Cartesian):
b (Cartesian):
align (bool): a and b are
prealigned along their principal axes of inertia and moved to their
barycenters before comparing.
rtol (float): Relative tolerance for the numerical eq... |
def resource_from_etree(self, etree, resource_class):
"""Construct a Resource from an etree.
Parameters:
etree - the etree to parse
resource_class - class of Resource object to create
The parsing is properly namespace aware but we search just
for the elements wanted a... | Construct a Resource from an etree.
Parameters:
etree - the etree to parse
resource_class - class of Resource object to create
The parsing is properly namespace aware but we search just
for the elements wanted and leave everything else alone. Will
raise an error if th... |
def temp_shell_task(cls, inp, mpi_procs=1, workdir=None, manager=None):
"""
Build a Task with a temporary workdir. The task is executed via the shell with 1 MPI proc.
Mainly used for invoking Abinit to get important parameters needed to prepare the real task.
Args:
mpi_procs... | Build a Task with a temporary workdir. The task is executed via the shell with 1 MPI proc.
Mainly used for invoking Abinit to get important parameters needed to prepare the real task.
Args:
mpi_procs: Number of MPI processes to use. |
def pdf_Gates_Gaudin_Schuhman(d, d_characteristic, m):
r'''Calculates the probability density of a particle
distribution following the Gates, Gaudin and Schuhman (GGS) model given a
particle diameter `d`, characteristic (maximum) particle
diameter `d_characteristic`, and exponent `m`.
.. math:... | r'''Calculates the probability density of a particle
distribution following the Gates, Gaudin and Schuhman (GGS) model given a
particle diameter `d`, characteristic (maximum) particle
diameter `d_characteristic`, and exponent `m`.
.. math::
q(d) = \frac{n}{d}\left(\frac{d}{d_{characteristi... |
def matches_prefix(ip, prefix):
"""
Returns True if the given IP address is part of the given
network, returns False otherwise.
:type ip: string
:param ip: An IP address.
:type prefix: string
:param prefix: An IP prefix.
:rtype: bool
:return: True if the IP is in the prefix, Fals... | Returns True if the given IP address is part of the given
network, returns False otherwise.
:type ip: string
:param ip: An IP address.
:type prefix: string
:param prefix: An IP prefix.
:rtype: bool
:return: True if the IP is in the prefix, False otherwise. |
def _flush(self):
"""Purges the buffer and commits all pending values into the estimator."""
self._buffer.sort()
self._replace_batch()
self._buffer = []
self._compress() | Purges the buffer and commits all pending values into the estimator. |
def is_suicide_or_check_by_dropping_pawn(self, move):
'''
Checks if the given move would move would leave the king in check or
put it into check.
'''
self.push(move)
is_suicide = self.was_suicide()
is_check_by_dropping_pawn = self.was_check_by_dropping_pawn(move)... | Checks if the given move would move would leave the king in check or
put it into check. |
def invert_hash(self, tok_hash):
'''Get strings that correspond to some hash.
No string will correspond to :data:`DOCUMENT_HASH_KEY`; use
:data:`DOCUMENT_HASH_KEY_REPLACEMENT` instead.
:param int tok_hash: Murmur hash to query
:return: list of :class:`unicode` strings
... | Get strings that correspond to some hash.
No string will correspond to :data:`DOCUMENT_HASH_KEY`; use
:data:`DOCUMENT_HASH_KEY_REPLACEMENT` instead.
:param int tok_hash: Murmur hash to query
:return: list of :class:`unicode` strings |
def get_node_fact_by_name(api_url=None, node_name=None, fact_name=None, verify=False, cert=list()):
"""
Returns specified fact for a Node
:param api_url: Base PuppetDB API url
:param node_name: Name of node
:param fact_name: Name of fact
"""
return utils._make_api_request(api_url, '/nodes/... | Returns specified fact for a Node
:param api_url: Base PuppetDB API url
:param node_name: Name of node
:param fact_name: Name of fact |
def libvlc_media_get_type(p_md):
'''Get the media type of the media descriptor object.
@param p_md: media descriptor object.
@return: media type.
@version: LibVLC 3.0.0 and later. See libvlc_media_type_t.
'''
f = _Cfunctions.get('libvlc_media_get_type', None) or \
_Cfunction('libvlc_medi... | Get the media type of the media descriptor object.
@param p_md: media descriptor object.
@return: media type.
@version: LibVLC 3.0.0 and later. See libvlc_media_type_t. |
def get_item(key):
"""Return content in cached file in JSON format"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
try:
return json.loads(open(CACHED_KEY_FILE, "rb").read().decode('UTF-8'))["_"]
except (IOError, ValueError):
return None | Return content in cached file in JSON format |
def start_tcp_server(self, port):
"""
Starts the TCP server using given port.
:param port: Port.
:type port: int
:return: Method success.
:rtype: bool
"""
self.__tcp_server.port = port
if not self.__tcp_server.online:
if self.__tcp_se... | Starts the TCP server using given port.
:param port: Port.
:type port: int
:return: Method success.
:rtype: bool |
def positions_to_contigs(positions):
"""Flattens and converts a positions array to a contigs array, if applicable.
"""
if isinstance(positions, np.ndarray):
flattened_positions = positions.flatten()
else:
try:
flattened_positions = np.array(
[pos for contig i... | Flattens and converts a positions array to a contigs array, if applicable. |
def write_table(page, headers, data, cl=''):
"""
Write table in html
"""
page.table(class_=cl)
# list
if cl=='list':
for i in range(len(headers)):
page.tr()
page.th()
page.add('%s' % headers[i])
page.th.close()
page.td()
... | Write table in html |
def _validate_minlength(self, min_length, field, value):
""" {'type': 'integer'} """
if isinstance(value, Iterable) and len(value) < min_length:
self._error(field, errors.MIN_LENGTH, len(value)) | {'type': 'integer'} |
def shorten_go_name_ptbl3(self, name, dcnt):
"""Shorten GO description for Table 3 in manuscript."""
if self._keep_this(name):
return name
name = name.replace("positive regulation of immune system process",
"+ reg. of immune sys. process")
name = n... | Shorten GO description for Table 3 in manuscript. |
def make(data, samples):
""" build a vcf file from the supercatg array and the cat.clust.gz output"""
outfile = open(os.path.join(data.dirs.outfiles, data.name+".vcf"), 'w')
inloci = os.path.join(data.dirs.outfiles, data.name+".loci")
names = [i.name for i in samples]
names.sort()
## TODO:... | build a vcf file from the supercatg array and the cat.clust.gz output |
def in_(self, *objs):
"""
Create a condition
"""
if not objs:
return self.table.c[self.fielda]!=self.table.c[self.fielda]
else:
keys = get_objs_columns(objs, self.reference_fieldname)
sub_query = select([self.table.c[self.fielda]], (self.table.... | Create a condition |
def diff(cwd,
item1=None,
item2=None,
opts='',
git_opts='',
user=None,
password=None,
no_index=False,
cached=False,
paths=None,
output_encoding=None):
'''
.. versionadded:: 2015.8.12,2016.3.3,2016.11.0
Interface to `g... | .. versionadded:: 2015.8.12,2016.3.3,2016.11.0
Interface to `git-diff(1)`_
cwd
The path to the git checkout
item1 and item2
Revision(s) to pass to the ``git diff`` command. One or both of these
arguments may be ignored if some of the options below are set to
``True``. When... |
def prev(self):
"""Get the previous segment."""
seg = Segment(segment_t=idaapi.get_prev_seg(self.ea))
if seg.ea >= self.ea:
raise exceptions.NoMoreSegments("This is the first segment. no segments exist before it.")
return seg | Get the previous segment. |
def incr(self, key, value, default=0, time=1000000):
"""
Increment a key, if it exists, returns its actual value, if it doesn't, return 0.
:param key: Key's name
:type key: six.string_types
:param value: Number to be incremented
:type value: int
:param default: D... | Increment a key, if it exists, returns its actual value, if it doesn't, return 0.
:param key: Key's name
:type key: six.string_types
:param value: Number to be incremented
:type value: int
:param default: Default value if key does not exist.
:type default: int
:p... |
def halt(self):
"""
Halt current endpoint.
"""
try:
self._halt()
except IOError as exc:
if exc.errno != errno.EBADMSG:
raise
else:
raise ValueError('halt did not return EBADMSG ?')
self._halted = True | Halt current endpoint. |
def play(events, speed_factor=1.0):
"""
Plays a sequence of recorded events, maintaining the relative time
intervals. If speed_factor is <= 0 then the actions are replayed as fast
as the OS allows. Pairs well with `record()`.
Note: the current keyboard state is cleared at the beginning and restored... | Plays a sequence of recorded events, maintaining the relative time
intervals. If speed_factor is <= 0 then the actions are replayed as fast
as the OS allows. Pairs well with `record()`.
Note: the current keyboard state is cleared at the beginning and restored at
the end of the function. |
def function(data, maxt=None):
"""
Calculate the autocorrelation function for a 1D time series.
Parameters
----------
data : numpy.ndarray (N,)
The time series.
Returns
-------
rho : numpy.ndarray (N,)
An autocorrelation function.
"""
data = np.atleast_1d(data)... | Calculate the autocorrelation function for a 1D time series.
Parameters
----------
data : numpy.ndarray (N,)
The time series.
Returns
-------
rho : numpy.ndarray (N,)
An autocorrelation function. |
def hook_focus_events(self):
""" Install the hooks for focus events.
This method may be overridden by subclasses as needed.
"""
widget = self.widget
widget.focusInEvent = self.focusInEvent
widget.focusOutEvent = self.focusOutEvent | Install the hooks for focus events.
This method may be overridden by subclasses as needed. |
def _noise_dict_update(noise_dict):
"""
Update the noise dictionary parameters with default values, in case any
were missing
Parameters
----------
noise_dict : dict
A dictionary specifying the types of noise in this experiment. The
noise types interact in important ways. First,... | Update the noise dictionary parameters with default values, in case any
were missing
Parameters
----------
noise_dict : dict
A dictionary specifying the types of noise in this experiment. The
noise types interact in important ways. First, all noise types
ending with sigma (e.g.... |
def remove_nopairs(in_bam, out_dir, config):
"""Remove any reads without both pairs present in the file.
"""
runner = broad.runner_from_config(config)
out_bam = os.path.join(out_dir, "{}-safepair{}".format(*os.path.splitext(os.path.basename(in_bam))))
if not utils.file_exists(out_bam):
read_... | Remove any reads without both pairs present in the file. |
def migrate_doc(self, doc):
"""
Migrate the doc from its current version to the target version
and return it.
"""
orig_ver = doc.get(self.version_attribute_name, 0)
funcs = self._get_migrate_funcs(orig_ver, self.target_version)
for func in funcs:
func(self, doc)
doc[self.version_attribute_name] = fu... | Migrate the doc from its current version to the target version
and return it. |
def get(self, key):
"""
Returns the list of values associated with the key. ``None`` if this map does not contain this key.
**Warning:
This method uses hashCode and equals of the binary form of the key, not the actual implementations of hashCode
and equals defined in the key's c... | Returns the list of values associated with the key. ``None`` if this map does not contain this key.
**Warning:
This method uses hashCode and equals of the binary form of the key, not the actual implementations of hashCode
and equals defined in the key's class.**
**Warning-2:
Th... |
def location(args):
"""
%prog location bedfile fastafile
Given SNP locations, summarize the locations in the sequences. For example,
find out if there are more 3`-SNPs than 5`-SNPs.
"""
from jcvi.formats.bed import BedLine
from jcvi.graphics.histogram import stem_leaf_plot
p = OptionPa... | %prog location bedfile fastafile
Given SNP locations, summarize the locations in the sequences. For example,
find out if there are more 3`-SNPs than 5`-SNPs. |
def get(self, *args, **kwargs):
"""
Works just like the default Manager's :func:`get` method, but
you can pass an additional keyword argument named ``path`` specifying
the full path of the object you want to retrieve, e.g.
``"path/to/folder/readme.txt"``.
"""
if '... | Works just like the default Manager's :func:`get` method, but
you can pass an additional keyword argument named ``path`` specifying
the full path of the object you want to retrieve, e.g.
``"path/to/folder/readme.txt"``. |
def validate(self, institute, case, user, link, variant, validate_type):
"""Mark validation status for a variant.
Arguments:
institute (dict): A Institute object
case (dict): Case object
user (dict): A User object
link (str): The url to be used in the eve... | Mark validation status for a variant.
Arguments:
institute (dict): A Institute object
case (dict): Case object
user (dict): A User object
link (str): The url to be used in the event
variant (dict): A variant object
validate_type(str): The ... |
def get_subscriptions(self):
"""
:calls: `GET /users/:user/subscriptions <http://developer.github.com/v3/activity/watching>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
"""
return github.PaginatedList.PaginatedList(
gi... | :calls: `GET /users/:user/subscriptions <http://developer.github.com/v3/activity/watching>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository` |
def is_domain_equal(self, other):
"""
Computes whether two Partial Orderings have the same generalization
structure.
"""
domain = self.get_domain()
other_domain = other.get_domain()
# if they share the same instance of memory for the domain
if domain == ot... | Computes whether two Partial Orderings have the same generalization
structure. |
def run(self, run_priority: Optional[int] = None):
"""
Run a pyquil program on the QPU.
This formats the classified data from the QPU server by stacking measured bits into
an array of shape (trials, classical_addresses). The mapping of qubit to
classical address is backed out fr... | Run a pyquil program on the QPU.
This formats the classified data from the QPU server by stacking measured bits into
an array of shape (trials, classical_addresses). The mapping of qubit to
classical address is backed out from MEASURE instructions in the program, so
only do measurements... |
def add_approximant_arg(parser, default=None, help=None):
"""Adds an approximant argument to the given parser.
Parameters
----------
parser : ArgumentParser
The argument parser to add the argument to.
default : {None, str}
Specify a default for the approximant argument. Defaults to ... | Adds an approximant argument to the given parser.
Parameters
----------
parser : ArgumentParser
The argument parser to add the argument to.
default : {None, str}
Specify a default for the approximant argument. Defaults to None.
help : {None, str}
Provide a custom help messag... |
def SetTimezone(self, timezone):
"""Sets the timezone.
Args:
timezone (str): timezone.
Raises:
ValueError: if the timezone is not supported.
"""
if not timezone:
return
try:
self._timezone = pytz.timezone(timezone)
except pytz.UnknownTimeZoneError:
raise Valu... | Sets the timezone.
Args:
timezone (str): timezone.
Raises:
ValueError: if the timezone is not supported. |
def to_dms(angle, style='dms'):
"""Convert decimal angle to degrees, minutes and possibly seconds.
Args:
angle (float): Angle to convert
style (str): Return fractional or whole minutes values
Returns:
tuple of int: Angle converted to degrees, minutes and possibly seconds
Raise... | Convert decimal angle to degrees, minutes and possibly seconds.
Args:
angle (float): Angle to convert
style (str): Return fractional or whole minutes values
Returns:
tuple of int: Angle converted to degrees, minutes and possibly seconds
Raises:
ValueError: Unknown value fo... |
def apply_weight_drop(block, local_param_regex, rate, axes=(),
weight_dropout_mode='training'):
"""Apply weight drop to the parameter of a block.
Parameters
----------
block : Block or HybridBlock
The block whose parameter is to be applied weight-drop.
local_param_rege... | Apply weight drop to the parameter of a block.
Parameters
----------
block : Block or HybridBlock
The block whose parameter is to be applied weight-drop.
local_param_regex : str
The regex for parameter names used in the self.params.get(), such as 'weight'.
rate : float
Fract... |
def _write_local_schema_file(self, cursor):
"""
Takes a cursor, and writes the BigQuery schema for the results to a
local file system.
:return: A dictionary where key is a filename to be used as an object
name in GCS, and values are file handles to local files that
... | Takes a cursor, and writes the BigQuery schema for the results to a
local file system.
:return: A dictionary where key is a filename to be used as an object
name in GCS, and values are file handles to local files that
contains the BigQuery schema fields in .json format. |
def _reorient_3d(image):
"""
Reorganize the data for a 3d nifti
"""
# Create empty array where x,y,z correspond to LR (sagittal), PA (coronal), IS (axial) directions and the size
# of the array in each direction is the same with the corresponding direction of the input image.
new_image = numpy.z... | Reorganize the data for a 3d nifti |
def richardson(vals, k, c=None):
"""Richardson extrapolation with parameter estimation"""
if c is None:
c = richardson_parameter(vals, k)
return vals[k] - (vals[k] - vals[k - 1]) / c | Richardson extrapolation with parameter estimation |
def _parse_block(self, block, node):
'''
Return:
Node
'''
assert block[self.get_key()] == 'Block'
if self.is_compact_ast:
statements = block['statements']
else:
statements = block[self.get_children('children')]
for statement i... | Return:
Node |
def _check_iso9660_filename(fullname, interchange_level):
# type: (bytes, int) -> None
'''
A function to check that a file identifier conforms to the ISO9660 rules
for a particular interchange level.
Parameters:
fullname - The name to check.
interchange_level - The interchange level to ch... | A function to check that a file identifier conforms to the ISO9660 rules
for a particular interchange level.
Parameters:
fullname - The name to check.
interchange_level - The interchange level to check against.
Returns:
Nothing. |
def _link_bam_file(in_file, new_dir, data):
"""Provide symlinks of BAM file and existing indexes if needed.
"""
new_dir = utils.safe_makedir(new_dir)
out_file = os.path.join(new_dir, os.path.basename(in_file))
if not utils.file_exists(out_file):
out_file = os.path.join(new_dir, "%s-prealign.... | Provide symlinks of BAM file and existing indexes if needed. |
def fig3(args):
"""
%prog fig3 chrA02,A02,C2,chrC02 chr.sizes all.bed data
Napus Figure 3 displays alignments between quartet chromosomes, inset
with read histograms.
"""
from jcvi.formats.bed import Bed
p = OptionParser(fig3.__doc__)
p.add_option("--gauge_step", default=10000000, type... | %prog fig3 chrA02,A02,C2,chrC02 chr.sizes all.bed data
Napus Figure 3 displays alignments between quartet chromosomes, inset
with read histograms. |
def send_command(self, cmd):
"""
Send a command to the remote SSH server.
:param cmd: The command to send
"""
logger.debug('Sending {0} command.'.format(cmd))
self.comm_chan.sendall(cmd + '\n') | Send a command to the remote SSH server.
:param cmd: The command to send |
def rgevolve(self, scale_out, **kwargs):
"""Solve the SMEFT RGEs from the initial scale to `scale_out`.
Returns a dictionary with parameters and Wilson coefficients at
`scale_out`. Additional keyword arguments will be passed to
the ODE solver `scipy.integrate.odeint`."""
self._ch... | Solve the SMEFT RGEs from the initial scale to `scale_out`.
Returns a dictionary with parameters and Wilson coefficients at
`scale_out`. Additional keyword arguments will be passed to
the ODE solver `scipy.integrate.odeint`. |
def create(self, rs_params):
"""create new replica set
Args:
rs_params - replica set configuration
Return repl_id which can use to take the replica set
"""
repl_id = rs_params.get('id', None)
if repl_id is not None and repl_id in self:
raise Replica... | create new replica set
Args:
rs_params - replica set configuration
Return repl_id which can use to take the replica set |
def prod(self, axis=None, dtype=None, out=None, keepdims=False):
"""Return the product of ``self``.
See Also
--------
numpy.prod
sum
"""
return self.elem.__array_ufunc__(
np.multiply, 'reduce', self.elem,
axis=axis, dtype=dtype, out=(out,)... | Return the product of ``self``.
See Also
--------
numpy.prod
sum |
async def update_firmware(port: str,
firmware_file_path: str,
loop: Optional[asyncio.AbstractEventLoop])\
-> Tuple[str, Tuple[bool, str]]:
"""
Run avrdude firmware upload command. Switch back to normal module port
Note: For modul... | Run avrdude firmware upload command. Switch back to normal module port
Note: For modules with old bootloader, the kernel could assign the module
a new port after the update (since the board is automatically reset).
Scan for such a port change and use the appropriate port.
Returns a tuple of the new po... |
def _ParseShVariables(self, lines):
"""Extract env_var and path values from sh derivative shells.
Iterates over each line, word by word searching for statements that set the
path. These are either variables, or conditions that would allow a variable
to be set later in the line (e.g. export).
Args:... | Extract env_var and path values from sh derivative shells.
Iterates over each line, word by word searching for statements that set the
path. These are either variables, or conditions that would allow a variable
to be set later in the line (e.g. export).
Args:
lines: A list of lines, each of whic... |
def button_number(self):
"""The button number that triggered this event, starting at 0.
For events that are not of type
:attr:`~libinput.constant.Event.TABLET_PAD_BUTTON`,
this property raises :exc:`AttributeError`.
Note that the number returned is a generic sequential button number
and not a semantic but... | The button number that triggered this event, starting at 0.
For events that are not of type
:attr:`~libinput.constant.Event.TABLET_PAD_BUTTON`,
this property raises :exc:`AttributeError`.
Note that the number returned is a generic sequential button number
and not a semantic button code as defined in ``linux... |
def surfacemass(self,R,log=False):
"""
NAME:
surfacemass
PURPOSE:
return the surface density profile at this R
INPUT:
R - Galactocentric radius (/ro)
log - if True, return the log (default: False)
OUTPUT:
Sigma(R)
HIS... | NAME:
surfacemass
PURPOSE:
return the surface density profile at this R
INPUT:
R - Galactocentric radius (/ro)
log - if True, return the log (default: False)
OUTPUT:
Sigma(R)
HISTORY:
2010-03-26 - Written - Bovy (NYU) |
def __runTaskMainLoop(self, numIters, learningOffAt=None):
""" Main loop of the OPF Model Runner.
Parameters:
-----------------------------------------------------------------------
recordIterator: Iterator for counting number of records (see _runTask)
learningOffAt: If not None, learning i... | Main loop of the OPF Model Runner.
Parameters:
-----------------------------------------------------------------------
recordIterator: Iterator for counting number of records (see _runTask)
learningOffAt: If not None, learning is turned off when we reach this
iteration n... |
def create_task(self, list_id, title, assignee_id=None, completed=None, recurrence_type=None, recurrence_count=None, due_date=None, starred=None):
''' Creates a new task with the given information in the list with the given ID '''
return tasks_endpoint.create_task(self, list_id, title, assignee_id=assig... | Creates a new task with the given information in the list with the given ID |
def delete(self, cluster):
"""Deletes the cluster from memory.
:param cluster: cluster to delete
:type cluster: :py:class:`elasticluster.cluster.Cluster`
"""
if cluster.name not in self.clusters:
raise ClusterNotFound(
"Unable to delete non-existent c... | Deletes the cluster from memory.
:param cluster: cluster to delete
:type cluster: :py:class:`elasticluster.cluster.Cluster` |
def get_size(self, boundary):
"""Returns the size in bytes that this param will be when encoded
with the given boundary."""
if self.filesize is not None:
valuesize = self.filesize
else:
valuesize = len(self.value)
return len(self.encode_hdr(boundary)) + 2... | Returns the size in bytes that this param will be when encoded
with the given boundary. |
def masses_of_galaxies_within_ellipses_in_units(self, major_axis : dim.Length, unit_mass='angular',
critical_surface_density=None):
"""Compute the total mass of all galaxies in this plane within a ellipse of specified major-axis.
See *galaxy.angular_m... | Compute the total mass of all galaxies in this plane within a ellipse of specified major-axis.
See *galaxy.angular_mass_within_ellipse* and *mass_profiles.angular_mass_within_ellipse* for details \
of how this is performed.
Parameters
----------
major_axis : float
T... |
def _normalize_http_methods(http_method):
"""
Normalizes Http Methods. Api Gateway allows a Http Methods of ANY. This is a special verb to denote all
supported Http Methods on Api Gateway.
:param str http_method: Http method
:yield str: Either the input http_method or one of the... | Normalizes Http Methods. Api Gateway allows a Http Methods of ANY. This is a special verb to denote all
supported Http Methods on Api Gateway.
:param str http_method: Http method
:yield str: Either the input http_method or one of the _ANY_HTTP_METHODS (normalized Http Methods) |
def filename_items_for_filetype(filenames, filetype_info):
"""Iterator over the filenames matching *filetype_info*."""
matched_files = []
for pattern in filetype_info['file_patterns']:
for filename in match_filenames(filenames, pattern):
if filename in matched_files:
... | Iterator over the filenames matching *filetype_info*. |
def create(self, deviceType):
"""
Register one or more new device types, each request can contain a maximum of 512KB.
"""
r = self._apiClient.post("api/v0002/device/types", deviceType)
if r.status_code == 201:
return DeviceType(apiClient=self._apiClient, **r.json())... | Register one or more new device types, each request can contain a maximum of 512KB. |
def allocate(self, size, max_time_to_block_ms):
"""
Allocate a buffer of the given size. This method blocks if there is not
enough memory and the buffer pool is configured with blocking mode.
Arguments:
size (int): The buffer size to allocate in bytes [ignored]
m... | Allocate a buffer of the given size. This method blocks if there is not
enough memory and the buffer pool is configured with blocking mode.
Arguments:
size (int): The buffer size to allocate in bytes [ignored]
max_time_to_block_ms (int): The maximum time in milliseconds to
... |
def prod(self):
"""Summary
Returns:
TYPE: Description
"""
return LazyOpResult(
grizzly_impl.aggr(
self.expr,
"*",
1,
self.weld_type
),
self.weld_type,
0
) | Summary
Returns:
TYPE: Description |
def update_ipsecpolicy(self, ipsecpolicy, body=None):
"""Updates an IPsecPolicy."""
return self.put(self.ipsecpolicy_path % (ipsecpolicy), body=body) | Updates an IPsecPolicy. |
def capabilities(self):
"""A tuple of capabilities this device supports.
Returns:
(~libinput.constant.DeviceCapability): Device capabilities.
"""
caps = []
for cap in DeviceCapability:
if self._libinput.libinput_device_has_capability(self._handle, cap):
caps.append(cap)
return tuple(caps) | A tuple of capabilities this device supports.
Returns:
(~libinput.constant.DeviceCapability): Device capabilities. |
def plos_doi_to_xmlurl(doi_string):
"""
Attempts to resolve a PLoS DOI into a URL path to the XML file.
"""
#Create URL to request DOI resolution from http://dx.doi.org
doi_url = 'http://dx.doi.org/{0}'.format(doi_string)
log.debug('DOI URL: {0}'.format(doi_url))
#Open the page, follow the r... | Attempts to resolve a PLoS DOI into a URL path to the XML file. |
def resize_hess(self, func):
"""
Removes values with identical indices to fixed parameters from the
output of func. func has to return the Hessian of a scalar function.
:param func: Hessian function to be wrapped. Is assumed to be the
Hessian of a scalar function.
:r... | Removes values with identical indices to fixed parameters from the
output of func. func has to return the Hessian of a scalar function.
:param func: Hessian function to be wrapped. Is assumed to be the
Hessian of a scalar function.
:return: Hessian corresponding to free parameters o... |
def xlink_href_target(self, node, group=None):
"""
Return either:
- a tuple (renderer, node) when the the xlink:href attribute targets
a vector file or node
- the path to an image file for any raster image targets
- None if any problem occurs
"""... | Return either:
- a tuple (renderer, node) when the the xlink:href attribute targets
a vector file or node
- the path to an image file for any raster image targets
- None if any problem occurs |
def build(self, builder):
"""Build XML by appending to builder"""
params = dict(StudyOID=self.study_oid,
MetaDataVersionOID=self.metadata_version_oid,
EffectiveDate=dt_to_iso8601(self.effective_date))
builder.start("MetaDataVersionRef", params)
... | Build XML by appending to builder |
def exists(table_name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if a table exists.
CLI Example:
.. code-block:: bash
salt myminion boto_dynamodb.exists table_name region=us-east-1
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=... | Check to see if a table exists.
CLI Example:
.. code-block:: bash
salt myminion boto_dynamodb.exists table_name region=us-east-1 |
def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
"""Set standardized axis formatting for figure."""
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position(yticks_position)
ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
... | Set standardized axis formatting for figure. |
def detect(self, tokens):
"""Return a (abbr, long) pair for each abbreviation definition."""
results = []
for abbr_span, long_span in self.detect_spans(tokens):
results.append((tokens[abbr_span[0]:abbr_span[1]], tokens[long_span[0]:long_span[1]]))
return results | Return a (abbr, long) pair for each abbreviation definition. |
def _from_dict(cls, mapping):
"""Create an instance from the corresponding state mapping.
:type mapping: dict
:param mapping: the instance state.
"""
if mapping.get("all"):
return cls(all_=True)
r_mappings = mapping.get("ranges", ())
ranges = [KeyRan... | Create an instance from the corresponding state mapping.
:type mapping: dict
:param mapping: the instance state. |
def _make_futures(futmap_keys, class_check, make_result_fn):
"""
Create futures and a futuremap for the keys in futmap_keys,
and create a request-level future to be bassed to the C API.
"""
futmap = {}
for key in futmap_keys:
if class_check is not None and not... | Create futures and a futuremap for the keys in futmap_keys,
and create a request-level future to be bassed to the C API. |
def _on_return(self, text):
"""Called when the user presses return on the send message widget."""
# Ignore if the user hasn't typed a message.
if not text:
return
elif text.startswith('/image') and len(text.split(' ')) == 2:
# Temporary UI for testing image upload... | Called when the user presses return on the send message widget. |
def platform_mapped(func):
"""Decorates functions for lookups within a config.platform_map dictionary.
The first level key is mapped to the func.__name__ of the decorated function.
Regular expressions are used on the second level key, values.
Note that there is no guaranteed order within the dictionary... | Decorates functions for lookups within a config.platform_map dictionary.
The first level key is mapped to the func.__name__ of the decorated function.
Regular expressions are used on the second level key, values.
Note that there is no guaranteed order within the dictionary evaluation. Only the first matchi... |
def _lons(self):
"""Return the longitudes (in degrees) of the gridded data."""
lons = _np.linspace(0.0, 360.0 - 360.0 / self.nlon, num=self.nlon)
return lons | Return the longitudes (in degrees) of the gridded data. |
def _patch_distribution_metadata():
"""Patch write_pkg_file and read_pkg_file for higher metadata standards"""
for attr in ('write_pkg_file', 'read_pkg_file', 'get_metadata_version'):
new_val = getattr(setuptools.dist, attr)
setattr(distutils.dist.DistributionMetadata, attr, new_val) | Patch write_pkg_file and read_pkg_file for higher metadata standards |
def dump(obj, fp, **kwargs):
"""
Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object)
"""
return json.dump(obj, fp, cls=BioCJSONEncoder, **kwargs) | Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) |
def spd_eig(W, epsilon=1e-10, method='QR', canonical_signs=False):
""" Rank-reduced eigenvalue decomposition of symmetric positive definite matrix.
Removes all negligible eigenvalues
Parameters
----------
W : ndarray((n, n), dtype=float)
Symmetric positive-definite (spd) matrix.
epsilo... | Rank-reduced eigenvalue decomposition of symmetric positive definite matrix.
Removes all negligible eigenvalues
Parameters
----------
W : ndarray((n, n), dtype=float)
Symmetric positive-definite (spd) matrix.
epsilon : float
Truncation parameter. Eigenvalues with norms smaller than... |
def forwards(self, orm):
"Write your forwards methods here."
for instance in orm.LocationSource.objects.all():
try:
instance.user = instance.points.all()[0].user
instance.save()
except IndexError:
# No points for this source.
... | Write your forwards methods here. |
def finalize(self, **kwargs):
"""
Finalize executes any subclass-specific axes finalization steps.
The user calls poof and poof calls finalize.
Parameters
----------
kwargs: dict
generic keyword arguments
"""
# Set the title
self.set_... | Finalize executes any subclass-specific axes finalization steps.
The user calls poof and poof calls finalize.
Parameters
----------
kwargs: dict
generic keyword arguments |
def is_compression_coordinate(ds, variable):
'''
Returns True if the variable is a coordinate variable that defines a
compression scheme.
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: Variable name
'''
# Must be a coordinate variable
if not is_coordinate_variabl... | Returns True if the variable is a coordinate variable that defines a
compression scheme.
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: Variable name |
def _init(self):
"""Read the success byte."""
self._ready = self._file.read(1)
self._hall_left = self._file.read(2)
self._hall_right = self._file.read(2)
self._carriage_type = self._file.read(1)[0]
self._carriage_position = self._file.read(1)[0] | Read the success byte. |
def AddDescriptor(self, desc):
"""Adds a Descriptor to the pool, non-recursively.
If the Descriptor contains nested messages or enums, the caller must
explicitly register them. This method also registers the FileDescriptor
associated with the message.
Args:
desc: A Descriptor.
"""
if... | Adds a Descriptor to the pool, non-recursively.
If the Descriptor contains nested messages or enums, the caller must
explicitly register them. This method also registers the FileDescriptor
associated with the message.
Args:
desc: A Descriptor. |
def analyze(self, handle, filename):
"""Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: Task ID as a string
"""
... | Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: Task ID as a string |
def get_build_config_by_labels_filtered(self, label_selectors, filter_key, filter_value):
"""
Returns a build config matching the given label selectors, filtering against
another predetermined value. This method will raise OsbsException
if not exactly one build config is found after filt... | Returns a build config matching the given label selectors, filtering against
another predetermined value. This method will raise OsbsException
if not exactly one build config is found after filtering. |
def download(self, filename, format='sdf', overwrite=False, resolvers=None, **kwargs):
""" Download the resolved structure as a file """
download(self.input, filename, format, overwrite, resolvers, **kwargs) | Download the resolved structure as a file |
def last_ser(self):
"""
Return the last `<c:ser>` element in the last xChart element, based
on series order (not necessarily the same element as document order).
"""
last_xChart = self.xCharts[-1]
sers = last_xChart.sers
if not sers:
return None
... | Return the last `<c:ser>` element in the last xChart element, based
on series order (not necessarily the same element as document order). |
def stars_list(self, **kwargs) -> SlackResponse:
"""Lists stars for a user."""
self._validate_xoxp_token()
return self.api_call("stars.list", http_verb="GET", params=kwargs) | Lists stars for a user. |
def read_pickle(fn):
"""Load a GOParser object from a pickle file.
The function automatically detects whether the file is compressed
with gzip.
Parameters
----------
fn: str
Path of the pickle file.
Returns
-------
`GOParser`
... | Load a GOParser object from a pickle file.
The function automatically detects whether the file is compressed
with gzip.
Parameters
----------
fn: str
Path of the pickle file.
Returns
-------
`GOParser`
The GOParser object stored ... |
def extracting(self, *names, **kwargs):
"""Asserts that val is collection, then extracts the named properties or named zero-arg methods into a list (or list of tuples if multiple names are given)."""
if not isinstance(self.val, Iterable):
raise TypeError('val is not iterable')
if isi... | Asserts that val is collection, then extracts the named properties or named zero-arg methods into a list (or list of tuples if multiple names are given). |
def std(self, n, array=False):
"""标准差"""
result = talib.STDDEV(self.close, n)
if array:
return result
return result[-1] | 标准差 |
def cluster_health(index=None, level='cluster', local=False, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Return Elasticsearch cluster health.
index
Limit the information returned to a specific index
level
Specify the level of detail for returned information, default '... | .. versionadded:: 2017.7.0
Return Elasticsearch cluster health.
index
Limit the information returned to a specific index
level
Specify the level of detail for returned information, default 'cluster', valid choices are: 'cluster', 'indices', 'shards'
local
Return local informati... |
def read_cstring(self) -> bool:
"""
read a double quoted string
Read following BNF rule else return False::
'"' -> ['\\' #char | ~'\\'] '"'
"""
self._stream.save_context()
idx = self._stream.index
if self.read_char("\"") and self.read_until("\"", "\\"):
txt = self._stream[i... | read a double quoted string
Read following BNF rule else return False::
'"' -> ['\\' #char | ~'\\'] '"' |
def format_progress(self, width):
"""Create the formatted string that displays the progress."""
chunk_widths = self._get_chunk_sizes(width)
progress_chunks = [chunk.format_chunk(chunk_width)
for (chunk, chunk_width)
in zip(self._progress_chun... | Create the formatted string that displays the progress. |
def H13(self):
"Information measure of correlation 2."
# An imaginary result has been encountered once in the Matlab
# version. The reason is unclear.
return np.sqrt(1 - np.exp(-2 * (self.hxy2 - self.H9()))) | Information measure of correlation 2. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.