code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def dispatch(self, test=False): # pylint: disable=too-many-branches
"""
Send configuration to satellites
:return: None
"""
if not self.new_to_dispatch:
raise DispatcherError("Dispatcher cannot dispatch, "
"because no configuration i... | Send configuration to satellites
:return: None |
def exhaust_stream(f):
"""Helper decorator for methods that exhausts the stream on return."""
def wrapper(self, stream, *args, **kwargs):
try:
return f(self, stream, *args, **kwargs)
finally:
exhaust = getattr(stream, "exhaust", None)
if exhaust is not None:
... | Helper decorator for methods that exhausts the stream on return. |
def execute_command_with_path_in_process(command, path, shell=False, cwd=None, logger=None):
"""Executes a specific command in a separate process with a path as argument.
:param command: the command to be executed
:param path: the path as first argument to the shell command
:param bool shell: Whether t... | Executes a specific command in a separate process with a path as argument.
:param command: the command to be executed
:param path: the path as first argument to the shell command
:param bool shell: Whether to use a shell
:param str cwd: The working directory of the command
:param logger: optional l... |
def _get_parameter(self, name, tp, timeout=1.0, max_retries=2):
""" Gets the specified drive parameter.
Gets a parameter from the drive. Only supports ``bool``,
``int``, and ``float`` parameters.
Parameters
----------
name : str
Name of the parameter to chec... | Gets the specified drive parameter.
Gets a parameter from the drive. Only supports ``bool``,
``int``, and ``float`` parameters.
Parameters
----------
name : str
Name of the parameter to check. It is always the command to
set it but without the value.
... |
def send_facebook(self, token):
"""
Tells the server which Facebook account this client uses.
After sending, the server takes some time to
get the data from Facebook.
Seems to be broken in recent versions of the game.
"""
self.send_struct('<B%iB' % len(token), 8... | Tells the server which Facebook account this client uses.
After sending, the server takes some time to
get the data from Facebook.
Seems to be broken in recent versions of the game. |
def cmd(send, _, args):
"""Returns a list of admins.
V = Verified (authed to NickServ), U = Unverified.
Syntax: {command}
"""
adminlist = []
for admin in args['db'].query(Permissions).order_by(Permissions.nick).all():
if admin.registered:
adminlist.append("%s (V)" % admin.n... | Returns a list of admins.
V = Verified (authed to NickServ), U = Unverified.
Syntax: {command} |
def encode(char_data, encoding='utf-8'):
"""
Encode the parameter as a byte string.
:param char_data:
:rtype: bytes
"""
if type(char_data) is unicode:
return char_data.encode(encoding, 'replace')
else:
return char_data | Encode the parameter as a byte string.
:param char_data:
:rtype: bytes |
def normalizeGlyphRightMargin(value):
"""
Normalizes glyph right margin.
* **value** must be a :ref:`type-int-float` or `None`.
* Returned value is the same type as the input value.
"""
if not isinstance(value, (int, float)) and value is not None:
raise TypeError("Glyph right margin mus... | Normalizes glyph right margin.
* **value** must be a :ref:`type-int-float` or `None`.
* Returned value is the same type as the input value. |
def _approximate_eigenvalues(A, tol, maxiter, symmetric=None,
initial_guess=None):
"""Apprixmate eigenvalues.
Used by approximate_spectral_radius and condest.
Returns [W, E, H, V, breakdown_flag], where W and E are the eigenvectors
and eigenvalues of the Hessenberg matrix ... | Apprixmate eigenvalues.
Used by approximate_spectral_radius and condest.
Returns [W, E, H, V, breakdown_flag], where W and E are the eigenvectors
and eigenvalues of the Hessenberg matrix H, respectively, and V is the
Krylov space. breakdown_flag denotes whether Lanczos/Arnoldi suffered
breakdown.... |
def count_matrix(self):
# TODO: does this belong here or to the BHMM sampler, or in a subclass containing HMM with data?
"""Compute the transition count matrix from hidden state trajectory.
Returns
-------
C : numpy.array with shape (nstates,nstates)
C[i,j] is the nu... | Compute the transition count matrix from hidden state trajectory.
Returns
-------
C : numpy.array with shape (nstates,nstates)
C[i,j] is the number of transitions observed from state i to state j
Raises
------
RuntimeError
A RuntimeError is raise... |
def main_base_ramp(self) -> "Ramp":
""" Returns the Ramp instance of the closest main-ramp to start location. Look in game_info.py for more information """
if hasattr(self, "cached_main_base_ramp"):
return self.cached_main_base_ramp
self.cached_main_base_ramp = min(
{ramp... | Returns the Ramp instance of the closest main-ramp to start location. Look in game_info.py for more information |
def _validate_logical(self, rule, field, value):
""" {'allowed': ('allof', 'anyof', 'noneof', 'oneof')} """
if not isinstance(value, Sequence):
self._error(field, errors.BAD_TYPE)
return
validator = self._get_child_validator(
document_crumb=rule, allow_unknow... | {'allowed': ('allof', 'anyof', 'noneof', 'oneof')} |
def set(self, key, val):
"""
Return a new PMap with key and val inserted.
>>> m1 = m(a=1, b=2)
>>> m2 = m1.set('a', 3)
>>> m3 = m1.set('c' ,4)
>>> m1
pmap({'a': 1, 'b': 2})
>>> m2
pmap({'a': 3, 'b': 2})
>>> m3
pmap({'a': 1, 'c': 4,... | Return a new PMap with key and val inserted.
>>> m1 = m(a=1, b=2)
>>> m2 = m1.set('a', 3)
>>> m3 = m1.set('c' ,4)
>>> m1
pmap({'a': 1, 'b': 2})
>>> m2
pmap({'a': 3, 'b': 2})
>>> m3
pmap({'a': 1, 'c': 4, 'b': 2}) |
def _build_flavors(p, flist, qualdecl=None):
"""
Build and return a dictionary defining the flavors from the
flist argument.
This function maps from the input keyword definitions for the flavors
(ex. EnableOverride) to the PyWBEM internal definitions
(ex. overridable)
... | Build and return a dictionary defining the flavors from the
flist argument.
This function maps from the input keyword definitions for the flavors
(ex. EnableOverride) to the PyWBEM internal definitions
(ex. overridable)
Uses the qualdecl argument as a basis if it exists. This i... |
def validate(self):
"""
Perform validation check on properties.
"""
if not self.api_token or not self.api_token_secret:
raise ImproperlyConfigured("'api_token' and 'api_token_secret' are required for authentication.")
if self.response_type not in ["json", "pson", "xm... | Perform validation check on properties. |
def describe_unsupported(series, **kwargs):
"""Compute summary statistics of a unsupported (`S_TYPE_UNSUPPORTED`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with ind... | Compute summary statistics of a unsupported (`S_TYPE_UNSUPPORTED`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys. |
def publish(self, message, tag=b''):
"""
Publish `message` with specified `tag`.
:param message: message data
:type message: str
:param tag: message tag
:type tag: str
"""
self.send(tag + b'\0' + message) | Publish `message` with specified `tag`.
:param message: message data
:type message: str
:param tag: message tag
:type tag: str |
def update(self):
"""Update sensors stats using the input method."""
# Init new stats
stats = self.get_init_value()
if self.input_method == 'local':
# Update stats using the dedicated lib
stats = []
# Get the temperature
try:
... | Update sensors stats using the input method. |
def transformer_en_de_512(dataset_name=None, src_vocab=None, tgt_vocab=None, pretrained=False,
ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""Transformer pretrained model.
Embedding size is 400, and hidden layer size is 1150.
Parameters
----------
... | r"""Transformer pretrained model.
Embedding size is 400, and hidden layer size is 1150.
Parameters
----------
dataset_name : str or None, default None
src_vocab : gluonnlp.Vocab or None, default None
tgt_vocab : gluonnlp.Vocab or None, default None
pretrained : bool, default False
... |
def format(logger,
show_successful=True,
show_errors=True,
show_traceback=True):
"""
Prints a report of the actions that were logged by the given Logger.
The report contains a list of successful actions, as well as the full
error message on failed actions.
:type lo... | Prints a report of the actions that were logged by the given Logger.
The report contains a list of successful actions, as well as the full
error message on failed actions.
:type logger: Logger
:param logger: The logger that recorded what happened in the queue.
:rtype: string
:return: A string... |
def get_root_path(self, language):
"""
Get root path to pass to the LSP servers.
This can be the current project path or the output of
getcwd_or_home (except for Python, see below).
"""
path = None
# Get path of the current project
if self.main and self.... | Get root path to pass to the LSP servers.
This can be the current project path or the output of
getcwd_or_home (except for Python, see below). |
def _call_process(self, method, *args, **kwargs):
"""Run the given git command with the specified arguments and return
the result as a String
:param method:
is the command. Contained "_" characters will be converted to dashes,
such as in 'ls_files' to call 'ls-files'.
:param args:
is the list of argu... | Run the given git command with the specified arguments and return
the result as a String
:param method:
is the command. Contained "_" characters will be converted to dashes,
such as in 'ls_files' to call 'ls-files'.
:param args:
is the list of arguments. If None is included, it will be pruned.
This ... |
def get_cpu_info(self) -> str:
'''Show device CPU information.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'cat', '/proc/cpuinfo')
return output | Show device CPU information. |
def get_coeffs(expr, expand=False, epsilon=0.):
"""Create a dictionary with all Operator terms of the expression
(understood as a sum) as keys and their coefficients as values.
The returned object is a defaultdict that return 0. if a term/key
doesn't exist.
Args:
expr: The operator express... | Create a dictionary with all Operator terms of the expression
(understood as a sum) as keys and their coefficients as values.
The returned object is a defaultdict that return 0. if a term/key
doesn't exist.
Args:
expr: The operator expression to get all coefficients from.
expand: Wheth... |
def _send_packet(
self, ip, port, packet,
update_timestamp=True, acknowledge_packet=True
):
"""
Send a packet
:param ip: Ip to send to
:type ip: str
:param port: Port to send to
:type port: int
:param packet: Packet to be transmitted
... | Send a packet
:param ip: Ip to send to
:type ip: str
:param port: Port to send to
:type port: int
:param packet: Packet to be transmitted
:type packet: APPMessage
:param update_timestamp: Should update timestamp to current
:type update_timestamp: bool
... |
def get_model(cls, name=None, status=ENABLED):
"""
Returns model instance of plugin point or plugin, depending from which
class this methos is called.
Example::
plugin_model_instance = MyPlugin.get_model()
plugin_model_instance = MyPluginPoint.get_model('plugin-... | Returns model instance of plugin point or plugin, depending from which
class this methos is called.
Example::
plugin_model_instance = MyPlugin.get_model()
plugin_model_instance = MyPluginPoint.get_model('plugin-name')
plugin_point_model_instance = MyPluginPoint.get_... |
def coerce(cls, arg):
"""Given an arg, return the appropriate value given the class."""
try:
return cls(arg).value
except (ValueError, TypeError):
raise InvalidParameterDatatype("%s coerce error" % (cls.__name__,)) | Given an arg, return the appropriate value given the class. |
def _get_simple_dtype_and_shape(self, colnum, rows=None):
"""
When reading a single column, we want the basic data
type and the shape of the array.
for scalar columns, shape is just nrows, otherwise
it is (nrows, dim1, dim2)
Note if rows= is sent and only a single row i... | When reading a single column, we want the basic data
type and the shape of the array.
for scalar columns, shape is just nrows, otherwise
it is (nrows, dim1, dim2)
Note if rows= is sent and only a single row is requested,
the shape will be (dim2,dim2) |
def predict_is(self, h=5, fit_once=True, fit_method='MLE', intervals=False):
""" Makes dynamic in-sample predictions with the estimated model
Parameters
----------
h : int (default : 5)
How many steps would you like to forecast?
fit_once : boolean
(defau... | Makes dynamic in-sample predictions with the estimated model
Parameters
----------
h : int (default : 5)
How many steps would you like to forecast?
fit_once : boolean
(default: True) Fits only once before the in-sample prediction; if False, fits after every new ... |
def extend(self, *args):
"""
Extend a given object with all the properties in
passed-in object(s).
"""
args = list(args)
for i in args:
self.obj.update(i)
return self._wrap(self.obj) | Extend a given object with all the properties in
passed-in object(s). |
def add(self, fact):
"""Create a VALID token and send it to all children."""
token = Token.valid(fact)
MATCHER.debug("<BusNode> added %r", token)
for child in self.children:
child.callback(token) | Create a VALID token and send it to all children. |
def widgetEdited(self, event=None, val=None, action='entry', skipDups=True):
""" A general method for firing any applicable triggers when
a value has been set. This is meant to be easily callable from any
part of this class (or its subclasses), so that it can be called
as so... | A general method for firing any applicable triggers when
a value has been set. This is meant to be easily callable from any
part of this class (or its subclasses), so that it can be called
as soon as need be (immed. on click?). This is smart enough to
be called multiple... |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(IPMISensorCollector, self).get_default_config()
config.update({
'bin': '/usr/bin/ipmitool',
'use_sudo': False,
'sudo_cmd': ... | Returns the default collector settings |
def curated(name):
"""Download and return a path to a sample that is curated by the PyAV developers.
Data is handled by :func:`cached_download`.
"""
return cached_download('https://docs.mikeboers.com/pyav/samples/' + name,
os.path.join('pyav-curated', name.replace('/', os.pa... | Download and return a path to a sample that is curated by the PyAV developers.
Data is handled by :func:`cached_download`. |
def power(self, n):
"""The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
Kraus: the matrix power of the SuperOp converted to a Kraus channel.
Raises:
QiskitError: if the input and output d... | The matrix power of the channel.
Args:
n (int): compute the matrix power of the superoperator matrix.
Returns:
Kraus: the matrix power of the SuperOp converted to a Kraus channel.
Raises:
QiskitError: if the input and output dimensions of the
Qu... |
def tar(filename, dirs=[], gzip=False):
""" Create a tar-file or a tar.gz at location: filename.
params:
gzip: if True - gzip the file, default = False
dirs: dirs to be tared
returns a 3-tuple with returncode (integer), terminal output (string)
and the new filename.
"""
if gzip:
... | Create a tar-file or a tar.gz at location: filename.
params:
gzip: if True - gzip the file, default = False
dirs: dirs to be tared
returns a 3-tuple with returncode (integer), terminal output (string)
and the new filename. |
def filter_by_cols(self, cols, ID=None):
"""
Keep only Measurements in corresponding columns.
"""
rows = to_list(cols)
fil = lambda x: x in rows
applyto = {k: self._positions[k][1] for k in self.keys()}
if ID is None:
ID = self.ID + '.filtered_by_cols'... | Keep only Measurements in corresponding columns. |
def strip_empty_lines_forward(self, content, i):
"""
Skip over empty lines
:param content: parsed text
:param i: current parsed line
:return: number of skipped lined
"""
while i < len(content):
line = content[i].strip(' \r\n\t\f')
if line !... | Skip over empty lines
:param content: parsed text
:param i: current parsed line
:return: number of skipped lined |
def from_pdf(
cls, pdf, filename, width=288, height=432, dpi=203, font_path=None,
center_of_pixel=False, use_bindings=False
):
"""
Filename is 1-8 alphanumeric characters to identify the GRF in ZPL.
Dimensions and DPI are for a typical 4"x6" shipping label.
E.g. 432 ... | Filename is 1-8 alphanumeric characters to identify the GRF in ZPL.
Dimensions and DPI are for a typical 4"x6" shipping label.
E.g. 432 points / 72 points in an inch / 203 dpi = 6 inches
Using center of pixel will improve barcode quality but may decrease
the quality of some text.
... |
def get_people(self, user_alias=None):
"""
获取用户信息
:param user_alias: 用户ID
:return:
"""
user_alias = user_alias or self.api.user_alias
content = self.api.req(API_PEOPLE_HOME % user_alias).content
xml = self.api.to_xml(re.sub(b'<br />', b'\n', cont... | 获取用户信息
:param user_alias: 用户ID
:return: |
def _strOrDate(st):
'''internal'''
if isinstance(st, string_types):
return st
elif isinstance(st, datetime):
return st.strftime('%Y%m%d')
raise PyEXception('Not a date: %s', str(st)) | internal |
def touch(self, connection=None):
"""
Mark this update as complete.
IMPORTANT, If the marker table doesn't exist,
the connection transaction will be aborted and the connection reset.
Then the marker table will be created.
"""
self.create_marker_table()
i... | Mark this update as complete.
IMPORTANT, If the marker table doesn't exist,
the connection transaction will be aborted and the connection reset.
Then the marker table will be created. |
def get_or_create_ec2_key_pair(name=None, verbose=1):
"""
Creates and saves an EC2 key pair to a local PEM file.
"""
verbose = int(verbose)
name = name or env.vm_ec2_keypair_name
pem_path = 'roles/%s/%s.pem' % (env.ROLE, name)
conn = get_ec2_connection()
kp = conn.get_key_pair(name)
... | Creates and saves an EC2 key pair to a local PEM file. |
def get(self, hash, account="*", max_transactions=100, min_confirmations=6, raw=False):
"""
Args:
hash: can be a bitcoin address or a transaction id. If it's a
bitcoin address it will return a list of transactions up to
``max_transactions`` a list of unspents ... | Args:
hash: can be a bitcoin address or a transaction id. If it's a
bitcoin address it will return a list of transactions up to
``max_transactions`` a list of unspents with confirmed
transactions greater or equal to ``min_confirmantions``
account (... |
def cache_method(func=None, prefix=''):
"""
Cache result of function execution into the `self` object (mostly useful in models).
Calculate cache key based on `args` and `kwargs` of the function (except `self`).
"""
def decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):... | Cache result of function execution into the `self` object (mostly useful in models).
Calculate cache key based on `args` and `kwargs` of the function (except `self`). |
def get_schema(self):
"""Return the schema."""
path = os.path.join(self._get_schema_folder(), self._name + ".json")
with open(path, "rb") as file:
schema = json.loads(file.read().decode("UTF-8"))
return schema | Return the schema. |
def export(self, path, session):
"""See `Module.export`."""
def variables_saver(variables_path):
if self._saver:
self._saver.save(
session, variables_path,
write_meta_graph=False,
write_state=False)
self._spec._export(path, variables_saver) | See `Module.export`. |
def draw_markers(self):
"""Draw all created markers on the TimeLine Canvas"""
self._canvas_markers.clear()
for marker in self._markers.values():
self.create_marker(marker["category"], marker["start"], marker["finish"], marker) | Draw all created markers on the TimeLine Canvas |
def hide_routemap_holder_route_map_content_set_dampening_half_life(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_map = ET.SubElem... | Auto Generated Code |
def reinforce(self, **kwargs):
"""
Reinforces the grid and calculates grid expansion costs.
See :meth:`edisgo.flex_opt.reinforce_grid` for more information.
"""
results = reinforce_grid(
self, max_while_iterations=kwargs.get(
'max_while_iterations', ... | Reinforces the grid and calculates grid expansion costs.
See :meth:`edisgo.flex_opt.reinforce_grid` for more information. |
def _send_data(self, data, start_offset, file_len):
"""Send the block to the storage service.
This is a utility method that does not modify self.
Args:
data: data to send in str.
start_offset: start offset of the data in relation to the file.
file_len: an int if this is the last data to ... | Send the block to the storage service.
This is a utility method that does not modify self.
Args:
data: data to send in str.
start_offset: start offset of the data in relation to the file.
file_len: an int if this is the last data to append to the file.
Otherwise '*'. |
def setName( self, name ):
"""
Define name for this expression, makes debugging and exception messages clearer.
Example::
Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)
Word(nums).setName("integer").parseString("ABC") #... | Define name for this expression, makes debugging and exception messages clearer.
Example::
Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)
Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (l... |
def kana2alphabet(text):
"""Convert Hiragana to hepburn-style alphabets
Parameters
----------
text : str
Hiragana string.
Return
------
str
Hepburn-style alphabets string.
Examples
--------
>>> print(jaconv.kana2alphabet('まみさん'))
mamisan
"""
text = ... | Convert Hiragana to hepburn-style alphabets
Parameters
----------
text : str
Hiragana string.
Return
------
str
Hepburn-style alphabets string.
Examples
--------
>>> print(jaconv.kana2alphabet('まみさん'))
mamisan |
def bipartition(seq):
"""Return a list of bipartitions for a sequence.
Args:
a (Iterable): The sequence to partition.
Returns:
list[tuple[tuple]]: A list of tuples containing each of the two
partitions.
Example:
>>> bipartition((1,2,3))
[((), (1, 2, 3)), ((1,),... | Return a list of bipartitions for a sequence.
Args:
a (Iterable): The sequence to partition.
Returns:
list[tuple[tuple]]: A list of tuples containing each of the two
partitions.
Example:
>>> bipartition((1,2,3))
[((), (1, 2, 3)), ((1,), (2, 3)), ((2,), (1, 3)), ((1... |
def get_all_fields(self, arr):
"""
Returns a list containing this struct's fields and all the fields of
its ancestors. Used during validation.
"""
for k, v in self.fields.items():
arr.append(v)
if self.extends:
parent = self.contract.... | Returns a list containing this struct's fields and all the fields of
its ancestors. Used during validation. |
def _xfs_info_get_kv(serialized):
'''
Parse one line of the XFS info output.
'''
# No need to know sub-elements here
if serialized.startswith("="):
serialized = serialized[1:].strip()
serialized = serialized.replace(" = ", "=*** ").replace(" =", "=")
# Keywords has no spaces, value... | Parse one line of the XFS info output. |
def delist(target):
''' for any "list" found, replace with a single entry if the list has exactly one entry '''
result = target
if type(target) is dict:
for key in target:
target[key] = delist(target[key])
if type(target) is list:
if len(target)==0:
result = None
... | for any "list" found, replace with a single entry if the list has exactly one entry |
def add_oxidation_state_by_guess(self, **kwargs):
"""
Decorates the structure with oxidation state, guessing
using Composition.oxi_state_guesses()
Args:
**kwargs: parameters to pass into oxi_state_guesses()
"""
oxid_guess = self.composition.oxi_state_guesses(... | Decorates the structure with oxidation state, guessing
using Composition.oxi_state_guesses()
Args:
**kwargs: parameters to pass into oxi_state_guesses() |
def dictlist_replace(dict_list: Iterable[Dict], key: str, value: Any) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, change
(in place) ``d[key]`` to ``value``.
"""
for d in dict_list:
d[key] = value | Process an iterable of dictionaries. For each dictionary ``d``, change
(in place) ``d[key]`` to ``value``. |
def run(host='0.0.0.0', port=5000, reload=True, debug=True):
""" Run development server """
from werkzeug.serving import run_simple
app = bootstrap.get_app()
return run_simple(
hostname=host,
port=port,
application=app,
use_reloader=reload,
use_debugger=debug,
... | Run development server |
def get_documents(self):
"""Return all the parsed ``Documents`` in the database.
:rtype: A list of all ``Documents`` in the database ordered by name.
"""
return self.session.query(Document).order_by(Document.name).all() | Return all the parsed ``Documents`` in the database.
:rtype: A list of all ``Documents`` in the database ordered by name. |
def display_widgets(self):
"""
Displays all the widgets associated with this Container.
Should be called when the widgets need to be "re-packed/gridded".
"""
# All widgets are removed and then recreated to ensure the order they
# were created is the order they are displa... | Displays all the widgets associated with this Container.
Should be called when the widgets need to be "re-packed/gridded". |
def remove(self, docid):
"""
Remove a document from the database.
"""
docid = int(docid)
self.store.executeSQL(self.removeSQL, (docid,)) | Remove a document from the database. |
def _id(self):
"""Handle identifiers and reserverd keywords."""
result = ''
while self.char is not None and (self.char.isalnum() or self.char == '_'):
result += self.char
self.advance()
token = RESERVED_KEYWORDS.get(result, Token(Nature.ID, result))
retur... | Handle identifiers and reserverd keywords. |
def surface_state(num_lat=90,
num_lon=None,
water_depth=10.,
T0=12.,
T2=-40.):
"""Sets up a state variable dictionary for a surface model
(e.g. :class:`~climlab.model.ebm.EBM`) with a uniform slab ocean depth.
The domain is either 1D (... | Sets up a state variable dictionary for a surface model
(e.g. :class:`~climlab.model.ebm.EBM`) with a uniform slab ocean depth.
The domain is either 1D (latitude) or 2D (latitude, longitude)
depending on whether the input argument num_lon is supplied.
Returns a single state variable `Ts`, the temperat... |
def shift(func, *args, **kwargs):
"""This function is basically a beefed up lambda x: func(x, *args, **kwargs)
:func:`shift` comes in handy when it is used in a pipeline with a function that
needs the passed value as its first argument.
:param func: a function
:param args: objects
:param kwarg... | This function is basically a beefed up lambda x: func(x, *args, **kwargs)
:func:`shift` comes in handy when it is used in a pipeline with a function that
needs the passed value as its first argument.
:param func: a function
:param args: objects
:param kwargs: keywords
>>> def div(x, y): retur... |
def task(**kwargs):
"""A function task decorator used in place of ``@celery_app.task``."""
def wrapper(wrapped):
def callback(scanner, name, obj):
celery_app = scanner.config.registry.celery_app
celery_app.task(**kwargs)(obj)
venusian.attach(wrapped, callback)
... | A function task decorator used in place of ``@celery_app.task``. |
def import_keyset(self, keyset):
"""Imports a RFC 7517 keyset using the standard JSON format.
:param keyset: The RFC 7517 representation of a JOSE Keyset.
"""
try:
jwkset = json_decode(keyset)
except Exception: # pylint: disable=broad-except
raise Invali... | Imports a RFC 7517 keyset using the standard JSON format.
:param keyset: The RFC 7517 representation of a JOSE Keyset. |
def integratedAutocorrelationTime(A_n, B_n=None, fast=False, mintime=3):
"""Estimate the integrated autocorrelation time.
See Also
--------
statisticalInefficiency
"""
g = statisticalInefficiency(A_n, B_n, fast, mintime)
tau = (g - 1.0) / 2.0
return tau | Estimate the integrated autocorrelation time.
See Also
--------
statisticalInefficiency |
def consulta(self, endereco, primeiro=False,
uf=None, localidade=None, tipo=None, numero=None):
"""Consulta site e retorna lista de resultados"""
if uf is None:
url = 'consultaEnderecoAction.do'
data = {
'relaxation': endereco.encode('ISO-8859-1'... | Consulta site e retorna lista de resultados |
def _update_task(self, task):
"""
Assigns current task step to self.task
then updates the task's data with self.task_data
Args:
task: Task object.
"""
self.task = task
self.task.data.update(self.task_data)
self.task_type = task.task_spec.__cla... | Assigns current task step to self.task
then updates the task's data with self.task_data
Args:
task: Task object. |
def _set_overlay_service_policy(self, v, load=False):
"""
Setter method for overlay_service_policy, mapped from YANG variable /overlay_gateway/overlay_service_policy (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_overlay_service_policy is considered as a pri... | Setter method for overlay_service_policy, mapped from YANG variable /overlay_gateway/overlay_service_policy (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_overlay_service_policy is considered as a private
method. Backends looking to populate this variable should... |
def _process_using_meta_feature_generator(self, X, meta_feature_generator):
"""Process using secondary learner meta-feature generator
Since secondary learner meta-feature generator can be anything e.g. predict, predict_proba,
this internal method gives the ability to use any string. Just make s... | Process using secondary learner meta-feature generator
Since secondary learner meta-feature generator can be anything e.g. predict, predict_proba,
this internal method gives the ability to use any string. Just make sure secondary learner
has the method.
Args:
X (array-like)... |
def extract_input(pipe_def=None, pipe_generator=None):
"""Extract inputs required by a pipe"""
if pipe_def:
pyinput = gen_input(pipe_def)
elif pipe_generator:
pyinput = pipe_generator(Context(describe_input=True))
else:
raise Exception('Must supply at least one kwarg!')
retu... | Extract inputs required by a pipe |
def validate_units(self):
"""Ensure that wavelenth and flux units belong to the
correct classes.
Raises
------
TypeError
Wavelength unit is not `~pysynphot.units.WaveUnits` or
flux unit is not `~pysynphot.units.FluxUnits`.
"""
if (not isi... | Ensure that wavelenth and flux units belong to the
correct classes.
Raises
------
TypeError
Wavelength unit is not `~pysynphot.units.WaveUnits` or
flux unit is not `~pysynphot.units.FluxUnits`. |
def clear(self):
"""
Removes all data from the buffer.
"""
self.io.seek(0)
self.io.truncate()
for item in self.monitors:
item[2] = 0 | Removes all data from the buffer. |
def propertyWidgetMap(self):
"""
Returns the mapping for this page between its widgets and its
scaffold property.
:return {<projex.scaffold.Property>: <QtGui.QWidget>, ..}
"""
out = {}
scaffold = self.scaffold()
# initialize... | Returns the mapping for this page between its widgets and its
scaffold property.
:return {<projex.scaffold.Property>: <QtGui.QWidget>, ..} |
def directory_open(self, path, filter_p, flags):
"""Opens a directory in the guest and creates a :py:class:`IGuestDirectory`
object that can be used for further operations.
This method follows symbolic links by default at the moment, this
may change in the future.
in p... | Opens a directory in the guest and creates a :py:class:`IGuestDirectory`
object that can be used for further operations.
This method follows symbolic links by default at the moment, this
may change in the future.
in path of type str
Path to the directory to open. G... |
def parse_date(datestring):
"""Attepmts to parse an ISO8601 formatted ``datestring``.
Returns a ``datetime.datetime`` object.
"""
datestring = str(datestring).strip()
if not datestring[0].isdigit():
raise ParseError()
if 'W' in datestring.upper():
try:
datestring =... | Attepmts to parse an ISO8601 formatted ``datestring``.
Returns a ``datetime.datetime`` object. |
def makedirs(path, ignore_extsep=False):
"""Makes all directories required for given path; returns true if successful
and false otherwise.
**Examples**:
::
auxly.filesys.makedirs("bar/baz")
"""
if not ignore_extsep and op.basename(path).find(os.extsep) > -1:
path = op.dirname(pa... | Makes all directories required for given path; returns true if successful
and false otherwise.
**Examples**:
::
auxly.filesys.makedirs("bar/baz") |
def cross_origin(app, *args, **kwargs):
"""
This function is the decorator which is used to wrap a Sanic route with.
In the simplest case, simply use the default parameters to allow all
origins in what is the most permissive configuration. If this method
modifies state or performs authentication whi... | This function is the decorator which is used to wrap a Sanic route with.
In the simplest case, simply use the default parameters to allow all
origins in what is the most permissive configuration. If this method
modifies state or performs authentication which may be brute-forced, you
should add some degr... |
def match(self, *args):
"""Whether or not to enter a given case statement"""
self.fall = self.fall or not args
self.fall = self.fall or (self.value in args)
return self.fall | Whether or not to enter a given case statement |
def add_to_context(self, name, **attrs):
"""Add attributes to a context.
"""
context = self.get_context(name=name)
attrs_ = context['context']
attrs_.update(**attrs) | Add attributes to a context. |
def find_by(cls, parent=None, **attributes):
"""
Gets the first resource of the given type and parent (if provided) with matching attributes.
This will trigger an api GET request.
:param parent ResourceBase: the parent of the resource - used for nesting the request url, optional
... | Gets the first resource of the given type and parent (if provided) with matching attributes.
This will trigger an api GET request.
:param parent ResourceBase: the parent of the resource - used for nesting the request url, optional
:param **attributes: any number of keyword arguments as attribute... |
def get_history_kline(self,
code,
start=None,
end=None,
ktype=KLType.K_DAY,
autype=AuType.QFQ,
fields=[KL_FIELD.ALL]):
"""
得到本地历史k线,需先参照帮助文档下载k线
:param cod... | 得到本地历史k线,需先参照帮助文档下载k线
:param code: 股票代码
:param start: 开始时间,例如'2017-06-20'
:param end: 结束时间,例如'2017-06-30'
start和end的组合如下:
========== ========== ========================================
start类型 end类型 说明
... |
def bgblack(cls, string, auto=False):
"""Color-code entire string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color
"""
return cls.colorize('bgblack', st... | Color-code entire string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color |
def reporter(self):
"""
Create the MASH report
"""
logging.info('Creating {} report'.format(self.analysistype))
make_path(self.reportpath)
header = 'Strain,ReferenceGenus,ReferenceFile,ReferenceGenomeMashDistance,Pvalue,NumMatchingHashes\n'
data = ''
for s... | Create the MASH report |
def stats(self, index=None, metric=None, params=None):
"""
Retrieve statistics on different operations happening on an index.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-stats.html>`_
:arg index: A comma-separated list of index names; use `_all` or empty
... | Retrieve statistics on different operations happening on an index.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-stats.html>`_
:arg index: A comma-separated list of index names; use `_all` or empty
string to perform the operation on all indices
:arg metric... |
def _create_archive(self):
'''This will create a tar.gz compressed archive of the scrubbed directory'''
try:
self.archive_path = os.path.join(self.report_dir, "%s.tar.gz" % self.session)
self.logger.con_out('Creating SOSCleaner Archive - %s', self.archive_path)
t = ta... | This will create a tar.gz compressed archive of the scrubbed directory |
def _parse_line(sep, line):
"""
Parse a grub commands/config with format: cmd{sep}opts
Returns: (name, value): value can be None
"""
strs = line.split(sep, 1)
return (strs[0].strip(), None) if len(strs) == 1 else (strs[0].strip(), strs[1].strip()) | Parse a grub commands/config with format: cmd{sep}opts
Returns: (name, value): value can be None |
def load_shapefile(self, feature_type, base_path):
"""Load downloaded shape file to QGIS Main Window.
TODO: This is cut & paste from OSM - refactor to have one method
:param feature_type: What kind of features should be downloaded.
Currently 'buildings', 'building-points' or 'roads... | Load downloaded shape file to QGIS Main Window.
TODO: This is cut & paste from OSM - refactor to have one method
:param feature_type: What kind of features should be downloaded.
Currently 'buildings', 'building-points' or 'roads' are supported.
:type feature_type: str
:par... |
def outline(self, face_ids=None, **kwargs):
"""
Given a list of face indexes find the outline of those
faces and return it as a Path3D.
The outline is defined here as every edge which is only
included by a single triangle.
Note that this implies a non-watertight mesh as... | Given a list of face indexes find the outline of those
faces and return it as a Path3D.
The outline is defined here as every edge which is only
included by a single triangle.
Note that this implies a non-watertight mesh as the
outline of a watertight mesh is an empty path.
... |
def optimize(self, x0, f=None, df=None, f_df=None):
"""
:param x0: initial point for a local optimizer.
:param f: function to optimize.
:param df: gradient of the function to optimize.
:param f_df: returns both the function to optimize and its gradient.
"""
if le... | :param x0: initial point for a local optimizer.
:param f: function to optimize.
:param df: gradient of the function to optimize.
:param f_df: returns both the function to optimize and its gradient. |
def kruskal(dv=None, between=None, data=None, detailed=False,
export_filename=None):
"""Kruskal-Wallis H-test for independent samples.
Parameters
----------
dv : string
Name of column containing the dependant variable.
between : string
Name of column containing the betwe... | Kruskal-Wallis H-test for independent samples.
Parameters
----------
dv : string
Name of column containing the dependant variable.
between : string
Name of column containing the between factor.
data : pandas DataFrame
DataFrame
export_filename : string
Filename (... |
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the r... | Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True ... |
def wiki_list(self, title=None, creator_id=None, body_matches=None,
other_names_match=None, creator_name=None, hide_deleted=None,
other_names_present=None, order=None):
"""Function to retrieves a list of every wiki page.
Parameters:
title (str): Page titl... | Function to retrieves a list of every wiki page.
Parameters:
title (str): Page title.
creator_id (int): Creator id.
body_matches (str): Page content.
other_names_match (str): Other names.
creator_name (str): Creator name.
hide_deleted (str... |
def create_parser_options(lazy_mfcollection_parsing: bool = False) -> Dict[str, Dict[str, Any]]:
"""
Utility method to create a default options structure with the lazy parsing inside
:param lazy_mfcollection_parsing:
:return: the options structure filled with lazyparsing option (for the MultifileCollec... | Utility method to create a default options structure with the lazy parsing inside
:param lazy_mfcollection_parsing:
:return: the options structure filled with lazyparsing option (for the MultifileCollectionParser) |
def getSpanDurations(self, time_stamp, service_name, rpc_name):
"""
Given a time stamp, server service name, and rpc name, fetch all of the client services calling in paired
with the lists of every span duration (list<i64>) from the server to client. The lists of span durations
include information on ca... | Given a time stamp, server service name, and rpc name, fetch all of the client services calling in paired
with the lists of every span duration (list<i64>) from the server to client. The lists of span durations
include information on call counts and mean/stdDev/etc of call durations.
The three arguments sp... |
def paramtypes(self):
""" get all parameter types """
for m in [p[1] for p in self.ports]:
for p in [p[1] for p in m]:
for pd in p:
if pd[1] in self.params:
continue
item = (pd[1], pd[1].resolve())
... | get all parameter types |
def unquote(str):
"""Remove quotes from a string."""
if len(str) > 1:
if str.startswith('"') and str.endswith('"'):
return str[1:-1].replace('\\\\', '\\').replace('\\"', '"')
if str.startswith('<') and str.endswith('>'):
return str[1:-1]
return str | Remove quotes from a string. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.