code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def format(obj, options):
"""Return a string representation of the Python object
Args:
obj: The Python object
options: Format options
"""
formatters = {
float_types: lambda x: '{:.{}g}'.format(x, options.digits),
}
for _types, fmtr in formatters.items():
if isins... | Return a string representation of the Python object
Args:
obj: The Python object
options: Format options |
def validate_xml(self) -> None:
"""Raise an error if the actual XML does not agree with one of the
available schema files.
# ToDo: should it be accompanied by a script function?
The first example relies on a distorted version of the configuration
file `single_run.xml`:
... | Raise an error if the actual XML does not agree with one of the
available schema files.
# ToDo: should it be accompanied by a script function?
The first example relies on a distorted version of the configuration
file `single_run.xml`:
>>> from hydpy.core.examples import prepar... |
def _display_sims(self, sims):
"""display computed similarities on stdout"""
nb_lignes_dupliquees = 0
for num, couples in sims:
print()
print(num, "similar lines in", len(couples), "files")
couples = sorted(couples)
for lineset, idx in couples:
... | display computed similarities on stdout |
def _set_log_handler(self, v, load=False):
"""
Setter method for log_handler, mapped from YANG variable /isis_state/router_isis_config/log_handler (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_log_handler is considered as a private
method. Backends look... | Setter method for log_handler, mapped from YANG variable /isis_state/router_isis_config/log_handler (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_log_handler is considered as a private
method. Backends looking to populate this variable should
do so via call... |
def releases(self, **kwargs):
"""
Get the release date and certification information by country for a
specific movie id.
Args:
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the ... | Get the release date and certification information by country for a
specific movie id.
Args:
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API. |
def plot_sn_discovery_ratio_map(log,
snSurveyDiscoveryTimes,
redshifts,
peakAppMagList,
snCampaignLengthList,
extraSurveyConstraints,
... | *Plot the SN discoveries and non-discoveries in a polar plot as function of redshift*
**Key Arguments:**
- ``log`` -- logger
- ``snSurveyDiscoveryTimes`` --
- ``redshifts`` --
- ``peakAppMagList`` -- the list of peakmags for each SN in each filter
- ``snCampaignLengthList`` ... |
def fix_simple_errors(self):
''' This attempts to fix the easy errors raised by ValidationError.
This includes removing items from the cart that are no longer
available, recalculating all of the discounts, and removing voucher
codes that are no longer available. '''
# Fix vouche... | This attempts to fix the easy errors raised by ValidationError.
This includes removing items from the cart that are no longer
available, recalculating all of the discounts, and removing voucher
codes that are no longer available. |
def AddShapefile(shapefile, graph, key_cols):
"""
Adds shapes found in the given shape filename to the given polyline
graph object.
"""
ds = ogr.Open(shapefile)
layer = ds.GetLayer(0)
for i in range(0, len(layer)):
feature = layer.GetFeature(i)
geometry = feature.GetGeometryRef()
if key_col... | Adds shapes found in the given shape filename to the given polyline
graph object. |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'word') and self.word is not None:
_dict['word'] = self.word
if hasattr(self, 'sounds_like') and self.sounds_like is not None:
_dict['sounds_like'] = self.sound... | Return a json dictionary representing this model. |
def DOMSnapshot_getSnapshot(self, computedStyleWhitelist):
"""
Function path: DOMSnapshot.getSnapshot
Domain: DOMSnapshot
Method name: getSnapshot
Parameters:
Required arguments:
'computedStyleWhitelist' (type: array) -> Whitelist of computed styles to return.
Returns:
'domNodes' (type: ... | Function path: DOMSnapshot.getSnapshot
Domain: DOMSnapshot
Method name: getSnapshot
Parameters:
Required arguments:
'computedStyleWhitelist' (type: array) -> Whitelist of computed styles to return.
Returns:
'domNodes' (type: array) -> The nodes in the DOM tree. The DOMNode at index 0 corresp... |
def _cloglog_utility_transform(systematic_utilities,
alt_IDs,
rows_to_alts,
shape_params,
intercept_params,
intercept_ref_pos=None,
*a... | Parameters
----------
systematic_utilities : 1D ndarray.
All elements should be ints, floats, or longs. Should contain the
systematic utilities of each observation per available alternative.
Note that this vector is formed by the dot product of the design matrix
with the vector o... |
def _figure_data(self, plot, fmt='png', bbox_inches='tight', as_script=False, **kwargs):
"""
Render matplotlib figure object and return the corresponding
data. If as_script is True, the content will be split in an
HTML and a JS component.
Similar to IPython.core.pylabtools.prin... | Render matplotlib figure object and return the corresponding
data. If as_script is True, the content will be split in an
HTML and a JS component.
Similar to IPython.core.pylabtools.print_figure but without
any IPython dependency. |
def spectral_pars_from_catalog(cat):
"""Create spectral parameters from 3FGL catalog columns."""
spectrum_type = cat['SpectrumType']
pars = get_function_defaults(cat['SpectrumType'])
par_idxs = {k: i for i, k in
enumerate(get_function_par_names(cat['SpectrumType']))}
for k in pars:... | Create spectral parameters from 3FGL catalog columns. |
def harmonic(word):
'''Return True if the word's vowels agree in frontness/backness.'''
depth = {'ä': 0, 'ö': 0, 'y': 0, 'a': 1, 'o': 1, 'u': 1}
vowels = filter(lambda ch: is_front(ch) or is_back(ch), word)
depths = (depth[x.lower()] for x in vowels)
return len(set(depths)) < 2 | Return True if the word's vowels agree in frontness/backness. |
def _create_latent_variables(self):
""" Creates model latent variables
Returns
----------
None (changes model attributes)
"""
for parm in range(self.z_no):
self.latent_variables.add_z('Scale ' + self.X_names[parm], fam.Flat(transform='exp'), fam.Normal(0, 3)... | Creates model latent variables
Returns
----------
None (changes model attributes) |
def authenticate(self, username, password):
"""
Verifies that a password matches the stored password for that username.
If verification passes, the matching user instance is returned
"""
PraetorianError.require_condition(
self.user_class is not None,
"Prae... | Verifies that a password matches the stored password for that username.
If verification passes, the matching user instance is returned |
def _request(request, request_fallback=None):
''' Extract request fields wherever they may come from: GET, POST, forms, fallback '''
# Use lambdas to avoid evaluating bottle.request.* which may throw an Error
all_dicts = [
lambda: request.json,
lambda: request.forms,
... | Extract request fields wherever they may come from: GET, POST, forms, fallback |
def remove_job_resolver(self, job_resolver):
"""Remove job_resolver from the list of job resolvers.
Keyword arguments:
job_resolver -- Function reference of the job resolver to be removed.
"""
for i, r in enumerate(self.job_resolvers()):
if job_resolver == r:
... | Remove job_resolver from the list of job resolvers.
Keyword arguments:
job_resolver -- Function reference of the job resolver to be removed. |
def validate(config):
'''
Validate the beacon configuration
'''
# Configuration for load beacon should be a list of dicts
if not isinstance(config, list):
return False, ('Configuration for load beacon must be a list.')
else:
_config = {}
list(map(_config.update, config))... | Validate the beacon configuration |
def update(self, delta_seconds):
"""update tweeners. delta_seconds is time in seconds since last frame"""
for obj in tuple(self.current_tweens):
for tween in tuple(self.current_tweens[obj]):
done = tween.update(delta_seconds)
if done:
self... | update tweeners. delta_seconds is time in seconds since last frame |
def _isCompatible(self, other, reporter):
"""
This is the environment implementation of
:meth:`BaseGuideline.isCompatible`.
Subclasses may override this method.
"""
guideline1 = self
guideline2 = other
# guideline names
if guideline1.name != guide... | This is the environment implementation of
:meth:`BaseGuideline.isCompatible`.
Subclasses may override this method. |
def _pad_bytes_new(name, length):
"""
Takes a bytes instance and pads it with null bytes until it's length chars.
"""
if isinstance(name, str):
name = bytes(name, 'utf-8')
return name + b'\x00' * (length - len(name)) | Takes a bytes instance and pads it with null bytes until it's length chars. |
def update_publisher_asset(self, upload_stream, publisher_name, asset_type=None, file_name=None, **kwargs):
"""UpdatePublisherAsset.
[Preview API] Update publisher asset like logo. It accepts asset file as an octet stream and file name is passed in header values.
:param object upload_stream: Str... | UpdatePublisherAsset.
[Preview API] Update publisher asset like logo. It accepts asset file as an octet stream and file name is passed in header values.
:param object upload_stream: Stream to upload
:param str publisher_name: Internal name of the publisher
:param str asset_type: Type of ... |
def prepare(self):
self.body_html = markdown(
codecs.open(self.abspath, 'r').read(),
extras=['fenced-code-blocks', 'hilite', 'tables', 'metadata'])
self.header = self.body_html.metadata
"""a blog post without tags causes an error ..."""
if 'tags' in self.header:... | a blog post without tags causes an error ... |
def get_magnet(self, detailed=True):
"""Returns torrent magnet link, consisting of BTIH (BitTorrent Info Hash) URN
anr optional other information.
:param bool|list|tuple|set detailed:
For boolean - whether additional info (such as trackers) should be included.
For iterab... | Returns torrent magnet link, consisting of BTIH (BitTorrent Info Hash) URN
anr optional other information.
:param bool|list|tuple|set detailed:
For boolean - whether additional info (such as trackers) should be included.
For iterable - expected allowed parameter names:
... |
def post_request(self, url, params):
"""Send a post request.
:return: a dict or raise Exception.
"""
data = encrypted_request(params)
resp = self.session.post(url, data=data, timeout=self.timeout,
proxies=self.proxies)
result = resp.json... | Send a post request.
:return: a dict or raise Exception. |
def select(self, nowait=True, cb=None):
'''
Set this channel to use publisher confirmations.
'''
nowait = nowait and self.allow_nowait() and not cb
if not self._enabled:
self._enabled = True
self.channel.basic._msg_id = 0
self.channel.basic._l... | Set this channel to use publisher confirmations. |
def in_lamp_reach(p):
''' Check if the provided XYPoint can be recreated by a Hue lamp. '''
v1 = XYPoint(Lime.x - Red.x, Lime.y - Red.y)
v2 = XYPoint(Blue.x - Red.x, Blue.y - Red.y)
q = XYPoint(p.x - Red.x, p.y - Red.y)
s = cross_product(q, v2) / cross_product(v1, v2)
t = cross_product(v1, q) /... | Check if the provided XYPoint can be recreated by a Hue lamp. |
def clean():
"take out the trash"
src_dir = easy.options.setdefault("docs", {}).get('src_dir', None)
if src_dir is None:
src_dir = 'src' if easy.path('src').exists() else '.'
with easy.pushd(src_dir):
for pkg in set(easy.options.setup.packages) | set(("tests",)):
for filenam... | take out the trash |
def make_writeable(filename):
"""
Make sure that the file is writeable.
Useful if our source is read-only.
"""
if not os.access(filename, os.W_OK):
st = os.stat(filename)
new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR
os.chmod(filename, new_permissions) | Make sure that the file is writeable.
Useful if our source is read-only. |
def _GetProxies(self):
"""Gather a list of proxies to use."""
# Detect proxies from the OS environment.
result = client_utils.FindProxies()
# Also try to connect directly if all proxies fail.
result.append("")
# Also try all proxies configured in the config system.
result.extend(config.CON... | Gather a list of proxies to use. |
def get(self, q=None, page=None):
"""Get styles."""
# Check cache to exit early if needed
etag = generate_etag(current_ext.content_version.encode('utf8'))
self.check_etag(etag, weak=True)
# Build response
res = jsonify(current_ext.styles)
res.set_etag(etag)
... | Get styles. |
def connect(self):
"""
Parameters
----------
prev_login : xnat.XNATSession
An XNAT login that has been opened in the code that calls
the method that calls login. It is wrapped in a
NoExitWrapper so the returned connection can be used
in a "... | Parameters
----------
prev_login : xnat.XNATSession
An XNAT login that has been opened in the code that calls
the method that calls login. It is wrapped in a
NoExitWrapper so the returned connection can be used
in a "with" statement in the method. |
def cmd_import(*args):
"""
Arguments:
<file_or_folder> [<file_or_folder> [...]]
[-- [--no_ocr] [--no_label_guessing] [--append <document_id>]]
Import a file or a PDF folder. OCR is run by default on images
and on PDF pages without text (PDF containing only images)
Please keep i... | Arguments:
<file_or_folder> [<file_or_folder> [...]]
[-- [--no_ocr] [--no_label_guessing] [--append <document_id>]]
Import a file or a PDF folder. OCR is run by default on images
and on PDF pages without text (PDF containing only images)
Please keep in mind that documents that are alre... |
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not... | Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name |
def move(g, n1, n2, **kwargs):
"""
Step along a graph until it ends or reach an intersection
Example graph:
Note that edge (1, 2) and (2, 3) are bidirectional, i.e., (2, 1) and
(3, 2) are also edges
1 -- 2 -- 3 -->-- 5 -->-- 7
| |
^ v
| ... | Step along a graph until it ends or reach an intersection
Example graph:
Note that edge (1, 2) and (2, 3) are bidirectional, i.e., (2, 1) and
(3, 2) are also edges
1 -- 2 -- 3 -->-- 5 -->-- 7
| |
^ v
| |
4 6
>>> list(... |
def input_fn(self,
mode,
hparams,
data_dir=None,
params=None,
config=None,
force_repeat=False,
prevent_repeat=False,
dataset_kwargs=None):
"""Builds input pipeline for problem.
Args:
mo... | Builds input pipeline for problem.
Args:
mode: tf.estimator.ModeKeys
hparams: HParams, model hparams
data_dir: str, data directory; if None, will use hparams.data_dir
params: dict, may include "batch_size"
config: RunConfig; should have the data_parallelism attribute if not using
... |
def get_xy_simple_dipole_dipole(dataframe, spacing=1, indices=None):
"""For each configuration indicated by the numerical index array, compute
(x,z) pseudo locations based on the paper from XX.
All positions are computed for indices=None.
"""
if indices is None:
indices = slice(None)
ab... | For each configuration indicated by the numerical index array, compute
(x,z) pseudo locations based on the paper from XX.
All positions are computed for indices=None. |
def _handle_sending(self, data):
"""
Handles results of a keypress send.
:param data: Sending string to parse
:type data: string
"""
matches = re.match('^!Sending(\.{1,5})done.*', data)
if matches is not None:
good_send = False
if len(mat... | Handles results of a keypress send.
:param data: Sending string to parse
:type data: string |
def get_user_by_name(self, firstname, lastname):
"""
Get a user by the first and last name of that user.
:param firstname: The first name of the user.
:type firstname: string
:param lastname: The last name of the user.
:type lastname: string
:returns: The user re... | Get a user by the first and last name of that user.
:param firstname: The first name of the user.
:type firstname: string
:param lastname: The last name of the user.
:type lastname: string
:returns: The user requested.
:rtype: dict |
def _pre_call(atdepth, parent, fqdn, stackdepth, *argl, **argd):
"""Checks whether the logging should create an entry based on stackdepth. If
so, the entry is created.
"""
from time import time
if not atdepth:
rstack = _reduced_stack()
if "<module>" in rstack[-1]: # pragma: no cover
... | Checks whether the logging should create an entry based on stackdepth. If
so, the entry is created. |
def Rfindalldirs(self, pathlist):
"""
Return all of the directories for a given path list, including
corresponding "backing" directories in any repositories.
The Node lookups are relative to this Node (typically a
directory), so memoizing result saves cycles from looking
... | Return all of the directories for a given path list, including
corresponding "backing" directories in any repositories.
The Node lookups are relative to this Node (typically a
directory), so memoizing result saves cycles from looking
up the same path for each target in a given directory... |
def request(self, method, path_append=None, headers=None, **kwargs):
"""Create a custom request
:param method: HTTP method to use
:param path_append: (optional) relative to :attr:`api_path`
:param headers: (optional) Dictionary of headers to add or override
:param kwargs: kwargs... | Create a custom request
:param method: HTTP method to use
:param path_append: (optional) relative to :attr:`api_path`
:param headers: (optional) Dictionary of headers to add or override
:param kwargs: kwargs to pass along to :class:`requests.Request`
:return:
- :clas... |
def configure_job():
"""Construct jobSpec for ML Engine job."""
# See documentation:
# https://cloud.google.com/ml-engine/reference/rest/v1/projects.jobs#traininginput
training_input = {
"pythonModule": "tensor2tensor.bin.t2t_trainer",
"args": flags_as_args(),
"region": text_encoder.native_to_... | Construct jobSpec for ML Engine job. |
def LogContrast(gain=1, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Adjust contrast by scaling each pixel value to ``255 * gain * log_2(1 + I_ij/255)``.
dtype support::
See :func:`imgaug.augmenters.contrast.adjust_contrast_log`.
Parameters
----------
gai... | Adjust contrast by scaling each pixel value to ``255 * gain * log_2(1 + I_ij/255)``.
dtype support::
See :func:`imgaug.augmenters.contrast.adjust_contrast_log`.
Parameters
----------
gain : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
... |
def add_config(self, config):
"""
:param config:
:type config: dict
"""
self.pre_configure()
self.config = config
if not self.has_revision_file():
#: Create new revision file.
touch_file(self.revfile_path)
self.history.load(self.... | :param config:
:type config: dict |
def _post_create(self, auto_refresh=False):
'''
resource.create() hook
'''
# set rdf type
self.add_triple(self.rdf.prefixes.rdf.type, self.rdf.prefixes.ore.Proxy)
# set triple for what this resource is a proxy for
if self.proxyForURI:
self.add_triple(self.rdf.prefixes.ore.proxyFor, self.proxyForURI)... | resource.create() hook |
def parse_files(self):
"""
Find the files and parse them.
Returns:
list: list of dictionaries (one for each parsed line).
"""
log_re = self.log_format_regex
log_lines = []
for log_file in self.matching_files():
with open(log_file) as f:
... | Find the files and parse them.
Returns:
list: list of dictionaries (one for each parsed line). |
def timezone(value,
allow_empty = False,
positive = True,
**kwargs):
"""Validate that ``value`` is a valid :class:`tzinfo <python:datetime.tzinfo>`.
.. caution::
This does **not** verify whether the value is a timezone that actually
exists, nor can it resolve... | Validate that ``value`` is a valid :class:`tzinfo <python:datetime.tzinfo>`.
.. caution::
This does **not** verify whether the value is a timezone that actually
exists, nor can it resolve timezone names (e.g. ``'Eastern'`` or ``'CET'``).
For that kind of functionality, we recommend you utilize:... |
def manifest_history(self, synchronous=True, **kwargs):
"""Obtain manifest history for subscriptions.
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's respo... | Obtain manifest history for subscriptions.
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's response otherwise.
:param kwargs: Arguments to pass to requests... |
def from_dict(data, ctx):
"""
Instantiate a new AccountChangesState from a dict (generally from
loading a JSON response). The data used to instantiate the
AccountChangesState is a shallow copy of the dict passed in, with any
complex child types instantiated appropriately.
... | Instantiate a new AccountChangesState from a dict (generally from
loading a JSON response). The data used to instantiate the
AccountChangesState is a shallow copy of the dict passed in, with any
complex child types instantiated appropriately. |
def _containerSetPath(container, folderpath, specfiles):
"""Helper function for :class:`MsrunContainer`, :class:`SiiContainer` and
:class:`FiContainer`. Changes the folderpath of the specified specfiles in
container.info: ``container.info[specfile]['path'] = folderpath``.
:param container: a container ... | Helper function for :class:`MsrunContainer`, :class:`SiiContainer` and
:class:`FiContainer`. Changes the folderpath of the specified specfiles in
container.info: ``container.info[specfile]['path'] = folderpath``.
:param container: a container like class that has an attribute ``.info``
:param folderpath... |
def get_line_configuration_message(self, line_number):
"""Return the cnfLine content without id for the line.
:param int line_number: the number of the line
:rtype: bytes
:return: a cnfLine message without id as defined in :ref:`cnfLine`
"""
if line_number not in self._l... | Return the cnfLine content without id for the line.
:param int line_number: the number of the line
:rtype: bytes
:return: a cnfLine message without id as defined in :ref:`cnfLine` |
def while_stmt(self, while_loc, test, while_colon_loc, body, else_opt):
"""while_stmt: 'while' test ':' suite ['else' ':' suite]"""
stmt = ast.While(test=test, body=body, orelse=[],
keyword_loc=while_loc, while_colon_loc=while_colon_loc,
else_loc=None, e... | while_stmt: 'while' test ':' suite ['else' ':' suite] |
def list_namespaced_custom_object(self, group, version, namespace, plural, **kwargs):
"""
list or watch namespace scoped custom objects
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_... | list or watch namespace scoped custom objects
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_custom_object(group, version, namespace, plural, async_req=True)
>>> result = thread.ge... |
def excision(args):
"""
%prog excision
Illustrate the mechanism of illegitimate recombination.
"""
p = OptionParser(__doc__)
opts, args = p.parse_args(args)
fig = plt.figure(1, (5, 5))
root = fig.add_axes([0, 0, 1, 1])
plt.plot((.2, .8), (.6, .6), 'r-', lw=3)
plt.plot((.4, .6)... | %prog excision
Illustrate the mechanism of illegitimate recombination. |
def extract_relationships(self):
"""extract relation ships between nodes in the diagram
"""
ClassDiagram.extract_relationships(self)
for obj in self.classes():
# ownership
try:
mod = self.object_from_node(obj.node.root())
self.add_r... | extract relation ships between nodes in the diagram |
def _format_arguments(ctx):
"""Format all `click.Argument` for a `click.Command`."""
params = [x for x in ctx.command.params if isinstance(x, click.Argument)]
for param in params:
for line in _format_argument(param):
yield line
yield '' | Format all `click.Argument` for a `click.Command`. |
def load_and_save_image(url, destination):
"""Download image from given url and saves it to destination."""
from urllib2 import Request, urlopen, URLError, HTTPError
# create the url and the request
req = Request(url)
# Open the url
try:
f = urlopen(req)
print "downloading " + u... | Download image from given url and saves it to destination. |
def get_pastml_parameter_file(method, model, column):
"""
Get the filename where the PastML parameters are saved
(for non-ML methods and input parameters will be None, as they have no parameters).
This file is inside the work_dir that can be specified for the pastml_pipeline method.
:param method: ... | Get the filename where the PastML parameters are saved
(for non-ML methods and input parameters will be None, as they have no parameters).
This file is inside the work_dir that can be specified for the pastml_pipeline method.
:param method: str, the ancestral state prediction method used by PASTML.
:pa... |
def create_or_edit(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin
"""Create or edit a highlight.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param resource: :class:`highlights.Highlight <highlights.Highlight>` object
... | Create or edit a highlight.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param resource: :class:`highlights.Highlight <highlights.Highlight>` object
:return: :class:`highlights.Highlight <highlights.Highlight>` object
:rtype: highlights.Highligh... |
def select_header_content_type(self, content_types):
"""
Returns `Content-Type` based on an array of content_types provided.
:param content_types: List of content-types.
:return: Content-Type (e.g. application/json).
"""
if not content_types:
return 'applicat... | Returns `Content-Type` based on an array of content_types provided.
:param content_types: List of content-types.
:return: Content-Type (e.g. application/json). |
def reset(self):
"""A copy of this description, with all servers marked Unknown."""
if self._topology_type == TOPOLOGY_TYPE.ReplicaSetWithPrimary:
topology_type = TOPOLOGY_TYPE.ReplicaSetNoPrimary
else:
topology_type = self._topology_type
# The default ServerDesc... | A copy of this description, with all servers marked Unknown. |
def job_stats_enhanced(job_id):
"""
Get full job and step stats for job_id
"""
stats_dict = {}
with os.popen('qstat -xf ' + str(job_id)) as f:
try:
line = f.readline().strip()
while line:
if line.startswith('Job Id:'):
stats_dict['j... | Get full job and step stats for job_id |
def _remove_unit_rule(g, rule):
"""Removes 'rule' from 'g' without changing the langugage produced by 'g'."""
new_rules = [x for x in g.rules if x != rule]
refs = [x for x in g.rules if x.lhs == rule.rhs[0]]
new_rules += [build_unit_skiprule(rule, ref) for ref in refs]
return Grammar(new_rules) | Removes 'rule' from 'g' without changing the langugage produced by 'g'. |
def save_local_scope(
self,
line_number,
saved_function_call_index
):
"""Save the local scope before entering a function call by saving all the LHS's of assignments so far.
Args:
line_number(int): Of the def of the function call about to be entered into.
... | Save the local scope before entering a function call by saving all the LHS's of assignments so far.
Args:
line_number(int): Of the def of the function call about to be entered into.
saved_function_call_index(int): Unique number for each call.
Returns:
saved_variable... |
def get_insights_for_project(self, project_owner, project_id, **kwargs):
"""
Get insights for project.
Get insights for a project.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invo... | Get insights for project.
Get insights for a project.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> ... |
def login(self, user, passwd, bank):
""" Login """
logger.info("login...")
if bank not in self.BANKS:
logger.error("Can't find that bank.")
return False
self.useragent = self.BANKS[bank]["u-a"]
self.bankid = self.BANKS[bank]["id"]
login = json.dump... | Login |
def set_ca_certificates(self, cacerts):
"""
Replace or set the CA certificates within the PKCS12 object.
:param cacerts: The new CA certificates, or :py:const:`None` to unset
them.
:type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
:return: ``None``
... | Replace or set the CA certificates within the PKCS12 object.
:param cacerts: The new CA certificates, or :py:const:`None` to unset
them.
:type cacerts: An iterable of :py:class:`X509` or :py:const:`None`
:return: ``None`` |
def color_intrinsics(self):
""":obj:`CameraIntrinsics` : The camera intrinsics for the RealSense color camera.
"""
return CameraIntrinsics(
self._frame,
self._intrinsics[0, 0],
self._intrinsics[1, 1],
self._intrinsics[0, 2],
self._intri... | :obj:`CameraIntrinsics` : The camera intrinsics for the RealSense color camera. |
def delete_record(table, sys_id):
'''
Delete an existing record
:param table: The table name, e.g. sys_user
:type table: ``str``
:param sys_id: The unique ID of the record
:type sys_id: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.delete_record sys_co... | Delete an existing record
:param table: The table name, e.g. sys_user
:type table: ``str``
:param sys_id: The unique ID of the record
:type sys_id: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.delete_record sys_computer 2134566 |
def zest_releaser_check(data):
"""Check the completeness of MANIFEST.in before the release.
This is an entry point for zest.releaser. See the documentation at
https://zestreleaser.readthedocs.io/en/latest/entrypoints.html
"""
from zest.releaser.utils import ask
source_tree = data['workingdir']... | Check the completeness of MANIFEST.in before the release.
This is an entry point for zest.releaser. See the documentation at
https://zestreleaser.readthedocs.io/en/latest/entrypoints.html |
def expect(self, msg) -> T:
"""
Unwraps the option. Raises an exception if the value is :py:data:`NONE`.
Args:
msg: The exception message.
Returns:
The wrapped value.
Raises:
``ValueError`` with message provided by ``msg`` if the value is :p... | Unwraps the option. Raises an exception if the value is :py:data:`NONE`.
Args:
msg: The exception message.
Returns:
The wrapped value.
Raises:
``ValueError`` with message provided by ``msg`` if the value is :py:data:`NONE`.
Examples:
>>... |
def _get_pkg_build_time(name):
'''
Get package build time, if possible.
:param name:
:return:
'''
iso_time = iso_time_t = None
changelog_dir = os.path.join('/usr/share/doc', name)
if os.path.exists(changelog_dir):
for fname in os.listdir(changelog_dir):
try:
... | Get package build time, if possible.
:param name:
:return: |
def POST(self):
"""Respond to inbound webhook JSON HTTP POSTs from Webex Teams."""
# Get the POST data sent from Webex Teams
json_data = web.data()
print("\nWEBHOOK POST RECEIVED:")
print(json_data, "\n")
# Create a Webhook object from the JSON data
webhook_obj =... | Respond to inbound webhook JSON HTTP POSTs from Webex Teams. |
def get_response_message(self, resp_msg_signature=None, delay=COMMAND_DELAY):
""" Receive data from connected gateway and if required seach and return a stream that starts at the required
response message signature. The reason we couple the search for the response signature here is that given the
... | Receive data from connected gateway and if required seach and return a stream that starts at the required
response message signature. The reason we couple the search for the response signature here is that given the
RNET protocol and TCP comms, we dont have an easy way of knowign that we have received ... |
def is_a_sequence(var, allow_none=False):
""" Returns True if var is a list or a tuple (but not a string!)
"""
return isinstance(var, (list, tuple)) or (var is None and allow_none) | Returns True if var is a list or a tuple (but not a string!) |
def _get_query_spec(cls, params):
"""Construct a model.QuerySpec from model.MapperSpec."""
entity_kind = params[cls.ENTITY_KIND_PARAM]
filters = params.get(cls.FILTERS_PARAM)
app = params.get(cls._APP_PARAM)
ns = params.get(cls.NAMESPACE_PARAM)
return model.QuerySpec(
entity_kind=cls._g... | Construct a model.QuerySpec from model.MapperSpec. |
def add_bookmark(request):
"""
This view serves and validates a bookmark form.
If requested via ajax it also returns the drop bookmark form to replace the
add bookmark form.
"""
if request.method == "POST":
form = BookmarkForm(user=request.user, data=request.POST)
if form.is_vali... | This view serves and validates a bookmark form.
If requested via ajax it also returns the drop bookmark form to replace the
add bookmark form. |
def should_set_tablename(cls):
"""Determine whether ``__tablename__`` should be automatically generated
for a model.
* If no class in the MRO sets a name, one should be generated.
* If a declared attr is found, it should be used instead.
* If a name is found, it should be used if the class is a mix... | Determine whether ``__tablename__`` should be automatically generated
for a model.
* If no class in the MRO sets a name, one should be generated.
* If a declared attr is found, it should be used instead.
* If a name is found, it should be used if the class is a mixin, otherwise
one should be gene... |
def load(fp, expand_includes=True, include_position=False, include_comments=False, **kwargs):
"""
Load a Mapfile from an open file or file-like object.
Parameters
----------
fp: file
A file-like object - as with all Mapfiles this should be encoded in "utf-8"
expand_includes: boolean
... | Load a Mapfile from an open file or file-like object.
Parameters
----------
fp: file
A file-like object - as with all Mapfiles this should be encoded in "utf-8"
expand_includes: boolean
Load any ``INCLUDE`` files in the MapFile
include_comments: boolean
Include or discard ... |
def clone(repo, log, depth=1):
"""Given a list of repositories, make sure they're all cloned.
Should be called from the subclassed `Catalog` objects, passed a list
of specific repository names.
Arguments
---------
all_repos : list of str
*Absolute* path specification of each target rep... | Given a list of repositories, make sure they're all cloned.
Should be called from the subclassed `Catalog` objects, passed a list
of specific repository names.
Arguments
---------
all_repos : list of str
*Absolute* path specification of each target repository. |
def Lastovka_solid_integral_over_T(T, similarity_variable):
r'''Integrates over T solid constant-pressure heat capacitiy with the
similarity variable concept and method as shown in [1]_.
Uses a explicit form as derived with Sympy.
Parameters
----------
T : float
Temperature of sol... | r'''Integrates over T solid constant-pressure heat capacitiy with the
similarity variable concept and method as shown in [1]_.
Uses a explicit form as derived with Sympy.
Parameters
----------
T : float
Temperature of solid [K]
similarity_variable : float
similarity variab... |
def assignproduct(self, category_id, product, position=None):
"""
Assign product to a category
:param category_id: ID of a category
:param product: ID or Code of the product
:param position: Position of product in category
:return: boolean
"""
return boo... | Assign product to a category
:param category_id: ID of a category
:param product: ID or Code of the product
:param position: Position of product in category
:return: boolean |
def _check_timestamp(self, timestamp):
"""Verify that timestamp is recentish."""
timestamp = int(timestamp)
now = int(time.time())
lapsed = now - timestamp
if lapsed > self.timestamp_threshold:
raise Error('Expired timestamp: given %d and now %s has a '
... | Verify that timestamp is recentish. |
def variance_at(self, singular_value):
"""get the error variance of all three terms at a singluar value
Parameters
----------
singular_value : int
singular value to test
Returns
-------
dict : dict
dictionary of (err var term,prediction_n... | get the error variance of all three terms at a singluar value
Parameters
----------
singular_value : int
singular value to test
Returns
-------
dict : dict
dictionary of (err var term,prediction_name), standard_deviation pairs |
def add_if_none_match(self):
"""
Add the if-none-match option to the request.
"""
option = Option()
option.number = defines.OptionRegistry.IF_NONE_MATCH.number
option.value = None
self.add_option(option) | Add the if-none-match option to the request. |
def dataCollector( self ):
"""
Returns a method or function that will be used to collect mime data \
for a list of tablewidgetitems. If set, the method should accept a \
single argument for a list of items and then return a QMimeData \
instance.
:usage |fro... | Returns a method or function that will be used to collect mime data \
for a list of tablewidgetitems. If set, the method should accept a \
single argument for a list of items and then return a QMimeData \
instance.
:usage |from projexui.qt.QtCore import QMimeData, QWidget
... |
def asHandle(fileNameOrHandle, mode='r'):
"""
Decorator for file opening that makes it easy to open compressed files.
Based on L{Bio.File.as_handle}.
@param fileNameOrHandle: Either a C{str} or a file handle.
@return: A generator that can be turned into a context manager via
L{contextlib.co... | Decorator for file opening that makes it easy to open compressed files.
Based on L{Bio.File.as_handle}.
@param fileNameOrHandle: Either a C{str} or a file handle.
@return: A generator that can be turned into a context manager via
L{contextlib.contextmanager}. |
def main_source(self, operator, value=None):
"""
Execute Main.Source.
Returns int
"""
try:
source = int(self.exec_command('main', 'source', operator, value))
return source
except (ValueError, TypeError):
pass
return None | Execute Main.Source.
Returns int |
def psf_slice(self, zint, size=11, zoffset=0., getextent=False):
"""
Calculates the 3D psf at a particular z pixel height
Parameters
----------
zint : float
z pixel height in image coordinates , converted to 1/k by the
function using the slab position as ... | Calculates the 3D psf at a particular z pixel height
Parameters
----------
zint : float
z pixel height in image coordinates , converted to 1/k by the
function using the slab position as well
size : int, list, tuple
The size over which to calculate th... |
def import_discord_user(self, uid, user):
"""Add a discord user to the database if not already present, get if is present. """
url = api_url+'users/social/'
payload = {
'user': int(user),
'provider': 'discord',
'uid': str(uid)
}
print(json.dumps(payload))
r = requests.put(url, data=json.dumps(paylo... | Add a discord user to the database if not already present, get if is present. |
def remove_values(self, keys):
"""Remove values from data"""
data = self.model.get_data()
for key in sorted(keys, reverse=True):
data.pop(key)
self.set_data(data) | Remove values from data |
def merge_trajectories(session):
""" Merges all trajectories found in the working directory """
jd = saga.job.Description()
jd.executable = 'python'
jd.arguments = ['merge_trajs.py']
jd.output = "mysagajob_merge.stdout"
jd.error = "mysagajob_merge.stderr"
jd.wo... | Merges all trajectories found in the working directory |
def _read_interleaved_numpy(self, f, data_objects):
"""Read interleaved data where all channels have a numpy type"""
log.debug("Reading interleaved data all at once")
# Read all data into 1 byte unsigned ints first
all_channel_bytes = data_objects[0].raw_data_width
if all_channe... | Read interleaved data where all channels have a numpy type |
def DEFINE_enum( # pylint: disable=g-bad-name,redefined-builtin
name, default, enum_values, help, flag_values=FLAGS, module_name=None,
**args):
"""Registers a flag whose value can be any string from enum_values.
Args:
name: A string, the flag name.
default: The default value of the flag.
enum_... | Registers a flag whose value can be any string from enum_values.
Args:
name: A string, the flag name.
default: The default value of the flag.
enum_values: A list of strings with the possible values for the flag.
help: A help string.
flag_values: FlagValues object with which the flag will be regis... |
def clean(args):
"""
%prog clean 1.fastq 2.fastq [insertsize]
Clean and dedup paired FASTQ files.
"""
p = OptionParser(clean.__doc__)
p.add_option("-a", default=0, type="int",
help="Trim length at 5' end [default: %default]")
p.add_option("-b", default=50, type="int",
... | %prog clean 1.fastq 2.fastq [insertsize]
Clean and dedup paired FASTQ files. |
def write_py(self):
"""Writes a python module file to the current working directory for the library.
"""
self._check_dir()
#We make it so that the write py method can be called independently (as opposed
#to first needing the F90 write method to be called).
self._find_exec... | Writes a python module file to the current working directory for the library. |
def uninstall_all_integration_alerts(self, id, **kwargs): # noqa: E501
"""Disable all alerts associated with this integration # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>... | Disable all alerts associated with this integration # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.uninstall_all_integration_alerts(id, async_req=True)
>>> re... |
def vertex_enumeration_gen(g, qhull_options=None):
"""
Generator version of `vertex_enumeration`.
Parameters
----------
g : NormalFormGame
NormalFormGame instance with 2 players.
qhull_options : str, optional(default=None)
Options to pass to `scipy.spatial.ConvexHull`. See the ... | Generator version of `vertex_enumeration`.
Parameters
----------
g : NormalFormGame
NormalFormGame instance with 2 players.
qhull_options : str, optional(default=None)
Options to pass to `scipy.spatial.ConvexHull`. See the `Qhull
manual <http://www.qhull.org>`_ for details.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.