code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _requires_submission(self):
"""
Returns True if the time since the last submission is greater than the submission interval.
If no submissions have ever been made, check if the database last modified time is greater than the
submission interval.
"""
if self.dbcon_part ... | Returns True if the time since the last submission is greater than the submission interval.
If no submissions have ever been made, check if the database last modified time is greater than the
submission interval. |
def name(self):
"""Dict with locale codes as keys and localized name as value"""
# pylint:disable=E1101
return next((self.names.get(x) for x in self._locales if x in
self.names), None) | Dict with locale codes as keys and localized name as value |
def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0):
'''
Receive a stream via the XMODEM protocol.
>>> stream = file('/etc/issue', 'wb')
>>> print modem.recv(stream)
2342
Returns the number of bytes received on success or ``None`` in c... | Receive a stream via the XMODEM protocol.
>>> stream = file('/etc/issue', 'wb')
>>> print modem.recv(stream)
2342
Returns the number of bytes received on success or ``None`` in case of
failure. |
def from_enum(gtype, enum_value):
"""Turn an int back into an enum string.
"""
pointer = vips_lib.vips_enum_nick(gtype, enum_value)
if pointer == ffi.NULL:
raise Error('value not in enum')
return _to_string(pointer) | Turn an int back into an enum string. |
def colorscale(mag, cmin, cmax):
"""
Return a tuple of floats between 0 and 1 for R, G, and B.
From Python Cookbook (9.11?)
"""
# Normalize to 0-1
try:
x = float(mag-cmin)/(cmax-cmin)
except ZeroDivisionError:
x = 0.5 # cmax == cmin
blue = min((max((4*(0.75-x), 0.)), 1.)... | Return a tuple of floats between 0 and 1 for R, G, and B.
From Python Cookbook (9.11?) |
def update_variables(func):
"""
Use this decorator on Step.action implementation.
Your action method should always return variables, or
both variables and output.
This decorator will update variables with output.
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
result = f... | Use this decorator on Step.action implementation.
Your action method should always return variables, or
both variables and output.
This decorator will update variables with output. |
def info(dev):
'''
Extract all info delivered by udevadm
CLI Example:
.. code-block:: bash
salt '*' udev.info /dev/sda
salt '*' udev.info /sys/class/net/eth0
'''
if 'sys' in dev:
qtype = 'path'
else:
qtype = 'name'
cmd = 'udevadm info --export --query=... | Extract all info delivered by udevadm
CLI Example:
.. code-block:: bash
salt '*' udev.info /dev/sda
salt '*' udev.info /sys/class/net/eth0 |
def neighbor_add(self, address, remote_as,
remote_port=DEFAULT_BGP_PORT,
enable_ipv4=DEFAULT_CAP_MBGP_IPV4,
enable_ipv6=DEFAULT_CAP_MBGP_IPV6,
enable_vpnv4=DEFAULT_CAP_MBGP_VPNV4,
enable_vpnv6=DEFAULT_CAP_MBGP_VPNV6... | This method registers a new neighbor. The BGP speaker tries to
establish a bgp session with the peer (accepts a connection
from the peer and also tries to connect to it).
``address`` specifies the IP address of the peer. It must be
the string representation of an IP address. Only IPv4 i... |
def set_attributes(self, **kwargs):
"""
Set a group of attributes (parameters and members). Calls
`setp` directly, so kwargs can include more than just the
parameter value (e.g., bounds, free, etc.).
"""
kwargs = dict(kwargs)
for name,value in kwargs.items():
... | Set a group of attributes (parameters and members). Calls
`setp` directly, so kwargs can include more than just the
parameter value (e.g., bounds, free, etc.). |
def get_groups_of_account_apikey(self, account_id, api_key, **kwargs): # noqa: E501
"""Get groups of the API key. # noqa: E501
An endpoint for retrieving groups of the API key. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/api-keys/{apiKey}/groups -H 'Authoriz... | Get groups of the API key. # noqa: E501
An endpoint for retrieving groups of the API key. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/api-keys/{apiKey}/groups -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method makes a synchronous HTTP request by de... |
def __parse_aliases_line(self, raw_alias, raw_username):
"""Parse aliases lines"""
alias = self.__encode(raw_alias)
username = self.__encode(raw_username)
return alias, username | Parse aliases lines |
def calc_piece_size(size, min_piece_size=20, max_piece_size=29, max_piece_count=1000):
"""
Calculates a good piece size for a size
"""
logger.debug('Calculating piece size for %i' % size)
for i in range(min_piece_size, max_piece_size): # 20 = 1MB
if size / (2**i) < max_piece_count:
... | Calculates a good piece size for a size |
def _lscmp(a, b):
''' Compares two strings in a cryptographically save way:
Runtime is not affected by length of common prefix. '''
return not sum(0 if x==y else 1 for x, y in zip(a, b)) and len(a) == len(b) | Compares two strings in a cryptographically save way:
Runtime is not affected by length of common prefix. |
def _sam_to_grouped_umi_cl(data, umi_consensus, tx_out_file):
"""Mark duplicates on aligner output and convert to grouped UMIs by position.
Works with either a separate umi_file or UMI embedded in the read names.
"""
tmp_file = "%s-sorttmp" % utils.splitext_plus(tx_out_file)[0]
jvm_opts = _get_fgbi... | Mark duplicates on aligner output and convert to grouped UMIs by position.
Works with either a separate umi_file or UMI embedded in the read names. |
def do_reparse(self, arg):
"""Reparses the currently active unit test to get the latest test results loaded
to the console.
"""
#We just get the full path of the currently active test and hit reparse.
full = arg == "full"
from os import path
fullpath = path.abspat... | Reparses the currently active unit test to get the latest test results loaded
to the console. |
def quote(key, value):
"""Certain options support string values. We want clients to be able to pass Python strings in
but we need them to be quoted in the output. Unfortunately some of those options also allow
numbers so we type check the value before wrapping it in quotes.
"""
if key in quoted_opt... | Certain options support string values. We want clients to be able to pass Python strings in
but we need them to be quoted in the output. Unfortunately some of those options also allow
numbers so we type check the value before wrapping it in quotes. |
def com_google_fonts_check_smart_dropout(ttFont):
"""Font enables smart dropout control in "prep" table instructions?
B8 01 FF PUSHW 0x01FF
85 SCANCTRL (unconditinally turn on
dropout control mode)
B0 04 PUSHB 0x04
8D SCANTYPE (enable smart dropout control)
... | Font enables smart dropout control in "prep" table instructions?
B8 01 FF PUSHW 0x01FF
85 SCANCTRL (unconditinally turn on
dropout control mode)
B0 04 PUSHB 0x04
8D SCANTYPE (enable smart dropout control)
Smart dropout control means activating rules 1, 2 an... |
def login(self, username, password, mode="demo"):
"""login function"""
url = "https://trading212.com/it/login"
try:
logger.debug(f"visiting %s" % url)
self.browser.visit(url)
logger.debug(f"connected to %s" % url)
except selenium.common.exceptions.WebD... | login function |
def maxdiff_dtu_configurations(list_of_objects):
"""Return DtuConfiguration instance with maximum differences.
Parameters
----------
list_of_objects : python list
List of DtuConfiguration instances to be averaged.
Returns
-------
result : DtuConfiguration instance
Object wi... | Return DtuConfiguration instance with maximum differences.
Parameters
----------
list_of_objects : python list
List of DtuConfiguration instances to be averaged.
Returns
-------
result : DtuConfiguration instance
Object with averaged values. |
def _generate_sdss_object_name(
self):
"""
*generate sdss object names for the results*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
"""
self.log.info('starting the ``_generate_sdss_object_name`` method')
con... | *generate sdss object names for the results*
**Key Arguments:**
# -
**Return:**
- None
.. todo:: |
def remove(self, observableElement):
"""
remove an obsrvable element
:param str observableElement: the name of the observable element
"""
if observableElement in self._observables:
self._observables.remove(observableElement) | remove an obsrvable element
:param str observableElement: the name of the observable element |
def location_from_dictionary(d):
"""
Builds a *Location* object out of a data dictionary. Only certain
properties of the dictionary are used: if these properties are not
found or cannot be read, an error is issued.
:param d: a data dictionary
:type d: dict
:returns: a *Location* instance
... | Builds a *Location* object out of a data dictionary. Only certain
properties of the dictionary are used: if these properties are not
found or cannot be read, an error is issued.
:param d: a data dictionary
:type d: dict
:returns: a *Location* instance
:raises: *KeyError* if it is impossible to ... |
def from_csv(cls, filename: str):
"""
Imports PDEntries from a csv.
Args:
filename: Filename to import from.
Returns:
List of Elements, List of PDEntries
"""
with open(filename, "r", encoding="utf-8") as f:
reader = csv.reader(f, deli... | Imports PDEntries from a csv.
Args:
filename: Filename to import from.
Returns:
List of Elements, List of PDEntries |
def connect(self, ip_address, tsap_snap7, tsap_logo, tcpport=102):
"""
Connect to a Siemens LOGO server. Howto setup Logo communication configuration see: http://snap7.sourceforge.net/logo.html
:param ip_address: IP ip_address of server
:param tsap_snap7: TSAP SNAP7 Client (e.g. 10.00 =... | Connect to a Siemens LOGO server. Howto setup Logo communication configuration see: http://snap7.sourceforge.net/logo.html
:param ip_address: IP ip_address of server
:param tsap_snap7: TSAP SNAP7 Client (e.g. 10.00 = 0x1000)
:param tsap_logo: TSAP Logo Server (e.g. 20.00 = 0x2000) |
def http_responder_factory(proto):
"""
The default factory function which creates a GrowlerHTTPResponder with
this object as the parent protocol, and the application's req/res
factory functions.
To change the default responder, overload this method with the same
to retur... | The default factory function which creates a GrowlerHTTPResponder with
this object as the parent protocol, and the application's req/res
factory functions.
To change the default responder, overload this method with the same
to return your
own responder.
Params
-... |
def segments_distance(segment1, segment2):
"""Calculate the distance between two line segments in the plane.
>>> a = LineSegment(Point(1,0), Point(2,0))
>>> b = LineSegment(Point(0,1), Point(0,2))
>>> "%0.2f" % segments_distance(a, b)
'1.41'
>>> c = LineSegment(Point(0,0), Point(5,5))
>>> d... | Calculate the distance between two line segments in the plane.
>>> a = LineSegment(Point(1,0), Point(2,0))
>>> b = LineSegment(Point(0,1), Point(0,2))
>>> "%0.2f" % segments_distance(a, b)
'1.41'
>>> c = LineSegment(Point(0,0), Point(5,5))
>>> d = LineSegment(Point(2,2), Point(4,4))
>>> e =... |
def ip_to_array(ipaddress):
"""Convert a string representing an IPv4 address to 4 bytes."""
res = []
for i in ipaddress.split("."):
res.append(int(i))
assert len(res) == 4
return res | Convert a string representing an IPv4 address to 4 bytes. |
def remove_internal_names(self):
"""
Set the name of all non-leaf nodes in the subtree to None.
"""
self.visit(lambda n: setattr(n, 'name', None), lambda n: not n.is_leaf) | Set the name of all non-leaf nodes in the subtree to None. |
def _convert_to(maybe_device, convert_to):
'''
Convert a device name, UUID or LABEL to a device name, UUID or
LABEL.
Return the fs_spec required for fstab.
'''
# Fast path. If we already have the information required, we can
# save one blkid call
if not convert_to or \
(convert... | Convert a device name, UUID or LABEL to a device name, UUID or
LABEL.
Return the fs_spec required for fstab. |
def pull_log_dump(self, project_name, logstore_name, from_time, to_time, file_path, batch_size=None,
compress=None, encodings=None, shard_list=None, no_escape=None):
""" dump all logs seperatedly line into file_path, file_path, the time parameters are log received time on server side.
... | dump all logs seperatedly line into file_path, file_path, the time parameters are log received time on server side.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
:param logstore_name: the logstore name
:type from_time: str... |
def get_sensor_code_by_number(si, mtype, sensor_number, quiet=False):
"""
Given a sensor number, get the full sensor code (e.g. ACCX-UB1-L2C-M)
:param si: dict, sensor index json dictionary
:param mtype: str, sensor type
:param sensor_number: int, number of sensor
:param quiet: bool, if true th... | Given a sensor number, get the full sensor code (e.g. ACCX-UB1-L2C-M)
:param si: dict, sensor index json dictionary
:param mtype: str, sensor type
:param sensor_number: int, number of sensor
:param quiet: bool, if true then return None if not found
:return: str or None, sensor_code: a sensor code (... |
def item_enclosure_length(self, item):
"""
Try to obtain the size of the enclosure if it's present on the FS,
otherwise returns an hardcoded value.
Note: this method is only called if item_enclosure_url
has returned something.
"""
try:
return str(item.... | Try to obtain the size of the enclosure if it's present on the FS,
otherwise returns an hardcoded value.
Note: this method is only called if item_enclosure_url
has returned something. |
def find_users(session, *usernames):
"""Find multiple users by name."""
user_string = ','.join(usernames)
return _make_request(session, FIND_USERS_URL, user_string) | Find multiple users by name. |
def sos_get_command_output(command, timeout=300, stderr=False,
chroot=None, chdir=None, env=None,
binary=False, sizelimit=None, poller=None):
"""Execute a command and return a dictionary of status and output,
optionally changing root or current working direc... | Execute a command and return a dictionary of status and output,
optionally changing root or current working directory before
executing command. |
def create_volume(self, volume, size, **kwargs):
"""Create a volume and return a dictionary describing it.
:param volume: Name of the volume to be created.
:type volume: str
:param size: Size in bytes, or string representing the size of the
volume to be created.
... | Create a volume and return a dictionary describing it.
:param volume: Name of the volume to be created.
:type volume: str
:param size: Size in bytes, or string representing the size of the
volume to be created.
:type size: int or str
:param \*\*kwargs: See t... |
def _send_resource(self, environ, start_response, is_head_method):
"""
If-Range
If the entity is unchanged, send me the part(s) that I am missing;
otherwise, send me the entire new entity
If-Range: "737060cd8c284d8af7ad3082f209582d"
@see: http://www.w3.org/Pr... | If-Range
If the entity is unchanged, send me the part(s) that I am missing;
otherwise, send me the entire new entity
If-Range: "737060cd8c284d8af7ad3082f209582d"
@see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.27 |
def can_rename(self):
# type: (LocalSourcePaths) -> bool
"""Check if source can be renamed
:param LocalSourcePath self: this
:rtype: bool
:return: if rename possible
"""
return len(self._paths) == 1 and (
self._paths[0].is_file() or
blobxfe... | Check if source can be renamed
:param LocalSourcePath self: this
:rtype: bool
:return: if rename possible |
def set_frame_parameters(self, profile_index: int, frame_parameters) -> None:
"""Set the frame parameters with the settings index and fire the frame parameters changed event.
If the settings index matches the current settings index, call set current frame parameters.
If the settings index matc... | Set the frame parameters with the settings index and fire the frame parameters changed event.
If the settings index matches the current settings index, call set current frame parameters.
If the settings index matches the record settings index, call set record frame parameters. |
def _cleanup_workflow(config, task_id, args, **kwargs):
""" Cleanup the results of a workflow when it finished.
Connects to the postrun signal of Celery. If the signal was sent by a workflow,
remove the result from the result backend.
Args:
task_id (str): The id of the task.
args (tupl... | Cleanup the results of a workflow when it finished.
Connects to the postrun signal of Celery. If the signal was sent by a workflow,
remove the result from the result backend.
Args:
task_id (str): The id of the task.
args (tuple): The arguments the task was started with.
**kwargs: K... |
def to_(self, data_pts):
"""Reverse of :meth:`from_`."""
data_pts = np.asarray(data_pts, dtype=np.float)
has_z = (data_pts.shape[-1] > 2)
if self.use_center:
data_pts = data_pts - self.viewer.data_off
# subtract data indexes at center reference pixel
ref_pt ... | Reverse of :meth:`from_`. |
def info(self, exp_path=False, project_path=False, global_path=False,
config_path=False, complete=False, no_fix=False,
on_projects=False, on_globals=False, projectname=None,
return_dict=False, insert_id=True, only_keys=False,
archives=False, **kwargs):
"""
... | Print information on the experiments
Parameters
----------
exp_path: bool
If True/set, print the filename of the experiment configuration
project_path: bool
If True/set, print the filename on the project configuration
global_path: bool
If True... |
def squared_toroidal_dist(p1, p2, world_size=(60, 60)):
"""
Separated out because sqrt has a lot of overhead
"""
halfx = world_size[0]/2.0
if world_size[0] == world_size[1]:
halfy = halfx
else:
halfy = world_size[1]/2.0
deltax = p1[0] - p2[0]
if deltax < -halfx:
... | Separated out because sqrt has a lot of overhead |
def _make_sprite_image(images, save_path):
"""Given an NDArray as a batch images, make a sprite image out of it following the rule
defined in
https://www.tensorflow.org/programmers_guide/embedding
and save it in sprite.png under the path provided by the user."""
if isinstance(images, np.ndarray):
... | Given an NDArray as a batch images, make a sprite image out of it following the rule
defined in
https://www.tensorflow.org/programmers_guide/embedding
and save it in sprite.png under the path provided by the user. |
def phase_fraction(im, normed=True):
r"""
Calculates the number (or fraction) of each phase in an image
Parameters
----------
im : ND-array
An ND-array containing integer values
normed : Boolean
If ``True`` (default) the returned values are normalized by the total
number... | r"""
Calculates the number (or fraction) of each phase in an image
Parameters
----------
im : ND-array
An ND-array containing integer values
normed : Boolean
If ``True`` (default) the returned values are normalized by the total
number of voxels in image, otherwise the voxel ... |
def calc_route_info(self, real_time=True, stop_at_bounds=False, time_delta=0):
"""Calculate best route info."""
route = self.get_route(1, time_delta)
results = route['results']
route_time, route_distance = self._add_up_route(results, real_time=real_time, stop_at_bounds=stop_at_bounds)
... | Calculate best route info. |
def listdir(self, path='.'):
"""
Gets an list of the contents of path in (s)FTP
"""
self._connect()
if self.sftp:
contents = self._sftp_listdir(path)
else:
contents = self._ftp_listdir(path)
self._close()
return contents | Gets an list of the contents of path in (s)FTP |
def exclude(self, *args, **kwargs):
"""
Works just like the default Manager's :func:`exclude` method, but
you can pass an additional keyword argument named ``path`` specifying
the full **path of the folder whose immediate child objects** you
want to exclude, e.g. ``"path/to/folde... | Works just like the default Manager's :func:`exclude` method, but
you can pass an additional keyword argument named ``path`` specifying
the full **path of the folder whose immediate child objects** you
want to exclude, e.g. ``"path/to/folder"``. |
def get_kafka_brokers():
"""
Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects.
"""
# NOTE: The Kafka environment variables need to be present. If using
# Apache Kafka on Heroku, they will be available in your app configuration.
if not os.... | Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects. |
def create_from_fits(cls, fitsfile, norm_type='eflux',
hdu_scan="SCANDATA",
hdu_energies="EBOUNDS",
irow=None):
"""Create a CastroData object from a tscube FITS file.
Parameters
----------
fitsfile : str
... | Create a CastroData object from a tscube FITS file.
Parameters
----------
fitsfile : str
Name of the fits file
norm_type : str
Type of normalization to use. Valid options are:
* norm : Normalization w.r.t. to test source
* flux : Flux ... |
def __upload(self, resource, bytes):
"""Performs a single chunk upload."""
# note: string conversion required here due to open encoding bug in requests-oauthlib.
headers = {
'x-ton-expires': http_time(self.options.get('x-ton-expires', self._DEFAULT_EXPIRE)),
'content-len... | Performs a single chunk upload. |
def start (self):
'''
Starts (Subscribes) the client.
'''
self.sub = rospy.Subscriber(self.topic, ImageROS, self.__callback) | Starts (Subscribes) the client. |
def restore_repository_from_recycle_bin(self, repository_details, project, repository_id):
"""RestoreRepositoryFromRecycleBin.
[Preview API] Recover a soft-deleted Git repository. Recently deleted repositories go into a soft-delete state for a period of time before they are hard deleted and become unrec... | RestoreRepositoryFromRecycleBin.
[Preview API] Recover a soft-deleted Git repository. Recently deleted repositories go into a soft-delete state for a period of time before they are hard deleted and become unrecoverable.
:param :class:`<GitRecycleBinRepositoryDetails> <azure.devops.v5_1.git.models.GitRec... |
def get(cls, resource_id=None, parent_id=None, grandparent_id=None):
"""Retrieves the required resources.
:param resource_id: The identifier for the specific resource
within the resource type.
:param parent_id: The identifier for the specific ancesto... | Retrieves the required resources.
:param resource_id: The identifier for the specific resource
within the resource type.
:param parent_id: The identifier for the specific ancestor
resource within the resource type.
:p... |
def sendstop(self):
'''
Kill process (:meth:`subprocess.Popen.terminate`).
Do not wait for command to complete.
:rtype: self
'''
if not self.is_started:
raise EasyProcessError(self, 'process was not started!')
log.debug('stopping process (pid=%s cmd=... | Kill process (:meth:`subprocess.Popen.terminate`).
Do not wait for command to complete.
:rtype: self |
def unmarshal(self, value, bind_client=None):
"""
Cast the specified value to the entity type.
"""
#self.log.debug("Unmarshall {0!r}: {1!r}".format(self, value))
if not isinstance(value, self.type):
o = self.type()
if bind_client is not None and hasattr(o.... | Cast the specified value to the entity type. |
def create(self, ospf_process_id, vrf=None):
"""Creates a OSPF process in the specified VRF or the default VRF.
Args:
ospf_process_id (str): The OSPF process Id value
vrf (str): The VRF to apply this OSPF process to
Returns:
bool: True if th... | Creates a OSPF process in the specified VRF or the default VRF.
Args:
ospf_process_id (str): The OSPF process Id value
vrf (str): The VRF to apply this OSPF process to
Returns:
bool: True if the command completed successfully
Exception:
... |
def propose_value(self, value, assume_leader=False):
"""
Proposes a value to the network.
"""
if value is None:
raise ValueError("Not allowed to propose value None")
paxos = self.paxos_instance
paxos.leader = assume_leader
msg = paxos.propose_value(val... | Proposes a value to the network. |
def move(self, remote_path_from, remote_path_to, overwrite=False):
"""Moves resource from one place to another on WebDAV server.
More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_MOVE
:param remote_path_from: the path to resource which will be moved,
:par... | Moves resource from one place to another on WebDAV server.
More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_MOVE
:param remote_path_from: the path to resource which will be moved,
:param remote_path_to: the path where resource will be moved.
:param overw... |
def _get_config(self, path=None):
"""
Get the config.
:rtype: dict
"""
if not path and not self.option("config"):
raise Exception("The --config|-c option is missing.")
if not path:
path = self.option("config")
filename, ext = os.path.spl... | Get the config.
:rtype: dict |
def data(self, name, chunk, body):
"""
Issue a DATA command
return None
Sends a chunk of data to a peer.
"""
self.callRemote(Data, name=name, chunk=chunk, body=body) | Issue a DATA command
return None
Sends a chunk of data to a peer. |
def evaluate_report(report):
"""Iterate over validation errors."""
if report["valid"]:
return
for warn in report["warnings"]:
LOGGER.warning(warn)
# We only ever test one table at a time.
for err in report["tables"][0]["errors"]:
LOGGER.error(e... | Iterate over validation errors. |
def add_generator_action(self, action):
"""
Attach/add one :class:`GeneratorAction`.
Warning:
The order in which you add :class:`GeneratorAction` objects **is** important in case of conflicting :class:`GeneratorAction` objects:
**only** the **first compatible** :class:`G... | Attach/add one :class:`GeneratorAction`.
Warning:
The order in which you add :class:`GeneratorAction` objects **is** important in case of conflicting :class:`GeneratorAction` objects:
**only** the **first compatible** :class:`GeneratorAction` object will be used to generate the (source ... |
def add_command_line_options(cls, parser):
"""function to inject command line parameters"""
if "add_argument" in dir(parser):
return cls.add_command_line_options_argparse(parser)
else:
return cls.add_command_line_options_optparse(parser) | function to inject command line parameters |
def add_color(self, name, model, description):
r"""Add a color that can be used throughout the document.
Args
----
name: str
Name to set for the color
model: str
The color model to use when defining the color
description: str
The value... | r"""Add a color that can be used throughout the document.
Args
----
name: str
Name to set for the color
model: str
The color model to use when defining the color
description: str
The values to use to define the color |
def dump_table_as_insert_sql(engine: Engine,
table_name: str,
fileobj: TextIO,
wheredict: Dict[str, Any] = None,
include_ddl: bool = False,
multirow: bool = False) -> None:
... | Reads a table from the database, and writes SQL to replicate the table's
data to the output ``fileobj``.
Args:
engine: SQLAlchemy :class:`Engine`
table_name: name of the table
fileobj: file-like object to write to
wheredict: optional dictionary of ``{column_name: value}`` to use... |
def imread(files, **kwargs):
"""Return image data from TIFF file(s) as numpy array.
Refer to the TiffFile and TiffSequence classes and their asarray
functions for documentation.
Parameters
----------
files : str, binary stream, or sequence
File name, seekable binary stream, glob patte... | Return image data from TIFF file(s) as numpy array.
Refer to the TiffFile and TiffSequence classes and their asarray
functions for documentation.
Parameters
----------
files : str, binary stream, or sequence
File name, seekable binary stream, glob pattern, or sequence of
file name... |
def save(self, filepath=None, filename=None, mode="md"):
"""保存答案为 Html 文档或 markdown 文档.
:param str filepath: 要保存的文件所在的目录,
不填为当前目录下以专栏标题命名的目录, 设为"."则为当前目录。
:param str filename: 要保存的文件名,
不填则默认为 所在文章标题 - 作者名.html/md。
如果文件已存在,自动在后面加上数字区分。
**自定义文件名时请不要... | 保存答案为 Html 文档或 markdown 文档.
:param str filepath: 要保存的文件所在的目录,
不填为当前目录下以专栏标题命名的目录, 设为"."则为当前目录。
:param str filename: 要保存的文件名,
不填则默认为 所在文章标题 - 作者名.html/md。
如果文件已存在,自动在后面加上数字区分。
**自定义文件名时请不要输入后缀 .html 或 .md。**
:param str mode: 保存类型,可选 `html` 、 `markd... |
def send_reminder(self, user, sender=None, **kwargs):
"""Sends a reminder email to the specified user"""
if user.is_active:
return False
token = RegistrationTokenGenerator().make_token(user)
kwargs.update({"token": token})
self.email_message(
user, self.re... | Sends a reminder email to the specified user |
def nmb_weights_hidden(self) -> int:
"""Number of hidden weights.
>>> from hydpy import ANN
>>> ann = ANN(None)
>>> ann(nmb_inputs=2, nmb_neurons=(4, 3, 2), nmb_outputs=3)
>>> ann.nmb_weights_hidden
18
"""
nmb = 0
for idx_layer in range(self.nmb_l... | Number of hidden weights.
>>> from hydpy import ANN
>>> ann = ANN(None)
>>> ann(nmb_inputs=2, nmb_neurons=(4, 3, 2), nmb_outputs=3)
>>> ann.nmb_weights_hidden
18 |
def phot(fits_filename, x_in, y_in, aperture=15, sky=20, swidth=10, apcor=0.3,
maxcount=30000.0, exptime=1.0, zmag=None, extno=0, centroid=True):
"""
Compute the centroids and magnitudes of a bunch sources on fits image.
:rtype : astropy.table.Table
:param fits_filename: Name of fits image to... | Compute the centroids and magnitudes of a bunch sources on fits image.
:rtype : astropy.table.Table
:param fits_filename: Name of fits image to measure source photometry on.
:type fits_filename: str
:param x_in: x location of source to measure
:type x_in: float, numpy.array
:param y_in: y loca... |
def state(self, state):
"""Set the current build state and record the time to maintain history.
Note! This is different from the dataset state. Setting the build set is commiteed to the
progress table/database immediately. The dstate is also set, but is not committed until the
bundle is... | Set the current build state and record the time to maintain history.
Note! This is different from the dataset state. Setting the build set is commiteed to the
progress table/database immediately. The dstate is also set, but is not committed until the
bundle is committed. So, the dstate changes ... |
def fingerprint(
self,
phrase,
phonetic_algorithm=double_metaphone,
joiner=' ',
*args,
**kwargs
):
"""Return the phonetic fingerprint of a phrase.
Parameters
----------
phrase : str
The string from which to calculate the ph... | Return the phonetic fingerprint of a phrase.
Parameters
----------
phrase : str
The string from which to calculate the phonetic fingerprint
phonetic_algorithm : function
A phonetic algorithm that takes a string and returns a string
(presumably a phone... |
def get_settings_from_client(client):
"""Pull out settings from a SoftLayer.BaseClient instance.
:param client: SoftLayer.BaseClient instance
"""
settings = {
'username': '',
'api_key': '',
'timeout': '',
'endpoint_url': '',
}
try:
settings['username'] = ... | Pull out settings from a SoftLayer.BaseClient instance.
:param client: SoftLayer.BaseClient instance |
def extended_key_usage(self):
"""The :py:class:`~django_ca.extensions.ExtendedKeyUsage` extension, or ``None`` if it doesn't
exist."""
try:
ext = self.x509.extensions.get_extension_for_oid(ExtensionOID.EXTENDED_KEY_USAGE)
except x509.ExtensionNotFound:
return None... | The :py:class:`~django_ca.extensions.ExtendedKeyUsage` extension, or ``None`` if it doesn't
exist. |
def add_status_code(code):
"""用于将mprpc的标准异常注册到`_mprpc_exceptions`的装饰器.
Parameters:
code (int): - 标准状态码
Return:
(Callable): - 装饰函数
"""
def class_decorator(cls):
"""内部装饰函数,用于将异常类注册到对应的状态码.
Parameters:
cls (Callable): - 要注册的异常类
Return:
... | 用于将mprpc的标准异常注册到`_mprpc_exceptions`的装饰器.
Parameters:
code (int): - 标准状态码
Return:
(Callable): - 装饰函数 |
def set_system_time(self, time_source, ntp_server, date_format,
time_format, time_zone, is_dst, dst, year,
mon, day, hour, minute, sec, callback=None):
'''
Set systeim time
'''
if ntp_server not in ['time.nist.gov',
... | Set systeim time |
def get_command(self, ctx: click.Context, name: str) -> click.Command:
"""Return the relevant command given the context and name.
.. warning::
This differs substaintially from Flask in that it allows
for the inbuilt commands to be overridden.
"""
info = ctx.ensu... | Return the relevant command given the context and name.
.. warning::
This differs substaintially from Flask in that it allows
for the inbuilt commands to be overridden. |
def pressure_tendency(code: str, unit: str = 'mb') -> str:
"""
Translates a 5-digit pressure outlook code
Ex: 50123 -> 12.3 mb: Increasing, then decreasing
"""
width, precision = int(code[2:4]), code[4]
return ('3-hour pressure difference: +/- '
f'{width}.{precision} {unit} - {PRESS... | Translates a 5-digit pressure outlook code
Ex: 50123 -> 12.3 mb: Increasing, then decreasing |
def _mod_run_check(cmd_kwargs, onlyif, unless):
'''
Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True
'''
if onlyif:
if __salt__['cmd.retcode'](onlyif, **cmd_kwargs) != 0:
retu... | Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True |
def run_to_selected_state(self, path, state_machine_id=None):
"""Execute the state machine until a specific state. This state won't be executed. This is an asynchronous task
"""
if self.state_machine_manager.get_active_state_machine() is not None:
self.state_machine_manager.get_activ... | Execute the state machine until a specific state. This state won't be executed. This is an asynchronous task |
def op_canonicalize(op_name, parsed_op):
"""
Get the canonical representation of a parsed operation's data.
Meant for backwards-compatibility
"""
global CANONICALIZE_METHODS
if op_name not in CANONICALIZE_METHODS:
# no canonicalization needed
return parsed_op
else:
r... | Get the canonical representation of a parsed operation's data.
Meant for backwards-compatibility |
def process_constraints(self, inequalities=None, equalities=None,
momentinequalities=None, momentequalities=None,
block_index=0, removeequalities=False):
"""Process the constraints and generate localizing matrices. Useful
only if the moment matrix ... | Process the constraints and generate localizing matrices. Useful
only if the moment matrix already exists. Call it if you want to
replace your constraints. The number of the respective types of
constraints and the maximum degree of each constraint must remain the
same.
:param in... |
def dispatch(self, event: Event) -> Iterator[Any]:
"""
Yields handlers matching the routing of the incoming :class:`slack.events.Event`.
Args:
event: :class:`slack.events.Event`
Yields:
handler
"""
LOG.debug('Dispatching event "%s"', event.get("t... | Yields handlers matching the routing of the incoming :class:`slack.events.Event`.
Args:
event: :class:`slack.events.Event`
Yields:
handler |
def remove_cons_vars_from_problem(model, what):
"""Remove variables and constraints from a Model's solver object.
Useful to temporarily remove variables and constraints from a Models's
solver object.
Parameters
----------
model : a cobra model
The model from which to remove the variable... | Remove variables and constraints from a Model's solver object.
Useful to temporarily remove variables and constraints from a Models's
solver object.
Parameters
----------
model : a cobra model
The model from which to remove the variables and constraints.
what : list or tuple of optlang ... |
def get_url(params):
"""Return external URL for warming up a given chart/table cache."""
baseurl = 'http://{SUPERSET_WEBSERVER_ADDRESS}:{SUPERSET_WEBSERVER_PORT}/'.format(
**app.config)
with app.test_request_context():
return urllib.parse.urljoin(
baseurl,
url_for('Su... | Return external URL for warming up a given chart/table cache. |
def p_instanceDeclaration(p):
# pylint: disable=line-too-long
"""instanceDeclaration : INSTANCE OF className '{' valueInitializerList '}' ';'
| INSTANCE OF className alias '{' valueInitializerList '}' ';'
| qualifierList INSTANCE OF className '{' valueInitia... | instanceDeclaration : INSTANCE OF className '{' valueInitializerList '}' ';'
| INSTANCE OF className alias '{' valueInitializerList '}' ';'
| qualifierList INSTANCE OF className '{' valueInitializerList '}' ';'
| qualifierList INSTANCE OF ... |
def _parse_octet(self, octet_str):
"""Convert a decimal octet into an integer.
Args:
octet_str: A string, the number to parse.
Returns:
The octet as an integer.
Raises:
ValueError: if the octet isn't strictly a decimal from [0..255].
"""
... | Convert a decimal octet into an integer.
Args:
octet_str: A string, the number to parse.
Returns:
The octet as an integer.
Raises:
ValueError: if the octet isn't strictly a decimal from [0..255]. |
def _build_integer_type(var, property_path=None):
""" Builds schema definitions for integer type values.
:param var: The integer type value
:param List[str] property_path: The property path of the current type,
defaults to None, optional
:param property_path: [type], optional
:return: The b... | Builds schema definitions for integer type values.
:param var: The integer type value
:param List[str] property_path: The property path of the current type,
defaults to None, optional
:param property_path: [type], optional
:return: The built schema definition
:rtype: Dict[str, Any] |
def preprocess_worksheet(self, table, worksheet):
'''
Performs a preprocess pass of the table to attempt naive conversions of data and to record
the initial types of each cell.
'''
table_conversion = []
flags = {}
units = {}
for rind, row in enumerate(tabl... | Performs a preprocess pass of the table to attempt naive conversions of data and to record
the initial types of each cell. |
def do_usufy(self, query, **kwargs):
"""
Verifying a usufy query in this platform.
This might be redefined in any class inheriting from Platform.
Args:
-----
query: The element to be searched.
Return:
-------
A list of elements to be app... | Verifying a usufy query in this platform.
This might be redefined in any class inheriting from Platform.
Args:
-----
query: The element to be searched.
Return:
-------
A list of elements to be appended. |
def get_data_pct(self, xpct, ypct):
"""Calculate new data size for the given axis ratios.
See :meth:`get_limits`.
Parameters
----------
xpct, ypct : float
Ratio for X and Y, respectively, where 1 is 100%.
Returns
-------
x, y : int
... | Calculate new data size for the given axis ratios.
See :meth:`get_limits`.
Parameters
----------
xpct, ypct : float
Ratio for X and Y, respectively, where 1 is 100%.
Returns
-------
x, y : int
Scaled dimensions. |
def retry(num_attempts=3, exception_class=Exception, log=None, sleeptime=1):
"""
>>> def fail():
... runs[0] += 1
... raise ValueError()
>>> runs = [0]; retry(sleeptime=0)(fail)()
Traceback (most recent call last):
...
ValueError
>>> runs
[3]
>>> runs = [0]; retry(2, ... | >>> def fail():
... runs[0] += 1
... raise ValueError()
>>> runs = [0]; retry(sleeptime=0)(fail)()
Traceback (most recent call last):
...
ValueError
>>> runs
[3]
>>> runs = [0]; retry(2, sleeptime=0)(fail)()
Traceback (most recent call last):
...
ValueError
>>... |
def make_file_object_logger(fh):
"""
Make a logger that logs to the given file object.
"""
def logger_func(stmt, args, fh=fh):
"""
A logger that logs everything sent to a file object.
"""
now = datetime.datetime.now()
six.print_("Executing (%s):" % now.isoformat()... | Make a logger that logs to the given file object. |
def nd_load_and_stats(filenames, base_path=BASEPATH):
"""
Load multiple files from disk and generate stats
Passes the list of files assuming the ding0 data structure as default in
:code:`~/.ding0`.
Data will be concatenated and key indicators for each grid district are
returned in table and gra... | Load multiple files from disk and generate stats
Passes the list of files assuming the ding0 data structure as default in
:code:`~/.ding0`.
Data will be concatenated and key indicators for each grid district are
returned in table and graphic format.
Parameters
----------
filenames : list o... |
def _within_box(points, boxes):
"""Validate which keypoints are contained inside a given box.
points: NxKx2
boxes: Nx4
output: NxK
"""
x_within = (points[..., 0] >= boxes[:, 0, None]) & (
points[..., 0] <= boxes[:, 2, None]
)
y_within = (points[..., 1] >= boxes[:, 1, None]) & (
... | Validate which keypoints are contained inside a given box.
points: NxKx2
boxes: Nx4
output: NxK |
def get_nameserver_detail_output_show_nameserver_nameserver_ag_base_device(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_nameserver_detail = ET.Element("get_nameserver_detail")
config = get_nameserver_detail
output = ET.SubElement(get_names... | Auto Generated Code |
def function_exclusion_filter_builder(func: Strings) -> NodePredicate:
"""Build a filter that fails on nodes of the given function(s).
:param func: A BEL Function or list/set/tuple of BEL functions
"""
if isinstance(func, str):
def function_exclusion_filter(_: BELGraph, node: BaseEntity) -> boo... | Build a filter that fails on nodes of the given function(s).
:param func: A BEL Function or list/set/tuple of BEL functions |
def explore(args):
"""Create mapping of sequences of two clusters
"""
logger.info("reading sequeces")
data = load_data(args.json)
logger.info("get sequences from json")
#get_sequences_from_cluster()
c1, c2 = args.names.split(",")
seqs, names = get_sequences_from_cluster(c1, c2, data[0])
... | Create mapping of sequences of two clusters |
def analyze(self, text):
"""
Runs a line of text through MeCab, and returns the results as a
list of lists ("records") that contain the MeCab analysis of each
word.
"""
try:
self.process # make sure things are loaded
text = render_safe(text).repla... | Runs a line of text through MeCab, and returns the results as a
list of lists ("records") that contain the MeCab analysis of each
word. |
async def expand_all_quays(self) -> None:
"""Find all quays from stop places."""
if not self.stops:
return
headers = {'ET-Client-Name': self._client_name}
request = {
'query': GRAPHQL_STOP_TO_QUAY_TEMPLATE,
'variables': {
'stops': self... | Find all quays from stop places. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.