code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def needle(self, serie):
"""Draw a needle for each value"""
serie_node = self.svg.serie(serie)
for i, theta in enumerate(serie.values):
if theta is None:
continue
def point(x, y):
return '%f %f' % self.view((x, y))
val = self.... | Draw a needle for each value |
def _maybe_validate_shape_override(self, override_shape, base_is_scalar,
validate_args, name):
"""Helper to __init__ which ensures override batch/event_shape are valid."""
if override_shape is None:
override_shape = []
override_shape = tf.convert_to_tensor(
... | Helper to __init__ which ensures override batch/event_shape are valid. |
def login_exists(login, domain='', **kwargs):
'''
Find if a login exists in the MS SQL server.
domain, if provided, will be prepended to login
CLI Example:
.. code-block:: bash
salt minion mssql.login_exists 'LOGIN'
'''
if domain:
login = '{0}\\{1}'.format(domain, login)
... | Find if a login exists in the MS SQL server.
domain, if provided, will be prepended to login
CLI Example:
.. code-block:: bash
salt minion mssql.login_exists 'LOGIN' |
def report(self, name, **kwargs):
"""Add Report data to Batch object.
Args:
name (str): The name for this Group.
file_name (str): The name for the attached file for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
file_c... | Add Report data to Batch object.
Args:
name (str): The name for this Group.
file_name (str): The name for the attached file for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
file_content (str;method, kwargs): The file content... |
def collect(coro, index, results,
preserve_order=False,
return_exceptions=False):
"""
Collect is used internally to execute coroutines and collect the returned
value. This function is intended to be used internally.
"""
result = yield from safe_run(coro, return_exceptions=ret... | Collect is used internally to execute coroutines and collect the returned
value. This function is intended to be used internally. |
def getRootJobs(self):
"""
:return: The roots of the connected component of jobs that contains this job. \
A root is a job with no predecessors.
:rtype : set of toil.job.Job instances
"""
roots = set()
visited = set()
#Function to get the roots of a job
... | :return: The roots of the connected component of jobs that contains this job. \
A root is a job with no predecessors.
:rtype : set of toil.job.Job instances |
def splitter(div, *args):
"""
Split text with dividers easily.
:return: newly made value
:rtype: str
:param div: the divider
"""
retstr = ""
if type(div) is int:
div = theArray()[div]
if len(args) == 1:
return args[0]
for s in args:
retstr += s
re... | Split text with dividers easily.
:return: newly made value
:rtype: str
:param div: the divider |
def actions(obj, **kwargs):
"""
Return actions available for an object
"""
if 'exclude' in kwargs:
kwargs['exclude'] = kwargs['exclude'].split(',')
actions = obj.get_actions(**kwargs)
if isinstance(actions, dict):
actions = actions.values()
buttons = "".join("%s" % action.ren... | Return actions available for an object |
def url_report(self, scan_url, apikey):
"""
Send URLS for list of past malicous associations
"""
url = self.base_url + "url/report"
params = {"apikey": apikey, 'resource': scan_url}
rate_limit_clear = self.rate_limit()
if rate_limit_clear:
response = r... | Send URLS for list of past malicous associations |
def log_formatter(request=None):
"""
Log formatter used in our syslog
:param request: a request object
:returns: logging.Formatter
"""
if request:
format_str = ('%(asctime)s {ip} {name}: ENV={env} '
'REMOTE_IP=%(remote_ip)s REQUEST_ID=%(request_id)s '
... | Log formatter used in our syslog
:param request: a request object
:returns: logging.Formatter |
def get_forces(self, a=None):
"""Calculate atomic forces."""
if a is None:
a = self.a
forces = np.zeros([len(a), 3], dtype=float)
if self.mask is None:
forces[self.mask] = self.force
else:
forces[:] = self.force
return forces | Calculate atomic forces. |
def read(self, source_path):
"""Parse content and metadata of creole files"""
self._metadata = {}
with pelican_open(source_path) as text:
content = creole2html(text, macros={'header': self._parse_header_macro,
'code': self._parse_code_macr... | Parse content and metadata of creole files |
def get_lookups(cls):
"""Fetch all Lookups"""
class_lookups = [parent.__dict__.get('class_lookups', {}) for parent in inspect.getmro(cls)]
return cls.merge_dicts(class_lookups) | Fetch all Lookups |
def set(self, section, option, value):
"""Set an option value. Knows how to set options properly marked
as secure."""
if not value:
value = '!!False!!'
if self.is_secure_option(section, option):
self.set_secure(section, option, value)
else:
Con... | Set an option value. Knows how to set options properly marked
as secure. |
def eklef(fname):
"""
Load an EK file, making it accessible to the EK readers.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eklef_c.html
:param fname: Name of EK file to load.
:type fname: str
:return: File handle of loaded EK file.
:rtype: int
"""
fname = stypes.stringT... | Load an EK file, making it accessible to the EK readers.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eklef_c.html
:param fname: Name of EK file to load.
:type fname: str
:return: File handle of loaded EK file.
:rtype: int |
def add_property(self, prop):
"""Add a property to an object. The property is an instance of
a Property or one of its derived classes. Adding a property
disconnects it from the collection of properties common to all of the
objects of its class."""
if _debug: Object._debug("add_... | Add a property to an object. The property is an instance of
a Property or one of its derived classes. Adding a property
disconnects it from the collection of properties common to all of the
objects of its class. |
def fullversion():
'''
Shows installed version of dnsmasq and compile options.
CLI Example:
.. code-block:: bash
salt '*' dnsmasq.fullversion
'''
cmd = 'dnsmasq -v'
out = __salt__['cmd.run'](cmd).splitlines()
comps = out[0].split()
version_num = comps[2]
comps = out[1]... | Shows installed version of dnsmasq and compile options.
CLI Example:
.. code-block:: bash
salt '*' dnsmasq.fullversion |
def get_devicelist(home_hub_ip='192.168.1.254'):
"""Retrieve data from BT Home Hub 5 and return parsed result.
"""
url = 'http://{}/'.format(home_hub_ip)
try:
response = requests.get(url, timeout=5)
except requests.exceptions.Timeout:
_LOGGER.exception("Connection to the router tim... | Retrieve data from BT Home Hub 5 and return parsed result. |
def display_google_book(id, page=None, width=700, height=500, **kwargs):
"""Display an embedded version of a Google book.
:param id: the id of the google book to display.
:type id: string
:param page: the start page for the book.
:type id: string or int."""
if isinstance(page, int):
url ... | Display an embedded version of a Google book.
:param id: the id of the google book to display.
:type id: string
:param page: the start page for the book.
:type id: string or int. |
def var(self, ddof=1, *args, **kwargs):
"""
Compute variance of groups, excluding missing values.
For multiple groupings, the result index will be a MultiIndex.
Parameters
----------
ddof : integer, default 1
degrees of freedom
"""
nv.validat... | Compute variance of groups, excluding missing values.
For multiple groupings, the result index will be a MultiIndex.
Parameters
----------
ddof : integer, default 1
degrees of freedom |
def set_alternative(self, experiment_name, alternative):
"""Explicitly set the alternative the user is enrolled in for the specified experiment.
This allows you to change a user between alternatives. The user and goal counts for the new
alternative will be increment, but those for the old one w... | Explicitly set the alternative the user is enrolled in for the specified experiment.
This allows you to change a user between alternatives. The user and goal counts for the new
alternative will be increment, but those for the old one will not be decremented. The user will
be enrolled in the exp... |
def extend(self, builder):
"""
Extend the query builder with the needed functions.
:param builder: The query builder
:type builder: eloquent.orm.builder.Builder
"""
for extension in self._extensions:
getattr(self, '_add_%s' % extension)(builder)
buil... | Extend the query builder with the needed functions.
:param builder: The query builder
:type builder: eloquent.orm.builder.Builder |
def attrlist(self):
'Transform the KEY_MAP paramiter into an attrlist for ldap filters'
keymap = self.config.get('KEY_MAP')
if keymap:
# https://github.com/ContinuumIO/flask-ldap-login/issues/11
# https://continuumsupport.zendesk.com/agent/tickets/393
return [... | Transform the KEY_MAP paramiter into an attrlist for ldap filters |
def clean_slug(self):
"""
Save the old slug to be used later in PageAdmin.save_model()
to make the slug change propagate down the page tree, and clean
leading and trailing slashes which are added on elsewhere.
"""
self.instance._old_slug = self.instance.slug
new_s... | Save the old slug to be used later in PageAdmin.save_model()
to make the slug change propagate down the page tree, and clean
leading and trailing slashes which are added on elsewhere. |
def print_file_results(file_result):
"""Print the results of validating a file.
Args:
file_result: A FileValidationResults instance.
"""
print_results_header(file_result.filepath, file_result.is_valid)
for object_result in file_result.object_results:
if object_result.warnings:
... | Print the results of validating a file.
Args:
file_result: A FileValidationResults instance. |
def parse_endpoint_name(self, endpoint):
'''split an endpoint name by colon, as the user can provide an
endpoint name separated from a path:
Parameters
==========
endpoint 12345:/path/on/remote
'''
parts = [x for x in endpoint.split(':') if x]
endpoint = parts[0]
if... | split an endpoint name by colon, as the user can provide an
endpoint name separated from a path:
Parameters
==========
endpoint 12345:/path/on/remote |
def get(self):
"""
*get the PDF*
**Return:**
- ``pdfPath`` -- the path to the generated PDF
"""
self.log.debug('starting the ``get`` method')
# APPEND TO FILENAME?
if not self.append:
self.append = ""
if not self.readability:
... | *get the PDF*
**Return:**
- ``pdfPath`` -- the path to the generated PDF |
def get_crimes_no_location(self, force, date=None, category=None):
"""
Get crimes with no location for a force. Uses the crimes-no-location_
API call.
.. _crimes-no-location:
https://data.police.uk/docs/method/crimes-no-location/
:rtype: list
:param force: T... | Get crimes with no location for a force. Uses the crimes-no-location_
API call.
.. _crimes-no-location:
https://data.police.uk/docs/method/crimes-no-location/
:rtype: list
:param force: The force to get no-location crimes for.
:type force: str or Force
:para... |
def deployment_label(self):
'''
this property returns the deployment label dictionary (mainly used by
stage description)
'''
label = dict()
label['swagger_info_object'] = self.info
label['api_name'] = self.rest_api_name
label['swagger_file'] = os.path.bas... | this property returns the deployment label dictionary (mainly used by
stage description) |
def transitDurationCircular(P, R_s, R_p, a, i):
r"""Estimation of the primary transit time. Assumes a circular orbit.
.. math::
T_\text{dur} = \frac{P}{\pi}\sin^{-1}
\left[\frac{R_\star}{a}\frac{\sqrt{(1+k)^2 + b^2}}{\sin{a}} \right]
Where :math:`T_\text{dur}` transit duration, P orbital p... | r"""Estimation of the primary transit time. Assumes a circular orbit.
.. math::
T_\text{dur} = \frac{P}{\pi}\sin^{-1}
\left[\frac{R_\star}{a}\frac{\sqrt{(1+k)^2 + b^2}}{\sin{a}} \right]
Where :math:`T_\text{dur}` transit duration, P orbital period,
:math:`R_\star` radius of the star, a is ... |
def add_bookmark(self, new_bookmark, *, max_retries=3):
"""
Add a bookmark and check whether it was successfully added to the
bookmark list. Already existant bookmarks are not added twice.
:param new_bookmark: the bookmark to add
:type new_bookmark: an instance of :class:`~bookm... | Add a bookmark and check whether it was successfully added to the
bookmark list. Already existant bookmarks are not added twice.
:param new_bookmark: the bookmark to add
:type new_bookmark: an instance of :class:`~bookmark_xso.Bookmark`
:param max_retries: the number of retries if setti... |
def join(self, column_label, other, other_label=None):
"""Creates a new table with the columns of self and other, containing
rows for all values of a column that appear in both tables.
Args:
``column_label`` (``str``): label of column in self that is used to
join r... | Creates a new table with the columns of self and other, containing
rows for all values of a column that appear in both tables.
Args:
``column_label`` (``str``): label of column in self that is used to
join rows of ``other``.
``other``: Table object to join with... |
def udom83(text: str) -> str:
"""
Udom83 - It's a Thai soundex rule.
:param str text: Thai word
:return: Udom83 soundex
"""
if not text or not isinstance(text, str):
return ""
text = _RE_1.sub("ัน\\1", text)
text = _RE_2.sub("ั\\1", text)
text = _RE_3.sub("ัน\\1", text)
... | Udom83 - It's a Thai soundex rule.
:param str text: Thai word
:return: Udom83 soundex |
def update(self):
"""Get info from dataset before opening dialog."""
self.filename = self.parent.info.dataset.filename
self.chan = self.parent.info.dataset.header['chan_name']
for chan in self.chan:
self.idx_chan.addItem(chan) | Get info from dataset before opening dialog. |
def get_plugin_folders():
"""Get linkchecker plugin folders. Default is ~/.linkchecker/plugins/."""
folders = []
defaultfolder = normpath("~/.linkchecker/plugins")
if not os.path.exists(defaultfolder) and not Portable:
try:
make_userdir(defaultfolder)
except Exception as errm... | Get linkchecker plugin folders. Default is ~/.linkchecker/plugins/. |
def to_gds(self, multiplier):
"""
Convert this object to a GDSII element.
Parameters
----------
multiplier : number
A number that multiplies all dimensions written in the GDSII
element.
Returns
-------
out : string
The... | Convert this object to a GDSII element.
Parameters
----------
multiplier : number
A number that multiplies all dimensions written in the GDSII
element.
Returns
-------
out : string
The GDSII binary string that represents this object. |
def get_cgroup_container_metadata():
"""
Reads docker/kubernetes metadata (container id, pod id) from /proc/self/cgroup
The result is a nested dictionary with the detected IDs, e.g.
{
"container": {"id": "2227daf62df6694645fee5df53c1f91271546a9560e8600a525690ae252b7f63"},
"... | Reads docker/kubernetes metadata (container id, pod id) from /proc/self/cgroup
The result is a nested dictionary with the detected IDs, e.g.
{
"container": {"id": "2227daf62df6694645fee5df53c1f91271546a9560e8600a525690ae252b7f63"},
"pod": {"uid": "90d81341_92de_11e7_8cf2_507b9d4141... |
def main():
"""main
The entrypoint function. This function should also handle any runtime
errors and exceptions in a cleanly fashon.
"""
try:
args = get_args()
if 'setup_cfg' in args and 'stdeb_cfg' in args:
_construct_cfgs_from_json(args)
else:
construct_cf... | main
The entrypoint function. This function should also handle any runtime
errors and exceptions in a cleanly fashon. |
def setup(options):
"""Initialize debug/logging in third party libraries correctly.
Args:
options (:class:`nyawc.Options`): The options to use for the current crawling runtime.
"""
if not options.misc.debug:
requests.packages.urllib3.disable_warnings(
... | Initialize debug/logging in third party libraries correctly.
Args:
options (:class:`nyawc.Options`): The options to use for the current crawling runtime. |
def parse_limit(limit_def):
"""Parse a structured flux limit definition as obtained from a YAML file
Returns a tuple of reaction, lower and upper bound.
"""
lower, upper = get_limits(limit_def)
reaction = limit_def.get('reaction')
return reaction, lower, upper | Parse a structured flux limit definition as obtained from a YAML file
Returns a tuple of reaction, lower and upper bound. |
def replace_discount_coupon_by_id(cls, discount_coupon_id, discount_coupon, **kwargs):
"""Replace DiscountCoupon
Replace all attributes of DiscountCoupon
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thr... | Replace DiscountCoupon
Replace all attributes of DiscountCoupon
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_discount_coupon_by_id(discount_coupon_id, discount_coupon, async=True)
>... |
def _set_fields(self, fields):
"""Set or update the fields value."""
super(_BaseHNVModel, self)._set_fields(fields)
if not self.resource_ref:
endpoint = self._endpoint.format(
resource_id=self.resource_id, parent_id=self.parent_id,
grandparent_id=self.... | Set or update the fields value. |
def read_dir(input_dir,input_ext,func):
'''reads all files with extension input_ext
in a directory input_dir and apply function func
to their contents'''
import os
for dirpath, dnames, fnames in os.walk(input_dir):
for fname in fnames:
if not dirpath.endswith(os.sep):
... | reads all files with extension input_ext
in a directory input_dir and apply function func
to their contents |
def invoked_with(self):
"""Similar to :attr:`Context.invoked_with` except properly handles
the case where :meth:`Context.send_help` is used.
If the help command was used regularly then this returns
the :attr:`Context.invoked_with` attribute. Otherwise, if
it the help command was... | Similar to :attr:`Context.invoked_with` except properly handles
the case where :meth:`Context.send_help` is used.
If the help command was used regularly then this returns
the :attr:`Context.invoked_with` attribute. Otherwise, if
it the help command was called using :meth:`Context.send_h... |
def purge_network(network_id, purge_data,**kwargs):
"""
Remove a network from DB completely
Use purge_data to try to delete the data associated with only this network.
If no other resources link to this data, it will be deleted.
"""
user_id = kwargs.get('user_id')
try:
n... | Remove a network from DB completely
Use purge_data to try to delete the data associated with only this network.
If no other resources link to this data, it will be deleted. |
def virtualchain_set_opfields( op, **fields ):
"""
Pass along virtualchain-reserved fields to a virtualchain operation.
This layer of indirection is meant to help with future compatibility,
so virtualchain implementations do not try to set operation fields
directly.
"""
# warn about unsuppo... | Pass along virtualchain-reserved fields to a virtualchain operation.
This layer of indirection is meant to help with future compatibility,
so virtualchain implementations do not try to set operation fields
directly. |
def one_step(self, current_state, previous_kernel_results):
"""Runs one iteration of the Elliptical Slice Sampler.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s). The first `r` dimensions
index independent chains,
... | Runs one iteration of the Elliptical Slice Sampler.
Args:
current_state: `Tensor` or Python `list` of `Tensor`s representing the
current state(s) of the Markov chain(s). The first `r` dimensions
index independent chains,
`r = tf.rank(log_likelihood_fn(*normal_sampler_fn()))`.
pr... |
async def fetch_wallet_search_next_records(wallet_handle: int,
wallet_search_handle: int,
count: int) -> str:
"""
Fetch next records for wallet search.
:param wallet_handle: wallet handler (created by open_wallet).
:p... | Fetch next records for wallet search.
:param wallet_handle: wallet handler (created by open_wallet).
:param wallet_search_handle: wallet wallet handle (created by open_wallet_search)
:param count: Count of records to fetch
:return: wallet records json:
{
totalCount: <str>, // present only i... |
def _plot_transform_pairs(fCI, r, k, axes, tit):
r"""Plot the input transform pairs."""
# Plot lhs
plt.sca(axes[0])
plt.title('|' + tit + ' lhs|')
for f in fCI:
if f.name == 'j2':
lhs = f.lhs(k)
plt.loglog(k, np.abs(lhs[0]), lw=2, label='j0')
plt.loglog(k... | r"""Plot the input transform pairs. |
def folderitem(self, obj, item, index):
"""Applies new properties to the item (analysis) that is currently
being rendered as a row in the list.
:param obj: analysis to be rendered as a row in the list
:param item: dict representation of the analysis, suitable for the list
:param... | Applies new properties to the item (analysis) that is currently
being rendered as a row in the list.
:param obj: analysis to be rendered as a row in the list
:param item: dict representation of the analysis, suitable for the list
:param index: current position of the item within the lis... |
def _get_state(self):
"""
Returns the VM state (e.g. running, paused etc.)
:returns: state (string)
"""
result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"])
for info in result.splitlines():
if '=' in info:
name... | Returns the VM state (e.g. running, paused etc.)
:returns: state (string) |
def get_ip_interface_output_interface_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.S... | Auto Generated Code |
def errmsg(self, message, opts={}):
""" Convenience short-hand for self.intf[-1].errmsg """
if 'plain' != self.debugger.settings['highlight']:
message = colorize('standout', message)
pass
return(self.intf[-1].errmsg(message)) | Convenience short-hand for self.intf[-1].errmsg |
def start(self):
"""
Start the installation wizard
"""
self.log.debug('Starting the installation process')
self.browser.open(self.url)
self.system_check() | Start the installation wizard |
def attach(cls, name, vhost, remote_name):
"""Attach an instance's vhost to a remote from the local repository."""
paas_access = cls.get('paas_access')
if not paas_access:
paas_info = cls.info(name)
paas_access = '%s@%s' \
% (paas_info['user'], ... | Attach an instance's vhost to a remote from the local repository. |
def handle_401(self, response, repo, **kwargs):
"""Fetch Bearer token and retry."""
if response.status_code != requests.codes.unauthorized:
return response
auth_info = response.headers.get('www-authenticate', '')
if 'bearer' not in auth_info.lower():
return resp... | Fetch Bearer token and retry. |
def create_mixin(self):
"""
This will create the custom Model Mixin to attach to your custom field
enabled model.
:return:
"""
_builder = self
class CustomModelMixin(object):
@cached_property
def _content_type(self):
retu... | This will create the custom Model Mixin to attach to your custom field
enabled model.
:return: |
def create_model(self,
base_model_id,
forced_glossary=None,
parallel_corpus=None,
name=None,
**kwargs):
"""
Create model.
Uploads Translation Memory eXchange (TMX) files to customize a trans... | Create model.
Uploads Translation Memory eXchange (TMX) files to customize a translation model.
You can either customize a model with a forced glossary or with a corpus that
contains parallel sentences. To create a model that is customized with a parallel
corpus <b>and</b> a forced glos... |
def reply_inform(self, inform, orig_req):
"""Send an inform as part of the reply to an earlier request.
Parameters
----------
inform : Message object
The inform message to send.
orig_req : Message object
The request message being replied to. The inform me... | Send an inform as part of the reply to an earlier request.
Parameters
----------
inform : Message object
The inform message to send.
orig_req : Message object
The request message being replied to. The inform message's
id is overridden with the id from... |
def getAxisNames(self):
"""
Collect a set of axis names from all deltas.
"""
s = {}
for l, x in self.items():
s.update(dict.fromkeys([k for k, v in l], None))
return set(s.keys()) | Collect a set of axis names from all deltas. |
def drag(self, NewPt):
# //Mouse drag, calculate rotation (Point2fT Quat4fT)
""" drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec
"""
X = 0
Y = 1
Z = 2
W = 3
self.m_EnVec = self._mapToSphere(NewPt)
# //Compute the vector perpendicular t... | drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec |
def channel_interpolate(layer1, n_channel1, layer2, n_channel2):
"""Interpolate between layer1, n_channel1 and layer2, n_channel2.
Optimize for a convex combination of layer1, n_channel1 and
layer2, n_channel2, transitioning across the batch.
Args:
layer1: layer to optimize 100% at batch=0.
n_channel1... | Interpolate between layer1, n_channel1 and layer2, n_channel2.
Optimize for a convex combination of layer1, n_channel1 and
layer2, n_channel2, transitioning across the batch.
Args:
layer1: layer to optimize 100% at batch=0.
n_channel1: neuron index to optimize 100% at batch=0.
layer2: layer to optim... |
def unique(values):
"""
Hash table-based unique. Uniques are returned in order
of appearance. This does NOT sort.
Significantly faster than numpy.unique. Includes NA values.
Parameters
----------
values : 1d array-like
Returns
-------
numpy.ndarray or ExtensionArray
T... | Hash table-based unique. Uniques are returned in order
of appearance. This does NOT sort.
Significantly faster than numpy.unique. Includes NA values.
Parameters
----------
values : 1d array-like
Returns
-------
numpy.ndarray or ExtensionArray
The return can be:
* Ind... |
def set_home_position_send(self, target_system, latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z, force_mavlink1=False):
'''
The position the system will return to and land on. The position is
set automatically by the system during the takeoff... | The position the system will return to and land on. The position is
set automatically by the system during the takeoff in
case it was not explicitely set by the operator before
or after. The global and local positions encode the
position in the respective ... |
def save_xml(self, doc, element):
'''Save this preceding condition into an xml.dom.Element object.'''
super(Preceding, self).save_xml(doc, element)
pre_element = doc.createElementNS(RTS_NS, RTS_NS_S + 'Preceding')
if self.timeout:
pre_element.setAttributeNS(RTS_NS, RTS_NS_S +... | Save this preceding condition into an xml.dom.Element object. |
def get_serializer(instance, plugin=None, model=None, *args, **kwargs):
"""
:param instance: model instance or queryset
:param plugin: plugin instance that is used to get serializer for
:param model: plugin model we build serializer for
:param kwargs: kwargs like many and other
:return:
"""
... | :param instance: model instance or queryset
:param plugin: plugin instance that is used to get serializer for
:param model: plugin model we build serializer for
:param kwargs: kwargs like many and other
:return: |
def _FracInt(x,y,z,a,b,c,tau,n):
"""Returns
1 x^2 y^2 z^2
-------------------------- (1 - ------- - ------- - -------)^n
sqrt(tau+a)(tau+b)(tau+c)) tau+a tau+b tau+c
"""
denom = np.sqrt((a + tau)*(b + tau)*(c + tau))
return (1. - x**2... | Returns
1 x^2 y^2 z^2
-------------------------- (1 - ------- - ------- - -------)^n
sqrt(tau+a)(tau+b)(tau+c)) tau+a tau+b tau+c |
def vlan_dot1q_tag_native(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vlan = ET.SubElement(config, "vlan", xmlns="urn:brocade.com:mgmt:brocade-vlan")
dot1q = ET.SubElement(vlan, "dot1q")
tag = ET.SubElement(dot1q, "tag")
native = ET.S... | Auto Generated Code |
def add_object(self, obj):
"""
Add object to local and app environment storage
:param obj: Instance of a AutoAPI object
"""
self.objects[obj.id] = obj
self.all_objects[obj.id] = obj
child_stack = list(obj.children)
while child_stack:
child = c... | Add object to local and app environment storage
:param obj: Instance of a AutoAPI object |
def tree(self, path, max_depth, full_path=False, include_stat=False):
"""DFS generator which starts from a given path and goes up to a max depth.
:param path: path from which the DFS will start
:param max_depth: max depth of DFS (0 means no limit)
:param full_path: should the full path ... | DFS generator which starts from a given path and goes up to a max depth.
:param path: path from which the DFS will start
:param max_depth: max depth of DFS (0 means no limit)
:param full_path: should the full path of the child node be returned
:param include_stat: return the child Znode... |
def query(self, query):
'''Returns an iterable of objects matching criteria expressed in `query`.
LoggingDatastore logs the access.
'''
self.logger.info('%s: query %s' % (self, query))
return super(LoggingDatastore, self).query(query) | Returns an iterable of objects matching criteria expressed in `query`.
LoggingDatastore logs the access. |
def order_by(self, field_name=None):
"""
Returns a new QuerySet instance with the ordering changed.
"""
assert self.query.can_filter(), "Cannot reorder a query once a slice has been taken."
clone = self._clone()
clone.query.clear_ordering()
if field_name is not ... | Returns a new QuerySet instance with the ordering changed. |
def dispatch_hook(cls, s=None, *_args, **_kwds):
# type: (Optional[str], *Any, **Any) -> base_classes.Packet_metaclass
"""dispatch_hook returns the subclass of HPackHeaders that must be used
to dissect the string.
"""
if s is None:
return config.conf.raw_layer
... | dispatch_hook returns the subclass of HPackHeaders that must be used
to dissect the string. |
def send_msg(self, msg):
"""
Sends Zebra message.
:param msg: Instance of py:class: `ryu.lib.packet.zebra.ZebraMessage`.
:return: Serialized msg if succeeded, otherwise None.
"""
if not self.is_active:
self.logger.debug(
'Cannot send message: ... | Sends Zebra message.
:param msg: Instance of py:class: `ryu.lib.packet.zebra.ZebraMessage`.
:return: Serialized msg if succeeded, otherwise None. |
def calibration_total_count(self):
"""The number of stimuli presentations (including reps) for the current calibration selected
:returns: int -- number of presentations
"""
if self.selected_calibration_index == 2:
return self.tone_calibrator.count()
else:
... | The number of stimuli presentations (including reps) for the current calibration selected
:returns: int -- number of presentations |
def _get_binop_contexts(context, left, right):
"""Get contexts for binary operations.
This will return two inference contexts, the first one
for x.__op__(y), the other one for y.__rop__(x), where
only the arguments are inversed.
"""
# The order is important, since the first one should be
# ... | Get contexts for binary operations.
This will return two inference contexts, the first one
for x.__op__(y), the other one for y.__rop__(x), where
only the arguments are inversed. |
def barrier_layer_thickness(SA, CT):
"""
Compute the thickness of water separating the mixed surface layer from the
thermocline. A more precise definition would be the difference between
mixed layer depth (MLD) calculated from temperature minus the mixed layer
depth calculated using density.
"... | Compute the thickness of water separating the mixed surface layer from the
thermocline. A more precise definition would be the difference between
mixed layer depth (MLD) calculated from temperature minus the mixed layer
depth calculated using density. |
def ltrim(self, name, start, end):
"""
Trim the list from start to end.
:param name: str the name of the redis key
:param start:
:param end:
:return: Future()
"""
with self.pipe as pipe:
return pipe.ltrim(self.redis_key(name), start, end) | Trim the list from start to end.
:param name: str the name of the redis key
:param start:
:param end:
:return: Future() |
def predict_cumulative_hazard(self, X):
"""
Returns the hazard rates for the individuals
Parameters
----------
X: a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order ... | Returns the hazard rates for the individuals
Parameters
----------
X: a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order as the training data. |
def read(self, client):
"""
read current data of db row from plc
"""
assert(isinstance(self._bytearray, DB))
assert(self.row_size >= 0)
db_nr = self._bytearray.db_number
_bytearray = client.db_read(db_nr, self.db_offset, self.row_size)
data = self.get_byt... | read current data of db row from plc |
def find_package_indexes_in_dir(self, simple_dir):
"""Given a directory that contains simple packages indexes, return
a sorted list of normalized package names. This presumes every
directory within is a simple package index directory."""
packages = sorted(
{
... | Given a directory that contains simple packages indexes, return
a sorted list of normalized package names. This presumes every
directory within is a simple package index directory. |
def get_default_config_help(self):
"""
Returns the help text for the configuration options for this handler
"""
config = super(RiemannHandler, self).get_default_config_help()
config.update({
'host': '',
'port': '',
'transport': 'tcp or udp',
... | Returns the help text for the configuration options for this handler |
def build(
self,
endpoint,
values=None,
method=None,
force_external=False,
append_unknown=True,
):
"""Building URLs works pretty much the other way round. Instead of
`match` you call `build` and pass it the endpoint and a dict of
arguments for... | Building URLs works pretty much the other way round. Instead of
`match` you call `build` and pass it the endpoint and a dict of
arguments for the placeholders.
The `build` function also accepts an argument called `force_external`
which, if you set it to `True` will force external URLs.... |
def extract_files(self, resource):
"""
:param resource str|iterable files, a file or a directory
@return: iterable
"""
if hasattr(resource, "__iter__"):
files = [file for file in resource if self.can_be_extracted(file)]
elif os.path.isfile(resource):
... | :param resource str|iterable files, a file or a directory
@return: iterable |
def repmct(instr, marker, value, repcase, lenout=None):
"""
Replace a marker with the text representation of a
cardinal number.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmc_c.html
:param instr: Input string.
:type instr: str
:param marker: Marker to be replaced.
:type ... | Replace a marker with the text representation of a
cardinal number.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmc_c.html
:param instr: Input string.
:type instr: str
:param marker: Marker to be replaced.
:type marker: str
:param value: Replacement value.
:type value: in... |
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result | Given a date tag, return a date object. |
def convert(self, newstart: str) -> None:
"""Convert to another list type by replacing starting pattern."""
match = self._match
ms = match.start()
for s, e in reversed(match.spans('pattern')):
self[s - ms:e - ms] = newstart
self.pattern = escape(newstart) | Convert to another list type by replacing starting pattern. |
def create_ascii_table(observation_table, outfile):
"""Given a table of observations create an ascii log file for easy parsing.
Store the result in outfile (could/should be a vospace dataNode)
observation_table: astropy.votable.array object
outfile: str (name of the vospace dataNode to store the result... | Given a table of observations create an ascii log file for easy parsing.
Store the result in outfile (could/should be a vospace dataNode)
observation_table: astropy.votable.array object
outfile: str (name of the vospace dataNode to store the result to) |
def target_slide(self):
"""
A reference to the slide in this presentation that is the target of
the slide jump action in this shape. Slide jump actions include
`PP_ACTION.FIRST_SLIDE`, `LAST_SLIDE`, `NEXT_SLIDE`,
`PREVIOUS_SLIDE`, and `NAMED_SLIDE`. Returns |None| for all other
... | A reference to the slide in this presentation that is the target of
the slide jump action in this shape. Slide jump actions include
`PP_ACTION.FIRST_SLIDE`, `LAST_SLIDE`, `NEXT_SLIDE`,
`PREVIOUS_SLIDE`, and `NAMED_SLIDE`. Returns |None| for all other
actions. In particular, the `LAST_SLI... |
def num_listeners(self, event=None):
"""Return the number of listeners for ``event``.
Return the total number of listeners for all events on this object if
``event`` is :class:`None`.
"""
if event is not None:
return len(self._listeners[event])
else:
... | Return the number of listeners for ``event``.
Return the total number of listeners for all events on this object if
``event`` is :class:`None`. |
def format_year(year):
"""
Format the year value of the ``YearArchiveView``,
which can be a integer or date object.
This tag is no longer needed, but exists for template compatibility.
It was a compatibility tag for Django 1.4.
"""
if isinstance(year, (date, datetime)):
# Django 1.5... | Format the year value of the ``YearArchiveView``,
which can be a integer or date object.
This tag is no longer needed, but exists for template compatibility.
It was a compatibility tag for Django 1.4. |
def store_field(self, state, field_name, field_type, value):
"""
Store a field of a given object, without resolving hierachy
:param state: angr state where we want to allocate the object attribute
:type SimState
:param field_name: name of the attribute
:type str
... | Store a field of a given object, without resolving hierachy
:param state: angr state where we want to allocate the object attribute
:type SimState
:param field_name: name of the attribute
:type str
:param field_value: attibute's value
:type SimSootValue |
def _load_stats(self):
""" Load the webpack-stats file """
for attempt in range(0, 3):
try:
with self.stats_file.open() as f:
return json.load(f)
except ValueError:
# If we failed to parse the JSON, it's possible that the
... | Load the webpack-stats file |
def event_choices(events):
""" Get the possible events from settings """
if events is None:
msg = "Please add some events in settings.WEBHOOK_EVENTS."
raise ImproperlyConfigured(msg)
try:
choices = [(x, x) for x in events]
except TypeError:
""" Not a valid iterator, so we... | Get the possible events from settings |
def replace(self, old, new):
"""Replace an instruction"""
if old.type != new.type:
raise TypeError("new instruction has a different type")
pos = self.instructions.index(old)
self.instructions.remove(old)
self.instructions.insert(pos, new)
for bb in self.paren... | Replace an instruction |
def pep440_dev_version(self, verbose=False, non_local=False):
""" Return a PEP-440 dev version appendix to the main version number.
Result is ``None`` if the workdir is in a release-ready state
(i.e. clean and properly tagged).
"""
version = capture("python setup.py --ve... | Return a PEP-440 dev version appendix to the main version number.
Result is ``None`` if the workdir is in a release-ready state
(i.e. clean and properly tagged). |
def iteration(self, node_status=True):
"""
Execute a single model iteration
:return: Iteration_id, Incremental node status (dictionary node->status)
"""
self.clean_initial_status(self.available_statuses.values())
actual_status = {node: nstatus for node, nstatus in futur... | Execute a single model iteration
:return: Iteration_id, Incremental node status (dictionary node->status) |
def steady_connection(self):
"""Get a steady, non-persistent PyGreSQL connection."""
return SteadyPgConnection(
self._maxusage, self._setsession, self._closeable,
*self._args, **self._kwargs) | Get a steady, non-persistent PyGreSQL connection. |
def post_optimization_step(self, batch_info, device, model, rollout):
""" Steps to take after optimization has been done"""
if batch_info.aggregate_batch_number % self.target_update_frequency == 0:
self.target_model.load_state_dict(model.state_dict())
self.target_model.eval() | Steps to take after optimization has been done |
def zonal_mean_column(num_lat=90, num_lev=30, water_depth=10., lat=None,
lev=None, **kwargs):
"""Creates two Domains with one water cell, a latitude axis and
a level/height axis.
* SlabOcean: one water cell and a latitude axis above
(similar to :func:`zonal_mean_surfa... | Creates two Domains with one water cell, a latitude axis and
a level/height axis.
* SlabOcean: one water cell and a latitude axis above
(similar to :func:`zonal_mean_surface`)
* Atmosphere: a latitude axis and a level/height axis (two dimensional)
**Function-call argument** \n
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.