text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def gapfill(model, universal=None, lower_bound=0.05,
penalties=None, demand_reactions=True, exchange_reactions=False,
iterations=1):
"""Perform gapfilling on a model.
See documentation for the class GapFiller.
Parameters
----------
model : cobra.Model
The model to p... | 0.000398 |
def do_build(self):
"""
Create the default version of the layer
:return: a string of the packet with the payload
"""
if not self.explicit:
self = next(iter(self))
pkt = self.self_build()
for t in self.post_transforms:
pkt = t(pkt)
... | 0.004175 |
def lv_load_areas(self):
"""Returns a generator for iterating over load_areas
Yields
------
int
generator for iterating over load_areas
"""
for load_area in sorted(self._lv_load_areas, key=lambda _: repr(_)):
yield load_area | 0.009836 |
def array_to_base64_png(array):
"""Convert an array into base64-enoded PNG image.
Args:
array: A 2D np.ndarray or nested list of items.
Returns:
A base64-encoded string the image. The image is grayscale if the array is
2D. The image is RGB color if the image is 3D with lsat dimension equal to
3.... | 0.010797 |
def _add_post_data(self, request: Request):
'''Add data to the payload.'''
if self._item_session.url_record.post_data:
data = wpull.string.to_bytes(self._item_session.url_record.post_data)
else:
data = wpull.string.to_bytes(
self._processor.fetch_params.po... | 0.004082 |
def _parse_message(self, data):
"""
Parses the raw message from the device.
:param data: message data
:type data: string
:raises: :py:class:`~alarmdecoder.util.InvalidMessageError`
"""
try:
_, values = data.split(':')
self.serial_number, ... | 0.004515 |
def set_string(self, string_options):
"""Set a series of properties using a string.
For example::
'fred=12, tile'
'[fred=12]'
"""
vo = ffi.cast('VipsObject *', self.pointer)
cstr = _to_bytes(string_options)
result = vips_lib.vips_object_set_fro... | 0.005464 |
def reload_manifest(self, manifest):
"""
Reloads a manifest from the disk
:param manifest: The manifest to reload
"""
self._logger.debug("Reloading manifest for {}.".format(manifest.get("name", "Unnamed Plugin")))
self._manifests.remove(manifest)
self.load_manifes... | 0.007732 |
def z_angle_rotate(xy, theta):
"""
Rotated the input vector or set of vectors `xy` by the angle `theta`.
Parameters
----------
xy : array_like
The vector or array of vectors to transform. Must have shape
"""
xy = np.array(xy).T
theta = np.array(theta).T
out = np.zeros_lik... | 0.014675 |
def _HandleLegacy(self, args, token=None):
"""Retrieves the stats for a hunt."""
hunt_obj = aff4.FACTORY.Open(
args.hunt_id.ToURN(), aff4_type=implementation.GRRHunt, token=token)
stats = hunt_obj.GetRunner().context.usage_stats
return ApiGetHuntStatsResult(stats=stats) | 0.003378 |
def figures(df,specs,asList=False):
"""
Generates multiple Plotly figures for a given DataFrame
Parameters:
-----------
df : DataFrame
Pandas DataFrame
specs : list(dict)
List of dictionaries with the properties
of each figure.
All properties avaialbe can be seen with
help(cufflinks.pd.DataFrame... | 0.045531 |
def plot_fluxseries(
self, names: Optional[Iterable[str]] = None,
average: bool = False, **kwargs: Any) \
-> None:
"""Plot the `flux` series of the handled model.
See the documentation on method |Element.plot_inputseries| for
additional information.
"... | 0.005063 |
async def send_contact(self, phone_number: base.String,
first_name: base.String, last_name: typing.Union[base.String, None] = None,
disable_notification: typing.Union[base.Boolean, None] = None,
reply_markup=None,
... | 0.006951 |
def query(self, expr, **kwargs):
"""Query columns of the DataManager with a boolean expression.
Args:
expr: Boolean expression to query the columns with.
Returns:
DataManager containing the rows where the boolean expression is satisfied.
"""
columns = se... | 0.003842 |
def warp_object(self, tileMapObj):
"""Warp the tile map object from one warp to another."""
print "Collision"
if tileMapObj.can_warp:
#Check to see if we need to load a different tile map
if self.map_association != self.exitWarp.map_association:
#Load the ... | 0.008772 |
def _init_filters(self):
"""Initialize the default pywb provided Jninja filters available during template rendering"""
self.filters = {}
@self.template_filter()
def format_ts(value, format_='%a, %b %d %Y %H:%M:%S'):
"""Formats the supplied timestamp using format_
... | 0.00226 |
def load_features(self, features, image_type=None, from_array=False,
threshold=0.001):
""" Load features from current Dataset instance or a list of files.
Args:
features: List containing paths to, or names of, features to
extract. Each element in the lis... | 0.001854 |
def _send_locked(self, cmd):
"""Sends the specified command to the lutron controller.
Assumes self._lock is held.
"""
_LOGGER.debug("Sending: %s" % cmd)
try:
self._telnet.write(cmd.encode('ascii') + b'\r\n')
except BrokenPipeError:
self._disconnect_locked() | 0.010204 |
def suites(self, request, pk=None):
"""
List of test suite names available in this project
"""
suites_names = self.get_object().suites.values_list('slug')
suites_metadata = SuiteMetadata.objects.filter(kind='suite', suite__in=suites_names)
page = self.paginate_queryset(su... | 0.00823 |
def hilbert(self, num_taps=None):
'''Apply an odd-tap Hilbert transform filter, phase-shifting the signal
by 90 degrees. This is used in many matrix coding schemes and for
analytic signal generation. The process is often written as a
multiplication by i (or j), the imaginary unit. An odd... | 0.001721 |
def regionsIntersection(s1, s2, collapse=True):
"""
given two lists of genomic regions with chromosome, start and end
coordinates, return a new list of regions which is the intersection of those
two sets. Lists must be sorted by chromosome and start index
:return: new list that represents the intersection of... | 0.009756 |
def _init_transforms(self, subjs, voxels, features, random_state):
"""Initialize the mappings (Wi) with random orthogonal matrices.
Parameters
----------
subjs : int
The number of subjects.
voxels : list of int
A list with the number of voxels per subjec... | 0.001781 |
def _removeContentPanels(cls, remove):
"""
Remove the panels and so hide the fields named.
"""
if type(remove) is str:
remove = [remove]
cls.content_panels = [panel for panel in cls.content_panels
if getattr(panel, "field_name", None) not... | 0.009063 |
def loads(s: str, load_module: types.ModuleType, **kwargs):
""" Convert a JSON string into a JSGObject
:param s: string representation of JSON document
:param load_module: module that contains declarations for types
:param kwargs: arguments see: json.load for details
:return: JSGObject representing... | 0.004556 |
def file_counts(container=None,
patterns=None,
image_package=None,
file_list=None):
'''file counts will return a list of files that match one or more regular expressions.
if no patterns is defined, a default of readme is used. All patterns and files are made
... | 0.011102 |
def fail(self, key, **kwargs):
"""A helper method that simply raises a `ValidationError`.
"""
try:
msg = self.error_messages[key]
except KeyError:
class_name = self.__class__.__name__
msg = MISSING_ERROR_MESSAGE.format(class_name=class_name,
... | 0.003717 |
def flush(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Flush current ipset set
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
set_check = __salt__['ipset.check... | 0.001756 |
def leave(self, screen_id):
"""Informs the target about a drag and drop leave event.
in screen_id of type int
The screen ID where the drag and drop event occurred.
raises :class:`VBoxErrorVmError`
VMM device is not available.
"""
if not isinstan... | 0.01002 |
def count_fingerprint(word, n_bits=16, most_common=MOST_COMMON_LETTERS_CG):
"""Return the count fingerprint.
This is a wrapper for :py:meth:`Count.fingerprint`.
Parameters
----------
word : str
The word to fingerprint
n_bits : int
Number of bits in the fingerprint returned
... | 0.001135 |
def get_queryset(self, request):
"""
Make special filtering by user's permissions.
"""
if not request.user.has_perm('zinnia.can_view_all'):
queryset = self.model.objects.filter(authors__pk=request.user.pk)
else:
queryset = super(EntryAdmin, self).get_query... | 0.004914 |
def add_library(self, name):
"""Add a library to the database
This method is for adding a library by name (eg: "BuiltIn")
rather than by a file.
"""
libdoc = LibraryDocumentation(name)
if len(libdoc.keywords) > 0:
# FIXME: figure out the path to the library f... | 0.004354 |
def _zlib_no_compress(data):
"""Compress data with zlib level 0."""
cobj = zlib.compressobj(0)
return b"".join([cobj.compress(data), cobj.flush()]) | 0.006289 |
def infer_call_result(self, caller, context=None):
"""infer what a class instance is returning when called"""
context = contextmod.bind_context_to_node(context, self)
inferred = False
for node in self._proxied.igetattr("__call__", context):
if node is util.Uninferable or not ... | 0.005042 |
def commit(self):
"""
Insert the specified text in all selected lines, always
at the same column position.
"""
# Get the number of lines and columns in last line.
last_line, last_col = self.qteWidget.getNumLinesAndColumns()
# If this is the first ever call to th... | 0.000505 |
def login_required(obj):
"""
Requires that the user be logged in order to gain access to the resource
at the specified the URI.
"""
decorator = request_passes_test(lambda r, *args, **kwargs: r.user.is_authenticated())
return wrap_object(obj, decorator) | 0.007246 |
def generate(self, callback=None):
"""
Computes and stores piece data. Returns ``True`` on success, ``False``
otherwise.
:param callback: progress/cancellation callable with method
signature ``(filename, pieces_completed, pieces_total)``.
Useful for reporting pro... | 0.0006 |
def hide_routemap_holder_route_map_content_match_extcommunity_extcommunity_num(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map ... | 0.003697 |
def get_instance_from_id(unique_id):
"""Get an instance of the `PolygonFilter` using a unique id"""
for instance in PolygonFilter.instances:
if instance.unique_id == unique_id:
return instance
# if this does not work:
raise KeyError("PolygonFilter with unique_... | 0.005263 |
def trace_dispatch(self, frame, event, arg):
"""allow to switch to Pdb instance"""
if hasattr(self, 'pdb'):
return self.pdb.trace_dispatch(frame, event, arg)
else:
return Pdb.trace_dispatch(self, frame, event, arg) | 0.007634 |
def find_external_metabolites(model):
"""Return all metabolites in the external compartment."""
ex_comp = find_external_compartment(model)
return [met for met in model.metabolites if met.compartment == ex_comp] | 0.004505 |
def get_cif(code, mmol_number, outfile=None):
"""
Parameters
----------
code : str
PDB code.
mmol_number : int
mmol number (biological assembly number) of file to download. Numbers from PDBe.
If None, defaults to the preferred biological assembly listed for code on the PDBe.
... | 0.003439 |
def post(self):
'''This handles POST requests.
Saves the changes made by the user on the frontend back to the current
checkplot-list.json file.
'''
# if self.readonly is set, then don't accept any changes
# return immediately with a 400
if self.readonly:
... | 0.009225 |
def _unpickle_collection(self, collection):
"""Unpickles all members of the specified dictionary."""
for mkey in collection:
if isinstance(collection[mkey], list):
for item in collection[mkey]:
item.unpickle(self)
else:
collecti... | 0.005831 |
def percentOverlap(x1, x2):
"""
Computes the percentage of overlap between vectors x1 and x2.
@param x1 (array) binary vector
@param x2 (array) binary vector
@param size (int) length of binary vectors
@return percentOverlap (float) percentage overlap between x1 and x2
"""
nonZeroX1 = np.count_no... | 0.014706 |
def _read_response(self, response):
"""
JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON
"""
rclass = response['rclass']
if rclass != "virtual":
raise ArtifactoryException("Repositiry '{}' have '{}', but expect 'virtual'".... | 0.007421 |
def _add_io_handler(self, handler):
"""Add an I/O handler to the loop."""
logger.debug('adding io handler: %r', handler)
self._unprepared_handlers[handler] = None
self._configure_io_handler(handler) | 0.008696 |
def run(self,
force=False,
ipyclient=None,
name_fields=30,
name_separator="_",
dry_run=False):
"""
Download the accessions into a the designated workdir.
Parameters
----------
force: (bool)
If force=True then existing fil... | 0.008396 |
def all_active(cls):
""" List active queues, based on their lengths in Redis. Warning, uses the unscalable KEYS redis command """
prefix = context.get_current_config()["redis_prefix"]
queues = []
for key in context.connections.redis.keys():
if key.startswith(prefix):
... | 0.007595 |
def create_option_value(cls, option_value, **kwargs):
"""Create OptionValue
Create a new OptionValue
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_option_value(option_value, async=Tru... | 0.005556 |
def head(records, head):
"""
Limit results to the top N records.
With the leading `-', print all but the last N records.
"""
logging.info('Applying _head generator: '
'limiting results to top ' + head + ' records.')
if head == '-0':
for record in records:
yi... | 0.001453 |
def create_nsg_rule(access_token, subscription_id, resource_group, nsg_name, nsg_rule_name,
description, protocol='Tcp', source_range='*', destination_range='*',
source_prefix='*', destination_prefix='*', access='Allow', priority=100,
direction='Inbound'):
... | 0.002326 |
def set_tags(name, tags, region=None, key=None, keyid=None, profile=None):
'''
Add the tags on an ELB
.. versionadded:: 2016.3.0
name
name of the ELB
tags
dict of name/value pair tags
CLI Example:
.. code-block:: bash
salt myminion boto_elb.set_tags my-elb-name ... | 0.003367 |
def add_scanner_param(self, name, scanner_param):
""" Add a scanner parameter. """
assert name
assert scanner_param
self.scanner_params[name] = scanner_param
command = self.commands.get('start_scan')
command['elements'] = {
'scanner_params':
{... | 0.005348 |
def learn(self, bottomUpInput, enableInference=None):
"""
TODO: document
:param bottomUpInput:
:param enableInference:
:return:
"""
return self.compute(bottomUpInput, enableLearn=True,
enableInference=enableInference) | 0.014652 |
def packet_read(self):
"""Read packet from network."""
bytes_received = 0
if self.sock == NC.INVALID_SOCKET:
return NC.ERR_NO_CONN
if self.in_packet.command == 0:
ba_data, errnum, errmsg = nyamuk_net.read(self.sock, 1)
if errnum == 0 ... | 0.006279 |
def _game_image_from_screen(self, game_type):
"""Return the image of the given game type from the screen.
Return None if no game is found.
"""
# screen
screen_img = self._screen_shot()
# game image
game_rect = self._game_finders[game_type].locate_in(screen_img)
... | 0.004338 |
def parse_release_id(release_id):
"""
Parse release_id to parts:
{short, version, type}
or
{short, version, type, bp_short, bp_version, bp_type}
:param release_id: Release ID string
:type release_id: str
:rtype: dict
"""
if "@" in release_id:
release, base_product = rele... | 0.001739 |
def packages(
state, host,
packages=None, present=True, latest=False,
update=False, cache_time=None, upgrade=False,
force=False, no_recommends=False,
allow_downgrades=False,
):
'''
Install/remove/update packages & update apt.
+ packages: list of packages to ensure
+ present: whether... | 0.002174 |
def transformer_parsing_base():
"""HParams for parsing on WSJ only."""
hparams = transformer_base()
hparams.attention_dropout = 0.2
hparams.layer_prepostprocess_dropout = 0.2
hparams.max_length = 512
hparams.learning_rate_warmup_steps = 16000
hparams.hidden_size = 1024
hparams.learning_rate = 0.05
hpa... | 0.028497 |
def populate_unique_identifiers(self, metamodel):
'''
Populate a *metamodel* with class unique identifiers previously
encountered from input.
'''
for stmt in self.statements:
if isinstance(stmt, CreateUniqueStmt):
metamodel.define_unique_identifier(stm... | 0.007353 |
def start_search(self):
"""
Start the Gateway Search Request and return the address information
:rtype: (string,int)
:return: a tuple(string(IP),int(Port) when found or None when
timeout occurs
"""
self._asyncio_loop = asyncio.get_event_loop()
# Cre... | 0.001036 |
def create_authentication_string(username, password):
'''
Creates an authentication string from the username and password.
:username: Username.
:password: Password.
:return: The encoded string.
'''
username_utf8 = username.encode('utf-8')
userpw_utf8 = password.encode('utf-8')
user... | 0.003503 |
def clean_password(self, password, user=None):
"""
Validates a password. You can hook into this if you want to
restric the allowed password choices.
"""
min_length = app_settings.PASSWORD_MIN_LENGTH
if min_length and len(password) < min_length:
raise forms.Val... | 0.003891 |
def cql_encode_float(self, val):
"""
Encode floats using repr to preserve precision
"""
if math.isinf(val):
return 'Infinity' if val > 0 else '-Infinity'
elif math.isnan(val):
return 'NaN'
else:
return repr(val) | 0.00678 |
def unique_categories(categories):
"""Pass array-like categories, return sorted cleaned unique categories."""
categories = np.unique(categories)
categories = np.setdiff1d(categories, np.array(settings.categories_to_ignore))
categories = np.array(natsorted(categories, key=lambda v: v.upper()))
return... | 0.006042 |
def handle(self, *args, **options):
"""
Transmit the courseware data for the EnterpriseCustomer(s) to the active integration channels.
"""
username = options['catalog_user']
# Before we do a whole bunch of database queries, make sure that the user we were passed exists.
... | 0.006596 |
def hll_count(expr, error_rate=0.01, splitter=None):
"""
Calculate HyperLogLog count
:param expr:
:param error_rate: error rate
:type error_rate: float
:param splitter: the splitter to split the column value
:return: sequence or scalar
:Example:
>>> df = DataFrame(pd.DataFrame({'a... | 0.003989 |
def mid_lvl_cmds_encode(self, target, hCommand, uCommand, rCommand):
'''
Mid Level commands sent from the GS to the autopilot. These are only
sent when being operated in mid-level commands mode
from the ground.
target : ... | 0.008439 |
def Mersmann_Kind_predictor(atoms, coeff=3.645, power=0.5,
covalent_radii=rcovs_Mersmann_Kind):
r'''Predicts the critical molar volume of a chemical based only on its
atomic composition according to [1]_ and [2]_. This is a crude approach,
but provides very reasonable
estima... | 0.007771 |
def register_cache_buster(self, app, config=None):
"""
Register `app` in cache buster so that `url_for` adds a unique prefix
to URLs generated for the `'static'` endpoint. Also make the app able
to serve cache-busted static files.
This allows setting long cache expiration values... | 0.001052 |
def clean_inputs(data):
"""Clean BED input files to avoid overlapping segments that cause downstream issues.
Per-merges inputs to avoid needing to call multiple times during later parallel steps.
"""
if not utils.get_in(data, ("config", "algorithm", "variant_regions_orig")):
data["config"]["alg... | 0.005722 |
def bootstrap(**kwargs):
""" Bootstrap an EC2 instance that has been booted into an AMI from http://www.daemonology.net/freebsd-on-ec2/
Note: deprecated, current AMI images are basically pre-bootstrapped, they just need to be configured.
"""
# the user for the image is `ec2-user`, there is no sudo, but ... | 0.004237 |
def get_entries(self, start=0, end=0, data_request=None, steam_ids=None):
"""Get leaderboard entries.
:param start: start entry, not index (e.g. rank 1 is ``start=1``)
:type start: :class:`int`
:param end: end entry, not index (e.g. only one entry then ``start=1,end=1``)
:type e... | 0.003147 |
def leaves(self, fragment_type=None):
"""
The current list of sync map fragments
which are (the values of) the leaves
of the sync map tree.
:rtype: list of :class:`~aeneas.syncmap.fragment.SyncMapFragment`
.. versionadded:: 1.7.0
"""
leaves = self.fragme... | 0.006289 |
def pull_all_rtl(configuration):
"""
Pulls all translations - reviewed or not - for RTL languages
"""
print("Pulling all translated RTL languages from transifex...")
for lang in configuration.rtl_langs:
print('rm -rf conf/locale/' + lang)
execute('rm -rf conf/locale/' + lang)
... | 0.002353 |
def get_bin(self):
"""Return the binary notation of the address/netmask."""
return _convert(self._ip_dec, notation=IP_BIN,
inotation=IP_DEC, _check=False, _isnm=self._isnm) | 0.009434 |
def find(self, other):
"""Return an interable of elements that overlap other in the tree."""
iset = self._iset
l = binsearch_left_start(iset, other[0] - self._maxlen, 0, len(iset))
r = binsearch_right_end(iset, other[1], 0, len(iset))
iopts = iset[l:r]
iiter = (s for s in... | 0.01 |
def stop_server(self, datacenter_id, server_id):
"""
Stops the server.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param server_id: The unique ID of the server.
:type server_id: ``str``
"""
... | 0.003802 |
def for_branch(self, branch):
"""
Return a new CourseLocator for another branch of the same library (also version agnostic)
"""
if self.org is None and branch is not None:
raise InvalidKeyError(self.__class__, "Branches must have full library ids not just versions")
r... | 0.010753 |
def td_taper(out, start, end, beta=8, side='left'):
"""Applies a taper to the given TimeSeries.
A half-kaiser window is used for the roll-off.
Parameters
----------
out : TimeSeries
The ``TimeSeries`` to taper.
start : float
The time (in s) to start the taper window.
end :... | 0.000694 |
def get_array_shape(self, key):
"""Return array's shape"""
data = self.model.get_data()
return data[key].shape | 0.014599 |
def _report_completion(self):
"""Update shared counters to signal that we are done with this cluster.
Call just before exiting run() method (in a finally clause)"""
rem_clust = self.remaining_clusters
if rem_clust is not None:
# -= is non-atomic, need to acquire a lock
... | 0.003515 |
def get_catalog_hierarchy_session(self, proxy):
"""Gets the catalog hierarchy traversal session.
arg: proxy (osid.proxy.Proxy): proxy
return: (osid.cataloging.CatalogHierarchySession) - a
``CatalogHierarchySession``
raise: NullArgument - ``proxy`` is null
rai... | 0.003704 |
def var(inlist):
"""
Returns the variance of the values in the passed list using N-1
for the denominator (i.e., for estimating population variance).
Usage: lvar(inlist)
"""
n = len(inlist)
mn = mean(inlist)
deviations = [0] * len(inlist)
for i in range(len(inlist)):
deviations[i] = inlist... | 0.00271 |
def minkowski_distance(point1, point2, degree=2):
"""!
@brief Calculate Minkowski distance between two vectors.
\f[
dist(a, b) = \sqrt[p]{ \sum_{i=0}^{N}\left(a_{i} - b_{i}\right)^{p} };
\f]
@param[in] point1 (array_like): The first vector.
@param[in] point2 (array_like): The seco... | 0.005997 |
def find_protein_complexes(model):
"""
Find reactions that are catalyzed by at least a heterodimer.
Parameters
----------
model : cobra.Model
The metabolic model under investigation.
Returns
-------
list
Reactions whose gene-protein-reaction association contains at leas... | 0.001531 |
def make_draft(self):
"""
Make this version the draft
"""
assert self.__class__ == self.get_version_class()
# If this is draft do nothing
if self.state == self.DRAFT:
return
with xact():
# Delete whatever is currently this draft
... | 0.002436 |
def from_file(cls, filename="CTRL", **kwargs):
"""
Creates a CTRL file object from an existing file.
Args:
filename: The name of the CTRL file. Defaults to 'CTRL'.
Returns:
An LMTOCtrl object.
"""
with zopen(filename, "rt") as f:
cont... | 0.005115 |
def initialize(self):
"""
Initialize the self._tm if not already initialized.
"""
if self._tm is None:
params = {
"columnCount": self.columnCount,
"basalInputSize": self.basalInputWidth,
"apicalInputSize": self.apicalInputWidth,
"cellsPerColumn": self.cellsPerColum... | 0.005732 |
def scheme(name, bins, bin_method='quantiles'):
"""Return a custom scheme based on CARTOColors.
Args:
name (str): Name of a CARTOColor.
bins (int or iterable): If an `int`, the number of bins for classifying
data. CARTOColors have 7 bins max for quantitative data, and 11 max
... | 0.00096 |
def classes_can_admin(self):
"""Return all the classes (sorted) that this user can admin."""
if self.is_admin:
return sorted(Session.query(Class).all())
else:
return sorted(self.admin_for) | 0.008475 |
def _load_embedding(self, pretrained_file_path, elem_delim,
encoding='utf8'):
"""Load embedding vectors from a pre-trained token embedding file.
Both text files and TokenEmbedding serialization files are supported.
elem_delim and encoding are ignored for non-text files.
... | 0.004954 |
def html_factory(tag, **defaults):
'''Returns an :class:`Html` factory function for ``tag`` and a given
dictionary of ``defaults`` parameters. For example::
>>> input_factory = html_factory('input', type='text')
>>> html = input_factory(value='bla')
'''
def html_input(*children, **params):
... | 0.002315 |
def get_sign_key(exported_session_key, magic_constant):
"""
3.4.5.2 SIGNKEY
@param exported_session_key: A 128-bit session key used to derive signing and sealing keys
@param magic_constant: A constant value set in the MS-NLMP documentation (constants.SignSealConstants)
@return sign_key: Key used to... | 0.006834 |
def _add_kwarg_datasets(datasets, kwargs):
"""Add data sets of the given kwargs.
:param datasets:
The dict where to accumulate data sets.
:type datasets:
`dict`
:param kwargs:
Dict of pre-named data sets.
:type kwargs:
`dict` of `unicode` to varies
"""
for te... | 0.002392 |
async def send_script(self, conn_id, data):
"""Send a a script to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
data (bytes): the script to send to the device
"""
self._ensure_connection(conn_id, True)
con... | 0.008078 |
def start(self, attempts=5, timeout=2):
"""
Start the network, will check if the network is active ``attempts``
times, waiting ``timeout`` between each attempt.
Args:
attempts (int): number of attempts to check the network is active
timeout (int): timeout for ea... | 0.001566 |
def __model_class(self, model_name):
""" this method is used by the lru_cache, do not call directly """
build_schema = deepcopy(self.definitions[model_name])
return self.schema_class(build_schema, model_name) | 0.008621 |
def create_data_element_from_resource(self, resource):
"""
Returns a new data element for the given resource object.
:returns: object implementing :class:`IResourceDataElement`.
"""
mp = self.__mp_reg.find_or_create_mapping(type(resource))
return mp.data_element_class.cr... | 0.005747 |
def reactions_to_files(model, dest, writer, split_subsystem):
"""Turn the reaction subsystems into their own files.
If a subsystem has a number of reactions over the threshold, it gets its
own YAML file. All other reactions, those that don't have a subsystem or
are in a subsystem that falls below the t... | 0.00034 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.