code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_properties(self):
# type: () -> dict
"""
Returns merged properties
:return: Endpoint merged properties
"""
# Get service properties
properties = self.__reference.get_properties()
# Merge with local properties
properties.update(self.__prop... | Returns merged properties
:return: Endpoint merged properties |
def _insert_command(self, command):
"""
Insert command by replacing the current input buffer and display it on the text edit.
"""
self._clear_user_buffer()
tc = self.edit.textCursor()
tc.insertText(command)
self.edit.setTextCursor(tc) | Insert command by replacing the current input buffer and display it on the text edit. |
def trimSegments(self, minPermanence=None, minNumSyns=None):
"""
Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.trimSegments`.
"""
# Fill in defaults
if minPermanence is None:
minPermanence = 0.0
if minNumSyns is None:
minNumSyns = 0
# Print all cells if verbos... | Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.trimSegments`. |
def is_greater_then_zero_bytes(self, path):
"""Return True if file <path> is greater than zero bytes in size, False otherwise"""
return self._getReturnCodeCmd([self._hadoop_cmd, 'fs', '-test', '-s', self._full_hdfs_path(path)]) == 0 | Return True if file <path> is greater than zero bytes in size, False otherwise |
def get_finder(import_path):
"""
Get a finder class from an import path.
Raises ``demosys.core.exceptions.ImproperlyConfigured`` if the finder is not found.
This function uses an lru cache.
:param import_path: string representing an import path
:return: An instance of the finder
"""
Fin... | Get a finder class from an import path.
Raises ``demosys.core.exceptions.ImproperlyConfigured`` if the finder is not found.
This function uses an lru cache.
:param import_path: string representing an import path
:return: An instance of the finder |
def G(w, Xs):
'''Calculate the G function given a cylinder direction w and a
list of data points Xs to be fitted.'''
n = len(Xs)
P = projection_matrix(w)
Ys = [np.dot(P, X) for X in Xs]
A = calc_A(Ys)
A_hat = calc_A_hat(A, skew_matrix(w))
u = sum(np.dot(Y, Y) for Y in Ys) / n
v... | Calculate the G function given a cylinder direction w and a
list of data points Xs to be fitted. |
def resolve(
requirements: typing.List[str],
index_urls: list = None,
python_version: int = 3,
exclude_packages: set = None,
transitive: bool = True,
subgraph_check_api: str = None,
) -> dict:
"""Resolve given requirements for the given Python version."""
assert python_version in (2, 3),... | Resolve given requirements for the given Python version. |
def remove_cache_tier(self, cache_pool):
"""
Removes a cache tier from Ceph. Flushes all dirty objects from writeback pools and waits for that to complete.
:param cache_pool: six.string_types. The cache tier pool name to remove.
:return: None
"""
# read-only is easy, wr... | Removes a cache tier from Ceph. Flushes all dirty objects from writeback pools and waits for that to complete.
:param cache_pool: six.string_types. The cache tier pool name to remove.
:return: None |
def Geldart_Ling(mp, rhog, D, mug):
r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_ and [3]_.
if Gs/D < 47000, use equation 1, otherwise use equation 2.
.. math::
V_{salt} = 1.5G_s^{0.465}D^{-0.01} \mu^{0.055}\rho_f^{-0.42}
... | r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_ and [3]_.
if Gs/D < 47000, use equation 1, otherwise use equation 2.
.. math::
V_{salt} = 1.5G_s^{0.465}D^{-0.01} \mu^{0.055}\rho_f^{-0.42}
V_{salt} = 8.7G_s^{0.302}D^{0.153} \mu^{... |
def _handle_task(self):
"""Pass request info to the async framework."""
headers = self.request.headers
message = None
try:
status_code, output = process_async_task(
headers, self.request.body)
except AbortAndRestart as restart:
# Async ret... | Pass request info to the async framework. |
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the Locate response payload to a buffer.
Args:
output_buffer (stream): A data buffer in which to encode object
data, supporting a write method.
kmip_versi... | Write the data encoding the Locate response payload to a buffer.
Args:
output_buffer (stream): A data buffer in which to encode object
data, supporting a write method.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the obj... |
def _ir_cum2(self, alpha=1.0):
code, _ = self.encode()
N = self.n_states
BL = np.zeros(N - 1) # BL is the block length of compror codewords
h0 = np.log2(np.cumsum(
[1.0 if sfx == 0 else 0.0 for sfx in self.sfx[1:]])
)
"""
h1 = np.array([h if m == 0 ... | h1 = np.array([h if m == 0 else h+np.log2(m)
for h,m in zip(h0,self.lrs[1:])])
h1 = np.array([h if m == 0 else h+np.log2(m)
for h,m in zip(h0,self.max_lrs[1:])])
h1 = np.array([h if m == 0 else h+np.log2(m)
for h,m in zip(h0,self.av... |
async def slowlog_get(self, num=None):
"""
Get the entries from the slowlog. If ``num`` is specified, get the
most recent ``num`` items.
"""
args = ['SLOWLOG GET']
if num is not None:
args.append(num)
return await self.execute_command(*args) | Get the entries from the slowlog. If ``num`` is specified, get the
most recent ``num`` items. |
def put(self, item, block=True, **kws):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
... | Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available wi... |
def prepend(self, node):
"""Prepend a statement to the current statement.
Note that multiple calls to prepend will result in the last statement to be
prepended to end up at the top.
Args:
node: The statement to prepend.
Raises:
ValueError: If the given node is not a statement.
""... | Prepend a statement to the current statement.
Note that multiple calls to prepend will result in the last statement to be
prepended to end up at the top.
Args:
node: The statement to prepend.
Raises:
ValueError: If the given node is not a statement. |
def update_defaults(self, defaults):
"""Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists)."""
# Then go and look for the other sources of configuration:
config = {}
# 1. config... | Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists). |
def list_subnets(auth=None, **kwargs):
'''
List subnets
filters
A Python dictionary of filter conditions to push down
CLI Example:
.. code-block:: bash
salt '*' neutronng.list_subnets
salt '*' neutronng.list_subnets \
filters='{"tenant_id": "1dcac318a83b4610b7a7... | List subnets
filters
A Python dictionary of filter conditions to push down
CLI Example:
.. code-block:: bash
salt '*' neutronng.list_subnets
salt '*' neutronng.list_subnets \
filters='{"tenant_id": "1dcac318a83b4610b7a7f7ba01465548"}' |
def use_isolated_objective_bank_view(self):
"""Pass through to provider ObjectiveLookupSession.use_isolated_objective_bank_view"""
self._objective_bank_view = ISOLATED
# self._get_provider_session('objective_lookup_session') # To make sure the session is tracked
for session in self._get_... | Pass through to provider ObjectiveLookupSession.use_isolated_objective_bank_view |
def nlmsg_append(n, data, len_, pad):
"""Append data to tail of a Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L442
Extends the Netlink message as needed and appends the data of given length to the message.
Positional arguments:
n -- Netlink message (nl_msg class i... | Append data to tail of a Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L442
Extends the Netlink message as needed and appends the data of given length to the message.
Positional arguments:
n -- Netlink message (nl_msg class instance).
data -- data to add.
len_ -... |
def ck_portf_004(self):
''' 價走平一個半月。(箱型整理、盤整) '''
return self.a.SD < 0.25 and self.a.stock_vol[-1] > 1000*1000 and self.a.raw_data[-1] > 10 | 價走平一個半月。(箱型整理、盤整) |
def collect(since, to, top=DEFAULT_TOP):
"""Collect the CSP report.
@returntype: CspReportSummary
"""
summary = CspReportSummary(since, to, top=top)
queryset = CSPReport.objects.filter(created__range=(since, to))
valid_queryset = queryset.filter(is_valid=True)
invalid_queryset = queryset.fi... | Collect the CSP report.
@returntype: CspReportSummary |
def mfe(self, strand, degenerate=False, temp=37.0, pseudo=False,
material=None, dangles='some', sodium=1.0, magnesium=0.0):
'''Compute the MFE for an ordered complex of strands. Runs the \'mfe\'
command.
:param strand: Strand on which to run mfe. Strands must be either
... | Compute the MFE for an ordered complex of strands. Runs the \'mfe\'
command.
:param strand: Strand on which to run mfe. Strands must be either
coral.DNA or coral.RNA).
:type strand: coral.DNA or coral.RNA
:param degenerate: Setting to True will result in returning... |
def build_machine_type(cls, min_cores, min_ram):
"""Returns a custom machine type string."""
min_cores = min_cores or job_model.DEFAULT_MIN_CORES
min_ram = min_ram or job_model.DEFAULT_MIN_RAM
# First, min_ram is given in GB. Convert to MB.
min_ram *= GoogleV2CustomMachine._MB_PER_GB
# Only ma... | Returns a custom machine type string. |
def cli(env, context_id):
"""Request configuration of a tunnel context.
This action will update the advancedConfigurationFlag on the context
instance and further modifications against the context will be prevented
until all changes can be propgated to network devices.
"""
manager = SoftLayer.IP... | Request configuration of a tunnel context.
This action will update the advancedConfigurationFlag on the context
instance and further modifications against the context will be prevented
until all changes can be propgated to network devices. |
def add_user_to_group(self, group_name, user_name):
"""
Add a user to a group
:type group_name: string
:param group_name: The name of the group
:type user_name: string
:param user_name: The to be added to the group.
"""
params = {'GroupName' : group_nam... | Add a user to a group
:type group_name: string
:param group_name: The name of the group
:type user_name: string
:param user_name: The to be added to the group. |
def all(self, data={}, **kwargs):
""""
Fetch all Settlement entities
Returns:
Dictionary of Settlement data
"""
return super(Settlement, self).all(data, **kwargs) | Fetch all Settlement entities
Returns:
Dictionary of Settlement data |
def update(self, E=None, **F):
"""
Update ContextDict from dict/iterable E and F
:return: Nothing
:rtype: None
"""
if E is not None:
if hasattr(E, 'keys'):
for K in E:
self.replace(K, E[K])
elif hasattr(E, 'items... | Update ContextDict from dict/iterable E and F
:return: Nothing
:rtype: None |
def search_alert_for_facets(self, **kwargs): # noqa: E501
"""Lists the values of one or more facets over the customer's non-deleted alerts # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=T... | Lists the values of one or more facets over the customer's non-deleted alerts # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.search_alert_for_facets(async_req=True)
... |
def reduce_data_frame_evenly_with_gaps (df, valcol, target_len, maxgap, **kwargs):
""""Reduce" a DataFrame by collapsing rows in grouped chunks, grouping based on
gaps in one of the columns.
This function combines :func:`reduce_data_frame` with
:func:`slice_evenly_with_gaps`.
"""
return reduce... | Reduce" a DataFrame by collapsing rows in grouped chunks, grouping based on
gaps in one of the columns.
This function combines :func:`reduce_data_frame` with
:func:`slice_evenly_with_gaps`. |
def _get_entity_prop(self, entity, prop):
"""
returns Wikidata entity property value
"""
variant = self.params.get('variant')
lang = self.params.get('lang')
if entity.get(prop):
ent = entity[prop]
try:
return ent[variant or lang].g... | returns Wikidata entity property value |
def validate_items(all_items):
"""Find errors in the schedule. Check for:
- pending / rejected talks in the schedule
- items with both talks and pages assigned
- items with neither talks nor pages assigned
"""
validation = []
for item in all_items:
if item.talk is... | Find errors in the schedule. Check for:
- pending / rejected talks in the schedule
- items with both talks and pages assigned
- items with neither talks nor pages assigned |
def get_viewer_names(self, dataobj):
"""Returns a list of viewer names that are registered that
can view `dataobj`.
"""
res = []
for bnch in self.viewer_db.values():
for vtype in bnch.vtypes:
if isinstance(dataobj, vtype):
res.appen... | Returns a list of viewer names that are registered that
can view `dataobj`. |
def update(self):
""" Update all local variable names to match OnShape. """
uri = self.parent.uri
script = r"""
function(context, queries) {
return getVariable(context, "measurements");
}
"""
self.res = c.evaluate_featurescript(uri.as_dict(), script) | Update all local variable names to match OnShape. |
def instruments(
self,
accountID,
**kwargs
):
"""
Get the list of tradeable instruments for the given Account. The list
of tradeable instruments is dependent on the regulatory division that
the Account is located in, thus should be the same for all Accounts
... | Get the list of tradeable instruments for the given Account. The list
of tradeable instruments is dependent on the regulatory division that
the Account is located in, thus should be the same for all Accounts
owned by a single user.
Args:
accountID:
Account Id... |
def delete_policy(vhost, name, runas=None):
'''
Delete a policy based on rabbitmqctl clear_policy.
Reference: http://www.rabbitmq.com/ha.html
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.delete_policy / HA
'''
if runas is None and not salt.utils.platform.is_windows():
... | Delete a policy based on rabbitmqctl clear_policy.
Reference: http://www.rabbitmq.com/ha.html
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.delete_policy / HA |
def timed_for(iterable,
name=None,
rgstr_stamps=None,
save_itrs=SET['SI'],
loop_end_stamp=None,
end_stamp_unique=SET['UN'],
keep_prev_subdivisions=SET['KS'],
keep_end_subdivisions=SET['KS'],
quick_print=SET['... | Instantiate a TimedLoop object for measuring for loop iteration timing data.
Can be used only on for loops.
Example::
for i in gtimer.timed_for(iterable, ..):
<body of loop with gtimer stamps>
Notes:
Can be used as a context manager around the loop. When breaking out of
... |
def _spectrum(self, photon_energy):
"""
Compute differential spectrum from pp interactions using Eq.71 and
Eq.58 of Kelner, S.R., Aharonian, F.A., and Bugayov, V.V., 2006
PhysRevD 74, 034018 (`arXiv:astro-ph/0606058
<http://www.arxiv.org/abs/astro-ph/0606058>`_).
Paramet... | Compute differential spectrum from pp interactions using Eq.71 and
Eq.58 of Kelner, S.R., Aharonian, F.A., and Bugayov, V.V., 2006
PhysRevD 74, 034018 (`arXiv:astro-ph/0606058
<http://www.arxiv.org/abs/astro-ph/0606058>`_).
Parameters
----------
photon_energy : :class:`~... |
def gap(lamda, sigma, mode='individual'):
"""Compute spectral gap.
Useful for eigenvalue/eigenvector bounds. Computes the gap
:math:`\delta\geq 0` between two sets of real numbers ``lamda`` and
``sigma``. The gap can be computed in several ways and may not exist, see
the ``mode`` parameter.
:p... | Compute spectral gap.
Useful for eigenvalue/eigenvector bounds. Computes the gap
:math:`\delta\geq 0` between two sets of real numbers ``lamda`` and
``sigma``. The gap can be computed in several ways and may not exist, see
the ``mode`` parameter.
:param lamda: a non-empty set
:math:`\Lambda=... |
def partitions(device=""):
"""
Get a partition list for all disk or for selected device only
Example::
from burlap.disk import partitions
spart = {'Linux': 0x83, 'Swap': 0x82}
parts = partitions()
# parts = {'/dev/sda1': 131, '/dev/sda2': 130, '/dev/sda3': 131}
r ... | Get a partition list for all disk or for selected device only
Example::
from burlap.disk import partitions
spart = {'Linux': 0x83, 'Swap': 0x82}
parts = partitions()
# parts = {'/dev/sda1': 131, '/dev/sda2': 130, '/dev/sda3': 131}
r = parts['/dev/sda1'] == spart['Linux']
... |
def pack(self, out: IO):
"""
Write the FieldTable to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `w... | Write the FieldTable to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write()` |
def to_naf(self):
"""
Converts the layer from NAF to KAF
"""
if self.type == 'KAF':
for node in self.__get_entity_nodes():
node.set('id',node.get('eid'))
del node.attrib['eid'] | Converts the layer from NAF to KAF |
def create_header(self):
""" return header dict """
try:
self.check_valid()
_header_list = []
for k,v in self.inputs.items():
if v is None:
return {self.__class__.__name__.replace('_','-'):None}
elif k == 'value':
_header_list.insert(0,str(v))
elif isinstance(v,bool):
if v is Tr... | return header dict |
def run(state, command, args):
"""Spawns a command installed into the virtualenv."""
from ..core import do_run
do_run(
command=command, args=args, three=state.three, python=state.python, pypi_mirror=state.pypi_mirror
) | Spawns a command installed into the virtualenv. |
def order_status(self, order_id):
"""
Returns dictionary.
- status: 'Finished'
or 'In Queue'
or 'Open'
- transactions: list of transactions
Each transaction is a dictionary with the following keys:
btc, usd, price, type, fee, datetime... | Returns dictionary.
- status: 'Finished'
or 'In Queue'
or 'Open'
- transactions: list of transactions
Each transaction is a dictionary with the following keys:
btc, usd, price, type, fee, datetime, tid
or btc, eur, ....
or eur, ... |
def cos(cls, x: 'TensorFluent') -> 'TensorFluent':
'''Returns a TensorFluent for the cos function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the cos function.
'''
return cls._unary_op(x, tf.cos, tf.float32) | Returns a TensorFluent for the cos function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the cos function. |
def wrap_application(application, before_run, on_start, shutdown):
"""
Wrap a tornado application in a callback-aware wrapper.
:param tornado.web.Application application: application to wrap.
:param list|NoneType before_run: optional list of callbacks
to invoke before the IOLoop is started.
... | Wrap a tornado application in a callback-aware wrapper.
:param tornado.web.Application application: application to wrap.
:param list|NoneType before_run: optional list of callbacks
to invoke before the IOLoop is started.
:param list|NoneType on_start: optional list of callbacks to
register ... |
def execute_work(self, key, command):
"""
Executes command received and stores result state in queue.
:param key: the key to identify the TI
:type key: tuple(dag_id, task_id, execution_date)
:param command: the command to execute
:type command: str
"""
if ... | Executes command received and stores result state in queue.
:param key: the key to identify the TI
:type key: tuple(dag_id, task_id, execution_date)
:param command: the command to execute
:type command: str |
def parse(cls, datestr):
"""Parse <DATE> string and make :py:class:`CalendarDate` from it.
:param str datestr: String with GEDCOM date.
"""
m = DATE_RE.match(datestr)
if m is not None:
day = None if m.group(2) is None else int(m.group(2))
return cls(m.gro... | Parse <DATE> string and make :py:class:`CalendarDate` from it.
:param str datestr: String with GEDCOM date. |
def _init_seqarray(self, quiet=False):
"""
Fills the seqarr with the full data set, and creates a bootsarr copy
with the following modifications:
1) converts "-" into "N"s, since they are similarly treated as missing.
2) randomly resolve ambiguities (RSKWYM)
3) convert... | Fills the seqarr with the full data set, and creates a bootsarr copy
with the following modifications:
1) converts "-" into "N"s, since they are similarly treated as missing.
2) randomly resolve ambiguities (RSKWYM)
3) convert to uint8 for smaller memory load and faster computation |
def matchToFeatures(fiContainer, specContainer, specfiles=None, fMassKey='mz',
sMassKey='obsMz', isotopeErrorList=(0),
precursorTolerance=5, toleranceUnit='ppm',
rtExpansionUp=0.10, rtExpansionDown=0.05, matchCharge=True,
scoreKey='pep', la... | Annotate :class:`Fi <maspy.core.Fi>` (Feature items) by matching
:class:`Si <maspy.core.Si>` (Spectrum items) or :class:`Sii
<maspy.core.Sii>` (Spectrum identification items).
:param fiContainer: :class:`maspy.core.FeatureContainer`, contains ``Fi``.
:param specContainer: :class:`maspy.core.MsrunContai... |
def search_obsgroups(self, search):
"""
Search for :class:`meteorpi_model.ObservationGroup` entities
:param search:
an instance of :class:`meteorpi_model.ObservationGroupSearch` used to constrain the observations returned
from the DB
:return:
a struct... | Search for :class:`meteorpi_model.ObservationGroup` entities
:param search:
an instance of :class:`meteorpi_model.ObservationGroupSearch` used to constrain the observations returned
from the DB
:return:
a structure of {count:int total rows of an unrestricted search, ... |
def watch_crc(params, ctxt, scope, stream, coord):
"""WatchCrc32 - Watch the total crc32 of the params.
Example:
The code below uses the ``WatchCrc32`` update function to update
the ``crc`` field to the crc of the ``length`` and ``data`` fields ::
char length;
char ... | WatchCrc32 - Watch the total crc32 of the params.
Example:
The code below uses the ``WatchCrc32`` update function to update
the ``crc`` field to the crc of the ``length`` and ``data`` fields ::
char length;
char data[length];
int crc<watch=length;data, updat... |
def symm_reduce(self, coords_set, threshold=1e-6):
"""
Reduces the set of adsorbate sites by finding removing
symmetrically equivalent duplicates
Args:
coords_set: coordinate set in cartesian coordinates
threshold: tolerance for distance equivalence, used
... | Reduces the set of adsorbate sites by finding removing
symmetrically equivalent duplicates
Args:
coords_set: coordinate set in cartesian coordinates
threshold: tolerance for distance equivalence, used
as input to in_coord_list_pbc for dupl. checking |
def get_limits_for_pool(self, pool):
"""
meterer.get_limits_for_pool(pool) -> dict
Returns the limits for the given pool. If the pool does not have limits
set, {} is returned.
The resulting dict has the following format. Each item is optional and
indicates no limit for ... | meterer.get_limits_for_pool(pool) -> dict
Returns the limits for the given pool. If the pool does not have limits
set, {} is returned.
The resulting dict has the following format. Each item is optional and
indicates no limit for the specified time period.
{
"year": ... |
def strip_xext(filepath):
"""
Strips the compression extension from the filename
:param filepath: Path to compressed file.
:return str filepath: Path to the file with the compression extension stripped off.
"""
ext_size = len(file_xext(filepath).split('.')) - 1
for i in xrange(0, ext_size):
... | Strips the compression extension from the filename
:param filepath: Path to compressed file.
:return str filepath: Path to the file with the compression extension stripped off. |
def update(self, value=None):
"""
Update progress bar via the console or notebook accordingly.
"""
# Update self.value
if value is None:
value = self._current_value + 1
self._current_value = value
# Choose the appropriate environment
if self.... | Update progress bar via the console or notebook accordingly. |
def update_complex(tree_to_update, xpath_root, xpath_map, prop, values):
"""
Updates and returns the updated complex Element parsed from tree_to_update.
:param tree_to_update: the XML tree compatible with element_utils to be updated
:param xpath_root: the XPATH location of the root of the complex Elemen... | Updates and returns the updated complex Element parsed from tree_to_update.
:param tree_to_update: the XML tree compatible with element_utils to be updated
:param xpath_root: the XPATH location of the root of the complex Element
:param xpath_map: a Dictionary of XPATHs corresponding to the complex structure... |
def _getue(self):
"""Return data as unsigned exponential-Golomb code.
Raises InterpretError if bitstring is not a single exponential-Golomb code.
"""
try:
value, newpos = self._readue(0)
if value is None or newpos != self.len:
raise ReadError
... | Return data as unsigned exponential-Golomb code.
Raises InterpretError if bitstring is not a single exponential-Golomb code. |
def grant(self, fail_on_found=False, **kwargs):
"""Add a user or a team to a role. Required information:
1) Type of the role
2) Resource of the role, inventory, credential, or any other
3) A user or a team to add to the role
=====API DOCS=====
Add a user or a team to a r... | Add a user or a team to a role. Required information:
1) Type of the role
2) Resource of the role, inventory, credential, or any other
3) A user or a team to add to the role
=====API DOCS=====
Add a user or a team to a role. Required information:
* Type of the role.
... |
def validate(self, obj, pointer=None):
"""
Validate object against validator
:param obj: the object to validate
"""
pointer = pointer or '#'
validator = deepcopy(self)
validator.errors = []
validator.fail_fast = False
obj = deepcopy(obj)
... | Validate object against validator
:param obj: the object to validate |
def get_images(config, name=None, quiet=False, all=True, *args, **kwargs):
'''
List docker images
:type name: string
:param name: A repository name to filter on
:type quiet: boolean
:param quiet: Only show image ids
:type all: boolean
:param all: Show all images
:rtype: dict
... | List docker images
:type name: string
:param name: A repository name to filter on
:type quiet: boolean
:param quiet: Only show image ids
:type all: boolean
:param all: Show all images
:rtype: dict
:returns: the images |
def _cached(f):
""" Decorator that makes a method cached."""
attr_name = '_cached_' + f.__name__
def wrapper(obj, *args, **kwargs):
if not hasattr(obj, attr_name):
setattr(obj, attr_name, f(obj, *args, **kwargs))
return getattr(obj, attr_name)
return wrapper | Decorator that makes a method cached. |
def grok_for_node(element, default_vars):
"""Properly parses a For loop element"""
if isinstance(element.iter, jinja2.nodes.Filter):
if element.iter.name == 'default' \
and element.iter.node.name not in default_vars:
default_vars.append(element.iter.node.name)
default_var... | Properly parses a For loop element |
def get_valid_indentations(self, idx):
"""Returns the valid offsets for the token at the given position."""
# The closing brace on a dict or the 'for' in a dict comprehension may
# reset two indent levels because the dict value is ended implicitly
stack_top = -1
if (
... | Returns the valid offsets for the token at the given position. |
def get_import_data_url(deployment_name,
token_manager=None,
app_url=defaults.APP_URL):
"""
return the import data url
"""
return get_data_url(deployment_name,
endpoint_type='http-import',
app_url=app_url,
... | return the import data url |
def analyze_overs(self1):
"""A helper function that prepares overlap and consecutive matches data"""
#check for full overlap first
self1.dif1 = [self1.overs[i][0]-self1.overs[i-1][0] for i in range(1,len(self1.overs))]
self1.dif2 = [self1.overs[i][1]-self1.overs[i-1][1] for i in range(1,len(self... | A helper function that prepares overlap and consecutive matches data |
def get_tags_of_reminder_per_page(self, reminder_id, per_page=1000, page=1):
"""
Get tags of reminder per page
:param reminder_id: the reminder id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
"""
... | Get tags of reminder per page
:param reminder_id: the reminder id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list |
def save_htmlid(html_id, skiplint=False):
""" Take a HTML ID, sanitise for HTML, check for duplicates and save.
Returns sanitised, unique ID """
global html_ids
global lint_errors
# Trailing whitespace
html_id_clean = html_id.strip()
# Trailing underscores
html_id_clean = html_id_clean... | Take a HTML ID, sanitise for HTML, check for duplicates and save.
Returns sanitised, unique ID |
def get_user_details(self, response):
""" Complete with additional information from original LTI POST data, as available. """
data = {}
# None of them is mandatory
data['id'] = response.get('user_id', None)
data['username'] = response.get('custom_username', None)
if not d... | Complete with additional information from original LTI POST data, as available. |
def from_py_func(cls, code):
''' Create a ``CustomJSHover`` instance from a Python functions. The
function is translated to JavaScript using PScript.
The python functions must have no positional arguments. It is
possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword
... | Create a ``CustomJSHover`` instance from a Python functions. The
function is translated to JavaScript using PScript.
The python functions must have no positional arguments. It is
possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword
arguments to the functions.
... |
def extract(self, searches, tree=None, as_dict=True):
"""
>>> foo = pdf.extract([['pages', 'LTPage']])
>>> foo
{'pages': [<LTPage>, <LTPage>]}
>>> pdf.extract([['bar', ':in_bbox("100,100,400,400")']], foo['pages'][0])
{'bar': [<LTTextLineHorizont... | >>> foo = pdf.extract([['pages', 'LTPage']])
>>> foo
{'pages': [<LTPage>, <LTPage>]}
>>> pdf.extract([['bar', ':in_bbox("100,100,400,400")']], foo['pages'][0])
{'bar': [<LTTextLineHorizontal>, <LTTextBoxHorizontal>,... |
def visit_insert(self, insert_stmt, asfrom=False, **kw):
"""
used to compile <sql.expression.Insert> expressions.
this function wraps insert_from_select statements inside
parentheses to be conform with earlier versions of CreateDB.
"""
self.stack.append(
{'... | used to compile <sql.expression.Insert> expressions.
this function wraps insert_from_select statements inside
parentheses to be conform with earlier versions of CreateDB. |
def sortino_ratio(returns,
required_return=0,
period=DAILY,
annualization=None,
out=None,
_downside_risk=None):
"""
Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.n... | Determines the Sortino ratio of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray or pd.DataFrame
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
required_return: float / series
minimum acceptable re... |
def tmpfile(root=TEMPS_DIR, prefix=TEMPS_PREFIX, suffix=TEMPS_SUFFIX):
'''
For use in a with statement, this function returns a context manager that
yields a path directly under root guaranteed to be unique by using the uuid
module. This path is not created. However if the path is an existing file
... | For use in a with statement, this function returns a context manager that
yields a path directly under root guaranteed to be unique by using the uuid
module. This path is not created. However if the path is an existing file
when the with statement is exited, the file will be removed.
This function is... |
def list_subtitles(self, video, languages):
"""List subtitles.
:param video: video to list subtitles for.
:type video: :class:`~subliminal.video.Video`
:param languages: languages to search for.
:type languages: set of :class:`~babelfish.language.Language`
:return: found... | List subtitles.
:param video: video to list subtitles for.
:type video: :class:`~subliminal.video.Video`
:param languages: languages to search for.
:type languages: set of :class:`~babelfish.language.Language`
:return: found subtitles.
:rtype: list of :class:`~subliminal... |
def get_hash_for(self, value):
"""Get hash for a given value.
:param value: The value to be indexed
:type value: object
:return: Hashed value
:rtype: str
"""
if isinstance(value,dict) and '__ref__' in value:
return self.get_hash_for(value['__ref__'])... | Get hash for a given value.
:param value: The value to be indexed
:type value: object
:return: Hashed value
:rtype: str |
def sign(self, encoded):
""" Return authentication signature of encoded bytes """
signature = self._hmac.copy()
signature.update(encoded)
return signature.hexdigest().encode('utf-8') | Return authentication signature of encoded bytes |
def _include_paths_from_environ(env_prefix=''):
"""Environment value via `/login;/register`"""
paths = os.environ.get(env_prefix + 'WSGI_AUTH_PATHS')
if not paths:
return []
return paths.split(';') | Environment value via `/login;/register` |
def command(name=None, cls=None, **attrs):
"""A decorator that transforms a function into a :class:`.Command`
or if called with :func:`.group`, :class:`.Group`.
By default the ``help`` attribute is received automatically from the
docstring of the function and is cleaned up with the use of
``inspect... | A decorator that transforms a function into a :class:`.Command`
or if called with :func:`.group`, :class:`.Group`.
By default the ``help`` attribute is received automatically from the
docstring of the function and is cleaned up with the use of
``inspect.cleandoc``. If the docstring is ``bytes``, then i... |
def value(self, key, default=None):
"""
Returns the value for the given key for this settings instance.
:return <variant>
"""
if self._customFormat:
return self._customFormat.value(key, default)
else:
return unwrapVariant(supe... | Returns the value for the given key for this settings instance.
:return <variant> |
def rm_pawn(self, name, *args):
"""Remove the :class:`Pawn` by the given name."""
if name not in self.pawn:
raise KeyError("No Pawn named {}".format(name))
# Currently there's no way to connect Pawns with Arrows but I
# think there will be, so, insurance
self.rm_arrow... | Remove the :class:`Pawn` by the given name. |
def emit_pdf(outputs, options):
'''Runs the PDF conversion command to generate the PDF.'''
cmd = options.pdf_cmd
cmd = cmd.replace('%o', options.pdfname)
if len(outputs) > 2:
cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...']))
else:
cmd_print = cmd.replace('%i', ' '.join... | Runs the PDF conversion command to generate the PDF. |
def anm_score(self, x, y):
"""Compute the fitness score of the ANM model in the x->y direction.
Args:
a (numpy.ndarray): Variable seen as cause
b (numpy.ndarray): Variable seen as effect
Returns:
float: ANM fit score
"""
gp = GaussianProcessR... | Compute the fitness score of the ANM model in the x->y direction.
Args:
a (numpy.ndarray): Variable seen as cause
b (numpy.ndarray): Variable seen as effect
Returns:
float: ANM fit score |
def _declarations_as_string(self, declarations):
"""
Returns a list of declarations as a formatted CSS string
:param declarations: The list of tinycss Declarations to format
:type declarations: list of tinycss.css21.Declaration
:returns: The CSS string for the declarations list
... | Returns a list of declarations as a formatted CSS string
:param declarations: The list of tinycss Declarations to format
:type declarations: list of tinycss.css21.Declaration
:returns: The CSS string for the declarations list
:rtype: str |
def _run_custom_data_engine(self, start_id_obj, end_id_obj, start_timeperiod, end_timeperiod):
""" fine-tuned data engine. MongoDB legacy """
collection_name = context.process_context[self.process_name].source
iteration = 0
while True:
cursor = self.ds.cursor_fine(collection_... | fine-tuned data engine. MongoDB legacy |
def disvec(self, x, y, aq=None):
'''Returns array of size (2, nparam, naq)'''
if aq is None: aq = self.model.aq.find_aquifer_data(x, y)
return np.sum(self.parameters * self.disvecinf(x, y, aq), 1) | Returns array of size (2, nparam, naq) |
def compose(self, type, data):
"""Compose text as a format.
:param type: The unique name of the format
:param data: The text to compose as the format
"""
try:
return self.registered_formats[type]['composer'](data)
except KeyError:
raise NotImpleme... | Compose text as a format.
:param type: The unique name of the format
:param data: The text to compose as the format |
def is_pigalle_class(kls: ClassVar) -> bool:
""" Return true if the passed object as argument is a class being to the Pigalle framework.
# Arguments
kls: The class to check.
# Returns:
bool:
* True if class is Pigalle.
* False else.
... | Return true if the passed object as argument is a class being to the Pigalle framework.
# Arguments
kls: The class to check.
# Returns:
bool:
* True if class is Pigalle.
* False else. |
def _index_document(self, document, force=False):
""" Adds parition document to the index. """
from ambry.util import int_maybe
time_coverage = document.pop('time_coverage', [])
from_year = None
to_year = None
if time_coverage:
from_year = int_maybe(time_cover... | Adds parition document to the index. |
def add_params_to_qs(query, params):
"""Extend a query with a list of two-tuples."""
if isinstance(params, dict):
params = params.items()
queryparams = urlparse.parse_qsl(query, keep_blank_values=True)
queryparams.extend(params)
return urlencode(queryparams) | Extend a query with a list of two-tuples. |
async def add_relation(self, local_relation, remote_relation):
"""Add a relation to another application.
:param str local_relation: Name of relation on this application
:param str remote_relation: Name of relation on the other
application in the form '<application>[:<relation_name>]... | Add a relation to another application.
:param str local_relation: Name of relation on this application
:param str remote_relation: Name of relation on the other
application in the form '<application>[:<relation_name>]' |
def set_device(self, dev):
"""
set the current device (that will be used for following API calls)
:param dict dev: device that should be used for the API calls
(can be obtained via get_devices function)
"""
log.debug("setting device to '{}'".format(dev))... | set the current device (that will be used for following API calls)
:param dict dev: device that should be used for the API calls
(can be obtained via get_devices function) |
def getCallSourceLines(callFrame, icNames, icMethod):
"""Raises NoSourceAvailableError."""
code = callFrame.f_code
# inspect.getblock(), which is called internally by inspect.getsource(),
# only returns the first line of <code> when <code> represents a top-level
# module, not the entire module's so... | Raises NoSourceAvailableError. |
def save_schedule(self):
'''
Save the current schedule
'''
self.persist()
# Fire the complete event back along with the list of schedule
evt = salt.utils.event.get_event('minion', opts=self.opts, listen=False)
evt.fire_event({'complete': True},
... | Save the current schedule |
def get_collection(self, folderid, username="", offset=0, limit=10):
"""Fetch collection folder contents
:param folderid: UUID of the folder to list
:param username: The user to list folders for, if omitted the authenticated user is used
:param offset: the pagination offset
:pa... | Fetch collection folder contents
:param folderid: UUID of the folder to list
:param username: The user to list folders for, if omitted the authenticated user is used
:param offset: the pagination offset
:param limit: the pagination limit |
def create_application(connection: Optional[str] = None) -> Flask:
"""Create a Flask application."""
app = Flask(__name__)
flask_bootstrap.Bootstrap(app)
Admin(app)
connection = connection or DEFAULT_CACHE_CONNECTION
engine, session = build_engine_session(connection)
for name, add_admin i... | Create a Flask application. |
def do_setup(self, arg, arguments):
"""
::
Usage:
setup init [--force]
Copies a cmd3.yaml file into ~/.cloudmesh/cmd3.yaml
"""
if arguments["init"]:
Console.ok("Initialize cmd3.yaml file")
from cmd3.yaml_setup import create... | ::
Usage:
setup init [--force]
Copies a cmd3.yaml file into ~/.cloudmesh/cmd3.yaml |
def get_Sb(data):
"""
returns vgp scatter for data set
"""
Sb, N = 0., 0.
for rec in data:
delta = 90. - abs(rec['vgp_lat'])
if rec['average_k'] != 0:
k = rec['average_k']
L = rec['average_lat'] * np.pi / 180. # latitude in radians
Nsi = rec['aver... | returns vgp scatter for data set |
def save(self, path):
"""Save a binary copy of this report
Args:
path (string): The path where we should save the binary copy of the report
"""
data = self.encode()
with open(path, "wb") as out:
out.write(data) | Save a binary copy of this report
Args:
path (string): The path where we should save the binary copy of the report |
def _save(self):
"""Saves the current state of this AssessmentTaken.
Should be called every time the sections map changes.
"""
collection = JSONClientValidated('assessment',
collection='AssessmentTaken',
... | Saves the current state of this AssessmentTaken.
Should be called every time the sections map changes. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.