code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def generate(self):
"""
Generates the report
"""
self._setup()
header_html = self._generate_header()
footer_html = self._generate_footer()
results_topbar_html = self._generate_topbar("results")
summary_topbar_html = self._generate_topbar("summary")
logs_topbar_html = self._generate_... | Generates the report |
def update(self, validate=False):
"""
Update the DB instance's status information by making a call to fetch
the current instance attributes from the service.
:type validate: bool
:param validate: By default, if EC2 returns no data about the
instance the ... | Update the DB instance's status information by making a call to fetch
the current instance attributes from the service.
:type validate: bool
:param validate: By default, if EC2 returns no data about the
instance the update method returns quietly. If
... |
def add_account_alias(self, account, alias):
"""
:param account: an account object to be used as a selector
:param alias: email alias address
:returns: None (the API itself returns nothing)
"""
self.request('AddAccountAlias', {
'id': self._get_or_... | :param account: an account object to be used as a selector
:param alias: email alias address
:returns: None (the API itself returns nothing) |
def get_api_name(self, func):
"""e.g. Convert 'do_work' to 'Do Work'"""
words = func.__name__.split('_')
words = [w.capitalize() for w in words]
return ' '.join(words) | e.g. Convert 'do_work' to 'Do Work |
def delete(group_id):
"""Delete group."""
group = Group.query.get_or_404(group_id)
if group.can_edit(current_user):
try:
group.delete()
except Exception as e:
flash(str(e), "error")
return redirect(url_for(".index"))
flash(_('Successfully removed... | Delete group. |
def remote_property(name, get_command, set_command, field_name, doc=None):
"""Property decorator that facilitates writing properties for values from a remote device.
Arguments:
name: The field name to use on the local object to store the cached property.
get_command: A function that returns the rem... | Property decorator that facilitates writing properties for values from a remote device.
Arguments:
name: The field name to use on the local object to store the cached property.
get_command: A function that returns the remote value of the property.
set_command: A function that accepts a new value ... |
def _get_host_details(self):
"""Get the system details."""
# Assuming only one system present as part of collection,
# as we are dealing with iLO's here.
status, headers, system = self._rest_get('/rest/v1/Systems/1')
if status < 300:
stype = self._get_type(system)
... | Get the system details. |
def __push_symbol(self, symbol):
'''Ask the websocket for a symbol push. Gets instrument, orderBook, quote, and trade'''
self.__send_command("getSymbol", symbol)
while not {'instrument', 'trade', 'orderBook25'} <= set(self.data):
sleep(0.1) | Ask the websocket for a symbol push. Gets instrument, orderBook, quote, and trade |
def astype(self, col_dtypes, **kwargs):
"""Converts columns dtypes to given dtypes.
Args:
col_dtypes: Dictionary of {col: dtype,...} where col is the column
name and dtype is a numpy dtype.
Returns:
DataFrame with updated dtypes.
"""
# Gr... | Converts columns dtypes to given dtypes.
Args:
col_dtypes: Dictionary of {col: dtype,...} where col is the column
name and dtype is a numpy dtype.
Returns:
DataFrame with updated dtypes. |
def raise_for_response(self, responses):
"""
Constructs appropriate exception from list of responses and raises it.
"""
exception_messages = [self.client.format_exception_message(response) for response in responses]
if len(exception_messages) == 1:
message = exception... | Constructs appropriate exception from list of responses and raises it. |
def retry(self):
"""No connection to device, retry connection after 15 seconds."""
self.stream = None
self.config.loop.call_later(RETRY_TIMER, self.start)
_LOGGER.debug('Reconnecting to %s', self.config.host) | No connection to device, retry connection after 15 seconds. |
def _find_binary(binary=None):
"""Find the absolute path to the GnuPG binary.
Also run checks that the binary is not a symlink, and check that
our process real uid has exec permissions.
:param str binary: The path to the GnuPG binary.
:raises: :exc:`~exceptions.RuntimeError` if it appears that Gnu... | Find the absolute path to the GnuPG binary.
Also run checks that the binary is not a symlink, and check that
our process real uid has exec permissions.
:param str binary: The path to the GnuPG binary.
:raises: :exc:`~exceptions.RuntimeError` if it appears that GnuPG is not
installed.
... |
def open_submission(self):
"""
Open the full submission and comment tree for the selected comment.
"""
url = self.get_selected_item().get('submission_permalink')
if url:
self.selected_page = self.open_submission_page(url) | Open the full submission and comment tree for the selected comment. |
def add_data(self, minimum_address, maximum_address, data, overwrite):
"""Add given data to this segment. The added data must be adjacent to
the current segment data, otherwise an exception is thrown.
"""
if minimum_address == self.maximum_address:
self.maximum_address = ma... | Add given data to this segment. The added data must be adjacent to
the current segment data, otherwise an exception is thrown. |
def _Authenticate(self):
"""Authenticates the user.
The authentication process works as follows:
1) We get a username and password from the user
2) We use ClientLogin to obtain an AUTH token for the user
(see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
3) We pass the auth token to /_... | Authenticates the user.
The authentication process works as follows:
1) We get a username and password from the user
2) We use ClientLogin to obtain an AUTH token for the user
(see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
3) We pass the auth token to /_ah/login on the server to obta... |
def CopyDirectory(source_dir, target_dir, override=False):
'''
Recursively copy a directory tree.
:param unicode source_dir:
Where files will come from
:param unicode target_dir:
Where files will go to
:param bool override:
If True and target_dir already exists, it will be... | Recursively copy a directory tree.
:param unicode source_dir:
Where files will come from
:param unicode target_dir:
Where files will go to
:param bool override:
If True and target_dir already exists, it will be deleted before copying.
:raises NotImplementedForRemotePathError:... |
def add_predicate(self, pred_obj):
"""
Adds a predicate object to the layer
@type pred_obj: L{Cpredicate}
@param pred_obj: the predicate object
"""
pred_id = pred_obj.get_id()
if not pred_id in self.idx:
pred_node = pred_obj.get_node()
self... | Adds a predicate object to the layer
@type pred_obj: L{Cpredicate}
@param pred_obj: the predicate object |
def plotMultipleInferenceRun(stats,
fields,
basename,
plotDir="plots"):
"""
Plots individual inference runs.
"""
if not os.path.exists(plotDir):
os.makedirs(plotDir)
plt.figure()
colorList = ['r', 'b', 'g', 'm', 'c', 'k', 'y']
# p... | Plots individual inference runs. |
def init(celf, *, loop = None, unregister = None, message = None) :
"for consistency with other classes that don’t want caller to instantiate directly."
return \
celf \
(
loop = loop,
unregister = unregister,
message = message,
... | for consistency with other classes that don’t want caller to instantiate directly. |
def LE32(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''32-bit field, Little endian encoded'''
return UInt32(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_LE, fuzzable=fuzzable, name=name, full_range=full_range) | 32-bit field, Little endian encoded |
def make_client(zhmc, userid=None, password=None):
"""
Create a `Session` object for the specified HMC and log that on. Create a
`Client` object using that `Session` object, and return it.
If no userid and password are specified, and if no previous call to this
method was made, userid and password ... | Create a `Session` object for the specified HMC and log that on. Create a
`Client` object using that `Session` object, and return it.
If no userid and password are specified, and if no previous call to this
method was made, userid and password are interactively inquired.
Userid and password are saved i... |
def _buildTemplates(self):
"""
do all the things necessary to build the viz
should be adapted to work for single-file viz, or multi-files etc.
:param output_path:
:return:
"""
# in this case we only have one
contents = self._renderTemplate(self.template_... | do all the things necessary to build the viz
should be adapted to work for single-file viz, or multi-files etc.
:param output_path:
:return: |
def loadModel(self, model_file):
"""load q table from model_file"""
with open(model_file) as f:
self.q_table = json.load(f) | load q table from model_file |
def showGrid( self ):
"""
Returns whether or not this delegate should draw its grid lines.
:return <bool>
"""
delegate = self.itemDelegate()
if ( isinstance(delegate, XTreeWidgetDelegate) ):
return delegate.showGrid()
return False | Returns whether or not this delegate should draw its grid lines.
:return <bool> |
def copy(self):
"""
Make deep copy of this KeyBundle
:return: The copy
"""
kb = KeyBundle()
kb._keys = self._keys[:]
kb.cache_time = self.cache_time
kb.verify_ssl = self.verify_ssl
if self.source:
kb.source = self.source
k... | Make deep copy of this KeyBundle
:return: The copy |
def change_axis(self, axis_num, channel_name):
"""
TODO: refactor that and set_axes
what to do with ax?
axis_num: int
axis number
channel_name: str
new channel to plot on that axis
"""
current_channels = list(self.current_channels)
i... | TODO: refactor that and set_axes
what to do with ax?
axis_num: int
axis number
channel_name: str
new channel to plot on that axis |
def callback(self, event):
"""
Callback function to spawn a mini-browser when a feature is clicked.
"""
artist = event.artist
ind = artist.ind
limit = 5
browser = True
if len(event.ind) > limit:
print "more than %s genes selected; not spawning ... | Callback function to spawn a mini-browser when a feature is clicked. |
def fftw_multi_normxcorr(template_array, stream_array, pad_array, seed_ids,
cores_inner, cores_outer):
"""
Use a C loop rather than a Python loop - in some cases this will be fast.
:type template_array: dict
:param template_array:
:type stream_array: dict
:param stream_... | Use a C loop rather than a Python loop - in some cases this will be fast.
:type template_array: dict
:param template_array:
:type stream_array: dict
:param stream_array:
:type pad_array: dict
:param pad_array:
:type seed_ids: list
:param seed_ids:
rtype: np.ndarray, list
:retur... |
def get_routes(
feed: "Feed", date: Optional[str] = None, time: Optional[str] = None
) -> DataFrame:
"""
Return a subset of ``feed.routes``
Parameters
-----------
feed : Feed
date : string
YYYYMMDD date string restricting routes to only those active on
the date
time : st... | Return a subset of ``feed.routes``
Parameters
-----------
feed : Feed
date : string
YYYYMMDD date string restricting routes to only those active on
the date
time : string
HH:MM:SS time string, possibly with HH > 23, restricting routes
to only those active during the ... |
def path_exists_glob(path):
'''
Tests to see if path after expansion is a valid path (file or directory).
Expansion allows usage of ? * and character ranges []. Tilde expansion
is not supported. Returns True/False.
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt... | Tests to see if path after expansion is a valid path (file or directory).
Expansion allows usage of ? * and character ranges []. Tilde expansion
is not supported. Returns True/False.
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' file.path_exists_glob /etc/pam*/pas... |
def mix(color1, color2, pos=0.5):
"""
Return the mix of two colors at a state of :pos:
Retruns color1 * pos + color2 * (1 - pos)
"""
opp_pos = 1 - pos
red = color1[0] * pos + color2[0] * opp_pos
green = color1[1] * pos + color2[1] * opp_pos
blue = color1[2] * pos + color2[2] * opp_pos
... | Return the mix of two colors at a state of :pos:
Retruns color1 * pos + color2 * (1 - pos) |
def rmdir(self, parents=False):
"""Removes this directory, provided it is empty.
Use :func:`~rpaths.Path.rmtree` if it might still contain files.
:param parents: If set to True, it will also destroy every empty
directory above it until an error is encountered.
"""
i... | Removes this directory, provided it is empty.
Use :func:`~rpaths.Path.rmtree` if it might still contain files.
:param parents: If set to True, it will also destroy every empty
directory above it until an error is encountered. |
def add_collaboration(self, collaboration):
"""Add collaboration.
:param collaboration: collaboration for the current document
:type collaboration: string
"""
collaborations = normalize_collaboration(collaboration)
for collaboration in collaborations:
self._a... | Add collaboration.
:param collaboration: collaboration for the current document
:type collaboration: string |
def exit_statistics(hostname, start_time, count_sent, count_received, min_time, avg_time, max_time, deviation):
"""
Print ping exit statistics
"""
end_time = datetime.datetime.now()
duration = end_time - start_time
duration_sec = float(duration.seconds * 1000)
duration_ms = float(duration.mi... | Print ping exit statistics |
def specificity(result, reference):
"""
Specificity.
Parameters
----------
result : array_like
Input data containing objects. Can be any type but will be converted
into binary: background where 0, object everywhere else.
reference : array_like
Input data containing o... | Specificity.
Parameters
----------
result : array_like
Input data containing objects. Can be any type but will be converted
into binary: background where 0, object everywhere else.
reference : array_like
Input data containing objects. Can be any type but will be converted
... |
def get_model_paths(model_dir):
"""Returns all model paths in the model_dir."""
all_models = gfile.Glob(os.path.join(model_dir, '*.meta'))
model_filenames = [os.path.basename(m) for m in all_models]
model_numbers_names = [
(shipname.detect_model_num(m), shipname.detect_model_name(m))
for... | Returns all model paths in the model_dir. |
def pop_marker(self, reset):
""" Pop a marker off of the marker stack. If reset is True then the
iterator will be returned to the state it was in before the
corresponding call to push_marker().
"""
marker = self.markers.pop()
if reset:
# Make the values ava... | Pop a marker off of the marker stack. If reset is True then the
iterator will be returned to the state it was in before the
corresponding call to push_marker(). |
def extract(self, html_text: str,
extract_title: bool = False,
extract_meta: bool = False,
extract_microdata: bool = False,
microdata_base_url: str = "",
extract_json_ld: bool = False,
extract_rdfa: bool = False,
... | Args:
html_text (str): input html string to be extracted
extract_title (bool): True if string of 'title' tag needs to be extracted, return as { "title": "..." }
extract_meta (bool): True if string of 'meta' tags needs to be extracted, return as { "meta": { "author": "...", ...}}
... |
def build(port=8000, fixtures=None):
"""
Builds a server file.
1. Extract mock response details from all valid docstrings in existing views
2. Parse and generate mock values
3. Create a store of all endpoints and data
4. Construct server file
"""
extractor = Extractor()
parser = Par... | Builds a server file.
1. Extract mock response details from all valid docstrings in existing views
2. Parse and generate mock values
3. Create a store of all endpoints and data
4. Construct server file |
def get_settings():
"""
This function returns a dict containing default settings
"""
s = getattr(settings, 'CLAMAV_UPLOAD', {})
s = {
'CONTENT_TYPE_CHECK_ENABLED': s.get('CONTENT_TYPE_CHECK_ENABLED', False),
# LAST_HANDLER is not a user configurable option; we return
... | This function returns a dict containing default settings |
def encode(B):
""" Encode data using Hamming(7, 4) code.
E.g.:
encode([0, 0, 1, 1])
encode([[0, 0, 0, 1],
[0, 1, 0, 1]])
:param array B: binary data to encode (must be shaped as (4, ) or (-1, 4)).
"""
B = array(B)
flatten = False
if len(B.shape) == 1:
... | Encode data using Hamming(7, 4) code.
E.g.:
encode([0, 0, 1, 1])
encode([[0, 0, 0, 1],
[0, 1, 0, 1]])
:param array B: binary data to encode (must be shaped as (4, ) or (-1, 4)). |
def getResponseAction(self, ps, action):
'''Returns response WS-Action if available
action -- request WS-Action value.
'''
opName = self.getOperationName(ps, action)
if self.wsAction.has_key(opName) is False:
raise WSActionNotSpecified, 'wsAction dictionary missing... | Returns response WS-Action if available
action -- request WS-Action value. |
def create_domain(self,
service_id,
version_number,
name,
comment=None):
"""Create a domain for a particular service and version."""
body = self._formdata({
"name": name,
"comment": comment,
}, FastlyDomain.FIELDS)
content = self._fetch("/service/%s/version/%d/domain" % (service_id, version_nu... | Create a domain for a particular service and version. |
def _sort_shared_logical_disks(logical_disks):
"""Sort the logical disks based on the following conditions.
When the share_physical_disks is True make sure we create the volume
which needs more disks first. This avoids the situation of insufficient
disks for some logical volume request.
For exampl... | Sort the logical disks based on the following conditions.
When the share_physical_disks is True make sure we create the volume
which needs more disks first. This avoids the situation of insufficient
disks for some logical volume request.
For example,
- two logical disk with number of disks - LD1... |
def get_metadata(doi):
"""Returns the metadata of an article given its DOI from CrossRef
as a JSON dict"""
url = crossref_url + 'works/' + doi
res = requests.get(url)
if res.status_code != 200:
logger.info('Could not get CrossRef metadata for DOI %s, code %d' %
(doi, res.... | Returns the metadata of an article given its DOI from CrossRef
as a JSON dict |
def apply_fseries_time_shift(htilde, dt, kmin=0, copy=True):
"""Shifts a frequency domain waveform in time. The waveform is assumed to
be sampled at equal frequency intervals.
"""
if htilde.precision != 'single':
raise NotImplementedError("CUDA version of apply_fseries_time_shift only supports s... | Shifts a frequency domain waveform in time. The waveform is assumed to
be sampled at equal frequency intervals. |
def parse(self, path):
"""Extracts a dictionary of values from the XML file at the specified path."""
#Load the template that will be used for parsing the values.
expath, template, root = self._load_template(path)
if expath is not None:
values = template.parse(root)
... | Extracts a dictionary of values from the XML file at the specified path. |
def add_dat_file(filename, settings, container=None, **kwargs):
""" Read a RES2DINV-style file produced by the ABEM export program.
"""
# each type is read by a different function
importers = {
# general array type
11: _read_general_type,
}
file_type, content = _read_file(filena... | Read a RES2DINV-style file produced by the ABEM export program. |
def period_break(dates, period):
"""
Returns the indices where the given period changes.
Parameters
----------
dates : PeriodIndex
Array of intervals to monitor.
period : string
Name of the period to monitor.
"""
current = getattr(dates, period)
previous = getattr(da... | Returns the indices where the given period changes.
Parameters
----------
dates : PeriodIndex
Array of intervals to monitor.
period : string
Name of the period to monitor. |
def toDict(self):
"""
Return a dictionary with the DataFrame data.
"""
d = {}
nindices = self.getNumIndices()
for i in range(self.getNumRows()):
row = list(self.getRowByIndex(i))
if nindices > 1:
key = tuple(row[:nindices])
... | Return a dictionary with the DataFrame data. |
async def move_to(self, channel: discord.VoiceChannel):
"""
Moves this player to a voice channel.
Parameters
----------
channel : discord.VoiceChannel
"""
if channel.guild != self.channel.guild:
raise TypeError("Cannot move to a different guild.")
... | Moves this player to a voice channel.
Parameters
----------
channel : discord.VoiceChannel |
def do_login(session, for_what):
"""
Performs a login handshake with a user on the command-line. This method
will handle all of the follow-up requests (e.g. capcha or two-factor). A
login that requires two-factor looks like this::
>>> import mwapi.cli
>>> import mwapi
>>> mwap... | Performs a login handshake with a user on the command-line. This method
will handle all of the follow-up requests (e.g. capcha or two-factor). A
login that requires two-factor looks like this::
>>> import mwapi.cli
>>> import mwapi
>>> mwapi.cli.do_login(mwapi.Session("https://en.wiki... |
def to_xdr_object(self):
"""Get an XDR object representation of this
:class:`TransactionEnvelope`.
"""
tx = self.tx.to_xdr_object()
return Xdr.types.TransactionEnvelope(tx, self.signatures) | Get an XDR object representation of this
:class:`TransactionEnvelope`. |
def set_tuning(self, tuning):
"""Set the tuning attribute on both the Track and its instrument (when
available).
Tuning should be a StringTuning or derivative object.
"""
if self.instrument:
self.instrument.tuning = tuning
self.tuning = tuning
return ... | Set the tuning attribute on both the Track and its instrument (when
available).
Tuning should be a StringTuning or derivative object. |
def mysql_timestamp_converter(s):
"""Convert a MySQL TIMESTAMP to a Timestamp object."""
# MySQL>4.1 returns TIMESTAMP in the same format as DATETIME
if s[4] == '-': return DateTime_or_None(s)
s = s + "0"*(14-len(s)) # padding
parts = map(int, filter(None, (s[:4],s[4:6],s[6:8],
... | Convert a MySQL TIMESTAMP to a Timestamp object. |
def fillna(self, value=None, method=None, limit=None):
"""
Fill NA/NaN values using the specified method.
Parameters
----------
value : scalar, dict, Series
If a scalar value is passed it is used to fill all missing values.
Alternatively, a Series or dict... | Fill NA/NaN values using the specified method.
Parameters
----------
value : scalar, dict, Series
If a scalar value is passed it is used to fill all missing values.
Alternatively, a Series or dict can be used to fill in different
values for each index. The va... |
def export_opml():
"""Export an OPML feed list"""
with Database("feeds") as feeds:
# Thanks to the canto project- used under the GPL
print("""<opml version="1.0">""")
print("""<body>""")
# Accurate but slow.
for name in list(feeds.keys()):
kind = feedparser.pa... | Export an OPML feed list |
def auth(username, password):
"""
Middleware implementing authentication via LOGIN.
Most of the time this middleware needs to be placed
*after* TLS.
:param username: Username to login with.
:param password: Password of the user.
"""
def middleware(conn):
conn.login(username, pas... | Middleware implementing authentication via LOGIN.
Most of the time this middleware needs to be placed
*after* TLS.
:param username: Username to login with.
:param password: Password of the user. |
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if PY2:
... | A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class. |
def openid_authorization_validator(self, request):
"""Additional validation when following the Authorization Code flow.
"""
request_info = super(HybridGrant, self).openid_authorization_validator(request)
if not request_info: # returns immediately if OAuth2.0
return request_i... | Additional validation when following the Authorization Code flow. |
def upload(self, file_obj=None, file_path=None, name=None, data=None):
"""
Upload an image and return its path on the server.
Either `file_obj` or `file_path` or `name` and `data` has to be specified.
:param file_obj: A file object to upload
:param file_path: A file path to uplo... | Upload an image and return its path on the server.
Either `file_obj` or `file_path` or `name` and `data` has to be specified.
:param file_obj: A file object to upload
:param file_path: A file path to upload from
:param name: A file name for uploading
:param data: The file conten... |
def define_mask_borders(image2d, sought_value, nadditional=0):
"""Generate mask avoiding undesired values at the borders.
Set to True image borders with values equal to 'sought_value'
Parameters
----------
image2d : numpy array
Initial 2D image.
sought_value : int, float, bool
... | Generate mask avoiding undesired values at the borders.
Set to True image borders with values equal to 'sought_value'
Parameters
----------
image2d : numpy array
Initial 2D image.
sought_value : int, float, bool
Pixel value that indicates missing data in the spectrum.
naddition... |
def _GetVisibilityPolicy():
"""If a debugger configuration is found, create a visibility policy."""
try:
visibility_config = yaml_data_visibility_config_reader.OpenAndRead()
except yaml_data_visibility_config_reader.Error as err:
return error_data_visibility_policy.ErrorDataVisibilityPolicy(
'Coul... | If a debugger configuration is found, create a visibility policy. |
def to_binary(s, encoding='utf8'):
"""Portable cast function.
In python 2 the ``str`` function which is used to coerce objects to bytes does not
accept an encoding argument, whereas python 3's ``bytes`` function requires one.
:param s: object to be converted to binary_type
:return: binary_type ins... | Portable cast function.
In python 2 the ``str`` function which is used to coerce objects to bytes does not
accept an encoding argument, whereas python 3's ``bytes`` function requires one.
:param s: object to be converted to binary_type
:return: binary_type instance, representing s. |
def output(self):
""" Produce a classic generator for this cell's final results. """
starters = self.finalize()
try:
yield from self._output(starters)
finally:
self.close() | Produce a classic generator for this cell's final results. |
def raw_sensor_strings(self):
"""
Reads the raw strings from the kernel module sysfs interface
:returns: raw strings containing all bytes from the sensor memory
:rtype: str
:raises NoSensorFoundError: if the sensor could not be found
:raises SensorNo... | Reads the raw strings from the kernel module sysfs interface
:returns: raw strings containing all bytes from the sensor memory
:rtype: str
:raises NoSensorFoundError: if the sensor could not be found
:raises SensorNotReadyError: if the sensor is not ready yet |
def _check_key_value_types(obj, key_type, value_type, key_check=isinstance, value_check=isinstance):
'''Ensures argument obj is a dictionary, and enforces that the keys/values conform to the types
specified by key_type, value_type.
'''
if not isinstance(obj, dict):
raise_with_traceback(_type_mis... | Ensures argument obj is a dictionary, and enforces that the keys/values conform to the types
specified by key_type, value_type. |
def fit_predict(self, sequences, y=None):
"""Performs clustering on X and returns cluster labels.
Parameters
----------
sequences : list of array-like, each of shape [sequence_length, n_features]
A list of multivariate timeseries. Each sequence may have
a differe... | Performs clustering on X and returns cluster labels.
Parameters
----------
sequences : list of array-like, each of shape [sequence_length, n_features]
A list of multivariate timeseries. Each sequence may have
a different length, but they all must have the same number
... |
def locale_escape(string, errors='replace'):
'''
Mangle non-supported characters, for savages with ascii terminals.
'''
encoding = locale.getpreferredencoding()
string = string.encode(encoding, errors).decode('utf8')
return string | Mangle non-supported characters, for savages with ascii terminals. |
def update(self, τ: float = 1.0, update_indicators=True, dampen=False):
""" Advance the model by one time step. """
for n in self.nodes(data=True):
n[1]["next_state"] = n[1]["update_function"](n)
for n in self.nodes(data=True):
n[1]["rv"].dataset = n[1]["next_state"]
... | Advance the model by one time step. |
def generate_random_string(number_of_random_chars=8, character_set=string.ascii_letters):
"""
Generate a series of random characters.
Kwargs:
number_of_random_chars (int) : Number of characters long
character_set (str): Specify a character set. Default is ASCII
"""
return u('').joi... | Generate a series of random characters.
Kwargs:
number_of_random_chars (int) : Number of characters long
character_set (str): Specify a character set. Default is ASCII |
def get_portchannel_info_by_intf_output_lacp_partner_brcd_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf")
config = get_portchannel_info_by_intf
output = ET.SubElement... | Auto Generated Code |
def cache(descriptor=None, *, store: IStore = None):
'''
usage:
``` py
@cache
@property
def name(self): pass
```
'''
if descriptor is None:
return functools.partial(cache, store=store)
hasattrs = {
'get': hasattr(descriptor, '__get__'),
'set': hasattr(d... | usage:
``` py
@cache
@property
def name(self): pass
``` |
def _unpack(self, data):
'''
Unpack a struct from bytes. For parser internal use.
'''
#self._logger.log(logging.DEBUG, 'unpacking %r', self)
current = self
while current is not None:
data = current._parser.unpack(data, current)
last = current
... | Unpack a struct from bytes. For parser internal use. |
def validateDatetime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
formats=('%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S',
'%Y/%m/%d %H:%M', '%y/%m/%d %H:%M', '%m/%d/%Y %H:%M', '%m/%d/%... | Raises ValidationException if value is not a datetime formatted in one
of the formats formats. Returns a datetime.datetime object of value.
* value (str): The value being validated as a datetime.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If ... |
def is_entailed_by(self, other):
"""
Returns True iff the values in this list can be entailed by the other
list (ie, this list is a prefix of the other)
"""
other = ListCell.coerce(other)
if other.size() < self.size():
# other is bigger, can't be entailed
... | Returns True iff the values in this list can be entailed by the other
list (ie, this list is a prefix of the other) |
def formatHeadings(self, text, isMain):
"""
This function accomplishes several tasks:
1) Auto-number headings if that option is enabled
2) Add an [edit] link to sections for logged in users who have enabled the option
3) Add a Table of contents on the top for users who have enabled the option
4) Auto-anchor... | This function accomplishes several tasks:
1) Auto-number headings if that option is enabled
2) Add an [edit] link to sections for logged in users who have enabled the option
3) Add a Table of contents on the top for users who have enabled the option
4) Auto-anchor headings
It loops through all headlines, col... |
def list_projects(self):
"""Return a list of all followed projects."""
method = 'GET'
url = '/projects?circle-token={token}'.format(
token=self.client.api_token)
json_data = self.client.request(method, url)
return json_data | Return a list of all followed projects. |
def _get_revision(self, revision):
"""
Get's an ID revision given as str. This will always return a fill
40 char revision number
:param revision: str or int or None
"""
if self._empty:
raise EmptyRepositoryError("There are no changesets yet")
if rev... | Get's an ID revision given as str. This will always return a fill
40 char revision number
:param revision: str or int or None |
def _remove_lead_trail_false(bool_list):
"""Remove leading and trailing false's from a list"""
# The internet can be a wonderful place...
for i in (0, -1):
while bool_list and not bool_list[i]:
bool_list.pop(i)
return bool_list | Remove leading and trailing false's from a list |
def _brzozowski_algebraic_method_init(self):
"""Initialize Brzozowski Algebraic Method"""
# Initialize B
for state_a in self.mma.states:
if state_a.final:
self.B[state_a.stateid] = self.epsilon
else:
self.B[state_a.stateid] = self.empty
... | Initialize Brzozowski Algebraic Method |
def nearest_qmed_catchments(self, subject_catchment, limit=None, dist_limit=500):
"""
Return a list of catchments sorted by distance to `subject_catchment` **and filtered to only include catchments
suitable for QMED analyses**.
:param subject_catchment: catchment object to measure dista... | Return a list of catchments sorted by distance to `subject_catchment` **and filtered to only include catchments
suitable for QMED analyses**.
:param subject_catchment: catchment object to measure distances to
:type subject_catchment: :class:`floodestimation.entities.Catchment`
:param li... |
def data_array_from_data_iterable(data_iterable):
'''Convert data iterable to raw data numpy array.
Parameters
----------
data_iterable : iterable
Iterable where each element is a tuple with following content: (raw data, timestamp_start, timestamp_stop, status).
Returns
------... | Convert data iterable to raw data numpy array.
Parameters
----------
data_iterable : iterable
Iterable where each element is a tuple with following content: (raw data, timestamp_start, timestamp_stop, status).
Returns
-------
data_array : numpy.array
concatenated data... |
def init_dataset_prepare_args(self, parser):
'''Only invoked conditionally if subcommand is 'prepare' '''
parser.add_argument('-f', '--configuration', dest='config', default=DEFAULT_USER_CONFIG_PATH,
help='the path to the configuration file to use -- ./config.yaml by default'... | Only invoked conditionally if subcommand is 'prepare' |
def check_specs(specs, renamings, types):
'''
Does nothing but raising PythranSyntaxError if specs
are incompatible with the actual code
'''
from pythran.types.tog import unify, clone, tr
from pythran.types.tog import Function, TypeVariable, InferenceError
functions = {renamings.get(k, k): ... | Does nothing but raising PythranSyntaxError if specs
are incompatible with the actual code |
def send_to_device(self, event_type, messages, txn_id=None):
"""Sends send-to-device events to a set of client devices.
Args:
event_type (str): The type of event to send.
messages (dict): The messages to send. Format should be
<user_id>: {<device_id>: <event_cont... | Sends send-to-device events to a set of client devices.
Args:
event_type (str): The type of event to send.
messages (dict): The messages to send. Format should be
<user_id>: {<device_id>: <event_content>}.
The device ID may also be '*', meaning all known ... |
def render_code(self):
""" Try to load the previous code (if we had a crash or something)
I should allow saving.
"""
tmp_dir = os.environ.get('TMP','')
view_code = os.path.join(tmp_dir,'view.enaml')
if os.path.exists(view_code):
try:
with o... | Try to load the previous code (if we had a crash or something)
I should allow saving. |
def isnap(self):
"""Snapshot index corresponding to time step.
It is set to None if no snapshot exists for the time step.
"""
if self._isnap is UNDETERMINED:
istep = None
isnap = -1
# could be more efficient if do 0 and -1 then bisection
#... | Snapshot index corresponding to time step.
It is set to None if no snapshot exists for the time step. |
def _exception_free_callback(self, callback, *args, **kwargs):
""" A wrapper that remove all exceptions raised from hooks """
try:
return callback(*args, **kwargs)
except Exception:
self._logger.exception("An exception occurred while calling a hook! ",exc_info=True)
... | A wrapper that remove all exceptions raised from hooks |
def backup(self):
"""
Backup the developer state of `output/` in order to make it restorable
and portable for user.
"""
# We set the current output directory path.
output_path = self.base + PyFunceble.OUTPUTS["parent_directory"]
# We initiate the structure b... | Backup the developer state of `output/` in order to make it restorable
and portable for user. |
def service_post_save(instance, *args, **kwargs):
"""
Used to do a service full check when saving it.
"""
# check service
if instance.is_monitored and settings.REGISTRY_SKIP_CELERY:
check_service(instance.id)
elif instance.is_monitored:
check_service.delay(instance.id) | Used to do a service full check when saving it. |
def uuid3(namespace, name):
"""Generate a UUID from the MD5 hash of a namespace UUID and a name."""
import md5
hash = md5.md5(namespace.bytes + name).digest()
return UUID(bytes=hash[:16], version=3) | Generate a UUID from the MD5 hash of a namespace UUID and a name. |
def getUTCDatetimeDOY(days=0, hours=0, minutes=0, seconds=0):
"""getUTCDatetimeDOY -> datetime
Returns the UTC current datetime with the input timedelta arguments (days, hours, minutes, seconds)
added to current date. Returns ISO-8601 datetime format for day of year:
YYYY-DDDTHH:mm:ssZ
"""
... | getUTCDatetimeDOY -> datetime
Returns the UTC current datetime with the input timedelta arguments (days, hours, minutes, seconds)
added to current date. Returns ISO-8601 datetime format for day of year:
YYYY-DDDTHH:mm:ssZ |
def start(self):
"""Initializes the bot, plugins, and everything."""
self.bot_start_time = datetime.now()
self.webserver = Webserver(self.config['webserver']['host'], self.config['webserver']['port'])
self.plugins.load()
self.plugins.load_state()
self._find_event_handlers... | Initializes the bot, plugins, and everything. |
def nsx_controller_connection_addr_method(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
nsx_controller = ET.SubElement(config, "nsx-controller", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(nsx_controller, "name")
name... | Auto Generated Code |
def status(config, group, accounts=(), region=None):
"""report current export state status"""
config = validate.callback(config)
destination = config.get('destination')
client = boto3.Session().client('s3')
for account in config.get('accounts', ()):
if accounts and account['name'] not in ac... | report current export state status |
def cast(self, value):
"""Cast a value to the type required by the option, if one is set.
This is used to cast the string values gathered from environment
variable into their required type.
Args:
value: The value to cast.
Returns:
The value casted to th... | Cast a value to the type required by the option, if one is set.
This is used to cast the string values gathered from environment
variable into their required type.
Args:
value: The value to cast.
Returns:
The value casted to the expected type for the option. |
def declare(self, name, memory_type='BIT', memory_size=1, shared_region=None, offsets=None):
"""DECLARE a quil variable
This adds the declaration to the current program and returns a MemoryReference to the
base (offset = 0) of the declared memory.
.. note::
This function re... | DECLARE a quil variable
This adds the declaration to the current program and returns a MemoryReference to the
base (offset = 0) of the declared memory.
.. note::
This function returns a MemoryReference and cannot be chained like some
of the other Program methods. Consid... |
def get_log_entries_by_search(self, log_entry_query, log_entry_search):
"""Pass through to provider LogEntrySearchSession.get_log_entries_by_search"""
# Implemented from azosid template for -
# osid.resource.ResourceSearchSession.get_resources_by_search_template
if not self._can('search'... | Pass through to provider LogEntrySearchSession.get_log_entries_by_search |
def create_hdf_file(self):
"""
:return: h5py DataSet
"""
mode = 'w'
if not self._overwrite and os.path.exists(self._fname):
mode = 'a'
self._hdf_file = h5py.File(self._fname, mode)
if self._hdf_basepath == '/':
self._group = self._hdf_fil... | :return: h5py DataSet |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.