code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def create(self, ip_access_control_list_sid):
"""
Create a new IpAccessControlListMappingInstance
:param unicode ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain
:returns: Newly created IpAccessControlListMappingInstance
:rtype: t... | Create a new IpAccessControlListMappingInstance
:param unicode ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain
:returns: Newly created IpAccessControlListMappingInstance
:rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_map... |
def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999):
"""Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or ... | Performs a user search using the Crowd search API.
https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource
Args:
entity_type: 'user' or 'group'
property_name: eg. 'email', 'name'
search_string: the string to search for... |
def get_redirect_target():
"""Get URL to redirect to and ensure that it is local."""
for target in request.values.get('next'), request.referrer:
if target and is_local_url(target):
return target | Get URL to redirect to and ensure that it is local. |
def filename(self):
"""Defines the name of the configuration file to use."""
# Needs to be done this way to be used by the project config.
# To fix on a later PR
self._filename = getattr(self, '_filename', None)
self._root_path = getattr(self, '_root_path', None)
... | Defines the name of the configuration file to use. |
def _find_zone_by_id(self, zone_id):
"""Return zone by id."""
if not self.zones:
return None
zone = list(filter(
lambda zone: zone.id == zone_id, self.zones))
return zone[0] if zone else None | Return zone by id. |
def find_two_letter_edits(word_string):
'''
Finds all possible two letter edits of word_string:
- Splitting word_string into two words at all character locations
- Deleting one letter at all character locations
- Switching neighbouring characters
- Replacing a character with every alphabetical l... | Finds all possible two letter edits of word_string:
- Splitting word_string into two words at all character locations
- Deleting one letter at all character locations
- Switching neighbouring characters
- Replacing a character with every alphabetical letter
- Inserting all possible alphabetical char... |
def copy(self, *args, **kwargs):
"""Copy this model element and contained elements if they exist."""
for slot in self.__slots__:
attr = getattr(self, slot)
if slot[0] == '_': # convert protected attribute name to public
slot = slot[1:]
if slot not in... | Copy this model element and contained elements if they exist. |
def __on_message(self, ws, msg):
"""This function is called whenever there is a message received from the server"""
msg = json.loads(msg)
logging.debug("ConnectorDB:WS: Msg '%s'", msg["stream"])
# Build the subcription key
stream_key = msg["stream"] + ":"
if "transform" ... | This function is called whenever there is a message received from the server |
def _attach_params(self, params, **kwargs):
"""Attach a list of parameters (or ParameterSet) to this ParameterSet.
:parameter list params: list of parameters, or ParameterSet
:parameter **kwargs: attributes to set for each parameter (ie tags)
"""
lst = params.to_list() if isinst... | Attach a list of parameters (or ParameterSet) to this ParameterSet.
:parameter list params: list of parameters, or ParameterSet
:parameter **kwargs: attributes to set for each parameter (ie tags) |
def _get_position_from_instance(self, instance, ordering):
"""
The position will be a tuple of values:
The QuerySet number inside of the QuerySetSequence.
Whatever the normal value taken from the ordering property gives.
"""
# Get the QuerySet number of the curr... | The position will be a tuple of values:
The QuerySet number inside of the QuerySetSequence.
Whatever the normal value taken from the ordering property gives. |
def _sort_locations(locations, expand_dir=False):
"""
Sort locations into "files" (archives) and "urls", and return
a pair of lists (files,urls)
"""
files = []
urls = []
# puts the url for the given file path into the appropriate list
def sort_path(path):... | Sort locations into "files" (archives) and "urls", and return
a pair of lists (files,urls) |
def GetCpuReservationMHz(self):
'''Retrieves the minimum processing power in MHz reserved for the virtual
machine. For information about setting a CPU reservation, see "Limits and
Reservations" on page 14.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetCpuReservationM... | Retrieves the minimum processing power in MHz reserved for the virtual
machine. For information about setting a CPU reservation, see "Limits and
Reservations" on page 14. |
def copy(self):
"""Return a copy of this actor with the same attribute values."""
health = self.health, self.health_max
r = self.r, self.r_max
g = self.g, self.g_max
b = self.b, self.b_max
y = self.y, self.y_max
x = self.x, self.x_max
m = self.m, self.m_ma... | Return a copy of this actor with the same attribute values. |
def _to_http_hosts(hosts: Union[Iterable[str], str]) -> List[str]:
"""Convert a string of whitespace or comma separated hosts into a list of hosts.
Hosts may also already be a list or other iterable.
Each host will be prefixed with 'http://' if it is not already there.
>>> _to_http_hosts('n1:4200,n2:4... | Convert a string of whitespace or comma separated hosts into a list of hosts.
Hosts may also already be a list or other iterable.
Each host will be prefixed with 'http://' if it is not already there.
>>> _to_http_hosts('n1:4200,n2:4200')
['http://n1:4200', 'http://n2:4200']
>>> _to_http_hosts('n1... |
def upload(self, array, fields=None, table="MyDB", configfile=None):
"""
Upload an array to a personal database using SOAP POST protocol.
http://skyserver.sdss3.org/casjobs/services/jobs.asmx?op=UploadData
"""
wsid=''
password=''
if configfile is None:
... | Upload an array to a personal database using SOAP POST protocol.
http://skyserver.sdss3.org/casjobs/services/jobs.asmx?op=UploadData |
def local_batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size,
shard_files, output_format):
"""See batch_predict"""
# from . import predict as predict_module
from .prediction import predict as predict_module
if mode == 'evaluation':
model_dir = os.path.jo... | See batch_predict |
def _handle_final_metric_data(self, data):
"""Call tuner to process final results
"""
id_ = data['parameter_id']
value = data['value']
if id_ in _customized_parameter_ids:
self.tuner.receive_customized_trial_result(id_, _trial_params[id_], value)
else:
... | Call tuner to process final results |
def append(self, header, f, _left=False):
"""Add a column to the table.
Args:
header (str):
Column header
f (function(datum)->str):
Makes the row string from the datum. Str returned by f should
have the same width as header.
... | Add a column to the table.
Args:
header (str):
Column header
f (function(datum)->str):
Makes the row string from the datum. Str returned by f should
have the same width as header. |
def SpiceUDREPU(f):
"""
Decorator for wrapping python functions in spice udrepu callback type
:param f: function to be wrapped
:type f: builtins.function
:return: wrapped udrepu function
:rtype: builtins.function
"""
@functools.wraps(f)
def wrapping_udrepu(beg, end, et):
f(be... | Decorator for wrapping python functions in spice udrepu callback type
:param f: function to be wrapped
:type f: builtins.function
:return: wrapped udrepu function
:rtype: builtins.function |
def plot_slippage_sensitivity(returns, positions, transactions,
ax=None, **kwargs):
"""
Plots curve relating per-dollar slippage to average annual returns.
Parameters
----------
returns : pd.Series
Timeseries of portfolio returns to be adjusted for various
... | Plots curve relating per-dollar slippage to average annual returns.
Parameters
----------
returns : pd.Series
Timeseries of portfolio returns to be adjusted for various
degrees of slippage.
positions : pd.DataFrame
Daily net position values.
- See full explanation in te... |
def validate(self):
"""
Ensure `self.path` has one of the extensions in `self.allowed_formats`.
"""
assert self.path, "{} must have a path".format(self.__class__.__name__)
ext = extract_path_ext(self.path, default_ext=self.subtitlesformat)
if ext not in self.allowed_forma... | Ensure `self.path` has one of the extensions in `self.allowed_formats`. |
def dictionary(self) -> dict:
"""Get a python dictionary of contents."""
self.config.read(self.filepath)
return self.config._sections | Get a python dictionary of contents. |
def download_song_by_id(self, song_id, song_name, folder='.'):
"""Download a song by id and save it to disk.
:params song_id: song id.
:params song_name: song name.
:params folder: storage path.
"""
try:
url = self.crawler.get_song_url(song_id)
i... | Download a song by id and save it to disk.
:params song_id: song id.
:params song_name: song name.
:params folder: storage path. |
def licenses_configured(name, licenses=None):
'''
Configures licenses on the cluster entity
Checks if each license exists on the server:
- if it doesn't, it creates it
Check if license is assigned to the cluster:
- if it's not assigned to the cluster:
- assign it to the clus... | Configures licenses on the cluster entity
Checks if each license exists on the server:
- if it doesn't, it creates it
Check if license is assigned to the cluster:
- if it's not assigned to the cluster:
- assign it to the cluster if there is space
- error if there's no sp... |
def _execute_wk(*args, input=None):
"""
Generate path for the wkhtmltopdf binary and execute command.
:param args: args to pass straight to subprocess.Popen
:return: stdout, stderr
"""
wk_args = (WK_PATH,) + args
return subprocess.run(wk_args, input=input, stdout=subprocess.PIPE, stderr=sub... | Generate path for the wkhtmltopdf binary and execute command.
:param args: args to pass straight to subprocess.Popen
:return: stdout, stderr |
def path(self):
"""Return path
:returns: path
:rtype: str
:raises: None
"""
p = os.path.normpath(self._path)
if p.endswith(':'):
p = p + os.path.sep
return p | Return path
:returns: path
:rtype: str
:raises: None |
def ssh_reachable(self, tries=None, propagate_fail=True):
"""
Check if the VM is reachable with ssh
Args:
tries(int): Number of tries to try connecting to the host
propagate_fail(bool): If set to true, this event will appear
in the log and fail the outter stag... | Check if the VM is reachable with ssh
Args:
tries(int): Number of tries to try connecting to the host
propagate_fail(bool): If set to true, this event will appear
in the log and fail the outter stage. Otherwise, it will be
discarded.
Returns:
b... |
def clear(self):
"""
Cleans up the manager. The manager can't be used after this method has
been called
"""
# Cancel timer
self.__cancel_timer()
self.__timer = None
self.__timer_args = None
self.__still_valid = False
self._value = None
... | Cleans up the manager. The manager can't be used after this method has
been called |
def next_k_array(a):
"""
Given an array `a` of k distinct nonnegative integers, sorted in
ascending order, return the next k-array in the lexicographic
ordering of the descending sequences of the elements [1]_. `a` is
modified in place.
Parameters
----------
a : ndarray(int, ndim=1)
... | Given an array `a` of k distinct nonnegative integers, sorted in
ascending order, return the next k-array in the lexicographic
ordering of the descending sequences of the elements [1]_. `a` is
modified in place.
Parameters
----------
a : ndarray(int, ndim=1)
Array of length k.
Retu... |
def autocorrelate(data, unbias=2, normalize=2):
"""
Compute the autocorrelation coefficients for time series data.
Here we use scipy.signal.correlate, but the results are the same as in
Yang, et al., 2012 for unbias=1:
"The autocorrelation coefficient refers to the correlation of a... | Compute the autocorrelation coefficients for time series data.
Here we use scipy.signal.correlate, but the results are the same as in
Yang, et al., 2012 for unbias=1:
"The autocorrelation coefficient refers to the correlation of a time
series with its own past or future values. iGAIT u... |
def chord(ref, est, **kwargs):
r'''Chord evaluation
Parameters
----------
ref : jams.Annotation
Reference annotation object
est : jams.Annotation
Estimated annotation object
kwargs
Additional keyword arguments
Returns
-------
scores : dict
Dictionary... | r'''Chord evaluation
Parameters
----------
ref : jams.Annotation
Reference annotation object
est : jams.Annotation
Estimated annotation object
kwargs
Additional keyword arguments
Returns
-------
scores : dict
Dictionary of scores, where the key is the me... |
def _attach_to_model(self, model):
"""
Check that the model can handle dynamic fields
"""
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so th... | Check that the model can handle dynamic fields |
def _revert_caffe2_pad(attr):
"""Removing extra padding from Caffe2."""
if len(attr) == 4:
attr = attr[:2]
elif len(attr) == 2:
pass
else:
raise ValueError("Invalid caffe2 type padding: {}".format(attr))
return attr | Removing extra padding from Caffe2. |
def paint( self, painter, option, widget ):
"""
Paints this item on the painter.
:param painter | <QPainter>
option | <QStyleOptionGraphicsItem>
widget | <QWidget>
"""
if ( self._rebuildRequired ):
self.... | Paints this item on the painter.
:param painter | <QPainter>
option | <QStyleOptionGraphicsItem>
widget | <QWidget> |
def list_experiments(project_path,
sort=None,
output=None,
filter_op=None,
info_keys=None):
"""Lists experiments in the directory subtree.
Args:
project_path (str): Directory where experiments are located.
C... | Lists experiments in the directory subtree.
Args:
project_path (str): Directory where experiments are located.
Corresponds to Experiment.local_dir.
sort (str): Key to sort by.
output (str): Name of file where output is saved.
filter_op (str): Filter operation in the form... |
def skip_if_empty(func):
"""
Decorator for validation functions which makes them pass if the value
passed in is the EMPTY sentinal value.
"""
@partial_safe_wraps(func)
def inner(value, *args, **kwargs):
if value is EMPTY:
return
else:
return func(value, *a... | Decorator for validation functions which makes them pass if the value
passed in is the EMPTY sentinal value. |
def _get_containers(self):
"""Return available containers."""
infos = self.native_conn.list_containers_info()
return [self.cont_cls(self, i['name'], i['count'], i['bytes'])
for i in infos] | Return available containers. |
def _sort(self, short_list, sorts):
"""
TAKE SHORTLIST, RETURN IT SORTED
:param short_list:
:param sorts: LIST OF SORTS TO PERFORM
:return:
"""
sort_values = self._index_columns(sorts)
# RECURSIVE SORTING
output = []
def _sort_more(short_... | TAKE SHORTLIST, RETURN IT SORTED
:param short_list:
:param sorts: LIST OF SORTS TO PERFORM
:return: |
def bls_snr(blsdict,
times,
mags,
errs,
assumeserialbls=False,
magsarefluxes=False,
sigclip=10.0,
npeaks=None,
perioddeltapercent=10,
ingressdurationfraction=0.1,
verbose=True):
'''Calculates the ... | Calculates the signal to noise ratio for each best peak in the BLS
periodogram, along with transit depth, duration, and refit period and epoch.
The following equation is used for SNR::
SNR = (transit model depth / RMS of LC with transit model subtracted)
* sqrt(number of points in transi... |
def setup_exchanges(app):
"""
Setup result exchange to route all tasks to platform queue.
"""
with app.producer_or_acquire() as P:
# Ensure all queues are noticed and configured with their
# appropriate exchange.
for q in app.amqp.queues.values():
P.maybe_declare(q) | Setup result exchange to route all tasks to platform queue. |
def get_base_wrappers(method='get', template_name='', predicates=(), wrappers=()):
""" basic View Wrappers used by view_config.
"""
wrappers += (preserve_view(MethodPredicate(method), *predicates),)
if template_name:
wrappers += (render_template(template_name),)
return wrappers | basic View Wrappers used by view_config. |
def connect(self):
''' instantiate objects / parse config file '''
# open config file for parsing
try:
settings = configparser.ConfigParser()
settings._interpolation = configparser.ExtendedInterpolation()
except Exception as err:
self.logger.error("Fai... | instantiate objects / parse config file |
def validate(self, model, checks=[]):
"""Use a defined schema to validate the given table."""
records = self.data.to_dict("records")
self.evaluate_report(
validate(records, headers=list(records[0]),
preset='table', schema=self.schema,
order_f... | Use a defined schema to validate the given table. |
def auprc(y_true, y_pred):
"""Area under the precision-recall curve
"""
y_true, y_pred = _mask_value_nan(y_true, y_pred)
return skm.average_precision_score(y_true, y_pred) | Area under the precision-recall curve |
def close(self):
"""Print error log and close session"""
if self.error_log and not self.quiet:
print("\nErrors occured:", file=sys.stderr)
for err in self.error_log:
print(err, file=sys.stderr)
self._session.close() | Print error log and close session |
def has_listener(self, evt_name, fn):
"""指定listener是否存在
:params evt_name: 事件名称
:params fn: 要注册的触发函数函数
"""
listeners = self.__get_listeners(evt_name)
return fn in listeners | 指定listener是否存在
:params evt_name: 事件名称
:params fn: 要注册的触发函数函数 |
def execute(opts, data, func, args, kwargs):
'''
Allow for the calling of execution modules via sudo.
This module is invoked by the minion if the ``sudo_user`` minion config is
present.
Example minion config:
.. code-block:: yaml
sudo_user: saltdev
Once this setting is made, any... | Allow for the calling of execution modules via sudo.
This module is invoked by the minion if the ``sudo_user`` minion config is
present.
Example minion config:
.. code-block:: yaml
sudo_user: saltdev
Once this setting is made, any execution module call done by the minion will be
run... |
def _default_hashfunc(content, hashbits):
"""
Default hash function is variable-length version of Python's builtin hash.
:param content: data that needs to hash.
:return: return a decimal number.
"""
if content == "":
return 0
x = ord(content[0]) << 7
m = 1000003
mask = 2 *... | Default hash function is variable-length version of Python's builtin hash.
:param content: data that needs to hash.
:return: return a decimal number. |
def resolve_outputs(self):
'''Resolve the names of outputs for this layer into shape tuples.'''
input_shape = None
for i, shape in enumerate(self._input_shapes.values()):
if i == 0:
input_shape = shape
if len(input_shape) != len(shape) or any(
... | Resolve the names of outputs for this layer into shape tuples. |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'document') and self.document is not None:
_dict['document'] = self.document._to_dict()
if hasattr(self, 'model_id') and self.model_id is not None:
_dict['model... | Return a json dictionary representing this model. |
def get_script(self):
"""
Gets the configuration script of the logical enclosure by ID or URI.
Return:
str: Configuration script.
"""
uri = "{}/script".format(self.data["uri"])
return self._helper.do_get(uri) | Gets the configuration script of the logical enclosure by ID or URI.
Return:
str: Configuration script. |
def renew_voms_proxy(passwd="", vo=None, lifetime="196:00"):
"""
Renews the voms proxy using a password *passwd*, an optional virtual organization name *vo*, and
a default *lifetime* of 8 days. The password is written to a temporary file first and piped into
the renewal commad to ensure it is not visibl... | Renews the voms proxy using a password *passwd*, an optional virtual organization name *vo*, and
a default *lifetime* of 8 days. The password is written to a temporary file first and piped into
the renewal commad to ensure it is not visible in the process list. |
def __parse_organizations(self, stream):
"""Parse organizations stream"""
for aliases in self.__parse_stream(stream):
# Parse identity
identity = self.__parse_alias(aliases[1])
uuid = identity.email
uid = self._identities.get(uuid, None)
if ... | Parse organizations stream |
def get_nameid_data(self):
"""
Gets the NameID Data provided by the SAML Response from the IdP
:returns: Name ID Data (Value, Format, NameQualifier, SPNameQualifier)
:rtype: dict
"""
nameid = None
nameid_data = {}
encrypted_id_data_nodes = self.__query_a... | Gets the NameID Data provided by the SAML Response from the IdP
:returns: Name ID Data (Value, Format, NameQualifier, SPNameQualifier)
:rtype: dict |
def get_section(value):
""" '*' digits
The formal BNF is more complicated because leading 0s are not allowed. We
check for that and add a defect. We also assume no CFWS is allowed between
the '*' and the digits, though the RFC is not crystal clear on that.
The caller should already have dealt wit... | '*' digits
The formal BNF is more complicated because leading 0s are not allowed. We
check for that and add a defect. We also assume no CFWS is allowed between
the '*' and the digits, though the RFC is not crystal clear on that.
The caller should already have dealt with leading CFWS. |
def create_index(self, index, index_type=GEO2D):
"""Create an index on a given attribute
:param str index: Attribute to set index on
:param str index_type: See PyMongo index types for further information, defaults to GEO2D index.
"""
self.logger.info("Adding %s index to stores o... | Create an index on a given attribute
:param str index: Attribute to set index on
:param str index_type: See PyMongo index types for further information, defaults to GEO2D index. |
def update_message(self, message_id, category_id, title, body,
extended_body, use_textile=False, private=False, notify=None):
"""
Updates an existing message, optionally sending notifications to a
selected list of people. Note that you can also upload files using
this function, b... | Updates an existing message, optionally sending notifications to a
selected list of people. Note that you can also upload files using
this function, but you have to format the request as
multipart/form-data. (See the ruby Basecamp API wrapper for an example
of how to do this.) |
def close(self, proto):
# pylint: disable=no-self-use
"""Closes a connection"""
try:
proto.sendClose()
except Exception as ex:
logger.exception("Failed to send close")
proto.reraise(ex) | Closes a connection |
def handler(*names, **kwargs):
"""Creates an Event Handler
This decorator can be applied to methods of classes derived from
:class:`circuits.core.components.BaseComponent`. It marks the method as a
handler for the events passed as arguments to the ``@handler`` decorator.
The events are specified by... | Creates an Event Handler
This decorator can be applied to methods of classes derived from
:class:`circuits.core.components.BaseComponent`. It marks the method as a
handler for the events passed as arguments to the ``@handler`` decorator.
The events are specified by their name.
The decorated method... |
def sample_discrete(self, state=None, n_steps=100, random_state=None):
r"""Generate a random sequence of states by propagating the model
using discrete time steps given by the model lagtime.
Parameters
----------
state : {None, ndarray, label}
Specify the starting st... | r"""Generate a random sequence of states by propagating the model
using discrete time steps given by the model lagtime.
Parameters
----------
state : {None, ndarray, label}
Specify the starting state for the chain.
``None``
Choose the initial sta... |
def sort(self, column_or_label, descending=False, distinct=False):
"""Return a Table of rows sorted according to the values in a column.
Args:
``column_or_label``: the column whose values are used for sorting.
``descending``: if True, sorting will be in descending, rather than
... | Return a Table of rows sorted according to the values in a column.
Args:
``column_or_label``: the column whose values are used for sorting.
``descending``: if True, sorting will be in descending, rather than
ascending order.
``distinct``: if True, repeated ... |
def init_state(self):
''' Sets the initial state of the state machine. '''
self.in_warc_response = False
self.in_http_response = False
self.in_payload = False | Sets the initial state of the state machine. |
def require_single_root_target(self):
"""If a single target was specified on the cmd line, returns that target.
Otherwise throws TaskError.
:API: public
"""
target_roots = self.context.target_roots
if len(target_roots) == 0:
raise TaskError('No target specified.')
elif len(target_roo... | If a single target was specified on the cmd line, returns that target.
Otherwise throws TaskError.
:API: public |
def setConfigurable(self, state):
"""
Sets whether or not this logger widget is configurable.
:param state | <bool>
"""
self._configurable = state
self._configButton.setVisible(state) | Sets whether or not this logger widget is configurable.
:param state | <bool> |
def invoked(self, ctx):
"""
Guacamole method used by the command ingredient.
:param ctx:
The guacamole context object. Context provides access to all
features of guacamole. The argparse ingredient adds the ``args``
attribute to it. That attribute contains the... | Guacamole method used by the command ingredient.
:param ctx:
The guacamole context object. Context provides access to all
features of guacamole. The argparse ingredient adds the ``args``
attribute to it. That attribute contains the result of parsing
command line ... |
def import_name(mod_name):
"""Import a module by module name.
@param mod_name: module name.
"""
try:
mod_obj_old = sys.modules[mod_name]
except KeyError:
mod_obj_old = None
if mod_obj_old is not None:
return mod_obj_old
__import__(mod_name)
mod_obj = sys.modul... | Import a module by module name.
@param mod_name: module name. |
def _on_hid_pnp(self, w_param, l_param):
"Process WM_DEVICECHANGE system messages"
new_status = "unknown"
if w_param == DBT_DEVICEARRIVAL:
# hid device attached
notify_obj = None
if int(l_param):
# Disable this error since pylint doesn't... | Process WM_DEVICECHANGE system messages |
def _is_image_sequenced(image):
"""Determine if the image is a sequenced image."""
try:
image.seek(1)
image.seek(0)
result = True
except EOFError:
result = False
return result | Determine if the image is a sequenced image. |
def get_valid_error(x1, x2=-1):
"""
Function that validates:
* x1 is possible to convert to numpy array
* x2 is possible to convert to numpy array (if exists)
* x1 and x2 have the same length (if both exist)
"""
# just error
if type(x2) == int and x2 == -1:
try:
... | Function that validates:
* x1 is possible to convert to numpy array
* x2 is possible to convert to numpy array (if exists)
* x1 and x2 have the same length (if both exist) |
def handle_setting_changed(sender, setting, value, enter, **kwargs): # pylint: disable=unused-argument
"""
Reinitialize handler implementation if a relevant setting changes
in e.g. application reconfiguration or during testing.
"""
if setting == 'AXES_HANDLER':
AxesProxyHandler.get_impleme... | Reinitialize handler implementation if a relevant setting changes
in e.g. application reconfiguration or during testing. |
def rgb2termhex(r: int, g: int, b: int) -> str:
""" Convert an rgb value to the nearest hex value that matches a term code.
The hex value will be one in `hex2term_map`.
"""
incs = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
res = []
parts = r, g, b
for part in parts:
if (part < 0) or (... | Convert an rgb value to the nearest hex value that matches a term code.
The hex value will be one in `hex2term_map`. |
def _g(self, z):
"""Helper function to solve Frank copula.
This functions encapsulates :math:`g_z = e^{-\\theta z} - 1` used on Frank copulas.
Argument:
z: np.ndarray
Returns:
np.ndarray
"""
return np.exp(np.multiply(-self.theta, z)) - 1 | Helper function to solve Frank copula.
This functions encapsulates :math:`g_z = e^{-\\theta z} - 1` used on Frank copulas.
Argument:
z: np.ndarray
Returns:
np.ndarray |
def certclone(chain, copy_extensions=False):
for i in range(len(chain)):
chain[i] = chain[i].to_cryptography()
newchain = []
'''
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
pubkey = key.public_key()
... | key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
pubkey = key.public_key() |
def __period_remaining(self):
'''
Return the period remaining for the current rate limit window.
:return: The remaing period.
:rtype: float
'''
elapsed = self.clock() - self.last_reset
return self.period - elapsed | Return the period remaining for the current rate limit window.
:return: The remaing period.
:rtype: float |
def parse_band_log(self, message):
"""Process incoming logging messages from the service."""
if "payload" in message and hasattr(message["payload"], "name"):
record = message["payload"]
for k in dir(record):
if k.startswith("workflows_exc_"):
s... | Process incoming logging messages from the service. |
def base_dict_to_string(base_dict):
"""
Converts a dictionary to a string. {'C': 12, 'A':4} gets converted to C:12;A:4
:param base_dict: Dictionary of bases and counts created by find_if_multibase
:return: String representing that dictionary.
"""
outstr = ''
# First, sort base_dict so that m... | Converts a dictionary to a string. {'C': 12, 'A':4} gets converted to C:12;A:4
:param base_dict: Dictionary of bases and counts created by find_if_multibase
:return: String representing that dictionary. |
def close(self, **kw):
"""
This asks Tor to close the underlying circuit object. See
:meth:`txtorcon.torstate.TorState.close_circuit`
for details.
You may pass keyword arguments to take care of any Flags Tor
accepts for the CLOSECIRCUIT command. Currently, this is only
... | This asks Tor to close the underlying circuit object. See
:meth:`txtorcon.torstate.TorState.close_circuit`
for details.
You may pass keyword arguments to take care of any Flags Tor
accepts for the CLOSECIRCUIT command. Currently, this is only
"IfUnused". So for example: circ.clo... |
def get_renderers(self):
"""
Instantiates and returns the list of renderers that this view can use.
"""
try:
source = self.get_object()
except (ImproperlyConfigured, APIException):
self.renderer_classes = [RENDERER_MAPPING[i] for i in self.__class__.render... | Instantiates and returns the list of renderers that this view can use. |
def wash_urlargd(form, content):
"""Wash the complete form based on the specification in content.
Content is a dictionary containing the field names as a
key, and a tuple (type, default) as value.
'type' can be list, unicode, legacy.wsgi.utils.StringField, int,
tuple, or legacy.wsgi.utils.Field (f... | Wash the complete form based on the specification in content.
Content is a dictionary containing the field names as a
key, and a tuple (type, default) as value.
'type' can be list, unicode, legacy.wsgi.utils.StringField, int,
tuple, or legacy.wsgi.utils.Field (for file uploads).
The specification... |
def _input_as_lines(self, data):
"""Writes data to tempfile and sets -i parameter
data -- list of lines, ready to be written to file
"""
if data:
self.Parameters['-i']\
.on(super(CD_HIT,self)._input_as_lines(data))
return '' | Writes data to tempfile and sets -i parameter
data -- list of lines, ready to be written to file |
def start_at(self, document_fields):
"""Start query at a cursor with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.start_at` for
more information on this method.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.Docu... | Start query at a cursor with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.start_at` for
more information on this method.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a document
... |
def fix_bam_header(job, bamfile, sample_type, univ_options, samtools_options, retained_chroms=None):
"""
Fix the bam header to remove the command line call. Failing to do this causes Picard to reject
the bam.
:param dict bamfile: The input bam file
:param str sample_type: Description of the sample... | Fix the bam header to remove the command line call. Failing to do this causes Picard to reject
the bam.
:param dict bamfile: The input bam file
:param str sample_type: Description of the sample to inject into the filename
:param dict univ_options: Dict of universal options used by almost all tools
... |
def generate_move(self, position):
"""
Returns valid and legal move given position
:type: position: Board
:rtype: Move
"""
while True:
print(position)
raw = input(str(self.color) + "\'s move \n")
move = converter.short_alg(raw, self.co... | Returns valid and legal move given position
:type: position: Board
:rtype: Move |
def get_assessments_offered(self):
"""Gets the assessment offered list resulting from the search.
return: (osid.assessment.AssessmentOfferedList) - the assessment
offered list
raise: IllegalState - the assessment offered list has already
been retrieved
*... | Gets the assessment offered list resulting from the search.
return: (osid.assessment.AssessmentOfferedList) - the assessment
offered list
raise: IllegalState - the assessment offered list has already
been retrieved
*compliance: mandatory -- This method must be i... |
def set_sim_data(inj, field, data):
"""Sets data of a SimInspiral instance."""
try:
sim_field = sim_inspiral_map[field]
except KeyError:
sim_field = field
# for tc, map to geocentric times
if sim_field == 'tc':
inj.geocent_end_time = int(data)
inj.geocent_end_time_ns ... | Sets data of a SimInspiral instance. |
def files(self, *args, **kwargs):
""" D.files() -> List of the files in this directory.
The elements of the list are Path objects.
This does not walk into subdirectories (see :meth:`walkfiles`).
Accepts parameters to :meth:`listdir`.
"""
return [p for p in self.listdir... | D.files() -> List of the files in this directory.
The elements of the list are Path objects.
This does not walk into subdirectories (see :meth:`walkfiles`).
Accepts parameters to :meth:`listdir`. |
def select(self, ids, do_emit=True, **kwargs):
"""Select some rows in the table.
By default, the `select` event is raised, unless `do_emit=False`.
"""
# Select the rows without emiting the event.
self.eval_js('table.select({}, false);'.format(dumps(ids)))
if do_emit:
... | Select some rows in the table.
By default, the `select` event is raised, unless `do_emit=False`. |
def configure_model(self, attrs, field_name):
'''
Hook for ResourceMeta class to call when initializing model class.
Saves fields obtained from resource class backlinks
'''
self.relationship = field_name
self._set_method_names(relationship=field_name)
if self.res_... | Hook for ResourceMeta class to call when initializing model class.
Saves fields obtained from resource class backlinks |
def Cp_material(ID, T=298.15):
r'''Returns heat capacity of a building, insulating, or refractory
material from tables in [1]_, [2]_, and [3]_. Heat capacity may or
may not be dependent on temperature depending on the source used. Function
must be provided with either a key to one of the dictionaries
... | r'''Returns heat capacity of a building, insulating, or refractory
material from tables in [1]_, [2]_, and [3]_. Heat capacity may or
may not be dependent on temperature depending on the source used. Function
must be provided with either a key to one of the dictionaries
`refractories`, `ASHRAE`, or `bu... |
def h(tagName, *children, **kwargs):
"""Takes an HTML Tag, children (string, array, or another element), and
attributes
Examples:
>>> h('div', [h('p', 'hey')])
<div><p>hey</p></div>
"""
attrs = {}
if 'attrs' in kwargs:
attrs = kwargs.pop('attrs')
attrs = attrs.copy()
... | Takes an HTML Tag, children (string, array, or another element), and
attributes
Examples:
>>> h('div', [h('p', 'hey')])
<div><p>hey</p></div> |
async def start(self):
"""Start api initialization."""
_LOGGER.debug('Initializing pyEight Version: %s', __version__)
await self.fetch_token()
if self._token is not None:
await self.fetch_device_list()
await self.assign_users()
return True
else... | Start api initialization. |
def adjoint(self):
"""Adjoint of the sampling operator, a `WeightedSumSamplingOperator`.
If each sampling point occurs only once, the adjoint consists
in inserting the given values into the output at the sampling
points. Duplicate sampling points are weighted with their
multipli... | Adjoint of the sampling operator, a `WeightedSumSamplingOperator`.
If each sampling point occurs only once, the adjoint consists
in inserting the given values into the output at the sampling
points. Duplicate sampling points are weighted with their
multiplicity.
Examples
... |
def SetTimelineOwner(self, username):
"""Sets the username of the user that should own the timeline.
Args:
username (str): username.
"""
self._timeline_owner = username
logger.info('Owner of the timeline: {0!s}'.format(self._timeline_owner)) | Sets the username of the user that should own the timeline.
Args:
username (str): username. |
def tube_hires(script, height=1.0, radius=None, radius1=None, radius2=None,
diameter=None, diameter1=None, diameter2=None, cir_segments=32,
rad_segments=1, height_segments=1, center=False,
simple_bottom=False, color=None):
"""Create a cylinder with user defined number of... | Create a cylinder with user defined number of segments |
def addcol(msname, colname=None, shape=None,
data_desc_type='array', valuetype=None, init_with=0, **kw):
""" add column to MS
msanme : MS to add colmn to
colname : column name
shape : shape
valuetype : data type
data_desc_type : 'scalar' for scalar elements and a... | add column to MS
msanme : MS to add colmn to
colname : column name
shape : shape
valuetype : data type
data_desc_type : 'scalar' for scalar elements and array for 'array' elements
init_with : value to initialise the column with |
def determine_deaths(self, event: Event):
"""Determines who dies each time step.
Parameters
----------
event :
An event object emitted by the simulation containing an index
representing the simulants affected by the event and timing
information.
... | Determines who dies each time step.
Parameters
----------
event :
An event object emitted by the simulation containing an index
representing the simulants affected by the event and timing
information. |
def load(self, ):
"""If the reference is in the scene but unloaded, load it.
.. Note:: Do not confuse this with reference or import. Load means that it is already referenced.
But the data from the reference was not read until now. Load loads the data from the reference.
This ... | If the reference is in the scene but unloaded, load it.
.. Note:: Do not confuse this with reference or import. Load means that it is already referenced.
But the data from the reference was not read until now. Load loads the data from the reference.
This will call :meth:`RefobjInterf... |
def serialize(self, private=False):
"""
Go from a
cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey
or EllipticCurvePublicKey instance to a JWK representation.
:param private: Whether we should include the private attributes or not.
:return: A JWK as a... | Go from a
cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey
or EllipticCurvePublicKey instance to a JWK representation.
:param private: Whether we should include the private attributes or not.
:return: A JWK as a dictionary |
def _get_mime_type(self, buff):
"""Get the MIME type for a given stream of bytes
:param buff: Stream of bytes
:type buff: bytes
:rtype: str
"""
if self._magic is not None:
return self._magic.id_buffer(buff)
else:
try:
ret... | Get the MIME type for a given stream of bytes
:param buff: Stream of bytes
:type buff: bytes
:rtype: str |
def gaussian_distribution(mean, stdev, num_pts=50):
""" get an x and y numpy.ndarray that spans the +/- 4
standard deviation range of a gaussian distribution with
a given mean and standard deviation. useful for plotting
Parameters
----------
mean : float
the mean of the distribution
... | get an x and y numpy.ndarray that spans the +/- 4
standard deviation range of a gaussian distribution with
a given mean and standard deviation. useful for plotting
Parameters
----------
mean : float
the mean of the distribution
stdev : float
the standard deviation of the distrib... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.