code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def handle_msec_timestamp(self, m, master):
'''special handling for MAVLink packets with a time_boot_ms field'''
if m.get_type() == 'GLOBAL_POSITION_INT':
# this is fix time, not boot time
return
msec = m.time_boot_ms
if msec + 30000 < master.highest_msec:
... | special handling for MAVLink packets with a time_boot_ms field |
def atanh(x, context=None):
"""
Return the inverse hyperbolic tangent of x.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_atanh,
(BigFloat._implicit_convert(x),),
context,
) | Return the inverse hyperbolic tangent of x. |
def mode_str_to_int(modestr):
"""
:param modestr: string like 755 or 644 or 100644 - only the last 6 chars will be used
:return:
String identifying a mode compatible to the mode methods ids of the
stat module regarding the rwx permissions for user, group and other,
special flags and ... | :param modestr: string like 755 or 644 or 100644 - only the last 6 chars will be used
:return:
String identifying a mode compatible to the mode methods ids of the
stat module regarding the rwx permissions for user, group and other,
special flags and file system flags, i.e. whether it is a sy... |
def regex_find(pattern, content):
"""Find the given 'pattern' in 'content'"""
find = re.findall(pattern, content)
if not find:
cij.err("pattern <%r> is invalid, no matches!" % pattern)
cij.err("content: %r" % content)
return ''
if len(find) >= 2:
cij.err("pattern <%r> i... | Find the given 'pattern' in 'content |
def update(self, *args, **kwargs):
'''Preserves order if given an assoc list.
'''
arg = dict_arg(*args, **kwargs)
if isinstance(arg, list):
for key, val in arg:
self[key] = val
else:
super(AssocDict, self).update(arg) | Preserves order if given an assoc list. |
def directive(self, name, default=None):
"""Returns the loaded directive with the specified name, or default if passed name is not present"""
return getattr(self, '_directives', {}).get(name, hug.defaults.directives.get(name, default)) | Returns the loaded directive with the specified name, or default if passed name is not present |
def update_server_map(self, config):
"""update server_map ({member_id:hostname})"""
self.server_map = dict([(member['_id'], member['host']) for member in config['members']]) | update server_map ({member_id:hostname}) |
def create_queue(self, queue_name, queue=None, fail_on_exist=False):
'''
Creates a new queue. Once created, this queue's resource manifest is
immutable.
queue_name:
Name of the queue to create.
queue:
Queue object to create.
fail_on_exist:
... | Creates a new queue. Once created, this queue's resource manifest is
immutable.
queue_name:
Name of the queue to create.
queue:
Queue object to create.
fail_on_exist:
Specify whether to throw an exception when the queue exists. |
def dedent(s):
"""Removes the hanging dedent from all the first line of a string."""
head, _, tail = s.partition('\n')
dedented_tail = textwrap.dedent(tail)
result = "{head}\n{tail}".format(
head=head,
tail=dedented_tail)
return result | Removes the hanging dedent from all the first line of a string. |
def msg2agent(msg, processor=None, legacy=False, **config):
""" Return the single username who is the "agent" for an event.
An "agent" is the one responsible for the event taking place, for example,
if one person gives karma to another, then both usernames are returned by
msg2usernames, but only the on... | Return the single username who is the "agent" for an event.
An "agent" is the one responsible for the event taking place, for example,
if one person gives karma to another, then both usernames are returned by
msg2usernames, but only the one who gave the karma is returned by
msg2agent.
If the proce... |
def rate_limit_info():
""" Returns (requests_remaining, minutes_to_reset) """
import json
import time
r = requests.get(gh_url + "/rate_limit", auth=login.auth())
out = json.loads(r.text)
mins = (out["resources"]["core"]["reset"]-time.time())/60
return out["resources"]["core"]["remaining"], ... | Returns (requests_remaining, minutes_to_reset) |
async def on_message(message):
"""The on_message event handler for this module
Args:
message (discord.Message): Input message
"""
# Simplify message info
server = message.server
author = message.author
channel = message.channel
content = message.content
data = datatools.ge... | The on_message event handler for this module
Args:
message (discord.Message): Input message |
def stop(self):
""" Stops the video stream and resets the clock. """
logger.debug("Stopping playback")
# Stop the clock
self.clock.stop()
# Set plauyer status to ready
self.status = READY | Stops the video stream and resets the clock. |
def _tobytes(self, skipprepack = False):
'''
Convert the struct to bytes. This is the standard way to convert a NamedStruct to bytes.
:param skipprepack: if True, the prepack stage is skipped. For parser internal use.
:returns: converted bytes
'''
stream... | Convert the struct to bytes. This is the standard way to convert a NamedStruct to bytes.
:param skipprepack: if True, the prepack stage is skipped. For parser internal use.
:returns: converted bytes |
def from_json(cls, data):
"""Return object based on JSON / dict input
Args:
data (dict): Dictionary containing a serialized User object
Returns:
:obj:`User`: User object representing the data
"""
user = cls()
user.user_id = data['userId']
... | Return object based on JSON / dict input
Args:
data (dict): Dictionary containing a serialized User object
Returns:
:obj:`User`: User object representing the data |
def get_normalized(self):
"""Returns a vector of unit length, unless it is the zero
vector, in which case it is left as is."""
magnitude = self.get_magnitude()
if magnitude > 0:
magnitude = 1.0 / magnitude
return Point(self.x * magnitude, self.y * magnitude)
... | Returns a vector of unit length, unless it is the zero
vector, in which case it is left as is. |
def fix_e702(self, result, logical):
"""Put semicolon-separated compound statement on separate lines."""
if not logical:
return [] # pragma: no cover
logical_lines = logical[2]
# Avoid applying this when indented.
# https://docs.python.org/reference/compound_stmts.h... | Put semicolon-separated compound statement on separate lines. |
def set_mode(self,mode):
"""Set SPI mode which controls clock polarity and phase. Should be a
numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
"""
if mode < 0 or mode > 3:
raise Valu... | Set SPI mode which controls clock polarity and phase. Should be a
numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus |
def _norm_perm_list_from_perm_dict(self, perm_dict):
"""Return a minimal, ordered, hashable list of subjects and permissions."""
high_perm_dict = self._highest_perm_dict_from_perm_dict(perm_dict)
return [
[k, list(sorted(high_perm_dict[k]))]
for k in ORDERED_PERM_LIST
... | Return a minimal, ordered, hashable list of subjects and permissions. |
def isObjectClassified(self, objectName, minOverlap=None, maxL2Size=None):
"""
Return True if objectName is currently unambiguously classified by every L2
column. Classification is correct and unambiguous if the current L2 overlap
with the true object is greater than minOverlap and if the size of the L2... | Return True if objectName is currently unambiguously classified by every L2
column. Classification is correct and unambiguous if the current L2 overlap
with the true object is greater than minOverlap and if the size of the L2
representation is no more than maxL2Size
:param minOverlap: min overlap to co... |
def is_date_type(cls):
"""Return True if the class is a date type."""
if not isinstance(cls, type):
return False
return issubclass(cls, date) and not issubclass(cls, datetime) | Return True if the class is a date type. |
def _from_pointer(pointer, incref):
"""Wrap an existing :c:type:`cairo_font_face_t *` cdata pointer.
:type incref: bool
:param incref:
Whether increase the :ref:`reference count <refcounting>` now.
:return:
A new instance of :class:`FontFace` or one of its sub-cl... | Wrap an existing :c:type:`cairo_font_face_t *` cdata pointer.
:type incref: bool
:param incref:
Whether increase the :ref:`reference count <refcounting>` now.
:return:
A new instance of :class:`FontFace` or one of its sub-classes,
depending on the face’s type... |
def ansible_inventory_temp_file(
self, keys=['vm-type', 'groups', 'vm-provider']
):
"""
Context manager which returns Ansible inventory written on a tempfile.
This is the same as :func:`~ansible_inventory`, only the inventory file
is written to a tempfile.
Args:
... | Context manager which returns Ansible inventory written on a tempfile.
This is the same as :func:`~ansible_inventory`, only the inventory file
is written to a tempfile.
Args:
keys (list of str): Path to the keys that will be used to
create groups.
Yields:
... |
def _deserialize_key(cls, key):
"""
:type key: str
:rtype: str
"""
if key in cls._KEYS_OVERLAPPING:
return key + cls._SUFFIX_KEY_OVERLAPPING
return key | :type key: str
:rtype: str |
def from_scalars(**kwargs):
"""Similar to from_arrays, but convenient for a DataFrame of length 1.
Example:
>>> import vaex
>>> df = vaex.from_scalars(x=1, y=2)
:rtype: DataFrame
"""
import numpy as np
return from_arrays(**{k: np.array([v]) for k, v in kwargs.items()}) | Similar to from_arrays, but convenient for a DataFrame of length 1.
Example:
>>> import vaex
>>> df = vaex.from_scalars(x=1, y=2)
:rtype: DataFrame |
def _is_dtype_type(arr_or_dtype, condition):
"""
Return a boolean if the condition is satisfied for the arr_or_dtype.
Parameters
----------
arr_or_dtype : array-like
The array-like or dtype object whose dtype we want to extract.
condition : callable[Union[np.dtype, ExtensionDtypeType]]
... | Return a boolean if the condition is satisfied for the arr_or_dtype.
Parameters
----------
arr_or_dtype : array-like
The array-like or dtype object whose dtype we want to extract.
condition : callable[Union[np.dtype, ExtensionDtypeType]]
Returns
-------
bool : if the condition is s... |
def hira2kata(text, ignore=''):
"""Convert Hiragana to Full-width (Zenkaku) Katakana.
Parameters
----------
text : str
Hiragana string.
ignore : str
Characters to be ignored in converting.
Return
------
str
Katakana string.
Examples
--------
>>> pri... | Convert Hiragana to Full-width (Zenkaku) Katakana.
Parameters
----------
text : str
Hiragana string.
ignore : str
Characters to be ignored in converting.
Return
------
str
Katakana string.
Examples
--------
>>> print(jaconv.hira2kata('ともえまみ'))
トモエマミ... |
def makescacoldesc(columnname, value,
datamanagertype='',
datamanagergroup='',
options=0, maxlen=0, comment='',
valuetype='', keywords={}):
"""Create description of a scalar column.
A description for a scalar column can be created from... | Create description of a scalar column.
A description for a scalar column can be created from a name for
the column and a data value, which is used only to determine the
type of the column. Note that a dict value is also possible.
It is possible to create the column description in more detail
by gi... |
def process_sels(self):
"""
Process soft clause selectors participating in a new core.
The negation :math:`\\neg{s}` of each selector literal
:math:`s` participating in the unsatisfiable core is added
to the list of relaxation literals, which will be later
... | Process soft clause selectors participating in a new core.
The negation :math:`\\neg{s}` of each selector literal
:math:`s` participating in the unsatisfiable core is added
to the list of relaxation literals, which will be later
used to create a new totalizer object in
... |
def get_class(self):
"""Return a Code class based on current ErrorType value.
Returns:
enum.IntEnum: class referenced by current error type.
"""
classes = {'OFPET_HELLO_FAILED': HelloFailedCode,
'OFPET_BAD_REQUEST': BadRequestCode,
'OFP... | Return a Code class based on current ErrorType value.
Returns:
enum.IntEnum: class referenced by current error type. |
def with_fakes(method):
"""Decorator that calls :func:`fudge.clear_calls` before method() and :func:`fudge.verify` afterwards.
"""
@wraps(method)
def apply_clear_and_verify(*args, **kw):
clear_calls()
method(*args, **kw)
verify() # if no exceptions
return apply_clear_and_veri... | Decorator that calls :func:`fudge.clear_calls` before method() and :func:`fudge.verify` afterwards. |
def _value_to_color(value, cmap):
"""Convert a value in the range [0,1] to an RGB tuple using a colormap."""
cm = plt.get_cmap(cmap)
rgba = cm(value)
return [int(round(255*v)) for v in rgba[0:3]] | Convert a value in the range [0,1] to an RGB tuple using a colormap. |
def base_geodetic_crs(self):
"""The :class:`GeodeticCRS` on which this projection is based."""
base = self.element.find(GML_NS + 'baseGeodeticCRS')
href = base.attrib[XLINK_NS + 'href']
return get(href) | The :class:`GeodeticCRS` on which this projection is based. |
def get_subresource_path_by(resource, subresource_path):
"""Helper function to find the resource path
:param resource: ResourceBase instance from which the path is loaded.
:param subresource_path: JSON field to fetch the value from.
Either a string, or a list of strings in case of a nested fiel... | Helper function to find the resource path
:param resource: ResourceBase instance from which the path is loaded.
:param subresource_path: JSON field to fetch the value from.
Either a string, or a list of strings in case of a nested field.
It should also include the '@odata.id'
:raise... |
def _get_format_from_style(self, token, style):
""" Returns a QTextCharFormat for token by reading a Pygments style.
"""
result = QtGui.QTextCharFormat()
items = list(style.style_for_token(token).items())
for key, value in items:
if value is None and key == 'color':
... | Returns a QTextCharFormat for token by reading a Pygments style. |
def adjoin(space: int, *lists: Sequence[str]) -> str:
"""Glue together two sets of strings using `space`."""
lengths = [max(map(len, x)) + space for x in lists[:-1]]
# not the last one
lengths.append(max(map(len, lists[-1])))
max_len = max(map(len, lists))
chains = (
itertools.chain(
... | Glue together two sets of strings using `space`. |
def subjects(auth, label=None, project=None):
'''
Retrieve Subject tuples for subjects returned by this function.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.subjects(auth, 'AB1234C')
Subject(uri=u'/data/experi... | Retrieve Subject tuples for subjects returned by this function.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.subjects(auth, 'AB1234C')
Subject(uri=u'/data/experiments/XNAT_S0001', label=u'AB1234C', id=u'XNAT_S0001',
... |
def add_vec_to_mat(mat, vec, axis=None, inplace=False,
target=None, substract=False):
""" Add a vector to a matrix
"""
assert mat.flags.c_contiguous
if axis is None:
if vec.shape[0] == mat.shape[0]:
axis = 0
elif vec.shape[0] == mat.shape[1]:
... | Add a vector to a matrix |
def import_or_die(module_name, entrypoint_names):
'''
Import user code; return reference to usercode function.
(str) -> function reference
'''
log_debug("Importing {}".format(module_name))
module_name = os.path.abspath(module_name)
if module_name.endswith('.py'):
module_name,ext = o... | Import user code; return reference to usercode function.
(str) -> function reference |
def _compute_std_dev(self, X):
"""Computes the standard deviation of a Gaussian Distribution with mean vector X[i]"""
self._sigma = []
if X.shape[0] <= 1:
self._sigma = [0.0]
else:
for x_mean in range(X.shape[0]):
std_dev = np.sqrt(sum([np.linalg.... | Computes the standard deviation of a Gaussian Distribution with mean vector X[i] |
def click_partial_link_text(self, partial_link_text,
timeout=settings.SMALL_TIMEOUT):
""" This method clicks the partial link text on a page. """
# If using phantomjs, might need to extract and open the link directly
if self.timeout_multiplier and timeout == setti... | This method clicks the partial link text on a page. |
def bind(self, fn: "Callable[[Any], Reader]") -> 'Reader':
r"""Bind a monadic function to the Reader.
Haskell:
Reader: m >>= k = Reader $ \r -> runReader (k (runReader m r)) r
Function: h >>= f = \w -> f (h w) w
"""
return Reader(lambda x: fn(self.run(x)).run(x)) | r"""Bind a monadic function to the Reader.
Haskell:
Reader: m >>= k = Reader $ \r -> runReader (k (runReader m r)) r
Function: h >>= f = \w -> f (h w) w |
def add_markdown_cell(self, text):
"""Add a markdown cell to the notebook
Parameters
----------
code : str
Cell content
"""
markdown_cell = {
"cell_type": "markdown",
"metadata": {},
"source": [rst2md(text)]
}
... | Add a markdown cell to the notebook
Parameters
----------
code : str
Cell content |
def mouseReleaseEvent(self, event):
"""
Emits mouse_released signal.
:param event: QMouseEvent
"""
initial_state = event.isAccepted()
event.ignore()
self.mouse_released.emit(event)
if not event.isAccepted():
event.setAccepted(initial_state)
... | Emits mouse_released signal.
:param event: QMouseEvent |
def make_wcs_data_from_hpx_data(self, hpx_data, wcs, normalize=True):
""" Creates and fills a wcs map from the hpx data using the pre-calculated
mappings
hpx_data : the input HEALPix data
wcs : the WCS object
normalize : True -> perserve integral by splitting HEALPix valu... | Creates and fills a wcs map from the hpx data using the pre-calculated
mappings
hpx_data : the input HEALPix data
wcs : the WCS object
normalize : True -> perserve integral by splitting HEALPix values between bins |
def concurrent_slots(slots):
"""
Yields all concurrent slot indices.
"""
for i, slot in enumerate(slots):
for j, other_slot in enumerate(slots[i + 1:]):
if slots_overlap(slot, other_slot):
yield (i, j + i + 1) | Yields all concurrent slot indices. |
def dot (self, other):
"""dot (self, other) -> number
Returns the dot product of this Point with another.
"""
if self.z:
return (self.x * other.x) + (self.y * other.y) + (self.z * other.z)
else:
return (self.x * other.x) + (self.y * other.y) | dot (self, other) -> number
Returns the dot product of this Point with another. |
def yaw_pitch_roll(self):
"""Get the equivalent yaw-pitch-roll angles aka. intrinsic Tait-Bryan angles following the z-y'-x'' convention
Returns:
yaw: rotation angle around the z-axis in radians, in the range `[-pi, pi]`
pitch: rotation angle around the y'-axis in radians, i... | Get the equivalent yaw-pitch-roll angles aka. intrinsic Tait-Bryan angles following the z-y'-x'' convention
Returns:
yaw: rotation angle around the z-axis in radians, in the range `[-pi, pi]`
pitch: rotation angle around the y'-axis in radians, in the range `[-pi/2, -pi/2]`
... |
def ellipsize(s, max_length=60):
"""
>>> print(ellipsize(u'lorem ipsum dolor sit amet', 40))
lorem ipsum dolor sit amet
>>> print(ellipsize(u'lorem ipsum dolor sit amet', 20))
lorem ipsum dolor...
"""
if len(s) > max_length:
ellipsis = '...'
return s[:(max_length - len(ellips... | >>> print(ellipsize(u'lorem ipsum dolor sit amet', 40))
lorem ipsum dolor sit amet
>>> print(ellipsize(u'lorem ipsum dolor sit amet', 20))
lorem ipsum dolor... |
def matches(self, txt: str) -> bool:
"""Determine whether txt matches pattern
:param txt: text to check
:return: True if match
"""
# rval = ref.getText()[1:-1].encode('utf-8').decode('unicode-escape')
if r'\\u' in self.pattern_re.pattern:
txt = txt.encode('ut... | Determine whether txt matches pattern
:param txt: text to check
:return: True if match |
def list(cls, path):
"""Return a list containing the names of the entries in the directory
given by path. The list is in arbitrary order.
"""
file_info = cls.parse_remote(path)
connection = cls.connect(path)
bucket = connection.get_bucket(file_info.bucket)
region ... | Return a list containing the names of the entries in the directory
given by path. The list is in arbitrary order. |
def closeEvent(self, event):
"""Send last file signal on close event
:param event: The close event
:type event:
:returns: None
:rtype: None
:raises: None
"""
lf = self.browser.get_current_selection()
if lf:
self.last_file.emit(lf)
... | Send last file signal on close event
:param event: The close event
:type event:
:returns: None
:rtype: None
:raises: None |
def get_remote_file(url):
"""
Wrapper around ``request.get`` which nicely handles connection errors
"""
try:
return requests.get(url)
except requests.exceptions.ConnectionError as e:
print("Connection error!")
print(e.message.reason)
exit(1) | Wrapper around ``request.get`` which nicely handles connection errors |
def delete_thing(self, lid):
"""Delete a Thing
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
i... | Delete a Thing
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
if there is a communications problem betw... |
def affine(self, pixelbuffer=0):
"""
Return an Affine object of tile.
- pixelbuffer: tile buffer in pixels
"""
return Affine(
self.pixel_x_size,
0,
self.bounds(pixelbuffer).left,
0,
-self.pixel_y_size,
self.... | Return an Affine object of tile.
- pixelbuffer: tile buffer in pixels |
def validateDtd(self, doc, dtd):
"""Try to validate the document against the dtd instance
Basically it does check all the definitions in the DtD.
Note the the internal subset (if present) is de-coupled
(i.e. not used), which could give problems if ID or IDREF
is present.... | Try to validate the document against the dtd instance
Basically it does check all the definitions in the DtD.
Note the the internal subset (if present) is de-coupled
(i.e. not used), which could give problems if ID or IDREF
is present. |
def process_order(self, order):
"""Keep track of an order that was placed.
Parameters
----------
order : zp.Order
The order to record.
"""
try:
dt_orders = self._orders_by_modified[order.dt]
except KeyError:
self._orders_by_mod... | Keep track of an order that was placed.
Parameters
----------
order : zp.Order
The order to record. |
def jwt_get_secret_key(payload=None):
"""
For enchanced security you may use secret key on user itself.
This way you have an option to logout only this user if:
- token is compromised
- password is changed
- etc.
"""
User = get_user_model() # noqa
if api_settings.JWT_GET... | For enchanced security you may use secret key on user itself.
This way you have an option to logout only this user if:
- token is compromised
- password is changed
- etc. |
def auto_directory(rel_name):
"""
if you're using py.path you make do that as:
py.path.local(full_path).ensure_dir()
"""
dir_name = rel_path(rel_name, check=False)
if not os.path.exists(dir_name):
os.makedirs(dir_name, exist_ok=True)
return dir_name | if you're using py.path you make do that as:
py.path.local(full_path).ensure_dir() |
def create_participant(worker_id, hit_id, assignment_id, mode):
"""Create a participant.
This route is hit early on. Any nodes the participant creates will be
defined in reference to the participant object. You must specify the
worker_id, hit_id, assignment_id, and mode in the url.
"""
# Lock t... | Create a participant.
This route is hit early on. Any nodes the participant creates will be
defined in reference to the participant object. You must specify the
worker_id, hit_id, assignment_id, and mode in the url. |
def dusk(self, date=None, local=True, use_elevation=True):
"""Calculates the dusk time (the time in the evening when the sun is a
certain number of degrees below the horizon. By default this is 6
degrees but can be changed by setting the
:attr:`solar_depression` property.)
:para... | Calculates the dusk time (the time in the evening when the sun is a
certain number of degrees below the horizon. By default this is 6
degrees but can be changed by setting the
:attr:`solar_depression` property.)
:param date: The date for which to calculate the dusk time.
... |
def _clear_dict(endpoint_props):
'''
Eliminates None entries from the features of the endpoint dict.
'''
return dict(
(prop_name, prop_val)
for prop_name, prop_val in six.iteritems(endpoint_props)
if prop_val is not None
) | Eliminates None entries from the features of the endpoint dict. |
def allowed(self, method, _dict, allow):
"""
Only these items are allowed in the dictionary
"""
for key in _dict.keys():
if key not in allow:
raise LunrError("'%s' is not an argument for method '%s'"
% (key, method)) | Only these items are allowed in the dictionary |
def matrix_rank(a, tol=None, validate_args=False, name=None):
"""Compute the matrix rank; the number of non-zero SVD singular values.
Arguments:
a: (Batch of) `float`-like matrix-shaped `Tensor`(s) which are to be
pseudo-inverted.
tol: Threshold below which the singular value is counted as "zero".
... | Compute the matrix rank; the number of non-zero SVD singular values.
Arguments:
a: (Batch of) `float`-like matrix-shaped `Tensor`(s) which are to be
pseudo-inverted.
tol: Threshold below which the singular value is counted as "zero".
Default value: `None` (i.e., `eps * max(rows, cols) * max(singu... |
def get_aggs(self):
"""
Compute the values for single valued aggregations
:returns: the single aggregation value
"""
res = self.fetch_aggregation_results()
if 'aggregations' in res and 'values' in res['aggregations'][str(self.parent_agg_counter - 1)]:
try:
... | Compute the values for single valued aggregations
:returns: the single aggregation value |
def run(self, options):
"""
.. todo::
check network connection
:param Namespace options: parse result from argparse
:return:
"""
self.logger.debug("debug enabled...")
depends = ['git']
nil_tools = []
self.logger.info("depends list: ... | .. todo::
check network connection
:param Namespace options: parse result from argparse
:return: |
def _set_ospf(self, v, load=False):
"""
Setter method for ospf, mapped from YANG variable /rbridge_id/ipv6/router/ospf (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ospf is considered as a private
method. Backends looking to populate this variable should
... | Setter method for ospf, mapped from YANG variable /rbridge_id/ipv6/router/ospf (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ospf is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_ospf() directly. |
def join(self, timeout=None):
"""block until this thread terminates
.. note::
this method can block the calling coroutine if the thread has not
yet completed.
:param timeout:
the maximum time to wait. with the default of ``None``, waits
indefini... | block until this thread terminates
.. note::
this method can block the calling coroutine if the thread has not
yet completed.
:param timeout:
the maximum time to wait. with the default of ``None``, waits
indefinitely
:type timeout: int, float or... |
def addComponentEditor(self):
"""Adds a new component to the model, and an editor for this component to this editor"""
row = self._model.rowCount()
comp_stack_editor = ExploreComponentEditor()
self.ui.trackStack.addWidget(comp_stack_editor)
idx_button = IndexButton(row)
... | Adds a new component to the model, and an editor for this component to this editor |
def get_queryset(self, request):
"""
Returns a QuerySet of all model instances that can be edited by the
admin site.
"""
qs = self.model._default_manager.get_queryset()
ordering = self.get_ordering(request)
if ordering:
qs = qs.order_by(*ordering)
... | Returns a QuerySet of all model instances that can be edited by the
admin site. |
def get_sequence(self):
"""Get the sequence number for a given account via Horizon.
:return: The current sequence number for a given account
:rtype: int
"""
if not self.address:
raise StellarAddressInvalidError('No address provided.')
address = self.horizon.... | Get the sequence number for a given account via Horizon.
:return: The current sequence number for a given account
:rtype: int |
def run(self, lines):
"""Filter method"""
ret = []
for line in lines:
while True:
match = re.search(r'\[(.*?)\]\((.*?\.md)\)', line)
if match != None:
title = match.group(1)
line = re.sub(r'\[.*?\]\(.*?\.md\)', t... | Filter method |
def unpack_results(
data: bytes,
repetitions: int,
key_sizes: Sequence[Tuple[str, int]]
) -> Dict[str, np.ndarray]:
"""Unpack data from a bitstring into individual measurement results.
Args:
data: Packed measurement results, in the form <rep0><rep1>...
where each rep... | Unpack data from a bitstring into individual measurement results.
Args:
data: Packed measurement results, in the form <rep0><rep1>...
where each repetition is <key0_0>..<key0_{size0-1}><key1_0>...
with bits packed in little-endian order in each byte.
repetitions: number of r... |
def print_struct(struct, ident=0):
"""
>>> from ctypes import *
>>> class Test(Structure):
... _fields_ = [('foo', c_int)]
...
>>> class Test2(Structure):
... _fields_ = [('foo', Test), ('bar', c_int)]
...
>>> t = Test2()
>>> t.foo.foo = 2
>>> t.bar = 1
>>> prin... | >>> from ctypes import *
>>> class Test(Structure):
... _fields_ = [('foo', c_int)]
...
>>> class Test2(Structure):
... _fields_ = [('foo', Test), ('bar', c_int)]
...
>>> t = Test2()
>>> t.foo.foo = 2
>>> t.bar = 1
>>> print_struct(t)
foo:
foo: 2
bar: 1 |
def height(self):
"""Terminal height.
"""
if self.interactive:
if self._height is None:
self._height = self.term.height
return self._height | Terminal height. |
def move_user_data(primary, secondary):
'''
Moves all submissions and other data linked to the secondary user into the primary user.
Nothing is deleted here, we just modify foreign user keys.
'''
# Update all submission authorships of the secondary to the primary
submissions = Submission... | Moves all submissions and other data linked to the secondary user into the primary user.
Nothing is deleted here, we just modify foreign user keys. |
def convert_bool(string):
"""Check whether string is boolean.
"""
if string == 'True':
return True, True
elif string == 'False':
return True, False
else:
return False, False | Check whether string is boolean. |
def compose_suffix(num_docs=0, num_topics=0, suffix=None):
"""Create a short, informative, but not-so-unique identifying string for a trained model
If a str suffix is provided then just pass it through.
>>> compose_suffix(num_docs=100, num_topics=20)
'_100X20'
>>> compose_suffix(suffix='_sfx')
'... | Create a short, informative, but not-so-unique identifying string for a trained model
If a str suffix is provided then just pass it through.
>>> compose_suffix(num_docs=100, num_topics=20)
'_100X20'
>>> compose_suffix(suffix='_sfx')
'_sfx'
>>> compose_suffix(suffix='')
''
>>> compose_suf... |
def _write_coco_results(self, _coco, detections):
""" example results
[{"image_id": 42,
"category_id": 18,
"bbox": [258.15,41.29,348.26,243.78],
"score": 0.236}, ...]
"""
cats = [cat['name'] for cat in _coco.loadCats(_coco.getCatIds())]
class_to_coco... | example results
[{"image_id": 42,
"category_id": 18,
"bbox": [258.15,41.29,348.26,243.78],
"score": 0.236}, ...] |
def fshdev(k):
"""
Generate a random draw from a Fisher distribution with mean declination
of 0 and inclination of 90 with a specified kappa.
Parameters
----------
k : kappa (precision parameter) of the distribution
k can be a single number or an array of values
Returns
-------... | Generate a random draw from a Fisher distribution with mean declination
of 0 and inclination of 90 with a specified kappa.
Parameters
----------
k : kappa (precision parameter) of the distribution
k can be a single number or an array of values
Returns
----------
dec, inc : declinat... |
def export_to(self, appliance, location):
"""Exports the machine to an OVF appliance. See :py:class:`IAppliance` for the
steps required to export VirtualBox machines to OVF.
in appliance of type :class:`IAppliance`
Appliance to export this machine to.
in location of type s... | Exports the machine to an OVF appliance. See :py:class:`IAppliance` for the
steps required to export VirtualBox machines to OVF.
in appliance of type :class:`IAppliance`
Appliance to export this machine to.
in location of type str
The target location.
return d... |
def cat(
self,
source,
buffersize=None,
memsize=2 ** 24,
compressed=False,
encoding='UTF-8',
raw=False,
):
"""
Returns an iterator for the data in the key or nothing if the key
doesn't exist. Decompresses data on the fly (if compressed ... | Returns an iterator for the data in the key or nothing if the key
doesn't exist. Decompresses data on the fly (if compressed is True
or key ends with .gz) unless raw is True. Pass None for encoding to
skip encoding. |
def edit(self, entry, name, mark=False):
"""
Edit an entry (file or directory)
:param entry: :class:`.BaseFile` object
:param str name: new name for the entry
:param bool mark: whether to bookmark the entry
"""
fcid = None
if isinstance(entry, File):
... | Edit an entry (file or directory)
:param entry: :class:`.BaseFile` object
:param str name: new name for the entry
:param bool mark: whether to bookmark the entry |
def create_default_users_and_perms():
"""
Adds the roles and perm to the DB. It adds only roles, perms and links between them that are not inside the db
It is possible adding new role or perm and connecting them just modifiying the following lists
"""
# perms = db.DBSession.query(Perm).all(... | Adds the roles and perm to the DB. It adds only roles, perms and links between them that are not inside the db
It is possible adding new role or perm and connecting them just modifiying the following lists |
def version(self):
"""
Return the version number of the Lending Club Investor tool
Returns
-------
string
The version number string
"""
this_path = os.path.dirname(os.path.realpath(__file__))
version_file = os.path.join(this_path, 'VERSION')
... | Return the version number of the Lending Club Investor tool
Returns
-------
string
The version number string |
def _decompress_dicom(dicom_file, output_file):
"""
This function can be used to convert a jpeg compressed image to an uncompressed one for further conversion
:param input_file: single dicom file to decompress
"""
gdcmconv_executable = _get_gdcmconv()
subprocess.check_output([gdcmconv_executab... | This function can be used to convert a jpeg compressed image to an uncompressed one for further conversion
:param input_file: single dicom file to decompress |
def create_segments(self, segments):
"""Enqueue segment creates"""
for segment in segments:
s_res = MechResource(segment['id'], a_const.SEGMENT_RESOURCE,
a_const.CREATE)
self.provision_queue.put(s_res) | Enqueue segment creates |
def pyephem_earthsun_distance(time):
"""
Calculates the distance from the earth to the sun using pyephem.
Parameters
----------
time : pd.DatetimeIndex
Returns
-------
pd.Series. Earth-sun distance in AU.
"""
import ephem
sun = ephem.Sun()
earthsun = []
for thetim... | Calculates the distance from the earth to the sun using pyephem.
Parameters
----------
time : pd.DatetimeIndex
Returns
-------
pd.Series. Earth-sun distance in AU. |
def get_max(array):
"""Get maximum value of an array. Automatically ignore invalid data.
**中文文档**
获得最大值。
"""
largest = -np.inf
for i in array:
try:
if i > largest:
largest = i
except:
pass
if np.isinf(largest):
raise ValueErro... | Get maximum value of an array. Automatically ignore invalid data.
**中文文档**
获得最大值。 |
def _check_convergence(current_position,
next_position,
current_objective,
next_objective,
next_gradient,
grad_tolerance,
f_relative_tolerance,
x_tolerance):
... | Checks if the algorithm satisfies the convergence criteria. |
def _decode_image(fobj, session, filename):
"""Reads and decodes an image from a file object as a Numpy array.
The SUN dataset contains images in several formats (despite the fact that
all of them have .jpg extension). Some of them are:
- BMP (RGB)
- PNG (grayscale, RGBA, RGB interlaced)
- JPEG (RGB)... | Reads and decodes an image from a file object as a Numpy array.
The SUN dataset contains images in several formats (despite the fact that
all of them have .jpg extension). Some of them are:
- BMP (RGB)
- PNG (grayscale, RGBA, RGB interlaced)
- JPEG (RGB)
- GIF (1-frame RGB)
Since TFDS assumes tha... |
def get_simulated_data(nmr_problems):
"""Simulate some data.
This returns the simulated tank observations and the corresponding ground truth maximum number of tanks.
Args:
nmr_problems (int): the number of problems
Returns:
tuple: (observations, nmr_tanks_ground_truth)
"""
# T... | Simulate some data.
This returns the simulated tank observations and the corresponding ground truth maximum number of tanks.
Args:
nmr_problems (int): the number of problems
Returns:
tuple: (observations, nmr_tanks_ground_truth) |
def get_instance(page_to_consume):
"""Return an instance of ConsumePage."""
global _instances
if isinstance(page_to_consume, basestring):
uri = page_to_consume
page_to_consume = page.get_instance(uri)
elif isinstance(page_to_consume, page.Page):
uri = page_to_consume.uri
else... | Return an instance of ConsumePage. |
def _map_update_posterior(self):
"""Maximum A Posterior (MAP) update of HTFA parameters
Returns
-------
HTFA
Returns the instance itself.
"""
self.global_posterior_ = self.global_prior_.copy()
prior_centers = self.get_centers(self.global_prior_)
... | Maximum A Posterior (MAP) update of HTFA parameters
Returns
-------
HTFA
Returns the instance itself. |
def delete_all(self):
'''Deletes all feature collections.
This does not destroy the ES index, but instead only
deletes all FCs with the configured document type
(defaults to ``fc``).
'''
try:
self.conn.indices.delete_mapping(
index=self.index,... | Deletes all feature collections.
This does not destroy the ES index, but instead only
deletes all FCs with the configured document type
(defaults to ``fc``). |
def highpass(cutoff):
"""
This strategy uses an exponential approximation for cut-off frequency
calculation, found by matching the one-pole Laplace lowpass filter
and mirroring the resulting filter to get a highpass.
"""
R = thub(exp(cutoff - pi), 2)
return (1 - R) / (1 + R * z ** -1) | This strategy uses an exponential approximation for cut-off frequency
calculation, found by matching the one-pole Laplace lowpass filter
and mirroring the resulting filter to get a highpass. |
def fit_df(self, labels, dfs, pstate_col=PSTATE_COL):
"""
Fit the classifier with labels y and DataFrames dfs
"""
assert len(labels) == len(dfs)
for label in set(labels):
label_dfs = [s for l,s in zip(labels, dfs) if l == label]
pohmm = self.pohmm_factor... | Fit the classifier with labels y and DataFrames dfs |
def _request(self, url, params={}):
"""Makes a request using the currently open session.
:param url: A url fragment to use in the creation of the master url
"""
r = self._session.get(url=url, params=params, headers=DEFAULT_ORIGIN)
return r | Makes a request using the currently open session.
:param url: A url fragment to use in the creation of the master url |
def cross_entropy_error(self, input_data, targets, average=True,
cache=None, prediction=False,
sum_errors=True):
""" Computes the cross-entropy error for all tasks.
"""
loss = []
if cache is None:
cache = self.n_tasks *... | Computes the cross-entropy error for all tasks. |
def install(cls, uninstallable, prefix, path_items, root=None, warning=None):
"""Install an importer for modules found under ``path_items`` at the given import ``prefix``.
:param bool uninstallable: ``True`` if the installed importer should be uninstalled and any
imports it perfo... | Install an importer for modules found under ``path_items`` at the given import ``prefix``.
:param bool uninstallable: ``True`` if the installed importer should be uninstalled and any
imports it performed be un-imported when ``uninstall`` is called.
:param str prefix: The import p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.