text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def Throughput(self):
"""Combined throughput from multiplying all the components together.
Returns
-------
throughput : `~pysynphot.spectrum.TabularSpectralElement` or `None`
Combined throughput.
"""
try:
throughput = spectrum.TabularSpectralElem... | 0.00489 |
def state(self):
"""Personsa state (e.g. Online, Offline, Away, Busy, etc)
:rtype: :class:`.EPersonaState`
"""
state = self.get_ps('persona_state', False)
return EPersonaState(state) if state else EPersonaState.Offline | 0.007722 |
def human_xor_01(X, y, model_generator, method_name):
""" XOR (false/true)
This tests how well a feature attribution method agrees with human intuition
for an eXclusive OR operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following fun... | 0.00692 |
def remap_index_fn(ref_file):
"""minimap2 can build indexes on the fly but will also store commons ones.
"""
index_dir = os.path.join(os.path.dirname(ref_file), os.pardir, "minimap2")
if os.path.exists(index_dir) and os.path.isdir(index_dir):
return index_dir
else:
return os.path.dir... | 0.002994 |
def refresh(self):
"""
Reloads the wallet and its accounts. By default, this method is called only once,
on :class:`Wallet` initialization. When the wallet is accessed by multiple clients or
exists in multiple instances, calling `refresh()` will be necessary to update
the list of... | 0.007396 |
def view_portfolio_losses(token, dstore):
"""
The losses for the full portfolio, for each realization and loss type,
extracted from the event loss table.
"""
oq = dstore['oqparam']
loss_dt = oq.loss_dt()
data = portfolio_loss(dstore).view(loss_dt)[:, 0]
rlzids = [str(r) for r in range(le... | 0.001946 |
def nice_log(x):
"""
Uses a log scale but with negative numbers.
:param x: NumPy array
"""
neg = x < 0
xi = np.log2(np.abs(x) + 1)
xi[neg] = -xi[neg]
return xi | 0.005208 |
def random(self, count=1, **kwargs):
"""
Retrieve a single random photo, given optional filters.
Note: If supplying multiple category ID’s,
the resulting photos will be those that
match all of the given categories, not ones that match any category.
Note: You can’t use t... | 0.004215 |
def phonetic_i_umlaut(sound: Vowel) -> Vowel:
"""
>>> umlaut_a = OldNorsePhonology.phonetic_i_umlaut(a)
>>> umlaut_a.ipar
'ɛ'
>>> umlaut_au = OldNorsePhonology.phonetic_i_umlaut(DIPHTHONGS_IPA_class["au"])
>>> umlaut_au.ipar
'ɐy'
:param sound:
:r... | 0.003628 |
def add_section(self, section):
"""Create a new section in the configuration. Extends
RawConfigParser.add_section by validating if the section name is
a string."""
section, _, _ = self._validate_value_types(section=section)
super(ConfigParser, self).add_section(section) | 0.006431 |
def retract(args):
"""Deletes a vote for a poll."""
if not args.msg:
return "Syntax: !vote retract <pollnum>"
if not args.msg.isdigit():
return "Not A Valid Positive Integer."
response = get_response(args.session, args.msg, args.nick)
if response is None:
return "You haven't ... | 0.002463 |
def send(self, message):
"""
Deliver a message to all destinations.
The passed in message might be mutated.
@param message: A message dictionary that can be serialized to JSON.
@type message: L{dict}
"""
message.update(self._globalFields)
errors = []
... | 0.005587 |
def list_view_changed(self, widget, event, data=None):
"""
Function shows last rows.
"""
adj = self.scrolled_window.get_vadjustment()
adj.set_value(adj.get_upper() - adj.get_page_size()) | 0.00885 |
def endure_multi(self, keys, persist_to=-1, replicate_to=-1,
timeout=5.0, interval=0.010, check_removed=False):
"""Check durability requirements for multiple keys
:param keys: The keys to check
The type of keys may be one of the following:
* Sequence of keys
... | 0.003243 |
def walker(top, names):
"""
Walks a directory and records all packages and file extensions.
"""
global packages, extensions
if any(exc in top for exc in excludes):
return
package = top[top.rfind('holoviews'):].replace(os.path.sep, '.')
packages.append(package)
for name in names:
... | 0.001919 |
def _digits(minval, maxval):
"""Digits needed to comforatbly display values in [minval, maxval]"""
if minval == maxval:
return 3
else:
return min(10, max(2, int(1 + abs(np.log10(maxval - minval))))) | 0.004425 |
def with_stdin(self, os_path=None, skip_sub_command=False,
disk_closed_callback=None):
"""
A context manager yielding a stdin-suitable file-like object
based on the optional os_path and optionally skipping any
configured sub-command.
:param os_path: Optional p... | 0.002351 |
def get_song(self, id_):
"""Data for a specific song."""
endpoint = "songs/{id}".format(id=id_)
return self._make_request(endpoint) | 0.012903 |
def res_1to1(pst,logger=None,filename=None,plot_hexbin=False,histogram=False,**kwargs):
""" make 1-to-1 plots and also observed vs residual by observation group
Parameters
----------
pst : pyemu.Pst
logger : Logger
if None, a generic one is created. Default is None
filename : str
... | 0.010466 |
def parseBtop(btopString):
"""
Parse a BTOP string.
The format is described at https://www.ncbi.nlm.nih.gov/books/NBK279682/
@param btopString: A C{str} BTOP sequence.
@raise ValueError: If C{btopString} is not valid BTOP.
@return: A generator that yields a series of integers and 2-tuples of
... | 0.000505 |
def fixed(self):
""" Moved to MODIFIED and not later moved to ASSIGNED """
decision = False
for record in self.history:
# Completely ignore older changes
if record["when"] < self.options.since.date:
continue
# Look for status change to MODIFIED... | 0.001838 |
def adjust_ip (self, ip=None):
"""Called to explicitely fixup an associated IP header
The function adjusts the IP header based on conformance rules
and the group address encoded in the IGMP message.
The rules are:
1. Send General Group Query to 224.0.0.1 (all systems)
2. Send Leave Group to 22... | 0.016265 |
def Boolean(value, true=(u'yes', u'1', u'true'), false=(u'no', u'0', u'false'),
encoding=None):
"""
Parse a value as a boolean.
:type value: `unicode` or `bytes`
:param value: Text value to parse.
:type true: `tuple` of `unicode`
:param true: Values to compare, ignoring case, for... | 0.001105 |
def add_method_drop_down(self, col_number, col_label):
"""
Add drop-down-menu options for magic_method_codes columns
"""
if self.data_type == 'age':
method_list = vocab.age_methods
elif '++' in col_label:
method_list = vocab.pmag_methods
elif self.... | 0.004008 |
def run(self, text):
"""Run each regex substitution on ``text``.
Args:
text (string): the input text.
Returns:
string: text after all substitutions have been sequentially
applied.
"""
for regex in self.regexes:
text = regex.sub(s... | 0.005634 |
def _checkIdEquality(self, requestedEffect, effect):
"""
Tests whether a requested effect and an effect
present in an annotation are equal.
"""
return self._idPresent(requestedEffect) and (
effect.term_id == requestedEffect.term_id) | 0.007042 |
def setData(self, index, value, role=Qt.EditRole):
"""Qt Override."""
if index.isValid() and 0 <= index.row() < len(self.shortcuts):
shortcut = self.shortcuts[index.row()]
column = index.column()
text = from_qvariant(value, str)
if column == SEQUENCE... | 0.004405 |
def list_closed_workflow_executions(domain=None, startTimeFilter=None, closeTimeFilter=None, executionFilter=None, closeStatusFilter=None, typeFilter=None, tagFilter=None, nextPageToken=None, maximumPageSize=None, reverseOrder=None):
"""
Returns a list of closed workflow executions in the specified domain that ... | 0.010078 |
def key_bytes(self):
"""Returns the raw signing key.
:rtype: bytes
"""
return self.key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
) | 0.006452 |
def addr_tuple(s):
"""converts a string into a tuple of (host, port)"""
if "[" in s:
# ip v6
if (s.count("[") != 1) or (s.count("]") != 1):
raise ValueError("Invalid IPv6 address!")
end = s.index("]")
if ":" not in s[end:]:
raise ValueError("IPv6 address d... | 0.001855 |
def pnorm(stat, stat0):
""" [P(X>pi, mu, sigma) for pi in pvalues] for normal distributed stat with
expectation value mu and std deviation sigma """
mu, sigma = mean_and_std_dev(stat0)
stat = to_one_dim_array(stat, np.float64)
args = (stat - mu) / sigma
return 1-(0.5 * (1.0 + scipy.special.erf... | 0.002915 |
def _pythonized_comments(tokens):
"""
Similar to tokens but converts strings after a colon (:) to comments.
"""
is_after_colon = True
for token_type, token_text in tokens:
if is_after_colon and (token_type in pygments.token.String):
token_type = pygments.token.Comment
eli... | 0.001645 |
def romanise(number):
"""Return the roman numeral for a number.
Note that this only works for number in interval range [0, 12] since at
the moment we only use it on realtime earthquake to conver MMI value.
:param number: The number that will be romanised
:type number: float
:return Roman nume... | 0.00157 |
def get_params(self):
"""
Provides access to the model's parameters.
Works arounds the non-availability of graph collections in
eager mode.
:return: A list of all Variables defining the model parameters.
"""
assert tf.executing_eagerly()
out = []
# Collecting params ... | 0.004619 |
def reindex(self, new_index=None, index_conf=None):
'''Rebuilt the current index
This function could be useful in the case you want to change some index settings/mappings
and you don't want to loose all the entries belonging to that index.
This function is built in such a way ... | 0.01451 |
def get_file_samples(file_ids):
"""Get TCGA associated sample barcodes for a list of file IDs.
Params
------
file_ids : Iterable
The file IDs.
Returns
-------
`pandas.Series`
Series containing file IDs as index and corresponding sample barcodes.
"""
ass... | 0.007587 |
def _set_src_vtep_ip(self, v, load=False):
"""
Setter method for src_vtep_ip, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/src_vtep_ip (inet:ipv4-address)
If this variable is read-only (config: false) in the
source YANG file, then _set_src_vtep_ip is considered as a private
... | 0.004255 |
def _from_matrix(cls, matrix):
"""Initialise from matrix representation
Create a Quaternion by specifying the 3x3 rotation or 4x4 transformation matrix
(as a numpy array) from which the quaternion's rotation should be created.
"""
try:
shape = matrix.shape
e... | 0.007003 |
def add_barplot(self):
""" Generate the Samblaster bar plot. """
cats = OrderedDict()
cats['n_nondups'] = {'name': 'Non-duplicates'}
cats['n_dups'] = {'name': 'Duplicates'}
pconfig = {
'id': 'samblaster_duplicates',
'title': 'Samblaster: Number of duplica... | 0.015086 |
def day(t, now=None, format='%B %d'):
'''
Date delta compared to ``t``. You can override ``now`` to specify what date
to compare to.
You can override the date format by supplying a ``format`` parameter.
:param t: timestamp, :class:`datetime.date` or :class:`datetime.datetime`
object
... | 0.000816 |
def init_logging(debug=False, logfile=None):
"""Initialize logging."""
loglevel = logging.DEBUG if debug else logging.INFO
logformat = '%(asctime)s %(name)s: %(levelname)s: %(message)s'
formatter = logging.Formatter(logformat)
stderr = logging.StreamHandler()
stderr.setFormatter(formatter)
... | 0.001842 |
def get_spatial_bounds(gtfs, as_dict=False):
"""
Parameters
----------
gtfs
Returns
-------
min_lon: float
max_lon: float
min_lat: float
max_lat: float
"""
stats = get_stats(gtfs)
lon_min = stats['lon_min']
lon_max = stats['lon_max']
lat_min = stats['lat_min'... | 0.003817 |
def find_autosummary_in_files(filenames):
"""Find out what items are documented in source/*.rst.
See `find_autosummary_in_lines`.
"""
documented = []
for filename in filenames:
f = open(filename, 'r')
lines = f.read().splitlines()
documented.extend(find_autosummary_in_lines(... | 0.002591 |
def _init_uninit_vars(self):
""" Initialize all other trainable variables, i.e. those which are uninitialized """
uninit_vars = self.sess.run(tf.report_uninitialized_variables())
vars_list = list()
for v in uninit_vars:
var = v.decode("utf-8")
vars_list.append(var... | 0.008147 |
def is_effective_member(self, group_id, netid):
"""
Returns True if the netid is in the group, False otherwise.
"""
self._valid_group_id(group_id)
# GWS doesn't accept EPPNs on effective member checks, for UW users
netid = re.sub('@washington.edu', '', netid)
ur... | 0.002725 |
def determine_interactive(self):
"""Determine whether we're in an interactive shell.
Sets interactivity off if appropriate.
cf http://stackoverflow.com/questions/24861351/how-to-detect-if-python-script-is-being-run-as-a-background-process
"""
try:
if not sys.stdout.isatty() or os.getpgrp() != os.tcgetpgrp(... | 0.035928 |
def get_objectives_by_search(self, objective_query, objective_search):
"""Pass through to provider ObjectiveSearchSession.get_objectives_by_search"""
# Implemented from azosid template for -
# osid.resource.ResourceSearchSession.get_resources_by_search_template
if not self._can('search')... | 0.008772 |
def getMaxISOPacketSize(self, endpoint):
"""
Get the maximum size for a single isochronous packet for given
endpoint.
Warning: this function will not always give you the expected result.
See https://libusb.org/ticket/77 . You should instead consult the
endpoint descripto... | 0.005803 |
def get_inc(self):
"""
Get include directories of Visual C++.
"""
dirs = []
for part in ['', 'atlmfc']:
include = os.path.join(self.vc_dir, part, 'include')
if os.path.isdir(include):
logging.info(_('using include: %s'), include)
... | 0.004435 |
def determine_config_changes(self):
""" The magic: Determine what has changed since the last time.
Caller should pass the returned config to register_config_changes to persist.
"""
# 'update' here is synonymous with 'add or update'
instances = set()
new_configs = {}
... | 0.004249 |
def _get_triplet_value_list(self, graph, identity, rdf_type):
"""
Get a list of values from RDF triples when more than one may be present
"""
values = []
for elem in graph.objects(identity, rdf_type):
values.append(elem.toPython())
return values | 0.006557 |
def exec_command(self):
"""Glean the command to run and exec.
On problems, sys.exit.
This method should *never* return.
"""
if not self.original_command_string:
raise SSHEnvironmentError('no SSH command found; '
'interactive shel... | 0.001654 |
def getDigitalChannelData(self,ChNumber):
"""
Returns an array of numbers (0 or 1) containing the values of the
digital channel status.
ChNumber: digital channel number.
"""
if not self.DatFileContent:
print "No data file content. Use the method Rea... | 0.010668 |
def unstack(self):
"""
Unstack array and return a new BoltArraySpark via flatMap().
"""
from bolt.spark.array import BoltArraySpark
if self._rekeyed:
rdd = self._rdd
else:
rdd = self._rdd.flatMap(lambda kv: zip(kv[0], list(kv[1])))
return... | 0.005319 |
def _create_attach_record(self, id, timed):
"""
Create a new pivot attachement record.
"""
record = super(MorphToMany, self)._create_attach_record(id, timed)
record[self._morph_type] = self._morph_class
return record | 0.007519 |
def simplex_identify_cycle(self, t, k, l):
'''
API:
identify_cycle(self, t, k, l)
Description:
Identifies and returns to the pivot cycle, which is a list of
nodes.
Pre:
(1) t is spanning tree solution, (k,l) is the entering arc.
Inp... | 0.002336 |
def python_script_exists(package=None, module=None):
"""
Return absolute path if Python script exists (otherwise, return None)
package=None -> module is in sys.path (standard library modules)
"""
assert module is not None
try:
if package is None:
path = imp.find_modul... | 0.001792 |
def get_files_in_commit(git_folder, commit_id="HEAD"):
"""List of files in HEAD commit.
"""
repo = Repo(str(git_folder))
output = repo.git.diff("--name-only", commit_id+"^", commit_id)
return output.splitlines() | 0.004329 |
def check_permission(cls, role, permission):
"""
Check if role contains permission
"""
result = permission in settings.ARCTIC_ROLES[role]
# will try to call a method with the same name as the permission
# to enable an object level permission check.
if result:
... | 0.00431 |
def GetSOAPHeaders(self, create_method):
"""Returns the SOAP headers required for request authorization.
Args:
create_method: The SOAP library specific method used to instantiate SOAP
objects.
Returns:
A SOAP object containing the headers.
"""
header = create_method(self._SOAP_HE... | 0.001783 |
def expire_in(self, value):
"""
Computes :attr:`.expiration_time` when the value is set.
"""
# pylint:disable=attribute-defined-outside-init
if value:
self._expiration_time = int(time.time()) + int(value)
self._expire_in = value | 0.006826 |
def repeater(self, req, tag):
"""
Render some UI for repeating our form.
"""
repeater = inevow.IQ(self.docFactory).onePattern('repeater')
return repeater.fillSlots(
'object-description', self.parameter.modelObjectDescription) | 0.00722 |
def request_param_update(self, complete_name):
"""
Request an update of the value for the supplied parameter.
"""
self.param_updater.request_param_update(
self.toc.get_element_id(complete_name)) | 0.008403 |
def plot_file_distances(dist_matrix):
"""
Plots dist_matrix
Parameters
----------
dist_matrix: np.ndarray
"""
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.matshow(dist_matrix, interpolation='nearest',
... | 0.005464 |
def rm(name):
"""
Remove an existing project and its container.
"""
path = get_existing_project_path(name)
click.confirm(
'Are you sure you want to delete project %s?' % name, abort=True)
container_name = get_container_name(name)
client = docker.Client()
try:
client.ins... | 0.001681 |
def _is_module_path(self, path):
"""Returns true if the passed in path is a test module path
:param path: string, the path to check, will need to start or end with the
module test prefixes or postfixes to be considered valid
:returns: boolean, True if a test module path, False other... | 0.003947 |
def _GetNormalizedTimestamp(self):
"""Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if the normalized timestamp cann... | 0.006033 |
def _fix_callback_item(self, item):
'Update component identifier'
item.component_id = self._fix_id(item.component_id)
return item | 0.013072 |
def start(self):
"""Schedule the fiber to be started in the next iteration of the
event loop."""
target = getattr(self._target, '__qualname__', self._target.__name__)
self._log.debug('starting fiber {}, target {}', self.name, target)
self._hub.run_callback(self.switch) | 0.006472 |
def _clear_empty_values(args):
'''
Scrap junk data from a dict.
'''
result = {}
for param in args:
if args[param] is not None:
result[param] = args[param]
return result | 0.004717 |
def circumradius(self):
'''
Distance from the circumcenter to all the verticies in
the Triangle, float.
'''
return (self.a * self.b * self.c) / (self.area * 4) | 0.01 |
def se_iban_load_map(filename: str) -> list:
"""
Loads Swedish monetary institution codes in CSV format.
:param filename: CSV file name of the BIC definitions.
Columns: Institution Name, Range Begin-Range End (inclusive), Account digits count
:return: List of (bank name, clearing code begin, clearin... | 0.002728 |
def days_to_hmsm(days):
"""
Convert fractional days to hours, minutes, seconds, and microseconds.
Precision beyond microseconds is rounded to the nearest microsecond.
Parameters
----------
days : float
A fractional number of days. Must be less than 1.
Returns
-------
hour :... | 0.001155 |
def wait(self):
'''This waits until the child exits. This is a blocking call. This will
not read any data from the child, so this will block forever if the
child has unread output and has terminated. In other words, the child
may have printed output then called exit(), but, the child is
... | 0.001955 |
def mpl_palette(name, n_colors=6):
"""Return discrete colors from a matplotlib palette.
Note that this handles the qualitative colorbrewer palettes
properly, although if you ask for more colors than a particular
qualitative palette can provide you will fewer than you are
expecting.
Parameters
... | 0.000853 |
def wait(self):
"""
Wait until all transferred events have been sent.
"""
if self.error:
raise self.error
if not self.running:
raise ValueError("Unable to send until client has been started.")
try:
self._handler.wait()
except (e... | 0.002015 |
def show_label(self, text, size = None, color = None, font_desc = None):
"""display text. unless font_desc is provided, will use system's default font"""
font_desc = pango.FontDescription(font_desc or _font_desc)
if color: self.set_color(color)
if size: font_desc.set_absolute_size(size *... | 0.029333 |
def build(self, client,
nobuild=False,
usecache=True,
pull=False):
"""
Drives the build of the final image - get the list of steps and execute them.
Args:
client (docker.Client): docker client object that will build the image
nob... | 0.005106 |
def post_periodic_filtered(values, repeat_after, block):
"""
After every *repeat_after* items, blocks the next *block* items from
*values*. Note that unlike :func:`pre_periodic_filtered`, *repeat_after*
can't be 0. For example, to block every tenth item read from an ADC::
from gpiozero import M... | 0.001086 |
def get_snapshots(self, si, logger, vm_uuid):
"""
Restores a virtual machine to a snapshot
:param vim.ServiceInstance si: py_vmomi service instance
:param logger: Logger
:param vm_uuid: uuid of the virtual machine
"""
vm = self.pyvmomi_service.find_by_uuid(si, vm_... | 0.004405 |
def read_files(*files):
"""Read files into setup"""
text = ""
for single_file in files:
content = read(single_file)
text = text + content + "\n"
return text | 0.005319 |
def pad_if_need(sz_atleast, img, mode='constant'):
# fixme : function or ....
"""
pad img if need to guarantee minumum size
:param sz_atleast: [H,W] at least
:param img: image np.array [H,W, ...]
:param mode: str, padding mode
:return: padded image or asis if enought size
"""
# sz_at... | 0.001302 |
def remove_whitespace(self, html):
"""
Clean whitespace from html
@Params
html - html source to remove whitespace from
@Returns
String html without whitespace
"""
# Does python have a better way to do exactly this?
clean_html = html
for cha... | 0.004717 |
def login_and_store_credentials_in_session(request, *args, **kwargs):
'''Custom login view. Calls the standard Django authentication,
but on successful login, stores encrypted user credentials in
order to allow accessing the Fedora repository with the
credentials of the currently-logged in user (e.g., ... | 0.00223 |
def reboot(name, call=None):
'''
Reboot a vagrant minion.
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
if call != 'action':
raise SaltCloudException(
'The reboot action must be called with -a or ... | 0.001712 |
def resample(data, s_freq=None, axis='time', ftype='fir', n=None):
"""Downsample the data after applying a filter.
Parameters
----------
data : instance of Data
data to downsample
s_freq : int or float
desired sampling frequency
axis : str
axis you want to apply downsamp... | 0.000783 |
def xml_filter(self, content):
r"""Filter and preprocess xml content
:param content: xml content
:rtype: str
"""
content = utils.strip_whitespace(content, True) if self.__options['strip'] else content.strip()
if not self.__options['encoding']:
encoding = sel... | 0.005348 |
def describe(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> dict:
"""
Return a dictionary that describes a given language tag in a specified
natural language.
See `language_name` and related methods for more specific versions of this.
The desired `language` will in fact... | 0.002911 |
def relabel(self, qubits: Qubits) -> 'Density':
"""Return a copy of this state with new qubits"""
return Density(self.vec.tensor, qubits, self._memory) | 0.011976 |
def subselect(self, obj):
"""
Filter a dict of hyperparameter settings to only those keys defined
in this HyperparameterDefaults .
"""
return dict(
(key, value) for (key, value)
in obj.items()
if key in self.defaults) | 0.006803 |
def data_in_db(db_data, user_data):
"""Validate db data in user data.
Args:
db_data (str): The data store in Redis.
user_data (list): The user provided data.
Returns:
bool: True if the data passed validation.
"""
if isinstance(user_data, list... | 0.004902 |
def _get_fuzzy_tc_matches(text, full_text, options):
'''
Get the options that match the full text, then from each option
return only the individual words which have not yet been matched
which also match the text being tab-completed.
'''
print("text: {}, full: {}, options: {}".format(text, full_t... | 0.001841 |
def parse_headers_link(headers):
"""Returns the parsed header links of the response, if any."""
header = CaseInsensitiveDict(headers).get('link')
l = {}
if header:
links = parse_link(header)
for link in links:
key = link.get('rel') or link.get('url')
l[key] = ... | 0.005917 |
def clean_time_slots(self):
"""Clean up all unused timeslots.
.. warning:: This can and will take time for larger tiers.
When you want to do a lot of operations on a lot of tiers please unset
the flags for cleaning in the functions so that the cleaning is only
performed afterwa... | 0.003861 |
def handle_connack(self):
"""Handle incoming CONNACK command."""
self.logger.info("CONNACK reveived")
ret, flags = self.in_packet.read_byte()
if ret != NC.ERR_SUCCESS:
self.logger.error("error read byte")
return ret
# useful for v3.1.1 only
... | 0.007273 |
def read_only(self, value):
"""
Setter for **self.__read_only** attribute.
:param value: Attribute value.
:type value: bool
"""
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("read_only", value)
... | 0.008721 |
def print_warning(cls):
"""Print a missing progress bar warning if it was not printed.
"""
if not cls.warning:
cls.warning = True
print('Can\'t create progress bar:', str(TQDM_IMPORT_ERROR),
file=sys.stderr) | 0.007326 |
def _dump_cml_molecule(f, molecule):
"""Dump a single molecule to a CML file
Arguments:
| ``f`` -- a file-like object
| ``molecule`` -- a Molecule instance
"""
extra = getattr(molecule, "extra", {})
attr_str = " ".join("%s='%s'" % (key, value) for key, value in extra.items())... | 0.004772 |
def setShowLanguage(self, state):
"""
Sets the display mode for this widget to the inputed mode.
:param state | <bool>
"""
if state == self._showLanguage:
return
self._showLanguage = state
self.setDirty() | 0.013115 |
def calculate_size(name, listener_flags, local_only):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += INT_SIZE_IN_BYTES
data_size += BOOLEAN_SIZE_IN_BYTES
return data_size | 0.003922 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.