text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def set_feature(dev, feature, recipient = None):
r"""Set/enable a specific feature.
dev is the Device object to which the request will be
sent to.
feature is the feature you want to enable.
The recipient can be None (on which the status will be queried
from the device), an Interface or Endpoi... | 0.018803 |
def load_waypoints(self, filename):
'''load waypoints from a file'''
self.wploader.target_system = self.target_system
self.wploader.target_component = self.target_component
try:
self.wploader.load(filename)
except Exception as msg:
print("Unable to load %s... | 0.006263 |
def create_floating_ip(kwargs=None, call=None):
'''
Create a new floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2'
salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='12... | 0.006667 |
def get_arg_value(state, host, arg):
'''
Runs string arguments through the jinja2 templating system with a state and
host. Used to avoid string formatting in deploy operations which result in
one operation per host/variable. By parsing the commands after we generate
the ``op_hash``, multiple command... | 0.000912 |
def _imputeMissing(X, center=True, unit=True, betaNotUnitVariance=False, betaA=1.0, betaB=1.0):
'''
fill in missing values in the SNP matrix by the mean value
optionally center the data and unit-variance it
Args:
X: scipy.array of SNP values. If dtype=='int8' the missin... | 0.017027 |
def add_operation(self, operation_type, operation, mode=None):
"""Add an operation to the version
:param mode: Name of the mode in which the operation is executed
:type mode: str
:param operation_type: one of 'pre', 'post'
:type operation_type: str
:param operation: the ... | 0.0025 |
def _convert_reftype_to_jaeger_reftype(ref):
"""Convert opencensus reference types to jaeger reference types."""
if ref == link_module.Type.CHILD_LINKED_SPAN:
return jaeger.SpanRefType.CHILD_OF
if ref == link_module.Type.PARENT_LINKED_SPAN:
return jaeger.SpanRefType.FOLLOWS_FROM
return N... | 0.003096 |
def chol(A):
"""
Calculate the lower triangular matrix of the Cholesky decomposition of
a symmetric, positive-definite matrix.
"""
A = np.array(A)
assert A.shape[0] == A.shape[1], "Input matrix must be square"
L = [[0.0] * len(A) for _ in range(len(A))]
for i in range(len(A)):
... | 0.003559 |
def apns_send_message(registration_id, alert, application_id=None, certfile=None, **kwargs):
"""
Sends an APNS notification to a single registration_id.
This will send the notification as form data.
If sending multiple notifications, it is more efficient to use
apns_send_bulk_message()
Note that if set alert sho... | 0.024831 |
def previous_page(self, max_=None):
"""
Return a query set which requests the page before this response.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request t... | 0.003656 |
def pkcs12_kdf(hash_algorithm, password, salt, iterations, key_length, id_):
"""
KDF from RFC7292 appendix b.2 - https://tools.ietf.org/html/rfc7292#page-19
:param hash_algorithm:
The string name of the hash algorithm to use: "md5", "sha1", "sha224",
"sha256", "sha384", "sha512"
:param... | 0.000448 |
def availableBranches(self):
''' return a list of GithubComponentVersion objects for the tip of each branch
'''
return [
GithubComponentVersion(
'', b[0], b[1], self.name, cache_key=None
) for b in _getBranchHeads(self.repo).items()
] | 0.009804 |
def join(self):
"""Note that the Executor must be close()'d elsewhere,
or join() will never return.
"""
self.inputfeeder_thread.join()
self.pool.join()
self.resulttracker_thread.join()
self.failuretracker_thread.join() | 0.038793 |
def peer_store(key, value, relation_name='cluster'):
"""Store the key/value pair on the named peer relation `relation_name`."""
cluster_rels = relation_ids(relation_name)
if len(cluster_rels) > 0:
cluster_rid = cluster_rels[0]
relation_set(relation_id=cluster_rid,
relati... | 0.002141 |
def find_neighbor_sites(sites, am, flatten=True, include_input=False,
logic='or'):
r"""
Given a symmetric adjacency matrix, finds all sites that are connected
to the input sites.
Parameters
----------
am : scipy.sparse matrix
The adjacency matrix of the network. ... | 0.000251 |
def set_routing(app, view_data):
"""
apply the routing configuration you've described
example:
view_data = [
("/", "app.IndexController", "index"),
]
1. "/" is receive request path
2. "app.IndexController" is to process the received request controller class path... | 0.00321 |
def generate_project(self):
"""
Generate the whole project. Returns True if at least one
file has been generated, False otherwise."""
# checks needed properties
if not self.name or not self.destdir or \
not os.path.isdir(self.destdir):
raise ValueError(... | 0.012369 |
def _deserialize(self, value, attr, data, **kwargs):
"""Deserialize an ISO8601-formatted time to a :class:`datetime.time` object."""
if not value: # falsy values are invalid
self.fail('invalid')
try:
return utils.from_iso_time(value)
except (AttributeError, TypeE... | 0.008086 |
def deletecols(X, cols):
"""
Delete columns from a numpy ndarry or recarray.
Can take a string giving a column name or comma-separated list of column
names, or a list of string column names.
Implemented by the tabarray method
:func:`tabular.tab.tabarray.deletecols`.
**Parameters**
... | 0.003509 |
def kdf(size, password, salt,
opslimit=OPSLIMIT_SENSITIVE,
memlimit=MEMLIMIT_SENSITIVE,
encoder=nacl.encoding.RawEncoder):
"""
Derive a ``size`` bytes long key from a caller-supplied
``password`` and ``salt`` pair using the argon2i
memory-hard construct.
the enclosing module... | 0.000492 |
def _path_to_module(path):
"""Translates paths to *.py? files into module paths.
>>> _path_to_module("rapport/bar.py")
'rapport.bar'
>>> _path_to_module("/usr/lib/rapport/bar.py")
'rapport.bar'
"""
# Split of preceeding path elements:
path = "rapport" + path.split("rappo... | 0.002222 |
def scons_copytree(src, dst, symlinks=False):
"""Recursively copy a directory tree using copy2().
The destination directory must not already exist.
If exception(s) occur, an CopytreeError is raised with a list of reasons.
If the optional symlinks flag is true, symbolic links in the
source tree res... | 0.00058 |
def fatal(*args, **kwargs):
"""Log an error message and exit.
Following arguments are keyword-only.
:param exitcode: Optional exit code to use
:param cause: Optional Invoke's Result object, i.e.
result of a subprocess invocation
"""
# determine the exitcode to return to the o... | 0.001267 |
def stop(self, key):
"""
Stop a concurrent operation.
This gets the concurrency limiter for the given key (creating it if
necessary) and stops a concurrent operation on it. If the concurrency
limiter is empty, it is deleted.
"""
self._get_limiter(key).stop()
... | 0.005714 |
def process_formdata(self, valuelist):
"""
Process data received over the wire from a form.
This will be called during form construction with data supplied
through the `formdata` argument.
Converting primary key to ORM for server processing.
:param valuelist: A list of ... | 0.004839 |
def _get_package_data():
"""Iterate over the `init` dir for directories and returns
all files within them.
Only files within `binaries` and `templates` will be added.
"""
from os import listdir as ls
from os.path import join as jn
x = 'init'
b = jn('serv', x)
dr = ['binaries', 'tem... | 0.002494 |
def ParseOptions(self, options):
"""Parses tool specific options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
# The extraction options are dependent on the data location.
helpers_manager.ArgumentHelperManager.... | 0.002662 |
def _from_dict(cls, _dict):
"""Initialize a DocStructure object from a json dictionary."""
args = {}
if 'section_titles' in _dict:
args['section_titles'] = [
SectionTitles._from_dict(x)
for x in (_dict.get('section_titles'))
]
if 'l... | 0.003745 |
def _save_action(extra_context=None):
'''
Save list of revisions revisions for active Conda environment.
.. versionchanged:: 0.18
Compress action revision files using ``bz2`` to save disk space.
Parameters
----------
extra_context : dict, optional
Extra content to store in stor... | 0.000714 |
def get_ipython_module_path(module_str):
"""Find the path to an IPython module in this version of IPython.
This will always find the version of the module that is in this importable
IPython package. This will always return the path to the ``.py``
version of the module.
"""
if module_str == 'IPy... | 0.001709 |
def point_scalar(mesh, name):
""" Returns point scalars of a vtk object """
vtkarr = mesh.GetPointData().GetArray(name)
if vtkarr:
if isinstance(vtkarr, vtk.vtkBitArray):
vtkarr = vtk_bit_array_to_char(vtkarr)
return vtk_to_numpy(vtkarr) | 0.00361 |
def parse(self, elt, ps, **kw):
'''attempt to parse sequentially. No way to know ahead of time
what this instance represents. Must be simple type so it can
not have attributes nor children, so this isn't too bad.
'''
self.setMemberTypeCodes()
(nsuri,typeName) = self.che... | 0.003714 |
def _expand_var(self, in_string, available_variables):
"""Expand variable to its corresponding value in_string
:param string variable: variable name
:param value: value to replace with
:param string in_string: the string to replace in
"""
instances = self._get_instances(... | 0.003135 |
def unlock(self, session=None):
"""Unlock a previously locked server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionchanged:: 3.6
Added ``session`` parameter.
"""
cmd = SON([("fsyncUnlock", 1)])... | 0.001825 |
def full_author_notes(soup, fntype_filter=None):
"""
Find the fn tags included in author-notes
"""
notes = []
author_notes_section = raw_parser.author_notes(soup)
if author_notes_section:
fn_nodes = raw_parser.fn(author_notes_section)
notes = footnotes(fn_nodes, fntype_filter)
... | 0.002976 |
def evaluate(self, reference_event_list, estimated_event_list, evaluated_length_seconds=None):
"""Evaluate file pair (reference and estimated)
Parameters
----------
reference_event_list : list of dict or dcase_util.containers.MetaDataContainer
Reference event list.
... | 0.003443 |
def _get_datapoints(self, params):
"""
Will make a direct REST call with the given json body payload to
get datapoints.
"""
url = self.query_uri + '/v1/datapoints'
return self.service._get(url, params=params) | 0.007813 |
def sub(self, *segments):
"Get a sub-configuration."
d = self
for segment in segments:
try:
d = d[segment]
except KeyError:
return ConfigDict({})
return d | 0.008264 |
def run(self, **kwargs):
""" Start the tornado server, run forever"""
try:
loop = IOLoop()
app = self.make_app()
app.listen(self.port)
loop.start()
except socket.error as serr:
# Re raise the socket error if not "[Errno 98] Address al... | 0.006645 |
def HTML_results(resultsFile):
"""generates HTML report of active folders/days."""
foldersByDay=loadResults(resultsFile)
# optionally skip dates before a certain date
# for day in sorted(list(foldersByDay.keys())):
# if time.strptime(day,"%Y-%m-%d")<time.strptime("2016-05-01","%Y-%m-%d"):
... | 0.021856 |
def evaluate_expression(expression, vars):
'''evaluation an expression'''
try:
v = eval(expression, globals(), vars)
except NameError:
return None
except ZeroDivisionError:
return None
return v | 0.004219 |
def to_xml(self, root):
'''
Returns a DOM element contaning the XML representation of the
ExtensibleXMLiElement
@param root:Element Root XML element.
@return: Element
'''
if not len(self.__custom_elements):
return
for uri, tags in self.__custo... | 0.003795 |
def add_prefix(self):
""" Add prefix according to the specification.
The following keys can be used:
vrf ID of VRF to place the prefix in
prefix the prefix to add if already known
family address family (4 or 6)
descripti... | 0.001805 |
def load(path):
'''
Load specified fault manager module
path: string
path of fault manager module
CLI Example:
.. code-block:: bash
salt '*' fmadm.load /module/path
'''
ret = {}
fmadm = _check_fmadm()
cmd = '{cmd} load {path}'.format(
cmd=fmadm,
pa... | 0.00189 |
def geturi(self):
"""Return the re-combined version of the original URI reference as a
string.
"""
scheme, authority, path, query, fragment = self
# RFC 3986 5.3. Component Recomposition
result = []
if scheme is not None:
result.extend([scheme, self.... | 0.003077 |
def set_parallel(self, width, name=None):
"""
Set this source stream to be split into multiple channels
as the start of a parallel region.
Calling ``set_parallel`` on a stream created by
:py:meth:`~Topology.source` results in the stream
having `width` channels, each crea... | 0.002481 |
def pick_target_decoy(tfeature, dfeature):
"""Feed it with a target and decoy score and the protein/gene/id names,
and this will return target/decoy type, the winning ID and the score"""
tscore, dscore = get_score(tfeature), get_score(dfeature)
if tscore == dscore:
# same score or both False
... | 0.001217 |
async def select_page(self, info: SQLQueryInfo, size=1, page=1) -> Tuple[Tuple[DataRecord, ...], int]:
"""
Select from database
:param info:
:param size: -1 means infinite
:param page:
:param need_count: if True, get count as second return value, otherwise -1
:ret... | 0.010336 |
def _set_red_profile_ecn(self, v, load=False):
"""
Setter method for red_profile_ecn, mapped from YANG variable /qos/ecn/red_profile/red_profile_ecn (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_red_profile_ecn is considered as a private
method. Backend... | 0.005319 |
def leastsqbound(func, x0, args=(), bounds=None, Dfun=None, full_output=0,
col_deriv=0, ftol=1.49012e-8, xtol=1.49012e-8,
gtol=0.0, maxfev=0, epsfcn=0.0, factor=100, diag=None):
"""
Bounded minimization of the sum of squares of a set of equations.
::
x = arg min(sum(func(y)... | 0.004994 |
def get_cell_lines(self, column_idx):
'''
''returns:
the lines of the cell specified by the column_idx or an empty list if the column does not exist
'''
return [] if column_idx >= len(self.columns) else self.columns[column_idx].get_cell_lines() | 0.013699 |
def _backwards_search(self, start_node, split_name, max_depth=float('inf'), shortcuts=True):
""" Performs a backwards search from the terminal node back to the start node
:param start_node:
The node from where search starts, or here better way where backwards search should
end.... | 0.00404 |
def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=False, options=False):
'''
Helper function for parsing BCache's SysFS interface
'''
result = {}
# ---------------- Parse through the interfaces list ----------------
intfs = __salt__['sysfs.interfaces'](path)
# Act... | 0.001722 |
def critical(self, msg, *args, **kwargs):
"""Log 'msg % args' with the critical severity level"""
self._log("CRITICAL", msg, args, kwargs) | 0.012987 |
def community_topic_posts(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/posts#list-posts"
api_path = "/api/v2/community/topics/{id}/posts.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | 0.010791 |
def deepfool_attack(sess,
x,
predictions,
logits,
grads,
sample,
nb_candidate,
overshoot,
max_iter,
clip_min,
clip_max,
... | 0.007657 |
def _initialize_tableaux_ig(X, Y, tableaux, bases):
"""
Given sequences `X` and `Y` of ndarrays, initialize the tableau and
basis arrays in place for the "geometric" imitation game as defined
in McLennan and Tourky (2006), to be passed to `_lemke_howson_tbl`.
Parameters
----------
X, Y : nd... | 0.000519 |
def parse_bitcode(bitcode, context=None):
"""
Create Module from a LLVM *bitcode* (a bytes object).
"""
if context is None:
context = get_global_context()
buf = c_char_p(bitcode)
bufsize = len(bitcode)
with ffi.OutputString() as errmsg:
mod = ModuleRef(ffi.lib.LLVMPY_ParseBit... | 0.001873 |
def load_wav(path, mono=True):
"""Loads a .wav file as a numpy array using ``scipy.io.wavfile``.
Parameters
----------
path : str
Path to a .wav file
mono : bool
If the provided .wav has more than one channel, it will be
converted to mono if ``mono=True``. (Default value = T... | 0.000909 |
def set_cookie(cookies, key, value='', max_age=None, expires=None, path='/',
domain=None, secure=False, httponly=False):
'''Set a cookie key into the cookies dictionary *cookies*.'''
cookies[key] = value
if expires is not None:
if isinstance(expires, datetime):
now = (expi... | 0.00074 |
def gen_triplets_master(wv_master, geometry=None, debugplot=0):
"""Compute information associated to triplets in master table.
Determine all the possible triplets that can be generated from the
array `wv_master`. In addition, the relative position of the
central line of each triplet is also computed.
... | 0.00069 |
def send_wp_requests(self, wps=None):
'''send some more WP requests'''
if wps is None:
wps = self.missing_wps_to_request()
tnow = time.time()
for seq in wps:
#print("REQUESTING %u/%u (%u)" % (seq, self.wploader.expected_count, i))
self.wp_requested[seq... | 0.010554 |
def x(self, x):
"""Project x as y"""
if x is None:
return None
if self._force_vertical:
return super(HorizontalView, self).x(x)
return super(HorizontalView, self).y(x) | 0.008969 |
def container_freeze(name, remote_addr=None,
cert=None, key=None, verify_cert=True):
'''
Freeze a container
name :
Name of the container to freeze
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and its... | 0.000995 |
def extracting(self, *names, **kwargs):
"""Asserts that val is collection, then extracts the named properties or named zero-arg methods into a list (or list of tuples if multiple names are given)."""
if not isinstance(self.val, Iterable):
raise TypeError('val is not iterable')
if isi... | 0.002683 |
def delete_raw(self):
"""Delete the current entity.
Make an HTTP DELETE call to ``self.path('base')``. Return the response.
:return: A ``requests.response`` object.
"""
return client.delete(
self.path(which='self'),
**self._server_config.get_client_kwar... | 0.005988 |
def classes(equivalences):
"""Compute mapping from element to list of equivalent elements.
`equivalences` is an iterable of (x, y) tuples representing
equivalences x ~ y.
Returns an OrderedDict mapping each x to the list of elements
equivalent to x.
"""
node = OrderedDict()
def N(x):
... | 0.002849 |
def reconnect(self):
"""
Invoked by the IOLoop timer if the connection is
closed. See the on_connection_closed method.
"""
# This is the old connection IOLoop instance, stop its ioloop
self._connection.ioloop.stop()
if not self._closing:
# Create a ne... | 0.004057 |
def get_anchor_point(self, anchor_name):
"""Return an anchor point of the node, if it exists."""
if anchor_name in self._possible_anchors:
return TikZNodeAnchor(self.handle, anchor_name)
else:
try:
anchor = int(anchor_name.split('_')[1])
excep... | 0.005693 |
def find_files(dir_or_filelist, pattern='*'):
"""
If given a path to a directory, finds files recursively,
e.g. all *.txt files in a given directory (or its subdirectories).
If given a list of files, yields all of the files that match the given
pattern.
adapted from: http://stackoverflow.com/a/... | 0.0011 |
def download_page(url, data=None):
'''Returns the response for the given url. The optional data argument is
passed directly to urlopen.'''
conn = urllib2.urlopen(url, data)
resp = conn.read()
conn.close()
return resp | 0.004167 |
def create_random(magf, magf_params, errf, errf_params,
timef=np.linspace, timef_params=None, size=DEFAULT_SIZE,
id=None, ds_name=DS_NAME, description=DESCRIPTION,
bands=BANDS, metadata=METADATA):
"""Generate a data with any given random function.
Parameter... | 0.000423 |
def download(date_array, tag, sat_id, data_path, user=None, password=None):
"""Routine to download Kp index data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '1min' and '5min'.
(default=None)
sat_id : (string or NoneType)
... | 0.003955 |
def set(key, value={}, reset=False, init=False):
"""
Set data
:param key: A unique to set, best to use __name__
:param value: dict - the value to save
:param reset: bool - If true, it will reset the value to the current one.
if False, it will just update the stored value with the c... | 0.004283 |
def _run(self):
"""
This is the logic to run it all.
Heavily influenced by this post: http://nickdesaulniers.github.io/blog/2015/05/25/interpreter-compiler-jit/
:return:
"""
i = 0
try:
while i < len(self.program):
if self.program[i] == ... | 0.003336 |
def process_tokens(self, tokens):
"""process tokens from the current module to search for module/block
level options
"""
control_pragmas = {"disable", "enable"}
for (tok_type, content, start, _, _) in tokens:
if tok_type != tokenize.COMMENT:
continue
... | 0.001753 |
def main():
"""Run newer stuffs."""
logging.basicConfig(format=LOGGING_FORMAT)
log = logging.getLogger(__name__)
parser = argparse.ArgumentParser()
add_debug(parser)
add_app(parser)
add_env(parser)
add_region(parser)
add_properties(parser)
parser.add_argument("--elb-subnet", hel... | 0.004243 |
def get_regions_and_coremasks(self):
"""Generate a set of ordered paired region and core mask representations.
.. note::
The region and core masks are ordered such that ``(region << 32) |
core_mask`` is monotonically increasing. Consequently region and
core masks gen... | 0.001609 |
def Page_deleteCookie(self, cookieName, url):
"""
Function path: Page.deleteCookie
Domain: Page
Method name: deleteCookie
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'cookieName' (type: string) -> Name of the cookie to remove.
'url' (type: string)... | 0.046838 |
def t_to_min(x):
"""
Convert XML 'xs: duration type' to decimal minutes, e.g.:
t_to_min('PT1H2M30S') == 62.5
"""
g = re.match('PT(?:(.*)H)?(?:(.*)M)?(?:(.*)S)?', x).groups()
return sum(0 if g[i] is None else float(g[i]) * 60. ** (1 - i)
for i in range(3)) | 0.003401 |
def partition_pairs(neurites, neurite_type=NeuriteType.all):
'''Partition pairs at bifurcation points of a collection of neurites.
Partition pait is defined as the number of bifurcations at the two
daughters of the bifurcating section'''
return map(_bifurcationfunc.partition_pair,
iter_se... | 0.002119 |
def _horizontal_segment(old_offs, new_offs, spacing, diameter):
'''Vertices of a horizontal rectangle
'''
return np.array(((old_offs[0], old_offs[1] + spacing[1]),
(new_offs[0], old_offs[1] + spacing[1]),
(new_offs[0], old_offs[1] + spacing[1] - diameter),
... | 0.002604 |
def mousePressEvent(self, event):
"""Begins edit on cell clicked, if allowed, and passes event to super class"""
index = self.indexAt(event.pos())
if index.isValid():
self.selectRow(index.row())
# selecting the row sets the current index to 0,0 for tab
# order... | 0.004831 |
def search(self, string, default=None):
"""Use re.search to find the result
:rtype: list"""
default = default if default else []
result = [item[1] for item in self.container if item[0].search(string)]
if self.ensure_mapping:
assert len(result) < 2, "%s matches more t... | 0.004435 |
def validate(self, value):
"""Validate field value."""
if self.required and value is None:
raise ValidationError("field is required")
if value is not None and self.choices is not None:
choices = [choice for choice, _ in self.choices]
if value not in choices:
... | 0.004435 |
def delete_port_postcommit(self, context):
"""Delete port non-database commit event."""
if self._is_supported_deviceowner(context.current):
vlan_segment, vxlan_segment = self._get_segments(
context.top_bound_segment,
... | 0.00458 |
def get_filter_form(self, **kwargs):
"""
If there is a filter_form, initializes that
form with the contents of request.GET and
returns it.
"""
form = None
if self.filter_form:
form = self.filter_form(self.request.GET)
elif self.model and hasat... | 0.004673 |
def _get_paths():
"""Generate paths to test data. Done in a function to protect namespace a bit."""
import os
base_path = os.path.dirname(os.path.abspath(__file__))
test_data_dir = os.path.join(base_path, 'tests', 'data', 'Plate01')
test_data_file = os.path.join(test_data_dir, 'RFP_Well_A3.fcs')
... | 0.005602 |
def all_points_core_distance(distance_matrix, d=2.0):
"""
Compute the all-points-core-distance for all the points of a cluster.
Parameters
----------
distance_matrix : array (cluster_size, cluster_size)
The pairwise distance matrix between points in the cluster.
d : integer
The... | 0.001012 |
def _octet_bits(o):
"""
Get the bits of an octet.
:param o: The octets.
:return: The bits as a list in LSB-to-MSB order.
:rtype: list
"""
if not isinstance(o, integer_types):
raise TypeError("o should be an int")
if not (0 <= o <= 255):
raise ValueError("o should be betw... | 0.002132 |
def validate_day(year, month, day):
"""Validate day."""
max_days = LONG_MONTH
if month == FEB:
max_days = FEB_LEAP_MONTH if ((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0) else FEB_MONTH
elif month in MONTHS_30:
max_days = SHORT_MONTH
return ... | 0.008824 |
def cube2map(data_cube, layout):
r"""Cube to Map
This method transforms the input data from a 3D cube to a 2D map with a
specified layout
Parameters
----------
data_cube : np.ndarray
Input data cube, 3D array of 2D images
Layout : tuple
2D layout of 2D images
Returns
... | 0.000874 |
def get_email(self, token):
"""Fetches email address from email API endpoint"""
resp = requests.get(self.emails_url,
params={'access_token': token.token})
emails = resp.json().get('values', [])
email = ''
try:
email = emails[0].get('email')... | 0.003546 |
def availability_zone_list(request):
"""Utility method to retrieve a list of availability zones."""
try:
return api.nova.availability_zone_list(request)
except Exception:
exceptions.handle(request,
_('Unable to retrieve Nova availability zones.'))
return [] | 0.003135 |
def get_complete_slug(self, language=None, hideroot=True):
"""Return the complete slug of this page by concatenating
all parent's slugs.
:param language: the wanted slug language."""
if not language:
language = settings.PAGE_DEFAULT_LANGUAGE
if self._complete_slug a... | 0.001889 |
def _registrant_publication(reg_pub, rules):
""" Separate the registration from the publication in a given
string.
:param reg_pub: A string of digits representing a registration
and publication.
:param rules: A list of RegistrantRules which designate where
to sepa... | 0.002451 |
def from_str(cls, timestr, shaked=False):
"""Use `dateutil` module to parse the give string
:param basestring timestr: string representing a date to parse
:param bool shaked: whether the input parameter been already
cleaned or not.
"""
orig = timestr
if not shake... | 0.001277 |
def install_auth_basic_user_file(self, site=None):
"""
Installs users for basic httpd auth.
"""
r = self.local_renderer
hostname = self.current_hostname
target_sites = self.genv.available_sites_by_host.get(hostname, None)
for _site, site_data in self.iter_sites... | 0.003981 |
def _download_urls(url_list, storage_folder, overwrite_existing,
meta_handler, access_cookie=None):
""" Save url from url_list to storage_folder
Parameters
----------
url_list: list of str
Valid url to download
storage_folder: str, valid path
Location to store th... | 0.000671 |
def _search_show_id(self, series, year=None):
"""Search the show id from the `series` and `year`.
:param str series: series of the episode.
:param year: year of the series, if any.
:type year: int
:return: the show id, if found.
:rtype: int
"""
# addic7e... | 0.002789 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.