code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def crs(self): # type: () -> CRS
"""Raster crs."""
if self._crs is None:
self._populate_from_rasterio_object(read_image=False)
return self._crs | Raster crs. |
def add_predicate(self, predicate):
"""
Add a new predicate callback to this handler.
"""
_predicate = predicate
if isinstance(predicate, partial):
_predicate = 'partial(%s, %s, %s)' % (predicate.func, predicate.args, predicate.keywords)
if LOG_OPTS['register'... | Add a new predicate callback to this handler. |
def Authenticate(self, app_id, challenge_data,
print_callback=sys.stderr.write):
"""See base class."""
# If authenticator is not plugged in, prompt
try:
device = u2f.GetLocalU2FInterface(origin=self.origin)
except errors.NoDeviceFoundError:
print_callback('Please insert yo... | See base class. |
def resolve_doc(cls, manifest, target_doc_name, target_doc_package,
current_project, node_package):
"""Resolve the given documentation. This follows the same algorithm as
resolve_ref except the is_enabled checks are unnecessary as docs are
always enabled.
"""
... | Resolve the given documentation. This follows the same algorithm as
resolve_ref except the is_enabled checks are unnecessary as docs are
always enabled. |
def PSWAP(angle, q1, q2):
"""Produces a parameterized SWAP gate::
PSWAP(phi) = [[1, 0, 0, 0],
[0, 0, exp(1j * phi), 0],
[0, exp(1j * phi), 0, 0],
[0, 0, 0, 1]]
:pa... | Produces a parameterized SWAP gate::
PSWAP(phi) = [[1, 0, 0, 0],
[0, 0, exp(1j * phi), 0],
[0, exp(1j * phi), 0, 0],
[0, 0, 0, 1]]
:param angle: The angle of the phase... |
def __parse_arguments(self, *args):
"""Parse command line arguments"""
params = self.parser.parse_args(args)
uuid = params.uuid
kw = {}
if params.name:
kw['name'] = params.name
if params.email:
kw['email'] = params.email
if params.gende... | Parse command line arguments |
def put(self, path, payload=None, headers=None):
"""HTTP PUT operation.
:param path: URI Path
:param payload: HTTP Body
:param headers: HTTP Headers
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a con... | HTTP PUT operation.
:param path: URI Path
:param payload: HTTP Body
:param headers: HTTP Headers
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:return: Response |
def write(self, string):
"""Erase newline from a string and write to the logger."""
string = string.rstrip()
if string: # Don't log empty lines
self.logger.critical(string) | Erase newline from a string and write to the logger. |
def client(self, name):
""" Returns the :class:`~plexapi.client.PlexClient` that matches the specified name.
Parameters:
name (str): Name of the client to return.
Raises:
:class:`plexapi.exceptions.NotFound`: Unknown client name
"""
for c... | Returns the :class:`~plexapi.client.PlexClient` that matches the specified name.
Parameters:
name (str): Name of the client to return.
Raises:
:class:`plexapi.exceptions.NotFound`: Unknown client name |
def compile_create(self, blueprint, command, _):
"""
Compile a create table command.
"""
columns = ", ".join(self._get_columns(blueprint))
return "CREATE TABLE %s (%s)" % (self.wrap_table(blueprint), columns) | Compile a create table command. |
def add(places, name, cmd, args, env=None, uid=None, gid=None, extras=None,
env_inherit=None):
"""Add a process.
:param places: a Places instance
:param name: string, the logical name of the process
:param cmd: string, executable
:param args: list of strings, command-line arguments
:par... | Add a process.
:param places: a Places instance
:param name: string, the logical name of the process
:param cmd: string, executable
:param args: list of strings, command-line arguments
:param env: dictionary mapping strings to strings
(will be environment in subprocess)
:param uid: int... |
def on_separate_dimensions(self):
"""
Checks whether the kernels in the combination act on disjoint subsets
of dimensions. Currently, it is hard to asses whether two slice objects
will overlap, so this will always return False.
:return: Boolean indicator.
"""
if n... | Checks whether the kernels in the combination act on disjoint subsets
of dimensions. Currently, it is hard to asses whether two slice objects
will overlap, so this will always return False.
:return: Boolean indicator. |
def __init(self):
""" initializes the service """
params = {
"f" : "json",
}
json_dict = self._get(self._url, params,
securityHandler=self._securityHandler,
proxy_port=self._proxy_port,
... | initializes the service |
def update_firmware(self, file_url, component_type):
"""Updates the given firmware on the server for the given component.
:param file_url: location of the raw firmware file. Extraction of the
firmware file (if in compact format) is expected to
happen pr... | Updates the given firmware on the server for the given component.
:param file_url: location of the raw firmware file. Extraction of the
firmware file (if in compact format) is expected to
happen prior to this invocation.
:param component_type: Type of c... |
async def handle_jobs(job_handler, host, port, *, loop):
"""
Connects to the remote master and continuously receives calls, executes
them, then returns a response until interrupted.
"""
try:
try:
reader, writer = await asyncio.open_connection(host, port, loop=loop)
exce... | Connects to the remote master and continuously receives calls, executes
them, then returns a response until interrupted. |
def delete_snapshot(self, snapshot_id):
"""Remove a previously created snapshot."""
query = self.query_factory(
action="DeleteSnapshot", creds=self.creds, endpoint=self.endpoint,
other_params={"SnapshotId": snapshot_id})
d = query.submit()
return d.addCallback(sel... | Remove a previously created snapshot. |
def get_vmpolicy_macaddr_input_last_rcvd_instance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vmpolicy_macaddr = ET.Element("get_vmpolicy_macaddr")
config = get_vmpolicy_macaddr
input = ET.SubElement(get_vmpolicy_macaddr, "input")
... | Auto Generated Code |
def _check_zone(self, name, create=False):
'''Checks whether a zone specified in a source exist in Azure server.
Note that Azure zones omit end '.' eg: contoso.com vs contoso.com.
Returns the name if it exists.
:param name: Name of a zone to checks
:type name: ... | Checks whether a zone specified in a source exist in Azure server.
Note that Azure zones omit end '.' eg: contoso.com vs contoso.com.
Returns the name if it exists.
:param name: Name of a zone to checks
:type name: str
:param create: If True, creates the zo... |
def find_nested_meta_first(d, prop_name, version):
"""Returns obj. for badgerfish and val for hbf. Appropriate for nested literals"""
if _is_badgerfish_version(version):
return find_nested_meta_first_bf(d, prop_name)
p = '^' + prop_name
return d.get(p) | Returns obj. for badgerfish and val for hbf. Appropriate for nested literals |
def strip_qos_cntrl(self, idx, prot_type):
"""strip(2 byte) wlan.qos
:idx: int
:prot_type: string
802.11 protocol type(.11ac, .11a, .11n, etc)
:return: int
number of processed bytes
:return: int
qos priority
:return: int
qos... | strip(2 byte) wlan.qos
:idx: int
:prot_type: string
802.11 protocol type(.11ac, .11a, .11n, etc)
:return: int
number of processed bytes
:return: int
qos priority
:return: int
qos bit
:return: int
qos acknowledgem... |
def Robbins(L, G, rhol, rhog, mul, H=1.0, Fpd=24.0):
r'''Calculates pressure drop across a packed column, using the Robbins
equation.
Pressure drop is given by:
.. math::
\Delta P = C_3 G_f^2 10^{C_4L_f}+0.4[L_f/20000]^{0.1}[C_3G_f^210^{C_4L_f}]^4
.. math::
G_f=G[0.075/\rho_g]^{0.... | r'''Calculates pressure drop across a packed column, using the Robbins
equation.
Pressure drop is given by:
.. math::
\Delta P = C_3 G_f^2 10^{C_4L_f}+0.4[L_f/20000]^{0.1}[C_3G_f^210^{C_4L_f}]^4
.. math::
G_f=G[0.075/\rho_g]^{0.5}[F_{pd}/20]^{0.5}=986F_s[F_{pd}/20]^{0.5}
.. math:... |
def locale(self):
'''
Do a lookup for the locale code that is set for this layout.
NOTE: USB HID specifies only 35 different locales. If your layout does not fit, it should be set to Undefined/0
@return: Tuple (<USB HID locale code>, <name>)
'''
name = self.json_data['h... | Do a lookup for the locale code that is set for this layout.
NOTE: USB HID specifies only 35 different locales. If your layout does not fit, it should be set to Undefined/0
@return: Tuple (<USB HID locale code>, <name>) |
def mro_resolve(name, bases, dict):
"""
Given a tuple of baseclasses and a dictionary that takes precedence
over any value in the bases, finds a value with the specified *name*
and returns it. Raises #KeyError if the value can not be found.
"""
if name in dict:
return dict[name]
for base in bases:
... | Given a tuple of baseclasses and a dictionary that takes precedence
over any value in the bases, finds a value with the specified *name*
and returns it. Raises #KeyError if the value can not be found. |
def DumpDirHashToStringIO(directory, stringio, base='', exclude=None, include=None):
'''
Helper to iterate over the files in a directory putting those in the passed StringIO in ini
format.
:param unicode directory:
The directory for which the hash should be done.
:param StringIO stringio:
... | Helper to iterate over the files in a directory putting those in the passed StringIO in ini
format.
:param unicode directory:
The directory for which the hash should be done.
:param StringIO stringio:
The string to which the dump should be put.
:param unicode base:
If provided... |
def getTemplates(self, workitems, template_folder=None,
template_names=None, keep=False, encoding="UTF-8"):
"""Get templates from a group of to-be-copied :class:`Workitems` and
write them to files named after the names in `template_names`
respectively.
:param workit... | Get templates from a group of to-be-copied :class:`Workitems` and
write them to files named after the names in `template_names`
respectively.
:param workitems: a :class:`list`/:class:`tuple`/:class:`set`
contains the ids (integer or equivalent string) of some
to-be-copie... |
def restore(self, url, tags=None):
"""
Full restore of a container backup. This restore method will recreate
an exact copy of the backedup container (including same network setup, and other
configurations as defined by the `create` method.
To just restore the container data, and... | Full restore of a container backup. This restore method will recreate
an exact copy of the backedup container (including same network setup, and other
configurations as defined by the `create` method.
To just restore the container data, and use new configuration, use the create method instead
... |
def group_by_allele(self, locus):
'''
Split the PileupCollection by the alleles suggested by the reads at the
specified locus.
If a read has an insertion immediately following the locus, then the
insertion is included in the allele. For example, if locus is the
1-base ra... | Split the PileupCollection by the alleles suggested by the reads at the
specified locus.
If a read has an insertion immediately following the locus, then the
insertion is included in the allele. For example, if locus is the
1-base range [5,6), one allele might be "AGA", indicating that ... |
def package_info(cls, package):
""" All package info for given package """
if package not in cls.package_info_cache:
package_json_url = 'https://pypi.python.org/pypi/%s/json' % package
try:
logging.getLogger('requests').setLevel(logging.WARN)
res... | All package info for given package |
def edited_channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None,
state=None, run_task=None, **kwargs):
"""
Decorator for edited channel post handler
:param commands: list of commands
:param regexp: REGEXP
... | Decorator for edited channel post handler
:param commands: list of commands
:param regexp: REGEXP
:param content_types: List of content types.
:param custom_filters: list of custom filters
:param state:
:param run_task: run callback in task (no wait results)
:par... |
def _FlushExportBuffer(self, output_module, deduplicate_events=True):
"""Flushes buffered events and writes them to the output module.
Args:
output_module (OutputModule): output module.
deduplicate_events (Optional[bool]): True if events should be
deduplicated.
"""
last_macb_group... | Flushes buffered events and writes them to the output module.
Args:
output_module (OutputModule): output module.
deduplicate_events (Optional[bool]): True if events should be
deduplicated. |
def init_discrete_hmm_spectral(C_full, nstates, reversible=True, stationary=True, active_set=None, P=None,
eps_A=None, eps_B=None, separate=None):
"""Initializes discrete HMM using spectral clustering of observation counts
Initializes HMM as described in [1]_. First estimates a M... | Initializes discrete HMM using spectral clustering of observation counts
Initializes HMM as described in [1]_. First estimates a Markov state model
on the given observations, then uses PCCA+ to coarse-grain the transition
matrix [2]_ which initializes the HMM transition matrix. The HMM output
probabili... |
def hset(self, hashroot, key, value):
""" hashed set """
hroot = self.root / hashroot
if not hroot.is_dir():
hroot.mkdir()
hfile = hroot / gethashfile(key)
d = self.get(hfile, {})
d.update( {key : value})
self[hfile] = d | hashed set |
def _security_auth_headers(self, username, password, headers):
"""
Add in the requisite HTTP Authentication Headers
:param username: Riak Security Username
:type str
:param password: Riak Security Password
:type str
:param headers: Dictionary of headers
:... | Add in the requisite HTTP Authentication Headers
:param username: Riak Security Username
:type str
:param password: Riak Security Password
:type str
:param headers: Dictionary of headers
:type dict |
def unwrap(self, value, session=None):
''' Unwrap value using the unwrap function from ``EnumField.item_type``.
Since unwrap validation could not happen in is_valid_wrap, it
happens in this function.'''
self.validate_unwrap(value)
value = self.item_type.unwrap(value, sess... | Unwrap value using the unwrap function from ``EnumField.item_type``.
Since unwrap validation could not happen in is_valid_wrap, it
happens in this function. |
def write_file(writer, filename):
"""Write all of lines from file using the writer."""
for line in txt_line_iterator(filename):
writer.write(line)
writer.write("\n") | Write all of lines from file using the writer. |
def get_deadline_metadata(self):
"""Gets the metadata for the assessment deadline.
return: (osid.Metadata) - metadata for the end time
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceForm.get_group_metadata_t... | Gets the metadata for the assessment deadline.
return: (osid.Metadata) - metadata for the end time
*compliance: mandatory -- This method must be implemented.* |
def scalarDecorator(func):
"""Decorator to return scalar outputs as a set"""
@wraps(func)
def scalar_wrapper(*args,**kwargs):
if nu.array(args[0]).shape == ():
scalarOut= True
newargs= ()
for ii in range(len(args)):
newargs= newargs+(nu.array([args... | Decorator to return scalar outputs as a set |
def generate_dataset_shelve(filename, number_items=1000):
"""
Generate a dataset with number_items elements.
"""
if os.path.exists(filename):
os.remove(filename)
data = shelve.open(filename)
names = get_names()
totalnames = len(names)
#init random seeder
random.seed()
#ca... | Generate a dataset with number_items elements. |
def entropy_from_samples(samples, vec):
"""
Estimate H(x|s) ~= -E_{x \sim P(x|s)}[\log Q(x|s)], where x are samples, and Q is parameterized by vec.
"""
samples_cat = tf.argmax(samples[:, :NUM_CLASS], axis=1, output_type=tf.int32)
samples_uniform = samples[:, NUM_CLASS:]
cat, uniform = get_distri... | Estimate H(x|s) ~= -E_{x \sim P(x|s)}[\log Q(x|s)], where x are samples, and Q is parameterized by vec. |
def status(config):
"""time series lastest record time by account."""
with open(config) as fh:
config = yaml.safe_load(fh.read())
jsonschema.validate(config, CONFIG_SCHEMA)
last_index = get_incremental_starts(config, None)
accounts = {}
for (a, region), last in last_index.items():
... | time series lastest record time by account. |
def unit(self, expression, default=None):
"""Returns the unit (an astropy.unit.Units object) for the expression.
Example
>>> import vaex
>>> ds = vaex.example()
>>> df.unit("x")
Unit("kpc")
>>> df.unit("x*L")
Unit("km kpc2 / s")
:param expressi... | Returns the unit (an astropy.unit.Units object) for the expression.
Example
>>> import vaex
>>> ds = vaex.example()
>>> df.unit("x")
Unit("kpc")
>>> df.unit("x*L")
Unit("km kpc2 / s")
:param expression: Expression, which can be a column name
:p... |
def send_group_text(self, sender, receiver, content):
"""
发送群聊文本消息
:param sender: 发送人
:param receiver: 会话 ID
:param content: 消息内容
:return: 返回的 JSON 数据包
"""
return self.send_text(sender, 'group', receiver, content) | 发送群聊文本消息
:param sender: 发送人
:param receiver: 会话 ID
:param content: 消息内容
:return: 返回的 JSON 数据包 |
def _report_disabled_command_usage(self, *args, message_to_print: str, **kwargs) -> None:
"""
Report when a disabled command has been run or had help called on it
:param args: not used
:param message_to_print: the message reporting that the command is disabled
:param kwargs: not ... | Report when a disabled command has been run or had help called on it
:param args: not used
:param message_to_print: the message reporting that the command is disabled
:param kwargs: not used |
def unlist(ctx, unlist_account, account):
""" Remove an account from any list
"""
account = Account(account, blockchain_instance=ctx.blockchain)
print_tx(account.nolist(unlist_account)) | Remove an account from any list |
def generator(
worker_id,
sleep=lambda x: time.sleep(x/1000.0),
now=lambda: int(time.time()*1000)):
"""
worker_id: a unique for your *entire* environment number between 0 and 255
to identify this generator.
sleep(n): function to pause this worker for n milliseconds. ... | worker_id: a unique for your *entire* environment number between 0 and 255
to identify this generator.
sleep(n): function to pause this worker for n milliseconds. you usually
want to supply a custom method for this in asynchronous
processes.
now(): function to... |
def bind(self, source, dest, destmeth):
"""Guild compatible version of :py:meth:`connect`.
This allows Pyctools compound components to be used in `Guild
<https://github.com/sparkslabs/guild>`_ pipelines.
"""
self.connect(source, getattr(dest, destmeth)) | Guild compatible version of :py:meth:`connect`.
This allows Pyctools compound components to be used in `Guild
<https://github.com/sparkslabs/guild>`_ pipelines. |
def revoke(self):
"""LeaseRevoke revokes a lease.
All keys attached to the lease will expire and be deleted.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the respon... | LeaseRevoke revokes a lease.
All keys attached to the lease will expire and be deleted.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return: |
def gmap(google_api_key, map_options, **kwargs):
''' Create a new :class:`~bokeh.plotting.gmap.GMap` for plotting.
Args:
google_api_key (str):
Google requires an API key be supplied for maps to function. See:
https://developers.google.com/maps/documentation/javascript/get-api-k... | Create a new :class:`~bokeh.plotting.gmap.GMap` for plotting.
Args:
google_api_key (str):
Google requires an API key be supplied for maps to function. See:
https://developers.google.com/maps/documentation/javascript/get-api-key
map_options: (GMapOptions)
Config... |
def _assemble_complex(stmt):
"""Assemble Complex statements into text."""
member_strs = [_assemble_agent_str(m) for m in stmt.members]
stmt_str = member_strs[0] + ' binds ' + _join_list(member_strs[1:])
return _make_sentence(stmt_str) | Assemble Complex statements into text. |
def process_user(self, user: types.User):
"""
Generate user data
:param user:
:return:
"""
if not user:
return
yield 'user_id', user.id
if self.include_content:
yield 'user_full_name', user.full_name
if user.username:
... | Generate user data
:param user:
:return: |
def create_asset_model(self, project, releasetype):
"""Create and return a new tree model that represents assets til descriptors
The tree will include assettypes, assets, tasks and descriptors of the given releaetype.
:param releasetype: the releasetype for the model
:type releasetype:... | Create and return a new tree model that represents assets til descriptors
The tree will include assettypes, assets, tasks and descriptors of the given releaetype.
:param releasetype: the releasetype for the model
:type releasetype: :data:`djadapter.RELEASETYPES`
:param project: the pro... |
def wrap_iter_with_message_events(
request_or_response_iter,
span,
message_event_type
):
"""Wraps a request or response iterator to add message events to the span
for each proto message sent or received
"""
for message_id, message in enumerate(request_or_response_iter, start=1):
add_... | Wraps a request or response iterator to add message events to the span
for each proto message sent or received |
def use_federated_vault_view(self):
"""Pass through to provider AuthorizationLookupSession.use_federated_vault_view"""
self._vault_view = FEDERATED
# self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked
for session in self._get_provider_session... | Pass through to provider AuthorizationLookupSession.use_federated_vault_view |
def is_abstract(self) -> bool:
"""
Whether or not the class-under-construction was declared as abstract (**NOTE:**
this property is usable even *before* the :class:`MetaOptionsFactory` has run)
"""
meta_value = getattr(self.clsdict.get('Meta'), 'abstract', False)
return s... | Whether or not the class-under-construction was declared as abstract (**NOTE:**
this property is usable even *before* the :class:`MetaOptionsFactory` has run) |
def remove(self, force=False):
"""
Remove the plugin from the server.
Args:
force (bool): Remove even if the plugin is enabled.
Default: False
Raises:
:py:class:`docker.errors.APIError`
If the server re... | Remove the plugin from the server.
Args:
force (bool): Remove even if the plugin is enabled.
Default: False
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error. |
def evaluate_at_x(self, arg, def_val=0):
"""
Returns Y value at arg of self. Arg can be a scalar,
but also might be np.array or other iterable
(like list). If domain of self is not wide enough to
interpolate the value of Y, method will return
def_val for those arguments i... | Returns Y value at arg of self. Arg can be a scalar,
but also might be np.array or other iterable
(like list). If domain of self is not wide enough to
interpolate the value of Y, method will return
def_val for those arguments instead.
Check the interpolation when arg in domain o... |
def get_data(self, name):
r"""
Get the data associated with a node.
:param name: Node name
:type name: :ref:`NodeName`
:rtype: any type or list of objects of any type
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[na... | r"""
Get the data associated with a node.
:param name: Node name
:type name: :ref:`NodeName`
:rtype: any type or list of objects of any type
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree) |
def _add_conversion(self, plugin, pbt):
"""Add a new PluginBlockType conversion.
If the plugin already exists, do nothing.
"""
assert self.shape == pbt.shape
assert len(self.inserts) == len(pbt.inserts)
for (i, o) in zip(self.inserts, pbt.inserts):
assert i.... | Add a new PluginBlockType conversion.
If the plugin already exists, do nothing. |
def clean(self, settings):
"""
Filter given settings to keep only key names available in
``DEFAULT_SETTINGS``.
Args:
settings (dict): Loaded settings.
Returns:
dict: Settings object filtered.
"""
return {k: v for k, v in settings.items()... | Filter given settings to keep only key names available in
``DEFAULT_SETTINGS``.
Args:
settings (dict): Loaded settings.
Returns:
dict: Settings object filtered. |
def get_image(self):
"""
Gets first image from post set.
"""
posts_with_images = self.post_set.filter(image__gt='')
if posts_with_images:
return posts_with_images[0].image | Gets first image from post set. |
def body_encode(body, maxlinelen=76, eol=NL):
"""Encode with quoted-printable, wrapping at maxlinelen characters.
Each line of encoded text will end with eol, which defaults to "\\n". Set
this to "\\r\\n" if you will be using the result of this function directly
in an email.
Each line will be wra... | Encode with quoted-printable, wrapping at maxlinelen characters.
Each line of encoded text will end with eol, which defaults to "\\n". Set
this to "\\r\\n" if you will be using the result of this function directly
in an email.
Each line will be wrapped at, at most, maxlinelen characters before the
... |
def set(self, key, value):
"""Set a value at key and return a Future.
:rtype: tornado.concurrent.Future
"""
value_encoded = encode(value, self.get_change_trigger(key))
if key in self.data and self.data[key] == value_encoded:
return self
self.data[key] = val... | Set a value at key and return a Future.
:rtype: tornado.concurrent.Future |
def get_currency(currency_str):
"""
Convert an identifier for a currency into a currency object.
Parameters
----------
currency_str : str
Returns
-------
currency : Currency
"""
path = 'units/currencies.csv' # always use slash in Python packages
filepath = pkg_resources.re... | Convert an identifier for a currency into a currency object.
Parameters
----------
currency_str : str
Returns
-------
currency : Currency |
def set_default(self, channels=None):
'''Setting default voltage
'''
if not channels:
channels = self._ch_cal.keys()
for channel in channels:
self.set_voltage(channel, self._ch_cal[channel]['default'], unit='V') | Setting default voltage |
def resize(self, size, interp='bilinear'):
"""Resize the image.
Parameters
----------
size : int, float, or tuple
* int - Percentage of current size.
* float - Fraction of current size.
* tuple - Size of the output image.
interp : :obj:`str... | Resize the image.
Parameters
----------
size : int, float, or tuple
* int - Percentage of current size.
* float - Fraction of current size.
* tuple - Size of the output image.
interp : :obj:`str`, optional
Interpolation to use for re-si... |
def get_cluster_custom_object_status(self, group, version, plural, name, **kwargs): # noqa: E501
"""get_cluster_custom_object_status # noqa: E501
read status of the specified cluster scoped custom object # noqa: E501
This method makes a synchronous HTTP request by default. To make an
... | get_cluster_custom_object_status # noqa: E501
read status of the specified cluster scoped custom object # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_cluster_custom_object_sta... |
def list_groups(self, filtr, url_prefix, auth, session, send_opts):
"""Get the groups the logged in user is a member of.
Optionally filter by 'member' or 'maintainer'.
Args:
filtr (string|None): ['member'|'maintainer'] or defaults to None.
url_prefix (string): Protocol ... | Get the groups the logged in user is a member of.
Optionally filter by 'member' or 'maintainer'.
Args:
filtr (string|None): ['member'|'maintainer'] or defaults to None.
url_prefix (string): Protocol + host such as https://api.theboss.io
auth (string): Token to send ... |
def url_decode(s, charset='utf-8', decode_keys=False, include_empty=True,
errors='replace', separator='&', cls=None):
"""Parse a querystring and return it as :class:`MultiDict`. Per default
only values are decoded into unicode strings. If `decode_keys` is set to
`True` the same will happen ... | Parse a querystring and return it as :class:`MultiDict`. Per default
only values are decoded into unicode strings. If `decode_keys` is set to
`True` the same will happen for keys.
Per default a missing value for a key will default to an empty key. If
you don't want that behavior you can set `include... |
def _names_to_bytes(names):
"""Reproducibly converts an iterable of strings to bytes
:param iter[str] names: An iterable of strings
:rtype: bytes
"""
names = sorted(names)
names_bytes = json.dumps(names).encode('utf8')
return names_bytes | Reproducibly converts an iterable of strings to bytes
:param iter[str] names: An iterable of strings
:rtype: bytes |
def request(
self, method, url, timeout=None,
headers=None, data=None, params=None
):
"""
Make a request using the requests library
:param method: Which http method to use (GET/POST)
:type method: str | unicode
:param url: Url to make request to
... | Make a request using the requests library
:param method: Which http method to use (GET/POST)
:type method: str | unicode
:param url: Url to make request to
:type url: str | unicode
:param timeout: Timeout for request (default: None)
None -> infinite timeout
:... |
def get_value_length(byte):
"""Length of the value, in bytes (value can be 8/16/24/custom bits)
:param byte:
:return:
"""
length_value = byte & length_type_mask
return LengthTypes.to_ints.get(length_value, byte & length_mask) | Length of the value, in bytes (value can be 8/16/24/custom bits)
:param byte:
:return: |
def get_header(self, key):
"""Returns the requested header, or an empty string if the header is not set.
Keyword arguments:
key -- The header name. It will be canonicalized before use.
"""
key = canonicalize_header(key)
if key in self.header:
return self.head... | Returns the requested header, or an empty string if the header is not set.
Keyword arguments:
key -- The header name. It will be canonicalized before use. |
def proxied_attribute(local_attr, proxied_attr, doc):
"""Create a property that proxies attribute ``proxied_attr`` through
the local attribute ``local_attr``.
"""
def fget(self):
return getattr(getattr(self, local_attr), proxied_attr)
def fset(self, value):
setattr(getattr(self, loca... | Create a property that proxies attribute ``proxied_attr`` through
the local attribute ``local_attr``. |
def get_build_artefacts(config):
"""Create all required build artefacts, modify config to refer to them."""
def aux(ctx, service_name, service):
compiler, environment = get_compiler(config, service)
new_service, service_barts = compiler.getBuildArtefacts(environment, ctx, service)
ctx =... | Create all required build artefacts, modify config to refer to them. |
def create_all(self, checkfirst: bool = True) -> None:
"""Create the PyBEL cache's database and tables.
:param checkfirst: Check if the database exists before trying to re-make it
"""
self.base.metadata.create_all(bind=self.engine, checkfirst=checkfirst) | Create the PyBEL cache's database and tables.
:param checkfirst: Check if the database exists before trying to re-make it |
def security():
"""View for security page."""
sessions = SessionActivity.query_by_user(
user_id=current_user.get_id()
).all()
master_session = None
for index, session in enumerate(sessions):
if SessionActivity.is_current(session.sid_s):
master_session = session
... | View for security page. |
def copy_object(self, container, obj, new_container, new_obj_name=None,
content_type=None, extra_info=None):
"""
Copies the object to the new container, optionally giving it a new name.
If you copy to the same container, you must supply a different name.
You can optionally c... | Copies the object to the new container, optionally giving it a new name.
If you copy to the same container, you must supply a different name.
You can optionally change the content_type of the object by supplying
that in the 'content_type' parameter.
The 'extra_info' parameter is includ... |
def configure_uploads(app, upload_sets):
"""
Call this after the app has been configured. It will go through all the
upload sets, get their configuration, and store the configuration on the
app. It will also register the uploads module if it hasn't been set. This
can be called multiple times with di... | Call this after the app has been configured. It will go through all the
upload sets, get their configuration, and store the configuration on the
app. It will also register the uploads module if it hasn't been set. This
can be called multiple times with different upload sets.
.. versionchanged:: 0.1.3
... |
def get_day_of_month(datestring):
"""Transforms an ordinal number into plain number with padding zero.
E.g. 3rd -> 03, or 12th -> 12
Keyword arguments:
datestring -- a string
Returns:
String, or None if the transformation fails
"""
get_day = re.compile(r"\d{1,2}(st|nd|rd|th)?", re.IGN... | Transforms an ordinal number into plain number with padding zero.
E.g. 3rd -> 03, or 12th -> 12
Keyword arguments:
datestring -- a string
Returns:
String, or None if the transformation fails |
def sort_values(self, return_indexer=False, ascending=True):
"""
Return a sorted copy of the index.
Return a sorted copy of the index, and optionally return the indices
that sorted the index itself.
Parameters
----------
return_indexer : bool, default False
... | Return a sorted copy of the index.
Return a sorted copy of the index, and optionally return the indices
that sorted the index itself.
Parameters
----------
return_indexer : bool, default False
Should the indices that would sort the index be returned.
ascendi... |
def cached_workflow_property(func=None, attr=None, setter=True):
"""
Decorator to declare an attribute that is stored only on a workflow and also cached for
subsequent calls. Therefore, the decorated method is expected to (lazily) provide the value to
cache. The resulting value is stored as ``_workflow_... | Decorator to declare an attribute that is stored only on a workflow and also cached for
subsequent calls. Therefore, the decorated method is expected to (lazily) provide the value to
cache. The resulting value is stored as ``_workflow_cached_<func.__name__>`` on the workflow,
which can be overwritten by set... |
def is_android(filename):
"""Return the type of the file
@param filename : the filename
@rtype : "APK", "DEX", None
"""
if not filename:
return None
with open(filename, "rb") as fd:
f_bytes = fd.read()
return is_android_raw(f_bytes)
return None | Return the type of the file
@param filename : the filename
@rtype : "APK", "DEX", None |
def defrise(space, nellipses=8, alternating=False, min_pt=None, max_pt=None):
"""Phantom with regularily spaced ellipses.
This phantom is often used to verify cone-beam algorithms.
Parameters
----------
space : `DiscreteLp`
Space in which the phantom should be created, must be 2- or
... | Phantom with regularily spaced ellipses.
This phantom is often used to verify cone-beam algorithms.
Parameters
----------
space : `DiscreteLp`
Space in which the phantom should be created, must be 2- or
3-dimensional.
nellipses : int, optional
Number of ellipses. If more el... |
def rank_genes_groups(
adata,
groupby,
use_raw=True,
groups: Union[str, Iterable[str]] = 'all',
reference='rest',
n_genes=100,
rankby_abs=False,
key_added=None,
copy=False,
method='t-test_overestim_var',
corr_method='benjamini-hochberg',
log_transformed=True,
**kwds
)... | Rank genes for characterizing groups.
Parameters
----------
adata : :class:`~anndata.AnnData`
Annotated data matrix.
groupby : `str`
The key of the observations grouping to consider.
use_raw : `bool`, optional (default: `True`)
Use `raw` attribute of `adata` if present.
... |
def _add_standard_attributes(cls):
"""Add attributes common to all state machines.
These are methods for setting and checking state etc.
"""
setattr(
cls.context.new_class,
cls.context.new_meta['state_attribute_name'],
cls.context.state_value)
... | Add attributes common to all state machines.
These are methods for setting and checking state etc. |
def does_not_contain(self, element):
"""
Ensures :attr:`subject` does not contain *element*.
"""
self._run(unittest_case.assertNotIn, (element, self._subject))
return ChainInspector(self._subject) | Ensures :attr:`subject` does not contain *element*. |
def _get_text(self, text):
"""Returns the text content of `text`, with all multi-character tokens
replaced with a single character. Substitutions are recorded
in self._substitutes.
:param text: text to get content from
:type text: `Text`
:rtype: `str`
"""
... | Returns the text content of `text`, with all multi-character tokens
replaced with a single character. Substitutions are recorded
in self._substitutes.
:param text: text to get content from
:type text: `Text`
:rtype: `str` |
def mac_str_to_bytes(mac_str):
'''
Convert a MAC address string into bytes. Works with or without separators:
b1 = mac_str_to_bytes('08:00:27:13:69:77')
b2 = mac_str_to_bytes('080027136977')
assert b1 == b2
assert isinstance(b1, bytes)
'''
if len(mac_str) == 12:
pass
elif le... | Convert a MAC address string into bytes. Works with or without separators:
b1 = mac_str_to_bytes('08:00:27:13:69:77')
b2 = mac_str_to_bytes('080027136977')
assert b1 == b2
assert isinstance(b1, bytes) |
def set_power_configuration(policy=None, delayType=None, delayValue=None):
'''
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an ... | Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server... |
def remove_instance(self, item):
"""Remove `instance` from model"""
self.instances.remove(item)
self.remove_item(item) | Remove `instance` from model |
def SetModel( self, model, adapter=None ):
"""Set our model object (root of the tree)"""
self.model = model
if adapter is not None:
self.adapter = adapter
self.UpdateDrawing() | Set our model object (root of the tree) |
def load_ext(self):
"""Read time series data like method |IOSequence.load_ext| of class
|IOSequence|, but with special handling of missing data.
The method's "special handling" is to convert errors to warnings.
We explain the reasons in the documentation on method |Obs.load_ext|
... | Read time series data like method |IOSequence.load_ext| of class
|IOSequence|, but with special handling of missing data.
The method's "special handling" is to convert errors to warnings.
We explain the reasons in the documentation on method |Obs.load_ext|
of class |Obs|, from which we ... |
def configure(self, listener):
"""
Configure a :class:`.Listener` to capture callback query
"""
listener.capture([
lambda msg: flavor(msg) == 'callback_query',
{'message': self._chat_origin_included}
])
listener.capture([
lambda msg: f... | Configure a :class:`.Listener` to capture callback query |
def search(self, query: Optional[dict] = None, offset: Optional[int] = None,
limit: Optional[int] = None,
order_by: Union[None, list, tuple] = None) -> Sequence['IModel']:
"""return search result based on specified rulez query"""
raise NotImplementedError | return search result based on specified rulez query |
def _find_dependent_modules(self, module):
"""
Return the set of dependent modules for used modules,
classes and routines.
"""
dms = set()
for um in inspect.getmembers(module, inspect.ismodule):
dms.add(um[1])
for uc in inspect.getmembers(module, insp... | Return the set of dependent modules for used modules,
classes and routines. |
def add(self, model):
"""raises an exception if the model cannot be added"""
def foo(m, p, i):
if m[i][0].name == model.name:
raise ValueError("Model already exists")
return
# checks if already existing
self.foreach(foo)
self.appen... | raises an exception if the model cannot be added |
def __parse_addr(self, addr):
""" Parse email addresses
"""
from email.utils import parseaddr
value = parseaddr(addr)
return value[0], value[1] | Parse email addresses |
def add_job(self, func, *args):
"""Add a job that should return a reply to be sent.
A job is a tuple of function and optional args. Keyword arguments
can be passed via use of functools.partial. The job should return a
string that should be sent by the gateway protocol.
The asyn... | Add a job that should return a reply to be sent.
A job is a tuple of function and optional args. Keyword arguments
can be passed via use of functools.partial. The job should return a
string that should be sent by the gateway protocol.
The async version of this method will send the repl... |
def getDailyMenu(self, restaurant_id):
"""
:param restaurant_id: id of restaurant whose details are requested
:return: json response
Get daily menu using Zomato restaurant ID.
"""
params = {"res_id": restaurant_id}
daily_menu = self.api.get("/dailymenu", params)
... | :param restaurant_id: id of restaurant whose details are requested
:return: json response
Get daily menu using Zomato restaurant ID. |
def convertDict2Attrs(self, *args, **kwargs):
"""The trick for iterable Mambu Objects comes here:
You iterate over each element of the responded List from Mambu,
and create a Mambu Group object for each one, initializing them
one at a time, and changing the attrs attribute (which just
... | The trick for iterable Mambu Objects comes here:
You iterate over each element of the responded List from Mambu,
and create a Mambu Group object for each one, initializing them
one at a time, and changing the attrs attribute (which just
holds a list of plain dictionaries) with a MambuGr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.