code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def remove_user(self, name):
"""Remove user `name` from this :class:`Database`.
User `name` will no longer have permissions to access this
:class:`Database`.
:Parameters:
- `name`: the name of the user to remove
"""
try:
cmd = SON([("dropUser", nam... | Remove user `name` from this :class:`Database`.
User `name` will no longer have permissions to access this
:class:`Database`.
:Parameters:
- `name`: the name of the user to remove |
def is_inexact(arg):
'''
is_inexact(x) yields True if x is a number represented by floating-point data (i.e., either a
non-integer real number or a complex number) and False otherwise.
'''
return (is_inexact(mag(arg)) if is_quantity(arg) else
is_npscalar(u, np.inexact) or is_npvalue(ar... | is_inexact(x) yields True if x is a number represented by floating-point data (i.e., either a
non-integer real number or a complex number) and False otherwise. |
def set_defaults(self, default_values, recursive = False):
"""
Set default values from specified Parameters and returns a new Parameters object.
:param default_values: Parameters with default parameter values.
:param recursive: (optional) true to perform deep copy, and false for shallo... | Set default values from specified Parameters and returns a new Parameters object.
:param default_values: Parameters with default parameter values.
:param recursive: (optional) true to perform deep copy, and false for shallow copy. Default: false
:return: a new Parameters object. |
def get_stdev(self, asset_type):
"""
Returns the standard deviation for a set of a certain asset type.
:param asset_type: ``str`` of the asset type to calculate standard
deviation for.
:returns: A ``int`` or ``float`` of standard deviation, depending on
the self.decimal_... | Returns the standard deviation for a set of a certain asset type.
:param asset_type: ``str`` of the asset type to calculate standard
deviation for.
:returns: A ``int`` or ``float`` of standard deviation, depending on
the self.decimal_precision |
def selfconsistency(self, u_int, J_coup, mean_field_prev=None):
"""Iterates over the hamiltonian to get the stable selfcosistent one"""
if mean_field_prev is None:
mean_field_prev = np.array([self.param['ekin']]*2)
hlog = [mean_field_prev]
self.oper['Hint'] = self.inter_spin... | Iterates over the hamiltonian to get the stable selfcosistent one |
def column_rename(self, existing_name, hsh=None):
"""
Like unique_name, but in addition must be unique to each column of this
feature. accomplishes this by prepending readable string to existing
column name and replacing unique hash at end of column name.
"""
try:
... | Like unique_name, but in addition must be unique to each column of this
feature. accomplishes this by prepending readable string to existing
column name and replacing unique hash at end of column name. |
def _subthread_handle_accepted(self, client):
"""Gets accepted clients from the queue object and sets up the client socket.
The client can then be found in the clients dictionary with the socket object
as the key.
"""
conn, addr = client
if self.handle_incoming(conn, add... | Gets accepted clients from the queue object and sets up the client socket.
The client can then be found in the clients dictionary with the socket object
as the key. |
def cublasStrmm(handle, side, uplo, trans, diag, m, n, alpha, A, lda, B, ldb, C, ldc):
"""
Matrix-matrix product for real triangular matrix.
"""
status = _libcublas.cublasStrmm_v2(handle,
_CUBLAS_SIDE_MODE[side],
_CUBLA... | Matrix-matrix product for real triangular matrix. |
def unlink_chunk(self, x, z):
"""
Remove a chunk from the header of the region file.
Fragmentation is not a problem, chunks are written to free sectors when possible.
"""
# This function fails for an empty file. If that is the case, just return.
if self.size < 2*SECTOR_LE... | Remove a chunk from the header of the region file.
Fragmentation is not a problem, chunks are written to free sectors when possible. |
def lpc(x, N=None):
"""Linear Predictor Coefficients.
:param x:
:param int N: default is length(X) - 1
:Details:
Finds the coefficients :math:`A=(1, a(2), \dots a(N+1))`, of an Nth order
forward linear predictor that predicts the current value value of the
real-valued time series x based ... | Linear Predictor Coefficients.
:param x:
:param int N: default is length(X) - 1
:Details:
Finds the coefficients :math:`A=(1, a(2), \dots a(N+1))`, of an Nth order
forward linear predictor that predicts the current value value of the
real-valued time series x based on past samples:
.. ma... |
def head(self, url):
'''head request, typically used for status code retrieval, etc.
'''
bot.debug('HEAD %s' %url)
return self._call(url, func=requests.head) | head request, typically used for status code retrieval, etc. |
def get_transition (self, input_symbol, state):
'''This returns (action, next state) given an input_symbol and state.
This does not modify the FSM state, so calling this method has no side
effects. Normally you do not call this method directly. It is called by
process().
The se... | This returns (action, next state) given an input_symbol and state.
This does not modify the FSM state, so calling this method has no side
effects. Normally you do not call this method directly. It is called by
process().
The sequence of steps to check for a defined transition goes from ... |
def solidangle_errorprop(twotheta, dtwotheta, sampletodetectordistance, dsampletodetectordistance, pixelsize=None):
"""Solid-angle correction for two-dimensional SAS images with error propagation
Inputs:
twotheta: matrix of two-theta values
dtwotheta: matrix of absolute error of two-theta value... | Solid-angle correction for two-dimensional SAS images with error propagation
Inputs:
twotheta: matrix of two-theta values
dtwotheta: matrix of absolute error of two-theta values
sampletodetectordistance: sample-to-detector distance
dsampletodetectordistance: absolute error of sample... |
def data(self):
"""
Returns a dictionnary containing all the passed data and an item
``error_list`` which holds the result of :attr:`error_list`.
"""
res = {'error_list': self.error_list}
res.update(super(ValidationErrors, self).data)
return res | Returns a dictionnary containing all the passed data and an item
``error_list`` which holds the result of :attr:`error_list`. |
def areObservableElements(self, elementNames):
"""
Mention if all elements are observable element.
:param str ElementName: the element name to evaluate
:return: true if is an observable element, otherwise false.
:rtype: bool
"""
if not(hasattr(elementNames, "__le... | Mention if all elements are observable element.
:param str ElementName: the element name to evaluate
:return: true if is an observable element, otherwise false.
:rtype: bool |
def update(self, personId, emails=None, displayName=None, firstName=None,
lastName=None, avatar=None, orgId=None, roles=None,
licenses=None, **request_parameters):
"""Update details for a person, by ID.
Only an admin can update a person's details.
Email addresses ... | Update details for a person, by ID.
Only an admin can update a person's details.
Email addresses for a person cannot be changed via the Webex Teams API.
Include all details for the person. This action expects all user
details to be present in the request. A common approach is to first... |
def accel_decrease_height(self, *args):
"""Callback to decrease height.
"""
height = self.settings.general.get_int('window-height')
self.settings.general.set_int('window-height', max(height - 2, 0))
return True | Callback to decrease height. |
def get_cfn_parameters(self):
"""Return a dictionary of variables with `type` :class:`CFNType`.
Returns:
dict: variables that need to be submitted as CloudFormation
Parameters.
"""
variables = self.get_variables()
output = {}
for key, value i... | Return a dictionary of variables with `type` :class:`CFNType`.
Returns:
dict: variables that need to be submitted as CloudFormation
Parameters. |
def FileHeader(self):
"""Return the per-file header as a string."""
dt = self.date_time
dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
if self.flag_bits & 0x08:
# Set these to zero because we write them after the f... | Return the per-file header as a string. |
def irelay(gen, thru):
"""Create a new generator by relaying yield/send interactions
through another generator
Parameters
----------
gen: Generable[T_yield, T_send, T_return]
the original generator
thru: ~typing.Callable[[T_yield], ~typing.Generator]
the generator callable throu... | Create a new generator by relaying yield/send interactions
through another generator
Parameters
----------
gen: Generable[T_yield, T_send, T_return]
the original generator
thru: ~typing.Callable[[T_yield], ~typing.Generator]
the generator callable through which each interaction is r... |
def parse_args(args=None):
"""Parse command line arguments and return a dictionary of options
for ttfautohint.ttfautohint function.
`args` can be either None, a list of strings, or a single string,
that is split into individual options with `shlex.split`.
When `args` is None, the console's default... | Parse command line arguments and return a dictionary of options
for ttfautohint.ttfautohint function.
`args` can be either None, a list of strings, or a single string,
that is split into individual options with `shlex.split`.
When `args` is None, the console's default sys.argv are used, and any
Sy... |
def read_mutating_webhook_configuration(self, name, **kwargs): # noqa: E501
"""read_mutating_webhook_configuration # noqa: E501
read the specified MutatingWebhookConfiguration # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, ... | read_mutating_webhook_configuration # noqa: E501
read the specified MutatingWebhookConfiguration # 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_mutating_webhook_configuration(... |
def db_create_table(self, table_name, columns):
"""Create a temporary DB table.
Arguments:
table_name (str): The name of the table.
columns (list): List of columns to add to the DB.
"""
formatted_columns = ''
for col in set(columns):
formatted... | Create a temporary DB table.
Arguments:
table_name (str): The name of the table.
columns (list): List of columns to add to the DB. |
def sync_to_db_from_config(
cls,
druid_config,
user,
cluster,
refresh=True):
"""Merges the ds config from druid_config into one stored in the db."""
session = db.session
datasource = (
session.query(cls)
.filter_... | Merges the ds config from druid_config into one stored in the db. |
def _calculate(self, field):
'''
We want to avoid trouble, so if the field is not enclosed by any other field,
we just return 0.
'''
encloser = field.enclosing
if encloser:
rendered = encloser.get_rendered_fields(RenderContext(self))
if field not i... | We want to avoid trouble, so if the field is not enclosed by any other field,
we just return 0. |
def _ExtractGoogleSearchQuery(self, url):
"""Extracts a search query from a Google URL.
Google Drive: https://drive.google.com/drive/search?q=query
Google Search: https://www.google.com/search?q=query
Google Sites: https://sites.google.com/site/.*/system/app/pages/
search?q=query
... | Extracts a search query from a Google URL.
Google Drive: https://drive.google.com/drive/search?q=query
Google Search: https://www.google.com/search?q=query
Google Sites: https://sites.google.com/site/.*/system/app/pages/
search?q=query
Args:
url (str): URL.
Returns:
... |
def _generate_journal_nested_queries(self, value):
"""Generates ElasticSearch nested query(s).
Args:
value (string): Contains the journal_title, journal_volume and artid or start_page separated by a comma.
This value should be of type string.
Notes:
... | Generates ElasticSearch nested query(s).
Args:
value (string): Contains the journal_title, journal_volume and artid or start_page separated by a comma.
This value should be of type string.
Notes:
The value contains at least one of the 3 mentioned ite... |
def hpcluster(self, data: ['SASdata', str] = None,
freq: str = None,
id: [str, list] = None,
input: [str, list, dict] = None,
score: [str, bool, 'SASdata'] = True,
procopts: str = None,
stmtpassthrough: str = Non... | Python method to call the HPCLUS procedure
Documentation link:
https://go.documentation.sas.com/?docsetId=emhpprcref&docsetTarget=emhpprcref_hpclus_toc.htm&docsetVersion=14.2&locale=en
:param data: SASdata object or string. This parameter is required.
:parm freq: The freq variable can ... |
def _inner(self, x1, x2):
"""Raw inner product of two elements."""
return self.tspace._inner(x1.tensor, x2.tensor) | Raw inner product of two elements. |
def get_encrypted_reply(self, message):
"""
对一个指定的 WeRoBot Message ,获取 handlers 处理后得到的 Reply。
如果可能,对该 Reply 进行加密。
返回 Reply Render 后的文本。
:param message: 一个 WeRoBot Message 实例。
:return: reply (纯文本)
"""
reply = self.get_reply(message)
if not reply:
... | 对一个指定的 WeRoBot Message ,获取 handlers 处理后得到的 Reply。
如果可能,对该 Reply 进行加密。
返回 Reply Render 后的文本。
:param message: 一个 WeRoBot Message 实例。
:return: reply (纯文本) |
def _expand_list(names):
""" Do a wildchar name expansion of object names in a list and return expanded list.
The items are expected to exist as this is used for copy sources or delete targets.
Currently we support wildchars in the key name only.
"""
if names is None:
names = []
elif isinstance(na... | Do a wildchar name expansion of object names in a list and return expanded list.
The items are expected to exist as this is used for copy sources or delete targets.
Currently we support wildchars in the key name only. |
def reverse_readfile(filename):
"""
A much faster reverse read of file by using Python's mmap to generate a
memory-mapped file. It is slower for very small files than
reverse_readline, but at least 2x faster for large files (the primary use
of such a method).
Args:
filename (str):
... | A much faster reverse read of file by using Python's mmap to generate a
memory-mapped file. It is slower for very small files than
reverse_readline, but at least 2x faster for large files (the primary use
of such a method).
Args:
filename (str):
Name of file to read.
Yields:
... |
def strduration_long (duration, do_translate=True):
"""Turn a time value in seconds into x hours, x minutes, etc."""
if do_translate:
# use global translator functions
global _, _n
else:
# do not translate
_ = lambda x: x
_n = lambda a, b, n: a if n==1 else b
if d... | Turn a time value in seconds into x hours, x minutes, etc. |
def preview(self, components=None, ask=0):
"""
Inspects differences between the last deployment and the current code state.
"""
ask = int(ask)
self.init()
component_order, plan_funcs = self.get_component_funcs(components=components)
print('\n%i changes found f... | Inspects differences between the last deployment and the current code state. |
def SetScrollPercent(self, horizontalPercent: float, verticalPercent: float, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationScrollPattern::SetScrollPercent.
Set the horizontal and vertical scroll positions as a percentage of the total content area within the UI Automation ... | Call IUIAutomationScrollPattern::SetScrollPercent.
Set the horizontal and vertical scroll positions as a percentage of the total content area within the UI Automation element.
horizontalPercent: float or int, a value in [0, 100] or ScrollPattern.NoScrollValue(-1) if no scroll.
verticalPercent: f... |
def _keep_this(self, name):
"""Return True if there are to be no modifications to name."""
for keep_name in self.keep:
if name == keep_name:
return True
return False | Return True if there are to be no modifications to name. |
def lt(self, key, value, includeMissing=False):
'''Return entries where the key's value is less (<).
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 },
... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]},
... | Return entries where the key's value is less (<).
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 },
... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]},
... {"name": "Joe", "age": 20, "income": 15000, ... |
def head_object_async(self, path, **kwds):
"""HEAD an object.
Depending on request headers, HEAD returns various object properties,
e.g. Content-Length, Last-Modified, and ETag.
Note: No payload argument is supported.
"""
return self.do_request_async(self.api_url + path, 'HEAD', **kwds) | HEAD an object.
Depending on request headers, HEAD returns various object properties,
e.g. Content-Length, Last-Modified, and ETag.
Note: No payload argument is supported. |
def get(app, name):
'''Get a backend given its name'''
backend = get_all(app).get(name)
if not backend:
msg = 'Harvest backend "{0}" is not registered'.format(name)
raise EntrypointError(msg)
return backend | Get a backend given its name |
def _sync_enter(self):
"""
Helps to cut boilerplate on async context
managers that offer synchronous variants.
"""
if hasattr(self, 'loop'):
loop = self.loop
else:
loop = self._client.loop
if loop.is_running():
raise RuntimeError(
'You must use "async wit... | Helps to cut boilerplate on async context
managers that offer synchronous variants. |
def iterscrapers(self, method, mode = None):
''' Iterates over all available scrapers. '''
global discovered
if discovered.has_key(self.language) and discovered[self.language].has_key(method):
for Scraper in discovered[self.language][method]:
yield Scraper | Iterates over all available scrapers. |
def dftphotom(cfg):
"""Run the discrete-Fourier-transform photometry algorithm.
See the module-level documentation and the output of ``casatask dftphotom
--help`` for help. All of the algorithm configuration is specified in the
*cfg* argument, which is an instance of :class:`Config`.
"""
tb = ... | Run the discrete-Fourier-transform photometry algorithm.
See the module-level documentation and the output of ``casatask dftphotom
--help`` for help. All of the algorithm configuration is specified in the
*cfg* argument, which is an instance of :class:`Config`. |
def file_resolve(backend, filepath):
"""
Mark a conflicted file as resolved, so that a merge can be completed
"""
recipe = DKRecipeDisk.find_recipe_name()
if recipe is None:
raise click.ClickException('You must be in a recipe folder.')
click.secho("%s - Resolving conflicts" % get_dateti... | Mark a conflicted file as resolved, so that a merge can be completed |
def wrap_text(text, width):
"""
Wrap text paragraphs to the given character width while preserving
newlines.
"""
out = []
for paragraph in text.splitlines():
# Wrap returns an empty list when paragraph is a newline. In order
# to preserve newlines ... | Wrap text paragraphs to the given character width while preserving
newlines. |
def add_argument(self, *args, parser=None, autoenv=False, env=None,
complete=None, **kwargs):
""" Allow cleaner action supplementation. Autoenv will generate an
environment variable to be usable as a defaults setter based on the
command name and the dest property of the act... | Allow cleaner action supplementation. Autoenv will generate an
environment variable to be usable as a defaults setter based on the
command name and the dest property of the action. |
def application_information(self, application_id):
"""
The MapReduce application master information resource provides overall
information about that mapreduce application master.
This includes application id, time it was started, user, name, etc.
:returns: API response object wi... | The MapReduce application master information resource provides overall
information about that mapreduce application master.
This includes application id, time it was started, user, name, etc.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response` |
def svd_thresh(data, threshold=None, n_pc=None, thresh_type='hard'):
r"""Threshold the singular values
This method thresholds the input data using singular value decomposition
Parameters
----------
data : np.ndarray
Input data array, 2D matrix
threshold : float or np.ndarray, optional
... | r"""Threshold the singular values
This method thresholds the input data using singular value decomposition
Parameters
----------
data : np.ndarray
Input data array, 2D matrix
threshold : float or np.ndarray, optional
Threshold value(s)
n_pc : int or str, optional
Number... |
def _set_switch_state(self, v, load=False):
"""
Setter method for switch_state, mapped from YANG variable /brocade_system_monitor_ext_rpc/show_system_monitor/output/switch_status/switch_state (system-monitor-health-state-enum)
If this variable is read-only (config: false) in the
source YANG file, then _... | Setter method for switch_state, mapped from YANG variable /brocade_system_monitor_ext_rpc/show_system_monitor/output/switch_status/switch_state (system-monitor-health-state-enum)
If this variable is read-only (config: false) in the
source YANG file, then _set_switch_state is considered as a private
method. ... |
def _schedule_pending_unlocked(self, state):
"""
Consider the pending transfers for a stream, pumping new chunks while
the unacknowledged byte count is below :attr:`window_size_bytes`. Must
be called with the FileStreamState lock held.
:param FileStreamState state:
S... | Consider the pending transfers for a stream, pumping new chunks while
the unacknowledged byte count is below :attr:`window_size_bytes`. Must
be called with the FileStreamState lock held.
:param FileStreamState state:
Stream to schedule chunks for. |
def diet(file, configuration, check):
"""Simple program that either print config customisations for your
environment or compresses file FILE."""
config = process.read_yaml_configuration(configuration)
process.diet(file, config) | Simple program that either print config customisations for your
environment or compresses file FILE. |
def find_all_template(im_source, im_search, threshold=0.5, maxcnt=0, rgb=False, bgremove=False):
'''
Locate image position with cv2.templateFind
Use pixel match to find pictures.
Args:
im_source(string): 图像、素材
im_search(string): 需要查找的图片
threshold: 阈值,当相识度小于该阈值的时候,就忽略掉
Retu... | Locate image position with cv2.templateFind
Use pixel match to find pictures.
Args:
im_source(string): 图像、素材
im_search(string): 需要查找的图片
threshold: 阈值,当相识度小于该阈值的时候,就忽略掉
Returns:
A tuple of found [(point, score), ...]
Raises:
IOError: when file read error |
def get_internal_header(request: HttpRequest) -> str:
"""
Return request's 'X_POLYAXON_INTERNAL:' header, as a bytestring.
"""
return get_header(request=request, header_service=conf.get('HEADERS_INTERNAL')) | Return request's 'X_POLYAXON_INTERNAL:' header, as a bytestring. |
def set_empty_symbol(self):
"""Resets the context, retaining the fields that make it a child of its container (``container``, ``queue``,
``depth``, ``whence``), and sets an empty ``pending_symbol``.
This is useful when an empty quoted symbol immediately follows a long string.
"""
... | Resets the context, retaining the fields that make it a child of its container (``container``, ``queue``,
``depth``, ``whence``), and sets an empty ``pending_symbol``.
This is useful when an empty quoted symbol immediately follows a long string. |
def run(graph, save_on_github=False, main_entity=None):
"""
2016-11-30
"""
try:
ontology = graph.all_ontologies[0]
uri = ontology.uri
except:
ontology = None
uri = ";".join([s for s in graph.sources])
# ontotemplate = open("template.html", "r")
ontotemplate ... | 2016-11-30 |
def user_getfield(self, field, access_token=None):
"""
Request a single field of information about the user.
:param field: The name of the field requested.
:type field: str
:returns: The value of the field. Depending on the type, this may be
a string, list, dict, or ... | Request a single field of information about the user.
:param field: The name of the field requested.
:type field: str
:returns: The value of the field. Depending on the type, this may be
a string, list, dict, or something else.
:rtype: object
.. versionadded:: 1.0 |
def threader(group=None, name=None, daemon=True):
""" decorator to thread functions
:param group: reserved for future extension when a ThreadGroup class is implemented
:param name: thread name
:param daemon: thread behavior
:rtype: decorator
"""
def decorator(job):
"""
:param... | decorator to thread functions
:param group: reserved for future extension when a ThreadGroup class is implemented
:param name: thread name
:param daemon: thread behavior
:rtype: decorator |
def get(self, *keys, fallback=None):
"""Retrieve a value in the config, if the value is not available
give the fallback value specified.
"""
section, *keys = keys
out = super().get(section, fallback)
while isinstance(out, dict):
key = keys.pop(0)
... | Retrieve a value in the config, if the value is not available
give the fallback value specified. |
def g_square_bin(dm, x, y, s):
"""G square test for a binary data.
Args:
dm: the data matrix to be used (as a numpy.ndarray).
x: the first node (as an integer).
y: the second node (as an integer).
s: the set of neibouring nodes of x and y (as a set()).
Returns:
p_va... | G square test for a binary data.
Args:
dm: the data matrix to be used (as a numpy.ndarray).
x: the first node (as an integer).
y: the second node (as an integer).
s: the set of neibouring nodes of x and y (as a set()).
Returns:
p_val: the p-value of conditional independ... |
def to_numpy(self, dtype=None, copy=False):
"""Convert the DataFrame to a NumPy array.
Args:
dtype: The dtype to pass to numpy.asarray()
copy: Whether to ensure that the returned value is a not a view on another
array.
Returns:
A num... | Convert the DataFrame to a NumPy array.
Args:
dtype: The dtype to pass to numpy.asarray()
copy: Whether to ensure that the returned value is a not a view on another
array.
Returns:
A numpy array. |
def _init_record(self, record_type_idstr):
"""Override this from osid.Extensible because Forms use a different
attribute in record_type_data."""
record_type_data = self._record_type_data_sets[Id(record_type_idstr).get_identifier()]
module = importlib.import_module(record_type_data['modul... | Override this from osid.Extensible because Forms use a different
attribute in record_type_data. |
def put(self, destination):
""" Copy the referenced directory to this path
The semantics of this command are similar to unix ``cp``: if ``destination`` already
exists, the copied directory will be put at ``[destination] // [basename(localpath)]``. If
it does not already exist, the dire... | Copy the referenced directory to this path
The semantics of this command are similar to unix ``cp``: if ``destination`` already
exists, the copied directory will be put at ``[destination] // [basename(localpath)]``. If
it does not already exist, the directory will be renamed to this path (the ... |
def __learn_oneself(self):
"""calculate cardinality, total and average string length"""
if not self.__parent_path or not self.__text_nodes:
raise Exception("This error occurred because the step constructor\
had insufficient textnodes or it had empty string\
... | calculate cardinality, total and average string length |
def __pop_frames_above(self, frame):
"""Pops all the frames above, but not including the given frame."""
while self.__stack[-1] is not frame:
self.__pop_top_frame()
assert self.__stack | Pops all the frames above, but not including the given frame. |
def netconf_state_datastores_datastore_locks_lock_type_global_lock_global_lock_locked_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
netconf_state = ET.SubElement(config, "netconf-state", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring")
... | Auto Generated Code |
def library_line(self, file_name):
"""
Specifies GULP library file to read species and potential parameters.
If using library don't specify species and potential
in the input file and vice versa. Make sure the elements of
structure are in the library file.
Args:
... | Specifies GULP library file to read species and potential parameters.
If using library don't specify species and potential
in the input file and vice versa. Make sure the elements of
structure are in the library file.
Args:
file_name: Name of GULP library file
Retur... |
def sortTitles(self, by):
"""
Sort titles by a given attribute and then by title.
@param by: A C{str}, one of 'length', 'maxScore', 'medianScore',
'readCount', or 'title'.
@raise ValueError: If an unknown C{by} value is given.
@return: A sorted C{list} of titles.
... | Sort titles by a given attribute and then by title.
@param by: A C{str}, one of 'length', 'maxScore', 'medianScore',
'readCount', or 'title'.
@raise ValueError: If an unknown C{by} value is given.
@return: A sorted C{list} of titles. |
def GetValueByPath(self, path_segments):
"""Retrieves a plist value by path.
Args:
path_segments (list[str]): path segment strings relative to the root
of the plist.
Returns:
object: The value of the key specified by the path or None.
"""
key = self.root_key
for path_segm... | Retrieves a plist value by path.
Args:
path_segments (list[str]): path segment strings relative to the root
of the plist.
Returns:
object: The value of the key specified by the path or None. |
def shift(self,
periods: int,
axis: libinternals.BlockPlacement = 0,
fill_value: Any = None) -> List['ExtensionBlock']:
"""
Shift the block by `periods`.
Dispatches to underlying ExtensionArray and re-boxes in an
ExtensionBlock.
"""
... | Shift the block by `periods`.
Dispatches to underlying ExtensionArray and re-boxes in an
ExtensionBlock. |
def get_config():
"""Create, populate and return the VersioneerConfig() object."""
# these strings are filled in when 'setup.py versioneer' creates
# _version.py
cfg = VersioneerConfig()
cfg.VCS = "git"
cfg.style = "pep440-post"
cfg.tag_prefix = ""
cfg.parentdir_prefix = "None"
cfg.v... | Create, populate and return the VersioneerConfig() object. |
def get_Note(self, string=0, fret=0, maxfret=24):
"""Return the Note on 'string', 'fret'.
Throw a RangeError if either the fret or string is unplayable.
Examples:
>>> t = tunings.StringTuning('test', 'test', ['A-3', 'A-4'])
>>> t,get_Note(0, 0)
'A-3'
>>> t.get_N... | Return the Note on 'string', 'fret'.
Throw a RangeError if either the fret or string is unplayable.
Examples:
>>> t = tunings.StringTuning('test', 'test', ['A-3', 'A-4'])
>>> t,get_Note(0, 0)
'A-3'
>>> t.get_Note(0, 1)
'A#-3'
>>> t.get_Note(1, 0)
... |
def filter_pyfqn(cls, value, relative_to=0):
"""
Returns Python form of fully qualified name.
Args:
relative_to: If greater 0, the returned path is relative to the first n directories.
"""
def collect_packages(element, packages):
parent = element.eContai... | Returns Python form of fully qualified name.
Args:
relative_to: If greater 0, the returned path is relative to the first n directories. |
def _interval(dates):
"""Return the distance between all dates and 0 if they are different"""
interval = (dates[1] - dates[0]).days
last = dates[0]
for dat in dates[1:]:
if (dat - last).days != interval:
return 0
last = dat
return interval | Return the distance between all dates and 0 if they are different |
def get_complete_ph_dos(partial_dos_path, phonopy_yaml_path):
"""
Creates a pymatgen CompletePhononDos from a partial_dos.dat and
phonopy.yaml files.
The second is produced when generating a Dos and is needed to extract
the structure.
Args:
partial_dos_path: path to the partial_dos.dat ... | Creates a pymatgen CompletePhononDos from a partial_dos.dat and
phonopy.yaml files.
The second is produced when generating a Dos and is needed to extract
the structure.
Args:
partial_dos_path: path to the partial_dos.dat file.
phonopy_yaml_path: path to the phonopy.yaml file. |
def boolean(flag):
"""
Convert string in boolean
"""
s = flag.lower()
if s in ('1', 'yes', 'true'):
return True
elif s in ('0', 'no', 'false'):
return False
raise ValueError('Unknown flag %r' % s) | Convert string in boolean |
def CreateUser(self, database_link, user, options=None):
"""Creates a user.
:param str database_link:
The link to the database.
:param dict user:
The Azure Cosmos user to create.
:param dict options:
The request options for the request.
:retu... | Creates a user.
:param str database_link:
The link to the database.
:param dict user:
The Azure Cosmos user to create.
:param dict options:
The request options for the request.
:return:
The created User.
:rtype:
dict |
def __updateStack(self, key):
"""
Update the input stack in non-hotkey mode, and determine if anything
further is needed.
@return: True if further action is needed
"""
#if self.lastMenu is not None:
# if not ConfigManager.SETTINGS[MENU_TAKES_FOCUS]:
# ... | Update the input stack in non-hotkey mode, and determine if anything
further is needed.
@return: True if further action is needed |
def _parse_message(self, data):
"""
Parses the raw message from the device.
:param data: message data to parse
:type data: string
:raises: :py:class:`~alarmdecoder.util.InvalidMessageError`
"""
try:
_, values = data.split(':')
values = va... | Parses the raw message from the device.
:param data: message data to parse
:type data: string
:raises: :py:class:`~alarmdecoder.util.InvalidMessageError` |
def get_subset(self, subset_ids):
"""
Returns a smaller dataset identified by their keys/sample IDs.
Parameters
----------
subset_ids : list
List od sample IDs to extracted from the dataset.
Returns
-------
sub-dataset : MLDataset
... | Returns a smaller dataset identified by their keys/sample IDs.
Parameters
----------
subset_ids : list
List od sample IDs to extracted from the dataset.
Returns
-------
sub-dataset : MLDataset
sub-dataset containing only requested sample IDs. |
def _expectation(p, kern1, feat1, kern2, feat2, nghp=None):
"""
Compute the expectation:
expectation[n] = <Ka_{Z1, x_n} Kb_{x_n, Z2}>_p(x_n)
- Ka_{.,.}, Kb_{.,.} :: RBF kernels
Ka and Kb as well as Z1 and Z2 can differ from each other.
:return: N x dim(Z1) x dim(Z2)
"""
if kern1.on... | Compute the expectation:
expectation[n] = <Ka_{Z1, x_n} Kb_{x_n, Z2}>_p(x_n)
- Ka_{.,.}, Kb_{.,.} :: RBF kernels
Ka and Kb as well as Z1 and Z2 can differ from each other.
:return: N x dim(Z1) x dim(Z2) |
def stopPoll(self, msg_identifier,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#stoppoll
:param msg_identifier:
a 2-tuple (``chat_id``, ``message_id``),
a 1-tuple (``inline_message_id``),
or simply ``inline_message_id``.
... | See: https://core.telegram.org/bots/api#stoppoll
:param msg_identifier:
a 2-tuple (``chat_id``, ``message_id``),
a 1-tuple (``inline_message_id``),
or simply ``inline_message_id``.
You may extract this value easily with :meth:`amanobot.message_identifier` |
def _retry_task(provider, job_descriptor, task_id, task_attempt):
"""Retry task_id (numeric id) assigning it task_attempt."""
td_orig = job_descriptor.find_task_descriptor(task_id)
new_task_descriptors = [
job_model.TaskDescriptor({
'task-id': task_id,
'task-attempt': task_attempt
... | Retry task_id (numeric id) assigning it task_attempt. |
def propose_template(self, template_id, from_account):
"""Propose a template.
:param template_id: id of the template, str
:param from_account: Account
:return: bool
"""
tx_hash = self.send_transaction(
'proposeTemplate',
(template_id,),
... | Propose a template.
:param template_id: id of the template, str
:param from_account: Account
:return: bool |
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in... | Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True |
def write_resume_point(self):
"""Keeps a list of the number of iterations that were in a file when a
run was resumed from a checkpoint."""
try:
resume_pts = self.attrs["resume_points"].tolist()
except KeyError:
resume_pts = []
try:
niterations ... | Keeps a list of the number of iterations that were in a file when a
run was resumed from a checkpoint. |
def get_ip_address(domain):
"""
Get IP address for given `domain`. Try to do smart parsing.
Args:
domain (str): Domain or URL.
Returns:
str: IP address.
Raises:
ValueError: If can't parse the domain.
"""
if "://" not in domain:
domain = "http://" + domain
... | Get IP address for given `domain`. Try to do smart parsing.
Args:
domain (str): Domain or URL.
Returns:
str: IP address.
Raises:
ValueError: If can't parse the domain. |
def list_():
'''
List the RAID devices.
CLI Example:
.. code-block:: bash
salt '*' raid.list
'''
ret = {}
for line in (__salt__['cmd.run_stdout']
(['mdadm', '--detail', '--scan'],
python_shell=False).splitlines()):
if ' ' not in lin... | List the RAID devices.
CLI Example:
.. code-block:: bash
salt '*' raid.list |
def run(self, circuit):
"""Run all the passes on a QuantumCircuit
Args:
circuit (QuantumCircuit): circuit to transform via all the registered passes
Returns:
QuantumCircuit: Transformed circuit.
"""
name = circuit.name
dag = circuit_to_dag(circui... | Run all the passes on a QuantumCircuit
Args:
circuit (QuantumCircuit): circuit to transform via all the registered passes
Returns:
QuantumCircuit: Transformed circuit. |
def __query_options(self):
"""Get the query options string to use for this query."""
options = 0
if self.__tailable:
options |= _QUERY_OPTIONS["tailable_cursor"]
if self.__slave_okay or self.__pool._slave_okay:
options |= _QUERY_OPTIONS["slave_okay"]
if no... | Get the query options string to use for this query. |
def _check_method(self, method):
"""Check if self.estimator has 'method'.
Raises
------
AttributeError
"""
estimator = self._postfit_estimator
if not hasattr(estimator, method):
msg = "The wrapped estimator '{}' does not have a '{}' method.".format(
... | Check if self.estimator has 'method'.
Raises
------
AttributeError |
def save(self, data=None, shape=None, dtype=None, returnoffset=False,
photometric=None, planarconfig=None, extrasamples=None, tile=None,
contiguous=True, align=16, truncate=False, compress=0,
rowsperstrip=None, predictor=False, colormap=None,
description=None, datetim... | Write numpy array and tags to TIFF file.
The data shape's last dimensions are assumed to be image depth,
height (length), width, and samples.
If a colormap is provided, the data's dtype must be uint8 or uint16
and the data values are indices into the last dimension of the
colorm... |
def simple_spend_p2sh(all_from_pubkeys, from_privkeys_to_use, to_address, to_satoshis,
change_address=None, min_confirmations=0, api_key=None, coin_symbol='btc'):
'''
Simple method to spend from a p2sh address.
all_from_pubkeys is a list of *all* pubkeys for the address in question.
from_privk... | Simple method to spend from a p2sh address.
all_from_pubkeys is a list of *all* pubkeys for the address in question.
from_privkeys_to_use is a list of all privkeys that will be used to sign the tx (and no more).
If the address is a 2-of-3 multisig and you supply 1 (or 3) from_privkeys_to_use this will bre... |
def get_phi_comps_from_recfile(recfile):
"""read the phi components from a record file by iteration
Parameters
----------
recfile : str
pest record file name
Returns
-------
iters : dict
nested dictionary of iteration number, {group,contribution}
"""
iiter = 1
... | read the phi components from a record file by iteration
Parameters
----------
recfile : str
pest record file name
Returns
-------
iters : dict
nested dictionary of iteration number, {group,contribution} |
def _init_sub_groups(self, parent):
"""
Initialise sub-groups, and create any that do not already exist.
"""
if self._sub_groups:
for sub_group in self._sub_groups:
for component in split_path_components(sub_group):
fp = os.path.join(paren... | Initialise sub-groups, and create any that do not already exist. |
def orbit(self, x1_px, y1_px, x2_px, y2_px):
"""
Causes the camera to "orbit" around the target point.
This is also called "tumbling" in some software packages.
"""
px_per_deg = self.vport_radius_px / float(self.orbit_speed)
radians_per_px = 1.0 / px_per_deg * np.pi / 180... | Causes the camera to "orbit" around the target point.
This is also called "tumbling" in some software packages. |
def count_residues(self, record, pdb_record):
'''Count the number of residues in the chains for the case.'''
mutations = self.get_record_mutations(record)
pdb_chains = set([m['Chain'] for m in mutations])
assert(len(pdb_chains) == 1) # we expect monomeric cases
pdb_chain = pdb_ch... | Count the number of residues in the chains for the case. |
def temp_water(self):
"""Use water to mask tirs and find 82.5 pctile
Equation 7 and 8 (Zhu and Woodcock, 2012)
Parameters
----------
is_water: ndarray, boolean
water mask, water is True, land is False
swir2: ndarray
tirs1: ndarray
Output
... | Use water to mask tirs and find 82.5 pctile
Equation 7 and 8 (Zhu and Woodcock, 2012)
Parameters
----------
is_water: ndarray, boolean
water mask, water is True, land is False
swir2: ndarray
tirs1: ndarray
Output
------
float:
... |
def _keynat(string):
"""A natural sort helper function for sort() and sorted()
without using regular expression.
"""
r = []
for c in string:
if c.isdigit():
if r and isinstance(r[-1], int):
r[-1] = r[-1] * 10 + int(c)
else:
r.append(int... | A natural sort helper function for sort() and sorted()
without using regular expression. |
def delete(self, ids):
"""
Method to delete ipv4's by their ids
:param ids: Identifiers of ipv4's
:return: None
"""
url = build_uri_with_ids('api/v3/ipv4/%s/', ids)
return super(ApiIPv4, self).delete(url) | Method to delete ipv4's by their ids
:param ids: Identifiers of ipv4's
:return: None |
def cli(yamlfile, directory, out, classname, format):
""" Generate graphviz representations of the biolink model """
DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out) | Generate graphviz representations of the biolink model |
def MotionBlur(k=5, angle=(0, 360), direction=(-1.0, 1.0), order=1, name=None, deterministic=False, random_state=None):
"""
Augmenter that sharpens images and overlays the result with the original image.
dtype support::
See ``imgaug.augmenters.convolutional.Convolve``.
Parameters
--------... | Augmenter that sharpens images and overlays the result with the original image.
dtype support::
See ``imgaug.augmenters.convolutional.Convolve``.
Parameters
----------
k : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
Kernel size to use.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.