code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_identity_provider(provider_id):
"""
Get Identity Provider with given id.
Return:
Instance of ProviderConfig or None.
"""
try:
from third_party_auth.provider import Registry # pylint: disable=redefined-outer-name
except ImportError as exception:
LOGGER.warning("... | Get Identity Provider with given id.
Return:
Instance of ProviderConfig or None. |
def windowed_iter(src, size):
"""Returns tuples with length *size* which represent a sliding
window over iterable *src*.
>>> list(windowed_iter(range(7), 3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]
If the iterable is too short to make a window of length *size*,
then no window t... | Returns tuples with length *size* which represent a sliding
window over iterable *src*.
>>> list(windowed_iter(range(7), 3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]
If the iterable is too short to make a window of length *size*,
then no window tuples are returned.
>>> list(win... |
def _parse_value(self, html_data, field):
"""
Parse the HTML table to find the requested field's value.
All of the values are passed in an HTML table row instead of as
individual items. The values need to be parsed by matching the
requested attribute with a parsing scheme that s... | Parse the HTML table to find the requested field's value.
All of the values are passed in an HTML table row instead of as
individual items. The values need to be parsed by matching the
requested attribute with a parsing scheme that sports-reference uses
to differentiate stats. This func... |
def send(self,
send,
expect=None,
shutit_pexpect_child=None,
timeout=None,
check_exit=None,
fail_on_empty_before=True,
record_command=True,
exit_values=None,
echo=None,
escape=False,
retry=3,
note=Non... | Send string as a shell command, and wait until the expected output
is seen (either a string or any from a list of strings) before
returning. The expected string will default to the currently-set
default expected string (see get_default_shutit_pexpect_session_expect)
Returns the pexpect return value (ie which e... |
def masked(name, runtime=False):
'''
.. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is masked (i.e. prevented from being
started).
name
Name of the service to mask
runtime : False
By ... | .. versionadded:: 2017.7.0
.. note::
This state is only available on minions which use systemd_.
Ensures that the named service is masked (i.e. prevented from being
started).
name
Name of the service to mask
runtime : False
By default, this state will manage an indefinite... |
def run(fn, blocksize, seed, c, delta):
"""Run the encoder until the channel is broken, signalling that the
receiver has successfully reconstructed the file
"""
with open(fn, 'rb') as f:
for block in encode.encoder(f, blocksize, seed, c, delta):
sys.stdout.buffer.write(block) | Run the encoder until the channel is broken, signalling that the
receiver has successfully reconstructed the file |
def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
config_file):
'''
Execute LDAP searches and return the aggregated data
'''
config_template = None
try:
config_template = _render_template(config_file)
except jinja2.exception... | Execute LDAP searches and return the aggregated data |
async def cancel_handler(message: types.Message, state: FSMContext, raw_state: Optional[str] = None):
"""
Allow user to cancel any action
"""
if raw_state is None:
return
# Cancel state and inform user about it
await state.finish()
# And remove keyboard (just in case)
await mess... | Allow user to cancel any action |
def run(self, tokens):
"""Runs the current list of functions that make up the pipeline against
the passed tokens."""
for fn in self._stack:
results = []
for i, token in enumerate(tokens):
# JS ignores additional arguments to the functions but we
... | Runs the current list of functions that make up the pipeline against
the passed tokens. |
def render(self, context):
"""Render markdown."""
import markdown
content = self.get_content_from_context(context)
return markdown.markdown(content) | Render markdown. |
def _getSyntaxByXmlFileName(self, xmlFileName):
"""Get syntax by its xml file name
"""
import qutepart.syntax.loader # delayed import for avoid cross-imports problem
with self._loadedSyntaxesLock:
if not xmlFileName in self._loadedSyntaxes:
xmlFilePath = os.... | Get syntax by its xml file name |
def lstring_as_obj(true_or_false=None):
"""Toggles whether lstrings should be treated as strings or as objects.
When FieldArrays is first loaded, the default is True.
Parameters
----------
true_or_false : {None|bool}
Pass True to map lstrings to objects; False otherwise. If None
pro... | Toggles whether lstrings should be treated as strings or as objects.
When FieldArrays is first loaded, the default is True.
Parameters
----------
true_or_false : {None|bool}
Pass True to map lstrings to objects; False otherwise. If None
provided, just returns the current state.
Ret... |
def LogNormSpheres(q, A, mu, sigma, N=1000):
"""Scattering of a population of non-correlated spheres (radii from a log-normal distribution)
Inputs:
-------
``q``: independent variable
``A``: scaling factor
``mu``: expectation of ``ln(R)``
``sigma``: hwhm of ``ln(R)``
No... | Scattering of a population of non-correlated spheres (radii from a log-normal distribution)
Inputs:
-------
``q``: independent variable
``A``: scaling factor
``mu``: expectation of ``ln(R)``
``sigma``: hwhm of ``ln(R)``
Non-fittable inputs:
--------------------
... |
def print_loading(self, wait, message):
"""
print loading message on screen
.. note::
loading message only write to `sys.stdout`
:param int wait: seconds to wait
:param str message: message to print
:return: None
"""
tags = ['\\', '|', '/',... | print loading message on screen
.. note::
loading message only write to `sys.stdout`
:param int wait: seconds to wait
:param str message: message to print
:return: None |
def from_json(cls, json, image_config=None):
"""Create a model instance
Arguments:
json (:py:class:`dict`): The parsed JSON data.
image_config (:py:class:`dict`): The API image configuration
data.
Returns:
:py:class:`BaseModel`: The model instance.
... | Create a model instance
Arguments:
json (:py:class:`dict`): The parsed JSON data.
image_config (:py:class:`dict`): The API image configuration
data.
Returns:
:py:class:`BaseModel`: The model instance. |
def generate_delete_user_command(username=None, manage_home=None):
"""Generate command to delete a user.
args:
username (str): user name
manage_home (bool): manage home directory
returns:
list: The user delete command string split into shell-like syntax
"""
command = None
... | Generate command to delete a user.
args:
username (str): user name
manage_home (bool): manage home directory
returns:
list: The user delete command string split into shell-like syntax |
def parse_known_chained(self, args=None):
"""
Parse the argument directly to the function used for setup
This function parses the command line arguments to the function that
has been used for the :meth:`setup_args` method.
Parameters
----------
args: list
... | Parse the argument directly to the function used for setup
This function parses the command line arguments to the function that
has been used for the :meth:`setup_args` method.
Parameters
----------
args: list
The arguments parsed to the :meth:`parse_args` function... |
def main():
"""
Entry point.
"""
parser = argparse.ArgumentParser(description=DESCRIPTION)
for arg in ARGUMENTS:
if "action" in arg:
if arg["short"] is not None:
parser.add_argument(arg["short"], arg["long"], action=arg["action"], help=arg["help"])
els... | Entry point. |
def inten(function):
"Decorator. Attempts to convert return value to int"
def wrapper(*args, **kwargs):
return coerce_to_int(function(*args, **kwargs))
return wrapper | Decorator. Attempts to convert return value to int |
def NEW_DEBUG_FRAME(self, requestHeader):
"""
Initialize a debug frame with requestHeader
Frame count is updated and will be attached to respond header
The structure of a frame: [requestHeader, statusCode, responseHeader, raw_data]
Some of them may be None
"""
if ... | Initialize a debug frame with requestHeader
Frame count is updated and will be attached to respond header
The structure of a frame: [requestHeader, statusCode, responseHeader, raw_data]
Some of them may be None |
def jwt_verify_token(headers):
"""Verify the JWT token.
:param dict headers: The request headers.
:returns: The token data.
:rtype: dict
"""
# Get the token from headers
token = headers.get(
current_app.config['OAUTH2SERVER_JWT_AUTH_HEADER']
)
if token is None:
raise... | Verify the JWT token.
:param dict headers: The request headers.
:returns: The token data.
:rtype: dict |
def new_instance(cls, classname):
"""
Creates a new object from the given classname using the default constructor, None in case of error.
:param classname: the classname in Java notation (eg "weka.core.DenseInstance")
:type classname: str
:return: the Java object
:rtype:... | Creates a new object from the given classname using the default constructor, None in case of error.
:param classname: the classname in Java notation (eg "weka.core.DenseInstance")
:type classname: str
:return: the Java object
:rtype: JB_Object |
def _iter_avro_blocks(fo, header, codec, writer_schema, reader_schema):
"""Return iterator over avro blocks."""
sync_marker = header['sync']
read_block = BLOCK_READERS.get(codec)
if not read_block:
raise ValueError('Unrecognized codec: %r' % codec)
while True:
offset = fo.tell()
... | Return iterator over avro blocks. |
def moving_average_bias_ratio(self, date1, date2):
""" 計算乖離率(均價)
date1 - date2
:param int data1: n 日
:param int data2: m 日
:rtype: tuple (序列 舊→新, 持續天數)
"""
data1 = self.moving_average(date1)[0]
data2 = self.moving_average(date2)[0]
... | 計算乖離率(均價)
date1 - date2
:param int data1: n 日
:param int data2: m 日
:rtype: tuple (序列 舊→新, 持續天數) |
def normalize_keys(suspect, snake_case=True):
"""
take a dict and turn all of its type string keys into snake_case
"""
if not isinstance(suspect, dict):
raise TypeError('you must pass a dict.')
for key in list(suspect):
if not isinstance(key, six.string_types):
continue
... | take a dict and turn all of its type string keys into snake_case |
def _Struct_set_Poly(Poly, pos=None, extent=None, arrayorder='C',
Type='Tor', Clock=False):
""" Compute geometrical attributes of a Struct object """
# Make Poly closed, counter-clockwise, with '(cc,N)' layout and arrayorder
Poly = _GG.Poly_Order(Poly, order='C', Clock=False,
... | Compute geometrical attributes of a Struct object |
def get_group_gn(dim, dim_per_gp, num_groups):
"""get number of groups used by GroupNorm, based on number of channels."""
assert dim_per_gp == -1 or num_groups == -1, \
"GroupNorm: can only specify G or C/G."
if dim_per_gp > 0:
assert dim % dim_per_gp == 0, \
"dim: {}, dim_per_g... | get number of groups used by GroupNorm, based on number of channels. |
def get_device_mac(self) -> str:
'''Show device MAC.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'cat', '/sys/class/net/wlan0/address')
return output.strip() | Show device MAC. |
def run_once(func):
"""
Simple decorator to ensure a function is ran only once
"""
def _inner(*args, **kwargs):
if func.__name__ in CTX.run_once:
LOGGER.info('skipping %s', func.__name__)
return CTX.run_once[func.__name__]
LOGGER.info('running: %s', func.__name_... | Simple decorator to ensure a function is ran only once |
def _init_vocab(self, analyzed_docs):
"""Create vocabulary
"""
class SetAccum(AccumulatorParam):
def zero(self, initialValue):
return set(initialValue)
def addInPlace(self, v1, v2):
v1 |= v2
return v1
if not self.... | Create vocabulary |
def stalta_pick(stream, stalen, ltalen, trig_on, trig_off, freqmin=False,
freqmax=False, debug=0, show=False):
"""
Basic sta/lta picker, suggest using alternative in obspy.
Simple sta/lta (short-term average/long-term average) picker, using
obspy's :func:`obspy.signal.trigger.classic_st... | Basic sta/lta picker, suggest using alternative in obspy.
Simple sta/lta (short-term average/long-term average) picker, using
obspy's :func:`obspy.signal.trigger.classic_sta_lta` routine to generate
the characteristic function.
Currently very basic quick wrapper, there are many other (better) options
... |
def get_panels(config):
"""Execute the panels phase
:param config: a Mordred config object
"""
task = TaskPanels(config)
task.execute()
task = TaskPanelsMenu(config)
task.execute()
logging.info("Panels creation finished!") | Execute the panels phase
:param config: a Mordred config object |
def create_xz(archive, compression, cmd, verbosity, interactive, filenames):
"""Create an XZ archive with the lzma Python module."""
return _create(archive, compression, cmd, 'xz', verbosity, filenames) | Create an XZ archive with the lzma Python module. |
def register(self, model, **attr):
"""Register a model or a table with this mapper
:param model: a table or a :class:`.BaseModel` class
:return: a Model class or a table
"""
metadata = self.metadata
if not isinstance(model, Table):
model_name = self._create_m... | Register a model or a table with this mapper
:param model: a table or a :class:`.BaseModel` class
:return: a Model class or a table |
def incrementSub(self, amount=1):
"""
Increments the sub-progress bar by amount.
"""
self._subProgressBar.setValue(self.subValue() + amount)
QApplication.instance().processEvents() | Increments the sub-progress bar by amount. |
def nth_combination(iterable, r, index):
"""Equivalent to ``list(combinations(iterable, r))[index]``.
The subsequences of *iterable* that are of length *r* can be ordered
lexicographically. :func:`nth_combination` computes the subsequence at
sort position *index* directly, without computing the previou... | Equivalent to ``list(combinations(iterable, r))[index]``.
The subsequences of *iterable* that are of length *r* can be ordered
lexicographically. :func:`nth_combination` computes the subsequence at
sort position *index* directly, without computing the previous
subsequences. |
def nl_socket_add_memberships(sk, *group):
"""Join groups.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L417
Joins the specified groups using the modern socket option. The list of groups has to be terminated by 0.
Make sure to use the correct group definitions as the older bitmask d... | Join groups.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L417
Joins the specified groups using the modern socket option. The list of groups has to be terminated by 0.
Make sure to use the correct group definitions as the older bitmask definitions for nl_join_groups() are likely to
... |
def set_inputs(self, inputs):
"""Assign input voltages."""
if len(inputs) != len(self.inputs):
raise RuntimeError(
"Number of inputs {0:d} does not match number of input nodes {1:d}".format(
len(inputs), len(self.inputs)))
for i, v in zip(self.inpu... | Assign input voltages. |
def ping(self, destination, length=20):
""" send ICMPv6 echo request with a given length to a unicast destination
address
Args:
destination: the unicast destination address of ICMPv6 echo request
length: the size of ICMPv6 echo request payload
"""
pri... | send ICMPv6 echo request with a given length to a unicast destination
address
Args:
destination: the unicast destination address of ICMPv6 echo request
length: the size of ICMPv6 echo request payload |
def create_node(participant_id):
"""Send a POST request to the node table.
This makes a new node for the participant, it calls:
1. exp.get_network_for_participant
2. exp.create_node
3. exp.add_node_to_network
4. exp.node_post_request
"""
exp = experiment(session)
# ... | Send a POST request to the node table.
This makes a new node for the participant, it calls:
1. exp.get_network_for_participant
2. exp.create_node
3. exp.add_node_to_network
4. exp.node_post_request |
def to_delete(datetimes,
years=0, months=0, weeks=0, days=0,
hours=0, minutes=0, seconds=0,
firstweekday=SATURDAY, now=None):
"""
Return a set of datetimes that should be deleted, out of ``datetimes``.
See ``to_keep`` for a description of arguments.
"""
dat... | Return a set of datetimes that should be deleted, out of ``datetimes``.
See ``to_keep`` for a description of arguments. |
def pfunc(func):
"""
pf = pfunc(func)
Returns a function that can be called just like func; however its arguments may be
PyMC objects or containers of PyMC objects, and its return value will be a deterministic.
Example:
>>> A = pymc.Normal('A',0,1,size=10)
>>> pprod = pymc.pfunc(n... | pf = pfunc(func)
Returns a function that can be called just like func; however its arguments may be
PyMC objects or containers of PyMC objects, and its return value will be a deterministic.
Example:
>>> A = pymc.Normal('A',0,1,size=10)
>>> pprod = pymc.pfunc(numpy.prod)
>>> B = pp... |
def fuller_scaling(target, DABo, To, Po, temperature='pore.temperature',
pressure='pore.pressure'):
r"""
Uses Fuller model to adjust a diffusion coefficient for gases from
reference conditions to conditions of interest
Parameters
----------
target : OpenPNM Object
The... | r"""
Uses Fuller model to adjust a diffusion coefficient for gases from
reference conditions to conditions of interest
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. This
controls the length of the calculated array, and also pr... |
def _termination_callback(self, returncode):
"""
Called when the process has stopped.
:param returncode: Process returncode
"""
if self.started:
log.info("QEMU process has stopped, return code: %d", returncode)
yield from self.stop()
# A retu... | Called when the process has stopped.
:param returncode: Process returncode |
def get_between_ngrams(c, attrib="words", n_min=1, n_max=1, lower=True):
"""Return the ngrams *between* two unary Mentions of a binary-Mention Candidate.
Get the ngrams *between* two unary Mentions of a binary-Mention Candidate,
where both share the same sentence Context.
:param c: The binary-Mention ... | Return the ngrams *between* two unary Mentions of a binary-Mention Candidate.
Get the ngrams *between* two unary Mentions of a binary-Mention Candidate,
where both share the same sentence Context.
:param c: The binary-Mention Candidate to evaluate.
:param attrib: The token attribute type (e.g. words, ... |
def _generate_comparator(cls, field_names):
"""
Construct a comparator function based on the field names. The comparator
returns the first non-zero comparison value.
Inputs:
field_names (iterable of strings): The field names to sort on.
Returns:
A compar... | Construct a comparator function based on the field names. The comparator
returns the first non-zero comparison value.
Inputs:
field_names (iterable of strings): The field names to sort on.
Returns:
A comparator function. |
def kline_echarts(self, code=None):
def kline_formater(param):
return param.name + ':' + vars(param)
"""plot the market_data"""
if code is None:
path_name = '.' + os.sep + 'QA_' + self.type + \
'_codepackage_' + self.if_fq + '.html'
kline = K... | plot the market_data |
def pprint(self):
"""Print tag key=value pairs."""
strings = []
for key in sorted(self.keys()):
values = self[key]
for value in values:
strings.append("%s=%s" % (key, value))
return "\n".join(strings) | Print tag key=value pairs. |
def post_process(self, tagnum2name):
"""Map the tag name instead of tag number to the tag value.
"""
for tag, value in self.raw_ifd.items():
try:
tag_name = tagnum2name[tag]
except KeyError:
# Ok, we don't recognize this tag. Just use the ... | Map the tag name instead of tag number to the tag value. |
def write_source_description(
self, capability_lists=None, outfile=None, links=None):
"""Write a ResourceSync Description document to outfile or STDOUT."""
rsd = SourceDescription(ln=links)
rsd.pretty_xml = self.pretty_xml
if (capability_lists is not None):
for ur... | Write a ResourceSync Description document to outfile or STDOUT. |
def parseFASTACommandLineOptions(args):
"""
Examine parsed command-line options and return a Reads instance.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@return: A C{Reads} subclass instance, depending on the type of FASTA file
given.
"""
... | Examine parsed command-line options and return a Reads instance.
@param args: An argparse namespace, as returned by the argparse
C{parse_args} function.
@return: A C{Reads} subclass instance, depending on the type of FASTA file
given. |
def _set_default_cfg_profile(self):
"""Set default network config profile.
Check whether the default_cfg_profile value exist in the current
version of DCNM. If not, set it to new default value which is supported
by latest version.
"""
try:
cfgplist = self.con... | Set default network config profile.
Check whether the default_cfg_profile value exist in the current
version of DCNM. If not, set it to new default value which is supported
by latest version. |
def _get_samples_to_process(fn, out_dir, config, force_single, separators):
"""parse csv file with one line per file. It will merge
all files that have the same description name"""
out_dir = os.path.abspath(out_dir)
samples = defaultdict(list)
with open(fn) as handle:
for l in handle:
... | parse csv file with one line per file. It will merge
all files that have the same description name |
def force_hashable(obj, recursive=True):
"""Force frozenset() command to freeze the order and contents of mutables and iterables like lists, dicts, generators
Useful for memoization and constructing dicts or hashtables where keys must be immutable.
FIXME: Rename function because "hashable" is misleading.
... | Force frozenset() command to freeze the order and contents of mutables and iterables like lists, dicts, generators
Useful for memoization and constructing dicts or hashtables where keys must be immutable.
FIXME: Rename function because "hashable" is misleading.
A better name might be `force_immutab... |
def _legal_operations(self, model, tabu_list=[], max_indegree=None):
"""Generates a list of legal (= not in tabu_list) graph modifications
for a given model, together with their score changes. Possible graph modifications:
(1) add, (2) remove, or (3) flip a single edge. For details on scoring
... | Generates a list of legal (= not in tabu_list) graph modifications
for a given model, together with their score changes. Possible graph modifications:
(1) add, (2) remove, or (3) flip a single edge. For details on scoring
see Koller & Fridman, Probabilistic Graphical Models, Section 18.4.3.3 (pa... |
def prov(self):
"""
Provenance stored for this document as :py:class:`prov.model.ProvDocument`
"""
if self._prov:
return self._prov
elif not self.abstract:
return self.read_prov()
raise EmptyDocumentException() | Provenance stored for this document as :py:class:`prov.model.ProvDocument` |
def read_math_env(src, expr):
r"""Read the environment from buffer.
Advances the buffer until right after the end of the environment. Adds
parsed content to the expression automatically.
:param Buffer src: a buffer of tokens
:param TexExpr expr: expression for the environment
:rtype: TexExpr
... | r"""Read the environment from buffer.
Advances the buffer until right after the end of the environment. Adds
parsed content to the expression automatically.
:param Buffer src: a buffer of tokens
:param TexExpr expr: expression for the environment
:rtype: TexExpr |
def _change_sample_name(in_file, sample_name, data=None):
"""Fix name in feature counts log file to get the same
name in multiqc report.
"""
out_file = append_stem(in_file, "_fixed")
with file_transaction(data, out_file) as tx_out:
with open(tx_out, "w") as out_handle:
with op... | Fix name in feature counts log file to get the same
name in multiqc report. |
def fullname(self):
"""Return the object's fullname.
A fullname is an object's kind mapping like `t3` followed by an
underscore and the object's base36 id, e.g., `t1_c5s96e0`.
"""
by_object = self.reddit_session.config.by_object
return '{0}_{1}'.format(by_object[self.__... | Return the object's fullname.
A fullname is an object's kind mapping like `t3` followed by an
underscore and the object's base36 id, e.g., `t1_c5s96e0`. |
def safe_process_files(path, files, args, state):
"""
Process a number of files in a directory. Catches any exception from the
processing and checks if we should fail directly or keep going.
"""
for fn in files:
full_fn = os.path.join(path, fn)
try:
if not process_file(pa... | Process a number of files in a directory. Catches any exception from the
processing and checks if we should fail directly or keep going. |
def add_commands(self):
""" You can override this method in order to add your command line
arguments to the argparse parser. The configuration file was
reloaded at this time."""
self.parser.add_argument(
'-d',
action="count",
**self.config.default.deb... | You can override this method in order to add your command line
arguments to the argparse parser. The configuration file was
reloaded at this time. |
def flatten(iterable):
'''This function allows a simple a way to iterate over a "complex" iterable, for example,
if the input [12, [23], (4, 3), "lkjasddf"], this will return an Iterable that returns
12, 23, 4, 3 and "lkjasddf".
Args:
iterable (Iterable) - A complex iterable that will be flatte... | This function allows a simple a way to iterate over a "complex" iterable, for example,
if the input [12, [23], (4, 3), "lkjasddf"], this will return an Iterable that returns
12, 23, 4, 3 and "lkjasddf".
Args:
iterable (Iterable) - A complex iterable that will be flattened
Returns:
(Ite... |
def outputs_of(self, partition_index):
"""The outputs of the partition at ``partition_index``.
Note that this returns a tuple of element indices, since coarse-
grained blackboxes may have multiple outputs.
"""
partition = self.partition[partition_index]
outputs = set(par... | The outputs of the partition at ``partition_index``.
Note that this returns a tuple of element indices, since coarse-
grained blackboxes may have multiple outputs. |
def euclideanDistance(instance1, instance2, considerDimensions):
"""
Calculate Euclidean Distance between two samples
Example use:
data1 = [2, 2, 2, 'class_a']
data2 = [4, 4, 4, 'class_b']
distance = euclideanDistance(data1, data2, 3)
:param instance1: list of attributes
:param instance2: list of attri... | Calculate Euclidean Distance between two samples
Example use:
data1 = [2, 2, 2, 'class_a']
data2 = [4, 4, 4, 'class_b']
distance = euclideanDistance(data1, data2, 3)
:param instance1: list of attributes
:param instance2: list of attributes
:param considerDimensions: a list of dimensions to consider
:re... |
def build_catalog(site, datasets, format=None):
'''Build the DCAT catalog for this site'''
site_url = url_for('site.home_redirect', _external=True)
catalog_url = url_for('site.rdf_catalog', _external=True)
graph = Graph(namespace_manager=namespace_manager)
catalog = graph.resource(URIRef(catalog_url... | Build the DCAT catalog for this site |
def write_block_data(self, i2c_addr, register, data, force=None):
"""
Write a block of byte data to a given register.
:param i2c_addr: i2c address
:type i2c_addr: int
:param register: Start register
:type register: int
:param data: List of bytes
:type dat... | Write a block of byte data to a given register.
:param i2c_addr: i2c address
:type i2c_addr: int
:param register: Start register
:type register: int
:param data: List of bytes
:type data: list
:param force:
:type force: Boolean
:rtype: None |
def compare(self, textOrFingerprint1, textOrFingerprint2):
"""Returns the semantic similarity of texts or fingerprints. Each argument can be eiter a text or a fingerprint.
Args:
textOrFingerprint1, str OR list of integers
textOrFingerprint2, str OR list of integers
Return... | Returns the semantic similarity of texts or fingerprints. Each argument can be eiter a text or a fingerprint.
Args:
textOrFingerprint1, str OR list of integers
textOrFingerprint2, str OR list of integers
Returns:
float: the semantic similarity in the range [0;1]
... |
def sign(self, signer: Signer):
""" Sign message using signer. """
message_data = self._data_to_sign()
self.signature = signer.sign(data=message_data) | Sign message using signer. |
def difference(self, boolean_switches):
"""
[COMPATIBILITY]
Make a copy of the current instance, and then discard all options that are in boolean_switches.
:param set boolean_switches: A collection of Boolean switches to disable.
:return: A new SimState... | [COMPATIBILITY]
Make a copy of the current instance, and then discard all options that are in boolean_switches.
:param set boolean_switches: A collection of Boolean switches to disable.
:return: A new SimStateOptions instance. |
def open_macros(self, filepath):
"""Loads macros from file and marks grid as changed
Parameters
----------
filepath: String
\tPath to macro file
"""
try:
wx.BeginBusyCursor()
self.main_window.grid.Disable()
with open(filepat... | Loads macros from file and marks grid as changed
Parameters
----------
filepath: String
\tPath to macro file |
def fetch_path(self, name):
"""
Fetch contents from the path retrieved via lookup_path.
No caching will be done.
"""
with codecs.open(self.lookup_path(name), encoding='utf-8') as fd:
return fd.read() | Fetch contents from the path retrieved via lookup_path.
No caching will be done. |
def begin(self):
"""Initialize library, must be called once before other functions are
called.
"""
resp = ws.ws2811_init(self._leds)
if resp != 0:
str_resp = ws.ws2811_get_return_t_str(resp)
raise RuntimeError('ws2811_init failed with code {0} ({1})'.form... | Initialize library, must be called once before other functions are
called. |
def resolver(schema):
"""Default implementation of a schema name resolver function
"""
name = schema.__name__
if name.endswith("Schema"):
return name[:-6] or name
return name | Default implementation of a schema name resolver function |
def add_worksheet(self, name=None):
""" Adds a new worksheet """
url = self.build_url(self._endpoints.get('get_worksheets'))
response = self.session.post(url, data={'name': name} if name else None)
if not response:
return None
data = response.json()
return sel... | Adds a new worksheet |
def restore(self, remotepath):
''' Usage: restore <remotepath> - \
restore a file from the recycle bin
remotepath - the remote path to restore
'''
rpath = get_pcs_path(remotepath)
# by default, only 1000 items, more than that sounds a bit crazy
pars = {
'method' : 'listrecycle' }
self.pd("Searching fo... | Usage: restore <remotepath> - \
restore a file from the recycle bin
remotepath - the remote path to restore |
def Default(self, *statements):
"""c-like default of switch statement
"""
assert self.parentStm is None
self.rank += 1
self.default = []
self._register_stements(statements, self.default)
return self | c-like default of switch statement |
def mvn(*args, **kwargs):
"""Convenience function to efficiently construct a MultivariateNormalDiag."""
# Faster than using `tfd.MultivariateNormalDiag`.
return tfd.Independent(tfd.Normal(*args, **kwargs),
reinterpreted_batch_ndims=1) | Convenience function to efficiently construct a MultivariateNormalDiag. |
async def deaths(self, root):
"""Causes of death in the nation, as percentages.
Returns
-------
an :class:`ApiQuery` of dict with keys of str and values of float
"""
return {
elem.get('type'): float(elem.text)
for elem in root.find('DEATHS')
... | Causes of death in the nation, as percentages.
Returns
-------
an :class:`ApiQuery` of dict with keys of str and values of float |
def scan_cnproxy(self):
"""Scan candidate (mainland) proxies from http://cn-proxy.com"""
self.logger.info(
'start scanning http://cn-proxy.com for proxy list...')
response = requests.get('http://cn-proxy.com')
soup = BeautifulSoup(response.content, 'lxml')
tables = so... | Scan candidate (mainland) proxies from http://cn-proxy.com |
def get_instantiated_service(self, name):
""" Get instantiated service by name """
if name not in self.instantiated_services:
raise UninstantiatedServiceException
return self.instantiated_services[name] | Get instantiated service by name |
def close(self):
"""
Close the connection and all associated cursors. This will implicitly
roll back any uncommitted operations.
"""
for c in self.cursors:
c.close()
self.cursors = []
self.impl = None | Close the connection and all associated cursors. This will implicitly
roll back any uncommitted operations. |
def manual_configure():
"""
Function to manually configure jackal.
"""
print("Manual configuring jackal")
mapping = { '1': 'y', '0': 'n'}
config = Config()
# Host
host = input_with_default("What is the Elasticsearch host?", config.get('jackal', 'host'))
config.set('jackal', 'host... | Function to manually configure jackal. |
def on_message(self, *args, accept_query=False, matcher=None, **kwargs):
"""
Convenience wrapper of `Client.on_message` pre-bound with `channel=self.name`.
"""
if accept_query:
def new_matcher(msg: Message):
ret = True
if matcher:
... | Convenience wrapper of `Client.on_message` pre-bound with `channel=self.name`. |
def t_prepro_ID(self, t):
r'[_a-zA-Z][_a-zA-Z0-9]*' # preprocessor directives
t.type = reserved_directives.get(t.value.lower(), 'ID')
if t.type == 'DEFINE':
t.lexer.begin('define')
elif t.type == 'PRAGMA':
t.lexer.begin('pragma')
return t | r'[_a-zA-Z][_a-zA-Z0-9]* |
def unlink(self):
"""
Remove this file or link.
If the path is a directory, use rmdir() instead.
"""
if self._closed:
self._raise_closed()
self._accessor.unlink(self) | Remove this file or link.
If the path is a directory, use rmdir() instead. |
def __create_canvas(self, dimension, pairs, position, **kwargs):
"""!
@brief Create new canvas with user defined parameters to display cluster or chunk of cluster on it.
@param[in] dimension (uint): Data-space dimension.
@param[in] pairs (list): Pair of coordinates that will be dis... | !
@brief Create new canvas with user defined parameters to display cluster or chunk of cluster on it.
@param[in] dimension (uint): Data-space dimension.
@param[in] pairs (list): Pair of coordinates that will be displayed on the canvas. If empty than label will not
be di... |
def _find_bounds_1d(data, x):
"""
Find the index of the lower bound where ``x`` should be inserted
into ``a`` to maintain order.
The index of the upper bound is the index of the lower bound
plus 2. Both bound indices must be within the array.
Parameters
-------... | Find the index of the lower bound where ``x`` should be inserted
into ``a`` to maintain order.
The index of the upper bound is the index of the lower bound
plus 2. Both bound indices must be within the array.
Parameters
----------
data : 1D `~numpy.ndarray`
... |
def _list_dir(self, path):
"""returns absolute paths for all entries in a directory"""
try:
elements = [
os.path.join(path, x) for x in os.listdir(path)
] if os.path.isdir(path) else []
elements.sort()
except OSError:
elements = Non... | returns absolute paths for all entries in a directory |
def load_all_methods(self):
r'''Method which picks out coefficients for the specified chemical
from the various dictionaries and DataFrames storing it. All data is
stored as attributes. This method also sets obj:`all_methods_P` as a
set of methods for which the data exists for.
... | r'''Method which picks out coefficients for the specified chemical
from the various dictionaries and DataFrames storing it. All data is
stored as attributes. This method also sets obj:`all_methods_P` as a
set of methods for which the data exists for.
Called on initialization only. See t... |
def metric(self, name, count, elapsed):
"""A metric function that writes a single CSV file
:arg str name: name of the metric
:arg int count: number of items
:arg float elapsed: time in seconds
"""
if name is None:
warnings.warn("Ignoring unnamed metric", sta... | A metric function that writes a single CSV file
:arg str name: name of the metric
:arg int count: number of items
:arg float elapsed: time in seconds |
def gen_search_gzh_url(keyword, page=1):
"""拼接搜索 公众号 URL
Parameters
----------
keyword : str or unicode
搜索文字
page : int, optional
页数 the default is 1
Returns
-------
str
search_gzh_url
"""
assert isinst... | 拼接搜索 公众号 URL
Parameters
----------
keyword : str or unicode
搜索文字
page : int, optional
页数 the default is 1
Returns
-------
str
search_gzh_url |
def rollback(self, revision=None, annotations=None):
"""
Performs a rollback of the Deployment.
If the 'revision' parameter is omitted, we fetch the Deployment's system-generated
annotation containing the current revision, and revert to the version immediately
preceding the curr... | Performs a rollback of the Deployment.
If the 'revision' parameter is omitted, we fetch the Deployment's system-generated
annotation containing the current revision, and revert to the version immediately
preceding the current version.
:param revision: The revision to rollback to.
... |
def stem(self, word):
"""Return the S-stemmed form of a word.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = SStemmer()
>>> stmr.stem('summarie... | Return the S-stemmed form of a word.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = SStemmer()
>>> stmr.stem('summaries')
'summary'
>>>... |
def vecs_to_datmesh(x, y):
"""
Converts input arguments x and y to a 2d meshgrid,
suitable for calling Means, Covariances and Realizations.
"""
x, y = meshgrid(x, y)
out = zeros(x.shape + (2,), dtype=float)
out[:, :, 0] = x
out[:, :, 1] = y
return out | Converts input arguments x and y to a 2d meshgrid,
suitable for calling Means, Covariances and Realizations. |
def handle_GET(self):
"""
Overwrite this method to handle a GET request. The default
action is to respond with "error 404 (not found)".
"""
self.send_response(404)
self.end_headers()
self.wfile.write('not found'.encode('utf8')) | Overwrite this method to handle a GET request. The default
action is to respond with "error 404 (not found)". |
def commit(self, snapshot: Tuple[Hash32, UUID]) -> None:
"""
Commit the journal to the point where the snapshot was taken. This
will merge in any changesets that were recorded *after* the snapshot changeset.
"""
_, account_snapshot = snapshot
self._account_db.commit(acco... | Commit the journal to the point where the snapshot was taken. This
will merge in any changesets that were recorded *after* the snapshot changeset. |
def get_authentication_statement(self, subject, ticket):
"""
Build an AuthenticationStatement XML block for a SAML 1.1
Assertion.
"""
authentication_statement = etree.Element('AuthenticationStatement')
authentication_statement.set('AuthenticationInstant',
... | Build an AuthenticationStatement XML block for a SAML 1.1
Assertion. |
def _on_state(self, state, client):
"""
Launch forward prediction for the new state given by some client.
"""
def cb(outputs):
try:
distrib, value = outputs.result()
except CancelledError:
logger.info("Client {} cancelled.".format(c... | Launch forward prediction for the new state given by some client. |
def setup(cli):
"""Everything to make skypipe ready to use"""
if not cli.global_config.loaded:
setup_dotcloud_account(cli)
discover_satellite(cli)
cli.success("Skypipe is ready for action") | Everything to make skypipe ready to use |
def update_playlist_song(self, playlist_id, song_id, op):
"""从播放列表删除或者增加一首歌曲
如果歌曲不存在与歌单中,删除时返回 True;如果歌曲已经存在于
歌单,添加时也返回 True。
"""
action = 'mtop.alimusic.music.list.collectservice.{}songs'.format(
'delete' if op == 'del' else 'add')
payload = {
'l... | 从播放列表删除或者增加一首歌曲
如果歌曲不存在与歌单中,删除时返回 True;如果歌曲已经存在于
歌单,添加时也返回 True。 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.