code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def add_content(obj, language, slot, content):
"""
Adds a TextPlugin with given content to given slot
"""
placeholder = obj.placeholders.get(slot=slot)
add_plugin(placeholder, TextPlugin, language, body=content) | Adds a TextPlugin with given content to given slot |
def get_film(film_id):
''' Return a single film '''
result = _get(film_id, settings.FILMS)
return Film(result.content) | Return a single film |
def _calc_min_width(self, table):
""" Calculate the minimum allowable width for a table """
width = len(table.name)
cap = table.consumed_capacity["__table__"]
width = max(width, 4 + len("%.1f/%d" % (cap["read"], table.read_throughput)))
width = max(width, 4 + len("%.1f/%d" % (cap... | Calculate the minimum allowable width for a table |
def prepare_url(self, url, params):
"""Prepares the given HTTP URL."""
url = to_native_string(url)
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and... | Prepares the given HTTP URL. |
def delimit(delimiters, content):
"""
Surround `content` with the first and last characters of `delimiters`.
>>> delimit('[]', "foo") # doctest: +SKIP
'[foo]'
>>> delimit('""', "foo") # doctest: +SKIP
'"foo"'
"""
if len(delimiters) != 2:
raise ValueError(
"`delimit... | Surround `content` with the first and last characters of `delimiters`.
>>> delimit('[]', "foo") # doctest: +SKIP
'[foo]'
>>> delimit('""', "foo") # doctest: +SKIP
'"foo"' |
def _set_lastpage(self):
"""Calculate value of class attribute ``last_page``."""
self.last_page = (len(self._page_data) - 1) // self.screen.page_size | Calculate value of class attribute ``last_page``. |
def verify_signature(certificate, signing_pub_key=None,
signing_pub_key_passphrase=None):
'''
Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
... | Verify that ``certificate`` has been signed by ``signing_pub_key``
certificate:
The certificate to verify. Can be a path or string containing a
PEM formatted certificate.
signing_pub_key:
The public key to verify, can be a string or path to a PEM formatted
certificate, csr, or ... |
def optimise_partition_multiplex(self, partitions, layer_weights=None, n_iterations=2):
""" Optimise the given partitions simultaneously.
Parameters
----------
partitions
List of :class:`~VertexPartition.MutableVertexPartition` layers to optimise.
layer_weights
List of weights of layer... | Optimise the given partitions simultaneously.
Parameters
----------
partitions
List of :class:`~VertexPartition.MutableVertexPartition` layers to optimise.
layer_weights
List of weights of layers.
n_iterations : int
Number of iterations to run the Leiden algorithm. By default, 2... |
def ind_nodes(self, graph=None):
""" Returns a list of all nodes in the graph with no dependencies. """
if graph is None:
graph = self.graph
dependent_nodes = set(
node for dependents in six.itervalues(graph) for node in dependents
)
return [node for node... | Returns a list of all nodes in the graph with no dependencies. |
def transform_config_from_estimator(estimator, task_id, task_type, instance_count, instance_type, data,
data_type='S3Prefix', content_type=None, compression_type=None, split_type=None,
job_name=None, model_name=None, strategy=None, assemble_with=No... | Export Airflow transform config from a SageMaker estimator
Args:
estimator (sagemaker.model.EstimatorBase): The SageMaker estimator to export Airflow config from.
It has to be an estimator associated with a training job.
task_id (str): The task id of any airflow.contrib.operators.SageMa... |
def understand(self):
"""
:returns: Version understand of preview
:rtype: twilio.rest.preview.understand.Understand
"""
if self._understand is None:
self._understand = Understand(self)
return self._understand | :returns: Version understand of preview
:rtype: twilio.rest.preview.understand.Understand |
def fix_parameters(self):
"""Helper function that fixes all parameters"""
for W, b in zip(self.W_list, self.b_list):
W.fix()
b.fix() | Helper function that fixes all parameters |
def get_correlation_matrix_from_columns(self):
"""Computes correlation matrix of columns
:return: Correlation matrix of columns
"""
header_to_column = {} # create index of headers
for header in self.headers:
header_to_column[header] = self.headers.index(header)
... | Computes correlation matrix of columns
:return: Correlation matrix of columns |
def to_pandas_closed_closed(date_range, add_tz=True):
"""
Pandas DateRange slicing is CLOSED-CLOSED inclusive at both ends.
Parameters
----------
date_range : `DateRange` object
converted to CLOSED_CLOSED form for Pandas slicing
add_tz : `bool`
Adds a TimeZone to the daterange ... | Pandas DateRange slicing is CLOSED-CLOSED inclusive at both ends.
Parameters
----------
date_range : `DateRange` object
converted to CLOSED_CLOSED form for Pandas slicing
add_tz : `bool`
Adds a TimeZone to the daterange start and end if it doesn't
have one.
Returns
---... |
def index(self):
""" Index all files/directories below the current BIDSNode. """
config_list = self.config
layout = self.layout
for (dirpath, dirnames, filenames) in os.walk(self.path):
# If layout configuration file exists, delete it
layout_file = self.layout.... | Index all files/directories below the current BIDSNode. |
def decode_terminated(data, encoding, strict=True):
"""Returns the decoded data until the first NULL terminator
and all data after it.
Args:
data (bytes): data to decode
encoding (str): The codec to use
strict (bool): If True will raise ValueError in case no NULL is found
... | Returns the decoded data until the first NULL terminator
and all data after it.
Args:
data (bytes): data to decode
encoding (str): The codec to use
strict (bool): If True will raise ValueError in case no NULL is found
but the available data decoded successfully.
Returns:... |
def avoid(self) -> Tuple[Tuple[int], Tuple[int]]:
"""
Assembles a list of per-hypothesis words to avoid. The indices are (x, y) pairs into the scores
array, which has dimensions (beam_size, target_vocab_size). These values are then used by the caller
to set these items to np.inf so they ... | Assembles a list of per-hypothesis words to avoid. The indices are (x, y) pairs into the scores
array, which has dimensions (beam_size, target_vocab_size). These values are then used by the caller
to set these items to np.inf so they won't be selected. Words to be avoided are selected by
consult... |
def json_response(request, data):
"""
Wrapper dumping `data` to a json and sending it to the user with an HttpResponse
:param django.http.HttpRequest request: The request object used to generate this response.
:param dict data: The python dictionnary to return as a json
:return: The... | Wrapper dumping `data` to a json and sending it to the user with an HttpResponse
:param django.http.HttpRequest request: The request object used to generate this response.
:param dict data: The python dictionnary to return as a json
:return: The content of ``data`` serialized in json
:r... |
def confd_state_loaded_data_models_data_model_namespace(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
loaded_data_models = ET.SubElement(confd_state, "l... | Auto Generated Code |
def _calculate_timestamps(self):
"""Return a list of Ladybug DateTime in this analysis period."""
self._timestamps_data = []
if not self._is_reversed:
self._calc_timestamps(self.st_time, self.end_time)
else:
self._calc_timestamps(self.st_time, DateTime.from_hoy(87... | Return a list of Ladybug DateTime in this analysis period. |
def kill_tasks(self, app_id, scale=False, wipe=False,
host=None, batch_size=0, batch_delay=0):
"""Kill all tasks belonging to app.
:param str app_id: application ID
:param bool scale: if true, scale down the app by the number of tasks killed
:param str host: if provid... | Kill all tasks belonging to app.
:param str app_id: application ID
:param bool scale: if true, scale down the app by the number of tasks killed
:param str host: if provided, only terminate tasks on this Mesos slave
:param int batch_size: if non-zero, terminate tasks in groups of this si... |
def require_scopes_exact(self, scope_string):
"""
:param scope_string: The required scopes.
:type scope_string: Union[str, list]
:return: The tokens with only the requested scopes.
:rtype: :class:`esi.managers.TokenQueryset`
"""
num_scopes = len(_process_scopes(sc... | :param scope_string: The required scopes.
:type scope_string: Union[str, list]
:return: The tokens with only the requested scopes.
:rtype: :class:`esi.managers.TokenQueryset` |
def excess_sharpe(returns, factor_returns, out=None):
"""
Determines the Excess Sharpe of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_retu... | Determines the Excess Sharpe of a strategy.
Parameters
----------
returns : pd.Series or np.ndarray
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns: float / series
Benchmark return to compare returns ag... |
def get_terms_in_subset(ont, subset):
"""
Find all nodes in a subset.
We assume the oboInOwl encoding of subsets, and subset IDs are IRIs
"""
namedGraph = get_named_graph(ont)
# note subsets have an unusual encoding
query = """
prefix oboInOwl: <http://www.geneontology.org/formats/oboI... | Find all nodes in a subset.
We assume the oboInOwl encoding of subsets, and subset IDs are IRIs |
def set_theme(self, theme_name, toplevel=None, themebg=None):
"""Redirect the set_theme call to also set Tk background color"""
if self._toplevel is not None and toplevel is None:
toplevel = self._toplevel
if self._themebg is not None and themebg is None:
themebg = self._... | Redirect the set_theme call to also set Tk background color |
def _make_namespace(self) -> Namespace:
"""Make a namespace."""
namespace = Namespace(
name=self._get_namespace_name(),
keyword=self._get_namespace_keyword(),
url=self._get_namespace_url(),
version=str(time.asctime()),
)
self.session.add(na... | Make a namespace. |
def _writeData(self, config=None):
"""Raises error"""
if config is None:
config = ID3SaveConfig()
if config.v2_version == 3:
frame = self._get_v23_frame(sep=config.v23_separator)
else:
frame = self
data = []
for writer in self._frame... | Raises error |
def check_version_info(conn, version_table, expected_version):
"""
Checks for a version value in the version table.
Parameters
----------
conn : sa.Connection
The connection to use to perform the check.
version_table : sa.Table
The version table of the asset database
expecte... | Checks for a version value in the version table.
Parameters
----------
conn : sa.Connection
The connection to use to perform the check.
version_table : sa.Table
The version table of the asset database
expected_version : int
The expected version of the asset database
Rai... |
def datetime_period(base=None, hours=None, minutes=None, seconds=None):
"""Round a datetime object down to the start of a defined period.
The `base` argument may be used to find the period start for an arbitrary datetime, defaults to `utcnow()`.
"""
if base is None:
base = utcnow()
base -= timedelta(
ho... | Round a datetime object down to the start of a defined period.
The `base` argument may be used to find the period start for an arbitrary datetime, defaults to `utcnow()`. |
def init_logger(
name="",
handler_path_levels=None,
level=logging.INFO,
formatter=None,
formatter_str=None,
datefmt="%Y-%m-%d %H:%M:%S",
):
"""Add a default handler for logger.
Args:
name = '' or logger obj.
handler_path_levels = [['loggerfile.log',13],['','DEBUG'],['','info']... | Add a default handler for logger.
Args:
name = '' or logger obj.
handler_path_levels = [['loggerfile.log',13],['','DEBUG'],['','info'],['','notSet']] # [[path,level]]
level = the least level for the logger.
formatter = logging.Formatter(
'%(levelname)-7s %(asctime)s %(name)s (%(file... |
def get_service_instance(host, username=None, password=None, protocol=None,
port=None, mechanism='userpass', principal=None,
domain=None):
'''
Authenticate with a vCenter server or ESX/ESXi host and return the service instance object.
host
The locat... | Authenticate with a vCenter server or ESX/ESXi host and return the service instance object.
host
The location of the vCenter server or ESX/ESXi host.
username
The username used to login to the vCenter server or ESX/ESXi host.
Required if mechanism is ``userpass``
password
... |
def goto_assignments(request_data):
"""
Go to assignements worker.
"""
code = request_data['code']
line = request_data['line'] + 1
column = request_data['column']
path = request_data['path']
# encoding = request_data['encoding']
encoding = 'utf-8'
script = jedi.Script(code, line,... | Go to assignements worker. |
def _sid_subdir_path(sid):
"""
Format subdir path to limit the number directories in any given
subdirectory to 100.
The number in each directory is designed to support at least 100000
equities.
Parameters
----------
sid : int
Asset identifier.
Returns
-------
out :... | Format subdir path to limit the number directories in any given
subdirectory to 100.
The number in each directory is designed to support at least 100000
equities.
Parameters
----------
sid : int
Asset identifier.
Returns
-------
out : string
A path for the bcolz ro... |
def readString(self, st):
"""Parse a WFS capabilities document, returning an
instance of WFSCapabilitiesInfoset
string should be an XML capabilities document
"""
if not isinstance(st, str) and not isinstance(st, bytes):
raise ValueError("String must be of type string... | Parse a WFS capabilities document, returning an
instance of WFSCapabilitiesInfoset
string should be an XML capabilities document |
def geom2localortho(geom):
"""Convert existing geom to local orthographic projection
Useful for local cartesian distance/area calculations
"""
cx, cy = geom.Centroid().GetPoint_2D()
lon, lat, z = cT_helper(cx, cy, 0, geom.GetSpatialReference(), wgs_srs)
local_srs = localortho(lon,lat)
local... | Convert existing geom to local orthographic projection
Useful for local cartesian distance/area calculations |
def tablecopy(tablename, newtablename, deep=False, valuecopy=False, dminfo={},
endian='aipsrc', memorytable=False, copynorows=False):
"""Copy a table.
It is the same as :func:`table.copy`, but without the need to open
the table first.
"""
t = table(tablename, ack=False)
return t.... | Copy a table.
It is the same as :func:`table.copy`, but without the need to open
the table first. |
def _create_subepochs(x, nperseg, step):
"""Transform the data into a matrix for easy manipulation
Parameters
----------
x : 1d ndarray
actual data values
nperseg : int
number of samples in each row to create
step : int
distance in samples between rows
Returns
--... | Transform the data into a matrix for easy manipulation
Parameters
----------
x : 1d ndarray
actual data values
nperseg : int
number of samples in each row to create
step : int
distance in samples between rows
Returns
-------
2d ndarray
a view (i.e. doesn'... |
def _bg_combine(self, bgs):
"""Combine several background amplitude images"""
out = np.ones(self.h5["raw"].shape, dtype=float)
# bg is an h5py.DataSet
for bg in bgs:
out *= bg[:]
return out | Combine several background amplitude images |
def grep(self, path, content, flags):
""" grep every child path under path for content """
try:
match = re.compile(content, flags)
except sre_constants.error as ex:
print("Bad regexp: %s" % (ex))
return
for gpath, matches in self.do_grep(path, match):... | grep every child path under path for content |
def start_server(self, host='localhost', port=9000, app=None):
"""Start a `wsgiref.simple_server` based server to run this mapper."""
from wsgiref.simple_server import make_server
if app is None:
app = self.wsgi
server = make_server(host, port, app)
server_addr = "%s:... | Start a `wsgiref.simple_server` based server to run this mapper. |
def leader_get(attribute=None):
"""Juju leader get value(s)"""
cmd = ['leader-get', '--format=json'] + [attribute or '-']
return json.loads(subprocess.check_output(cmd).decode('UTF-8')) | Juju leader get value(s) |
def set_pending_symbol(self, pending_symbol=None):
"""Sets the context's ``pending_symbol`` with the given unicode sequence and resets the context's ``value``.
If the input is None, an empty :class:`CodePointArray` is used.
"""
if pending_symbol is None:
pending_symbol = Cod... | Sets the context's ``pending_symbol`` with the given unicode sequence and resets the context's ``value``.
If the input is None, an empty :class:`CodePointArray` is used. |
def encode(data, encoding=None, errors='strict', keep=False,
preserve_dict_class=False, preserve_tuples=False):
'''
Generic function which will encode whichever type is passed, if necessary
If `strict` is True, and `keep` is False, and we fail to encode, a
UnicodeEncodeError will be raised. ... | Generic function which will encode whichever type is passed, if necessary
If `strict` is True, and `keep` is False, and we fail to encode, a
UnicodeEncodeError will be raised. Passing `keep` as True allows for the
original value to silently be returned in cases where encoding fails. This
can be useful ... |
def sg_flatten(tensor, opt):
r"""Reshapes a tensor to `batch_size x -1`.
See `tf.reshape()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
name: If provided, it replaces current tensor's name.
Returns:
A 2-D tensor.
"""
dim = np.pro... | r"""Reshapes a tensor to `batch_size x -1`.
See `tf.reshape()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
name: If provided, it replaces current tensor's name.
Returns:
A 2-D tensor. |
def name(self):
"""The unique name of this object, relative to the parent."""
basename = self.basename
if basename is None:
return None
parent = self.Naming_parent
if parent is None:
return basename
else:
return parent.gene... | The unique name of this object, relative to the parent. |
def compute_freq(self, csd=False):
"""Compute frequency domain analysis.
Returns
-------
list of dict
each item is a dict where 'data' is an instance of ChanFreq for a
single segment of signal, 'name' is the event type, if applicable,
'times' is a tup... | Compute frequency domain analysis.
Returns
-------
list of dict
each item is a dict where 'data' is an instance of ChanFreq for a
single segment of signal, 'name' is the event type, if applicable,
'times' is a tuple of the start and end times in sec, 'duratio... |
def get_cgi_parameter_list(form: cgi.FieldStorage, key: str) -> List[str]:
"""
Extracts a list of values, all with the same key, from a CGI form.
"""
return form.getlist(key) | Extracts a list of values, all with the same key, from a CGI form. |
def self_register_user(self, user_name, account_id, user_terms_of_use, pseudonym_unique_id, communication_channel_address=None, communication_channel_type=None, user_birthdate=None, user_locale=None, user_short_name=None, user_sortable_name=None, user_time_zone=None):
"""
Self register a user.
... | Self register a user.
Self register and return a new user and pseudonym for an account.
If self-registration is enabled on the account, you can use this
endpoint to self register new users. |
def send(self, to, message):
"""Send a message to another process.
Same as ``Process.send`` except that ``message`` is a protocol buffer.
Returns immediately.
:param to: The pid of the process to send a message.
:type to: :class:`PID`
:param message: The message to send
:type method: A pr... | Send a message to another process.
Same as ``Process.send`` except that ``message`` is a protocol buffer.
Returns immediately.
:param to: The pid of the process to send a message.
:type to: :class:`PID`
:param message: The message to send
:type method: A protocol buffer instance.
:raises:... |
def italic(s, *, escape=True):
r"""Make a string appear italicized in LaTeX formatting.
italic() wraps a given string in the LaTeX command \textit{}.
Args
----
s : str
The string to be formatted.
escape: bool
If true the italic text will be escaped
Returns
-------
... | r"""Make a string appear italicized in LaTeX formatting.
italic() wraps a given string in the LaTeX command \textit{}.
Args
----
s : str
The string to be formatted.
escape: bool
If true the italic text will be escaped
Returns
-------
NoEscape
The formatted stri... |
def get_datetime_type(to_string):
""" Validates UTC datetime. Examples of accepted forms:
2017-12-31T01:11:59Z,2017-12-31T01:11Z or 2017-12-31T01Z or 2017-12-31 """
from datetime import datetime
def datetime_type(string):
""" Validates UTC datetime. Examples of accepted forms:
2017-12-3... | Validates UTC datetime. Examples of accepted forms:
2017-12-31T01:11:59Z,2017-12-31T01:11Z or 2017-12-31T01Z or 2017-12-31 |
def container_stop(name, timeout=30, force=True, remote_addr=None,
cert=None, key=None, verify_cert=True):
'''
Stop a container
name :
Name of the container to stop
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide rem... | Stop a container
name :
Name of the container to stop
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and its a TCP Address!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
... |
def unflatten_list(flat_dict, separator='_'):
"""
Unflattens a dictionary, first assuming no lists exist and then tries to
identify lists and replaces them
This is probably not very efficient and has not been tested extensively
Feel free to add test cases or rewrite the logic
Issues that stand o... | Unflattens a dictionary, first assuming no lists exist and then tries to
identify lists and replaces them
This is probably not very efficient and has not been tested extensively
Feel free to add test cases or rewrite the logic
Issues that stand out to me:
- Sorting all the keys in the dictionary, wh... |
def get_win32_short_path_name(long_name):
"""
Gets the short path name of a given long path.
References:
http://stackoverflow.com/a/23598461/200291
http://stackoverflow.com/questions/23598289/get-win-short-fname-python
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_... | Gets the short path name of a given long path.
References:
http://stackoverflow.com/a/23598461/200291
http://stackoverflow.com/questions/23598289/get-win-short-fname-python
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import * # NOQA
>>> import utool as ut ... |
def makeDependencyMap(aMap):
"""
create a dependency data structure as follows:
- Each key in aMap represents an item that depends on each item in the iterable which is that key's value
- Each Node represents an item which is a precursor to its parents and depends on its children
Returns a map whose keys are ... | create a dependency data structure as follows:
- Each key in aMap represents an item that depends on each item in the iterable which is that key's value
- Each Node represents an item which is a precursor to its parents and depends on its children
Returns a map whose keys are the items described in aMap and whose... |
def ip_hide_as_path_holder_as_path_access_list_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
hide_as_path_holder = ET.SubElement(ip, "hide-as-path-holder", xmlns="ur... | Auto Generated Code |
def drain_K(self):
""" Return the minor loss coefficient of the drain pipe.
:returns: Minor Loss Coefficient
:return: float
"""
drain_K = minorloss.PIPE_ENTRANCE_K_MINOR + minorloss.PIPE_ENTRANCE_K_MINOR + minorloss.PIPE_EXIT_K_MINOR
return drain_K | Return the minor loss coefficient of the drain pipe.
:returns: Minor Loss Coefficient
:return: float |
def dehtml(text):
'''Remove HTML tag in input text and format the texts
accordingly. '''
# added by BoPeng to handle html output from kernel
#
# Do not understand why, but I cannot define the class outside of the
# function.
try:
# python 2
from HTMLParser import HTMLParser
... | Remove HTML tag in input text and format the texts
accordingly. |
def stream(self,Tsec = 2,numChan = 1):
"""
Stream audio using callback
Parameters
----------
Tsec : stream time in seconds if Tsec > 0. If Tsec = 0, then stream goes to infinite
mode. When in infinite mode, Tsec.stop() can be used to stop the stream.
... | Stream audio using callback
Parameters
----------
Tsec : stream time in seconds if Tsec > 0. If Tsec = 0, then stream goes to infinite
mode. When in infinite mode, Tsec.stop() can be used to stop the stream.
numChan : number of channels. Use 1 for mono and 2 f... |
def get_qcqp_form(prob):
"""Returns the problem metadata in QCQP class
"""
# Check quadraticity
if not prob.objective.args[0].is_quadratic():
raise Exception("Objective is not quadratic.")
if not all([constr._expr.is_quadratic() for constr in prob.constraints]):
raise Exception("Not ... | Returns the problem metadata in QCQP class |
def build_application_map(vertices_applications, placements, allocations,
core_resource=Cores):
"""Build a mapping from application to a list of cores where the
application is used.
This utility function assumes that each vertex is associated with a
specific application.
... | Build a mapping from application to a list of cores where the
application is used.
This utility function assumes that each vertex is associated with a
specific application.
Parameters
----------
vertices_applications : {vertex: application, ...}
Applications are represented by the path... |
def _catalog_report_helper(catalog, catalog_validation, url, catalog_id,
catalog_org):
"""Toma un dict con la metadata de un catálogo, y devuelve un dict con
los valores que catalog_report() usa para reportar sobre él.
Args:
catalog (dict): Diccionario... | Toma un dict con la metadata de un catálogo, y devuelve un dict con
los valores que catalog_report() usa para reportar sobre él.
Args:
catalog (dict): Diccionario con la metadata de un catálogo.
validation (dict): Resultado, únicamente a nivel catálogo, de la
val... |
def reformat_python_docstrings(top_dirs: List[str],
correct_copyright_lines: List[str],
show_only: bool = True,
rewrite: bool = False,
process_only_filenum: int = None) -> None:
"""
Walk a... | Walk a directory, finding Python files and rewriting them.
Args:
top_dirs: list of directories to descend into
correct_copyright_lines:
list of lines (without newlines) representing the copyright
docstring block, including the transition lines of equals
symbols
... |
def scale(self, sx, sy=None):
"""Modifies the current transformation matrix (CTM)
by scaling the X and Y user-space axes
by :obj:`sx` and :obj:`sy` respectively.
The scaling of the axes takes place after
any existing transformation of user space.
If :obj:`sy` is omitted,... | Modifies the current transformation matrix (CTM)
by scaling the X and Y user-space axes
by :obj:`sx` and :obj:`sy` respectively.
The scaling of the axes takes place after
any existing transformation of user space.
If :obj:`sy` is omitted, it is the same as :obj:`sx`
so t... |
def list_roles(self, principal_name, principal_type):
"""
Parameters:
- principal_name
- principal_type
"""
self.send_list_roles(principal_name, principal_type)
return self.recv_list_roles() | Parameters:
- principal_name
- principal_type |
def item_dict(self, item):
"""
create a default dict of values, including
category and tag lookup
"""
# mocking wierd JSON structure
ret_dict = {"terms":{"category":[],"post_tag":[]}}
for e in item:
# is it a category or tag??
if "category"... | create a default dict of values, including
category and tag lookup |
async def __handle_ping(self, _ : Ping):
""" Handle a Ping message. Pong the backend """
self.__last_ping = time.time()
await ZMQUtils.send(self.__backend_socket, Pong()) | Handle a Ping message. Pong the backend |
def compute_ranks(x):
"""Returns ranks in [0, len(x))
Note: This is different from scipy.stats.rankdata, which returns ranks in
[1, len(x)].
"""
assert x.ndim == 1
ranks = np.empty(len(x), dtype=int)
ranks[x.argsort()] = np.arange(len(x))
return ranks | Returns ranks in [0, len(x))
Note: This is different from scipy.stats.rankdata, which returns ranks in
[1, len(x)]. |
def OpenFile(filename, binary=False, newline=None, encoding=None):
'''
Open a file and returns it.
Consider the possibility of a remote file (HTTP, HTTPS, FTP)
:param unicode filename:
Local or remote filename.
:param bool binary:
If True returns the file as is, ignore any EOL conv... | Open a file and returns it.
Consider the possibility of a remote file (HTTP, HTTPS, FTP)
:param unicode filename:
Local or remote filename.
:param bool binary:
If True returns the file as is, ignore any EOL conversion.
If set ignores univeral_newlines parameter.
:param None|''... |
def match(self, name):
"""
Check if given name matches.
Args:
name (str): name to check.
Returns:
bool: matches name.
"""
if self.method == Ex.Method.PREFIX:
return name.startswith(self.value)
elif self.method == Ex.Method.SUF... | Check if given name matches.
Args:
name (str): name to check.
Returns:
bool: matches name. |
def rpc_method(func=None, name=None, entry_point=ALL, protocol=ALL,
str_standardization=settings.MODERNRPC_PY2_STR_TYPE,
str_standardization_encoding=settings.MODERNRPC_PY2_STR_ENCODING):
"""
Mark a standard python function as RPC method.
All arguments are optional
:param... | Mark a standard python function as RPC method.
All arguments are optional
:param func: A standard function
:param name: Used as RPC method name instead of original function name
:param entry_point: Default: ALL. Used to limit usage of the RPC method for a specific set of entry points
:param protoc... |
def update(self, ng_template_id, name=NotUpdated, plugin_name=NotUpdated,
hadoop_version=NotUpdated, flavor_id=NotUpdated,
description=NotUpdated, volumes_per_node=NotUpdated,
volumes_size=NotUpdated, node_processes=NotUpdated,
node_configs=NotUpdated, floatin... | Update a Node Group Template. |
def get_ftr(self):
"""
Process footer and return the processed string
"""
if not self.ftr:
return self.ftr
width = self.size()[0]
return re.sub(
"%time", "%s\n" % time.strftime("%H:%M:%S"), self.ftr).rjust(width) | Process footer and return the processed string |
def load_toml_path_config(filename):
"""Returns a PathConfig created by loading a TOML file from the
filesystem.
"""
if not os.path.exists(filename):
LOGGER.info(
"Skipping path loading from non-existent config file: %s",
filename)
return PathConfig()
LOGGER.... | Returns a PathConfig created by loading a TOML file from the
filesystem. |
def put_item(TableName=None, Item=None, Expected=None, ReturnValues=None, ReturnConsumedCapacity=None, ReturnItemCollectionMetrics=None, ConditionalOperator=None, ConditionExpression=None, ExpressionAttributeNames=None, ExpressionAttributeValues=None):
"""
Creates a new item, or replaces an old item with a new ... | Creates a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item. You can perform a conditional put operation (add a new item if one with the specified primary key doesn't exist... |
def __getDependenciesRecursiveWithProvider(self,
available_components = None,
search_dirs = None,
target = None,
traverse_links = False,
... | Get installed components using "provider" to find (and possibly
install) components.
This function is called with different provider functions in order
to retrieve a list of all of the dependencies, or install all
dependencies.
Returns
=======
... |
def view_matrix(self):
"""
:return: The current view matrix for the camera
"""
self._update_yaw_and_pitch()
return self._gl_look_at(self.position, self.position + self.dir, self._up) | :return: The current view matrix for the camera |
def police_priority_map_exceed_map_pri7_exceed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
name_key = ET.SubElement(police_priority_map, ... | Auto Generated Code |
def max(self, spec):
"""Adds `max` operator that specifies upper bound for specific index.
:Parameters:
- `spec`: a list of field, limit pairs specifying the exclusive
upper bound for all keys of a specific index in order.
.. versionadded:: 2.7
"""
if not ... | Adds `max` operator that specifies upper bound for specific index.
:Parameters:
- `spec`: a list of field, limit pairs specifying the exclusive
upper bound for all keys of a specific index in order.
.. versionadded:: 2.7 |
def options(self, *args, **kwargs):
"""Applies simplified option definition returning a new object
Applies options defined in a flat format to the objects
returned by the DynamicMap. If the options are to be set
directly on the objects in the HoloMap a simple format may be
used,... | Applies simplified option definition returning a new object
Applies options defined in a flat format to the objects
returned by the DynamicMap. If the options are to be set
directly on the objects in the HoloMap a simple format may be
used, e.g.:
obj.options(cmap='viridis',... |
def get_generator(self, field):
'''
Return a value generator based on the field instance that is passed to
this method. This function may return ``None`` which means that the
specified field will be ignored (e.g. if no matching generator was
found).
'''
if isinsta... | Return a value generator based on the field instance that is passed to
this method. This function may return ``None`` which means that the
specified field will be ignored (e.g. if no matching generator was
found). |
def _find_parenthesis(self, position, forward=True):
""" If 'forward' is True (resp. False), proceed forwards
(resp. backwards) through the line that contains 'position' until an
unmatched closing (resp. opening) parenthesis is found. Returns a
tuple containing the position o... | If 'forward' is True (resp. False), proceed forwards
(resp. backwards) through the line that contains 'position' until an
unmatched closing (resp. opening) parenthesis is found. Returns a
tuple containing the position of this parenthesis (or -1 if it is
not found) and the... |
def tangency_portfolio(cov_mat, exp_rets, allow_short=False):
"""
Computes a tangency portfolio, i.e. a maximum Sharpe ratio portfolio.
Note: As the Sharpe ratio is not invariant with respect
to leverage, it is not possible to construct non-trivial
market neutral tangency portfolios. This is be... | Computes a tangency portfolio, i.e. a maximum Sharpe ratio portfolio.
Note: As the Sharpe ratio is not invariant with respect
to leverage, it is not possible to construct non-trivial
market neutral tangency portfolios. This is because for
a positive initial Sharpe ratio the sharpe grows unbound
... |
def import_from_string(self, text, title=None):
"""Import data from string"""
data = self.model.get_data()
# Check if data is a dict
if not hasattr(data, "keys"):
return
editor = ImportWizard(self, text, title=title,
contents_title... | Import data from string |
def mknts(self, add_dct):
"""Add information from add_dct to a new copy of namedtuples stored in nts."""
nts = []
assert len(add_dct) == len(self.nts)
flds = list(next(iter(self.nts))._fields) + list(next(iter(add_dct)).keys())
ntobj = cx.namedtuple("ntgoea", " ".join(flds))
... | Add information from add_dct to a new copy of namedtuples stored in nts. |
def channels(self):
"""
Access the channels
:returns: twilio.rest.chat.v2.service.channel.ChannelList
:rtype: twilio.rest.chat.v2.service.channel.ChannelList
"""
if self._channels is None:
self._channels = ChannelList(self._version, service_sid=self._solution... | Access the channels
:returns: twilio.rest.chat.v2.service.channel.ChannelList
:rtype: twilio.rest.chat.v2.service.channel.ChannelList |
def _init_metadata(self):
"""stub"""
self._min_integer_value = None
self._max_integer_value = None
self._integer_value_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
... | stub |
def match_serializers(self, serializers, default_media_type):
"""Choose serializer for a given request based on query arg or headers.
Checks if query arg `format` (by default) is present and tries to match
the serializer based on the arg value, by resolving the mimetype mapped
to the ar... | Choose serializer for a given request based on query arg or headers.
Checks if query arg `format` (by default) is present and tries to match
the serializer based on the arg value, by resolving the mimetype mapped
to the arg value.
Otherwise, chooses the serializer by retrieving the best... |
def binary_dilation(x, radius=3):
"""Return fast binary morphological dilation of an image.
see `skimage.morphology.binary_dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_dilation>`__.
Parameters
-----------
x : 2D array
A binary image.
r... | Return fast binary morphological dilation of an image.
see `skimage.morphology.binary_dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_dilation>`__.
Parameters
-----------
x : 2D array
A binary image.
radius : int
For the radius of mas... |
def read_namespaced_event(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_event # noqa: E501
read the specified Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> t... | read_namespaced_event # noqa: E501
read the specified Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_event(name, namespace, async_req=True)
>>> result... |
def destroy(self):
'''
Tear down the minion
'''
if self._running is False:
return
self._running = False
if hasattr(self, 'schedule'):
del self.schedule
if hasattr(self, 'pub_channel') and self.pub_channel is not None:
self.pub_... | Tear down the minion |
def set_cache_complex_value(self, name, value):
"""Set a variable in the local complex state dictionary.
This does not change the physical device. Useful if you want the
device state to refect a new value which has not yet updated from
Vera.
"""
for item in self.json_sta... | Set a variable in the local complex state dictionary.
This does not change the physical device. Useful if you want the
device state to refect a new value which has not yet updated from
Vera. |
def _join_json_files(cls, prefix, clear=False):
"""Join different REACH output JSON files into a single JSON object.
The output of REACH is broken into three files that need to be joined
before processing. Specifically, there will be three files of the form:
`<prefix>.uaz.<subcategory>.... | Join different REACH output JSON files into a single JSON object.
The output of REACH is broken into three files that need to be joined
before processing. Specifically, there will be three files of the form:
`<prefix>.uaz.<subcategory>.json`.
Parameters
----------
prefi... |
def on_install(self, editor):
"""
Extends :meth:`spyder.api.EditorExtension.on_install` method to set the
editor instance as the parent widget.
.. warning:: Don't forget to call **super** if you override this
method!
:param editor: editor instance
:type edit... | Extends :meth:`spyder.api.EditorExtension.on_install` method to set the
editor instance as the parent widget.
.. warning:: Don't forget to call **super** if you override this
method!
:param editor: editor instance
:type editor: spyder.plugins.editor.widgets.codeeditor.CodeE... |
def main(args):
"""Main entry point allowing external calls
Args:
args ([str]): command line parameter list
"""
args = parse_args(args)
setup_logging(args.loglevel)
_logger.debug("Starting crazy calculations...")
print("The {}-th Fibonacci number is {}".format(args.n, fib(args.n)))
... | Main entry point allowing external calls
Args:
args ([str]): command line parameter list |
def facilities(self):
"""
This method returns the properties facilities.
:return:
"""
facilities = []
try:
list_items = self._ad_page_content.select("#facilities li")
except Exception as e:
if self._debug:
logging.error(
... | This method returns the properties facilities.
:return: |
def fingerprint(P, obs1, obs2=None, p0=None, tau=1, k=None, ncv=None):
r"""Dynamical fingerprint for equilibrium or relaxation experiment
The dynamical fingerprint is given by the implied time-scale
spectrum together with the corresponding amplitudes.
Parameters
----------
P : (M, M) scipy.spa... | r"""Dynamical fingerprint for equilibrium or relaxation experiment
The dynamical fingerprint is given by the implied time-scale
spectrum together with the corresponding amplitudes.
Parameters
----------
P : (M, M) scipy.sparse matrix
Transition matrix
obs1 : (M,) ndarray
Observ... |
def from_db_value(self, value, expression, connection, context):
"""
"Called in all circumstances when the data is loaded from the
database, including in aggregates and values() calls."
"""
if value is None:
return value
return json_decode(value) | "Called in all circumstances when the data is loaded from the
database, including in aggregates and values() calls." |
def get_system_config_dir():
"""Returns system config location. E.g. /etc/dvc.conf.
Returns:
str: path to the system config directory.
"""
from appdirs import site_config_dir
return site_config_dir(
appname=Config.APPNAME, appauthor=Config.APPAUTHOR
... | Returns system config location. E.g. /etc/dvc.conf.
Returns:
str: path to the system config directory. |
def get_element_mass(self, element):
"""
Determine the masses of elements in the package.
:returns: [kg] An array of element masses. The sequence of the elements
in the result corresponds with the sequence of elements in the
element list of the material.
"""
... | Determine the masses of elements in the package.
:returns: [kg] An array of element masses. The sequence of the elements
in the result corresponds with the sequence of elements in the
element list of the material. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.