code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_facet_serializer(self, *args, **kwargs):
"""
Return the facet serializer instance that should be used for
serializing faceted output.
"""
assert "objects" in kwargs, "`objects` is a required argument to `get_facet_serializer()`"
facet_serializer_class = self.get_... | Return the facet serializer instance that should be used for
serializing faceted output. |
def unlink(self, *others):
"""
Unlink (disassociate) the specified properties object.
@param others: The list object to unlink. Unspecified means unlink all.
@type others: [L{Properties},..]
@return: self
@rtype: L{Properties}
"""
if not len(others):
... | Unlink (disassociate) the specified properties object.
@param others: The list object to unlink. Unspecified means unlink all.
@type others: [L{Properties},..]
@return: self
@rtype: L{Properties} |
def _element(cls):
''' find the element with controls '''
if not cls.__is_selector():
raise Exception("Invalid selector[%s]." %cls.__control["by"])
driver = Web.driver
try:
elements = WebDriverWait(driver, cls.__control["timeout"]).un... | find the element with controls |
def _load_lib():
"""Load libary by searching possible path."""
lib_path = _find_lib_path()
lib = ctypes.cdll.LoadLibrary(lib_path[0])
# DMatrix functions
lib.MXGetLastError.restype = ctypes.c_char_p
return lib | Load libary by searching possible path. |
def countRandomBitFrequencies(numTerms = 100000, percentSparsity = 0.01):
"""Create a uniformly random counts matrix through sampling."""
# Accumulate counts by inplace-adding sparse matrices
counts = SparseMatrix()
size = 128*128
counts.resize(1, size)
# Pre-allocate buffer sparse matrix
sparseBitmap = ... | Create a uniformly random counts matrix through sampling. |
def make_wheelfile_inner(base_name, base_dir='.'):
"""Create a whl file from all the files under 'base_dir'.
Places .dist-info at the end of the archive."""
zip_filename = base_name + ".whl"
log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
# Some applications need reproduc... | Create a whl file from all the files under 'base_dir'.
Places .dist-info at the end of the archive. |
def _input_as_parameter(self, data):
""" Set the input path and log path based on data (a fasta filepath)
"""
self.Parameters['-i'].on(data)
# access data through self.Parameters so we know it's been cast
# to a FilePath
input_filepath = self.Parameters['-i'].Value
... | Set the input path and log path based on data (a fasta filepath) |
def check_attr(self, repo_abspath, attrs):
"""
Generator that returns attributes for given paths relative to repo_abspath.
>>> g = GitArchiver.check_attr('repo_path', ['export-ignore'])
>>> next(g)
>>> attrs = g.send('relative_path')
>>> print(attrs['export-ignore'])
... | Generator that returns attributes for given paths relative to repo_abspath.
>>> g = GitArchiver.check_attr('repo_path', ['export-ignore'])
>>> next(g)
>>> attrs = g.send('relative_path')
>>> print(attrs['export-ignore'])
@param repo_abspath: Absolute path to a git repository.
... |
def add_signature(name=None, inputs=None, outputs=None):
"""Adds a signature to the module definition.
NOTE: This must be called within a `module_fn` that is defining a Module.
Args:
name: Signature name as a string. If omitted, it is interpreted as 'default'
and is the signature used when `Module.__c... | Adds a signature to the module definition.
NOTE: This must be called within a `module_fn` that is defining a Module.
Args:
name: Signature name as a string. If omitted, it is interpreted as 'default'
and is the signature used when `Module.__call__` `signature` is not
specified.
inputs: A dict ... |
def form_valid(self, form):
"""
save the data
:param form:
:return:
"""
valid = True
# 'name' is injected in the clean() of the form line 56
name = form.cleaned_data.get('name').name
user = self.request.user
form.save(user=user, service_nam... | save the data
:param form:
:return: |
def reset_weights(self):
""" Initialize properly model weights """
self.input_block.reset_weights()
self.policy_backbone.reset_weights()
self.value_backbone.reset_weights()
self.action_head.reset_weights()
self.critic_head.reset_weights() | Initialize properly model weights |
def averagingData(array, windowSize=None, averagingType='median'):
"""#TODO: docstring
:param array: #TODO: docstring
:param windowSize: #TODO: docstring
:param averagingType: "median" or "mean"
:returns: #TODO: docstring
"""
assert averagingType in ['median', 'mean']
if windowSize is ... | #TODO: docstring
:param array: #TODO: docstring
:param windowSize: #TODO: docstring
:param averagingType: "median" or "mean"
:returns: #TODO: docstring |
def _task_to_text(self, task):
""" Return a standard formatting of a Task serialization. """
started = self._format_date(task.get('started_at', None))
completed = self._format_date(task.get('completed_at', None))
success = task.get('success', None)
success_lu = {None: 'Not exec... | Return a standard formatting of a Task serialization. |
def create_attachment(self, upload_stream, project, wiki_identifier, name, **kwargs):
"""CreateAttachment.
Creates an attachment in the wiki.
:param object upload_stream: Stream to upload
:param str project: Project ID or project name
:param str wiki_identifier: Wiki Id or name.
... | CreateAttachment.
Creates an attachment in the wiki.
:param object upload_stream: Stream to upload
:param str project: Project ID or project name
:param str wiki_identifier: Wiki Id or name.
:param str name: Wiki attachment name.
:rtype: :class:`<WikiAttachmentResponse> <... |
def get_all_tags(self, filters=None, max_records=None, next_token=None):
"""
Lists the Auto Scaling group tags.
This action supports pagination by returning a token if there are more
pages to retrieve. To get the next page, call this action again with the returned token as t... | Lists the Auto Scaling group tags.
This action supports pagination by returning a token if there are more
pages to retrieve. To get the next page, call this action again with the returned token as the NextToken parameter.
:type filters: dict
:param filters: The value of the... |
def cmd_unzip(zip_file,
dest,
excludes=None,
options=None,
template=None,
runas=None,
trim_output=False,
password=None):
'''
.. versionadded:: 2015.5.0
In versions 2014.7.x and earlier, this function was kn... | .. versionadded:: 2015.5.0
In versions 2014.7.x and earlier, this function was known as
``archive.unzip``.
Uses the ``unzip`` command to unpack zip files. This command is part of the
`Info-ZIP`_ suite of tools, and is typically packaged as simply ``unzip``.
.. _`Info-ZIP`: http://www.info-... |
def get_ga_tracking_id(self):
"""
Retrieve tracking ID from settings
"""
if hasattr(settings, self.ga_tracking_id_settings_key):
return getattr(settings, self.ga_tracking_id_settings_key)
return super(GARequestErrorReportingMixin, self).get_ga_tracking_id() | Retrieve tracking ID from settings |
def del_key(self, ref):
"""
Delete a key.
(ref)
Return None or LCDd response on error
"""
if ref not in self.keys:
response = self.request("client_del_key %s" % (ref))
self.keys.remove(ref)
if "success" in response:
ret... | Delete a key.
(ref)
Return None or LCDd response on error |
def atlas_peer_dequeue_all( peer_queue=None ):
"""
Get all queued peers
"""
peers = []
with AtlasPeerQueueLocked(peer_queue) as pq:
while len(pq) > 0:
peers.append( pq.pop(0) )
return peers | Get all queued peers |
def is_underlined(r):
"""
The function will return True if the r tag passed in is considered
underlined.
"""
w_namespace = get_namespace(r, 'w')
rpr = r.find('%srPr' % w_namespace)
if rpr is None:
return False
underline = rpr.find('%su' % w_namespace)
return style_is_false(un... | The function will return True if the r tag passed in is considered
underlined. |
def find_field_generators(obj):
"""
Return dictionary with the names and instances of
all tohu.BaseGenerator occurring in the given
object's class & instance namespaces.
"""
cls_dict = obj.__class__.__dict__
obj_dict = obj.__dict__
#debug_print_dict(cls_dict, 'cls_dict')
#debug_prin... | Return dictionary with the names and instances of
all tohu.BaseGenerator occurring in the given
object's class & instance namespaces. |
def copy_opts_for_single_ifo(opt, ifo):
"""
Takes the namespace object (opt) from the multi-detector interface and
returns a namespace object for a single ifo that can be used with
functions expecting output from the single-detector interface.
"""
opt = copy.deepcopy(opt)
for arg, val in var... | Takes the namespace object (opt) from the multi-detector interface and
returns a namespace object for a single ifo that can be used with
functions expecting output from the single-detector interface. |
def Q_weir_rectangular_full_Kindsvater_Carter(h1, h2, b):
r'''Calculates the flow rate across a full-channel rectangular weir from
the height of the liquid above the crest of the weir, the liquid depth
beneath it, and the width of the channel. Model from [1]_ as reproduced in
[2]_.
Flow rate is giv... | r'''Calculates the flow rate across a full-channel rectangular weir from
the height of the liquid above the crest of the weir, the liquid depth
beneath it, and the width of the channel. Model from [1]_ as reproduced in
[2]_.
Flow rate is given by:
.. math::
Q = \frac{2}{3}\sqrt{2}\left(0.6... |
def parse_temperature_response(
temperature_string: str) -> Mapping[str, Optional[float]]:
'''
Example input: "T:none C:25"
'''
err_msg = 'Unexpected argument to parse_temperature_response: {}'.format(
temperature_string)
if not temperature_string or \
not isinstance(temp... | Example input: "T:none C:25" |
def array_2d_from_array_1d(self, padded_array_1d):
""" Map a padded 1D array of values to its original 2D array, trimming all edge values.
Parameters
-----------
padded_array_1d : ndarray
A 1D array of values which were computed using the *PaddedRegularGrid*.
"""
... | Map a padded 1D array of values to its original 2D array, trimming all edge values.
Parameters
-----------
padded_array_1d : ndarray
A 1D array of values which were computed using the *PaddedRegularGrid*. |
def activate(self, span, finish_on_close):
"""
Make a :class:`~opentracing.Span` instance active.
:param span: the :class:`~opentracing.Span` that should become active.
:param finish_on_close: whether *span* should automatically be
finished when :meth:`Scope.close()` is call... | Make a :class:`~opentracing.Span` instance active.
:param span: the :class:`~opentracing.Span` that should become active.
:param finish_on_close: whether *span* should automatically be
finished when :meth:`Scope.close()` is called.
If no :func:`tracer_stack_context()` is detected, ... |
def daysInMonth(date):
"""
Returns the number of the days in the month for the given date. This will
take into account leap years based on the inputted date's year.
:param date | <datetime.date>
:return <int>
"""
# map from Qt information
if type(date).__name__ in ('Q... | Returns the number of the days in the month for the given date. This will
take into account leap years based on the inputted date's year.
:param date | <datetime.date>
:return <int> |
def parse(cls, conn):
"""Read a request from the HTTP connection ``conn``.
May raise ``BadHttpRequestError``.
"""
req = cls(conn)
req_line = yield from conn.reader.readline()
logger('HttpRequest').debug('req_line = %r', req_line)
req._parse_req_line(req_line)
... | Read a request from the HTTP connection ``conn``.
May raise ``BadHttpRequestError``. |
def _auto_scroll(self, *args):
""" Scroll to the end of the text view """
adj = self['scrollable'].get_vadjustment()
adj.set_value(adj.get_upper() - adj.get_page_size()) | Scroll to the end of the text view |
def __get_gp_plan(self, gp):
"""
Request the planner a search plan for a given gp and returns the plan as a graph.
:param gp:
:return:
"""
query = urlencode({'gp': gp})
response = requests.get('{}/plan?'.format(self.__planner) + query, headers={'Accept': 'text/tur... | Request the planner a search plan for a given gp and returns the plan as a graph.
:param gp:
:return: |
def cd(path_to): # pylint: disable=invalid-name
"""cd to the given path
If the path is a file, then cd to its parent directory
Remember current directory before the cd
so that we can cd back there with cd('-')
"""
if path_to == '-':
if not cd.previous:
raise PathError(... | cd to the given path
If the path is a file, then cd to its parent directory
Remember current directory before the cd
so that we can cd back there with cd('-') |
def circle_touching_line(center, radius, start, end):
""" Return true if the given circle intersects the given segment. Note
that this checks for intersection with a line segment, and not an actual
line.
:param center: Center of the circle.
:type center: Vector
:param radius: Radius of the c... | Return true if the given circle intersects the given segment. Note
that this checks for intersection with a line segment, and not an actual
line.
:param center: Center of the circle.
:type center: Vector
:param radius: Radius of the circle.
:type radius: float
:param start: The first end... |
def metadata(request):
""" Returns an XML with the SAML 2.0 metadata for this Idp.
The metadata is constructed on-the-fly based on the config dict in the django settings.
"""
conf = IdPConfig()
conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))
metadata = entity_descriptor(conf)
return H... | Returns an XML with the SAML 2.0 metadata for this Idp.
The metadata is constructed on-the-fly based on the config dict in the django settings. |
def event(
title,
text,
alert_type=None,
aggregation_key=None,
source_type_name=None,
date_happened=None,
priority=None,
tags=None,
hostname=None,
):
"""
Send an event.
""" | Send an event. |
def get_category_metrics(self, category):
"""Get metrics belonging to the given category"""
slug_list = self._category_slugs(category)
return self.get_metrics(slug_list) | Get metrics belonging to the given category |
def cancel_subscription(self, sid):
"""
Unsubscribes from a previously configured subscription.
"""
url = urljoin(self._url_base, self._event_sub_url)
headers = dict(
HOST=urlparse(url).netloc,
SID=sid
)
resp = requests.request('UNSUBSCRIBE... | Unsubscribes from a previously configured subscription. |
def run_kmeans(self, X, K):
"""Runs k-means and returns the labels assigned to the data."""
wX = vq.whiten(X)
means, dist = vq.kmeans(wX, K, iter=100)
labels, dist = vq.vq(wX, means)
return means, labels | Runs k-means and returns the labels assigned to the data. |
def visit_For(self, node):
'''
For loop creates aliasing between the target
and the content of the iterator
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse("""
... def foo(a):
... for i in a:
... | For loop creates aliasing between the target
and the content of the iterator
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse("""
... def foo(a):
... for i in a:
... {i}""")
>>> result = pm.ga... |
def _fill(self, values):
"""Add extra values to fill the line"""
if not self._previous_line:
self._previous_line = values
return super(StackedLine, self)._fill(values)
new_values = values + list(reversed(self._previous_line))
self._previous_line = values
r... | Add extra values to fill the line |
def processFormData(self, data, dataset_name):
"""Take a string of form data as CSV and convert to insert statements, return template and data values"""
# Get the cols for this dataset
cols = self.datasets[dataset_name]
reader = self.getCSVReader(data, reader_type=csv.reader)
#... | Take a string of form data as CSV and convert to insert statements, return template and data values |
def parse_headers(self, headers):
"""Parses a semi-colon delimited list of headers.
Example: foo=bar;baz=qux
"""
for name, value in _parse_keyvalue_list(headers):
self.headers[name] = value | Parses a semi-colon delimited list of headers.
Example: foo=bar;baz=qux |
def irfs(self, **kwargs):
""" Get the name of IFRs associted with a particular dataset
"""
dsval = kwargs.get('dataset', self.dataset(**kwargs))
tokens = dsval.split('_')
irf_name = "%s_%s_%s" % (DATASET_DICTIONARY['%s_%s' % (tokens[0], tokens[1])],
... | Get the name of IFRs associted with a particular dataset |
def sequence_names(fasta):
"""
return a list of the sequence IDs in a FASTA file
"""
sequences = SeqIO.parse(fasta, "fasta")
records = [record.id for record in sequences]
return records | return a list of the sequence IDs in a FASTA file |
def add(self, type, orig, replace):
"""Add an entry in the catalog, it may overwrite existing but
different entries. """
ret = libxml2mod.xmlACatalogAdd(self._o, type, orig, replace)
return ret | Add an entry in the catalog, it may overwrite existing but
different entries. |
def action(self, action):
r"""Activate or deactivate an output.
Use the <wait> option to activate/deactivate the port for a
limited period of time.
<Port ID> = Port name. Default: Name from Output.Name
<a> = Action character. /=active, \=inactive
<wait> = Delay befor... | r"""Activate or deactivate an output.
Use the <wait> option to activate/deactivate the port for a
limited period of time.
<Port ID> = Port name. Default: Name from Output.Name
<a> = Action character. /=active, \=inactive
<wait> = Delay before the next action. Unit: milliseco... |
def send(self, message):
""" Send a message object
:type message: data.OutgoingMessage
:param message: The message to send
:rtype: data.OutgoingMessage
:returns: The sent message with populated fields
:raises AssertionError: wrong provider name encoun... | Send a message object
:type message: data.OutgoingMessage
:param message: The message to send
:rtype: data.OutgoingMessage
:returns: The sent message with populated fields
:raises AssertionError: wrong provider name encountered (returned by the router, or pro... |
def main():
"""Sample usage for this python module
This main method simply illustrates sample usage for this python
module.
:return: None
"""
log = logging.getLogger(Logify.get_name() + '.logify.main')
log.info('logger name is: %s', Logify.get_name())
log.debug('This is DEBUG')
log... | Sample usage for this python module
This main method simply illustrates sample usage for this python
module.
:return: None |
def login_required(f, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
"""
Decorator that wraps django.contrib.auth.decorators.login_required, but supports extracting Shopify's authentication
query parameters (`shop`, `timestamp`, `signature` and `hmac`) and passing them on to the login URL (instea... | Decorator that wraps django.contrib.auth.decorators.login_required, but supports extracting Shopify's authentication
query parameters (`shop`, `timestamp`, `signature` and `hmac`) and passing them on to the login URL (instead of just
wrapping them up and encoding them in to the `next` parameter).
This is u... |
def _is_entity(bpe):
"""Return True if the element is a physical entity."""
if isinstance(bpe, _bp('Protein')) or \
isinstance(bpe, _bpimpl('Protein')) or \
isinstance(bpe, _bp('SmallMolecule')) or \
isinstance(bpe, _bpimpl('SmallMolecule')) or \
isinstance(bpe, _bp('Complex')) o... | Return True if the element is a physical entity. |
def if_url(context, url_name, yes, no):
"""
Example:
%li{ class:"{% if_url 'contacts.contact_read' 'active' '' %}" }
"""
current = context["request"].resolver_match.url_name
return yes if url_name == current else no | Example:
%li{ class:"{% if_url 'contacts.contact_read' 'active' '' %}" } |
def to_grid_locator(latitude, longitude, precision='square'):
"""Calculate Maidenhead locator from latitude and longitude.
Args:
latitude (float): Position's latitude
longitude (float): Position's longitude
precision (str): Precision with which generate locator string
Returns:
... | Calculate Maidenhead locator from latitude and longitude.
Args:
latitude (float): Position's latitude
longitude (float): Position's longitude
precision (str): Precision with which generate locator string
Returns:
str: Maidenhead locator for latitude and longitude
Raise:
... |
def status_schedule(token):
"""
Returns the json string from the Hydrawise server after calling
statusschedule.php.
:param token: The users API token.
:type token: string
:returns: The response from the controller. If there was an error returns
None.
:rtype: string or None
... | Returns the json string from the Hydrawise server after calling
statusschedule.php.
:param token: The users API token.
:type token: string
:returns: The response from the controller. If there was an error returns
None.
:rtype: string or None |
def reassemble(cls, fields, document):
"""
Take a previously assembled document and reassemble the given set of
fields for it in place.
"""
for field_name in cls._instructions:
if field_name in fields:
maker = cls._instructions[field_name]
... | Take a previously assembled document and reassemble the given set of
fields for it in place. |
def cifar_generator(cifar_version, tmp_dir, training, how_many, start_from=0):
"""Image generator for CIFAR-10 and 100.
Args:
cifar_version: string; one of "cifar10" or "cifar100"
tmp_dir: path to temporary storage directory.
training: a Boolean; if true, we use the train set, otherwise the test set.
... | Image generator for CIFAR-10 and 100.
Args:
cifar_version: string; one of "cifar10" or "cifar100"
tmp_dir: path to temporary storage directory.
training: a Boolean; if true, we use the train set, otherwise the test set.
how_many: how many images and labels to generate.
start_from: from which imag... |
def add_caveat(self, cav, key=None, loc=None):
'''Add a caveat to the macaroon.
It encrypts it using the given key pair
and by looking up the location using the given locator.
As a special case, if the caveat's Location field has the prefix
"local " the caveat is added as a clie... | Add a caveat to the macaroon.
It encrypts it using the given key pair
and by looking up the location using the given locator.
As a special case, if the caveat's Location field has the prefix
"local " the caveat is added as a client self-discharge caveat using
the public key base... |
def get_config_filename(args):
'''get the file name of config file'''
experiment_id = check_experiment_id(args)
if experiment_id is None:
print_error('Please set the experiment id!')
exit(1)
experiment_config = Experiments()
experiment_dict = experiment_config.get_all_experiments()
... | get the file name of config file |
def dad_status_output_dad_last_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
dad_status = ET.Element("dad_status")
config = dad_status
output = ET.SubElement(dad_status, "output")
dad_last_state = ET.SubElement(output, "dad-last-s... | Auto Generated Code |
def flatten(list_of_lists):
"""Flatten a list of lists but maintain strings and ints as entries."""
flat_list = []
for sublist in list_of_lists:
if isinstance(sublist, string_types) or isinstance(sublist, int):
flat_list.append(sublist)
elif sublist is None:
continue
... | Flatten a list of lists but maintain strings and ints as entries. |
def add_gate_option_group(parser):
"""Adds the options needed to apply gates to data.
Parameters
----------
parser : object
ArgumentParser instance.
"""
gate_group = parser.add_argument_group("Options for gating data.")
gate_group.add_argument("--gate", nargs="+", type=str,
... | Adds the options needed to apply gates to data.
Parameters
----------
parser : object
ArgumentParser instance. |
def validateRequest(self, uri, postVars, expectedSignature):
"""validate a request from plivo
uri: the full URI that Plivo requested on your server
postVars: post vars that Plivo sent with the request
expectedSignature: signature in HTTP X-Plivo-Signature header
returns true if... | validate a request from plivo
uri: the full URI that Plivo requested on your server
postVars: post vars that Plivo sent with the request
expectedSignature: signature in HTTP X-Plivo-Signature header
returns true if the request passes validation, false if not |
def to_tf_matrix(expression_matrix,
gene_names,
tf_names):
"""
:param expression_matrix: numpy matrix. Rows are observations and columns are genes.
:param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index.
:param tf... | :param expression_matrix: numpy matrix. Rows are observations and columns are genes.
:param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index.
:param tf_names: a list of transcription factor names. Should be a subset of gene_names.
:return: tuple of:
... |
def _get_co_name(self, context):
"""
Obtain the CO name previously saved in the request state, or if not set
use the request path obtained from the current context to determine
the target CO.
:type context: The current context
:rtype: string
:param context: The ... | Obtain the CO name previously saved in the request state, or if not set
use the request path obtained from the current context to determine
the target CO.
:type context: The current context
:rtype: string
:param context: The current context
:return: CO name |
def make_parser_with_config_adder(parser, config):
"""factory function for a smarter parser:
return an utility function that pull default from the config as well.
Pull the default for parser not only from the ``default`` kwarg,
but also if an identical value is find in ``config`` where leading
``-... | factory function for a smarter parser:
return an utility function that pull default from the config as well.
Pull the default for parser not only from the ``default`` kwarg,
but also if an identical value is find in ``config`` where leading
``--`` or ``--no`` is removed.
If the option is a boolea... |
def draw(self, scale=0.7, filename=None, style=None, output='text',
interactive=False, line_length=None, plot_barriers=True,
reverse_bits=False, justify=None):
"""Draw the quantum circuit
Using the output parameter you can specify the format. The choices are:
0. text: ... | Draw the quantum circuit
Using the output parameter you can specify the format. The choices are:
0. text: ASCII art string
1. latex: high-quality images, but heavy external software dependencies
2. matplotlib: purely in Python with no external dependencies
Defaults to an overco... |
def create_can_publish_and_can_republish_permissions(sender, **kwargs):
"""
Add `can_publish` and `ca_nrepublish` permissions for each publishable
model in the system.
"""
for model in sender.get_models():
if not issubclass(model, PublishingModel):
continue
content_type =... | Add `can_publish` and `ca_nrepublish` permissions for each publishable
model in the system. |
def get(self, request, bot_id, format=None):
"""
Get list of Telegram bots
---
serializer: TelegramBotSerializer
responseMessages:
- code: 401
message: Not authenticated
"""
return super(TelegramBotList, self).get(request, bot_id, format) | Get list of Telegram bots
---
serializer: TelegramBotSerializer
responseMessages:
- code: 401
message: Not authenticated |
def emit_message(self, message):
"""
Send a message to the channel. We also emit the message
back to the sender's WebSocket.
"""
try:
nickname_color = self.nicknames[self.nickname]
except KeyError:
# Only accept messages if we've joined.
... | Send a message to the channel. We also emit the message
back to the sender's WebSocket. |
def _handle_ansi_color_codes(self, s):
"""Replace ansi escape sequences with spans of appropriately named css classes."""
parts = HtmlReporter._ANSI_COLOR_CODE_RE.split(s)
ret = []
span_depth = 0
# Note that len(parts) is always odd: text, code, text, code, ..., text.
for i in range(0, len(parts... | Replace ansi escape sequences with spans of appropriately named css classes. |
def sqrt_rc_imp(Ns,alpha,M=6):
"""
A truncated square root raised cosine pulse used in digital communications.
The pulse shaping factor :math:`0 < \\alpha < 1` is required as well as the
truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`.
Parameters
----------... | A truncated square root raised cosine pulse used in digital communications.
The pulse shaping factor :math:`0 < \\alpha < 1` is required as well as the
truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`.
Parameters
----------
Ns : number of samples per symbol
... |
def validate_filters_or_records(filters_or_records):
"""Validation for filters_or_records variable from bulk_modify and bulk_delete"""
# If filters_or_records is empty, fail
if not filters_or_records:
raise ValueError('Must provide at least one filter tuples or Records')
# If filters_or_records ... | Validation for filters_or_records variable from bulk_modify and bulk_delete |
async def connect(self):
"""
Get an connection for the self instance
"""
if isinstance(self.connection, dict):
# a dict like {'host': 'localhost', 'port': 6379,
# 'db': 0, 'password': 'pass'}
kwargs = self.connection.copy()
ad... | Get an connection for the self instance |
def _load32(ins):
""" Load a 32 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
"""
output = _32bit_oper(ins.quad[2])
output.append('push de')
output.append('push hl')
return output | Load a 32 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value. |
def strip_trailing_slashes(self, path):
"""Return input path minus any trailing slashes."""
m = re.match(r"(.*)/+$", path)
if (m is None):
return(path)
return(m.group(1)) | Return input path minus any trailing slashes. |
def _split_iso9660_filename(fullname):
# type: (bytes) -> Tuple[bytes, bytes, bytes]
'''
A function to split an ISO 9660 filename into its constituent parts. This
is the name, the extension, and the version number.
Parameters:
fullname - The name to split.
Returns:
A tuple containing... | A function to split an ISO 9660 filename into its constituent parts. This
is the name, the extension, and the version number.
Parameters:
fullname - The name to split.
Returns:
A tuple containing the name, extension, and version. |
def lrucache(func, size):
"""
A simple implementation of a least recently used (LRU) cache.
Memoizes the recent calls of a computationally intensive function.
Parameters
----------
func : function
Must be unary (takes a single argument)
size : int
The size of the cache (num... | A simple implementation of a least recently used (LRU) cache.
Memoizes the recent calls of a computationally intensive function.
Parameters
----------
func : function
Must be unary (takes a single argument)
size : int
The size of the cache (number of previous calls to store) |
def console_output(msg, logging_msg=None):
"""Use instead of print, to clear the status information before printing"""
assert isinstance(msg, bytes)
assert isinstance(logging_msg, bytes) or logging_msg is None
from polysh import remote_dispatcher
remote_dispatcher.log(logging_msg or msg)
if re... | Use instead of print, to clear the status information before printing |
def read_file(self, location):
"""Read in a yaml file and return as a python object"""
try:
return yaml.load(open(location))
except (yaml.parser.ParserError, yaml.scanner.ScannerError) as error:
raise self.BadFileErrorKls("Failed to read yaml", location=location, error_ty... | Read in a yaml file and return as a python object |
def timeseries(self):
"""
Feed-in time series of generator
It returns the actual time series used in power flow analysis. If
:attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise,
:meth:`timeseries` looks for generation and curtailment time series
of the acco... | Feed-in time series of generator
It returns the actual time series used in power flow analysis. If
:attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise,
:meth:`timeseries` looks for generation and curtailment time series
of the according type of technology (and weather cell... |
def _map_query_path_to_location_info(query_metadata_table):
"""Create a map from each query path to a LocationInfo at that path.
Args:
query_metadata_table: QueryMetadataTable, object containing all metadata collected during
query processing, including location metadata (e... | Create a map from each query path to a LocationInfo at that path.
Args:
query_metadata_table: QueryMetadataTable, object containing all metadata collected during
query processing, including location metadata (e.g. which locations
are folded or opt... |
def check_vip_ip(self, ip, environment_vip):
"""
Check available ipv6 in environment vip
"""
uri = 'api/ipv6/ip/%s/environment-vip/%s/' % (ip, environment_vip)
return super(ApiNetworkIPv6, self).get(uri) | Check available ipv6 in environment vip |
def warning(self, msg, indent=0, **kwargs):
"""invoke ``self.logger.warning``"""
return self.logger.warning(self._indent(msg, indent), **kwargs) | invoke ``self.logger.warning`` |
def triangle_normal(tri):
""" Computes the (approximate) normal vector of the input triangle.
:param tri: triangle object
:type tri: elements.Triangle
:return: normal vector of the triangle
:rtype: tuple
"""
vec1 = vector_generate(tri.vertices[0].data, tri.vertices[1].data)
vec2 = vecto... | Computes the (approximate) normal vector of the input triangle.
:param tri: triangle object
:type tri: elements.Triangle
:return: normal vector of the triangle
:rtype: tuple |
def active(self):
"""Returns all outlets that are currently active and have sales."""
qs = self.get_queryset()
return qs.filter(
models.Q(
models.Q(start_date__isnull=True) |
models.Q(start_date__lte=now().date())
) &
models.Q(
... | Returns all outlets that are currently active and have sales. |
def _replace_type_to_regex(cls, match):
""" /<int:id> -> r'(?P<id>\d+)' """
groupdict = match.groupdict()
_type = groupdict.get('type')
type_regex = cls.TYPE_REGEX_MAP.get(_type, '[^/]+')
name = groupdict.get('name')
return r'(?P<{name}>{type_regex})'.format(
... | /<int:id> -> r'(?P<id>\d+)' |
def getSpec(cls):
"""
Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getSpec`.
"""
ns = dict(
description=KNNClassifierRegion.__doc__,
singleNodeOnly=True,
inputs=dict(
categoryIn=dict(
description='Vector of zero or more category indices for this... | Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getSpec`. |
def generate_query_string(self, otp, nonce, timestamp=False, sl=None,
timeout=None):
"""
Returns a query string which is sent to the validation servers.
"""
data = [('id', self.client_id),
('otp', otp),
('nonce', nonce)]
... | Returns a query string which is sent to the validation servers. |
def controller(self):
"""Show current linked controllers."""
if hasattr(self, 'controllers'):
if len(self.controllers) > 1:
# in the future, we should support more controllers
raise TypeError("Only one controller per account.")
return self.controll... | Show current linked controllers. |
def get_all_webhooks(self, **kwargs): # noqa: E501
"""Get all webhooks for a customer # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_webhooks(async_r... | Get all webhooks for a customer # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_webhooks(async_req=True)
>>> result = thread.get()
:param asyn... |
async def write(self, data):
"""Writes a chunk of data to the streaming response.
:param data: bytes-ish data to be written.
"""
if type(data) != bytes:
data = self._encode_body(data)
self.protocol.push_data(b"%x\r\n%b\r\n" % (len(data), data))
await self.pr... | Writes a chunk of data to the streaming response.
:param data: bytes-ish data to be written. |
def _item_check(self, dim_vals, data):
"""
Applies optional checks to individual data elements before
they are inserted ensuring that they are of a certain
type. Subclassed may implement further element restrictions.
"""
if not self._check_items:
return
... | Applies optional checks to individual data elements before
they are inserted ensuring that they are of a certain
type. Subclassed may implement further element restrictions. |
def get_mapped_filenames(self, memoryMap = None):
"""
Retrieves the filenames for memory mapped files in the debugee.
@type memoryMap: list( L{win32.MemoryBasicInformation} )
@param memoryMap: (Optional) Memory map returned by L{get_memory_map}.
If not given, the current me... | Retrieves the filenames for memory mapped files in the debugee.
@type memoryMap: list( L{win32.MemoryBasicInformation} )
@param memoryMap: (Optional) Memory map returned by L{get_memory_map}.
If not given, the current memory map is used.
@rtype: dict( int S{->} str )
@ret... |
def implementation(self,
commands_module: arg(short_option='-m') = DEFAULT_COMMANDS_MODULE,
config_file: arg(short_option='-f') = None,
# Globals
globals_: arg(
container=dict,
... | Run one or more commands in succession.
For example, assume the commands ``local`` and ``remote`` have been
defined; the following will run ``ls`` first on the local host and
then on the remote host::
runcommands local ls remote <host> ls
When a command name is encountered... |
def liste_campagnes(self, campagne=None):
"""
Liste des campagnes de mesure et des stations associées
Paramètres:
campagne: Si définie, liste des stations que pour cette campagne
"""
condition = ""
if campagne:
condition = "WHERE NOM_COURT_CM='%s' "... | Liste des campagnes de mesure et des stations associées
Paramètres:
campagne: Si définie, liste des stations que pour cette campagne |
def ecef2ned(x: float, y: float, z: float,
lat0: float, lon0: float, h0: float,
ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]:
"""
Convert ECEF x,y,z to North, East, Down
Parameters
----------
x : float or numpy.ndarray of float
ECEF x coo... | Convert ECEF x,y,z to North, East, Down
Parameters
----------
x : float or numpy.ndarray of float
ECEF x coordinate (meters)
y : float or numpy.ndarray of float
ECEF y coordinate (meters)
z : float or numpy.ndarray of float
ECEF z coordinate (meters)
lat0 : float
... |
def write_json(path, params):
"""Write local or remote."""
logger.debug("write %s to %s", params, path)
if path.startswith("s3://"):
bucket = get_boto3_bucket(path.split("/")[2])
key = "/".join(path.split("/")[3:])
logger.debug("upload %s", key)
bucket.put_object(
... | Write local or remote. |
def username(self, value=None):
"""
Return or set the username
:param string value: the new username to use
:returns: string or new :class:`URL` instance
"""
if value is not None:
return URL._mutate(self, username=value)
return unicode_unquote(self._t... | Return or set the username
:param string value: the new username to use
:returns: string or new :class:`URL` instance |
def is_playing_line_in(self):
"""bool: Is the speaker playing line-in?"""
response = self.avTransport.GetPositionInfo([
('InstanceID', 0),
('Channel', 'Master')
])
track_uri = response['TrackURI']
return re.match(r'^x-rincon-stream:', track_uri) is not Non... | bool: Is the speaker playing line-in? |
def UpdateCronJob(self,
cronjob_id,
last_run_status=unchanged,
last_run_time=unchanged,
current_run_id=unchanged,
state=unchanged,
forced_run_requested=unchanged):
"""Updates run information for a... | Updates run information for an existing cron job.
Args:
cronjob_id: The id of the cron job to update.
last_run_status: A CronJobRunStatus object.
last_run_time: The last time a run was started for this cron job.
current_run_id: The id of the currently active run.
state: The state dict... |
def get_candidate_election(self, election):
"""Get a CandidateElection."""
return CandidateElection.objects.get(candidate=self, election=election) | Get a CandidateElection. |
def enforce_dependencies(cls, functions, kind):
'''
This is a class global method to enforce the dependencies that you
currently know about.
It will modify the "functions" dict and remove/replace modules that
are missing dependencies.
'''
for dependency, dependent... | This is a class global method to enforce the dependencies that you
currently know about.
It will modify the "functions" dict and remove/replace modules that
are missing dependencies. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.