code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def edit_inputs(client, workflow):
"""Edit workflow inputs."""
types = {
'int': int,
'string': str,
'File': lambda x: File(path=Path(x).resolve()),
}
for input_ in workflow.inputs:
convert = types.get(input_.type, str)
input_.default = convert(
click.p... | Edit workflow inputs. |
def emit(self, action, payload=None, retry=0):
"""Emit action with payload.
:param action: an action slug
:param payload: data, default {}
:param retry: integer, default 0.
:return: information in form of dict.
"""
payload = payload or {}
if retry:
... | Emit action with payload.
:param action: an action slug
:param payload: data, default {}
:param retry: integer, default 0.
:return: information in form of dict. |
def _load_image_labels(self):
"""
preprocess all ground-truths
Returns:
----------
labels packed in [num_images x max_num_objects x 5] tensor
"""
temp = []
# load ground-truth from xml annotations
for idx in self.image_set_index:
labe... | preprocess all ground-truths
Returns:
----------
labels packed in [num_images x max_num_objects x 5] tensor |
def hierarchy_spectrum(mg, filter=True, plot=False):
"""Examine a multilevel hierarchy's spectrum.
Parameters
----------
mg { pyamg multilevel hierarchy }
e.g. generated with smoothed_aggregation_solver(...) or
ruge_stuben_solver(...)
Returns
-------
(1) table to standard o... | Examine a multilevel hierarchy's spectrum.
Parameters
----------
mg { pyamg multilevel hierarchy }
e.g. generated with smoothed_aggregation_solver(...) or
ruge_stuben_solver(...)
Returns
-------
(1) table to standard out detailing the spectrum of each level in mg
(2) if plo... |
def assert_image_exists(self, pattern, timeout=20.0, **kwargs):
"""
Assert if image exists
Args:
- pattern: image filename # not support pattern for now
- timeout (float): seconds
- safe (bool): not raise assert error even throung failed.
"""
p... | Assert if image exists
Args:
- pattern: image filename # not support pattern for now
- timeout (float): seconds
- safe (bool): not raise assert error even throung failed. |
def validate_unit_process_ids(self, expected, actual):
"""Validate process id quantities for services on units."""
self.log.debug('Checking units for running processes...')
self.log.debug('Expected PIDs: {}'.format(expected))
self.log.debug('Actual PIDs: {}'.format(actual))
if l... | Validate process id quantities for services on units. |
def snmp_server_community_ipv4_acl(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp")
community = ET.SubElement(snmp_server, "community")
community_key = E... | Auto Generated Code |
def convert_cifar10(directory, output_directory,
output_filename='cifar10.hdf5'):
"""Converts the CIFAR-10 dataset to HDF5.
Converts the CIFAR-10 dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CIFAR10`. The converted dataset is saved as
'cifar10.hdf5'.
It assu... | Converts the CIFAR-10 dataset to HDF5.
Converts the CIFAR-10 dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CIFAR10`. The converted dataset is saved as
'cifar10.hdf5'.
It assumes the existence of the following file:
* `cifar-10-python.tar.gz`
Parameters
----------
d... |
def functions(self):
"""Returns a dictionary containing the functions defined in this
object. The keys are function names (as exposed in templates)
and the values are Python functions.
"""
out = {}
for key in self._func_names:
out[key[len(self._prefix):]] = ge... | Returns a dictionary containing the functions defined in this
object. The keys are function names (as exposed in templates)
and the values are Python functions. |
def delete(self, request, key):
"""Remove an email address, validated or not."""
request.DELETE = http.QueryDict(request.body)
email_addr = request.DELETE.get('email')
user_id = request.DELETE.get('user')
if not email_addr:
return http.HttpResponseBadRequest()
... | Remove an email address, validated or not. |
def make_owner(user):
'''
Makes the given user a owner and tutor.
'''
tutor_group, owner_group = _get_user_groups()
user.is_staff = True
user.is_superuser = False
user.save()
owner_group.user_set.add(user)
owner_group.save()
tutor_group.user_set.add(user)
tutor_group.save() | Makes the given user a owner and tutor. |
def keystoneclient(request, admin=False):
"""Returns a client connected to the Keystone backend.
Several forms of authentication are supported:
* Username + password -> Unscoped authentication
* Username + password + tenant id -> Scoped authentication
* Unscoped token -> Unscoped authe... | Returns a client connected to the Keystone backend.
Several forms of authentication are supported:
* Username + password -> Unscoped authentication
* Username + password + tenant id -> Scoped authentication
* Unscoped token -> Unscoped authentication
* Unscoped token + tenant id ->... |
def transitive_subgraph_of_addresses_bfs(self,
addresses,
predicate=None,
dep_predicate=None):
"""Returns the transitive dependency closure of `addresses` using BFS.
:API: public
... | Returns the transitive dependency closure of `addresses` using BFS.
:API: public
:param list<Address> addresses: The closure of `addresses` will be walked.
:param function predicate: If this parameter is not given, no Targets will be filtered
out of the closure. If it is given, any Target which fai... |
def lookup(self):
"""
The meat of this middleware.
Returns None and sets settings.SITE_ID if able to find a Site
object by domain and its subdomain is valid.
Returns an HttpResponsePermanentRedirect to the Site's default
subdomain if a site is found but the requested su... | The meat of this middleware.
Returns None and sets settings.SITE_ID if able to find a Site
object by domain and its subdomain is valid.
Returns an HttpResponsePermanentRedirect to the Site's default
subdomain if a site is found but the requested subdomain
is not supported, or i... |
def kvlclient(self):
'''Return a thread local ``kvlayer`` client.'''
if self._kvlclient is None:
self._kvlclient = kvlayer.client()
return self._kvlclient | Return a thread local ``kvlayer`` client. |
def connection_lost(self, exc=None):
"""Fires the ``connection_lost`` event.
"""
if self._loop.get_debug():
self.producer.logger.debug('connection lost %s', self)
self.event('connection_lost').fire(exc=exc) | Fires the ``connection_lost`` event. |
def _iteratively_analyze_function_features(self, all_funcs_completed=False):
"""
Iteratively analyze function features until a fixed point is reached.
:return: the "changes" dict
:rtype: dict
"""
changes = {
'functions_do_not_return': set(),
'fu... | Iteratively analyze function features until a fixed point is reached.
:return: the "changes" dict
:rtype: dict |
def read(self, size=None):
"""Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
re... | Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
remaining data.
Returns:
... |
def ping():
'''
Is the marathon api responding?
'''
try:
response = salt.utils.http.query(
"{0}/ping".format(CONFIG[CONFIG_BASE_URL]),
decode_type='plain',
decode=True,
)
log.debug(
'marathon.info returned successfully: %s',
... | Is the marathon api responding? |
def corrcoef(time, crossf, integration_window=0.):
"""
Calculate the correlation coefficient for given auto- and crosscorrelation
functions. Standard settings yield the zero lag correlation coefficient.
Setting integration_window > 0 yields the correlation coefficient of
integrated auto- and crossco... | Calculate the correlation coefficient for given auto- and crosscorrelation
functions. Standard settings yield the zero lag correlation coefficient.
Setting integration_window > 0 yields the correlation coefficient of
integrated auto- and crosscorrelation functions. The correlation coefficient
between a ... |
def delete(handler, item_id, id_name):
"""Delete an item"""
data = {'operation': 'delete',
'id': item_id,
'id_name': id_name}
handler.invoke(data) | Delete an item |
def _createStructure(self, linkResult, replaceParamFile):
"""
Create GSSHAPY Structure Objects Method
"""
# Constants
WEIRS = ('WEIR', 'SAG_WEIR')
CULVERTS = ('ROUND_CULVERT', 'RECT_CULVERT')
CURVES = ('RATING_CURVE', 'SCHEDULED_RELEASE', 'RULE_CURVE')
... | Create GSSHAPY Structure Objects Method |
def check_and_order_id_inputs(rid, ridx, cid, cidx, row_meta_df, col_meta_df):
"""
Makes sure that (if entered) id inputs entered are of one type (string id or index)
Input:
- rid (list or None): if not None, a list of rids
- ridx (list or None): if not None, a list of indexes
- cid ... | Makes sure that (if entered) id inputs entered are of one type (string id or index)
Input:
- rid (list or None): if not None, a list of rids
- ridx (list or None): if not None, a list of indexes
- cid (list or None): if not None, a list of cids
- cidx (list or None): if not None, a l... |
def median_date(dt_list):
"""Calcuate median datetime from datetime list
"""
#dt_list_sort = sorted(dt_list)
idx = len(dt_list)/2
if len(dt_list) % 2 == 0:
md = mean_date([dt_list[idx-1], dt_list[idx]])
else:
md = dt_list[idx]
return md | Calcuate median datetime from datetime list |
def set_datastore_policy(self, func):
"""Set the context datastore policy function.
Args:
func: A function that accepts a Key instance as argument and returns
a bool indicating if it should use the datastore. May be None.
"""
if func is None:
func = self.default_datastore_policy
... | Set the context datastore policy function.
Args:
func: A function that accepts a Key instance as argument and returns
a bool indicating if it should use the datastore. May be None. |
def _decode_png(self, encoded_observation):
"""Decodes a single observation from PNG."""
return self._session.obj.run(
self._decoded_image_t.obj,
feed_dict={self._encoded_image_p.obj: encoded_observation}
) | Decodes a single observation from PNG. |
def postprocess(options):
""" perform parametric fit of the test statistics and provide permutation and test pvalues """
resdir = options.resdir
out_file = options.outfile
tol = options.tol
print('.. load permutation results')
file_name = os.path.join(resdir,'perm*','*.res')
files = glob.g... | perform parametric fit of the test statistics and provide permutation and test pvalues |
def fig_height(self):
"""Figure out the height of this plot."""
# hand-tuned
return (
4
+ len(self.data) * len(self.var_names)
- 1
+ 0.1 * sum(1 for j in self.plotters.values() for _ in j.iterator())
) | Figure out the height of this plot. |
def abort(self):
"""
Handle request to cancel HTTP call
"""
if (self.reply and self.reply.isRunning()):
self.on_abort = True
self.reply.abort() | Handle request to cancel HTTP call |
async def read(cls, id: int):
"""Get `BootResource` by `id`."""
data = await cls._handler.read(id=id)
return cls(data) | Get `BootResource` by `id`. |
def _gen_glob_data(dir, pattern, child_table):
"""Generates node data by globbing a directory for a pattern"""
dir = pathlib.Path(dir)
matched = False
used_names = set() # Used by to_nodename to prevent duplicate names
# sorted so that renames (if any) are consistently ordered
for filepath in s... | Generates node data by globbing a directory for a pattern |
def getCell(self, row, width=None):
'Return DisplayWrapper for displayable cell value.'
cellval = wrapply(self.getValue, row)
typedval = wrapply(self.type, cellval)
if isinstance(typedval, TypedWrapper):
if isinstance(cellval, TypedExceptionWrapper): # calc failed
... | Return DisplayWrapper for displayable cell value. |
def write_document(document, out, validate=True):
"""
Write an SPDX RDF document.
- document - spdx.document instance.
- out - file like object that will be written to.
Optionally `validate` the document before writing and raise
InvalidDocumentError if document.validate returns False.
"""
... | Write an SPDX RDF document.
- document - spdx.document instance.
- out - file like object that will be written to.
Optionally `validate` the document before writing and raise
InvalidDocumentError if document.validate returns False. |
def get_file_size(filename):
"""
Get the file size of a given file
:param filename: string: pathname of a file
:return: human readable filesize
"""
if os.path.isfile(filename):
return convert_size(os.path.getsize(filename))
return None | Get the file size of a given file
:param filename: string: pathname of a file
:return: human readable filesize |
def ladder_length(begin_word, end_word, word_list):
"""
Bidirectional BFS!!!
:type begin_word: str
:type end_word: str
:type word_list: Set[str]
:rtype: int
"""
if len(begin_word) != len(end_word):
return -1 # not possible
if begin_word == end_word:
return 0
#... | Bidirectional BFS!!!
:type begin_word: str
:type end_word: str
:type word_list: Set[str]
:rtype: int |
def get_queryset(self, request):
"""
Make special filtering by user's permissions.
"""
if not request.user.has_perm('zinnia.can_view_all'):
queryset = self.model.objects.filter(authors__pk=request.user.pk)
else:
queryset = super(EntryAdmin, self).get_query... | Make special filtering by user's permissions. |
def odata_converter(data, str_type):
''' Convert odata type
http://www.odata.org/documentation/odata-version-2-0/overview#AbstractTypeSystem
To be completed
'''
if not str_type:
return _str(data)
if str_type in ["Edm.Single", "Edm.Double"]:
return ... | Convert odata type
http://www.odata.org/documentation/odata-version-2-0/overview#AbstractTypeSystem
To be completed |
def action_log_create(sender, instance, created, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is first saved to the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead.
"""
if created:
changes = mod... | Signal receiver that creates a log entry when a model instance is first saved to the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead. |
def press_button(self, value):
"""
Click the button with the given label.
"""
button = find_button(world.browser, value)
if not button:
raise AssertionError(
"Cannot find a button named '{}'.".format(value))
button.click() | Click the button with the given label. |
def validateAuthCode(code, redirect_uri, client_id, state=None, validationEndpoint='https://indieauth.com/auth', headers={}):
"""Call authorization endpoint to validate given auth code.
:param code: the auth code to validate
:param redirect_uri: redirect_uri for the given auth code
:param client_id: wh... | Call authorization endpoint to validate given auth code.
:param code: the auth code to validate
:param redirect_uri: redirect_uri for the given auth code
:param client_id: where to find the auth endpoint for the given auth code
:param state: state for the given auth code
:param validationEndpoint: ... |
def terminate(self):
"""Stop the standalone manager."""
logger.info(__(
"Terminating Resolwe listener on channel '{}'.",
state.MANAGER_EXECUTOR_CHANNELS.queue
))
self._should_stop = True | Stop the standalone manager. |
def get(self, name_or_klass):
"""
Gets a mode by name (or class)
:param name_or_klass: The name or the class of the mode to get
:type name_or_klass: str or type
:rtype: pyqode.core.api.Mode
"""
if not isinstance(name_or_klass, str):
name_or_klass = na... | Gets a mode by name (or class)
:param name_or_klass: The name or the class of the mode to get
:type name_or_klass: str or type
:rtype: pyqode.core.api.Mode |
def reactToAMQPMessage(message, send_back):
"""
React to given (AMQP) message. `message` is expected to be
:py:func:`collections.namedtuple` structure from :mod:`.structures` filled
with all necessary data.
Args:
message (object): One of the request objects defined in
... | React to given (AMQP) message. `message` is expected to be
:py:func:`collections.namedtuple` structure from :mod:`.structures` filled
with all necessary data.
Args:
message (object): One of the request objects defined in
:mod:`.structures`.
send_back (fn reference)... |
def stats_enabled(self, value):
"""Setter method; for a description see the getter method."""
if value:
self.statistics.enable()
else:
self.statistics.disable() | Setter method; for a description see the getter method. |
def get_endpoint_server_root(self):
"""Parses RemoteLRS object's endpoint and returns its root
:return: Root of the RemoteLRS object endpoint
:rtype: unicode
"""
parsed = urlparse(self._endpoint)
root = parsed.scheme + "://" + parsed.hostname
if parsed.port is n... | Parses RemoteLRS object's endpoint and returns its root
:return: Root of the RemoteLRS object endpoint
:rtype: unicode |
def construct_txt_file(self):
"""Construct the header of the txt file"""
textlines = ['Prediction of noncovalent interactions for PDB structure %s' % self.mol.pymol_name.upper(), ]
textlines.append("=" * len(textlines[0]))
textlines.append('Created on %s using PLIP v%s\n' % (time.strftim... | Construct the header of the txt file |
def matrixplot(adata, var_names, groupby=None, use_raw=None, log=False, num_categories=7,
figsize=None, dendrogram=False, gene_symbols=None, var_group_positions=None, var_group_labels=None,
var_group_rotation=None, layer=None, standard_scale=None, swap_axes=False, show=None,
... | \
Creates a heatmap of the mean expression values per cluster of each var_names
If groupby is not given, the matrixplot assumes that all data belongs to a single
category.
Parameters
----------
{common_plot_args}
standard_scale : {{'var', 'group'}}, optional (default: None)
Whether ... |
def get_forms(self):
"""
Initializes the forms defined in `form_classes` with initial data from `get_initial()`,
kwargs from get_form_kwargs() and form instance object from `get_objects()`.
"""
forms = {}
objects = self.get_objects()
initial = self.get_initial()
... | Initializes the forms defined in `form_classes` with initial data from `get_initial()`,
kwargs from get_form_kwargs() and form instance object from `get_objects()`. |
def draw_bars(out_value, features, feature_type, width_separators, width_bar):
"""Draw the bars and separators."""
rectangle_list = []
separator_list = []
pre_val = out_value
for index, features in zip(range(len(features)), features):
if feature_type == 'positive':
left_boun... | Draw the bars and separators. |
def reduce_object_file_names(self, dirn):
"""Recursively renames all files named XXX.cpython-...-linux-gnu.so"
to "XXX.so", i.e. removing the erroneous architecture name
coming from the local system.
"""
py_so_files = shprint(sh.find, dirn, '-iname', '*.so')
filens = py_s... | Recursively renames all files named XXX.cpython-...-linux-gnu.so"
to "XXX.so", i.e. removing the erroneous architecture name
coming from the local system. |
def restore(ctx, filename):
"""Restore the database from a zipped file.
Default is to restore from db dump in loqusdb/resources/
"""
filename = filename or background_path
if not os.path.isfile(filename):
LOG.warning("File {} does not exist. Please point to a valid file".format(filename... | Restore the database from a zipped file.
Default is to restore from db dump in loqusdb/resources/ |
def get_bearing(origin_point, destination_point):
"""
Calculate the bearing between two lat-long points. Each tuple should
represent (lat, lng) as decimal degrees.
Parameters
----------
origin_point : tuple
destination_point : tuple
Returns
-------
bearing : float
the c... | Calculate the bearing between two lat-long points. Each tuple should
represent (lat, lng) as decimal degrees.
Parameters
----------
origin_point : tuple
destination_point : tuple
Returns
-------
bearing : float
the compass bearing in decimal degrees from the origin point
... |
def split_by_rand_pct(self, valid_pct:float=0.2, seed:int=None)->'ItemLists':
"Split the items randomly by putting `valid_pct` in the validation set, optional `seed` can be passed."
if valid_pct==0.: return self.split_none()
if seed is not None: np.random.seed(seed)
rand_idx = np.random.... | Split the items randomly by putting `valid_pct` in the validation set, optional `seed` can be passed. |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncListContext for this SyncListInstance
:rtype: twilio.rest.sync.v1.service.sync_list.SyncListC... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: SyncListContext for this SyncListInstance
:rtype: twilio.rest.sync.v1.service.sync_list.SyncListContext |
def scan_keys(self, match=None, count=None):
"""Take a pattern expected by the redis `scan` command and iter on all matching keys
Parameters
----------
match: str
The pattern of keys to look for
count: int, default to None (redis uses 10)
Hint for redis a... | Take a pattern expected by the redis `scan` command and iter on all matching keys
Parameters
----------
match: str
The pattern of keys to look for
count: int, default to None (redis uses 10)
Hint for redis about the number of expected result
Yields
... |
def _quote(data):
"""Prepare a string for quoting for DIGEST-MD5 challenge or response.
Don't add the quotes, only escape '"' and "\\" with backslashes.
:Parameters:
- `data`: a raw string.
:Types:
- `data`: `bytes`
:return: `data` with '"' and "\\" escaped using "\\".
:return... | Prepare a string for quoting for DIGEST-MD5 challenge or response.
Don't add the quotes, only escape '"' and "\\" with backslashes.
:Parameters:
- `data`: a raw string.
:Types:
- `data`: `bytes`
:return: `data` with '"' and "\\" escaped using "\\".
:returntype: `bytes` |
def ipv6_range_to_list(start_packed, end_packed):
""" Return a list of IPv6 entries from start_packed to end_packed. """
new_list = list()
start = int(binascii.hexlify(start_packed), 16)
end = int(binascii.hexlify(end_packed), 16)
for value in range(start, end + 1):
high = value >> 64
... | Return a list of IPv6 entries from start_packed to end_packed. |
def ReleaseSW(self):
' Go away from Limit Switch '
while self.ReadStatusBit(2) == 1: # is Limit Switch ON ?
spi.SPI_write(self.CS, [0x92, 0x92] | (~self.Dir & 1)) # release SW
while self.IsBusy():
pass
self.MoveWait(10) | Go away from Limit Switch |
def fix_e112(self, result):
"""Fix under-indented comments."""
line_index = result['line'] - 1
target = self.source[line_index]
if not target.lstrip().startswith('#'):
# Don't screw with invalid syntax.
return []
self.source[line_index] = self.indent_wor... | Fix under-indented comments. |
def status(url="http://127.0.0.1/status"):
"""
Return the data from an Nginx status page as a dictionary.
http://wiki.nginx.org/HttpStubStatusModule
url
The URL of the status page. Defaults to 'http://127.0.0.1/status'
CLI Example:
.. code-block:: bash
salt '*' nginx.status
... | Return the data from an Nginx status page as a dictionary.
http://wiki.nginx.org/HttpStubStatusModule
url
The URL of the status page. Defaults to 'http://127.0.0.1/status'
CLI Example:
.. code-block:: bash
salt '*' nginx.status |
def fit(self, inputs=None, wait=True, logs=True, job_name=None):
"""Train a model using the input training dataset.
The API calls the Amazon SageMaker CreateTrainingJob API to start model training.
The API uses configuration you provided to create the estimator and the
specified input t... | Train a model using the input training dataset.
The API calls the Amazon SageMaker CreateTrainingJob API to start model training.
The API uses configuration you provided to create the estimator and the
specified input training data to send the CreatingTrainingJob request to Amazon SageMaker.
... |
def dcshift(self, shift=0.0):
'''Apply a DC shift to the audio.
Parameters
----------
shift : float
Amount to shift audio between -2 and 2. (Audio is between -1 and 1)
See Also
--------
highpass
'''
if not is_number(shift) or shift <... | Apply a DC shift to the audio.
Parameters
----------
shift : float
Amount to shift audio between -2 and 2. (Audio is between -1 and 1)
See Also
--------
highpass |
def options(self, parser, env):
"""Register commandline options.
"""
parser.add_option('--collect-only',
action='store_true',
dest=self.enableOpt,
default=env.get('NOSE_COLLECT_ONLY'),
help="E... | Register commandline options. |
def gridmake(*arrays):
"""
Expands one or more vectors (or matrices) into a matrix where rows span the
cartesian product of combinations of the input arrays. Each column of the
input arrays will correspond to one column of the output matrix.
Parameters
----------
*arrays : tuple/list of np.... | Expands one or more vectors (or matrices) into a matrix where rows span the
cartesian product of combinations of the input arrays. Each column of the
input arrays will correspond to one column of the output matrix.
Parameters
----------
*arrays : tuple/list of np.ndarray
Tuple/list of... |
def _process_dependencies(self, anexec, contents, mode="insert"):
"""Extracts a list of subroutines and functions that are called from
within this executable.
:arg mode: specifies whether the matches should be added, removed
or merged into the specified executable.
"""
... | Extracts a list of subroutines and functions that are called from
within this executable.
:arg mode: specifies whether the matches should be added, removed
or merged into the specified executable. |
def stop(self):
"""Stops the background synchronization thread"""
with self.synclock:
if self.syncthread is not None:
self.syncthread.cancel()
self.syncthread = None | Stops the background synchronization thread |
def addLogicalInterfaceToDeviceType(self, typeId, logicalInterfaceId):
"""
Adds a logical interface to a device type.
Parameters:
- typeId (string) - the device type
- logicalInterfaceId (string) - the id returned by the platform on creation of the logical interface
... | Adds a logical interface to a device type.
Parameters:
- typeId (string) - the device type
- logicalInterfaceId (string) - the id returned by the platform on creation of the logical interface
- description (string) - optional (not used)
Throws APIException on failure. |
def create_tag(self, tags):
"""Create tags for a Point in the language you specify. Tags can only contain alphanumeric (unicode) characters
and the underscore. Tags will be stored lower-cased.
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing t... | Create tags for a Point in the language you specify. Tags can only contain alphanumeric (unicode) characters
and the underscore. Tags will be stored lower-cased.
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects ... |
def joinCommissioned(self, strPSKd='threadjpaketest', waitTime=20):
"""start joiner
Args:
strPSKd: Joiner's PSKd
Returns:
True: successful to start joiner
False: fail to start joiner
"""
print '%s call joinCommissioned' % self.port
se... | start joiner
Args:
strPSKd: Joiner's PSKd
Returns:
True: successful to start joiner
False: fail to start joiner |
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
From django.utils.encoding.py in 1.4.2+, minus the dependency on Six.
To support Python 2 and 3 with a single code base, define a __str__ method
... | A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
From django.utils.encoding.py in 1.4.2+, minus the dependency on Six.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class... |
def __check(self, decorated_function, *args, **kwargs):
""" Check whether function is a bounded method or not. If check fails then exception is raised
:param decorated_function: called function (original)
:param args: args with which function is called
:param kwargs: kwargs with which function is called
:ret... | Check whether function is a bounded method or not. If check fails then exception is raised
:param decorated_function: called function (original)
:param args: args with which function is called
:param kwargs: kwargs with which function is called
:return: None |
def tokenizer(text):
"""A lexical analyzer for the `mwtab` formatted files.
:param str text: `mwtab` formatted text.
:return: Tuples of data.
:rtype: py:class:`~collections.namedtuple`
"""
stream = deque(text.split("\n"))
while len(stream) > 0:
line = stream.popleft()
if ... | A lexical analyzer for the `mwtab` formatted files.
:param str text: `mwtab` formatted text.
:return: Tuples of data.
:rtype: py:class:`~collections.namedtuple` |
def ReadHashes(self):
"""
Read Hash values from the stream.
Returns:
list: a list of hash values. Each value is of the bytearray type.
"""
len = self.ReadVarInt()
items = []
for i in range(0, len):
ba = bytearray(self.ReadBytes(32))
... | Read Hash values from the stream.
Returns:
list: a list of hash values. Each value is of the bytearray type. |
def verify_leaf_hash_inclusion(self, leaf_hash: bytes, leaf_index: int,
proof: List[bytes], sth: STH):
"""Verify a Merkle Audit Path.
See section 2.1.1 of RFC6962 for the exact path description.
Args:
leaf_hash: The hash of the leaf for which the ... | Verify a Merkle Audit Path.
See section 2.1.1 of RFC6962 for the exact path description.
Args:
leaf_hash: The hash of the leaf for which the proof was provided.
leaf_index: Index of the leaf in the tree.
proof: A list of SHA-256 hashes representing the Merkle audit... |
def upsert_many(col, data):
"""
Only used when having "_id" field.
**中文文档**
要求 ``data`` 中的每一个 ``document`` 都必须有 ``_id`` 项。这样才能进行
``upsert`` 操作。
"""
ready_to_insert = list()
for doc in data:
res = col.update({"_id": doc["_id"]}, {"$set": doc}, upsert=False)
# 没有任何数据被修改, ... | Only used when having "_id" field.
**中文文档**
要求 ``data`` 中的每一个 ``document`` 都必须有 ``_id`` 项。这样才能进行
``upsert`` 操作。 |
def zero_pad(m, n=1):
"""Pad a matrix with zeros, on all sides."""
return np.pad(m, (n, n), mode='constant', constant_values=[0]) | Pad a matrix with zeros, on all sides. |
def lock(self):
"""Lock thread.
Requires that the currently authenticated user has the modposts oauth
scope or has user/password authentication as a mod of the subreddit.
:returns: The json response from the server.
"""
url = self.reddit_session.config['lock']
... | Lock thread.
Requires that the currently authenticated user has the modposts oauth
scope or has user/password authentication as a mod of the subreddit.
:returns: The json response from the server. |
def parallel(fsms, test):
'''
Crawl several FSMs in parallel, mapping the states of a larger meta-FSM.
To determine whether a state in the larger FSM is final, pass all of the
finality statuses (e.g. [True, False, False] to `test`.
'''
alphabet = set().union(*[fsm.alphabet for fsm in fsms])
initial = dict([(... | Crawl several FSMs in parallel, mapping the states of a larger meta-FSM.
To determine whether a state in the larger FSM is final, pass all of the
finality statuses (e.g. [True, False, False] to `test`. |
def theme(self, value):
"""
Setter for **self.__theme** attribute.
:param value: Attribute value.
:type value: dict
"""
if value is not None:
assert type(value) is dict, "'{0}' attribute: '{1}' type is not 'dict'!".format("theme", value)
self.__theme... | Setter for **self.__theme** attribute.
:param value: Attribute value.
:type value: dict |
def delete_job(self, job_id):
"""Delete the given job id. The job must have been previously reserved by this connection"""
if hasattr(job_id, 'job_id'):
job_id = job_id.job_id
with self._sock_ctx() as socket:
self._send_message('delete {0}'.format(job_id), socket)
... | Delete the given job id. The job must have been previously reserved by this connection |
def Popup(*args, **_3to2kwargs):
if 'location' in _3to2kwargs: location = _3to2kwargs['location']; del _3to2kwargs['location']
else: location = (None, None)
if 'keep_on_top' in _3to2kwargs: keep_on_top = _3to2kwargs['keep_on_top']; del _3to2kwargs['keep_on_top']
else: keep_on_top = False
if 'grab_an... | Popup - Display a popup box with as many parms as you wish to include
:param args:
:param button_color:
:param background_color:
:param text_color:
:param button_type:
:param auto_close:
:param auto_close_duration:
:param non_blocking:
:param icon:
:param line_width:
:param f... |
def to_xdr_object(self):
"""Create an XDR object for this :class:`Asset`.
:return: An XDR Asset object
"""
if self.is_native():
xdr_type = Xdr.const.ASSET_TYPE_NATIVE
return Xdr.types.Asset(type=xdr_type)
else:
x = Xdr.nullclass()
... | Create an XDR object for this :class:`Asset`.
:return: An XDR Asset object |
def rest_put(url, data, timeout):
'''Call rest put method'''
try:
response = requests.put(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\
data=data, timeout=timeout)
return response
except Exception as e:
print('Get ex... | Call rest put method |
def get_listening(self, listen=['0.0.0.0']):
"""Returns a list of addresses SSH can list on
Turns input into a sensible list of IPs SSH can listen on. Input
must be a python list of interface names, IPs and/or CIDRs.
:param listen: list of IPs, CIDRs, interface names
:returns:... | Returns a list of addresses SSH can list on
Turns input into a sensible list of IPs SSH can listen on. Input
must be a python list of interface names, IPs and/or CIDRs.
:param listen: list of IPs, CIDRs, interface names
:returns: list of IPs available on the host |
def combineblocks(blks, imgsz, stpsz=None, fn=np.median):
"""Combine blocks from an ndarray to reconstruct ndarray signal.
Parameters
----------
blks : ndarray
nd array of blocks of a signal
imgsz : tuple
tuple of the signal size
stpsz : tuple, optional (default None, corresponds to... | Combine blocks from an ndarray to reconstruct ndarray signal.
Parameters
----------
blks : ndarray
nd array of blocks of a signal
imgsz : tuple
tuple of the signal size
stpsz : tuple, optional (default None, corresponds to steps of 1)
tuple of step sizes between neighboring blocks... |
def conditional(self, condition, requirements):
"""Calculates conditional requirements for multiple requirements
at once. This is a shorthand to be reduce duplication and to
keep an inline declarative syntax. For example:
lib x : x.cpp : [ conditional <toolset>gcc <variant>debug :
... | Calculates conditional requirements for multiple requirements
at once. This is a shorthand to be reduce duplication and to
keep an inline declarative syntax. For example:
lib x : x.cpp : [ conditional <toolset>gcc <variant>debug :
<define>DEBUG_EXCEPTION <define>DEBUG_TRACE ... |
def t_KEYWORD_AS_TAG(self, t):
r'[a-zA-Z]+'
t.type = self.reserved.get(t.value, 'UNKNOWN_TAG')
t.value = t.value.strip()
return t | r'[a-zA-Z]+ |
def BROKER_TYPE(self):
"""Custom setting allowing switch between rabbitmq, redis"""
broker_type = get('BROKER_TYPE', DEFAULT_BROKER_TYPE)
if broker_type not in SUPPORTED_BROKER_TYPES:
log.warn("Specified BROKER_TYPE {} not supported. Backing to default {}".format(
br... | Custom setting allowing switch between rabbitmq, redis |
def asDictionary(self):
""" returns the data source as a dictionary """
return {
"type": "joinTable",
"leftTableSource": self._leftTableSource,
"rightTableSource": self._rightTableSource,
"leftTableKey": self._leftTableKey,
"rightTableKey": sel... | returns the data source as a dictionary |
def build_import_keychain( cls, keychain_dir, namespace_id, pubkey_hex ):
"""
Generate all possible NAME_IMPORT addresses from the NAMESPACE_REVEAL public key
"""
pubkey_addr = virtualchain.BitcoinPublicKey(str(pubkey_hex)).address()
# do we have a cached one on disk?
c... | Generate all possible NAME_IMPORT addresses from the NAMESPACE_REVEAL public key |
def loaders(self): # pragma: no cover
"""Return available loaders"""
if self.LOADERS_FOR_DYNACONF in (None, 0, "0", "false", False):
self.logger.info("No loader defined")
return []
if not self._loaders:
for loader_module_name in self.LOADERS_FOR_DYNACONF:
... | Return available loaders |
def AUC_analysis(AUC):
"""
Analysis AUC with interpretation table.
:param AUC: area under the ROC curve
:type AUC : float
:return: interpretation result as str
"""
try:
if AUC == "None":
return "None"
if AUC < 0.6:
return "Poor"
if AUC >= 0.6 ... | Analysis AUC with interpretation table.
:param AUC: area under the ROC curve
:type AUC : float
:return: interpretation result as str |
def resample_ann(resampled_t, ann_sample):
"""
Compute the new annotation indices
Parameters
----------
resampled_t : numpy array
Array of signal locations as returned by scipy.signal.resample
ann_sample : numpy array
Array of annotation locations
Returns
-------
re... | Compute the new annotation indices
Parameters
----------
resampled_t : numpy array
Array of signal locations as returned by scipy.signal.resample
ann_sample : numpy array
Array of annotation locations
Returns
-------
resampled_ann_sample : numpy array
Array of resam... |
def _safe_run_theta(input_file, out_dir, output_ext, args, data):
"""Run THetA, catching and continuing on any errors.
"""
out_file = os.path.join(out_dir, _split_theta_ext(input_file) + output_ext)
skip_file = out_file + ".skipped"
if utils.file_exists(skip_file):
return None
if not uti... | Run THetA, catching and continuing on any errors. |
def search(self, query, indices=None, doc_types=None, model=None, scan=False, headers=None, **query_params):
"""Execute a search against one or more indices to get the resultset.
`query` must be a Search object, a Query object, or a custom
dictionary of search parameters using the query DSL to ... | Execute a search against one or more indices to get the resultset.
`query` must be a Search object, a Query object, or a custom
dictionary of search parameters using the query DSL to be passed
directly. |
def junos_call(fun, *args, **kwargs):
'''
.. versionadded:: 2019.2.0
Execute an arbitrary function from the
:mod:`junos execution module <salt.module.junos>`. To check what ``args``
and ``kwargs`` you must send to the function, please consult the appropriate
documentation.
fun
The ... | .. versionadded:: 2019.2.0
Execute an arbitrary function from the
:mod:`junos execution module <salt.module.junos>`. To check what ``args``
and ``kwargs`` you must send to the function, please consult the appropriate
documentation.
fun
The name of the function. E.g., ``set_hostname``.
... |
def getTransitionUsers(obj, action_id, last_user=False):
"""
This function returns a list with the users who have done the transition.
:action_id: a sring as the transition id.
:last_user: a boolean to return only the last user triggering the
transition or all of them.
:returns: a list of us... | This function returns a list with the users who have done the transition.
:action_id: a sring as the transition id.
:last_user: a boolean to return only the last user triggering the
transition or all of them.
:returns: a list of user ids. |
def get_file(path=None, content=None):
"""
:param path: relative path, or None to get from request
:param content: file content, output in data. Used for editfile
"""
if path is None:
path = request.args.get('path')
if path is None:
return error('No path in request')
fi... | :param path: relative path, or None to get from request
:param content: file content, output in data. Used for editfile |
def register_link(self, link):
"""
source record and index must have been set
"""
keys = tuple((ref, link.initial_hook_value) for ref in link.hook_references)
# look for a record hook
for k in keys:
if k in self._record_hooks:
# set link targe... | source record and index must have been set |
def split(table, field, pattern, newfields=None, include_original=False,
maxsplit=0, flags=0):
"""
Add one or more new fields with values generated by splitting an
existing value around occurrences of a regular expression. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'variab... | Add one or more new fields with values generated by splitting an
existing value around occurrences of a regular expression. E.g.::
>>> import petl as etl
>>> table1 = [['id', 'variable', 'value'],
... ['1', 'parad1', '12'],
... ['2', 'parad2', '15'],
... ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.