text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _convert_epytext(line):
"""
>>> _convert_epytext("L{A}")
:class:`A`
"""
line = line.replace('@', ':')
for p, sub in RULES:
line = re.sub(p, sub, line)
return line | 0.00495 |
def appliance_device_read_community(self):
"""
Gets the ApplianceDeviceReadCommunity API client.
Returns:
ApplianceDeviceReadCommunity:
"""
if not self.__appliance_device_read_community:
self.__appliance_device_read_community = ApplianceDeviceReadCommunit... | 0.007614 |
def apply(
self, value, locale, currency=None, currency_digits=True,
decimal_quantization=True):
"""Renders into a string a number following the defined pattern.
Forced decimal quantization is active by default so we'll produce a
number string that is strictly following C... | 0.000618 |
def create_sym_log_bar_chart(self, x_labels, y_values, y_label):
"""Creates bar chart (log version)
:param x_labels: Names for each variable
:param y_values: Values of x labels
:param y_label: Label of y axis
:return: Sym-log bar chart
"""
ax1 = self.create_bar_c... | 0.004505 |
def __split_genomic_interval_filename(fn):
"""
Split a filename of the format chrom:start-end.ext or chrom.ext (full chrom).
:return: tuple of (chrom, start, end) -- 'start' and 'end' are None if not
present in the filename.
"""
if fn is None or fn == "":
raise ValueError("invalid filename: " ... | 0.01248 |
def ignore_after(seconds, coro=None, *args, timeout_result=None):
'''Execute the specified coroutine and return its result. Issue a
cancellation request after seconds have elapsed. When a timeout
occurs, no exception is raised. Instead, timeout_result is
returned.
If coro is None, the result is an ... | 0.001117 |
def _add_series_or_dataframe_operations(cls):
"""
Add the series or dataframe only operations to the cls; evaluate
the doc strings again.
"""
from pandas.core import window as rwindow
@Appender(rwindow.rolling.__doc__)
def rolling(self, window, min_periods=None,... | 0.001294 |
def get(self, buffer_type, offset):
"""Get a reading from the buffer at offset.
Offset is specified relative to the start of the data buffer.
This means that if the buffer rolls over, the offset for a given
item will appear to change. Anyone holding an offset outside of this
en... | 0.004016 |
def dump_poly_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
"""Dump poly data object to vtkjs"""
if root is None:
root = {}
root['vtkClass'] = 'vtkPolyData'
container = root
# Points
points = dump_data_array(dataset_dir, data_dir,
... | 0.005967 |
def main():
"""
Simple command-line program for powering on virtual machines on a system.
"""
args = GetArgs()
if args.password:
password = args.password
else:
password = getpass.getpass(prompt='Enter password for host %s and user %s: ' % (args.host,args.user))
try:
vmnames = ar... | 0.022042 |
def create_class(self, method):
"""
Build the estimator class.
Returns
-------
:return : string
The built class as string.
"""
temp_type = self.temp('type')
temp_arr = self.temp('arr')
temp_arr_ = self.temp('arr[]')
temp_arr__ ... | 0.001866 |
def read_excitation_energies(self):
"""
Read a excitation energies after a TD-DFT calculation.
Returns:
A list: A list of tuple for each transition such as
[(energie (eV), lambda (nm), oscillatory strength), ... ]
"""
transitions = list()
... | 0.003432 |
def sls(mods, saltenv='base', test=None, exclude=None, **kwargs):
'''
Create the seed file for a state.sls run
'''
st_kwargs = __salt__.kwargs
__opts__['grains'] = __grains__
__pillar__.update(kwargs.get('pillar', {}))
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
st_ = salt.c... | 0.000658 |
def getBucketInfo(self, buckets):
""" See the function description in base.py
"""
# For the category encoder, the bucket index is the category index
bucketInfo = self.encoder.getBucketInfo(buckets)[0]
categoryIndex = int(round(bucketInfo.value))
category = self.indexToCategory[categoryIndex]
... | 0.004556 |
def to_html_(self) -> str:
"""Convert the main dataframe to html
:return: html data
:rtype: str
:example: ``ds.to_html_()``
"""
try:
renderer = pytablewriter.HtmlTableWriter
data = self._build_export(renderer)
return data
exce... | 0.005076 |
def Open(self, filename):
"""Opens the database reader object.
Args:
filename (str): filename of the database.
Returns:
bool: True if successful.
Raises:
RuntimeError: if the version or string format of the database
is not supported.
"""
if not super(Wine... | 0.005682 |
def set_config_variables(repo, variables):
"""Set config variables
Args:
repo (git.Repo): repo
variables (dict): entries of the form 'user.email': 'you@example.com'
"""
with repo.config_writer() as writer:
for k, value in variables.items():
section, option = k.split(... | 0.002488 |
def record_process(self, process, prg=''):
"""
log a process or program - log a physical program (.py, .bat, .exe)
"""
self._log(self.logFileProcess, force_to_string(process), prg) | 0.009434 |
def read_inp(path):
"""
Reads Abaqus inp file
"""
def lineInfo(line):
out = {"type": "data"}
if line[0] == "*":
if line[1] == "*":
out["type"] = "comment"
out["text"] = line[2:]
else:
out["type"] = "command"
words = line[1:].split(",")
out["value"... | 0.034579 |
def setComponentByName(self, name, value=noValue,
verifyConstraints=True,
matchTags=True,
matchConstraints=True):
"""Assign |ASN.1| type component by name.
Equivalent to Python :class:`dict` item assignment operation (e.g.... | 0.005398 |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
options = super(For... | 0.003272 |
def name_to_hex(name, spec=u'css3'):
"""
Convert a color name to a normalized hexadecimal color value.
The optional keyword argument ``spec`` determines which
specification's list of color names will be used; valid values are
``html4``, ``css2``, ``css21`` and ``css3``, and the default is
``css... | 0.001008 |
def pack_data(self, remaining_size):
"""Pack data. readoffset has to be increased by one, seems like HANA starts from 1, not zero."""
payload = self.part_struct.pack(self.locator_id, self.readoffset + 1, self.readlength, b' ')
return 4, payload | 0.01476 |
def init_app(self, app):
"""
Initializes a Flask app object for the extension.
Args:
app(Flask): Flask app
"""
app.config.setdefault('FEDORA_BASE_URL', 'http://localhost:8080')
if hasattr(app, 'teardown_appcontext'):
app.teardown_appcontext(self.t... | 0.005128 |
def error_asymptotes(pca,**kwargs):
"""
Plots asymptotic error bounds for
hyperbola on a stereonet.
"""
ax = kwargs.pop("ax",current_axes())
lon,lat = pca.plane_errors('upper', n=1000)
ax.plot(lon,lat,'-')
lon,lat = pca.plane_errors('lower', n=1000)
ax.plot(lon,lat,'-')
ax.pla... | 0.026393 |
def gen_gmfs(self):
"""
Compute the GMFs for the given realization and
yields arrays of the dtype (sid, eid, imti, gmv), one for rupture
"""
self.sig_eps = []
for computer in self.computers:
rup = computer.rupture
sids = computer.sids
e... | 0.00104 |
def endpoint(cls):
"""Return the :class:`sandman.model.Model`'s endpoint.
:rtype: string
"""
endpoint = ''
if cls.__endpoint__ is not None:
return cls.__endpoint__
elif cls.__from_class__ is not None:
endpoint = cls.__from_class__.__name__.lower(... | 0.004211 |
def setup_catalog_mappings(portal):
"""Setup portal_type -> catalog mappings
"""
logger.info("*** Setup Catalog Mappings ***")
at = api.get_tool("archetype_tool")
for portal_type, catalogs in CATALOG_MAPPINGS:
at.setCatalogsByType(portal_type, catalogs) | 0.003546 |
def main(arguments=None):
'''Converts a given url with the specified arguments.'''
parsed_options, arguments = get_options(arguments)
image_url = arguments[0]
image_url = quote(image_url)
try:
config = Config.load(None)
except Exception:
config = None
if not parsed_option... | 0.004104 |
def get_application_logo_label(self):
"""
Provides the default **Application_Logo_label** widget.
:return: Application logo label.
:rtype: QLabel
"""
logo_label = QLabel()
logo_label.setObjectName("Application_Logo_label")
logo_label.setPixmap(QPixmap(um... | 0.007444 |
def rgb_percent_to_name(rgb_percent_triplet, spec=u'css3'):
"""
Convert a 3-tuple of percentages, suitable for use in an ``rgb()``
color triplet, to its corresponding normalized color name, if any
such name exists.
The optional keyword argument ``spec`` determines which
specification's list of ... | 0.001449 |
def reverse_code_map(self):
"""Return a map from a code ( usually a string ) to the shorter numeric value"""
return {c.value: (c.ikey if c.ikey else c.key) for c in self.codes} | 0.015464 |
def has_slave(self):
'''Returns True/False wether we have a slave agency which is not
standalone running.'''
slave = first(x for x in self.slaves.itervalues()
if not x.is_standalone)
return slave is not None | 0.007663 |
def _check_ising_quadratic_ranges(quad_ranges, graph):
"""check correctness/populate defaults for ising_quadratic_ranges."""
if quad_ranges is None:
quad_ranges = {}
# first just populate the top level so we can rely on the structure
for u in graph:
if u not in q... | 0.002669 |
def copy_table(tbl, start=0, stop=None, blen=None, storage=None,
create='table', **kwargs):
"""Copy `tbl` block-wise into a new table."""
# setup
names, columns = _util.check_table_like(tbl)
storage = _util.get_storage(storage)
blen = _util.get_blen_table(tbl, blen)
if stop is No... | 0.001161 |
def db_connect(connection_string=None, **kwargs):
"""Function to supply a database connection object."""
if connection_string is None:
connection_string = get_current_registry().settings[CONNECTION_STRING]
db_conn = psycopg2.connect(connection_string, **kwargs)
try:
with db_conn:
... | 0.002667 |
def objectConfusion(self):
"""
Compute overlap between each pair of objects. Computes the average number
of feature/location pairs that are identical, as well as the average number
of shared locations and features.
This function will raise an exception if two objects are identical.
Returns th... | 0.011105 |
def gen_edge_knots(data, dtype, verbose=True):
"""
generate uniform knots from data including the edges of the data
for discrete data, assumes k categories in [0, k-1] interval
Parameters
----------
data : array-like with one dimension
dtype : str in {'categorical', 'numerical'}
verbos... | 0.002083 |
def _to_patches(self, X):
"""
Reshapes input to patches of the size of classifier's receptive field.
For example:
input X shape: [n_samples, n_pixels_y, n_pixels_x, n_bands]
output: [n_samples * n_pixels_y/receptive_field_y * n_pixels_x/receptive_field_x,
... | 0.004405 |
def _total_seconds(t):
'''
Takes a `datetime.timedelta` object and returns the delta in seconds.
>>> _total_seconds(datetime.timedelta(23, 42, 123456))
1987242
>>> _total_seconds(datetime.timedelta(23, 42, 654321))
1987243
'''
return sum([
int(t.days * 86400 + t.seconds),
... | 0.002725 |
def list_databases(self, name):
'''
List the SQL databases defined on the specified server name
'''
response = self._perform_get(self._get_list_databases_path(name),
None)
return _MinidomXmlToObject.parse_service_resources_response(
... | 0.005865 |
def set_output_fields(self, output_fields):
"""Defines where to put the dictionary output of the extractor in the doc, but renames
the fields of the extracted output for the document or just filters the keys"""
if isinstance(output_fields, dict) or isinstance(output_fields, list):
se... | 0.007553 |
def value_to_string(self, obj):
"""Prepare field for serialization."""
if DJANGO_VERSION > (1, 9):
value = self.value_from_object(obj)
else:
value = self._get_val_from_obj(obj)
return self.get_prep_value(value) | 0.007519 |
def absent(name, orgname=None, profile='grafana'):
'''
Ensure the named grafana dashboard is absent.
name
Name of the grafana dashboard.
orgname
Name of the organization in which the dashboard should be present.
profile
Configuration profile used to connect to the Grafana ... | 0.000907 |
def add_edge(self, fro, to):
"""
When doing topological sorting, the semantics of the edge mean that
the depedency runs from the parent to the child - which is to say that
the parent is required to be sorted *before* the child.
[ FROM ] ------> [ TO ]
Committee... | 0.003584 |
def _build(self, inputs, memory, treat_input_as_matrix=False):
"""Adds relational memory to the TensorFlow graph.
Args:
inputs: Tensor input.
memory: Memory output from the previous time step.
treat_input_as_matrix: Optional, whether to treat `input` as a sequence
of matrices. Default... | 0.006325 |
def jr6_jr6(mag_file, dir_path=".", input_dir_path="",
meas_file="measurements.txt", spec_file="specimens.txt",
samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
specnum=1, samp_con='1', location='unknown', lat='', lon='',
noave=False, meth_code="L... | 0.001745 |
def wait_for_vacancy(self, processor_type):
"""Waits for a particular processor type to have the capacity to
handle additional transactions or until is_cancelled is True.
Args:
processor_type (ProcessorType): The family, and version of
the transaction processor.
... | 0.002703 |
def notify_ready(self, apply_result):
"""Called by the ApplyResult object (already registered via
register_result()) that it is now ready (ie. the Job's result
is available or an exception has been raised).
\param apply_result ApplyResult object telling us that the job
has been p... | 0.00367 |
def getAssociation(self, assoc_handle, dumb, checkExpiration=True):
"""Get the association with the specified handle.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool
@returns: the association, or None if no valid association with ... | 0.002126 |
def mutate_node(node, context):
"""
:type context: Context
"""
context.stack.append(node)
try:
if node.type in ('tfpdef', 'import_from', 'import_name'):
return
if node.start_pos[0] - 1 != context.current_line_index:
context.current_line_index = node.start_pos... | 0.002882 |
def _building_cost(self, use_mix, stories):
"""
Generate building cost for a set of buildings
Parameters
----------
use_mix : array
The mix of uses for this form
stories : series
A Pandas Series of stories
Returns
-------
... | 0.002134 |
def build_definitions_example(self):
"""Parse all definitions in the swagger specification."""
for def_name, def_spec in self.specification.get('definitions', {}).items():
self.build_one_definition_example(def_name) | 0.012346 |
def situation_parameters(self):
"""
Situation parameters defining detection logic for the context.
This will return a list of SituationParameter indicating how
the detection is made, i.e. regular expression, integer value,
etc.
:rtype: list(SituationParameter)
... | 0.004918 |
def this(obj, **kwargs):
"""Prints series of debugging steps to user.
Runs through pipeline of functions and print results of each.
"""
verbose = kwargs.get("verbose", True)
if verbose:
print('{:=^30}'.format(" whatis.this? "))
for func in pipeline:
s = func(obj, **kwargs)
... | 0.002315 |
def frequencies_plot(self, xmin=0, xmax=200):
""" Generate the qualities plot """
helptext = '''
A possible way to assess the complexity of a library even in
absence of a reference sequence is to look at the kmer profile of the reads.
The idea is to count all the kme... | 0.011765 |
def symbols_bollinger(symbols='sp5002012',
start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='adjusted_close', cleaner=clean_dataframe,
window=20, sigma=1.):
"""Calculate the Bolinger for a list or set of symbols
Example:
>>> symbols_bollinger(["AAPL", "GOOG", "IB... | 0.006979 |
def update_tcs(self):
"""
Periodically update TCS info.
A long running process, so run in a thread and fill a queue
"""
g = get_root(self).globals
if not g.cpars['tcs_on']:
self.after(20000, self.update_tcs)
return
if g.cpars['telins_nam... | 0.00166 |
def prt_report_grp1(self, prt=sys.stdout, **kws_grp):
"""Print full GO/gene report with grouping."""
summaryline = self.str_summaryline()
# Print grouped GO IDs
prt.write("{SUMMARY}\n".format(SUMMARY=summaryline))
self.prt_gos_grouped(prt, **kws_grp)
# genes
genes... | 0.002946 |
def _float_check(self, attribute_array, value, irow, key):
'''Checks if value is valid float, appends to array if valid, appends
nan if not'''
value = value.strip(' ')
try:
if value:
attribute_array = np.hstack([attribute_array, float(value)])
else... | 0.004926 |
def unsubscribe(request, watch_id):
"""Unsubscribe from (i.e. delete) the watch of ID ``watch_id``.
Expects an ``s`` querystring parameter matching the watch's secret.
GET will result in a confirmation page (or a failure page if the secret is
wrong). POST will actually delete the watch (again, if the ... | 0.000674 |
def directory(context, data):
"""Store the collected files to a given directory."""
with context.http.rehash(data) as result:
if not result.ok:
return
content_hash = data.get('content_hash')
if content_hash is None:
context.emit_warning("No content hash in data."... | 0.001053 |
def where_entry_first(query, ref):
""" Generate a where clause where this is the first entry
ref -- the entry of reference
"""
return orm.select(
e for e in query
if e.local_date > ref.local_date or
(e.local_date == ref.local_date and
e.id >= ref.id
)
) | 0.003165 |
def read_until_done(self, command, timeout=None):
"""Yield messages read until we receive a 'DONE' command.
Read messages of the given command until we receive a 'DONE' command. If a
command different than the requested one is received, an AdbProtocolError
is raised.
Args:
command: The comm... | 0.004878 |
def process_lines( self, input_lines, **kwargs ):
''' Executes the pipeline of subsequent VISL_CG3 commands. The first process
in pipeline gets input_lines as an input, and each subsequent process gets
the output of the previous process as an input.
The idea of h... | 0.014627 |
def classes(request):
"""Get all classes of current user"""
if not request.user.is_authenticated() or not hasattr(request.user, "userprofile"):
return render_json(request, {
'error': _('User is not logged in'),
'error_type': 'user_unauthorized'
}, template='user_json.htm... | 0.00759 |
def load(file):
"""
This function expects a path to a file containing a
**Detailed billing report with resources and tags**
report from AWS.
It returns a ``Costs`` object containing all of the lineitems
from that detailed billing report
"""
fp = open(file)
reader = csv.reader(fp)
... | 0.001456 |
def groupby_with_null(data, *args, **kwargs):
"""
Groupby on columns with NaN/None/Null values
Pandas currently does have proper support for
groupby on columns with null values. The nulls
are discarded and so not grouped on.
"""
by = kwargs.get('by', args[0])
altered_columns = {}
i... | 0.000574 |
def is_set(self, key):
"""Return True if variable is a set"""
data = self.model.get_data()
return isinstance(data[key], set) | 0.013245 |
def wait(self, timeout=None):
"""Wait for command to complete.
Timeout:
- discussion: http://stackoverflow.com/questions/1191374/subprocess-with-timeout
- implementation: threading
:rtype: self
"""
if timeout is not None:
if not self._thread:
... | 0.005398 |
def gchart(self, s = 0, size = [], candle = 20):
""" Chart for serious stocks
輸出 Google Chart 圖表。
s = 資料筆數
size = 圖表寬度、高度 [寬度,高度]
candle = K 棒的寬度
"""
if s == 0:
s = len(self.raw_data)
if len(size) == 2:
sw,sh = size
else:
sh = 300
sw = 25 * s
... | 0.014393 |
def _get_cookie(self, mgmt_ip, config, refresh=False):
"""Performs authentication and retries cookie."""
if mgmt_ip not in self.credentials:
return None
security_data = self.credentials[mgmt_ip]
verify = security_data[const.HTTPS_CERT_TUPLE]
if not verify:
... | 0.004894 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'word') and self.word is not None:
_dict['word'] = self.word
if hasattr(self, 'sounds_like') and self.sounds_like is not None:
_dict['sounds_like'] = self.sound... | 0.004264 |
def dec2hms(dec):
"""
ADW: This should really be replaced by astropy
"""
DEGREE = 360.
HOUR = 24.
MINUTE = 60.
SECOND = 3600.
dec = float(dec)
fhour = dec*(HOUR/DEGREE)
hour = int(fhour)
fminute = (fhour - hour)*MINUTE
minute = int(fminute)
second = (fminut... | 0.008065 |
def mcs_to_rate(mcs, bw=20, long_gi=True):
"""Convert MCS index to rate in Mbps.
See http://mcsindex.com/
Args:
mcs (int): MCS index
bw (int): bandwidth, 20, 40, 80, ...
long_gi(bool): True if long GI is used.
Returns:
rate (float): bitrate in Mbps
>>> mcs_to_rat... | 0.001236 |
def state(self):
"""
State of this instance. One of ``OFFLINE``, ``INITIALIZING``,
``INITIALIZED``, ``STARTING``, ``RUNNING``, ``STOPPING`` or
``FAILED``.
"""
if self._proto.HasField('state'):
return yamcsManagement_pb2.YamcsInstance.InstanceState.Name(self._p... | 0.008547 |
def convert_to_LHC(imt):
"""
Converts from GMRotI50 to Larger of two horizontal components using
global equation of:
Boore, D and Kishida, T (2016). Relations between some horizontal-
component ground-motion intensity measures used in practice.
Bulletin of the Seismological Society of America, 1... | 0.001107 |
def parse_log(self, bowtie_log):
"""Parse a bowtie log file.
This is a bowtie log parsing method that populates the
:py:attr:`self.n_reads, self.align_0x, self.align_1x, self.align_mt1x and self.overall_rate` attributes with
data from the log file.
Disclamer: THIS METHOD IS HOR... | 0.007156 |
def evaluate(tensor: BKTensor) -> TensorLike:
"""Return the value of a tensor"""
if isinstance(tensor, _DTYPE):
if torch.numel(tensor) == 1:
return tensor.item()
if tensor.numel() == 2:
return tensor[0].cpu().numpy() + 1.0j * tensor[1].cpu().numpy()
return tensor... | 0.002577 |
def league_header(self, league):
"""Prints the league header"""
league_name = " {0} ".format(league)
click.secho("{:=^62}".format(league_name), fg=self.colors.MISC)
click.echo() | 0.009569 |
def refund_order(self, order_id, **params):
"""https://developers.coinbase.com/api/v2#refund-an-order"""
for required in ['currency']:
if required not in params:
raise ValueError("Missing required parameter: %s" % required)
response = self._post('v2', 'orders', order_... | 0.005 |
def prior_prior_model_dict(self):
"""
Returns
-------
prior_prior_model_dict: {Prior: PriorModel}
A dictionary mapping priors to associated prior models. Each prior will only have one prior model; if a
prior is shared by two prior models then one of those prior mo... | 0.009881 |
def extent(self):
"""
Return the source range (the range of text) occupied by the entity
pointed at by the cursor.
"""
if not hasattr(self, '_extent'):
self._extent = conf.lib.clang_getCursorExtent(self)
return self._extent | 0.007042 |
def add_stats_plot(self):
"""Plots alignment stats as bargraph."""
keys = OrderedDict()
keys['species_a'] = {'color': '#437bb1', 'name': 'Species a'}
keys['species_b'] = {'color': '#b1084c', 'name': 'Species b'}
keys['ambiguous'] = {'color': '#333333', 'name': 'Ambiguous'}
... | 0.003195 |
def get_display_names_metadata(self):
"""Gets the metadata for all display_names.
return: (osid.Metadata) - metadata for the display_names
*compliance: mandatory -- This method must be implemented.*
"""
metadata = dict(self._display_names_metadata)
metadata.update({'exi... | 0.006682 |
def get_value(self, row, column):
"""Return the value of the DataFrame."""
# To increase the performance iat is used but that requires error
# handling, so fallback uses iloc
try:
value = self.df.iat[row, column]
except OutOfBoundsDatetime:
value = ... | 0.006667 |
def multi_stream_iter(client, log_group, streams, positions=None):
"""Iterate over the available events coming from a set of log streams in a single log group
interleaving the events from each stream so they're yielded in timestamp order.
Args:
client (boto3 client): The boto client for logs.
... | 0.004885 |
def filter_leading_non_json_lines(buf):
'''
used to avoid random output from SSH at the top of JSON output, like messages from
tcagetattr, or where dropbear spews MOTD on every single command (which is nuts).
need to filter anything which starts not with '{', '[', ', '=' or is an empty line.
filter... | 0.007267 |
def add_renderer(self, klass, *args, **kwargs):
'''Add a renderer to the current scene.
**Parameter**
klass: renderer class
The renderer class to be added
args, kwargs:
Arguments used by the renderer constructor,
except for the *widge... | 0.007802 |
async def _deferred_init(self):
"""
Register the web hook onto which Telegram should send its messages.
"""
hook_path = self.make_hook_path()
url = urljoin(settings.BERNARD_BASE_URL, hook_path)
await self.call('setWebhook', url=url)
logger.info('Setting Telegram ... | 0.005848 |
def decode(self, encoded, parentFieldName=''):
""" See the function description in base.py
"""
assert (encoded[0:self.n] <= 1.0).all()
resultString = ""
resultRanges = []
overlaps = (self.sdrs * encoded[0:self.n]).sum(axis=1)
if self.verbosity >= 2:
print "Overlaps for decoding:"... | 0.01464 |
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... | 0.026115 |
def regroup_vectorized(srccat, eps, far=None, dist=norm_dist):
"""
Regroup the islands of a catalog according to their normalised distance.
Assumes srccat is recarray-like for efficiency.
Return a list of island groups.
Parameters
----------
srccat : np.rec.arry or pd.DataFrame
Sho... | 0.000375 |
def resolve_nested_schema(self, schema):
"""Return the Open API representation of a marshmallow Schema.
Adds the schema to the spec if it isn't already present.
Typically will return a dictionary with the reference to the schema's
path in the spec unless the `schema_name_resolver` retu... | 0.002336 |
def blocks_to_mark_complete_on_view(self, blocks):
"""
Returns a set of blocks which should be marked complete on view and haven't been yet.
"""
blocks = {block for block in blocks if self.can_mark_block_complete_on_view(block)}
completions = self.get_completions({block.location ... | 0.014019 |
def use_plenary_resource_view(self):
"""Pass through to provider ResourceLookupSession.use_plenary_resource_view"""
self._object_views['resource'] = PLENARY
# self._get_provider_session('resource_lookup_session') # To make sure the session is tracked
for session in self._get_provider_ses... | 0.00883 |
def task_list():
"""
Scans the modules set in RQ_JOBS_MODULES for RQ jobs decorated with @task
Compiles a readable list for Job model task choices
"""
try:
jobs_module = settings.RQ_JOBS_MODULE
except AttributeError:
raise ImproperlyConfigured(_("You have to define RQ_JOBS_MODULE... | 0.004433 |
def annToRLE(self, ann):
"""
Convert annotation which can be polygons, uncompressed RLE to RLE.
:return: binary mask (numpy 2D array)
"""
t = self.imgs[ann['image_id']]
h, w = t['height'], t['width']
segm = ann['segmentation']
if type(segm) == list:
... | 0.002667 |
def _GetRoutingMap(self, router):
"""Returns a routing map for a given router instance."""
try:
routing_map = self._routing_maps_cache.Get(router.__class__)
except KeyError:
routing_map = self._BuildHttpRoutingMap(router.__class__)
self._routing_maps_cache.Put(router.__class__, routing_ma... | 0.011561 |
def bot_has_any_role(*items):
"""Similar to :func:`.has_any_role` except checks if the bot itself has
any of the roles listed.
This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot
is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message.
... | 0.004193 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.