code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def expand_abbreviations(template, abbreviations):
"""Expand abbreviations in a template name.
:param template: The project template name.
:param abbreviations: Abbreviation definitions.
"""
if template in abbreviations:
return abbreviations[template]
# Split on colon. If there is no c... | Expand abbreviations in a template name.
:param template: The project template name.
:param abbreviations: Abbreviation definitions. |
def kill(self):
""" Kill the queue-consumer.
Unlike `stop()` any pending message ack or requeue-requests,
requests to remove providers, etc are lost and the consume thread is
asked to terminate as soon as possible.
"""
# greenlet has a magic attribute ``dead`` - pylint: ... | Kill the queue-consumer.
Unlike `stop()` any pending message ack or requeue-requests,
requests to remove providers, etc are lost and the consume thread is
asked to terminate as soon as possible. |
def __set_log_file_name(self):
"""Automatically set logFileName attribute"""
# ensure directory exists
dir, _ = os.path.split(self.__logFileBasename)
if len(dir) and not os.path.exists(dir):
os.makedirs(dir)
# create logFileName
self.__logFileName = self.__log... | Automatically set logFileName attribute |
def create_project(self, project_name, desc):
"""
Send POST to /projects creating a new project with the specified name and desc.
Raises DataServiceError on error.
:param project_name: str name of the project
:param desc: str description of the project
:return: requests.R... | Send POST to /projects creating a new project with the specified name and desc.
Raises DataServiceError on error.
:param project_name: str name of the project
:param desc: str description of the project
:return: requests.Response containing the successful result |
def sanitize_win_path(winpath):
'''
Remove illegal path characters for windows
'''
intab = '<>:|?*'
if isinstance(winpath, six.text_type):
winpath = winpath.translate(dict((ord(c), '_') for c in intab))
elif isinstance(winpath, six.string_types):
outtab = '_' * len(intab)
... | Remove illegal path characters for windows |
async def get_agents(self, addr=True, agent_cls=None):
"""Get addresses of all agents in all the slave environments.
This is a managing function for
:meth:`creamas.mp.MultiEnvironment.get_agents`.
.. note::
Since :class:`aiomas.rpc.Proxy` objects do not seem to handle
... | Get addresses of all agents in all the slave environments.
This is a managing function for
:meth:`creamas.mp.MultiEnvironment.get_agents`.
.. note::
Since :class:`aiomas.rpc.Proxy` objects do not seem to handle
(re)serialization, ``addr`` and ``agent_cls`` parameters a... |
def add_success(self, group=None, type_='', field='', description=''):
"""parse and append a success data param"""
group = group or '(200)'
group = int(group.lower()[1:-1])
self.retcode = self.retcode or group
if group != self.retcode:
raise ValueError('Two or more re... | parse and append a success data param |
def unpack_rsp(cls, rsp_pb):
"""Convert from PLS response to user response"""
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
order_id = str(rsp_pb.s2c.orderID)
modify_order_list = [{
'trd_env': TRADE.REV_TRD_ENV_MAP[rsp_pb.s2c.header.trdEnv],
... | Convert from PLS response to user response |
def get_enterprise_program_enrollment_page(self, request, enterprise_customer, program_details):
"""
Render Enterprise-specific program enrollment page.
"""
# Safely make the assumption that we can use the first authoring organization.
organizations = program_details['authoring_o... | Render Enterprise-specific program enrollment page. |
def generate_html_report(self, include_turtle=False, exclude_warning=False, list_auxiliary_line=False) -> str:
"""
Shows links to all classes and properties, a nice hierarchy of the classes, and then a nice
description of all the classes with all the properties that apply to it.
Example:... | Shows links to all classes and properties, a nice hierarchy of the classes, and then a nice
description of all the classes with all the properties that apply to it.
Example: http://www.cidoc-crm.org/sites/default/files/Documents/cidoc_crm_version_5.0.4.html
:param include_turtle: include turtle... |
def uninstall_hook(ctx):
""" Uninstall gitlint commit-msg hook. """
try:
lint_config = ctx.obj[0]
hooks.GitHookInstaller.uninstall_commit_msg_hook(lint_config)
# declare victory :-)
hook_path = hooks.GitHookInstaller.commit_msg_hook_path(lint_config)
click.echo(u"Successf... | Uninstall gitlint commit-msg hook. |
def confirm_login_allowed(self, user):
"""
Controls whether the given User may log in. This is a policy setting,
independent of end-user authentication. This default behavior is to
allow login by active users, and reject login by inactive users.
If the given user cannot log in, ... | Controls whether the given User may log in. This is a policy setting,
independent of end-user authentication. This default behavior is to
allow login by active users, and reject login by inactive users.
If the given user cannot log in, this method should raise a
``forms.ValidationError`... |
def global_position_int_cov_encode(self, time_boot_ms, time_utc, estimator_type, lat, lon, alt, relative_alt, vx, vy, vz, covariance):
'''
The filtered global position (e.g. fused GPS and accelerometers). The
position is in GPS-frame (right-handed, Z-up). It is
... | The filtered global position (e.g. fused GPS and accelerometers). The
position is in GPS-frame (right-handed, Z-up). It is
designed as scaled integer message since the
resolution of float is not sufficient. NOTE: This
message is intended for onboard netwo... |
def load_alias_hash(self):
"""
Load (create, if not exist) the alias hash file.
"""
# w+ creates the alias hash file if it does not exist
open_mode = 'r+' if os.path.exists(GLOBAL_ALIAS_HASH_PATH) else 'w+'
with open(GLOBAL_ALIAS_HASH_PATH, open_mode) as alias_config_hash... | Load (create, if not exist) the alias hash file. |
def cmdline_generator(param_iter, PathToBin=None, PathToCmd=None,
PathsToInputs=None, PathToOutput=None,
PathToStderr='/dev/null', PathToStdout='/dev/null',
UniqueOutputs=False, InputParam=None,
OutputParam=None):
"""Generates c... | Generates command lines that can be used in a cluster environment
param_iter : ParameterIterBase subclass instance
PathToBin : Absolute location primary command (i.e. Python)
PathToCmd : Absolute location of the command
PathsToInputs : Absolute location(s) of input file(s)
PathToOutput : Absolute l... |
def _set_show_bare_metal_state(self, v, load=False):
"""
Setter method for show_bare_metal_state, mapped from YANG variable /brocade_preprovision_rpc/show_bare_metal_state (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_bare_metal_state is considered as a priv... | Setter method for show_bare_metal_state, mapped from YANG variable /brocade_preprovision_rpc/show_bare_metal_state (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_bare_metal_state is considered as a private
method. Backends looking to populate this variable should... |
def sync_focus(self, *_):
"""
Focus the focused window from the pymux arrangement.
"""
# Pop-up displayed?
if self.display_popup:
self.app.layout.focus(self.layout_manager.popup_dialog)
return
# Confirm.
if self.confirm_text:
r... | Focus the focused window from the pymux arrangement. |
def from_dict(cls, d):
"""
Reconstructs the MultiWeightsChemenvStrategy object from a dict representation of the
MultipleAbundanceChemenvStrategy object created using the as_dict method.
:param d: dict representation of the MultiWeightsChemenvStrategy object
:return: MultiWeights... | Reconstructs the MultiWeightsChemenvStrategy object from a dict representation of the
MultipleAbundanceChemenvStrategy object created using the as_dict method.
:param d: dict representation of the MultiWeightsChemenvStrategy object
:return: MultiWeightsChemenvStrategy object |
def get_http_info_with_retriever(self, request, retriever):
"""
Exact method for getting http_info but with form data work around.
"""
urlparts = urlparse.urlsplit(request.url)
try:
data = retriever(request)
except Exception:
data = {}
re... | Exact method for getting http_info but with form data work around. |
def normal_cdf(x, mu=0, sigma=1):
"""Cumulative Normal Distribution Function.
:param x: scalar or array of real numbers.
:type x: numpy.ndarray, float
:param mu: Mean value. Default 0.
:type mu: float, numpy.ndarray
:param sigma: Standard deviation. Default 1.
:type sigma: float
:ret... | Cumulative Normal Distribution Function.
:param x: scalar or array of real numbers.
:type x: numpy.ndarray, float
:param mu: Mean value. Default 0.
:type mu: float, numpy.ndarray
:param sigma: Standard deviation. Default 1.
:type sigma: float
:returns: An approximation of the cdf of the ... |
def in_cwd():
"""
Return list of configs in current working directory.
If filename is ``.tmuxp.py``, ``.tmuxp.json``, ``.tmuxp.yaml``.
Returns
-------
list
configs in current working directory
"""
configs = []
for filename in os.listdir(os.getcwd()):
if filename.st... | Return list of configs in current working directory.
If filename is ``.tmuxp.py``, ``.tmuxp.json``, ``.tmuxp.yaml``.
Returns
-------
list
configs in current working directory |
def new(cls, user, provider, federated_id):
"""
Create a new login
:param user: AuthUser
:param provider: str - ie: facebook, twitter, ...
:param federated_id: str - an id associated to provider
:return:
"""
if cls.get_user(provider, federated_id):
... | Create a new login
:param user: AuthUser
:param provider: str - ie: facebook, twitter, ...
:param federated_id: str - an id associated to provider
:return: |
def reset_next_ids(classes):
"""
For each class in the list, if the .next_id attribute is not None
(meaning the table has an ID generator associated with it), set
.next_id to 0. This has the effect of reseting the ID generators,
and is useful in applications that process multiple documents and
add new rows to ta... | For each class in the list, if the .next_id attribute is not None
(meaning the table has an ID generator associated with it), set
.next_id to 0. This has the effect of reseting the ID generators,
and is useful in applications that process multiple documents and
add new rows to tables in those documents. Calling t... |
def stop_processes(self):
"""Iterate through all of the consumer processes shutting them down."""
self.set_state(self.STATE_SHUTTING_DOWN)
LOGGER.info('Stopping consumer processes')
signal.signal(signal.SIGABRT, signal.SIG_IGN)
signal.signal(signal.SIGALRM, signal.SIG_IGN)
... | Iterate through all of the consumer processes shutting them down. |
def _make_params_pb(params, param_types):
"""Helper for :meth:`execute_update`.
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``dml``.
:type param_types: dict[str -> Union[dict, .type... | Helper for :meth:`execute_update`.
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``dml``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Opt... |
def setup_packages():
'''
Custom setup for Corrfunc package.
Optional: Set compiler via 'CC=/path/to/compiler' or
'CC /path/to/compiler' or 'CC = /path/to/compiler'
All the CC options are removed from sys.argv after
being parsed.
'''
# protect the user in ... | Custom setup for Corrfunc package.
Optional: Set compiler via 'CC=/path/to/compiler' or
'CC /path/to/compiler' or 'CC = /path/to/compiler'
All the CC options are removed from sys.argv after
being parsed. |
def remove(self, point, **kwargs):
"""!
@brief Remove specified point from kd-tree.
@details It removes the first found node that satisfy to the input parameters. Make sure that
pair (point, payload) is unique for each node, othewise the first found is removed.
... | !
@brief Remove specified point from kd-tree.
@details It removes the first found node that satisfy to the input parameters. Make sure that
pair (point, payload) is unique for each node, othewise the first found is removed.
@param[in] point (list): Coordinates of ... |
def _Bern_to_Fierz_III_IV_V(C, qqqq):
"""From Bern to 4-quark Fierz basis for Classes III, IV and V.
`qqqq` should be of the form 'sbuc', 'sdcc', 'ucuu' etc."""
# 2nd != 4th, color-octet redundant
if qqqq in ['sbss', 'dbdd', 'dbds', 'sbsd', 'bsbd', 'dsdd']:
return {
'F' + qqqq + ... | From Bern to 4-quark Fierz basis for Classes III, IV and V.
`qqqq` should be of the form 'sbuc', 'sdcc', 'ucuu' etc. |
def clean_all(ctx, dry_run=False):
"""Clean up everything, even the precious stuff.
NOTE: clean task is executed first.
"""
cleanup_dirs(ctx.clean_all.directories or [], dry_run=dry_run)
cleanup_dirs(ctx.clean_all.extra_directories or [], dry_run=dry_run)
cleanup_files(ctx.clean_all.files or [],... | Clean up everything, even the precious stuff.
NOTE: clean task is executed first. |
def __lookup_builtin(name):
"""Lookup the parameter name and default parameter values for
builtin functions.
"""
global __builtin_functions
if __builtin_functions is None:
builtins = dict()
for proto in __builtins:
pos = proto.find('(')
name, params, defaults ... | Lookup the parameter name and default parameter values for
builtin functions. |
def post_build_time_coverage(self):
"""Collect all of the time coverage for the bundle."""
from ambry.util.datestimes import expand_to_years
years = set()
# From the bundle about
if self.metadata.about.time:
for year in expand_to_years(self.metadata.about.time):
... | Collect all of the time coverage for the bundle. |
def xerrorbar(self, canvas, X, Y, error, color=None, label=None, **kwargs):
"""
Make an errorbar along the xaxis for points at (X,Y) on the canvas.
if error is two dimensional, the lower error is error[:,0] and
the upper error is error[:,1]
the kwargs are plotting librar... | Make an errorbar along the xaxis for points at (X,Y) on the canvas.
if error is two dimensional, the lower error is error[:,0] and
the upper error is error[:,1]
the kwargs are plotting library specific kwargs! |
def sources(verbose=False):
'''
Return a list of available sources
verbose : boolean (False)
toggle verbose output
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' imgadm.sources
'''
ret = {}
cmd = 'imgadm sources -j'
res = __salt__['cmd.... | Return a list of available sources
verbose : boolean (False)
toggle verbose output
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' imgadm.sources |
def apply (self, img):
yup,uup,vup = self.getUpLimit()
ydwn,udwn,vdwn = self.getDownLimit()
''' We convert RGB as BGR because OpenCV
with RGB pass to YVU instead of YUV'''
yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
minValues = np.array([ydwn,udwn,vdw... | We convert RGB as BGR because OpenCV
with RGB pass to YVU instead of YUV |
def get_string(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[str]:
"""
Find a string as per :func:`get_what_follows`.
Args:
strings: see :func:`get_what_follows`
prefix: see :func:`get... | Find a string as per :func:`get_what_follows`.
Args:
strings: see :func:`get_what_follows`
prefix: see :func:`get_what_follows`
ignoreleadingcolon: if ``True``, restrict the result to what comes
after its first colon (and whitespace-strip that)
precedingline: see :func:`... |
def change_weibo_header(uri, headers, body):
"""Since weibo is a rubbish server, it does not follow the standard,
we need to change the authorization header for it."""
auth = headers.get('Authorization')
if auth:
auth = auth.replace('Bearer', 'OAuth2')
headers['Authorization'] = auth
... | Since weibo is a rubbish server, it does not follow the standard,
we need to change the authorization header for it. |
def _setEndpoint(self, location):
'''
Set the endpoint after when Salesforce returns the URL after successful login()
'''
# suds 0.3.7+ supports multiple wsdl services, but breaks setlocation :(
# see https://fedorahosted.org/suds/ticket/261
try:
self._sforce.set_options(location = locatio... | Set the endpoint after when Salesforce returns the URL after successful login() |
def get_market_summary(self, market):
"""
Used to get the last 24 hour summary of all active
exchanges in specific coin
Endpoint:
1.1 /public/getmarketsummary
2.0 /pub/Market/GetMarketSummary
:param market: String literal for the market(ex: BTC-XRP)
:typ... | Used to get the last 24 hour summary of all active
exchanges in specific coin
Endpoint:
1.1 /public/getmarketsummary
2.0 /pub/Market/GetMarketSummary
:param market: String literal for the market(ex: BTC-XRP)
:type market: str
:return: Summaries of active exchang... |
def RENEWING(self):
"""RENEWING state."""
logger.debug('In state: RENEWING')
self.current_state = STATE_RENEWING
if self.script is not None:
self.script.script_init(self.client.lease, self.current_state)
self.script.script_go()
else:
set_net(se... | RENEWING state. |
def contains(self, key_or_keypath):
""" Allows the 'in' operator to work for checking if a particular key (or keypath)
is inside the dictionary. """
if isinstance(key_or_keypath, list):
if len(key_or_keypath) == 0:
# empty list is root
return False
... | Allows the 'in' operator to work for checking if a particular key (or keypath)
is inside the dictionary. |
def save(self, filename, binary=True):
"""
Writes a ``MultiBlock`` dataset to disk.
Written file may be an ASCII or binary vtm file.
Parameters
----------
filename : str
Filename of mesh to be written. File type is inferred from
the extension of... | Writes a ``MultiBlock`` dataset to disk.
Written file may be an ASCII or binary vtm file.
Parameters
----------
filename : str
Filename of mesh to be written. File type is inferred from
the extension of the filename unless overridden with
ftype. Ca... |
def create_keep_package(cls, package_name, recursive=True):
"""Convenience constructor for a package keep rule.
Essentially equivalent to just using ``shading_keep('package_name.**')``.
:param string package_name: Package name to keep (eg, ``org.pantsbuild.example``).
:param bool recursive: Whether to... | Convenience constructor for a package keep rule.
Essentially equivalent to just using ``shading_keep('package_name.**')``.
:param string package_name: Package name to keep (eg, ``org.pantsbuild.example``).
:param bool recursive: Whether to keep everything under any subpackage of ``package_name``,
or... |
def _certify_int_param(value, negative=True, required=False):
"""
A private certifier (to `certifiable`) to certify integers from `certify_int`.
:param int value:
The value to certify is an integer.
:param bool negative:
If the value can be negative. Default=False.
:param bool requi... | A private certifier (to `certifiable`) to certify integers from `certify_int`.
:param int value:
The value to certify is an integer.
:param bool negative:
If the value can be negative. Default=False.
:param bool required:
If the value is required. Default=False.
:raises Certifi... |
def to_python(value, seen=None):
"""Reify values to their Python equivalents.
Does recursion detection, failing when that happens.
"""
seen = seen or set()
if isinstance(value, framework.TupleLike):
if value.ident in seen:
raise RecursionException('to_python: infinite recursion while evaluating %r'... | Reify values to their Python equivalents.
Does recursion detection, failing when that happens. |
def update_metadata(self, scaling_group, metadata):
"""
Adds the given metadata dict to the existing metadata for the scaling
group.
"""
if not isinstance(scaling_group, ScalingGroup):
scaling_group = self.get(scaling_group)
curr_meta = scaling_group.metadata
... | Adds the given metadata dict to the existing metadata for the scaling
group. |
def rotate(l, steps=1):
r"""Rotates a list `l` `steps` to the left. Accepts
`steps` > `len(l)` or < 0.
>>> rotate([1,2,3])
[2, 3, 1]
>>> rotate([1,2,3,4],-2)
[3, 4, 1, 2]
>>> rotate([1,2,3,4],-5)
[4, 1, 2, 3]
>>> rotate([1,2,3,4],1)
[2, 3, 4, 1]
>>> l = [1,2,3]; rotate(l) is... | r"""Rotates a list `l` `steps` to the left. Accepts
`steps` > `len(l)` or < 0.
>>> rotate([1,2,3])
[2, 3, 1]
>>> rotate([1,2,3,4],-2)
[3, 4, 1, 2]
>>> rotate([1,2,3,4],-5)
[4, 1, 2, 3]
>>> rotate([1,2,3,4],1)
[2, 3, 4, 1]
>>> l = [1,2,3]; rotate(l) is not l
True |
def get_columns(self, df, usage, columns=None):
"""
Returns a `data_frame.columns`.
:param df: dataframe to select columns from
:param usage: should be a value from [ALL, INCLUDE, EXCLUDE].
this value only makes sense if attr `columns` is also set.
... | Returns a `data_frame.columns`.
:param df: dataframe to select columns from
:param usage: should be a value from [ALL, INCLUDE, EXCLUDE].
this value only makes sense if attr `columns` is also set.
otherwise, should be used with default value ALL.
... |
def remap_name(name_generator, names, table=None):
"""
Produces a series of variable assignments in the form of::
<obfuscated name> = <some identifier>
for each item in *names* using *name_generator* to come up with the
replacement names.
If *table* is provided, replacements will be looke... | Produces a series of variable assignments in the form of::
<obfuscated name> = <some identifier>
for each item in *names* using *name_generator* to come up with the
replacement names.
If *table* is provided, replacements will be looked up there before
generating a new unique name. |
def explain_weights_lightgbm(lgb,
vec=None,
top=20,
target_names=None, # ignored
targets=None, # ignored
feature_names=None,
feature_re=None,
... | Return an explanation of an LightGBM estimator (via scikit-learn wrapper
LGBMClassifier or LGBMRegressor) as feature importances.
See :func:`eli5.explain_weights` for description of
``top``, ``feature_names``,
``feature_re`` and ``feature_filter`` parameters.
``target_names`` and ``targets`` param... |
def add_send_last_message(self, connection, send_last_message):
"""Adds a send_last_message function to the Dispatcher's
dictionary of functions indexed by connection.
Args:
connection (str): A locally unique identifier
provided by the receiver of messages.
... | Adds a send_last_message function to the Dispatcher's
dictionary of functions indexed by connection.
Args:
connection (str): A locally unique identifier
provided by the receiver of messages.
send_last_message (fn): The method that should be called
... |
def degree_elevation(degree, ctrlpts, **kwargs):
""" Computes the control points of the rational/non-rational spline after degree elevation.
Implementation of Eq. 5.36 of The NURBS Book by Piegl & Tiller, 2nd Edition, p.205
Keyword Arguments:
* ``num``: number of degree elevations
Please note... | Computes the control points of the rational/non-rational spline after degree elevation.
Implementation of Eq. 5.36 of The NURBS Book by Piegl & Tiller, 2nd Edition, p.205
Keyword Arguments:
* ``num``: number of degree elevations
Please note that degree elevation algorithm can only operate on Bezi... |
def convert(filename,
num_questions=None,
solution=False,
pages_per_q=DEFAULT_PAGES_PER_Q,
folder='question_pdfs',
output='gradescope.pdf',
zoom=1):
"""
Public method that exports nb to PDF and pads all the questions.
If num_questions ... | Public method that exports nb to PDF and pads all the questions.
If num_questions is specified, will also check the final PDF for missing
questions.
If the output font size is too small/large, increase or decrease the zoom
argument until the size looks correct.
If solution=True, we'll export solu... |
def add_broker(self, broker):
"""Add broker to current broker-list."""
if broker not in self._brokers:
self._brokers.add(broker)
else:
self.log.warning(
'Broker {broker_id} already present in '
'replication-group {rg_id}'.format(
... | Add broker to current broker-list. |
def _update_names(self):
"""Update the derived names"""
d = dict(
table=self.table_name,
time=self.time,
space=self.space,
grain=self.grain,
variant=self.variant,
segment=self.segment
)
assert self.dataset
... | Update the derived names |
def store_user_documents(user_document_gen, client, mongo_database_name, mongo_collection_name):
"""
Stores Twitter list objects that a Twitter user is a member of in different mongo collections.
Inputs: - user_document_gen: A python generator that yields a Twitter user id and an associated document list.
... | Stores Twitter list objects that a Twitter user is a member of in different mongo collections.
Inputs: - user_document_gen: A python generator that yields a Twitter user id and an associated document list.
- client: A pymongo MongoClient object.
- mongo_database_name: The name of a Mongo da... |
def init_tasks():
"""
Performs basic setup before any of the tasks are run. All tasks needs to
run this before continuing. It only fires once.
"""
# Make sure exist are set
if "exists" not in env:
env.exists = exists
if "run" not in env:
env.run = run
if "cd" not in en... | Performs basic setup before any of the tasks are run. All tasks needs to
run this before continuing. It only fires once. |
def get_ip_reports(self, ips):
"""Retrieves the most recent VT info for a set of ips.
Args:
ips: list of IPs.
Returns:
A dict with the IP as key and the VT report as value.
"""
api_name = 'virustotal-ip-address-reports'
(all_responses, ips) = sel... | Retrieves the most recent VT info for a set of ips.
Args:
ips: list of IPs.
Returns:
A dict with the IP as key and the VT report as value. |
def is_visible(self, selector):
"""Check if an element is visible in the dom or not
This method will check if the element is displayed or not
This method might (according
to the config highlight:element_is_visible)
highlight the element if it is visible
This method won... | Check if an element is visible in the dom or not
This method will check if the element is displayed or not
This method might (according
to the config highlight:element_is_visible)
highlight the element if it is visible
This method won't wait until the element is visible or pre... |
def models(cls, api_version=DEFAULT_API_VERSION):
"""Module depends on the API version:
* 2016-09-01: :mod:`v2016_09_01.models<azure.mgmt.resource.links.v2016_09_01.models>`
"""
if api_version == '2016-09-01':
from .v2016_09_01 import models
return models
... | Module depends on the API version:
* 2016-09-01: :mod:`v2016_09_01.models<azure.mgmt.resource.links.v2016_09_01.models>` |
def to_pandas_dataframe(self, sample_column=False):
"""Convert a SampleSet to a Pandas DataFrame
Returns:
:obj:`pandas.DataFrame`
Examples:
>>> samples = dimod.SampleSet.from_samples([{'a': -1, 'b': +1, 'c': -1},
... {... | Convert a SampleSet to a Pandas DataFrame
Returns:
:obj:`pandas.DataFrame`
Examples:
>>> samples = dimod.SampleSet.from_samples([{'a': -1, 'b': +1, 'c': -1},
... {'a': -1, 'b': -1, 'c': +1}],
... ... |
def vim_enter(self, filename):
"""Set up EnsimeClient when vim enters.
This is useful to start the EnsimeLauncher as soon as possible."""
success = self.setup(True, False)
if success:
self.editor.message("start_message") | Set up EnsimeClient when vim enters.
This is useful to start the EnsimeLauncher as soon as possible. |
def sample(self, withReplacement=None, fraction=None, seed=None):
"""Returns a sampled subset of this :class:`DataFrame`.
:param withReplacement: Sample with replacement or not (default False).
:param fraction: Fraction of rows to generate, range [0.0, 1.0].
:param seed: Seed for sampli... | Returns a sampled subset of this :class:`DataFrame`.
:param withReplacement: Sample with replacement or not (default False).
:param fraction: Fraction of rows to generate, range [0.0, 1.0].
:param seed: Seed for sampling (default a random seed).
.. note:: This is not guaranteed to prov... |
def eigenvectors(T, k=None, right=True, ncv=None, reversible=False, mu=None):
r"""Compute eigenvectors of given transition matrix.
Parameters
----------
T : scipy.sparse matrix
Transition matrix (stochastic matrix).
k : int (optional) or array-like
For integer k compute the first k ... | r"""Compute eigenvectors of given transition matrix.
Parameters
----------
T : scipy.sparse matrix
Transition matrix (stochastic matrix).
k : int (optional) or array-like
For integer k compute the first k eigenvalues of T
else return those eigenvector sepcified by integer indice... |
def path(self):
"""Return the full path of the current object."""
names = []
obj = self
while obj:
names.insert(0, obj.name)
obj = obj.parent_dir
sep = self.filesystem._path_separator(self.name)
if names[0] == sep:
names.pop(0)
... | Return the full path of the current object. |
def save(self, to_save, **kwargs):
"""save method
"""
check = kwargs.pop('check', True)
if check:
self._valid_record(to_save)
if '_id' in to_save:
self.__collect.replace_one(
{'_id': to_save['_id']}, to_save, **kwargs)
return to... | save method |
def get_data(start, end, username=None, password=None,
data_path=os.path.abspath(".")+'/tmp_data'):
"""**Download data (badly) from Blitzorg**
Using a specified time stamp for start and end, data is downloaded at a
default frequency (10 minute intervals). If a directory called data is not
... | **Download data (badly) from Blitzorg**
Using a specified time stamp for start and end, data is downloaded at a
default frequency (10 minute intervals). If a directory called data is not
present, it will be added to the cwd as the target for the downloads.
This is probably a bad idea however. It is muc... |
def hash_folder(folder, regex='[!_]*'):
"""
Get the md5 sum of each file in the folder and return to the user
:param folder: the folder to compute the sums over
:param regex: an expression to limit the files we match
:return:
Note: by default we will hash every file in the folder
Note: we... | Get the md5 sum of each file in the folder and return to the user
:param folder: the folder to compute the sums over
:param regex: an expression to limit the files we match
:return:
Note: by default we will hash every file in the folder
Note: we will not match anything that starts with an undersc... |
def convert_to_duckling_language_id(cls, lang):
"""Ensure a language identifier has the correct duckling format and is supported."""
if lang is not None and cls.is_supported(lang):
return lang
elif lang is not None and cls.is_supported(lang + "$core"): # Support ISO 639-1 Language... | Ensure a language identifier has the correct duckling format and is supported. |
def align_and_build_tree(seqs, moltype, best_tree=False, params=None):
"""Returns an alignment and a tree from Sequences object seqs.
seqs: a cogent.core.alignment.SequenceCollection object, or data that can
be used to build one.
moltype: cogent.core.moltype.MolType object
best_tree: if True (def... | Returns an alignment and a tree from Sequences object seqs.
seqs: a cogent.core.alignment.SequenceCollection object, or data that can
be used to build one.
moltype: cogent.core.moltype.MolType object
best_tree: if True (default:False), uses a slower but more accurate
algorithm to build the tree.
... |
def year(columns, name=None):
"""
Creates the grammar for a field containing a year.
:param columns: the number of columns for the year
:param name: the name of the field
:return:
"""
if columns < 0:
# Can't have negative size
raise BaseException()
field = numeric(colu... | Creates the grammar for a field containing a year.
:param columns: the number of columns for the year
:param name: the name of the field
:return: |
def load_configuration_from_file(directory, args):
"""Return new ``args`` with configuration loaded from file."""
args = copy.copy(args)
directory_or_file = directory
if args.config is not None:
directory_or_file = args.config
options = _get_options(directory_or_file, debug=args.debug)
... | Return new ``args`` with configuration loaded from file. |
def _send(self):
""" Send all queued messages to the server.
"""
data = self.output_buffer.view()
if not data:
return
if self.closed():
raise self.Error("Failed to write to closed connection {!r}".format(self.server.address))
if self.defunct():
... | Send all queued messages to the server. |
def label_contours(self, intervals, window=150, hop=30):
"""
In a very flowy contour, it is not trivial to say which pitch value corresponds
to what interval. This function labels pitch contours with intervals by guessing
from the characteristics of the contour and its melodic context.... | In a very flowy contour, it is not trivial to say which pitch value corresponds
to what interval. This function labels pitch contours with intervals by guessing
from the characteristics of the contour and its melodic context.
:param window: the size of window over which the context is gauged,... |
def subdomain_row_factory(cls, cursor, row):
"""
Dict row factory for subdomains
"""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d | Dict row factory for subdomains |
def ShouldRetry(self, exception):
"""Returns true if should retry based on the passed-in exception.
:param (errors.HTTPFailure instance) exception:
:rtype:
boolean
"""
if self.current_retry_attempt_count < self._max_retry_attempt_count:
self.current_ret... | Returns true if should retry based on the passed-in exception.
:param (errors.HTTPFailure instance) exception:
:rtype:
boolean |
def orientation_angle(im, approxangle=None, *, isshiftdft=False, truesize=None,
rotateAngle=None):
"""Give the highest contribution to the orientation
Parameters
----------
im: 2d array
The image
approxangle: number, optional
The approximate angle (None if unkn... | Give the highest contribution to the orientation
Parameters
----------
im: 2d array
The image
approxangle: number, optional
The approximate angle (None if unknown)
isshiftdft: Boolean, default False
True if the image has been processed (DFT, fftshift)
truesize: 2 numbers... |
def irods_filepath(det_id, run_id):
"""Generate the iRODS filepath for given detector (O)ID and run ID"""
data_path = "/in2p3/km3net/data/raw/sea"
from km3pipe.db import DBManager
if not isinstance(det_id, int):
dts = DBManager().detectors
det_id = int(dts[dts.OID == det_id].SERIALNUMBER... | Generate the iRODS filepath for given detector (O)ID and run ID |
def restore(self, workspace_uuid):
"""
Restore the workspace to the given workspace_uuid.
If workspace_uuid is None then create a new workspace and use it.
"""
workspace = next((workspace for workspace in self.document_model.workspaces if workspace.uuid == workspace_uuid... | Restore the workspace to the given workspace_uuid.
If workspace_uuid is None then create a new workspace and use it. |
def create_manage_py(self, apps):
"""Creates manage.py file, with a given list of installed apps.
:param list apps:
"""
self.logger.debug('Creating manage.py ...')
with open(self._get_manage_py_path(), mode='w') as f:
south_migration_modules = []
for app ... | Creates manage.py file, with a given list of installed apps.
:param list apps: |
def subgrid_kernel(kernel, subgrid_res, odd=False, num_iter=100):
"""
creates a higher resolution kernel with subgrid resolution as an interpolation of the original kernel in an
iterative approach
:param kernel: initial kernel
:param subgrid_res: subgrid resolution required
:return: kernel with... | creates a higher resolution kernel with subgrid resolution as an interpolation of the original kernel in an
iterative approach
:param kernel: initial kernel
:param subgrid_res: subgrid resolution required
:return: kernel with higher resolution (larger) |
async def fetch(self, method, url, params=None, headers=None, data=None):
"""Make an HTTP request.
Automatically uses configured HTTP proxy, and adds Google authorization
header and cookies.
Failures will be retried MAX_RETRIES times before raising NetworkError.
Args:
... | Make an HTTP request.
Automatically uses configured HTTP proxy, and adds Google authorization
header and cookies.
Failures will be retried MAX_RETRIES times before raising NetworkError.
Args:
method (str): Request method.
url (str): Request URL.
par... |
def com_google_fonts_check_font_copyright(ttFont):
"""Copyright notices match canonical pattern in fonts"""
import re
from fontbakery.utils import get_name_entry_strings
failed = False
for string in get_name_entry_strings(ttFont, NameID.COPYRIGHT_NOTICE):
does_match = re.search(r'Copyright [0-9]{4} The .... | Copyright notices match canonical pattern in fonts |
def _get_name(self):
""" Property getter.
"""
if (self.tail_node is not None) and (self.head_node is not None):
return "%s %s %s" % (self.tail_node.ID, self.conn,
self.head_node.ID)
else:
return "Edge" | Property getter. |
def convex_hull(features):
"""Returns points on convex hull of an array of points in CCW order."""
points = sorted([s.point() for s in features])
l = reduce(_keep_left, points, [])
u = reduce(_keep_left, reversed(points), [])
return l.extend(u[i] for i in xrange(1, len(u) - 1)) or l | Returns points on convex hull of an array of points in CCW order. |
def validate_event_type(sender, event, created):
"""Verify that the Event's code is a valid one."""
if event.code not in sender.event_codes():
raise ValueError("The Event.code '{}' is not a valid Event "
"code.".format(event.code)) | Verify that the Event's code is a valid one. |
def _create_buffer(self):
"""
Create the `Buffer` for the Python input.
"""
python_buffer = Buffer(
name=DEFAULT_BUFFER,
complete_while_typing=Condition(lambda: self.complete_while_typing),
enable_history_search=Condition(lambda: self.enable_history_se... | Create the `Buffer` for the Python input. |
def unlock(arguments):
"""Unlock the database."""
import redis
u = coil.utils.ask("Redis URL", "redis://localhost:6379/0")
db = redis.StrictRedis.from_url(u)
db.set('site:lock', 0)
print("Database unlocked.")
return 0 | Unlock the database. |
def get_gui_hint(self, hint):
"""Returns the value for specified gui hint (or a sensible default value,
if this argument doesn't specify the hint).
Args:
hint: name of the hint to get value for
Returns:
value of the hint specified in yaml or a sensible default
... | Returns the value for specified gui hint (or a sensible default value,
if this argument doesn't specify the hint).
Args:
hint: name of the hint to get value for
Returns:
value of the hint specified in yaml or a sensible default |
def hessian(self, x, y, n_sersic, R_sersic, k_eff, center_x=0, center_y=0):
"""
returns Hessian matrix of function d^2f/dx^2, d^f/dy^2, d^2/dxdy
"""
x_ = x - center_x
y_ = y - center_y
r = np.sqrt(x_**2 + y_**2)
if isinstance(r, int) or isinstance(r, float):
... | returns Hessian matrix of function d^2f/dx^2, d^f/dy^2, d^2/dxdy |
def create_release():
"""Creates a new release candidate for a build."""
build = g.build
release_name = request.form.get('release_name')
utils.jsonify_assert(release_name, 'release_name required')
url = request.form.get('url')
utils.jsonify_assert(release_name, 'url required')
release = mod... | Creates a new release candidate for a build. |
def add_event(self, rule, callback):
"""Adds an event to the algorithm's EventManager.
Parameters
----------
rule : EventRule
The rule for when the callback should be triggered.
callback : callable[(context, data) -> None]
The function to execute when the... | Adds an event to the algorithm's EventManager.
Parameters
----------
rule : EventRule
The rule for when the callback should be triggered.
callback : callable[(context, data) -> None]
The function to execute when the rule is triggered. |
def _calculate_unpack_filter(cls, includes=None, excludes=None, spec=None):
"""Take regex patterns and return a filter function.
:param list includes: List of include patterns to pass to _file_filter.
:param list excludes: List of exclude patterns to pass to _file_filter.
"""
include_patterns = cls... | Take regex patterns and return a filter function.
:param list includes: List of include patterns to pass to _file_filter.
:param list excludes: List of exclude patterns to pass to _file_filter. |
def deployAll(self):
'''
Deploys all the items from the vault. Useful after a format
'''
targets = [Target.getTarget(iid) for iid, n, p in self.db.listTargets()]
for target in targets:
target.deploy()
verbose('Deploy all complete') | Deploys all the items from the vault. Useful after a format |
def _separate_epochs(activity_data, epoch_list):
""" create data epoch by epoch
Separate data into epochs of interest specified in epoch_list
and z-score them for computing correlation
Parameters
----------
activity_data: list of 2D array in shape [nVoxels, nTRs]
the masked activity da... | create data epoch by epoch
Separate data into epochs of interest specified in epoch_list
and z-score them for computing correlation
Parameters
----------
activity_data: list of 2D array in shape [nVoxels, nTRs]
the masked activity data organized in voxel*TR formats of all subjects
epoc... |
def fetch_url(url, method='GET', user_agent='django-oembed', timeout=SOCKET_TIMEOUT):
"""
Fetch response headers and data from a URL, raising a generic exception
for any kind of failure.
"""
sock = httplib2.Http(timeout=timeout)
request_headers = {
'User-Agent': user_agent,
'Acce... | Fetch response headers and data from a URL, raising a generic exception
for any kind of failure. |
def exports(self):
"""
:rtype: twilio.rest.preview.bulk_exports.export.ExportList
"""
if self._exports is None:
self._exports = ExportList(self)
return self._exports | :rtype: twilio.rest.preview.bulk_exports.export.ExportList |
def create_dashboard(self, name):
'''
**Description**
Creates an empty dashboard. You can then add panels by using ``add_dashboard_panel``.
**Arguments**
- **name**: the name of the dashboard that will be created.
**Success Return Value**
A dictionar... | **Description**
Creates an empty dashboard. You can then add panels by using ``add_dashboard_panel``.
**Arguments**
- **name**: the name of the dashboard that will be created.
**Success Return Value**
A dictionary showing the details of the new dashboard.
*... |
def wx_menu(self):
'''return a wx.Menu() for this menu'''
from MAVProxy.modules.lib.wx_loader import wx
menu = wx.Menu()
for i in range(len(self.items)):
m = self.items[i]
m._append(menu)
return menu | return a wx.Menu() for this menu |
def sign_up(self):
"""Signs up a participant for the experiment.
This is done using a POST request to the /participant/ endpoint.
"""
self.log("Bot player signing up.")
self.subscribe_to_quorum_channel()
while True:
url = (
"{host}/participant... | Signs up a participant for the experiment.
This is done using a POST request to the /participant/ endpoint. |
def dict_to_vtk(data, path='./dictvtk', voxel_size=1, origin=(0, 0, 0)):
r"""
Accepts multiple images as a dictionary and compiles them into a vtk file
Parameters
----------
data : dict
A dictionary of *key: value* pairs, where the *key* is the name of the
scalar property stored in ... | r"""
Accepts multiple images as a dictionary and compiles them into a vtk file
Parameters
----------
data : dict
A dictionary of *key: value* pairs, where the *key* is the name of the
scalar property stored in each voxel of the array stored in the
corresponding *value*.
path... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.