text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def on(self, left_speed, right_speed):
"""
Start rotating the motors according to ``left_speed`` and ``right_speed`` forever.
Speeds can be percentages or any SpeedValue implementation.
"""
(left_speed_native_units, right_speed_native_units) = self._unpack_speeds_to_native_units(... | 0.004489 |
def strftime(dt, fmt):
'''
`strftime` implementation working before 1900
'''
if _illegal_s.search(fmt):
raise TypeError("This strftime implementation does not handle %s")
if dt.year > 1900:
return dt.strftime(fmt)
fmt = fmt.replace('%c', '%a %b %d %H:%M:%S %Y')\
.re... | 0.001289 |
def subsampleCorrelatedData(A_t, g=None, fast=False, conservative=False, verbose=False):
"""Determine the indices of an uncorrelated subsample of the data.
Parameters
----------
A_t : np.ndarray
A_t[t] is the t-th value of timeseries A(t). Length is deduced from vector.
g : float, optional... | 0.004409 |
def generate_version_py(packagename=None, version=None, release=None, debug=None,
uses_git=None, srcdir='.'):
"""
Generate a version.py file in the package with version information, and
update developer version strings.
This function should normally be called without any argumen... | 0.001098 |
def init(self, input_dim=0, input_dims=None, no_prepare=False):
"""
Initialize the layer.
:param no_prepare: avoid calling preparation function
"""
if self.initialized:
return
# configure input dimensions
if input_dims:
self.input_dims = in... | 0.002805 |
def get_keystone_endpoint(self, keystone_ip, api_version=None,
admin_port=False):
"""Return keystone endpoint"""
port = 5000
if admin_port:
port = 35357
base_ep = "http://{}:{}".format(keystone_ip.strip().decode('utf-8'),
... | 0.006383 |
def upload_file(self, owner, id, name, **kwargs):
"""
Upload file
Upload one file at a time to a dataset. This endpoint expects requests of type `application/octet-stream`. For example, assuming that you want to upload a local file named `file1.csv` to a hypothetical dataset `https://data.worl... | 0.003138 |
def get_headerReference(self, type_):
"""Return headerReference element of *type_* or None if not present."""
matching_headerReferences = self.xpath(
"./w:headerReference[@w:type='%s']" % WD_HEADER_FOOTER.to_xml(type_)
)
if len(matching_headerReferences) == 0:
ret... | 0.008065 |
def get_plaintext_citations(bbl):
"""
Parse a ``*.bbl`` file to get a clean list of plaintext citations.
:param bbl: Either the path to the .bbl file or the content of a ``.bbl`` \
file.
:returns: A list of cleaned plaintext citations.
"""
# Handle path or content
if os.path.is... | 0.001159 |
def validate_wrap(self, value):
''' Checks that ``value`` is an instance of ``DocumentField.type``.
if it is, then validation on its fields has already been done and
no further validation is needed.
'''
if not isinstance(value, self.type):
self._fail_validatio... | 0.005814 |
def p_statement_switch(p):
'statement : SWITCH LPAREN expr RPAREN switch_case_list'
p[0] = ast.Switch(p[3], p[5], lineno=p.lineno(1)) | 0.007092 |
def get_items(self):
"""Returns a list of SuperModel items
"""
uids = self.get_uids()
if not uids:
return [SuperModel(self.context)]
items = map(lambda uid: SuperModel(uid), uids)
return self._resolve_number_of_copies(items) | 0.007042 |
def do(self, func, *args, **kwargs):
"""Apply the function to myself, and return myself.
Look up the function in the database if needed. Pass it any
arguments given, keyword or positional.
Useful chiefly when chaining.
"""
if not callable(func):
func = geta... | 0.004914 |
def register(linter):
'''required method to auto register this checker '''
linter.register_checker(StringCurlyBracesFormatIndexChecker(linter))
linter.register_checker(StringLiteralChecker(linter)) | 0.004785 |
def load_hours(network, min_load=0.9, max_load=1, boundaries=[0, 8760]):
"""Plot number of hours with line loading in selected range.
Parameters
----------
network: PyPSA network container
Holds topology of grid including results from powerflow analysis
min_load: float
Cho... | 0.004151 |
def Meissner(Tc=None, Pc=None, Vc=None):
r'''Old (1942) relationship for estimating critical
properties from each other. Two of the three properties are required.
This model uses the "critical surface", a general plot of Tc vs Pc vs Vc.
The model used 42 organic and inorganic compounds to derive the equ... | 0.000492 |
def get_categories(self, app_name):
"""
Returns a list of the categories for an app name.
"""
cat_nums = self.apps.get(app_name, {}).get("cats", [])
cat_names = [self.categories.get("%s" % cat_num, "")
for cat_num in cat_nums]
return cat_names | 0.00639 |
def parse_tags(self, tags):
"""Parse tags into a dict.
input tags: a comma separated list of 'key:value' pairs.
Example: foo:bar,spam:eggs
output dtags: a dict of tags.
Example: {'foo': 'bar', 'spam': 'eggs'}
"""
dtags = {}
if tags:
tr... | 0.003378 |
def smooth_normals(positions, normals):
'''Assigns an averaged normal to each position based on all of the normals
originally used for the position.
'''
lookup = defaultdict(list)
for position, normal in zip(positions, normals):
lookup[position].append(normal)
result = []
for positio... | 0.001736 |
def get_file(self, fid):
"""Get file from WeedFS.
Returns file content. May be problematic for large files as content is
stored in memory.
Args:
**fid**: File identifier <volume_id>,<file_name_hash>
Returns:
Content of the file with provided fid or None... | 0.004057 |
def Debugger_setAsyncCallStackDepth(self, maxDepth):
"""
Function path: Debugger.setAsyncCallStackDepth
Domain: Debugger
Method name: setAsyncCallStackDepth
Parameters:
Required arguments:
'maxDepth' (type: integer) -> Maximum depth of async call stacks. Setting to <code>0</code> will effective... | 0.039945 |
def difference(self, reference, hypothesis, uem=None, uemified=False):
"""Get error analysis as `Annotation`
Labels are (status, reference_label, hypothesis_label) tuples.
`status` is either 'correct', 'confusion', 'missed detection' or
'false alarm'.
`reference_label` is None i... | 0.000907 |
def parse_query_param(url, param):
"""Parses the query string of a URL and returns the value of a parameter.
Args:
url: A URL.
param: A string representing the name of the parameter.
Returns:
The value of the parameter.
"""
try:
return parse.parse_qs(parse.urlparse... | 0.005348 |
def parse_signed_request(self, signed_request):
'''
parse signed request when using in-site app.
Returns:
dict object like { 'uid': 12345, 'access_token': 'ABC123XYZ', 'expires': unix-timestamp },
or None if parse failed.
'''
def _b64_normalize(s):
... | 0.003333 |
def ticket_flag(self, which, new=None):
"""
Get or set a ticket flag.
'which' can be either a string ('APPEND_CR' etc.), or an integer.
You should ALWAYS use a string, unless you really know what you are doing.
"""
flag = _get_flag(which, TicketFlags)
if flag:
... | 0.008212 |
def hs_indices(self):
"""tuple of (anchor_idx, addend_idxs) pair for each subtotal.
Example::
(
(2, (0, 1, 2)),
(3, (3,)),
('bottom', (4, 5))
)
Note that the `anchor_idx` item in the first position of each pair
ca... | 0.00431 |
def describe(self, fields=None, io=None, **kwargs):
"""
:param fields: dict where the keys are field names that should
be returned, and values should be set to True (by default,
all fields are returned)
:type fields: dict
:param io: Include input and output fields... | 0.002976 |
def default_indexes(
coords: Mapping[Any, Variable],
dims: Iterable,
) -> 'OrderedDict[Any, pd.Index]':
"""Default indexes for a Dataset/DataArray.
Parameters
----------
coords : Mapping[Any, xarray.Variable]
Coordinate variables from which to draw default indexes.
dims : iterable
... | 0.001645 |
def RIBVRFRouteLimitExceeded_VRFName(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
RIBVRFRouteLimitExceeded = ET.SubElement(config, "RIBVRFRouteLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream")
VRFName = ET.SubElement(RIBVRFRou... | 0.006211 |
def code_block(self, code, language, indent=0):
"""Example::
.. code-block:: python
from __future__ import print_function
import math
print(math.sqrt(10.0))
"""
if language not in [None, "console", "python", "ruby", "c"]:
... | 0.00314 |
def get_certificate_der(self, filename):
"""
Return the DER coded X.509 certificate from the signature file.
:param filename: Signature filename in APK
:returns: DER coded X.509 certificate as binary
"""
pkcs7message = self.get_file(filename)
pkcs7obj = cms.Cont... | 0.004608 |
def _write_ini(source_dict, namespace_name=None, level=0, indent_size=4,
output_stream=sys.stdout):
"""this function prints the components of a configobj ini file. It is
recursive for outputing the nested sections of the ini file."""
options = [
value
... | 0.000966 |
def disconnect(self, node):
"""
Disconnect a node
:param node:
:return:
"""
rel = _rel_helper(lhs='a', rhs='b', ident='r', **self.definition)
q = "MATCH (a), (b) WHERE id(a)={self} and id(b)={them} " \
"MATCH " + rel + " DELETE r"
self.source.... | 0.005747 |
def on_message(self, message):
"""Pass response from server to process receive queue
Args:
message(str): Received message
"""
# Called in tornado loop
try:
self.log.debug("Got message %s", message)
d = json_decode(message)
response... | 0.001812 |
def _wait(self, args, now, cap, consumed_history, consumed_capacity):
""" Check the consumed capacity against the limit and sleep """
for key in ['read', 'write']:
if key in cap and cap[key] > 0:
consumed_history[key].add(now, consumed_capacity[key])
consumed ... | 0.002353 |
def calculate(bam_file, data, sv_bed):
"""Calculate coverage in parallel using mosdepth.
Removes duplicates and secondary reads from the counts:
if ( b->core.flag & (BAM_FUNMAP | BAM_FSECONDARY | BAM_FQCFAIL | BAM_FDUP) ) continue;
"""
params = {"min": dd.get_coverage_depth_min(data)}
variant_r... | 0.005291 |
def rows(self):
"""Iterate over all of the rows"""
for s_name, s in self.sections.items():
# Yield the section header
if s.name != 'Root':
yield [''] # Unecessary, but makes for nice formatting. Should actually be done just before write
yield [... | 0.007429 |
def bidiagonalize_real_matrix_pair_with_symmetric_products(
mat1: np.ndarray,
mat2: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8,
check_preconditions: bool = True) -> Tuple[np.ndarray, np.ndarray]:
"""Finds orthogonal matrices that diagonalize both mat1 and m... | 0.000924 |
def append_row(self, index, values, new_cols=True):
"""
Appends a row of values to the end of the data. If there are new columns in the values and new_cols is True
they will be added. Be very careful with this function as for sort DataFrames it will not enforce sort order.
Use this only... | 0.004931 |
def search_feature_sets(self, dataset_id):
"""
Returns an iterator over the FeatureSets fulfilling the specified
conditions from the specified Dataset.
:param str dataset_id: The ID of the
:class:`ga4gh.protocol.Dataset` of interest.
:return: An iterator over the :cl... | 0.002963 |
def url_unquote(s, charset='utf-8', errors='replace'):
"""URL decode a single string with a given decoding.
Per default encoding errors are ignored. If you want a different behavior
you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a
`HTTPUnicodeError` is raised.
:param s: th... | 0.001742 |
def get_app_ext(self, loops=float('inf')):
""" get_app_ext(loops=float('inf'))
Application extention. This part specifies the amount of loops.
If loops is 0 or inf, it goes on infinitely.
"""
if loops == 0 or loops == float('inf'):
loops = 2**16 - 1
# b... | 0.004335 |
def _create_index_content(words):
"""Create html string of index file.
Parameters
----------
words : list of str
List of cached words.
Returns
-------
str
html string.
"""
content = ["<h1>Index</h1>", "<ul>"]
for word in words:
content.append(
... | 0.00367 |
def nodes_minimum_distance_validation(self):
"""
if minimum distance is specified, ensure node is not too close to other nodes;
"""
if self.layer and self.layer.nodes_minimum_distance:
minimum_distance = self.layer.nodes_minimum_distance
# TODO - lower priority: do this check only when c... | 0.008143 |
def conv_output_length(input_length, filter_size, border_mode, stride,
dilation=1):
""" Compute the length of the output sequence after 1D convolution along
time. Note that this function is in line with the function used in
Convolution1D class from Keras.
Params:
i... | 0.001045 |
def generate_child_leaf_nodes(self):
"""
Generate leaf nodes of this node.
"""
def _yield_child_leaf_nodes(node):
"""
Args:
node:
Yields:
"""
if not node.has_children():
yield node
... | 0.004637 |
def fit(self, text, epochs=EPOCHS):
""" Given a string `text`, use it to train the segmentation classifier for `epochs` iterations.
"""
logger.debug("Extracting features and classifications.")
Phi = []
Y = []
for (L, P, R, gold, _) in Detector.candidates(text):
... | 0.006356 |
def stored_bind(self, instance):
"""Bind an instance to this Pangler, using the bound Pangler store.
This method functions identically to `bind`, except that it might
return a Pangler which was previously bound to the provided instance.
"""
if self.id is None:
retu... | 0.003752 |
def post(interface, method, version=1,
apihost=DEFAULT_PARAMS['apihost'], https=DEFAULT_PARAMS['https'],
caller=None, session=None, params=None):
"""Send POST request to an API endpoint
.. versionadded:: 0.8.3
:param interface: interface name
:type interface: str
:param method: m... | 0.00223 |
def get_constant(self, const_name, context):
""" Return unrolled const """
# check if value is compatible with
const = self._constants[const_name]
if isinstance(const, ast.AnnAssign): # Handle ByteArrays.
if context:
expr = Expr(const.value, context).lll_no... | 0.004754 |
def _format_batch_statuses(statuses, batch_ids, tracker):
"""Takes a statuses dict and formats it for transmission with Protobuf and
ZMQ.
Args:
statuses (dict of int): Dict with batch ids as the key, status as value
batch_ids (list of str): The batch ids in their original order
trac... | 0.000905 |
def left_join(input, **params):
"""
Left join transformation
:param input:
:param params:
:return:
"""
PARAM_COL_RIGHT = 'col.right'
PARAM_COL_LEFT = 'col.left'
PARAM_FIELD_JOIN = 'field.join'
right_df = pd.DataFrame.from_records(input[params.get(PARAM_COL_RIGHT)])
left_df =... | 0.003419 |
def stopPoll(self, msg_identifier,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#stoppoll
:param msg_identifier:
a 2-tuple (``chat_id``, ``message_id``),
a 1-tuple (``inline_message_id``),
or simply ``inline_message_id``.
... | 0.006757 |
def _get_serializable_model(cls):
"""
Returns a model with a valid _meta.local_fields (serializable).
Basically, this means the original model, not a proxied model.
(this is a workaround for a bug in django)
"""
current_class = cls
while current_class._meta.prox... | 0.004819 |
def get_stencil(self, stencil_name, **options):
"""Return a Stencil instance given a stencil name."""
if stencil_name not in self.manifest.get('stencils', {}):
raise ValueError("Stencil '%s' not declared in StencilSet "
"manifest." % stencil_name)
stencil... | 0.001514 |
def avl_join2(t1, t2):
"""
join two trees without any intermediate key
Returns:
Node: new_root
O(log(n) + log(m)) = O(r(t1) + r(t2))
For AVL-Trees the rank r(t1) = height(t1) - 1
"""
if t1 is None and t2 is None:
new_root = None
elif t2 is None:
new_root = t1
... | 0.000878 |
def print_version():
"""Print the environment versions."""
click.echo("Versions:")
click.secho(
"CLI Package Version: %(version)s"
% {"version": click.style(get_cli_version(), bold=True)}
)
click.secho(
"API Package Version: %(version)s"
% {"version": click.style(get_... | 0.002841 |
def check(self):
"""Check this transaction for completeness"""
if not self.date:
raise XnDataError("Missing date")
if not self.desc:
raise XnDataError("Missing description")
if not self.dst:
raise XnDataError("No destination accounts")
if not s... | 0.00432 |
def makeLogic(self):
# *** When camera list has been closed, re-create the cameralist tree and update filterchains ***
# self.manage_cameras_win.signals.close.connect(self.updateCameraTree) # now put into save_camera_config_slot
# self.manage_cameras_win.signals.close.connect(self.filte... | 0.011045 |
def directionality(image, min_distance = 4, threshold = 0.1, voxelspacing = None, mask = slice(None)):
r"""
Takes a simple or multi-spectral image and returns the directionality of the image texture.
It is just a value representing the strength of directionality, not the specific direction.
An edg... | 0.014148 |
def map(self, options=None):
"""Trigger find of serialized sources and build objects"""
for path, data in self.paths.items():
for item in data:
for obj in self.create_class(item, options):
obj.jinja_env = self.jinja_env
self.add_object(... | 0.006173 |
def _naive_concordance_summary_statistics(event_times, predicted_event_times, event_observed):
"""
Fallback, simpler method to compute concordance.
Assumes the data has been verified by lifelines.utils.concordance_index first.
"""
num_pairs = 0.0
num_correct = 0.0
num_tied = 0.0
for a,... | 0.004184 |
def _canvas_route(self, *args, **kwargs):
""" Decorator for canvas route
"""
def outer(view_fn):
@self.route(*args, **kwargs)
def inner(*args, **kwargs):
fn_args = getargspec(view_fn)
try:
idx = fn_args.args.index(_ARG_KEY)
except ValueErr... | 0.001704 |
def run(self):
"""run the model"""
model = self.model
configfile = self.configfile
interval = self.interval
sockets = self.sockets
model.initialize(configfile)
if model.state == 'pause':
logger.info(
"model initialized and started in ... | 0.001693 |
def set(self, key, data, retry=0):
"""
Store data <data> index by key <key>
Args
key <string> couchbase document id
data <dict> data to store
"""
try:
if type(data) != dict:
raise Exception("data needs to be of type <dict>")
self.bucket.set(key, 0, 0, json.d... | 0.019663 |
def set_element(self, index, e):
r""" Replaces a pipeline stage.
Replace an element in chain and return replaced element.
"""
if index > len(self._chain):
raise IndexError("tried to access element %i, but chain has only %i"
" elements" % (index, ... | 0.002685 |
def get_type_data(name):
"""Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
"""
name = name.upper()
try:
return {
'authority': 'okapia.net',
'namespace': 'TextFormats',
'identifier': name,
'... | 0.001486 |
def update_proficiency(self, proficiency_form):
"""Updates an existing proficiency.
arg: proficiency_form (osid.learning.ProficiencyForm): the
form containing the elements to be updated
raise: IllegalState - ``proficiency_form`` already used in an
update tran... | 0.004111 |
def validate(cls, partial=True, **kwargs):
"""
Validate kwargs before setting attributes on the model
"""
data = kwargs
if not partial:
data = dict(**kwargs, **{col.name: None for col in cls.__table__.c
if col.name not in kwargs})
... | 0.002717 |
def night(self, date=None, local=True, use_elevation=True):
"""Calculates the night time (the time between astronomical dusk and
astronomical dawn of the next day)
:param date: The date for which to calculate the start of the night time.
If no date is specified then the cur... | 0.005505 |
def sct2e(sc, sclkdp):
"""
Convert encoded spacecraft clock ("ticks") to ephemeris
seconds past J2000 (ET).
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sct2e_c.html
:param sc: NAIF spacecraft ID code.
:type sc: int
:param sclkdp: SCLK, encoded as ticks since spacecraft clock st... | 0.001712 |
def read_int32(self, little_endian=True):
"""
Read 4 bytes as a signed integer value from the stream.
Args:
little_endian (bool): specify the endianness. (Default) Little endian.
Returns:
int:
"""
if little_endian:
endian = "<"
... | 0.007538 |
def _eq(self, T, P):
"""Procedure for calculate the composition in saturation state
Parameters
----------
T : float
Temperature [K]
P : float
Pressure [MPa]
Returns
-------
Asat : float
Saturation mass fraction of dry ... | 0.002339 |
def radius_server_host_retries(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
radius_server = ET.SubElement(config, "radius-server", xmlns="urn:brocade.com:mgmt:brocade-aaa")
host = ET.SubElement(radius_server, "host")
hostname_key = ET.SubEleme... | 0.005208 |
def read_google(self,url,**kwargs):
"""
Reads a google sheet
"""
if url[-1]!='/':
url+='/'
return self.read_csv(url+'export?gid=0&format=csv',**kwargs) | 0.075949 |
def translate(self, trans_inputs: List[TranslatorInput]) -> List[TranslatorOutput]:
"""
Batch-translates a list of TranslatorInputs, returns a list of TranslatorOutputs.
Splits oversized sentences to sentence chunks of size less than max_input_length.
:param trans_inputs: List of Transl... | 0.006532 |
def delete_group_maintainer(self, grp_name, user):
"""Delete the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user (string): User to add to group.
Raises:
requests.HTT... | 0.003984 |
def generate(self, api):
"""
Generates a module for each namespace.
Each namespace will have Python classes to represent data types and
routes in the Stone spec.
"""
rsrc_folder = os.path.join(os.path.dirname(__file__), 'python_rsrc')
self.logger.info('Copying st... | 0.003743 |
def authenticate(self, token):
""" Authenticate a token
:param token:
"""
if self.verify_token_callback:
# Specified verify function overrides below
return self.verify_token_callback(token)
if not token:
return False
name = self.toke... | 0.004878 |
def fetch(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
"""Convenience wrapper for database SELECT and fetch all."""
return select(table, cols, where, group, order, limit, **kwargs).fetchall() | 0.004464 |
def _py_invar(parameter, lparams, tab):
"""Returns the code to create the local input parameter that is coerced to have the
correct type for ctypes interaction.
"""
if ("in" in parameter.direction and parameter.D > 0):
if parameter.direction == "(inout)" and ":" not in parameter.dimension:
... | 0.006679 |
def gradients_X(self, dL_dK, X, X2=None):
"""Compute the gradient of the objective function with respect to X.
:param dL_dK: An array of gradients of the objective function with respect to the covariance function.
:type dL_dK: np.ndarray (num_samples x num_inducing)
:param X: Observed d... | 0.004673 |
def as_dict(self):
"""
Serializes the object necessary data in a dictionary.
:returns: Serialized data in a dictionary.
:rtype: dict
"""
result_dict = super(Group, self).as_dict()
statuses = list()
version = None
titles = list()
descript... | 0.001212 |
def get_filter_value(self, column_name):
"""
Returns the filtered value for a certain column
:param column_name: The name of the column that we want the value from
:return: the filter value of the column
"""
for flt, value in zip(self.filters, self.values):
... | 0.007614 |
def glance(msg, flavor='chat', long=False):
"""
Extract "headline" info about a message.
Use parameter ``long`` to control whether a short or long tuple is returned.
When ``flavor`` is ``chat``
(``msg`` being a `Message <https://core.telegram.org/bots/api#message>`_ object):
- short: (content_... | 0.005061 |
def save_and_scan(filename, b64_data):
"""
Save `b64_data` to temporary file and scan it for viruses.
Args:
filename (str): Name of the file - used as basename for tmp file.
b64_data (str): Content of the file encoded in base64.
Returns:
dict: ``{filename: ("FOUND", "virus type... | 0.001715 |
def stop_artifact_creation(self, id_or_uri, task_uri):
"""
Stops creation of the selected Artifact Bundle.
Args:
id_or_uri: ID or URI of the Artifact Bundle.
task_uri: Task URI associated with the Artifact Bundle.
Returns:
string:
"""
... | 0.005871 |
def bar(self, x=None, y=None, **kwds):
"""
Vertical bar plot.
A bar plot is a plot that presents categorical data with
rectangular bars with lengths proportional to the values that they
represent. A bar plot shows comparisons among discrete categories. One
axis of the pl... | 0.000695 |
def cli(ctx, profile):
"""dw commands support working with multiple data.world accounts
\b
Use a different <profile> value for each account.
In the absence of a <profile>, 'default' will be used.
"""
if ctx.obj is None:
ctx.obj = {}
ctx.obj['profile'] = profile
pass | 0.003257 |
def breadth_first_vertex_order(vertices_resources, nets):
"""A generator which iterates over a set of vertices in a breadth-first
order in terms of connectivity.
For use as a vertex ordering for the sequential placer.
"""
# Special case: no vertices, just stop immediately
if len(vertices_resour... | 0.000822 |
def output_tray_status(self) -> Dict[int, Dict[str, str]]:
"""Return the state of all output trays."""
tray_status = {}
try:
tray_stat = self.data.get('outputTray', [])
for i, stat in enumerate(tray_stat):
tray_status[i] = {
'nam... | 0.003738 |
def _generate_linear_range(start, end, periods):
"""Generate an equally-spaced sequence of cftime.datetime objects between
and including two dates (whose length equals the number of periods)."""
import cftime
total_seconds = (end - start).total_seconds()
values = np.linspace(0., total_seconds, peri... | 0.001773 |
def event_list_tabs(counts, current_kind, page_number=1):
"""
Displays the tabs to different event_list pages.
`counts` is a dict of number of events for each kind, like:
{'all': 30, 'gig': 12, 'movie': 18,}
`current_kind` is the event kind that's active, if any. e.g. 'gig',
'movie', e... | 0.001126 |
def filename_input(self, path_or_filename):
'''
Open and read input from a *path or filename*, and parse its content.
If the filename is a directory, files that ends with .xtuml located
somewhere in the directory or sub directories will be loaded as well.
'''
if ... | 0.005988 |
def grp_start_len(a):
"""Given a sorted 1D input array `a`, e.g., [0 0, 1, 2, 3, 4, 4, 4], this
routine returns the indices where the blocks of equal integers start and
how long the blocks are.
"""
# https://stackoverflow.com/a/50394587/353337
m = numpy.concatenate([[True], a[:-1] != a[1:], [Tru... | 0.002551 |
def read_packet(self):
"""Reads a RTMP packet from the server.
Returns a :class:`RTMPPacket`.
Raises :exc:`RTMPError` on error.
Raises :exc:`RTMPTimeoutError` on timeout.
Usage::
>>> packet = conn.read_packet()
>>> packet.body
b'packet body ...'
... | 0.002317 |
def RootGroup(self):
"""Returns group object for datacenter root group.
>>> clc.v2.Datacenter().RootGroup()
<clc.APIv2.group.Group object at 0x105feacd0>
>>> print _
WA1 Hardware
"""
return(clc.v2.Group(id=self.root_group_id,alias=self.alias,session=self.session)) | 0.042705 |
def _gpdfit(x):
"""Estimate the parameters for the Generalized Pareto Distribution (GPD).
Empirical Bayes estimate for the parameters of the generalized Pareto
distribution given the data.
Parameters
----------
x : array
sorted 1D data array
Returns
-------
k : float
... | 0.002088 |
def from_packets(packets, sequence=0, default_size=4096,
wiggle_room=2048):
"""Construct a list of Ogg pages from a list of packet data.
The algorithm will generate pages of approximately
default_size in size (rounded down to the nearest multiple of
255). However, i... | 0.001262 |
def _distance(self, x0, y0, x1, y1):
"""Utitlity function to compute distance between points."""
dx = x1-x0
dy = y1-y0
# roll displacements across the borders
if self.pix:
dx[ dx > self.Lx/2 ] -= self.Lx
dx[ dx < -self.Lx/2 ] += self.Lx
if self.piy... | 0.023148 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.