code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
async def linsert(self, name, where, refvalue, value):
"""
Insert ``value`` in list ``name`` either immediately before or after
[``where``] ``refvalue``
Returns the new length of the list on success or -1 if ``refvalue``
is not in the list.
"""
return await self.... | Insert ``value`` in list ``name`` either immediately before or after
[``where``] ``refvalue``
Returns the new length of the list on success or -1 if ``refvalue``
is not in the list. |
def index(self, item, **kwargs):
# type: (Any, dict) -> int
"""
Get index of the parameter.
:param item: Item for which get the index.
:return: Index of the parameter in the WeakList.
"""
return list.index(self, self.ref(item), **kwargs) | Get index of the parameter.
:param item: Item for which get the index.
:return: Index of the parameter in the WeakList. |
def transform(self, translation, theta, method='opencv'):
"""Create a new image by translating and rotating the current image.
Parameters
----------
translation : :obj:`numpy.ndarray` of float
The XY translation vector.
theta : float
Rotation angle in rad... | Create a new image by translating and rotating the current image.
Parameters
----------
translation : :obj:`numpy.ndarray` of float
The XY translation vector.
theta : float
Rotation angle in radians, with positive meaning counter-clockwise.
method : :obj:... |
def get_all(self):
# type: () -> typing.Iterable[typing.Tuple[str, str]]
"""Returns an iterable of all (name, value) pairs.
If a header has multiple values, multiple pairs will be
returned with the same name.
"""
for name, values in six.iteritems(self._as_list):
... | Returns an iterable of all (name, value) pairs.
If a header has multiple values, multiple pairs will be
returned with the same name. |
def get_monitoring_problems(self):
"""Get the schedulers satellites problems list
:return: problems dictionary
:rtype: dict
"""
res = self.get_id()
res['problems'] = {}
# Report our schedulers information, but only if a dispatcher exists
if getattr(self,... | Get the schedulers satellites problems list
:return: problems dictionary
:rtype: dict |
def get_value_by_version(d):
"""
Finds the value depending in current eplus version.
Parameters
----------
d: dict
{(0, 0): value, (x, x): value, ...}
for current version (cv), current value is the value of version v such as v <= cv < v+1
"""
from oplus import CONF # touch... | Finds the value depending in current eplus version.
Parameters
----------
d: dict
{(0, 0): value, (x, x): value, ...}
for current version (cv), current value is the value of version v such as v <= cv < v+1 |
def fixup_for_packaged():
''' If we are installing FROM an sdist, then a pre-built BokehJS is
already installed in the python source tree.
The command line options ``--build-js`` or ``--install-js`` are
removed from ``sys.argv``, with a warning.
Also adds ``--existing-js`` to ``sys.argv`` to signa... | If we are installing FROM an sdist, then a pre-built BokehJS is
already installed in the python source tree.
The command line options ``--build-js`` or ``--install-js`` are
removed from ``sys.argv``, with a warning.
Also adds ``--existing-js`` to ``sys.argv`` to signal that BokehJS is
already pack... |
def list_pkgs(installed=True,
attributes=True):
'''
Lists installed packages. Due to how nix works, it defaults to just doing a ``nix-env -q``.
:param bool installed:
list only installed packages. This can be a very long list (12,000+ elements), so caution is advised.
Default:... | Lists installed packages. Due to how nix works, it defaults to just doing a ``nix-env -q``.
:param bool installed:
list only installed packages. This can be a very long list (12,000+ elements), so caution is advised.
Default: True
:param bool attributes:
show the attributes of the pack... |
def get_referenced_object(self):
"""
:rtype: core.BunqModel
:raise: BunqException
"""
if self._DeviceServer is not None:
return self._DeviceServer
raise exception.BunqException(self._ERROR_NULL_FIELDS) | :rtype: core.BunqModel
:raise: BunqException |
def _parse_csv_header(header):
'''This parses a CSV header from a K2 CSV LC.
Returns a dict that can be used to update an existing lcdict with the
relevant metadata info needed to form a full LC.
'''
# first, break into lines
headerlines = header.split('\n')
headerlines = [x.lstrip('# ') ... | This parses a CSV header from a K2 CSV LC.
Returns a dict that can be used to update an existing lcdict with the
relevant metadata info needed to form a full LC. |
def _write_version1(self,new_filename,update_regul=False):
"""write a version 1 pest control file
Parameters
----------
new_filename : str
name of the new pest control file
update_regul : (boolean)
flag to update zero-order Tikhonov prior information
... | write a version 1 pest control file
Parameters
----------
new_filename : str
name of the new pest control file
update_regul : (boolean)
flag to update zero-order Tikhonov prior information
equations to prefer the current parameter values |
def from_file(cls, filename, directory=None,
format=None, engine=None, encoding=File._encoding):
"""Return an instance with the source string read from the given file.
Args:
filename: Filename for loading/saving the source.
directory: (Sub)directory for source ... | Return an instance with the source string read from the given file.
Args:
filename: Filename for loading/saving the source.
directory: (Sub)directory for source loading/saving and rendering.
format: Rendering output format (``'pdf'``, ``'png'``, ...).
engine: Lay... |
def Analyze(self, source_path, output_writer):
"""Analyzes the source.
Args:
source_path (str): the source path.
output_writer (StdoutWriter): the output writer.
Raises:
RuntimeError: if the source path does not exists, or if the source path
is not a file or directory, or if th... | Analyzes the source.
Args:
source_path (str): the source path.
output_writer (StdoutWriter): the output writer.
Raises:
RuntimeError: if the source path does not exists, or if the source path
is not a file or directory, or if the format of or within the source
file is not... |
def patch(self, patch):
"""Given a ParsedNodePatch, add the new information to the node."""
# explicitly pick out the parts to update so we don't inadvertently
# step on the model name or anything
self._contents.update({
'patch_path': patch.original_file_path,
'de... | Given a ParsedNodePatch, add the new information to the node. |
def patch_custom_resource_definition(self, name, body, **kwargs): # noqa: E501
"""patch_custom_resource_definition # noqa: E501
partially update the specified CustomResourceDefinition # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP r... | patch_custom_resource_definition # noqa: E501
partially update the specified CustomResourceDefinition # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_custom_resource_definitio... |
def _removeGlyph(self, name, **kwargs):
"""
This is the environment implementation of
:meth:`BaseFont.removeGlyph`. **name** will
be a :ref:`type-string` representing an
existing glyph in the default layer. The
value will have been normalized with
:func:`normalize... | This is the environment implementation of
:meth:`BaseFont.removeGlyph`. **name** will
be a :ref:`type-string` representing an
existing glyph in the default layer. The
value will have been normalized with
:func:`normalizers.normalizeGlyphName`.
Subclasses may override thi... |
def get_cut_prefix(value, max_len):
"""Drops Characters by unicode not by bytes."""
should_convert = isinstance(value, bytes)
if should_convert:
value = value.decode("utf8", "ignore")
for i in range(len(value)):
if terminal_width(value[i:]) <= max_len:
break
return value[... | Drops Characters by unicode not by bytes. |
def _execCmd(self, cmd, args):
"""Execute command and return result body as list of lines.
@param cmd: Command string.
@param args: Comand arguments string.
@return: Result dictionary.
"""
output = self._eslconn.api(cmd, args)
... | Execute command and return result body as list of lines.
@param cmd: Command string.
@param args: Comand arguments string.
@return: Result dictionary. |
def GetRosettaResidueMap(self, ConvertMSEToAtom = False, RemoveIncompleteFinalResidues = False, RemoveIncompleteResidues = False):
'''Note: This function ignores any DNA.'''
raise Exception('This code looks to be deprecated. Use construct_pdb_to_rosetta_residue_map instead.')
chain = None
... | Note: This function ignores any DNA. |
def notify_server_ready(self, language, config):
"""Notify language server availability to code editors."""
for index in range(self.get_stack_count()):
editor = self.tabs.widget(index)
if editor.language.lower() == language:
editor.start_lsp_services(config) | Notify language server availability to code editors. |
def _stripe_object_to_refunds(cls, target_cls, data, charge):
"""
Retrieves Refunds for a charge
:param target_cls: The target class to instantiate per invoice item.
:type target_cls: ``Refund``
:param data: The data dictionary received from the Stripe API.
:type data: dict
:param charge: The charge objec... | Retrieves Refunds for a charge
:param target_cls: The target class to instantiate per invoice item.
:type target_cls: ``Refund``
:param data: The data dictionary received from the Stripe API.
:type data: dict
:param charge: The charge object that refunds are for.
:type invoice: ``djstripe.models.Refund``
... |
def _adjust_axis(self, axis):
"""Return raw axis/axes corresponding to apparent axis/axes.
This method adjusts user provided 'axis' parameter, for some of the
cube operations, mainly 'margin'. The user never sees the MR selections
dimension, and treats all MRs as single dimensions. Thus... | Return raw axis/axes corresponding to apparent axis/axes.
This method adjusts user provided 'axis' parameter, for some of the
cube operations, mainly 'margin'. The user never sees the MR selections
dimension, and treats all MRs as single dimensions. Thus we need to
adjust the values of ... |
def delta13c_craig(r45sam, r46sam, d13cstd, r45std, r46std,
ks='Craig', d18ostd=23.5):
"""
Algorithm from Craig 1957.
From the original Craig paper, we can set up a pair of equations
and solve for d13C and d18O simultaneously:
d45 * r45 = r13 * d13
+ 0.5 * ... | Algorithm from Craig 1957.
From the original Craig paper, we can set up a pair of equations
and solve for d13C and d18O simultaneously:
d45 * r45 = r13 * d13
+ 0.5 * r17 * d18
d46 = r13 * ((r17**2 + r17 - r18) / a) * d13
+ 1 - 0.5 * r17 * ((r13**2 + r13 - r18) / a... |
def extractDates(inp, tz=None, now=None):
"""Extract semantic date information from an input string.
This is a convenience method which would only be used if
you'd rather not initialize a DateService object.
Args:
inp (str): The input string to be parsed.
tz: An optional Pytz timezone. ... | Extract semantic date information from an input string.
This is a convenience method which would only be used if
you'd rather not initialize a DateService object.
Args:
inp (str): The input string to be parsed.
tz: An optional Pytz timezone. All datetime objects returned will
be... |
def get_context(line, pos):
"""
computes start and end position of substring of line that is the
command string under given position
"""
commands = split_commandline(line) + ['']
i = 0
start = 0
end = len(commands[i])
while pos > end:
i... | computes start and end position of substring of line that is the
command string under given position |
def main():
"""
Starts the Application.
:return: Definition success.
:rtype: bool
"""
components_paths = []
for path in (os.path.join(umbra.__path__[0], Constants.factory_components_directory),
os.path.join(umbra.__path__[0], Constants.factory_addons_components_directory))... | Starts the Application.
:return: Definition success.
:rtype: bool |
def parseAddress(address):
"""
Parse the given RFC 2821 email address into a structured object.
@type address: C{str}
@param address: The address to parse.
@rtype: L{Address}
@raise xmantissa.error.ArgumentError: The given string was not a valid RFC
2821 address.
"""
parts = []
... | Parse the given RFC 2821 email address into a structured object.
@type address: C{str}
@param address: The address to parse.
@rtype: L{Address}
@raise xmantissa.error.ArgumentError: The given string was not a valid RFC
2821 address. |
def loads(string, *transformers, **kwargs):
"""
Deserializes Java objects and primitive data serialized using
ObjectOutputStream from a string.
:param string: A Java data string
:param transformers: Custom transformers to use
:param ignore_remaining_data: If True, don't log an error when unused... | Deserializes Java objects and primitive data serialized using
ObjectOutputStream from a string.
:param string: A Java data string
:param transformers: Custom transformers to use
:param ignore_remaining_data: If True, don't log an error when unused
trailing bytes are re... |
def run(self, scenario):
"""Run the algorithm, utilizing a classifier set to choose the
most appropriate action for each situation produced by the
scenario. Improve the situation/action mapping on each reward
cycle to maximize reward. Return the classifier set that was
created.
... | Run the algorithm, utilizing a classifier set to choose the
most appropriate action for each situation produced by the
scenario. Improve the situation/action mapping on each reward
cycle to maximize reward. Return the classifier set that was
created.
Usage:
scenario ... |
def val_to_mrc(code, val):
"""
Convert one single `val` to MRC.
This function may be used for control fields in MARC records.
Args:,
code (str): Code of the field.
val (str): Value of the field.
Returns:
str: Correctly padded MRC line with field.
"""
code = str(cod... | Convert one single `val` to MRC.
This function may be used for control fields in MARC records.
Args:,
code (str): Code of the field.
val (str): Value of the field.
Returns:
str: Correctly padded MRC line with field. |
def on_ctcp(self, connection, event):
"""Default handler for ctcp events.
Replies to VERSION and PING requests and relays DCC requests
to the on_dccchat method.
"""
nick = event.source.nick
if event.arguments[0] == "VERSION":
connection.ctcp_reply(nick, "VERS... | Default handler for ctcp events.
Replies to VERSION and PING requests and relays DCC requests
to the on_dccchat method. |
def from_name(clz, name):
"""
Instantiates the object from a known name
"""
if isinstance(name, list) and "green" in name:
name = "teal"
assert name in COLOR_NAMES, 'Unknown color name'
r, b, g = COLOR_NAMES[name]
return clz(r, b, g) | Instantiates the object from a known name |
def finalize(self):
"""
Connects the wires.
"""
self._check_finalized()
self._final = True
for dest_w, values in self.dest_instrs_info.items():
mux_vals = dict(zip(self.instructions, values))
dest_w <<= sparse_mux(self.signal_wire, mux_vals) | Connects the wires. |
def profile(event_type, extra_data=None):
"""Profile a span of time so that it appears in the timeline visualization.
Note that this only works in the raylet code path.
This function can be used as follows (both on the driver or within a task).
.. code-block:: python
with ray.profile("custom... | Profile a span of time so that it appears in the timeline visualization.
Note that this only works in the raylet code path.
This function can be used as follows (both on the driver or within a task).
.. code-block:: python
with ray.profile("custom event", extra_data={'key': 'value'}):
... |
def nucmer(args):
"""
%prog nucmer mappings.bed MTR.fasta assembly.fasta chr1 3
Select specific chromosome region based on MTR mapping. The above command
will extract chr1:2,000,001-3,000,000.
"""
p = OptionParser(nucmer.__doc__)
opts, args = p.parse_args(args)
if len(args) != 5:
... | %prog nucmer mappings.bed MTR.fasta assembly.fasta chr1 3
Select specific chromosome region based on MTR mapping. The above command
will extract chr1:2,000,001-3,000,000. |
def p_static_non_empty_array_pair_list_item(p):
'''static_non_empty_array_pair_list : static_non_empty_array_pair_list COMMA static_scalar
| static_scalar'''
if len(p) == 4:
p[0] = p[1] + [ast.ArrayElement(None, p[3], False, lineno=p.lineno(2))]
else:
... | static_non_empty_array_pair_list : static_non_empty_array_pair_list COMMA static_scalar
| static_scalar |
def _process_pathway_disease(self, limit):
"""
We make a link between the pathway identifiers,
and any diseases associated with them.
Since we model diseases as processes, we make a triple saying that
the pathway may be causally upstream of or within the disease process.
... | We make a link between the pathway identifiers,
and any diseases associated with them.
Since we model diseases as processes, we make a triple saying that
the pathway may be causally upstream of or within the disease process.
:param limit:
:return: |
def get_size(self, m):
"""
Return the 2-D size of a Jacobian matrix in tuple
"""
nrow, ncol = 0, 0
if m[0] == 'F':
nrow = self.n
elif m[0] == 'G':
nrow = self.m
if m[1] == 'x':
ncol = self.n
elif m[1] == 'y':
... | Return the 2-D size of a Jacobian matrix in tuple |
def plot_map(fignum, lats, lons, Opts):
"""
makes a cartopy map with lats/lons
Requires installation of cartopy
Parameters:
_______________
fignum : matplotlib figure number
lats : array or list of latitudes
lons : array or list of longitudes
Opts : dictionary of plotting options:
... | makes a cartopy map with lats/lons
Requires installation of cartopy
Parameters:
_______________
fignum : matplotlib figure number
lats : array or list of latitudes
lons : array or list of longitudes
Opts : dictionary of plotting options:
Opts.keys=
proj : projection [su... |
def unset(config, section, opt=None):
"""Unsets specified option and/or section in the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): optional option name.
"""
if section not in config.keys():
... | Unsets specified option and/or section in the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): optional option name. |
def _get_params(self, rdata):
"""
Returns a list of jsonrpc request's method parameters.
"""
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
... | Returns a list of jsonrpc request's method parameters. |
def reset(self):
"""Clear the internal statistics to initial state."""
if getattr(self, 'num', None) is None:
self.num_inst = 0
self.sum_metric = 0.0
else:
self.num_inst = [0] * self.num
self.sum_metric = [0.0] * self.num
self.records = dic... | Clear the internal statistics to initial state. |
def aux_insertTree(childTree, parentTree):
"""This a private (You shouldn't have to call it) recursive function that inserts a child tree into a parent tree."""
if childTree.x1 != None and childTree.x2 != None :
parentTree.insert(childTree.x1, childTree.x2, childTree.name, childTree.referedObject)
for c in childT... | This a private (You shouldn't have to call it) recursive function that inserts a child tree into a parent tree. |
def extract_full_summary_from_signature(operation):
""" Extract the summary from the docstring of the command. """
lines = inspect.getdoc(operation)
regex = r'\s*(:param)\s+(.+?)\s*:(.*)'
summary = ''
if lines:
match = re.search(regex, lines)
summary = lines[:match.regs[0][0]] if mat... | Extract the summary from the docstring of the command. |
def parse_cookie(name, seed, kaka):
"""Parses and verifies a cookie value
:param seed: A seed used for the HMAC signature
:param kaka: The cookie
:return: A tuple consisting of (payload, timestamp)
"""
if not kaka:
return None
cookie_obj = SimpleCookie(kaka)
morsel = cookie_obj... | Parses and verifies a cookie value
:param seed: A seed used for the HMAC signature
:param kaka: The cookie
:return: A tuple consisting of (payload, timestamp) |
def strip(self, text, *args, **kwargs):
"""
Try to maintain parity with what is extracted by extract since strip
will most likely be used in conjunction with extract
"""
if OEMBED_DEFAULT_PARSE_HTML:
extracted = self.extract_oembeds_html(text, *args, **kwargs)
... | Try to maintain parity with what is extracted by extract since strip
will most likely be used in conjunction with extract |
def load_simdata(self, idx: int) -> None:
"""Load the next sim sequence value (of the given index)."""
if self._sim_ramflag:
self.sim[0] = self._sim_array[idx]
elif self._sim_diskflag:
raw = self._sim_file.read(8)
self.sim[0] = struct.unpack('d', raw) | Load the next sim sequence value (of the given index). |
def natural_keys(text: str) -> List[Union[int, str]]:
"""
Sort key function.
Returns text split into string/number parts, for natural sorting; as per
http://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside
Example (as per the source above):
..... | Sort key function.
Returns text split into string/number parts, for natural sorting; as per
http://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside
Example (as per the source above):
.. code-block:: python
>>> from cardinal_pythonlib.sort... |
def Open(self, file_object):
"""Opens the database file object.
Args:
file_object (FileIO): file-like object.
Raises:
IOError: if the SQLite database signature does not match.
OSError: if the SQLite database signature does not match.
ValueError: if the file-like object is invalid.
... | Opens the database file object.
Args:
file_object (FileIO): file-like object.
Raises:
IOError: if the SQLite database signature does not match.
OSError: if the SQLite database signature does not match.
ValueError: if the file-like object is invalid. |
def getMdriztabParameters(files):
""" Gets entry in MDRIZTAB where task parameters live.
This method returns a record array mapping the selected
row.
"""
# Get the MDRIZTAB table file name from the primary header.
# It is gotten from the first file in the input list. No
# consistenc... | Gets entry in MDRIZTAB where task parameters live.
This method returns a record array mapping the selected
row. |
def _markerlib_evaluate(cls, text):
"""
Evaluate a PEP 426 environment marker using markerlib.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid.
"""
from pip._vendor import _markerlib
# markerlib implements ... | Evaluate a PEP 426 environment marker using markerlib.
Return a boolean indicating the marker result in this environment.
Raise SyntaxError if marker is invalid. |
def Nusselt_laminar(Tsat, Tw, rhog, rhol, kl, mul, Hvap, L, angle=90.):
r'''Calculates heat transfer coefficient for laminar film condensation
of a pure chemical on a flat plate, as presented in [1]_ according to an
analysis performed by Nusselt in 1916.
.. math::
h=0.943\left[\frac{g\sin(\thet... | r'''Calculates heat transfer coefficient for laminar film condensation
of a pure chemical on a flat plate, as presented in [1]_ according to an
analysis performed by Nusselt in 1916.
.. math::
h=0.943\left[\frac{g\sin(\theta)\rho_{liq}(\rho_l-\rho_v)k_{l}^3
\Delta H_{vap}}{\mu_l(T_{sat}-T_w... |
def abort_request(self, request):
"""Called to abort request on timeout"""
self.timedout = True
try:
request.cancel()
except error.AlreadyCancelled:
return | Called to abort request on timeout |
def Campbell_Thodos(T, Tb, Tc, Pc, M, dipole=None, hydroxyl=False):
r'''Calculate saturation liquid density using the Campbell-Thodos [1]_
CSP method.
An old and uncommon estimation method.
.. math::
V_s = \frac{RT_c}{P_c}{Z_{RA}}^{[1+(1-T_r)^{2/7}]}
Z_{RA} = \alpha + \beta(1-T_r)
... | r'''Calculate saturation liquid density using the Campbell-Thodos [1]_
CSP method.
An old and uncommon estimation method.
.. math::
V_s = \frac{RT_c}{P_c}{Z_{RA}}^{[1+(1-T_r)^{2/7}]}
Z_{RA} = \alpha + \beta(1-T_r)
\alpha = 0.3883-0.0179s
s = T_{br} \frac{\ln P_c}{(1-T_{b... |
def bytes_cast(maybe_str, encoding='utf-8'):
"""
Converts any string-like input to a bytes-like output, with respect to
python version
Parameters
----------
maybe_str : if this is a string-like object, it will be converted to bytes
encoding : str, default='utf-8'
encoding to be use... | Converts any string-like input to a bytes-like output, with respect to
python version
Parameters
----------
maybe_str : if this is a string-like object, it will be converted to bytes
encoding : str, default='utf-8'
encoding to be used when encoding string |
def description(self):
"""Extract description from a release."""
if self.release.get('body'):
return markdown(self.release['body'])
elif self.repository.get('description'):
return self.repository['description']
return 'No description provided.' | Extract description from a release. |
def add_reply_comment(self, msg_data_id, index, user_comment_id, content):
"""
回复评论
"""
return self._post(
'comment/reply/add',
data={
'msg_data_id': msg_data_id,
'index': index,
'user_comment_id': user_comment_id,
... | 回复评论 |
def _cleanup(self, dry_run=False):
"""
Cleans up (removes) intermediate files.
You can register intermediate files, which will be deleted automatically
when the pipeline completes. This function deletes them,
either absolutely or conditionally. It is run automatically when the
... | Cleans up (removes) intermediate files.
You can register intermediate files, which will be deleted automatically
when the pipeline completes. This function deletes them,
either absolutely or conditionally. It is run automatically when the
pipeline succeeds, so you shouldn't need to call... |
def _delete_duplicates(l, keep_last):
"""Delete duplicates from a sequence, keeping the first or last."""
seen=set()
result=[]
if keep_last: # reverse in & out, then keep first
l.reverse()
for i in l:
try:
if i not in seen:
result.append(i)
... | Delete duplicates from a sequence, keeping the first or last. |
def trigger_event(self, event, *args):
"""Dispatch an event to the proper handler method.
In the most common usage, this method is not overloaded by subclasses,
as it performs the routing of events to methods. However, this
method can be overriden if special dispatching rules are needed... | Dispatch an event to the proper handler method.
In the most common usage, this method is not overloaded by subclasses,
as it performs the routing of events to methods. However, this
method can be overriden if special dispatching rules are needed, or if
having a single method that catche... |
def delete_dev_vlans(vlanid, auth, url, devid=None, devip=None):
"""
function takes devid and vlanid of specific device and 802.1q VLAN tag and issues a RESTFUL
call to remove the specified VLAN from the target device.
:param vlanid:int or str value of target 802.1q VLAN
:param auth: requests auth ... | function takes devid and vlanid of specific device and 802.1q VLAN tag and issues a RESTFUL
call to remove the specified VLAN from the target device.
:param vlanid:int or str value of target 802.1q VLAN
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: bas... |
def _merge_retry_options(retry_options, overrides):
"""Helper for ``construct_settings()``.
Takes two retry options, and merges them into a single RetryOption instance.
Args:
retry_options (RetryOptions): The base RetryOptions.
overrides (RetryOptions): The RetryOptions used for overriding ``r... | Helper for ``construct_settings()``.
Takes two retry options, and merges them into a single RetryOption instance.
Args:
retry_options (RetryOptions): The base RetryOptions.
overrides (RetryOptions): The RetryOptions used for overriding ``retry``.
Use the values if it is not None. If entire... |
def counts_to_dicts(df, column):
"""
convert (values, counts) as returned by aggregate.aggregate_counts() to dicts
makes expand_counts much faster
"""
# index where there are counts and they aren't null
d = df[column].apply(lambda c: pd.notnull(c) and len(c[0]) > 0)
return df.loc[d, column].... | convert (values, counts) as returned by aggregate.aggregate_counts() to dicts
makes expand_counts much faster |
def file_exists_on_unit(self, sentry_unit, file_name):
"""Check if a file exists on a unit."""
try:
sentry_unit.file_stat(file_name)
return True
except IOError:
return False
except Exception as e:
msg = 'Error checking file {}: {}'.format(f... | Check if a file exists on a unit. |
def delete_cli(access_token, project_member_id, base_url=OH_BASE_URL,
file_basename=None, file_id=None, all_files=False):
"""
Command line function for deleting files.
For more information visit
:func:`delete_file<ohapi.api.delete_file>`.
"""
response = delete_file(access_token, p... | Command line function for deleting files.
For more information visit
:func:`delete_file<ohapi.api.delete_file>`. |
def get_objective_requisite_assignment_session_for_objective_bank(self, objective_bank_id, proxy):
"""Gets the ``OsidSession`` associated with the objective sequencing service for the given objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` of the
objective bank
... | Gets the ``OsidSession`` associated with the objective sequencing service for the given objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` of the
objective bank
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveRequisiteAssignmentSession) ... |
def find(self, *args, **kwargs):
"""Same as :meth:`pymongo.collection.Collection.find`, except
it returns the right document class.
"""
return Cursor(self, *args, wrap=self.document_class, **kwargs) | Same as :meth:`pymongo.collection.Collection.find`, except
it returns the right document class. |
async def fetch_transaction(self, request):
"""Fetches a specific transaction from the validator, specified by id.
Request:
path:
- transaction_id: The 128-character id of the txn to be fetched
Response:
data: A JSON object with the data from the expande... | Fetches a specific transaction from the validator, specified by id.
Request:
path:
- transaction_id: The 128-character id of the txn to be fetched
Response:
data: A JSON object with the data from the expanded Transaction
link: The link to this exact ... |
def interval_wait(self):
"""Pauses the correct amount of time according to this
acquisition object's interval setting, and the last time this
function was called"""
# calculate time since last interation and wait to acheive desired interval
now = time.time()
elapsed = (... | Pauses the correct amount of time according to this
acquisition object's interval setting, and the last time this
function was called |
def deliver_hook(instance, target, payload_override=None):
"""
Deliver the payload to the target URL.
By default it serializes to JSON and POSTs.
"""
payload = payload_override or serialize_hook(instance)
if hasattr(settings, 'HOOK_DELIVERER'):
deliverer = get_module(settings.HOOK_DELIV... | Deliver the payload to the target URL.
By default it serializes to JSON and POSTs. |
def decrypt_data(self, name, ciphertext, context="", nonce="", batch_input=None, mount_point=DEFAULT_MOUNT_POINT):
"""Decrypt the provided ciphertext using the named key.
Supported methods:
POST: /{mount_point}/decrypt/{name}. Produces: 200 application/json
:param name: Specifies t... | Decrypt the provided ciphertext using the named key.
Supported methods:
POST: /{mount_point}/decrypt/{name}. Produces: 200 application/json
:param name: Specifies the name of the encryption key to decrypt against. This is specified as part of the URL.
:type name: str | unicode
... |
def load_module(self, fullmodname):
"""
PEP-302-compliant load_module() method.
Args:
fullmodname: The dot-separated full module name, e.g. 'django.core.mail'.
Returns:
The module object constructed from the source code.
Raises:
SyntaxError if the... | PEP-302-compliant load_module() method.
Args:
fullmodname: The dot-separated full module name, e.g. 'django.core.mail'.
Returns:
The module object constructed from the source code.
Raises:
SyntaxError if the module's source code is syntactically incorrect.
... |
def _convert_to_dataset_class(df, dataset_class, expectations_config=None, autoinspect_func=None):
"""
Convert a (pandas) dataframe to a great_expectations dataset, with (optional) expectations_config
"""
if expectations_config is not None:
# Cast the dataframe into the new class, and manually i... | Convert a (pandas) dataframe to a great_expectations dataset, with (optional) expectations_config |
def get_index_declaration_sql(self, name, index):
"""
Obtains DBMS specific SQL code portion needed to set an index
declaration to be used in statements like CREATE TABLE.
:param name: The name of the index.
:type name: str
:param index: The index definition
:ty... | Obtains DBMS specific SQL code portion needed to set an index
declaration to be used in statements like CREATE TABLE.
:param name: The name of the index.
:type name: str
:param index: The index definition
:type index: Index
:return: DBMS specific SQL code portion neede... |
def dot(a, b):
r"""Dot product of two 3d vectors."""
if isinstance(a, Mul):
a = a.expand()
avect = 1
aivect = -1
for ai, fact in enumerate(a.args):
if isinstance(fact, Vector3D):
avect = fact
aivect = ai
break
a... | r"""Dot product of two 3d vectors. |
def get_program_duration(program):
'''
Get a program's duration in seconds
'''
program_start = program.get('start_time')
program_end = program.get('end_time')
if not program_start or not program_end:
_LOGGER.error('Could not determine program start and/or end times.')
_LOGGER.deb... | Get a program's duration in seconds |
def render_image(self, rgbobj, dst_x, dst_y):
"""Render the image represented by (rgbobj) at dst_x, dst_y
in the offscreen pixmap.
"""
self.logger.debug("redraw pixmap=%s" % (self.pixmap))
if self.pixmap is None:
return
self.logger.debug("drawing to pixmap")
... | Render the image represented by (rgbobj) at dst_x, dst_y
in the offscreen pixmap. |
def listen(self, *, host, port, override=False, forever=False, **kwargs):
"""Listen on TCP/IP socket.
Parameters
----------
host: str
Host like '127.0.0.1'
port:
Port like 80.
"""
if override:
argv = dict(enumerate(sys.argv))
... | Listen on TCP/IP socket.
Parameters
----------
host: str
Host like '127.0.0.1'
port:
Port like 80. |
def parser(self):
"Load the configuration file."
if not hasattr(self, '_conf'):
cfile = self.config_file
logger.debug('loading config %s' % cfile)
if os.path.isfile(cfile):
conf = self._create_config_parser()
conf.read(os.path.expanduse... | Load the configuration file. |
def conjugate(self):
"""Quaternion conjugate, encapsulated in a new instance.
For a unit quaternion, this is the same as the inverse.
Returns:
A new Quaternion object clone with its vector part negated
"""
return self.__class__(scalar=self.scalar, vector= -self.vect... | Quaternion conjugate, encapsulated in a new instance.
For a unit quaternion, this is the same as the inverse.
Returns:
A new Quaternion object clone with its vector part negated |
def without_edge(self, edge: Edge) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]':
"""Returns a copy of this bipartite graph with the given edge removed."""
return BipartiteGraph((e2, v) for e2, v in self._edges.items() if edge != e2) | Returns a copy of this bipartite graph with the given edge removed. |
def gpu_iuwt_recomposition(in1, scale_adjust, store_on_gpu, smoothed_array):
"""
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for a GPU.
INPUTS:
in1 (no ... | This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for a GPU.
INPUTS:
in1 (no default): Array containing wavelet coefficients.
scale_adjust (no default): In... |
def block_header_to_hex( block_data, prev_hash ):
"""
Calculate the hex form of a block's header, given its getblock information from bitcoind.
"""
header_info = {
"version": block_data['version'],
"prevhash": prev_hash,
"merkle_root": block_data['merkleroot'],
"timestamp": b... | Calculate the hex form of a block's header, given its getblock information from bitcoind. |
def update_json(self, fields=None):
"""Update the current entity.
Call :meth:`update_raw`. Check the response status code, decode JSON
and return the decoded JSON as a dict.
:param fields: See :meth:`update`.
:return: A dict consisting of the decoded JSON in the server's
... | Update the current entity.
Call :meth:`update_raw`. Check the response status code, decode JSON
and return the decoded JSON as a dict.
:param fields: See :meth:`update`.
:return: A dict consisting of the decoded JSON in the server's
response.
:raises: ``requests.exc... |
def agg_multi_func(values, agg_field, agg_funcs, group_by=None):
"""
Aggregates several functions
:param values: list of objects (dict)
:param agg_field: target field to calculate aggregates
:param agg_funcs: list of aggregate functions
:param group_by: field used to dete... | Aggregates several functions
:param values: list of objects (dict)
:param agg_field: target field to calculate aggregates
:param agg_funcs: list of aggregate functions
:param group_by: field used to determine group
:return: dict {agg_func0: value, agg_func1: agg_value, ...} |
def get(self, filetype, **kwargs):
"""Returns file name, downloading if remote access configured.
Parameters
----------
filetype : str
type of file
keyword arguments :
keywords to fully specify path
Notes
-----
Path templates are... | Returns file name, downloading if remote access configured.
Parameters
----------
filetype : str
type of file
keyword arguments :
keywords to fully specify path
Notes
-----
Path templates are defined in $DIMAGE_DIR/data/dimage_paths.ini |
def upstream_url(self, uri):
"Returns the URL to the upstream data source for the given URI based on configuration"
return self.application.options.upstream + self.request.uri | Returns the URL to the upstream data source for the given URI based on configuration |
def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=''):
"""Generates a help string for the key flags of a given module.
Args:
module: A module object or a module name (a string).
output_lines: A list of strings. The generated help message
lines will be appended to this list.
... | Generates a help string for the key flags of a given module.
Args:
module: A module object or a module name (a string).
output_lines: A list of strings. The generated help message
lines will be appended to this list.
prefix: A string that is prepended to each generated help line. |
def date_in_past(self):
"""Is the block's date in the past?
(Has it not yet happened?)
"""
now = datetime.datetime.now()
return (now.date() > self.date) | Is the block's date in the past?
(Has it not yet happened?) |
def get_season(self, season_key, card_type="micro_card"):
"""
Calling Season API.
Arg:
season_key: key of the season
card_type: optional, default to micro_card. Accepted values are
micro_card & summary_card
Return:
json data
"""
... | Calling Season API.
Arg:
season_key: key of the season
card_type: optional, default to micro_card. Accepted values are
micro_card & summary_card
Return:
json data |
def config_examples(dest, user_dir):
""" Copy the example workflows to a directory.
\b
DEST: Path to which the examples should be copied.
"""
examples_path = Path(lightflow.__file__).parents[1] / 'examples'
if examples_path.exists():
dest_path = Path(dest).resolve()
if not user_... | Copy the example workflows to a directory.
\b
DEST: Path to which the examples should be copied. |
def num_features_model(m:nn.Module)->int:
"Return the number of output features for `model`."
sz = 64
while True:
try: return model_sizes(m, size=(sz,sz))[-1][1]
except Exception as e:
sz *= 2
if sz > 2048: raise | Return the number of output features for `model`. |
def delete_secret(self, path, mount_point=DEFAULT_MOUNT_POINT):
"""Delete the secret at the specified location.
Supported methods:
DELETE: /{mount_point}/{path}. Produces: 204 (empty body)
:param path: Specifies the path of the secret to delete.
This is specified as pa... | Delete the secret at the specified location.
Supported methods:
DELETE: /{mount_point}/{path}. Produces: 204 (empty body)
:param path: Specifies the path of the secret to delete.
This is specified as part of the URL.
:type path: str | unicode
:param mount_point... |
def parse_row(self):
"""
Parses a row, cell-by-cell, returning a dict of field names
to the cleaned field values.
"""
fields = self.mapping
for i, cell in enumerate(self.row[0:len(fields)]):
field_name, field_type = fields[str(i)]
parsed_cell = sel... | Parses a row, cell-by-cell, returning a dict of field names
to the cleaned field values. |
def checkedItems(self, column=0, parent=None, recurse=True):
"""
Returns a list of the checked items for this tree widget based on
the inputed column and parent information.
:param column | <int>
parent | <QtGui.QTreeWidget> || None
... | Returns a list of the checked items for this tree widget based on
the inputed column and parent information.
:param column | <int>
parent | <QtGui.QTreeWidget> || None
recurse | <bool>
:return [<QtGui.QTreeWidgetItem>, .... |
def read_reg_file(f, foff=0x2D):
"""
Given a file handle for an old-style Agilent *.REG file, this
will parse that file into a dictonary of key/value pairs
(including any tables that are in the *.REG file, which will
be parsed into lists of lists).
"""
# convenience function for reading in d... | Given a file handle for an old-style Agilent *.REG file, this
will parse that file into a dictonary of key/value pairs
(including any tables that are in the *.REG file, which will
be parsed into lists of lists). |
def load_rules(self, force_reload=False, overwrite=True):
"""Load rules from policy file or cache."""
# double-checked locking
if self.load_once and self._policy_loaded:
return
with self._load_lock:
if self.load_once and self._policy_loaded:
retur... | Load rules from policy file or cache. |
def parsed_whois(self, query, **kwargs):
"""Pass in a domain name"""
return self._results('parsed-whois', '/v1/{0}/whois/parsed'.format(query), cls=ParsedWhois, **kwargs) | Pass in a domain name |
def rebind_invalidated_ars(portal):
"""Rebind the ARs automatically generated because of the retraction of their
parent to the new field 'Invalidated'. The field used until now
'ParentAnalysisRequest' will be used for partitioning
"""
logger.info("Rebinding retracted/invalidated ARs")
# Walk th... | Rebind the ARs automatically generated because of the retraction of their
parent to the new field 'Invalidated'. The field used until now
'ParentAnalysisRequest' will be used for partitioning |
def find_duplicate_keys(data):
"""
Find duplicate keys in a layer of ordered pairs. Intended as the object_pairs_hook callable
for json.load or loads.
:param data: ordered pairs
:return: Dictionary with no duplicate keys
:raises ValueError if duplicate keys are found
"""
out_dict = {}
... | Find duplicate keys in a layer of ordered pairs. Intended as the object_pairs_hook callable
for json.load or loads.
:param data: ordered pairs
:return: Dictionary with no duplicate keys
:raises ValueError if duplicate keys are found |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.