code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_traffic(self, subreddit):
"""Return the json dictionary containing traffic stats for a subreddit.
:param subreddit: The subreddit whose /about/traffic page we will
collect.
"""
url = self.config['subreddit_traffic'].format(
subreddit=six.text_type(subred... | Return the json dictionary containing traffic stats for a subreddit.
:param subreddit: The subreddit whose /about/traffic page we will
collect. |
def ResolveForRead(self, partition_key):
"""Resolves the collection for reading/querying the documents based on the partition key.
:param dict document:
The document to be read/queried.
:return:
Collection Self link(s) or Name based link(s) which should handle the Read ... | Resolves the collection for reading/querying the documents based on the partition key.
:param dict document:
The document to be read/queried.
:return:
Collection Self link(s) or Name based link(s) which should handle the Read operation.
:rtype:
list |
def _render(roster_file, **kwargs):
"""
Render the roster file
"""
renderers = salt.loader.render(__opts__, {})
domain = __opts__.get('roster_domain', '')
try:
result = salt.template.compile_template(roster_file,
renderers,
... | Render the roster file |
def package_releases(self, project_name):
""" Retrieve the versions from PyPI by ``project_name``.
Args:
project_name (str): The name of the project we wish to retrieve
the versions of.
Returns:
list: Of string versions.
"""
try:
... | Retrieve the versions from PyPI by ``project_name``.
Args:
project_name (str): The name of the project we wish to retrieve
the versions of.
Returns:
list: Of string versions. |
def _get_embed(self, embed, vocab_size, embed_size, initializer, dropout, prefix):
""" Construct an embedding block. """
if embed is None:
assert embed_size is not None, '"embed_size" cannot be None if "word_embed" or ' \
'token_type_embed is not gi... | Construct an embedding block. |
def _send(self, message):
"""
Given a message, directly invoke the lamdba function for this task.
"""
message['command'] = 'zappa.asynchronous.route_lambda_task'
payload = json.dumps(message).encode('utf-8')
if len(payload) > LAMBDA_ASYNC_PAYLOAD_LIMIT: # pragma: no cover... | Given a message, directly invoke the lamdba function for this task. |
def get_hotp(
secret,
intervals_no,
as_string=False,
casefold=True,
digest_method=hashlib.sha1,
token_length=6,
):
"""
Get HMAC-based one-time password on the basis of given secret and
interval number.
:param secret: the base32-encoded string acting as se... | Get HMAC-based one-time password on the basis of given secret and
interval number.
:param secret: the base32-encoded string acting as secret key
:type secret: str or unicode
:param intervals_no: interval number used for getting different tokens, it
is incremented with each use
:type interva... |
def threshold_monitor_hidden_threshold_monitor_Memory_actions(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshold_m... | Auto Generated Code |
def setLinkState(self, tlsID, tlsLinkIndex, state):
"""setLinkState(string, string, int, string) -> None
Sets the state for the given tls and link index. The state must be one
of rRgGyYoOu for red, red-yellow, green, yellow, off, where lower case letters mean that the stream has to decelerate.
... | setLinkState(string, string, int, string) -> None
Sets the state for the given tls and link index. The state must be one
of rRgGyYoOu for red, red-yellow, green, yellow, off, where lower case letters mean that the stream has to decelerate.
The link index is shown the gui when setting the appropr... |
def getClientIP(request):
"""Returns the best IP address found from the request"""
forwardedfor = request.META.get('HTTP_X_FORWARDED_FOR')
if forwardedfor:
ip = forwardedfor.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip | Returns the best IP address found from the request |
def list(self, path, timeout=None):
"""List directory contents on the device.
Args:
path: List the contents of this directory.
timeout: Timeout to use for this operation.
Returns:
Generator yielding DeviceFileStat tuples representing the contents of
the requested path.
"""
tr... | List directory contents on the device.
Args:
path: List the contents of this directory.
timeout: Timeout to use for this operation.
Returns:
Generator yielding DeviceFileStat tuples representing the contents of
the requested path. |
def register_remove_user_command(self, remove_user_func):
"""
Add the remove-user command to the parser and call remove_user_func(project_name, user_full_name) when chosen.
:param remove_user_func: func Called when this option is chosen: remove_user_func(project_name, user_full_name).
""... | Add the remove-user command to the parser and call remove_user_func(project_name, user_full_name) when chosen.
:param remove_user_func: func Called when this option is chosen: remove_user_func(project_name, user_full_name). |
def _translate(self, from_str, to_str):
"""
Returns string with set of 'from' characters replaced
by set of 'to' characters.
from_str[x] is replaced by to_str[x].
To avoid unexpected behavior, from_str should be
shorter than to_string.
Parameters
----------
from_str : string
to_... | Returns string with set of 'from' characters replaced
by set of 'to' characters.
from_str[x] is replaced by to_str[x].
To avoid unexpected behavior, from_str should be
shorter than to_string.
Parameters
----------
from_str : string
to_str : string
Examples
--------
>>> impo... |
def files_view(request):
"""The main filecenter view."""
hosts = Host.objects.visible_to_user(request.user)
context = {"hosts": hosts}
return render(request, "files/home.html", context) | The main filecenter view. |
def ball_count(cls, ball_tally, strike_tally, pitch_res):
"""
Ball/Strike counter
:param ball_tally: Ball telly
:param strike_tally: Strike telly
:param pitch_res: pitching result(Retrosheet format)
:return: ball count, strike count
"""
b, s = ball_tally, ... | Ball/Strike counter
:param ball_tally: Ball telly
:param strike_tally: Strike telly
:param pitch_res: pitching result(Retrosheet format)
:return: ball count, strike count |
def delete_user_from_group(self, GroupID, UserID):
"""Delete a user from a group."""
# http://teampasswordmanager.com/docs/api-groups/#del_user
log.info('Delete user %s from group %s' % (UserID, GroupID))
self.put('groups/%s/delete_user/%s.json' % (GroupID, UserID)) | Delete a user from a group. |
def scaled_dot_product_attention_simple(q, k, v, bias, name=None):
"""Scaled dot-product attention. One head. One spatial dimension.
Args:
q: a Tensor with shape [batch, length_q, depth_k]
k: a Tensor with shape [batch, length_kv, depth_k]
v: a Tensor with shape [batch, length_kv, depth_v]
bias: op... | Scaled dot-product attention. One head. One spatial dimension.
Args:
q: a Tensor with shape [batch, length_q, depth_k]
k: a Tensor with shape [batch, length_kv, depth_k]
v: a Tensor with shape [batch, length_kv, depth_v]
bias: optional Tensor broadcastable to [batch, length_q, length_kv]
name: an... |
def configured_logger(self, name=None):
"""Configured logger.
"""
log_handlers = self.log_handlers
# logname
if not name:
# base name is always pulsar
basename = 'pulsar'
# the namespace name for this config
name = self.name
... | Configured logger. |
def check( state_engine, nameop, block_id, checked_ops ):
"""
Given a NAME_IMPORT nameop, see if we can import it.
* the name must be well-formed
* the namespace must be revealed, but not ready
* the name cannot have been imported yet
* the sender must be the same as the namespace's sender
... | Given a NAME_IMPORT nameop, see if we can import it.
* the name must be well-formed
* the namespace must be revealed, but not ready
* the name cannot have been imported yet
* the sender must be the same as the namespace's sender
Set the __preorder__ and __prior_history__ fields, since this
is a... |
def clear(self):
"""
Clear the lock, allowing it to be acquired. Do not use this
method except to recover from a deadlock. Otherwise you should
use :py:meth:`Lock.release`.
"""
self.database.delete(self.key)
self.database.delete(self.event) | Clear the lock, allowing it to be acquired. Do not use this
method except to recover from a deadlock. Otherwise you should
use :py:meth:`Lock.release`. |
def create_routertype(self, context, routertype):
"""Creates a router type.
Also binds it to the specified hosting device template.
"""
LOG.debug("create_routertype() called. Contents %s", routertype)
rt = routertype['routertype']
with context.session.begin(subtransactio... | Creates a router type.
Also binds it to the specified hosting device template. |
def list_addresses(self, tag_values=None):
'''
a method to list elastic ip addresses associated with account on AWS
:param tag_values: [optional] list of tag values
:return: list of strings with ip addresses
'''
title = '%s.list_addresse... | a method to list elastic ip addresses associated with account on AWS
:param tag_values: [optional] list of tag values
:return: list of strings with ip addresses |
def horizon_main_nav(context):
"""Generates top-level dashboard navigation entries."""
if 'request' not in context:
return {}
current_dashboard = context['request'].horizon.get('dashboard', None)
dashboards = []
for dash in Horizon.get_dashboards():
if dash.can_access(context):
... | Generates top-level dashboard navigation entries. |
def parse_pr_numbers(git_log_lines):
"""
Parse PR numbers from commit messages. At GitHub those have the format:
`here is the message (#1234)`
being `1234` the PR number.
"""
prs = []
for line in git_log_lines:
pr_number = parse_pr_number(line)
if pr_number:
... | Parse PR numbers from commit messages. At GitHub those have the format:
`here is the message (#1234)`
being `1234` the PR number. |
def plot_lognormal_cdf(self,**kwargs):
"""
Plot the fitted lognormal distribution
"""
if not hasattr(self,'lognormal_dist'):
return
x=np.sort(self.data)
n=len(x)
xcdf = np.arange(n,0,-1,dtype='float')/float(n)
lcdf = self.lognormal_dist.sf(x)
... | Plot the fitted lognormal distribution |
def fit(self, sequences, y=None):
"""Fit a PCCA lumping model using a sequence of cluster assignments.
Parameters
----------
sequences : list(np.ndarray(dtype='int'))
List of arrays of cluster assignments
y : None
Unused, present for sklearn compatibility... | Fit a PCCA lumping model using a sequence of cluster assignments.
Parameters
----------
sequences : list(np.ndarray(dtype='int'))
List of arrays of cluster assignments
y : None
Unused, present for sklearn compatibility only.
Returns
-------
... |
def info(device):
'''
Get BTRFS filesystem information.
CLI Example:
.. code-block:: bash
salt '*' btrfs.info /dev/sda1
'''
out = __salt__['cmd.run_all']("btrfs filesystem show {0}".format(device))
salt.utils.fsutils._verify_run(out)
return _parse_btrfs_info(out['stdout']) | Get BTRFS filesystem information.
CLI Example:
.. code-block:: bash
salt '*' btrfs.info /dev/sda1 |
def _harvest_validate(self, userkwargs):
"""Validate and Plant user provided arguments
- Go through and plants the seedlings
for any user arguments provided.
- Validate the arguments, cleaning and adapting (valideer wise)
- Extract negatives "!" arguments
"""
# ... | Validate and Plant user provided arguments
- Go through and plants the seedlings
for any user arguments provided.
- Validate the arguments, cleaning and adapting (valideer wise)
- Extract negatives "!" arguments |
def lru_cache(fn):
'''
Memoization wrapper that can handle function attributes, mutable arguments,
and can be applied either as a decorator or at runtime.
:param fn: Function
:type fn: function
:returns: Memoized function
:rtype: function
'''
@wraps(fn)
def memoized_fn(*args):
... | Memoization wrapper that can handle function attributes, mutable arguments,
and can be applied either as a decorator or at runtime.
:param fn: Function
:type fn: function
:returns: Memoized function
:rtype: function |
def stop_reactor_on_state_machine_finish(state_machine):
""" Wait for a state machine to be finished and stops the reactor
:param state_machine: the state machine to synchronize with
"""
wait_for_state_machine_finished(state_machine)
from twisted.internet import reactor
if reactor.running:
... | Wait for a state machine to be finished and stops the reactor
:param state_machine: the state machine to synchronize with |
def format_help_text(self, ctx, formatter):
"""Writes the help text to the formatter if it exists."""
if self.help:
formatter.write_paragraph()
with formatter.indentation():
formatter.write_text(self.help) | Writes the help text to the formatter if it exists. |
def worker(self):
"""
Returns the worker associated with this tree widget.
:return <projexui.xorblookupworker.XOrbLookupWorker>
"""
if self._worker is None:
self._worker = XOrbLookupWorker(self.isThreadEnabled())
# create... | Returns the worker associated with this tree widget.
:return <projexui.xorblookupworker.XOrbLookupWorker> |
def build(self, get_grad_fn, get_opt_fn):
"""
Args:
get_grad_fn (-> [(grad, var)]):
get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer
Returns:
(tf.Operation, tf.Operation, tf.Operation):
1. the training op.
2. t... | Args:
get_grad_fn (-> [(grad, var)]):
get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer
Returns:
(tf.Operation, tf.Operation, tf.Operation):
1. the training op.
2. the op which sync all the local variables from PS.
... |
def _evaluate(self,R,z,phi=0.,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,z
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
Phi(R,z)
... | NAME:
_evaluate
PURPOSE:
evaluate the potential at R,z
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
Phi(R,z)
HISTORY:
2013-09-08 - Written - Bovy (IA... |
def sample(model, n, method="optgp", thinning=100, processes=1, seed=None):
"""Sample valid flux distributions from a cobra model.
The function samples valid flux distributions from a cobra model.
Currently we support two methods:
1. 'optgp' (default) which uses the OptGPSampler that supports parallel... | Sample valid flux distributions from a cobra model.
The function samples valid flux distributions from a cobra model.
Currently we support two methods:
1. 'optgp' (default) which uses the OptGPSampler that supports parallel
sampling [1]_. Requires large numbers of samples to be performant
... |
def to_ascii_bytes(self, filter_func=None):
""" Attempt to encode the headers block as ascii
If encoding fails, call percent_encode_non_ascii_headers()
to encode any headers per RFCs
"""
try:
string = self.to_str(filter_func)
string = string.encode... | Attempt to encode the headers block as ascii
If encoding fails, call percent_encode_non_ascii_headers()
to encode any headers per RFCs |
def _parse_response_types(argspec, attrs):
"""
from the given parameters, return back the response type dictionaries.
"""
return_type = argspec.annotations.get("return") or None
type_description = attrs.parameter_descriptions.get("return", "")
response_types = attrs.respo... | from the given parameters, return back the response type dictionaries. |
def _SetYaraRules(self, yara_rules_string):
"""Sets the Yara rules.
Args:
yara_rules_string (str): unparsed Yara rule definitions.
"""
if not yara_rules_string:
return
analyzer_object = analyzers_manager.AnalyzersManager.GetAnalyzerInstance(
'yara')
analyzer_object.SetRules... | Sets the Yara rules.
Args:
yara_rules_string (str): unparsed Yara rule definitions. |
def do_reference(self, parent=None, ident=0):
"""
Handles a TC_REFERENCE opcode
:param parent:
:param ident: Log indentation level
:return: The referenced object
"""
(handle,) = self._readStruct(">L")
log_debug("## Reference handle: 0x{0:X}".format(handle... | Handles a TC_REFERENCE opcode
:param parent:
:param ident: Log indentation level
:return: The referenced object |
def summarize(self):
"""Summarize game."""
if not self._achievements_summarized:
for _ in self.operations():
pass
self._summarize()
return self._summary | Summarize game. |
def _parse_complement(self, tokens):
""" Parses a complement
Complement ::= 'complement' '(' SuperRange ')'
"""
tokens.pop(0) # Pop 'complement'
tokens.pop(0) # Pop '('
res = self._parse_nested_interval(tokens)
tokens.pop(0) # Pop ')'
res.switch_strand... | Parses a complement
Complement ::= 'complement' '(' SuperRange ')' |
def show_hbonds(self):
"""Visualizes hydrogen bonds."""
grp = self.getPseudoBondGroup("Hydrogen Bonds-%i" % self.tid, associateWith=[self.model])
grp.lineWidth = 3
for i in self.plcomplex.hbonds.ldon_id:
b = grp.newPseudoBond(self.atoms[i[0]], self.atoms[i[1]])
b.... | Visualizes hydrogen bonds. |
def resolve_indirect (data, key, splithosts=False):
"""Replace name of environment variable with its value."""
value = data[key]
env_value = os.environ.get(value)
if env_value:
if splithosts:
data[key] = split_hosts(env_value)
else:
data[key] = env_value
else:... | Replace name of environment variable with its value. |
def build_spec(user, repo, sha=None, prov=None, extraMetadata=[]):
"""Build grlc specification for the given github user / repo."""
loader = grlc.utils.getLoader(user, repo, sha=sha, prov=prov)
files = loader.fetchFiles()
raw_repo_uri = loader.getRawRepoUri()
# Fetch all .rq files
items = []
... | Build grlc specification for the given github user / repo. |
def process(
self, request, application,
expected_state, label, extra_roles=None):
""" Process the view request at the current state. """
# Get the authentication of the current user
roles = self._get_roles_for_request(request, application)
if extra_roles is not ... | Process the view request at the current state. |
def nextGen(self):
"""
Decide the fate of the cells
"""
self.current_gen += 1
self.change_gen[self.current_gen % 3] = copy.copy(self.grid)
grid_cp = copy.copy(self.grid)
for cell in self.grid:
y, x = cell
y1 = (y - 1) % self.y_grid
... | Decide the fate of the cells |
def compute_Pi_JinsDJ_given_D(self, CDR3_seq, Pi_J_given_D, max_J_align):
"""Compute Pi_JinsDJ conditioned on D.
This function returns the Pi array from the model factors of the J genomic
contributions, P(D,J)*P(delJ|J), and the DJ (N2) insertions,
first_nt_bias_insDJ(n_1)PinsDJ(\e... | Compute Pi_JinsDJ conditioned on D.
This function returns the Pi array from the model factors of the J genomic
contributions, P(D,J)*P(delJ|J), and the DJ (N2) insertions,
first_nt_bias_insDJ(n_1)PinsDJ(\ell_{DJ})\prod_{i=2}^{\ell_{DJ}}Rdj(n_i|n_{i-1})
conditioned on D identity. T... |
def roundrobin(*iterables):
"""roundrobin('ABC', 'D', 'EF') --> A D E B F C"""
raise NotImplementedError('not sure if this implementation is correct')
# http://stackoverflow.com/questions/11125212/interleaving-lists-in-python
#sentinel = object()
#return (x for x in chain(*zip_longest(fillvalue=sent... | roundrobin('ABC', 'D', 'EF') --> A D E B F C |
def isLoggedIn(self):
"""
Sends a request to Facebook to check the login status
:return: True if the client is still logged in
:rtype: bool
"""
# Send a request to the login url, to see if we're directed to the home page
r = self._cleanGet(self.req_url.LOGIN, all... | Sends a request to Facebook to check the login status
:return: True if the client is still logged in
:rtype: bool |
def bytes(num, check_result=False):
"""
Returns num bytes of cryptographically strong pseudo-random
bytes. If checkc_result is True, raises error if PRNG is not
seeded enough
"""
if num <= 0:
raise ValueError("'num' should be > 0")
buf = create_string_buffer(num)
result = libcry... | Returns num bytes of cryptographically strong pseudo-random
bytes. If checkc_result is True, raises error if PRNG is not
seeded enough |
def dispatch(self, request, **kwargs):
'''
Entry point for this class, here we decide basic stuff
'''
# Delete method must happen with POST not with GET
if request.method == 'POST':
# Check if this is a webservice request
self.__authtoken = (bool(getattr(... | Entry point for this class, here we decide basic stuff |
def get_urls(self):
"""
Add a preview URL.
"""
from django.conf.urls import patterns, url
urls = super(RecurrenceRuleAdmin, self).get_urls()
my_urls = patterns(
'',
url(
r'^preview/$',
self.admin_site.admin_view(self... | Add a preview URL. |
def merge_chromosome_dfs(df_tuple):
# type: (Tuple[pd.DataFrame, pd.DataFrame]) -> pd.DataFrame
"""Merges data from the two strands into strand-agnostic counts."""
plus_df, minus_df = df_tuple
index_cols = "Chromosome Bin".split()
count_column = plus_df.columns[0]
if plus_df.empty:
ret... | Merges data from the two strands into strand-agnostic counts. |
def read_params(filename, asheader=False, verbosity=0) -> Dict[str, Union[int, float, bool, str, None]]:
"""Read parameter dictionary from text file.
Assumes that parameters are specified in the format:
par1 = value1
par2 = value2
Comments that start with '#' are allowed.
Parameters
... | Read parameter dictionary from text file.
Assumes that parameters are specified in the format:
par1 = value1
par2 = value2
Comments that start with '#' are allowed.
Parameters
----------
filename : str, Path
Filename of data file.
asheader : bool, optional
Read... |
def expand_variables(template_str, value_map, transformer=None):
"""
Expand a template string like "blah blah $FOO blah" using given value mapping.
"""
if template_str is None:
return None
else:
if transformer is None:
transformer = lambda v: v
try:
# Don't bother iterating items for P... | Expand a template string like "blah blah $FOO blah" using given value mapping. |
def switch_on(self, *args):
"""
Sets the state of the switch to True if on_check() returns True,
given the arguments provided in kwargs.
:param kwargs: variable length dictionary of key-pair arguments
:return: Boolean. Returns True if the operation is successful
"""
... | Sets the state of the switch to True if on_check() returns True,
given the arguments provided in kwargs.
:param kwargs: variable length dictionary of key-pair arguments
:return: Boolean. Returns True if the operation is successful |
def prior_to_xarray(self):
"""Convert prior samples to xarray."""
prior = self.prior
prior_model = self.prior_model
# filter posterior_predictive and log_likelihood
prior_predictive = self.prior_predictive
if prior_predictive is None:
prior_predictive =... | Convert prior samples to xarray. |
def generate_em_constraint_data(mNS_min, mNS_max, delta_mNS, sBH_min, sBH_max, delta_sBH, eos_name, threshold, eta_default):
"""
Wrapper that calls find_em_constraint_data_point over a grid
of points to generate the bh_spin_z x ns_g_mass x eta surface
above which NS-BH binaries yield a remnant disk mass... | Wrapper that calls find_em_constraint_data_point over a grid
of points to generate the bh_spin_z x ns_g_mass x eta surface
above which NS-BH binaries yield a remnant disk mass that
exceeds the threshold required by the user. The user must also
specify the default symmetric mass ratio value to be assign... |
def memory_used(self):
"""To know the allocated memory at function termination.
..versionadded:: 4.1
This property might return None if the function is still running.
This function should help to show memory leaks or ram greedy code.
"""
if self._end_memory:
... | To know the allocated memory at function termination.
..versionadded:: 4.1
This property might return None if the function is still running.
This function should help to show memory leaks or ram greedy code. |
def casperjs_capture(stream, url, method=None, width=None, height=None,
selector=None, data=None, waitfor=None, size=None,
crop=None, render='png', wait=None):
"""
Captures web pages using ``casperjs``
"""
if isinstance(stream, six.string_types):
output ... | Captures web pages using ``casperjs`` |
def _crossmatch_transients_against_catalogues(
self,
transientsMetadataListIndex,
colMaps):
"""run the transients through the crossmatch algorithm in the settings file
**Key Arguments:**
- ``transientsMetadataListIndex`` -- the list of transient metadata... | run the transients through the crossmatch algorithm in the settings file
**Key Arguments:**
- ``transientsMetadataListIndex`` -- the list of transient metadata lifted from the database.
- ``colMaps`` -- dictionary of dictionaries with the name of the database-view (e.g. `tcs_view_agn_m... |
def request(
self,
url,
params=None,
data=None,
headers=None,
timeout=None,
auth=None,
cookiejar=None,
):
"""
Make a request to a url and retrieve the results.
If the headers parameter does not provide an 'User-Agent' key, one ... | Make a request to a url and retrieve the results.
If the headers parameter does not provide an 'User-Agent' key, one will
be added automatically following the convention:
py3status/<version> <per session random uuid>
:param url: url to request eg `http://example.com`
:para... |
def _hex_to_dec(ip, check=True):
"""Hexadecimal to decimal conversion."""
if check and not is_hex(ip):
raise ValueError('_hex_to_dec: invalid IP: "%s"' % ip)
if isinstance(ip, int):
ip = hex(ip)
return int(str(ip), 16) | Hexadecimal to decimal conversion. |
def get_content(self, default=None):
"""
Returns content for this document as HTML string. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Args:
- default: Default value for the content if it is not defined.
:Returns:
Returns content of this... | Returns content for this document as HTML string. Content will be of type 'str' (Python 2)
or 'bytes' (Python 3).
:Args:
- default: Default value for the content if it is not defined.
:Returns:
Returns content of this document. |
def _bcrypt_generate_pair(algorithm, bit_size=None, curve=None):
"""
Generates a public/private key pair using CNG
:param algorithm:
The key algorithm - "rsa", "dsa" or "ec"
:param bit_size:
An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024,
2048, 3072 or ... | Generates a public/private key pair using CNG
:param algorithm:
The key algorithm - "rsa", "dsa" or "ec"
:param bit_size:
An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024,
2048, 3072 or 4096. For "dsa" the value may be 1024, plus 2048 or 3072
if on Window... |
def __read_response(self, nblines=-1):
"""Read a response from the server.
In the usual case, we read lines until we find one that looks
like a response (OK|NO|BYE\s*(.+)?).
If *nblines* > 0, we read excactly nblines before returning.
:param nblines: number of lines to read (d... | Read a response from the server.
In the usual case, we read lines until we find one that looks
like a response (OK|NO|BYE\s*(.+)?).
If *nblines* > 0, we read excactly nblines before returning.
:param nblines: number of lines to read (default : -1)
:rtype: tuple
:return... |
def format_national_number_with_preferred_carrier_code(numobj, fallback_carrier_code):
"""Formats a phone number in national format for dialing using the carrier
as specified in the preferred_domestic_carrier_code field of the
PhoneNumber object passed in. If that is missing, use the
fallback_carrier_co... | Formats a phone number in national format for dialing using the carrier
as specified in the preferred_domestic_carrier_code field of the
PhoneNumber object passed in. If that is missing, use the
fallback_carrier_code passed in instead. If there is no
preferred_domestic_carrier_code, and the fallback_car... |
def iri(uri_string):
"""converts a string to an IRI or returns an IRI if already formated
Args:
uri_string: uri in string format
Returns:
formated uri with <>
"""
uri_string = str(uri_string)
if uri_string[:1] == "?":
return uri_strin... | converts a string to an IRI or returns an IRI if already formated
Args:
uri_string: uri in string format
Returns:
formated uri with <> |
def _deserialize_value(cls, types, value):
"""
:type types: ValueTypes
:type value: int|str|bool|float|bytes|unicode|list|dict
:rtype: int|str|bool|float|bytes|unicode|list|dict|object
"""
if types.main == list and value is not None:
return cls._deserialize_... | :type types: ValueTypes
:type value: int|str|bool|float|bytes|unicode|list|dict
:rtype: int|str|bool|float|bytes|unicode|list|dict|object |
def set_matrix_dimensions(self, bounds, xdensity, ydensity):
"""
Change the dimensions of the matrix into which the pattern
will be drawn. Users of this class should call this method
rather than changing the bounds, xdensity, and ydensity
parameters directly. Subclasses can ove... | Change the dimensions of the matrix into which the pattern
will be drawn. Users of this class should call this method
rather than changing the bounds, xdensity, and ydensity
parameters directly. Subclasses can override this method to
update any internal data structures that may depend ... |
def transform(self, blocks, y=None):
"""
Transform an ordered sequence of blocks into a 2D features matrix with
shape (num blocks, num features).
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for A... | Transform an ordered sequence of blocks into a 2D features matrix with
shape (num blocks, num features).
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for API consistency.
Returns:
`np.ndarray... |
def get_access_token(self, code):
"""Returns Access Token retrieved from the Health Graph API Token
Endpoint following the login to RunKeeper.
to RunKeeper.
@param code: Code returned by Health Graph API at the Authorization or
RunKeeper Login phase.
... | Returns Access Token retrieved from the Health Graph API Token
Endpoint following the login to RunKeeper.
to RunKeeper.
@param code: Code returned by Health Graph API at the Authorization or
RunKeeper Login phase.
@return: Access Token for querying the... |
def walk(self, parent=None):
"""Generator that yields pages in infix order
Args:
parent: hotdoc.core.tree.Page, optional, the page to start
traversal from. If None, defaults to the root of the tree.
Yields:
hotdoc.core.tree.Page: the next page
""... | Generator that yields pages in infix order
Args:
parent: hotdoc.core.tree.Page, optional, the page to start
traversal from. If None, defaults to the root of the tree.
Yields:
hotdoc.core.tree.Page: the next page |
def get_executions(self, **kwargs):
"""
Retrieve the executions related to the current service.
.. versionadded:: 1.13
:param kwargs: (optional) additional search keyword arguments to limit the search even further.
:type kwargs: dict
:return: list of ServiceExecutions a... | Retrieve the executions related to the current service.
.. versionadded:: 1.13
:param kwargs: (optional) additional search keyword arguments to limit the search even further.
:type kwargs: dict
:return: list of ServiceExecutions associated to the current service. |
def classify(self, dataset, missing_value_action='auto'):
"""
Return a classification, for each example in the ``dataset``, using the
trained boosted trees model. The output SFrame contains predictions
as class labels (0 or 1) and probabilities associated with the the example.
P... | Return a classification, for each example in the ``dataset``, using the
trained boosted trees model. The output SFrame contains predictions
as class labels (0 or 1) and probabilities associated with the the example.
Parameters
----------
dataset : SFrame
Dataset of n... |
def run(self):
"""
Plays the audio. This method plays the audio, and shouldn't be called
explicitly, let the constructor do so.
"""
# From now on, it's multi-thread. Let the force be with them.
st = self.stream._stream
for chunk in chunks(self.audio,
size=self.chunk_... | Plays the audio. This method plays the audio, and shouldn't be called
explicitly, let the constructor do so. |
async def auth_crammd5(
self, username: str, password: str, timeout: DefaultNumType = _default
) -> SMTPResponse:
"""
CRAM-MD5 auth uses the password as a shared secret to MD5 the server's
response.
Example::
250 AUTH CRAM-MD5
auth cram-md5
... | CRAM-MD5 auth uses the password as a shared secret to MD5 the server's
response.
Example::
250 AUTH CRAM-MD5
auth cram-md5
334 PDI0NjA5LjEwNDc5MTQwNDZAcG9wbWFpbC5TcGFjZS5OZXQ+
dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw |
def get_tier(self, name_num):
"""Gives a tier, when multiple tiers exist with that name only the
first is returned.
:param name_num: Name or number of the tier to return.
:type name_num: int or str
:returns: The tier.
:raises IndexError: If the tier doesn't exist.
... | Gives a tier, when multiple tiers exist with that name only the
first is returned.
:param name_num: Name or number of the tier to return.
:type name_num: int or str
:returns: The tier.
:raises IndexError: If the tier doesn't exist. |
def train(self, x=None, y=None, training_frame=None, offset_column=None, fold_column=None,
weights_column=None, validation_frame=None, max_runtime_secs=None, ignored_columns=None,
model_id=None, verbose=False):
"""
Train the H2O model.
:param x: A list of column name... | Train the H2O model.
:param x: A list of column names or indices indicating the predictor columns.
:param y: An index or a column name indicating the response column.
:param H2OFrame training_frame: The H2OFrame having the columns indicated by x and y (as well as any
additional colu... |
def get_logger(name):
"""Helper function to get a logger"""
if name in loggers:
return loggers[name]
logger = logging.getLogger(name)
logger.propagate = False
pre1, suf1 = hash_coloured_escapes(name) if supports_color() else ('', '')
pre2, suf2 = hash_coloured_escapes(name + 'salt') \
... | Helper function to get a logger |
def add_country_location(self, country, exact=True, locations=None, use_live=True):
# type: (str, bool, Optional[List[str]], bool) -> bool
"""Add a country. If an iso 3 code is not provided, value is parsed and if it is a valid country name,
converted to an iso 3 code. If the country is already ... | Add a country. If an iso 3 code is not provided, value is parsed and if it is a valid country name,
converted to an iso 3 code. If the country is already added, it is ignored.
Args:
country (str): Country to add
exact (bool): True for exact matching or False to allow fuzzy match... |
def remove_label(self, label, relabel=False):
"""
Remove the label number.
The removed label is assigned a value of zero (i.e.,
background).
Parameters
----------
label : int
The label number to remove.
relabel : bool, optional
I... | Remove the label number.
The removed label is assigned a value of zero (i.e.,
background).
Parameters
----------
label : int
The label number to remove.
relabel : bool, optional
If `True`, then the segmentation image will be relabeled
... |
def reload(self, metadata, ignore_unsupported_plugins=True):
"""
Loads the metadata. They will be used so that it is possible to generate lv2 audio plugins.
:param list metadata: lv2 audio plugins metadata
:param bool ignore_unsupported_plugins: Not allows instantiation of uninstalled o... | Loads the metadata. They will be used so that it is possible to generate lv2 audio plugins.
:param list metadata: lv2 audio plugins metadata
:param bool ignore_unsupported_plugins: Not allows instantiation of uninstalled or unrecognized audio plugins? |
def append_query_parameter(url, parameters, ignore_if_exists=True):
""" quick and dirty appending of query parameters to a url """
if ignore_if_exists:
for key in parameters.keys():
if key + "=" in url:
del parameters[key]
parameters_str = "&".join(k + "=" + v for k, v in... | quick and dirty appending of query parameters to a url |
def remove_this_tlink(self,tlink_id):
"""
Removes the tlink for the given tlink identifier
@type tlink_id: string
@param tlink_id: the tlink identifier to be removed
"""
for tlink in self.get_tlinks():
if tlink.get_id() == tlink_id:
self.node.r... | Removes the tlink for the given tlink identifier
@type tlink_id: string
@param tlink_id: the tlink identifier to be removed |
def _time_threaded_normxcorr(templates, stream, *args, **kwargs):
"""
Use the threaded time-domain routine for concurrency
:type templates: list
:param templates:
A list of templates, where each one should be an obspy.Stream object
containing multiple traces of seismic data and the rele... | Use the threaded time-domain routine for concurrency
:type templates: list
:param templates:
A list of templates, where each one should be an obspy.Stream object
containing multiple traces of seismic data and the relevant header
information.
:type stream: obspy.core.stream.Stream
... |
def more_statements(self, more_url):
"""Query the LRS for more statements
:param more_url: URL from a StatementsResult object used to retrieve more statements
:type more_url: str | unicode
:return: LRS Response object with the returned StatementsResult object as content
:rtype: ... | Query the LRS for more statements
:param more_url: URL from a StatementsResult object used to retrieve more statements
:type more_url: str | unicode
:return: LRS Response object with the returned StatementsResult object as content
:rtype: :class:`tincan.lrs_response.LRSResponse` |
def indexTupleFromItem(self, treeItem): # TODO: move to BaseTreeItem?
""" Return (first column model index, last column model index) tuple for a configTreeItem
"""
if not treeItem:
return (QtCore.QModelIndex(), QtCore.QModelIndex())
if not treeItem.parentItem: # TODO: only n... | Return (first column model index, last column model index) tuple for a configTreeItem |
def get_imported_repo(self, import_path):
"""Looks for a go-import meta tag for the provided import_path.
Returns an ImportedRepo instance with the information in the meta tag,
or None if no go-import meta tag is found.
"""
try:
session = requests.session()
# TODO: Support https with (o... | Looks for a go-import meta tag for the provided import_path.
Returns an ImportedRepo instance with the information in the meta tag,
or None if no go-import meta tag is found. |
def _save_documentation(version, base_url="https://spark.apache.org/docs"):
"""
Write the spark property documentation to a file
"""
target_dir = join(dirname(__file__), 'spylon', 'spark')
with open(join(target_dir, "spark_properties_{}.json".format(version)), 'w') as fp:
all_props = _fetch_... | Write the spark property documentation to a file |
def set_main_wire(self, wire=None):
"""
Sets the specified wire as the link's main wire
This is done automatically during the first wire() call
Keyword Arguments:
- wire (Wire): if None, use the first wire instance found
Returns:
- Wire: the new main ... | Sets the specified wire as the link's main wire
This is done automatically during the first wire() call
Keyword Arguments:
- wire (Wire): if None, use the first wire instance found
Returns:
- Wire: the new main wire instance |
def dicom_read(directory, pixeltype='float'):
"""
Read a set of dicom files in a directory into a single ANTsImage.
The origin of the resulting 3D image will be the origin of the
first dicom image read.
Arguments
---------
directory : string
folder in which all the dicom images exis... | Read a set of dicom files in a directory into a single ANTsImage.
The origin of the resulting 3D image will be the origin of the
first dicom image read.
Arguments
---------
directory : string
folder in which all the dicom images exist
Returns
-------
ANTsImage
Example
... |
def consultar_status_operacional(self):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_status_operacional`.
:return: Uma resposta SAT especializada em ``ConsultarStatusOperacional``.
:rtype: satcfe.resposta.consultarstatusoperacional.RespostaConsultarStatusOperacional
"""
... | Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_status_operacional`.
:return: Uma resposta SAT especializada em ``ConsultarStatusOperacional``.
:rtype: satcfe.resposta.consultarstatusoperacional.RespostaConsultarStatusOperacional |
def imfill(immsk):
'''fill the empty patches of image mask 'immsk' '''
for iz in range(immsk.shape[0]):
for iy in range(immsk.shape[1]):
ix0 = np.argmax(immsk[iz,iy,:]>0)
ix1 = immsk.shape[2] - np.argmax(immsk[iz,iy,::-1]>0)
if (ix1-ix0) > immsk.shape[2]-10: continue... | fill the empty patches of image mask 'immsk' |
def ImportFile(store, filename, start):
"""Import hashes from 'filename' into 'store'."""
with io.open(filename, "r") as fp:
reader = csv.Reader(fp.read())
i = 0
current_row = None
product_code_list = []
op_system_code_list = []
for row in reader:
# Skip first row.
i += 1
i... | Import hashes from 'filename' into 'store'. |
def _printer(self, *out, **kws):
"""Generic print function."""
flush = kws.pop('flush', True)
fileh = kws.pop('file', self.writer)
sep = kws.pop('sep', ' ')
end = kws.pop('sep', '\n')
print(*out, file=fileh, sep=sep, end=end)
if flush:
fileh.flush() | Generic print function. |
def addLOADDEV(rh):
"""
Sets the LOADDEV statement in the virtual machine's directory entry.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'ADDLOADDEV'
userid - userid of the virtual machine
parms['boot'] ... | Sets the LOADDEV statement in the virtual machine's directory entry.
Input:
Request Handle with the following properties:
function - 'CHANGEVM'
subfunction - 'ADDLOADDEV'
userid - userid of the virtual machine
parms['boot'] - Boot program number
... |
def _reset(self, command, *args, **kwargs):
"""
Shortcut for commands that reset values of the field.
All will be deindexed and reindexed.
"""
if self.indexable:
self.deindex()
result = self._traverse_command(command, *args, **kwargs)
if self.indexable... | Shortcut for commands that reset values of the field.
All will be deindexed and reindexed. |
def draw_key(self, surface, key):
"""Default drawing method for key.
Draw the key accordingly to it type.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn.
"""
if isinstance(key, VSpaceKey):
self.draw_space_key(surfa... | Default drawing method for key.
Draw the key accordingly to it type.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn. |
def parse_wait_time(text: str) -> int:
"""Parse the waiting time from the exception"""
val = RATELIMIT.findall(text)
if len(val) > 0:
try:
res = val[0]
if res[1] == 'minutes':
return int(res[0]) * 60
if res[1] == 'seconds':
return ... | Parse the waiting time from the exception |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.