code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def by_classifiers(cls, session, classifiers):
"""
Get releases for given classifiers.
:param session: SQLAlchemy session
:type session: :class:`sqlalchemy.Session`
:param classifiers: classifiers
:type classifiers: unicode
:return: release instances
:r... | Get releases for given classifiers.
:param session: SQLAlchemy session
:type session: :class:`sqlalchemy.Session`
:param classifiers: classifiers
:type classifiers: unicode
:return: release instances
:rtype: generator of :class:`pyshop.models.Release` |
def get_template_loaders():
"""
Compatibility method to fetch the template loaders.
Source: https://github.com/django-debug-toolbar/django-debug-toolbar/blob/ece1c2775af108a92a0ef59636266b49e286e916/debug_toolbar/compat.py
"""
try:
from django.template.engine import Engine
except ImportE... | Compatibility method to fetch the template loaders.
Source: https://github.com/django-debug-toolbar/django-debug-toolbar/blob/ece1c2775af108a92a0ef59636266b49e286e916/debug_toolbar/compat.py |
def min(self):
""" -> #float :func:numpy.min of the timing intervals """
return round(np.min(self.array), self.precision)\
if len(self.array) else None | -> #float :func:numpy.min of the timing intervals |
def register(cls):
''' Decorator to add a Message (and its revision) to the Protocol index.
Example:
.. code-block:: python
@register
class some_msg_1(Message):
msgtype = 'SOME-MSG'
revision = 1
@classmethod
de... | Decorator to add a Message (and its revision) to the Protocol index.
Example:
.. code-block:: python
@register
class some_msg_1(Message):
msgtype = 'SOME-MSG'
revision = 1
@classmethod
def create(cls, **metadata):
... |
def get_user_deliveryserver(self, domainid, serverid):
"""Get a user delivery server"""
return self.api_call(
ENDPOINTS['userdeliveryservers']['get'],
dict(domainid=domainid, serverid=serverid)) | Get a user delivery server |
def __autoconnect_signals(self):
"""This is called during view registration, to autoconnect
signals in glade file with methods within the controller"""
dic = {}
for name in dir(self):
method = getattr(self, name)
if (not isinstance(method, collections.Callable)):
... | This is called during view registration, to autoconnect
signals in glade file with methods within the controller |
def get_rtc_table(self):
"""Returns global RTC table.
Creates the table if it does not exist.
"""
rtc_table = self._global_tables.get(RF_RTC_UC)
# Lazy initialization of the table.
if not rtc_table:
rtc_table = RtcTable(self._core_service, self._signal_bus)
... | Returns global RTC table.
Creates the table if it does not exist. |
def _dir2(obj, pref='', excl=(), slots=None, itor=''):
'''Return an attribute name, object 2-tuple for certain
attributes or for the ``__slots__`` attributes of the
given object, but not both. Any iterator referent
objects are returned with the given name if the
latter is non-empty.
... | Return an attribute name, object 2-tuple for certain
attributes or for the ``__slots__`` attributes of the
given object, but not both. Any iterator referent
objects are returned with the given name if the
latter is non-empty. |
def validate_config(self, organization, config, actor=None):
"""
```
if config['foo'] and not config['bar']:
raise PluginError('You cannot configure foo with bar')
return config
```
"""
if config.get('name'):
client = self.get_client(actor)... | ```
if config['foo'] and not config['bar']:
raise PluginError('You cannot configure foo with bar')
return config
``` |
def http_request(self, path="/", method="GET", host=None, port=None, json=False, data=None):
"""
perform a HTTP request
:param path: str, path within the request, e.g. "/api/version"
:param method: str, HTTP method
:param host: str, if None, set to 127.0.0.1
:param port:... | perform a HTTP request
:param path: str, path within the request, e.g. "/api/version"
:param method: str, HTTP method
:param host: str, if None, set to 127.0.0.1
:param port: str or int, if None, set to 8080
:param json: bool, should we expect json?
:param data: data to ... |
def scale_WCS(self,pixel_scale,retain=True):
''' Scale the WCS to a new pixel_scale. The 'retain' parameter
[default value: True] controls whether or not to retain the original
distortion solution in the CD matrix.
'''
_ratio = pixel_scale / self.pscale
# Correct the siz... | Scale the WCS to a new pixel_scale. The 'retain' parameter
[default value: True] controls whether or not to retain the original
distortion solution in the CD matrix. |
def inline(self) -> str:
"""
Return inline document string
:return:
"""
return "{0}:{1}:{2}:{3}".format(self.pubkey_from, self.pubkey_to,
self.timestamp.number, self.signatures[0]) | Return inline document string
:return: |
def apply_uncertainties(self, branch_ids, source_group):
"""
Parse the path through the source model logic tree and return
"apply uncertainties" function.
:param branch_ids:
List of string identifiers of branches, representing the path
through source model logic ... | Parse the path through the source model logic tree and return
"apply uncertainties" function.
:param branch_ids:
List of string identifiers of branches, representing the path
through source model logic tree.
:param source_group:
A group of sources
:re... |
def best_matches(self, target, choices):
"""\
Get all the first choices listed from best match to worst match,
optionally grouping on equal matches.
:param target:
:param choices:
:param group:
"""
all = self.all_matches
try:
matches... | \
Get all the first choices listed from best match to worst match,
optionally grouping on equal matches.
:param target:
:param choices:
:param group: |
def reload_pimms():
'''
reload_pimms() reloads the entire pimms module and returns it.
'''
import sys, six
try: from importlib import reload
except: from imp import reload
reload(sys.modules['pimms.util'])
reload(sys.modules['pimms.table'])
reload(sys.modules['pimms.immutabl... | reload_pimms() reloads the entire pimms module and returns it. |
def complete_credit_note(self, credit_note_it, complete_dict):
"""
Completes an credit note
:param complete_dict: the complete dict with the template id
:param credit_note_it: the credit note id
:return: Response
"""
return self._create_put_request(
r... | Completes an credit note
:param complete_dict: the complete dict with the template id
:param credit_note_it: the credit note id
:return: Response |
def str_between(str_, startstr, endstr):
r"""
gets substring between two sentianl strings
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> import utool as ut
>>> str_ = '\n INSERT INTO vsone(\n'
>>> startstr = 'INSERT'
>>> en... | r"""
gets substring between two sentianl strings
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> import utool as ut
>>> str_ = '\n INSERT INTO vsone(\n'
>>> startstr = 'INSERT'
>>> endstr = '('
>>> result = str_between(s... |
def UsesArtifact(self, artifacts):
"""Determines if the check uses the specified artifact.
Args:
artifacts: Either a single artifact name, or a list of artifact names
Returns:
True if the check uses a specific artifact.
"""
# If artifact is a single string, see if it is in the list of ... | Determines if the check uses the specified artifact.
Args:
artifacts: Either a single artifact name, or a list of artifact names
Returns:
True if the check uses a specific artifact. |
def add_slave_server(self):
"""
添加slave服务器
:return:
"""
master = self.args.config[1]
slave = self.args.add_slave
# install java at slave server
self.reset_server_env(slave, self.configure)
if self.prompt_check("Update package at slave server"):
... | 添加slave服务器
:return: |
def iwls(y, x, family, offset, y_fix,
ini_betas=None, tol=1.0e-8, max_iter=200, wi=None):
"""
Iteratively re-weighted least squares estimation routine
Parameters
----------
y : array
n*1, dependent variable
x : array
n*k, designs... | Iteratively re-weighted least squares estimation routine
Parameters
----------
y : array
n*1, dependent variable
x : array
n*k, designs matrix of k independent variables
family : family object
probability models: Gauss... |
def pid(self):
"""Get the pid which represents a daemonized process.
The result should be None if the process is not running.
"""
try:
with open(self.pidfile, 'r') as pidfile:
try:
pid = int(pidfile.read().strip())
exce... | Get the pid which represents a daemonized process.
The result should be None if the process is not running. |
def channel(self, channel_id=None, auto_encode_decode=True):
"""Fetch a Channel object identified by the numeric channel_id, or
create that object if it doesn't already exist. See Channel for meaning
of auto_encode_decode. If the channel already exists, the auto_* flag
will not be update... | Fetch a Channel object identified by the numeric channel_id, or
create that object if it doesn't already exist. See Channel for meaning
of auto_encode_decode. If the channel already exists, the auto_* flag
will not be updated. |
def remove_remap_file(filename):
"""Remove any mapping for *filename* and return that if it exists"""
global file2file_remap
if filename in file2file_remap:
retval = file2file_remap[filename]
del file2file_remap[filename]
return retval
return None | Remove any mapping for *filename* and return that if it exists |
def consumer(self, name):
"""
Create a new consumer for the :py:class:`ConsumerGroup`.
:param name: name of consumer
:returns: a :py:class:`ConsumerGroup` using the given consumer name.
"""
return type(self)(self.database, self.name, self.keys, name) | Create a new consumer for the :py:class:`ConsumerGroup`.
:param name: name of consumer
:returns: a :py:class:`ConsumerGroup` using the given consumer name. |
def try_enqueue(conn, queue_name, msg):
"""
Try to enqueue a message. If it succeeds, return the message ID.
:param conn: SQS API connection
:type conn: :py:class:`botocore:SQS.Client`
:param queue_name: name of queue to put message in
:type queue_name: str
:param msg: JSON-serialized messa... | Try to enqueue a message. If it succeeds, return the message ID.
:param conn: SQS API connection
:type conn: :py:class:`botocore:SQS.Client`
:param queue_name: name of queue to put message in
:type queue_name: str
:param msg: JSON-serialized message body
:type msg: str
:return: message ID
... |
def add_threat_list(self, threat_list):
"""Add threat list entry if it does not exist."""
q = '''INSERT OR IGNORE INTO threat_list
(threat_type, platform_type, threat_entry_type, timestamp)
VALUES
(?, ?, ?, current_timestamp)
'''
pa... | Add threat list entry if it does not exist. |
def search(term, lang=None):
"""
As a convenient alternative to downloading and parsing a dump,
This function will instead query the AID search provided by Eloyard.
This is the same information available at http://anisearch.outrance.pl/.
:param str term: Search Term
:par... | As a convenient alternative to downloading and parsing a dump,
This function will instead query the AID search provided by Eloyard.
This is the same information available at http://anisearch.outrance.pl/.
:param str term: Search Term
:param list lang: A list of language codes which dete... |
def save(self, *args, **kwargs):
"""Saving ensures that the slug, if not set, is set to the slugified name."""
self.clean()
if not self.slug:
self.slug = slugify(self.name)
super(SpecialCoverage, self).save(*args, **kwargs)
if self.query and self.query != {}:
... | Saving ensures that the slug, if not set, is set to the slugified name. |
def add_new_refs(cls, manifest, current_project, node, macros):
"""Given a new node that is not in the manifest, copy the manifest and
insert the new node into it as if it were part of regular ref
processing
"""
manifest = manifest.deepcopy(config=current_project)
# it's ... | Given a new node that is not in the manifest, copy the manifest and
insert the new node into it as if it were part of regular ref
processing |
def cleanup(self, **kwargs):
"""cleanup ASA context for an edge tenant pair. """
params = kwargs.get('params')
LOG.info("asa_cleanup: tenant %(tenant)s %(in_vlan)d %(out_vlan)d"
" %(in_ip)s %(in_mask)s %(out_ip)s %(out_mask)s",
{'tenant': params.get('tenant_name... | cleanup ASA context for an edge tenant pair. |
def _validate_config(self, config):
"""
Validates that all necessary config parameters are specified.
:type config: dict[str, dict[str, Any] | str]
:param config: the module config
"""
if config is None:
raise ValueError("OIDCFrontend conf can't be 'None'.")
... | Validates that all necessary config parameters are specified.
:type config: dict[str, dict[str, Any] | str]
:param config: the module config |
def manage_beacons(self, tag, data):
'''
Manage Beacons
'''
func = data.get('func', None)
name = data.get('name', None)
beacon_data = data.get('beacon_data', None)
include_pillar = data.get('include_pillar', None)
include_opts = data.get('include_opts', No... | Manage Beacons |
def set_char(key, value):
""" Updates charters used to render components.
"""
global _chars
category = _get_char_category(key)
if not category:
raise KeyError
_chars[category][key] = value | Updates charters used to render components. |
def callers(variant_obj, category='snv'):
"""Return info about callers."""
calls = set()
for caller in CALLERS[category]:
if variant_obj.get(caller['id']):
calls.add((caller['name'], variant_obj[caller['id']]))
return list(calls) | Return info about callers. |
def to_dict(self, ignore_none: bool=True, force_value: bool=True, ignore_empty: bool=False) -> dict:
"""From instance to dict
:param ignore_none: Properties which is None are excluded if True
:param force_value: Transform to value using to_value (default: str()) of ValueTransformer which inheri... | From instance to dict
:param ignore_none: Properties which is None are excluded if True
:param force_value: Transform to value using to_value (default: str()) of ValueTransformer which inherited if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Dict
... |
def getmessage(self) -> str:
""" parse self into unicode string as message content """
image = {}
for key, default in vars(self.__class__).items():
if not key.startswith('_') and key !='' and (not key in vars(QueueMessage).items()):
... | parse self into unicode string as message content |
def BackAssign(cls,
other_entity_klass,
this_entity_backpopulate_field,
other_entity_backpopulate_field,
is_many_to_one=False):
"""
Assign defined one side mapping relationship to other side.
For example, each employee ... | Assign defined one side mapping relationship to other side.
For example, each employee belongs to one department, then one department
includes many employees. If you defined each employee's department,
this method will assign employees to ``Department.employees`` field.
This is an one t... |
def lp7(self, reaction_subset):
"""Approximately maximize the number of reaction with flux.
This is similar to FBA but approximately maximizing the number of
reactions in subset with flux > epsilon, instead of just maximizing the
flux of one particular reaction. LP7 prefers "flux splitt... | Approximately maximize the number of reaction with flux.
This is similar to FBA but approximately maximizing the number of
reactions in subset with flux > epsilon, instead of just maximizing the
flux of one particular reaction. LP7 prefers "flux splitting" over
"flux concentrating". |
def bandpass(s, f1, f2, order=2, fs=1000.0, use_filtfilt=False):
"""
-----
Brief
-----
For a given signal s passes the frequencies within a certain range (between f1 and f2) and rejects (attenuates) the
frequencies outside that range by applying a Butterworth digital filter.
-----------
... | -----
Brief
-----
For a given signal s passes the frequencies within a certain range (between f1 and f2) and rejects (attenuates) the
frequencies outside that range by applying a Butterworth digital filter.
-----------
Description
-----------
Signals may have frequency components of mul... |
def add_called_sequence(self, section, name, sequence, qstring):
""" Add basecalled sequence data
:param section: ['template', 'complement' or '2D']
:param name: The record ID to use for the fastq.
:param sequence: The called sequence.
:param qstring: The quality string.... | Add basecalled sequence data
:param section: ['template', 'complement' or '2D']
:param name: The record ID to use for the fastq.
:param sequence: The called sequence.
:param qstring: The quality string. |
def info(self, section=None):
"""The INFO command returns information and statistics about the server
in a format that is simple to parse by computers and easy to read by
humans.
The optional parameter can be used to select a specific section of
information:
- serve... | The INFO command returns information and statistics about the server
in a format that is simple to parse by computers and easy to read by
humans.
The optional parameter can be used to select a specific section of
information:
- server: General information about the Redis se... |
def removereadergroup(self, group):
"""Remove a reader group"""
hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
if 0 != hresult:
raise error(
'Failed to establish context: ' + \
SCardGetErrorMessage(hresult))
try:
hresu... | Remove a reader group |
def _filter_repeating_items(download_list):
""" Because of data_filter some requests in download list might be the same. In order not to download them again
this method will reduce the list of requests. It will also return a mapping list which can be used to
reconstruct the previous list of down... | Because of data_filter some requests in download list might be the same. In order not to download them again
this method will reduce the list of requests. It will also return a mapping list which can be used to
reconstruct the previous list of download requests.
:param download_list: List of do... |
def find_minimal_node(self, node_head, discriminator):
"""!
@brief Find minimal node in line with coordinate that is defined by discriminator.
@param[in] node_head (node): Node of KD tree from that search should be started.
@param[in] discriminator (uint): Coordinate number... | !
@brief Find minimal node in line with coordinate that is defined by discriminator.
@param[in] node_head (node): Node of KD tree from that search should be started.
@param[in] discriminator (uint): Coordinate number that is used for comparison.
@return (node) Min... |
def login(self, username=None, password=None, login_url=None,
auth_url=None):
"""
This will automatically log the user into the pre-defined account
Feel free to overwrite this with an endpoint on endpoint load
:param username: str of the user name to logi... | This will automatically log the user into the pre-defined account
Feel free to overwrite this with an endpoint on endpoint load
:param username: str of the user name to login in as
:param password: str of the password to login as
:param login_url: str of the url for t... |
def cancelScannerSubscription(self, dataList: ScanDataList):
"""
Cancel market data subscription.
https://interactivebrokers.github.io/tws-api/market_scanners.html
Args:
dataList: The scan data list that was obtained from
:meth:`.reqScannerSubscription`.
... | Cancel market data subscription.
https://interactivebrokers.github.io/tws-api/market_scanners.html
Args:
dataList: The scan data list that was obtained from
:meth:`.reqScannerSubscription`. |
def build_state_assignment(self, runnable, regime, state_assignment):
"""
Build state assignment code.
@param state_assignment: State assignment object
@type state_assignment: lems.model.dynamics.StateAssignment
@return: Generated state assignment code
@rtype: string
... | Build state assignment code.
@param state_assignment: State assignment object
@type state_assignment: lems.model.dynamics.StateAssignment
@return: Generated state assignment code
@rtype: string |
def create_api_key(self, body, **kwargs): # noqa: E501
"""Create a new API key. # noqa: E501
An endpoint for creating a new API key. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/api-keys -d '{\"name\": \"MyKey1\"}' -H 'content-type: application/json' -H 'Authorization: Be... | Create a new API key. # noqa: E501
An endpoint for creating a new API key. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/api-keys -d '{\"name\": \"MyKey1\"}' -H 'content-type: application/json' -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method makes a synchronou... |
def build_tree(self, data, tagname, attrs=None, depth=0):
r"""Build xml tree.
:param data: data for build xml.
:param tagname: element tag name.
:param attrs: element attributes. Default:``None``.
:type attrs: dict or None
:param depth: element depth of the hierarchy. De... | r"""Build xml tree.
:param data: data for build xml.
:param tagname: element tag name.
:param attrs: element attributes. Default:``None``.
:type attrs: dict or None
:param depth: element depth of the hierarchy. Default:``0``.
:type depth: int |
def get_queryset(self):
"Restrict to a single kind of event, if any, and include Venue data."
qs = super().get_queryset()
kind = self.get_event_kind()
if kind is not None:
qs = qs.filter(kind=kind)
qs = qs.select_related('venue')
return qs | Restrict to a single kind of event, if any, and include Venue data. |
def get(self):
"""Gets the current evaluation result.
Returns
-------
names : list of str
Name of the metrics.
values : list of float
Value of the evaluations.
"""
if self.num_inst == 0:
return (self.name, float('nan'))
e... | Gets the current evaluation result.
Returns
-------
names : list of str
Name of the metrics.
values : list of float
Value of the evaluations. |
def build_from_file(self, dockerfile, tag, **kwargs):
"""
Builds a docker image from the given :class:`~dockermap.build.dockerfile.DockerFile`. Use this as a shortcut to
:meth:`build_from_context`, if no extra data is added to the context.
:param dockerfile: An instance of :class:`~dock... | Builds a docker image from the given :class:`~dockermap.build.dockerfile.DockerFile`. Use this as a shortcut to
:meth:`build_from_context`, if no extra data is added to the context.
:param dockerfile: An instance of :class:`~dockermap.build.dockerfile.DockerFile`.
:type dockerfile: dockermap.bu... |
def get_topology(self):
"""
Get the converted topology ready for JSON encoding
:return: converted topology assembled into a single dict
:rtype: dict
"""
topology = {'name': self._name,
'resources_type': 'local',
'topology': {},
... | Get the converted topology ready for JSON encoding
:return: converted topology assembled into a single dict
:rtype: dict |
def port_profile_vlan_profile_switchport_mode_vlan_mode(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile")
name_key = ET.SubElement(port_profile, "name")... | Auto Generated Code |
def lang_items(self, lang=None):
"""Yield pairs of (id, string) for the given language."""
if lang is None:
lang = self.language
yield from self.cache.setdefault(lang, {}).items() | Yield pairs of (id, string) for the given language. |
def bullet_ant():
"""Configuration for PyBullet's ant task."""
locals().update(default())
# Environment
import pybullet_envs # noqa pylint: disable=unused-import
env = 'AntBulletEnv-v0'
max_length = 1000
steps = 3e7 # 30M
update_every = 60
return locals() | Configuration for PyBullet's ant task. |
def to_reminders(self, ical, label=None, priority=None, tags=None,
tail=None, sep=" ", postdate=None, posttime=None):
"""Return Remind commands for all events of a iCalendar"""
if not hasattr(ical, 'vevent_list'):
return ''
reminders = [self.to_remind(vevent, la... | Return Remind commands for all events of a iCalendar |
def x_at_y(self, y, reverse=False):
"""
Calculates inverse profile - for given y returns x such that f(x) = y
If given y is not found in the self.y, then interpolation is used.
By default returns first result looking from left,
if reverse argument set to True,
looks from ... | Calculates inverse profile - for given y returns x such that f(x) = y
If given y is not found in the self.y, then interpolation is used.
By default returns first result looking from left,
if reverse argument set to True,
looks from right. If y is outside range of self.y
then np.n... |
def digital_write_pullup(pin_num, value, hardware_addr=0):
"""Writes the value to the input pullup specified.
.. note:: This function is for familiarality with users of other types of
IO board. Consider accessing the ``gppub`` attribute of a
PiFaceDigital object:
>>> pfd = PiFaceDigital(h... | Writes the value to the input pullup specified.
.. note:: This function is for familiarality with users of other types of
IO board. Consider accessing the ``gppub`` attribute of a
PiFaceDigital object:
>>> pfd = PiFaceDigital(hardware_addr)
>>> hex(pfd.gppub.value)
0xff
>... |
def assign_interval(data):
"""Identify coverage based on percent of genome covered and relation to targets.
Classifies coverage into 3 categories:
- genome: Full genome coverage
- regional: Regional coverage, like exome capture, with off-target reads
- amplicon: Amplication based regional cov... | Identify coverage based on percent of genome covered and relation to targets.
Classifies coverage into 3 categories:
- genome: Full genome coverage
- regional: Regional coverage, like exome capture, with off-target reads
- amplicon: Amplication based regional coverage without off-target reads |
def translate_src(src, cortex):
"""
Convert source nodes to new surface (without medial wall).
"""
src_new = np.array(np.where(np.in1d(cortex, src))[0], dtype=np.int32)
return src_new | Convert source nodes to new surface (without medial wall). |
def _tot_unhandled_hosts_by_state(self, state):
"""Generic function to get the number of unhandled problem hosts in the specified state
:param state: state to filter on
:type state:
:return: number of host in state *state* and which are not acknowledged problems
:rtype: int
... | Generic function to get the number of unhandled problem hosts in the specified state
:param state: state to filter on
:type state:
:return: number of host in state *state* and which are not acknowledged problems
:rtype: int |
def encode_xml(obj, E=None):
""" Encodes an OpenMath object as an XML node.
:param obj: OpenMath object (or related item) to encode as XML.
:type obj: OMAny
:param ns: Namespace prefix to use for
http://www.openmath.org/OpenMath", or None if default namespace.
:type ns: str, None
:ret... | Encodes an OpenMath object as an XML node.
:param obj: OpenMath object (or related item) to encode as XML.
:type obj: OMAny
:param ns: Namespace prefix to use for
http://www.openmath.org/OpenMath", or None if default namespace.
:type ns: str, None
:return: The XML node representing the Op... |
def match(self, node):
u"""
Since the tree needs to be fixed once and only once if and only if it
matches, we can start discarding matches after the first.
"""
if node.type == self.syms.term:
div_idx = find_division(node)
if div_idx is not False:
... | u"""
Since the tree needs to be fixed once and only once if and only if it
matches, we can start discarding matches after the first. |
def delete_autostart_entry():
"""Remove a present autostart entry. If none is found, nothing happens."""
autostart_file = Path(common.AUTOSTART_DIR) / "autokey.desktop"
if autostart_file.exists():
autostart_file.unlink()
_logger.info("Deleted old autostart entry: {}".format(autostart_file)) | Remove a present autostart entry. If none is found, nothing happens. |
def make_compute_file(self):
"""
Make the compute file from the self.vardict and self.vardictformat
"""
string = ""
try:
vardict_items = self.vardict.iteritems()
except AttributeError:
vardict_items = self.vardict.items()
for key, val in va... | Make the compute file from the self.vardict and self.vardictformat |
def flush(self):
""" Sends the current. batch to Cloud Bigtable.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_batcher_flush]
:end-before: [END bigtable_batcher_flush]
"""
if len(self.rows) != 0:
self.table.mutate... | Sends the current. batch to Cloud Bigtable.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_batcher_flush]
:end-before: [END bigtable_batcher_flush] |
def show_download_links(self):
"""
Query PyPI for pkg download URI for a packge
@returns: 0
"""
#In case they specify version as 'dev' instead of using -T svn,
#don't show three svn URI's
if self.options.file_type == "all" and self.version == "dev":
... | Query PyPI for pkg download URI for a packge
@returns: 0 |
def initialize(self):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.initialize`.
Is called once by NuPIC before the first call to compute().
Initializes self._sdrClassifier if it is not already initialized.
"""
if self._sdrClassifier is None:
self._sdrClassifier = SDRClass... | Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.initialize`.
Is called once by NuPIC before the first call to compute().
Initializes self._sdrClassifier if it is not already initialized. |
def display_required_items(msg_type):
"""
Display the required items needed to configure a profile for the given
message type.
Args:
:msg_type: (str) message type to create config entry.
"""
print("Configure a profile for: " + msg_type)
print("You will need the following information... | Display the required items needed to configure a profile for the given
message type.
Args:
:msg_type: (str) message type to create config entry. |
def shard_filename(path, tag, shard_num, total_shards):
"""Create filename for data shard."""
return os.path.join(
path, "%s-%s-%s-%.5d-of-%.5d" % (_PREFIX, _ENCODE_TAG, tag, shard_num, total_shards)) | Create filename for data shard. |
def cmd_arp_sniff(iface):
"""Listen for ARP packets and show information for each device.
Columns: Seconds from last packet | IP | MAC | Vendor
Example:
\b
1 192.168.0.1 a4:08:f5:19:17:a4 Sagemcom Broadband SAS
7 192.168.0.2 64:bc:0c:33:e5:57 LG Electronics (Mobile Communicati... | Listen for ARP packets and show information for each device.
Columns: Seconds from last packet | IP | MAC | Vendor
Example:
\b
1 192.168.0.1 a4:08:f5:19:17:a4 Sagemcom Broadband SAS
7 192.168.0.2 64:bc:0c:33:e5:57 LG Electronics (Mobile Communications)
2 192.168.0.5 00:c... |
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_remote_management_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail")
config = get_lldp_neighbor_detail
output = ET.Sub... | Auto Generated Code |
def consumption(self):
"""
Consumption in kWh per sector for whole grid
Returns
-------
:pandas:`pandas.Series<series>`
Indexed by demand sector
"""
consumption = defaultdict(float)
for load in self.graph.nodes_by_attribute('load'):
... | Consumption in kWh per sector for whole grid
Returns
-------
:pandas:`pandas.Series<series>`
Indexed by demand sector |
def open(self, *, autocommit=False):
"""Sets the connection with the core's open method.
:param autocommit: the default autocommit state
:type autocommit: boolean
:return: self
"""
if self.connection is not None:
raise Exception("Connection already set")
self.connection = self.core.op... | Sets the connection with the core's open method.
:param autocommit: the default autocommit state
:type autocommit: boolean
:return: self |
def image_members(self):
"""
Returns a json-schema document that represents an image members entity
(a container of member entities).
"""
uri = "/%s/members" % self.uri_base
resp, resp_body = self.api.method_get(uri)
return resp_body | Returns a json-schema document that represents an image members entity
(a container of member entities). |
def woodbury_chol(self):
"""
return $L_{W}$ where L is the lower triangular Cholesky decomposition of the Woodbury matrix
$$
L_{W}L_{W}^{\top} = W^{-1}
W^{-1} := \texttt{Woodbury inv}
$$
"""
if self._woodbury_chol is None:
# compute woodbury ch... | return $L_{W}$ where L is the lower triangular Cholesky decomposition of the Woodbury matrix
$$
L_{W}L_{W}^{\top} = W^{-1}
W^{-1} := \texttt{Woodbury inv}
$$ |
def read_pot_status(self):
"""Read the status of the digital pot. Firmware v18+ only.
The return value is a dictionary containing the following as
unsigned 8-bit integers: FanON, LaserON, FanDACVal, LaserDACVal.
:rtype: dict
:Example:
>>> alpha.read_pot_status()
... | Read the status of the digital pot. Firmware v18+ only.
The return value is a dictionary containing the following as
unsigned 8-bit integers: FanON, LaserON, FanDACVal, LaserDACVal.
:rtype: dict
:Example:
>>> alpha.read_pot_status()
{
'LaserDACVal': 230,
... |
def delete(self):
""" Delete the table.
Returns:
True if the Table no longer exists; False otherwise.
"""
try:
self._api.table_delete(self._name_parts)
except google.datalab.utils.RequestException:
# TODO(gram): May want to check the error reasons here and if it is not
# bec... | Delete the table.
Returns:
True if the Table no longer exists; False otherwise. |
def token(self, value):
""" Setter to convert any token dict into Token instance """
if value and not isinstance(value, Token):
value = Token(value)
self._token = value | Setter to convert any token dict into Token instance |
async def auto_add(self, device, recursive=None, automount=True):
"""
Automatically attempt to mount or unlock a device, but be quiet if the
device is not supported.
:param device: device object, block device path or mount path
:param bool recursive: recursively mount and unlock... | Automatically attempt to mount or unlock a device, but be quiet if the
device is not supported.
:param device: device object, block device path or mount path
:param bool recursive: recursively mount and unlock child devices
:returns: whether all attempted operations succeeded |
def _default_capacity(self, value):
""" Get the value for ReturnConsumedCapacity from provided value """
if value is not None:
return value
if self.default_return_capacity or self.rate_limiters:
return INDEXES
return NONE | Get the value for ReturnConsumedCapacity from provided value |
def _reader_thread_func(self, read_stdout: bool) -> None:
"""
Thread function that reads a stream from the process
:param read_stdout: if True, then this thread deals with stdout. Otherwise it deals with stderr.
"""
if read_stdout:
read_stream = self._proc.stdout
... | Thread function that reads a stream from the process
:param read_stdout: if True, then this thread deals with stdout. Otherwise it deals with stderr. |
def create_gtk_grid(self, row_spacing=6, col_spacing=6, row_homogenous=False, col_homogenous=True):
"""
Function creates a Gtk Grid with spacing
and homogeous tags
"""
grid_lang = Gtk.Grid()
grid_lang.set_column_spacing(row_spacing)
grid_lang.set_row_spacing(col_s... | Function creates a Gtk Grid with spacing
and homogeous tags |
def get_reply(self, method, reply):
"""
Process the I{reply} for the specified I{method} by sax parsing the
I{reply} and then unmarshalling into python object(s).
@param method: The name of the invoked method.
@type method: str
@param reply: The reply XML received after i... | Process the I{reply} for the specified I{method} by sax parsing the
I{reply} and then unmarshalling into python object(s).
@param method: The name of the invoked method.
@type method: str
@param reply: The reply XML received after invoking the specified
method.
@type ... |
def update_or_create(cls, **kwargs):
"""Checks if an instance already exists by filtering with the
kwargs. If yes, updates the instance with new kwargs and
returns that instance. If not, creates a new
instance with kwargs and returns it.
Args:
**kwargs: The keyword ... | Checks if an instance already exists by filtering with the
kwargs. If yes, updates the instance with new kwargs and
returns that instance. If not, creates a new
instance with kwargs and returns it.
Args:
**kwargs: The keyword arguments which are used for filtering
... |
def process(self):
"""
Calls the process endpoint for all locales of the asset.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets/asset-processing
"""
for locale in self._fields.keys():
self._client._put(
... | Calls the process endpoint for all locales of the asset.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets/asset-processing |
def select_segments_by_definer(segment_file, segment_name=None, ifo=None):
""" Return the list of segments that match the segment name
Parameters
----------
segment_file: str
path to segment xml file
segment_name: str
Name of segment
ifo: str, optional
Returns
-------
... | Return the list of segments that match the segment name
Parameters
----------
segment_file: str
path to segment xml file
segment_name: str
Name of segment
ifo: str, optional
Returns
-------
seg: list of segments |
def _parse_time_to_freeze(time_to_freeze_str):
"""Parses all the possible inputs for freeze_time
:returns: a naive ``datetime.datetime`` object
"""
if time_to_freeze_str is None:
time_to_freeze_str = datetime.datetime.utcnow()
if isinstance(time_to_freeze_str, datetime.datetime):
ti... | Parses all the possible inputs for freeze_time
:returns: a naive ``datetime.datetime`` object |
def import_all_modules():
"""
<Purpose>
Imports all modules within the modules folder. This should only be called once
throughout the entire execution of seash.
<Side Effects>
Modules that don't have collisions will have their commanddicts and
helptexts loaded and returned.
<Excep... | <Purpose>
Imports all modules within the modules folder. This should only be called once
throughout the entire execution of seash.
<Side Effects>
Modules that don't have collisions will have their commanddicts and
helptexts loaded and returned.
<Exceptions>
ImportError: There is a... |
def backspace(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press backspace key n times.
**中文文档**
按退格键 n 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.backspace_key, n, interval)
self.delay(post_dl) | Press backspace key n times.
**中文文档**
按退格键 n 次。 |
def proto_01_01_HP010(abf=exampleABF):
"""hyperpolarization step. Use to calculate tau and stuff."""
swhlab.memtest.memtest(abf) #knows how to do IC memtest
swhlab.memtest.checkSweep(abf) #lets you eyeball check how it did
swhlab.plot.save(abf,tag="tau") | hyperpolarization step. Use to calculate tau and stuff. |
def register_all_shape_checker(shape_checker_function,
arg_types,
exclude=(),
ignore_existing=False):
"""Register a gradient adder for all combinations of given types.
This is a convenience shorthand for calling register_a... | Register a gradient adder for all combinations of given types.
This is a convenience shorthand for calling register_add_grad when registering
gradient adders for multiple types that can be interchanged for the purpose
of addition.
Args:
shape_checker_function: A shape checker, see register_shape_checker.
... |
def _apply_axes_mapping(self, target, inverse=False):
"""
Apply the transposition to the target iterable.
Parameters
----------
target - iterable
The iterable to transpose. This would be suitable for things
such as a shape as well as a list of ``__getitem... | Apply the transposition to the target iterable.
Parameters
----------
target - iterable
The iterable to transpose. This would be suitable for things
such as a shape as well as a list of ``__getitem__`` keys.
inverse - bool
Whether to map old dimension... |
def gatk_type(self):
"""Retrieve type of GATK jar, allowing support for older GATK lite.
Returns either `lite` (targeting GATK-lite 2.3.9) or `restricted`,
the latest 2.4+ restricted version of GATK.
"""
if LooseVersion(self.gatk_major_version()) > LooseVersion("3.9"):
... | Retrieve type of GATK jar, allowing support for older GATK lite.
Returns either `lite` (targeting GATK-lite 2.3.9) or `restricted`,
the latest 2.4+ restricted version of GATK. |
def get(self, path):
""" Perform a GET request with GSSAPI authentication """
# Generate token
service_name = gssapi.Name('HTTP@{0}'.format(self.url.netloc),
gssapi.NameType.hostbased_service)
ctx = gssapi.SecurityContext(usage="initiate", name=service_... | Perform a GET request with GSSAPI authentication |
def create_namespaced_ingress(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_ingress # noqa: E501
create an Ingress # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> ... | create_namespaced_ingress # noqa: E501
create an Ingress # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_ingress(namespace, body, async_req=True)
>>> resul... |
def do_dice_roll():
"""
Roll n-sided dice and return each result and the total
"""
options = get_options()
dice = Dice(options.sides)
rolls = [dice.roll() for n in range(options.number)]
for roll in rolls:
print('rolled', roll)
if options.number > 1:
print('total', sum(rolls)) | Roll n-sided dice and return each result and the total |
def set_contributor_details(self, contdetails):
""" Sets 'contributor_details' parameter used to enhance the \
contributors element of the status response to include \
the screen_name of the contributor. By default only \
the user_id of the contributor is included
:param contdet... | Sets 'contributor_details' parameter used to enhance the \
contributors element of the status response to include \
the screen_name of the contributor. By default only \
the user_id of the contributor is included
:param contdetails: Boolean triggering the usage of the parameter
... |
def get_languages(self):
"""
Return a list of all used languages for this page.
"""
if self._languages:
return self._languages
self._languages = cache.get(self.PAGE_LANGUAGES_KEY % (self.id))
if self._languages is not None:
return self._languages
... | Return a list of all used languages for this page. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.