code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def dispatch(self, request, *args, **kwargs):
# type: (HttpRequest, object, object) -> HttpResponse
"""Inspect the HTTP method and delegate to the view method.
This is the default implementation of the
:py:class:`django.views.View` method, which will inspect the
HTTP method in t... | Inspect the HTTP method and delegate to the view method.
This is the default implementation of the
:py:class:`django.views.View` method, which will inspect the
HTTP method in the input request and delegate it to the
corresponding method in the view. The only allowed method on
th... |
def get_nicknames(self):
"""
:rtype: list(list(str))
"""
nicknames = []
for child in self.vcard.getChildren():
if child.name == "NICKNAME":
nicknames.append(child.value)
return sorted(nicknames) | :rtype: list(list(str)) |
async def _on_message(self, update):
"""Receive a message from a service."""
name = update['service']
message_obj = update['payload']
if name not in self.services:
return
with self._state_lock:
self.services[name].post_message(message_obj['level'], mess... | Receive a message from a service. |
def update_in_ioloop(update):
"""Decorator that ensures an update() method is run in the tornado ioloop.
Does this by checking the thread identity. Requires that the object to
which the method is bound has the attributes :attr:`_ioloop_thread_id`
(the result of thread.get_ident() in the ioloop thread) ... | Decorator that ensures an update() method is run in the tornado ioloop.
Does this by checking the thread identity. Requires that the object to
which the method is bound has the attributes :attr:`_ioloop_thread_id`
(the result of thread.get_ident() in the ioloop thread) and :attr:`ioloop`
(the ioloop in... |
def spawn_process(self, target, *args):
"""
:type target: function or class
"""
p = Process(target=target, args=args)
p.daemon = True
if target == worker:
p.daemon = Conf.DAEMONIZE_WORKERS
p.timer = args[2]
self.pool.append(p)
p... | :type target: function or class |
def check_for_usable_environment(self):
"""Check if the current env is usable and has everything's required."""
# Do not let the user run Mackup as root
if os.geteuid() == 0:
utils.error("Running Mackup as a superuser is useless and"
" dangerous. Don't do it!"... | Check if the current env is usable and has everything's required. |
def save_bookmarks(self, filename, bookmarks):
"""Receive bookmark changes and save them."""
filename = to_text_string(filename)
bookmarks = to_text_string(bookmarks)
filename = osp.normpath(osp.abspath(filename))
bookmarks = eval(bookmarks)
save_bookmarks(filename,... | Receive bookmark changes and save them. |
def pre_dispatch(self, request, path_args):
"""
Pre dispatch hook
"""
secret_key = self.get_secret_key(request, path_args)
if not secret_key:
raise PermissionDenied('Signature not valid.')
try:
signing.verify_url_path(request.path, request.GET, se... | Pre dispatch hook |
def __evaluation_error(self, result, condition, throw):
"""Helper-method for easy error-logging"""
self.log.error("Result does not match condition, dropping item. "
"Result %s; Condition: %s; Throw: %s",
result, condition, throw)
return False | Helper-method for easy error-logging |
def current(self):
# type: () -> Hub
"""Returns the current instance of the hub."""
rv = _local.get(None)
if rv is None:
rv = Hub(GLOBAL_HUB)
_local.set(rv)
return rv | Returns the current instance of the hub. |
def find_surface_sites_by_height(self, slab, height=0.9, xy_tol=0.05):
"""
This method finds surface sites by determining which sites are within
a threshold value in height from the topmost site in a list of sites
Args:
site_list (list): list of sites from which to select su... | This method finds surface sites by determining which sites are within
a threshold value in height from the topmost site in a list of sites
Args:
site_list (list): list of sites from which to select surface sites
height (float): threshold in angstroms of distance from topmost
... |
def lcumsum (inlist):
"""
Returns a list consisting of the cumulative sum of the items in the
passed list.
Usage: lcumsum(inlist)
"""
newlist = copy.deepcopy(inlist)
for i in range(1,len(newlist)):
newlist[i] = newlist[i] + newlist[i-1]
return newlist | Returns a list consisting of the cumulative sum of the items in the
passed list.
Usage: lcumsum(inlist) |
def keyPressEvent(self, event):
"""Qt Override.
Handle key press events.
"""
if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
if self.add_current_text_if_valid():
self.selected()
self.hide_completer()
elif event... | Qt Override.
Handle key press events. |
def g_subset(g, atwts, atwt,
digits=_DEF.SYMM_ATWT_ROUND_DIGITS):
""" Extract a subset of a geometry matching a desired atom.
.. todo:: Complete g_subset docstring
"""
# Imports
import numpy as np
# Ensure g and atwts are n-D vectors
g = make_nd_vec(g, nd=None, t=np.float64, ... | Extract a subset of a geometry matching a desired atom.
.. todo:: Complete g_subset docstring |
def plan_first_phase(N1, N2):
"""
Create a plan for the first stage of the pruned FFT operation.
(Alex to provide a write up with more details.)
Parameters
-----------
N1 : int
Number of rows.
N2 : int
Number of columns.
Returns
--------
plan : FFTWF plan
... | Create a plan for the first stage of the pruned FFT operation.
(Alex to provide a write up with more details.)
Parameters
-----------
N1 : int
Number of rows.
N2 : int
Number of columns.
Returns
--------
plan : FFTWF plan
The plan for performing the first phase ... |
def ner_net(source, destinations, width, height, wrap_around=False, radius=10):
"""Produce a shortest path tree for a given net using NER.
This is the kernel of the NER algorithm.
Parameters
----------
source : (x, y)
The coordinate of the source vertex.
destinations : iterable([(x, y)... | Produce a shortest path tree for a given net using NER.
This is the kernel of the NER algorithm.
Parameters
----------
source : (x, y)
The coordinate of the source vertex.
destinations : iterable([(x, y), ...])
The coordinates of destination vertices.
width : int
Width ... |
def get_df_ilocs(self, band, date):
"""Get positions of rows matching specific band(s) and date(s).
The method supports three typical queries:
* one band and one date (both given as strings)
* one band and of several dates (band given as strings, date as list of strings)
* se... | Get positions of rows matching specific band(s) and date(s).
The method supports three typical queries:
* one band and one date (both given as strings)
* one band and of several dates (band given as strings, date as list of strings)
* several band and of one date (date given as strin... |
def check_prerequisites(
prerequisites,
checker,
msg_tmpl='Prerequisites "{}" are required in method "{}" but not '
'found, please install them first.'):
"""A decorator factory to check if prerequisites are satisfied.
Args:
prerequisites (str of list[str]): Prerequisites... | A decorator factory to check if prerequisites are satisfied.
Args:
prerequisites (str of list[str]): Prerequisites to be checked.
checker (callable): The checker method that returns True if a
prerequisite is meet, False otherwise.
msg_tmpl (str): The message template with two va... |
def retry(self, timeout=RETRY_SAME_TIMEOUT):
'''
retry - Retry the timed-out function with same arguments.
@param timeout <float/RETRY_SAME_TIMEOUT/None> Default RETRY_SAME_TIMEOUT
If RETRY_SAME_TIMEOUT : Will retry the function same args, same timeout
... | retry - Retry the timed-out function with same arguments.
@param timeout <float/RETRY_SAME_TIMEOUT/None> Default RETRY_SAME_TIMEOUT
If RETRY_SAME_TIMEOUT : Will retry the function same args, same timeout
If a float/int : Will retry the function same args wit... |
def train(cls, data, lambda_=1.0):
"""
Train a Naive Bayes model given an RDD of (label, features)
vectors.
This is the Multinomial NB (U{http://tinyurl.com/lsdw6p}) which
can handle all kinds of discrete data. For example, by
converting documents into TF-IDF vectors, i... | Train a Naive Bayes model given an RDD of (label, features)
vectors.
This is the Multinomial NB (U{http://tinyurl.com/lsdw6p}) which
can handle all kinds of discrete data. For example, by
converting documents into TF-IDF vectors, it can be used for
document classification. By m... |
def validate_environment(self):
"""
Make sure :data:`sys.prefix` matches ``$VIRTUAL_ENV`` (if defined).
This may seem like a strange requirement to dictate but it avoids hairy
issues like `documented here <https://github.com/paylogic/pip-accel/issues/5>`_.
The most sneaky thing... | Make sure :data:`sys.prefix` matches ``$VIRTUAL_ENV`` (if defined).
This may seem like a strange requirement to dictate but it avoids hairy
issues like `documented here <https://github.com/paylogic/pip-accel/issues/5>`_.
The most sneaky thing is that ``pip`` doesn't have this problem
(... |
def from_rtm(cls, raw_event: MutableMapping) -> "Event":
"""
Create an event with data coming from the RTM API.
If the event type is a message a :class:`slack.events.Message` is returned.
Args:
raw_event: JSON decoded data from the RTM API
Returns:
:cla... | Create an event with data coming from the RTM API.
If the event type is a message a :class:`slack.events.Message` is returned.
Args:
raw_event: JSON decoded data from the RTM API
Returns:
:class:`slack.events.Event` or :class:`slack.events.Message` |
def indxByRange(self, valu):
'''
Override default ``*range=`` handler to account for relative computation.
'''
if not isinstance(valu, (list, tuple)):
raise s_exc.BadCmprValu(valu=valu, cmpr='*range=')
if len(valu) != 2:
raise s_exc.BadCmprValu(valu=valu... | Override default ``*range=`` handler to account for relative computation. |
def QA_SU_save_index_min(client=DATABASE, ui_log=None, ui_progress=None):
"""save index_min
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
__index_list = QA_fetch_get_stock_list('index')
coll = client.index_min
coll.create_index(
[
('c... | save index_min
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) |
def create_link_button(self, text="None", uri="None"):
"""
Function creates a link button with corresponding text and
URI reference
"""
link_btn = Gtk.LinkButton(uri, text)
return link_btn | Function creates a link button with corresponding text and
URI reference |
def init_db(self):
'''initialize the database, with the default database path or custom of
the format sqlite:////scif/data/expfactory.db
'''
# Database Setup, use default if uri not provided
if self.database == 'sqlite':
db_path = os.path.join(EXPFACTORY_DATA, '%s.db' % EXPFACTORY_SUBID... | initialize the database, with the default database path or custom of
the format sqlite:////scif/data/expfactory.db |
def paintEvent( self, event ):
"""
Overloads the paint event for this menu to draw its title based on its \
show title property.
:param event | <QPaintEvent>
"""
super(XMenu, self).paintEvent(event)
if self.showTitle():
with XPai... | Overloads the paint event for this menu to draw its title based on its \
show title property.
:param event | <QPaintEvent> |
def get_gradebooks_by_grade_system(self, grade_system_id):
"""Gets the list of ``Gradebooks`` mapped to a ``GradeSystem``.
arg: grade_system_id (osid.id.Id): ``Id`` of a
``GradeSystem``
return: (osid.grading.GradebookList) - list of gradebooks
raise: NotFound - ``gra... | Gets the list of ``Gradebooks`` mapped to a ``GradeSystem``.
arg: grade_system_id (osid.id.Id): ``Id`` of a
``GradeSystem``
return: (osid.grading.GradebookList) - list of gradebooks
raise: NotFound - ``grade_system_id`` is not found
raise: NullArgument - ``grade_sys... |
def solve(self,b):
"""
Solves system Ax=b.
Parameters
----------
b : ndarray
Returns
-------
x : ndarray
"""
x = b.copy()
self.mumps.set_rhs(x)
self.mumps.run(job=3)
return x | Solves system Ax=b.
Parameters
----------
b : ndarray
Returns
-------
x : ndarray |
def rev_parse(repo, rev):
"""
:return: Object at the given revision, either Commit, Tag, Tree or Blob
:param rev: git-rev-parse compatible revision specification as string, please see
http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html
for details
:raise BadObject: if the ... | :return: Object at the given revision, either Commit, Tag, Tree or Blob
:param rev: git-rev-parse compatible revision specification as string, please see
http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html
for details
:raise BadObject: if the given revision could not be found
... |
def sha1(self):
"""
:return:
The SHA1 hash of the DER-encoded bytes of this public key info
"""
if self._sha1 is None:
self._sha1 = hashlib.sha1(byte_cls(self['public_key'])).digest()
return self._sha1 | :return:
The SHA1 hash of the DER-encoded bytes of this public key info |
def info(self, message):
'''
Logs an informational message to stdout.
This method should only be used by the Runner.
'''
return self._log(
message=message.upper(),
stream=sys.stdout
) | Logs an informational message to stdout.
This method should only be used by the Runner. |
def _hash_the_file(hasher, filename):
"""Helper function for creating hash functions.
See implementation of :func:`dtoolcore.filehasher.shasum`
for more usage details.
"""
BUF_SIZE = 65536
with open(filename, 'rb') as f:
buf = f.read(BUF_SIZE)
while len(buf) > 0:
has... | Helper function for creating hash functions.
See implementation of :func:`dtoolcore.filehasher.shasum`
for more usage details. |
def iter_next(self) -> bool:
"""
True if the iterator can return another batch.
"""
# Read batch_size lines from the source stream
sources_sentences = [[] for x in self.sources_sentences] # type: List[List[str]]
target_sentences = [] # type: List[str]
num_read ... | True if the iterator can return another batch. |
def add_filters(self, filterer, filters):
"""Add filters to a filterer from a list of names."""
for f in filters:
try:
filterer.addFilter(self.config['filters'][f])
except StandardError as e:
raise ValueError('Unable to add filter %r: %s' % (f, e)) | Add filters to a filterer from a list of names. |
def tokenize_conf_stream(conf_handle):
"""
convert the key=val pairs in a LSF config stream to tuples of tokens
"""
for line in conf_handle:
if line.startswith("#"):
continue
tokens = line.split("=")
if len(tokens) != 2:
continue
yield (tokens[0].s... | convert the key=val pairs in a LSF config stream to tuples of tokens |
def _set_default__configuration_options(app):
"""
Sets the default configuration options used by this extension
"""
app.config.setdefault('JWT_TOKEN_ARGUMENT_NAME', "token") # Name of token argument in GraphQL request resolver
app.config.setdefault('JWT_REFRESH_TOKEN_ARGUMENT_NA... | Sets the default configuration options used by this extension |
def evaluate(self, eval_iter: data_io.BaseParallelSampleIter, eval_metric: mx.metric.EvalMetric):
"""
Resets and recomputes evaluation metric on given data iterator.
"""
for eval_batch in eval_iter:
self.module.forward(eval_batch, is_train=False)
self.module.updat... | Resets and recomputes evaluation metric on given data iterator. |
def text_filter_changed(self, text):
"""
Called to handle changes to the text filter.
:param text: The text for the filter.
"""
text = text.strip() if text else None
if text is not None:
self.__text_filter = ListModel.TextFilter("text_for_filter", te... | Called to handle changes to the text filter.
:param text: The text for the filter. |
def has_cjk(self):
"""Checks if the word of the chunk contains CJK characters.
This is using unicode codepoint ranges from
https://github.com/nltk/nltk/blob/develop/nltk/tokenize/util.py#L149
Returns:
bool: True if the chunk has any CJK character.
"""
cjk_codepoint_ranges = [
(43... | Checks if the word of the chunk contains CJK characters.
This is using unicode codepoint ranges from
https://github.com/nltk/nltk/blob/develop/nltk/tokenize/util.py#L149
Returns:
bool: True if the chunk has any CJK character. |
def setup_jukebox_logger():
"""Setup the jukebox top-level logger with handlers
The logger has the name ``jukebox`` and is the top-level logger for all other loggers of jukebox.
It does not propagate to the root logger, because it also has a StreamHandler and that might cause double output.
The logger... | Setup the jukebox top-level logger with handlers
The logger has the name ``jukebox`` and is the top-level logger for all other loggers of jukebox.
It does not propagate to the root logger, because it also has a StreamHandler and that might cause double output.
The logger default level is defined in the co... |
def Main():
"""The main function."""
multiprocessing.freeze_support()
input_reader = cli_tools.StdinInputReader()
tool = psort_tool.PsortTool(input_reader=input_reader)
if not tool.ParseArguments():
return False
have_list_option = False
if tool.list_analysis_plugins:
tool.ListAnalysisPlugins()
... | The main function. |
def add_record(self, msg_id, rec):
"""Add a new Task Record, by msg_id."""
# print rec
rec = self._binary_buffers(rec)
self._records.insert(rec) | Add a new Task Record, by msg_id. |
def matrix_params_from_table(table, transpose=False):
"""
Calculate TP,TN,FP,FN from confusion matrix.
:param table: input matrix
:type table : dict
:param transpose : transpose flag
:type transpose : bool
:return: [classes_list,table,TP,TN,FP,FN]
"""
classes = sorted(table.keys())
... | Calculate TP,TN,FP,FN from confusion matrix.
:param table: input matrix
:type table : dict
:param transpose : transpose flag
:type transpose : bool
:return: [classes_list,table,TP,TN,FP,FN] |
def _connect(self):
"""Connects to the ec2 cloud provider
:return: :py:class:`boto.ec2.connection.EC2Connection`
:raises: Generic exception on error
"""
# check for existing connection
if self._ec2_connection:
return self._ec2_connection
if not self.... | Connects to the ec2 cloud provider
:return: :py:class:`boto.ec2.connection.EC2Connection`
:raises: Generic exception on error |
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Link Node Dataset File Read from File Method
"""
# Set file extension property
self.fileExtension = extension
# Dictionary of keywords/cards and parse... | Link Node Dataset File Read from File Method |
def _weaken_key(flags, key):
"""
NOTE: Key weakening in NTLM2 (Extended Session Security) is performed simply by truncating the master key (or
secondary master key, if key exchange is performed) to the appropriate length. 128-bit keys are supported under
NTLM2. In this case, the master k... | NOTE: Key weakening in NTLM2 (Extended Session Security) is performed simply by truncating the master key (or
secondary master key, if key exchange is performed) to the appropriate length. 128-bit keys are supported under
NTLM2. In this case, the master key is used directly in the generation of subkeys ... |
def _add_header_domains_xml(self, document):
"""
Generates the XML elements for allowed header domains.
"""
for domain, attrs in self.header_domains.items():
header_element = document.createElement(
'allow-http-request-headers-from'
)
... | Generates the XML elements for allowed header domains. |
def _get_binary_replacement(first, second, cls):
"""Helper function for match_replace_binary"""
expr = ProtoExpr([first, second], {})
if LOG:
logger = logging.getLogger('QNET.create')
for key, rule in cls._binary_rules.items():
pat, replacement = rule
match_dict = match_pattern(p... | Helper function for match_replace_binary |
def facets_by_halfspace(self):
"""
Returns a list of vertex indices for each halfspace
e.g: facets_by_halfspace[0] is the list of indices ov vertices
incident to halfspace 0
"""
if self._fbh_out is None:
output = qhalf('FN', self.halfspaces, self.interior_poin... | Returns a list of vertex indices for each halfspace
e.g: facets_by_halfspace[0] is the list of indices ov vertices
incident to halfspace 0 |
def _dump_crawl_stats(self):
'''
Dumps flattened crawling stats so the spiders do not have to
'''
extras = {}
spiders = {}
spider_set = set()
total_spider_count = 0
keys = self.redis_conn.keys('stats:crawler:*:*:*')
for key in keys:
#... | Dumps flattened crawling stats so the spiders do not have to |
def trim_trailing_silence(obj):
"""
Return a copy of the object with trimmed trailing silence of the
piano-roll(s).
"""
_check_supported(obj)
copied = deepcopy(obj)
length = copied.get_active_length()
copied.pianoroll = copied.pianoroll[:length]
return copied | Return a copy of the object with trimmed trailing silence of the
piano-roll(s). |
def folders(self):
'''gets the property value for folders'''
if self._folders is None :
self.__init()
if self._folders is not None and isinstance(self._folders, list):
if len(self._folders) == 0:
self._loadFolders()
return self._folders | gets the property value for folders |
def get_by_identifier(self, identifier):
"""Gets blocks by identifier
Args:
identifier (str): Should be any of: username, phone_number, email.
See: https://auth0.com/docs/api/management/v2#!/User_Blocks/get_user_blocks
"""
params = {'identifier': identifier}
... | Gets blocks by identifier
Args:
identifier (str): Should be any of: username, phone_number, email.
See: https://auth0.com/docs/api/management/v2#!/User_Blocks/get_user_blocks |
def state_machine_change_after(self, model, prop_name, info):
"""Called on any change within th state machine
This method is called, when any state, transition, data flow, etc. within the state machine changes. This
then typically requires a redraw of the graphical editor, to display these chan... | Called on any change within th state machine
This method is called, when any state, transition, data flow, etc. within the state machine changes. This
then typically requires a redraw of the graphical editor, to display these changes immediately.
:param rafcon.gui.models.state_machine.StateMac... |
def angle_v2_rad(vec_a, vec_b):
"""Returns angle between vec_a and vec_b in range [0, PI]. This does not
distinguish if a is left of or right of b.
"""
# cos(x) = A * B / |A| * |B|
return math.acos(vec_a.dot(vec_b) / (vec_a.length() * vec_b.length())) | Returns angle between vec_a and vec_b in range [0, PI]. This does not
distinguish if a is left of or right of b. |
def stop_transmit(self, *ports):
""" Stop traffic on ports.
:param ports: list of ports to stop traffic on, if empty start on all ports.
"""
port_list = self.set_ports_list(*ports)
self.api.call_rc('ixStopTransmit {}'.format(port_list))
time.sleep(0.2) | Stop traffic on ports.
:param ports: list of ports to stop traffic on, if empty start on all ports. |
def AddEnumDescriptor(self, enum_desc):
"""Adds an EnumDescriptor to the pool.
This method also registers the FileDescriptor associated with the message.
Args:
enum_desc: An EnumDescriptor.
"""
if not isinstance(enum_desc, descriptor.EnumDescriptor):
raise TypeError('Expected instance... | Adds an EnumDescriptor to the pool.
This method also registers the FileDescriptor associated with the message.
Args:
enum_desc: An EnumDescriptor. |
def add_point_labels(self, points, labels, italic=False, bold=True,
font_size=None, text_color='k',
font_family=None, shadow=False,
show_points=True, point_color='k', point_size=5,
name=None):
"""
Creates... | Creates a point actor with one label from list labels assigned to
each point.
Parameters
----------
points : np.ndarray
n x 3 numpy array of points.
labels : list
List of labels. Must be the same length as points.
italic : bool, optional
... |
def p_stmt_cmp_eq(p):
"""stmt : VAR EQUALS value comparison_op value"""
p[0] = ast.EqNode(ast.VariableNode(p[1]), ast.CmpExprNode(p[4], p[3], p[5])) | stmt : VAR EQUALS value comparison_op value |
def check(qpi_or_h5file, checks=["attributes", "background"]):
"""Checks various properties of a :class:`qpimage.core.QPImage` instance
Parameters
----------
qpi_or_h5file: qpimage.core.QPImage or str
A QPImage object or a path to an hdf5 file
checks: list of str
Which checks to per... | Checks various properties of a :class:`qpimage.core.QPImage` instance
Parameters
----------
qpi_or_h5file: qpimage.core.QPImage or str
A QPImage object or a path to an hdf5 file
checks: list of str
Which checks to perform ("attributes" and/or "background")
Raises
------
Int... |
def run(self):
"""
This method handles the user's command line arguments, for example, if
the user specified a path file we'll open it and read the contents.
Finally it will run the scan using TagCubeClient.scan(...)
:return: The exit code for our process
"""
cli... | This method handles the user's command line arguments, for example, if
the user specified a path file we'll open it and read the contents.
Finally it will run the scan using TagCubeClient.scan(...)
:return: The exit code for our process |
def find( self, flags = 0 ):
"""
Looks throught the text document based on the current criteria. The \
inputed flags will be merged with the generated search flags.
:param flags | <QTextDocument.FindFlag>
:return <bool> | success
"""
... | Looks throught the text document based on the current criteria. The \
inputed flags will be merged with the generated search flags.
:param flags | <QTextDocument.FindFlag>
:return <bool> | success |
def sort(x, axis=-1, reverse=False, with_index=False, only_index=False):
"""Sorts the elements of `x` along a given `axis` in ascending order
by value. A negative `axis` counts from the last dimension of `x`,
so the default of -1 sorts along the last dimension. If `reverse`
is True, then the elements ar... | Sorts the elements of `x` along a given `axis` in ascending order
by value. A negative `axis` counts from the last dimension of `x`,
so the default of -1 sorts along the last dimension. If `reverse`
is True, then the elements are soreted in descending order.
If `with_index` is True, result is a tuple `... |
def _sub_ms_char(self, match):
"""Changes a MS smart quote character to an XML or HTML
entity, or an ASCII character."""
orig = match.group(1)
if self.smart_quotes_to == 'ascii':
sub = self.MS_CHARS_TO_ASCII.get(orig).encode()
else:
sub = self.MS_CHARS.get... | Changes a MS smart quote character to an XML or HTML
entity, or an ASCII character. |
def afw_word_acceptance(afw: dict, word: list) -> bool:
""" Checks if a **word** is accepted by input AFW, returning
True/False.
The word w is accepted by a AFW if exists at least an
accepting run on w. A run for AFWs is a tree and
an alternating automaton can have multiple runs on a given
inpu... | Checks if a **word** is accepted by input AFW, returning
True/False.
The word w is accepted by a AFW if exists at least an
accepting run on w. A run for AFWs is a tree and
an alternating automaton can have multiple runs on a given
input.
A run is accepting if all the leaf nodes are accepting st... |
def obj_in_list_always(target_list, obj):
"""
>>> l = [1,1,1]
>>> obj_in_list_always(l, 1)
True
>>> l.append(2)
>>> obj_in_list_always(l, 1)
False
"""
for item in set(target_list):
if item is not obj:
return False
return True | >>> l = [1,1,1]
>>> obj_in_list_always(l, 1)
True
>>> l.append(2)
>>> obj_in_list_always(l, 1)
False |
def _get_tag(self, url, tag, print_warn=True):
"""Check if url is available and returns given tag type
:param url: url to content relative to base url
:param anchor: anchor type to return
:param print_warn: if True print warn when url is unavailable
"""
# construct comple... | Check if url is available and returns given tag type
:param url: url to content relative to base url
:param anchor: anchor type to return
:param print_warn: if True print warn when url is unavailable |
def stroke_opacity(value):
"""ValueRef : number, opacity of the stroke (0 to 1)
"""
if value.value:
_assert_is_type('stroke_opacity.value', value.value,
(float, int))
if value.value < 0 or value.value > 1:
raise ValueError(
... | ValueRef : number, opacity of the stroke (0 to 1) |
def duplicates(base, items):
"""Get an iterator of items similar but not equal to the base.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: generator of items sorted by similarity to the base
"""
for item in items:
if ite... | Get an iterator of items similar but not equal to the base.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: generator of items sorted by similarity to the base |
def delete_network_acl(network_acl_id=None, network_acl_name=None, disassociate=False,
region=None, key=None, keyid=None, profile=None):
'''
Delete a network acl based on the network_acl_id or network_acl_name provided.
CLI Examples:
.. code-block:: bash
salt myminion b... | Delete a network acl based on the network_acl_id or network_acl_name provided.
CLI Examples:
.. code-block:: bash
salt myminion boto_vpc.delete_network_acl network_acl_id='acl-5fb85d36' \\
disassociate=false
.. code-block:: bash
salt myminion boto_vpc.delete_network_acl ... |
def validate_voicing(ref_voicing, est_voicing):
"""Checks that voicing inputs to a metric are in the correct format.
Parameters
----------
ref_voicing : np.ndarray
Reference boolean voicing array
est_voicing : np.ndarray
Estimated boolean voicing array
"""
if ref_voicing.si... | Checks that voicing inputs to a metric are in the correct format.
Parameters
----------
ref_voicing : np.ndarray
Reference boolean voicing array
est_voicing : np.ndarray
Estimated boolean voicing array |
def set_authorization_password(self, password):
"""
Changes the authorization password of the account.
:type password: string
:param password: The new authorization password.
"""
self.authorization_password = password
self.changed_event.emit(self) | Changes the authorization password of the account.
:type password: string
:param password: The new authorization password. |
def make_session(self):
"""Authenticate and get the name of assigned SFDC data server"""
with connect_lock:
if self._sf_session is None:
sf_session = requests.Session()
# TODO configurable class Salesforce***Auth
sf_session.auth = SalesforcePas... | Authenticate and get the name of assigned SFDC data server |
def has_printout(
state, index, not_printed_msg=None, pre_code=None, name=None, copy=False
):
"""Check if the right printouts happened.
``has_printout()`` will look for the printout in the solution code that you specified with ``index`` (0 in this case), rerun the ``print()`` call in
the solution proce... | Check if the right printouts happened.
``has_printout()`` will look for the printout in the solution code that you specified with ``index`` (0 in this case), rerun the ``print()`` call in
the solution process, capture its output, and verify whether the output is present in the output of the student.
This ... |
def set_call_back(self, func):
"""sets callback function for updating the plot.
in the callback function implement the logic of reading of serial input
also the further processing of the signal if necessary has to be done
in this
callbak function."""
self.timer.add_call... | sets callback function for updating the plot.
in the callback function implement the logic of reading of serial input
also the further processing of the signal if necessary has to be done
in this
callbak function. |
def nside_to_npix(nside):
"""
Find the number of pixels corresponding to a HEALPix resolution.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
npix : int
The number of pixels in the HEALPix m... | Find the number of pixels corresponding to a HEALPix resolution.
Parameters
----------
nside : int
The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
Returns
-------
npix : int
The number of pixels in the HEALPix map. |
def _sequence(self, i):
"""Handle character group."""
result = ['[']
end_range = 0
escape_hyphen = -1
removed = False
last_posix = False
c = next(i)
if c in ('!', '^'):
# Handle negate char
result.append('^')
c = next(... | Handle character group. |
def volatility(data, period):
"""
Volatility.
Formula:
SDt / SVt
"""
volatility = sd(data, period) / sv(data, period)
return volatility | Volatility.
Formula:
SDt / SVt |
def _set_interface_fe(self, v, load=False):
"""
Setter method for interface_fe, mapped from YANG variable /rule/command/interface_fe (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_fe is considered as a private
method. Backends looking to popula... | Setter method for interface_fe, mapped from YANG variable /rule/command/interface_fe (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_fe is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._s... |
def to_json(self, filename, indent=2):
"""
Return a JSON string of all model inputs and outputs.
Parameters
----------
filename : str or file
Either the file name (string) or an open file (file-like object)
where the data will be saved.
indent : i... | Return a JSON string of all model inputs and outputs.
Parameters
----------
filename : str or file
Either the file name (string) or an open file (file-like object)
where the data will be saved.
indent : int, optional
Indentation level for JSON output.... |
def update_variable_group(self, group, project, group_id):
"""UpdateVariableGroup.
[Preview API] Update a variable group.
:param :class:`<VariableGroupParameters> <azure.devops.v5_1.task_agent.models.VariableGroupParameters>` group: Variable group to update.
:param str project: Project I... | UpdateVariableGroup.
[Preview API] Update a variable group.
:param :class:`<VariableGroupParameters> <azure.devops.v5_1.task_agent.models.VariableGroupParameters>` group: Variable group to update.
:param str project: Project ID or project name
:param int group_id: Id of the variable grou... |
def get_chromosome_lengths(fasta_file, fancy_sort=True):
"""Extract chromosome lengths from genome FASTA file."""
chromlen = []
with gzip.open(fasta_file, 'rt', encoding='ascii') as fh:
fasta = SeqIO.parse(fh, 'fasta')
for i, f in enumerate(fasta):
chromlen.append((f.id, len(f.se... | Extract chromosome lengths from genome FASTA file. |
def create_subnetwork(kwargs=None, call=None):
'''
... versionadded:: 2017.7.0
Create a GCE Subnetwork. Must specify name, cidr, network, and region.
CLI Example:
.. code-block:: bash
salt-cloud -f create_subnetwork gce name=mysubnet network=mynet1 region=us-west1 cidr=10.0.0.0/24 descrip... | ... versionadded:: 2017.7.0
Create a GCE Subnetwork. Must specify name, cidr, network, and region.
CLI Example:
.. code-block:: bash
salt-cloud -f create_subnetwork gce name=mysubnet network=mynet1 region=us-west1 cidr=10.0.0.0/24 description=optional |
def run(self):
"""
If the connection drops, then run_forever will terminate and a
reconnection attempt will be made.
"""
while True:
self.connect_lock.acquire()
if self.stopped():
return
self.__connect()
self.connect... | If the connection drops, then run_forever will terminate and a
reconnection attempt will be made. |
def convert(self, argument):
"""Converts the argument to a boolean; raise ValueError on errors."""
if isinstance(argument, str):
if argument.lower() in ['true', 't', '1']:
return True
elif argument.lower() in ['false', 'f', '0']:
return False
bool_argument = bool(argument)
i... | Converts the argument to a boolean; raise ValueError on errors. |
def get(self, name):
"""Get the set of compatible packages given a resolvable name."""
resolvable, packages, parent, constraint_only = self._collapse().get(
self.normalize(name), _ResolvedPackages.empty())
return packages | Get the set of compatible packages given a resolvable name. |
def aks_versions_table_format(result):
"""Format get-versions results as a summary for display with "-o table"."""
# pylint: disable=import-error
from jmespath import compile as compile_jmes, Options
parsed = compile_jmes("""orchestrators[].{
kubernetesVersion: orchestratorVersion,
upgr... | Format get-versions results as a summary for display with "-o table". |
def verify_signature(self, signature_filename, data_filename,
keystore=None):
"""
Verify a signature for a file.
:param signature_filename: The pathname to the file containing the
signature.
:param data_filename: The pathname t... | Verify a signature for a file.
:param signature_filename: The pathname to the file containing the
signature.
:param data_filename: The pathname to the file containing the
signed data.
:param keystore: The path to a directory which... |
def adj_par_names(self):
""" get the adjustable (not fixed or tied) parameter names
Returns
-------
adj_par_names : list
list of adjustable (not fixed or tied) parameter names
"""
adj_names = []
for t,n in zip(self.parameter_data.partrans,
... | get the adjustable (not fixed or tied) parameter names
Returns
-------
adj_par_names : list
list of adjustable (not fixed or tied) parameter names |
def connect(self, address):
'connects to the address and wraps the connection in an SSL context'
tout = _timeout(self.gettimeout())
while 1:
self._wait_event(tout.now, write=True)
err = self._connect(address, tout.now)
if err in (errno.EINPROGRESS, errno.EALRE... | connects to the address and wraps the connection in an SSL context |
def cosbetas(self):
"""
TODO: add documentation
(ComputedColumn)
"""
coords = self.coords_for_computations
norms = self.normals_for_computations
# TODO: ditch the list comprehension... I know I figured out how to do
# this (ie along an axis) with np.dot ... | TODO: add documentation
(ComputedColumn) |
def zoning_defined_configuration_zone_member_entry_entry_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
zoning = ET.SubElement(config, "zoning", xmlns="urn:brocade.com:mgmt:brocade-zone")
defined_configuration = ET.SubElement(zoning, "defined-confi... | Auto Generated Code |
def _xml_escape(data):
"""Escape &, <, >, ", ', etc. in a string of data."""
# ampersand must be replaced first
from_symbols = '&><"\''
to_symbols = ('&'+s+';' for s in "amp gt lt quot apos".split())
for from_,to_ in zip(from_symbols, to_symbols):
data = data.replace(from_, to_)
return ... | Escape &, <, >, ", ', etc. in a string of data. |
def _generateForServerTokenSecurity(self,
serverURL,
token,
tokenUrl,
referer,
expiration=None
... | generates a token for a feature service |
def referenceframe(self, event):
"""Handles navigational reference frame updates.
These are necessary to assign geo coordinates to alerts and other
misc things.
:param event with incoming referenceframe message
"""
self.log("Got a reference frame update! ", event, lvl=v... | Handles navigational reference frame updates.
These are necessary to assign geo coordinates to alerts and other
misc things.
:param event with incoming referenceframe message |
def mpl_palette(name, n_colors=6):
"""Return discrete colors from a matplotlib palette.
Note that this handles the qualitative colorbrewer palettes
properly, although if you ask for more colors than a particular
qualitative palette can provide you will fewer than you are
expecting.
Parameters
... | Return discrete colors from a matplotlib palette.
Note that this handles the qualitative colorbrewer palettes
properly, although if you ask for more colors than a particular
qualitative palette can provide you will fewer than you are
expecting.
Parameters
----------
name : string
n... |
def _imm_init_setattr(self, name, value):
'''
An immutable's initial setattr allows only param's to be set and does not run checks on the new
parameters until a full parameter-set has been specified, at which point it runs all checks and
switches over to a normal setattr and getattr method.
'''
... | An immutable's initial setattr allows only param's to be set and does not run checks on the new
parameters until a full parameter-set has been specified, at which point it runs all checks and
switches over to a normal setattr and getattr method. |
def role(ctx, dependency_name, driver_name, lint_name, provisioner_name,
role_name, verifier_name, template): # pragma: no cover
""" Initialize a new role for use with Molecule. """
command_args = {
'dependency_name': dependency_name,
'driver_name': driver_name,
'lint_name': li... | Initialize a new role for use with Molecule. |
def new_closure(vals):
"""
Build a new closure
"""
args = ','.join('x%i' % i for i in range(len(vals)))
f = eval("lambda %s:lambda:(%s)" % (args, args))
if sys.version_info[0] >= 3:
return f(*vals).__closure__
return f(*vals).func_closure | Build a new closure |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.