code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def chunks_str(str, n, separator="\n", fill_blanks_last=True):
"""returns lines with max n characters
:Example:
>>> print (chunks_str('123456X', 3))
123
456
X
"""
return separator.join(chunks(str, n)) | returns lines with max n characters
:Example:
>>> print (chunks_str('123456X', 3))
123
456
X |
def ifilter(self, recursive=True, matches=None, flags=FLAGS,
forcetype=None):
"""Iterate over nodes in our list matching certain conditions.
If *forcetype* is given, only nodes that are instances of this type (or
tuple of types) are yielded. Setting *recursive* to ``True`` will
... | Iterate over nodes in our list matching certain conditions.
If *forcetype* is given, only nodes that are instances of this type (or
tuple of types) are yielded. Setting *recursive* to ``True`` will
iterate over all children and their descendants. ``RECURSE_OTHERS``
will only iterate ove... |
def _sampleLocationOnDisc(self, top=None):
"""
Helper method to sample from the top and bottom discs of a cylinder.
If top is set to True, samples only from top disc. If top is set to False,
samples only from bottom disc. If not set (defaults to None), samples from
both discs.
"""
if top is... | Helper method to sample from the top and bottom discs of a cylinder.
If top is set to True, samples only from top disc. If top is set to False,
samples only from bottom disc. If not set (defaults to None), samples from
both discs. |
def save(self, overwrite=True):
"""
Saves PopulationSet and TransitSignal.
Shouldn't need to use this if you're using
:func:`FPPCalculation.from_ini`.
Saves :class`PopulationSet` to ``[folder]/popset.h5]``
and :class:`TransitSignal` to ``[folder]/trsig.pkl``.
:... | Saves PopulationSet and TransitSignal.
Shouldn't need to use this if you're using
:func:`FPPCalculation.from_ini`.
Saves :class`PopulationSet` to ``[folder]/popset.h5]``
and :class:`TransitSignal` to ``[folder]/trsig.pkl``.
:param overwrite: (optional)
Whether to o... |
def getWhatIf(number):
""" Returns a :class:`WhatIf` object corresponding to the What If article of
index passed to the function. If the index is less than zero or
greater than the maximum number of articles published thus far,
None is returned instead.
Like all the routines for handling What If articles, :fu... | Returns a :class:`WhatIf` object corresponding to the What If article of
index passed to the function. If the index is less than zero or
greater than the maximum number of articles published thus far,
None is returned instead.
Like all the routines for handling What If articles, :func:`getWhatIfArchive`
is c... |
def input(self, *args, **kwargs):
"""
Adapt the input and check for errors.
Returns a tuple of adapted (args, kwargs) or raises
AnticipateErrors
"""
errors = []
if args and self.arg_names:
args = list(args)
# Replace args inline that have... | Adapt the input and check for errors.
Returns a tuple of adapted (args, kwargs) or raises
AnticipateErrors |
def set_attribute(self, obj, attr, value):
"""Set value of attribute in given object instance.
Reason for existence of this method is the fact that 'attribute' can
be also a object's key if it is a dict or any other kind of mapping.
Args:
obj (object): object instance to mo... | Set value of attribute in given object instance.
Reason for existence of this method is the fact that 'attribute' can
be also a object's key if it is a dict or any other kind of mapping.
Args:
obj (object): object instance to modify
attr (str): attribute (or key) to cha... |
def add(self, relation):
"""Add the relation inner to the cache, under the schema schema and
identifier identifier
:param BaseRelation relation: The underlying relation.
"""
cached = _CachedRelation(relation)
logger.debug('Adding relation: {!s}'.format(cached))
l... | Add the relation inner to the cache, under the schema schema and
identifier identifier
:param BaseRelation relation: The underlying relation. |
def get_parsed_data(fn, *args, **kwargs):
"""All above functions as a single function
:param str fn: file name
:return list parsed_data: structured metadata
"""
file_format = detect_format(fn, *args, **kwargs)
data = get_header(fn, file_format, *args, **kwargs)
parsed_data = parse_heade... | All above functions as a single function
:param str fn: file name
:return list parsed_data: structured metadata |
def listBlockChildren(self, block_name=""):
"""
list parents of a block
"""
if (not block_name) or re.search("['%','*']", block_name):
dbsExceptionHandler("dbsException-invalid-input", "DBSBlock/listBlockChildren. Block_name must be provided." )
conn = self.dbi.connec... | list parents of a block |
def _get_job_status(line):
"""magic used as an endpoint for client to get job status.
%_get_job_status <name>
Returns:
A JSON object of the job status.
"""
try:
args = line.strip().split()
job_name = args[0]
job = None
if job_name in _local_jobs:
job = _local_jobs[job_name]
... | magic used as an endpoint for client to get job status.
%_get_job_status <name>
Returns:
A JSON object of the job status. |
def _get_github(self):
"""Creates an instance of github.Github to interact with the repos via the
API interface in pygithub.
"""
from github import Github
vms("Querying github with user '{}'.".format(self.username))
g = Github(self.username, self.apikey)
self._us... | Creates an instance of github.Github to interact with the repos via the
API interface in pygithub. |
def update(self, _values=None, **values):
"""
Update a record in the database
:param values: The values of the update
:type values: dict
:return: The number of records affected
:rtype: int
"""
if _values is not None:
values.update(_values)
... | Update a record in the database
:param values: The values of the update
:type values: dict
:return: The number of records affected
:rtype: int |
def create(self, data, **kwargs):
"""Create a new object.
Args:
data (dict): parameters to send to the server to create the
resource
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
RESTObject, RESTObject: The sourc... | Create a new object.
Args:
data (dict): parameters to send to the server to create the
resource
**kwargs: Extra options to send to the server (e.g. sudo)
Returns:
RESTObject, RESTObject: The source and target issues
Raises:
... |
def list_functions(region=None, key=None, keyid=None, profile=None):
'''
List all Lambda functions visible in the current scope.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.list_functions
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
... | List all Lambda functions visible in the current scope.
CLI Example:
.. code-block:: bash
salt myminion boto_lambda.list_functions |
def smooth_angle_channels(self, channels):
"""Remove discontinuities in angle channels so that they don't cause artifacts in algorithms that rely on the smoothness of the functions."""
for vertex in self.vertices:
for col in vertex.meta['rot_ind']:
if col:
... | Remove discontinuities in angle channels so that they don't cause artifacts in algorithms that rely on the smoothness of the functions. |
def rates(ctx, opts):
"""Check current API rate limits."""
click.echo("Retrieving rate limits ... ", nl=False)
context_msg = "Failed to retrieve status!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
resources_limits = get_rate_limits... | Check current API rate limits. |
def _prompt(pre_prompt, items, post_prompt, default, indexed, stream):
'''
Prompt once.
If you want the default displayed, put a format {} into the
post_prompt string (like 'select one [{}]: ')
'''
# try to sub in the default if provided
if default is not None:
if '{}' in pre_prompt:... | Prompt once.
If you want the default displayed, put a format {} into the
post_prompt string (like 'select one [{}]: ') |
def snake_to_camel(value):
"""
Converts a snake_case_string to a camelCaseString.
>>> snake_to_camel("foo_bar_baz")
'fooBarBaz'
"""
camel = "".join(word.title() for word in value.split("_"))
return value[:1].lower() + camel[1:] | Converts a snake_case_string to a camelCaseString.
>>> snake_to_camel("foo_bar_baz")
'fooBarBaz' |
def appendComponent(self, baseGlyph=None, offset=None, scale=None, component=None):
"""
Append a component to this glyph.
>>> component = glyph.appendComponent("A")
This will return a :class:`BaseComponent` object representing
the new component in the glyph. ``offset`` indi... | Append a component to this glyph.
>>> component = glyph.appendComponent("A")
This will return a :class:`BaseComponent` object representing
the new component in the glyph. ``offset`` indicates the x and
y shift values that should be applied to the appended component.
It must... |
def get_hosting_device_plugging_driver(self, context, id):
"""Returns plugging driver for hosting device template with <id>."""
if id is None:
return
try:
return self._plugging_drivers[id]
except KeyError:
try:
template = self._get_hos... | Returns plugging driver for hosting device template with <id>. |
def group(requestContext, *seriesLists):
"""
Takes an arbitrary number of seriesLists and adds them to a single
seriesList. This is used to pass multiple seriesLists to a function which
only takes one.
"""
seriesGroup = []
for s in seriesLists:
seriesGroup.extend(s)
return serie... | Takes an arbitrary number of seriesLists and adds them to a single
seriesList. This is used to pass multiple seriesLists to a function which
only takes one. |
def get_all_rules(cls):
"Load all available Adblock rules."
from adblockparser import AdblockRules
raw_rules = []
for url in [
config.ADBLOCK_EASYLIST_URL, config.ADBLOCK_EXTRALIST_URL]:
raw_rules.extend(cls.load_raw_rules(url))
rules = ... | Load all available Adblock rules. |
def _get_network(self, kind, router=True, vlans=True, vlan_ids=True):
"""Wrapper for getting details about networks.
:param string kind: network kind. Typically 'public' or 'private'
:param boolean router: flag to include router information
:param boolean vlans: flag to incl... | Wrapper for getting details about networks.
:param string kind: network kind. Typically 'public' or 'private'
:param boolean router: flag to include router information
:param boolean vlans: flag to include vlan information
:param boolean vlan_ids: flag to include vlan_id... |
def process(self, request):
"""
process determines if this item should visible, if its selected, etc...
"""
# if we're not visible we return since we don't need to do anymore processing
self.check(request)
if not self.visible:
return
# evaluate our ti... | process determines if this item should visible, if its selected, etc... |
def check_connection (self):
"""
Connect to NNTP server and try to request the URL article
resource (if specified).
"""
nntpserver = self.host or self.aggregate.config["nntpserver"]
if not nntpserver:
self.add_warning(
_("No NNTP server was... | Connect to NNTP server and try to request the URL article
resource (if specified). |
def get_projections_on_elements_and_orbitals(self, el_orb_spec):
"""
Method returning a dictionary of projections on elements and specific
orbitals
Args:
el_orb_spec: A dictionary of Elements and Orbitals for which we want
to have projections on. It is given ... | Method returning a dictionary of projections on elements and specific
orbitals
Args:
el_orb_spec: A dictionary of Elements and Orbitals for which we want
to have projections on. It is given as: {Element:[orbitals]},
e.g., {'Si':['3s','3p']} or {'Si':['3s','3p... |
def build_iiif_file_storage_path(url_path, ik_image, iiif_storage):
"""
Return the file storage path for a given IIIF Image API URL path.
NOTE: The returned file storage path includes the given ``Image``
instance's ID to ensure the path is unique and identifiable, and its
modified timestamp to act ... | Return the file storage path for a given IIIF Image API URL path.
NOTE: The returned file storage path includes the given ``Image``
instance's ID to ensure the path is unique and identifiable, and its
modified timestamp to act as a primitive cache-busting mechanism for
when the image is changed but the... |
def _contains_yieldpoint(children):
"""Returns True if ``children`` contains any YieldPoints.
``children`` may be a dict or a list, as used by `MultiYieldPoint`
and `multi_future`.
"""
if isinstance(children, dict):
return any(isinstance(i, YieldPoint) for i in children.values())
if isi... | Returns True if ``children`` contains any YieldPoints.
``children`` may be a dict or a list, as used by `MultiYieldPoint`
and `multi_future`. |
def financials(self, security):
"""
get financials:
google finance provide annual and quanter financials, if annual is true, we will use annual data
Up to four lastest year/quanter data will be provided by google
Refer to page as an example: http://www.google.com/finance?q=T... | get financials:
google finance provide annual and quanter financials, if annual is true, we will use annual data
Up to four lastest year/quanter data will be provided by google
Refer to page as an example: http://www.google.com/finance?q=TSE:CVG&fstype=ii |
def get_default_download_dir(self, *subdirs):
""" Get the download path for a file. If not defined, return default
from config.
Parameters
==========
subdirs: a single (or list of) subfolders under the basepath
"""
# Look up value for key "path" i... | Get the download path for a file. If not defined, return default
from config.
Parameters
==========
subdirs: a single (or list of) subfolders under the basepath |
def on_enter(self, command):
"""on_enter"""
if self.profile:
# Simple profiling test
t0 = time()
for _ in range(10):
self.execute_command(command)
self.insert_text(u"\n<Δt>=%dms\n" % (1e2*(time()-t0)))
self.new_prompt(se... | on_enter |
def ignore(self, *ignore_lst: str):
"""
ignore a set of tokens with specific names
"""
def stream():
for each in ignore_lst:
each = ConstStrPool.cast_to_const(each)
yield id(each), each
self.ignore_lst.update(stream()) | ignore a set of tokens with specific names |
def insertPrimaryDataset(self):
"""
API to insert A primary dataset in DBS
:param primaryDSObj: primary dataset object
:type primaryDSObj: dict
:key primary_ds_type: TYPE (out of valid types in DBS, MC, DATA) (Required)
:key primary_ds_name: Name of the primary dataset (... | API to insert A primary dataset in DBS
:param primaryDSObj: primary dataset object
:type primaryDSObj: dict
:key primary_ds_type: TYPE (out of valid types in DBS, MC, DATA) (Required)
:key primary_ds_name: Name of the primary dataset (Required) |
def multi_buffering(layer, radii, callback=None):
"""Buffer a vector layer using many buffers (for volcanoes or rivers).
This processing algorithm will keep the original attribute table and
will add a new one for the hazard class name according to
safe.definitions.fields.hazard_value_field.
radii ... | Buffer a vector layer using many buffers (for volcanoes or rivers).
This processing algorithm will keep the original attribute table and
will add a new one for the hazard class name according to
safe.definitions.fields.hazard_value_field.
radii = OrderedDict()
radii[500] = 'high'
radii[1000] =... |
def _style_to_xlwt(cls, item, firstlevel=True, field_sep=',',
line_sep=';'):
"""helper which recursively generate an xlwt easy style string
for example:
hstyle = {"font": {"bold": True},
"border": {"top": "thin",
"right": "thin",
... | helper which recursively generate an xlwt easy style string
for example:
hstyle = {"font": {"bold": True},
"border": {"top": "thin",
"right": "thin",
"bottom": "thin",
"left": "thin"},
"align": {"horiz": "center"}}
... |
def can(self, *args, **kwargs):
'''Overwrite this method to implement custom contextual permissions'''
if isinstance(self.require, auth.Permission):
return self.require.can()
elif callable(self.require):
return self.require()
elif isinstance(self.require, bool):
... | Overwrite this method to implement custom contextual permissions |
def integrity_negotiated(self):
"""
After :meth:`step` has been called, this property will be set to
True if integrity protection (signing) has been negotiated in this context, False
otherwise. If this property is True, you can use :meth:`get_mic` to sign messages with a
message ... | After :meth:`step` has been called, this property will be set to
True if integrity protection (signing) has been negotiated in this context, False
otherwise. If this property is True, you can use :meth:`get_mic` to sign messages with a
message integrity code (MIC), which the peer application can... |
def iter_fit_shifts(xy,uv,nclip=3,sigma=3.0):
""" Perform an iterative-fit with 'nclip' iterations
"""
fit = fit_shifts(xy,uv)
if nclip is None: nclip = 0
# define index to initially include all points
for n in range(nclip):
resids = compute_resids(xy,uv,fit)
resids1d = np.sqrt(n... | Perform an iterative-fit with 'nclip' iterations |
def _checkServer(self, address, port):
"""
*Check that the TCP Port we've decided to use for tunnelling is available*
"""
# CREATE A TCP SOCKET
import socket
s = socket.socket()
try:
s.connect((address, port))
return True
except so... | *Check that the TCP Port we've decided to use for tunnelling is available* |
def update_hit_tally(self):
''' Tally hits '''
if not self.quiet:
num_hits = self.amt_services_wrapper.tally_hits()
if self.sandbox:
self.sandbox_hits = num_hits
else:
self.live_hits = num_hits | Tally hits |
def superclass(self, klass):
"""True if the Class is a superclass of the given one."""
return bool(lib.EnvSuperclassP(self._env, self._cls, klass._cls)) | True if the Class is a superclass of the given one. |
def scalar_projection(v1, v2):
'''compute the scalar projection of v1 upon v2
Args:
v1, v2: iterable
indices 0, 1, 2 corresponding to cartesian coordinates
Returns:
3-vector of the projection of point p onto the direction of v
'''
return np.dot(v1, v2) / np.linalg.norm(v2) | compute the scalar projection of v1 upon v2
Args:
v1, v2: iterable
indices 0, 1, 2 corresponding to cartesian coordinates
Returns:
3-vector of the projection of point p onto the direction of v |
def explain(self, sql=None, sql_args=None):
"""
Runs EXPLAIN on this query
:type sql: str or None
:param sql: The sql to run EXPLAIN on. If None is specified, the query will
use ``self.get_sql()``
:type sql_args: dict or None
:param sql_args: A dictionary of... | Runs EXPLAIN on this query
:type sql: str or None
:param sql: The sql to run EXPLAIN on. If None is specified, the query will
use ``self.get_sql()``
:type sql_args: dict or None
:param sql_args: A dictionary of the arguments to be escaped in the query. If None and
... |
def get_function_args(func, no_self=False, no_varargs=False):
"""
Return tuple of the function argument names in the order of the function signature.
:param func: Function
:type func: function object
:param no_self: Flag that indicates whether the function argument *self*,
if ... | Return tuple of the function argument names in the order of the function signature.
:param func: Function
:type func: function object
:param no_self: Flag that indicates whether the function argument *self*,
if present, is included in the output (False) or not (True)
:type no_sel... |
def run_section(self, name, input_func=_stdin_):
"""Run the given section."""
print('\nStuff %s by the license:\n' % name)
section = self.survey[name]
for question in section:
self.run_question(question, input_func) | Run the given section. |
def upload_data(job, master_ip, inputs, hdfs_name, upload_name, spark_on_toil):
"""
Upload file hdfsName from hdfs to s3
"""
if mock_mode():
truncate_file(master_ip, hdfs_name, spark_on_toil)
log.info("Uploading output BAM %s to %s.", hdfs_name, upload_name)
call_conductor(job, master_... | Upload file hdfsName from hdfs to s3 |
def _check_tunnel(self, _srv):
""" Check if tunnel is already established """
if self.skip_tunnel_checkup:
self.tunnel_is_up[_srv.local_address] = True
return
self.logger.info('Checking tunnel to: {0}'.format(_srv.remote_address))
if isinstance(_srv.local_address,... | Check if tunnel is already established |
def olympic_sprints(data_set='rogers_girolami_data'):
"""All olympics sprint winning times for multiple output prediction."""
X = np.zeros((0, 2))
Y = np.zeros((0, 1))
cats = {}
for i, dataset in enumerate([olympic_100m_men,
olympic_100m_women,
... | All olympics sprint winning times for multiple output prediction. |
def visitAdditionOrSubtractionExpression(self, ctx):
"""
expression: expression (PLUS | MINUS) expression
"""
is_add = ctx.PLUS() is not None
arg1 = self.visit(ctx.expression(0))
arg2 = self.visit(ctx.expression(1))
# first try as decimals
try:
... | expression: expression (PLUS | MINUS) expression |
def callback(self, event):
"""
Function that gets called on each event from pyinotify.
"""
# IN_CLOSE_WRITE -> 0x00000008
if event.mask == 0x00000008:
if event.name.endswith('.json'):
print_success("Ldapdomaindump file found")
if ev... | Function that gets called on each event from pyinotify. |
def _get_lts_from_user(self, user):
""" Get layertemplates owned by a user from the database. """
req = meta.Session.query(LayerTemplate).select_from(join(LayerTemplate, User))
return req.filter(User.login==user).all() | Get layertemplates owned by a user from the database. |
def libvlc_video_get_track_description(p_mi):
'''Get the description of available video tracks.
@param p_mi: media player.
@return: list with description of available video tracks, or NULL on error.
'''
f = _Cfunctions.get('libvlc_video_get_track_description', None) or \
_Cfunction('libvlc_v... | Get the description of available video tracks.
@param p_mi: media player.
@return: list with description of available video tracks, or NULL on error. |
def _ReadDataTypeDefinitionWithMembers(
self, definitions_registry, definition_values,
data_type_definition_class, definition_name, supports_conditions=False):
"""Reads a data type definition with members.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
... | Reads a data type definition with members.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str, object]): definition values.
data_type_definition_class (str): data type definition class.
definition_name (str): name ... |
def get_source(fileobj):
"""Translate fileobj into file contents.
fileobj is either a string or a dict. If it's a string, that's the
file contents. If it's a string, then the filename key contains
the name of the file whose contents we are to use.
If the dict contains a true value for the key dele... | Translate fileobj into file contents.
fileobj is either a string or a dict. If it's a string, that's the
file contents. If it's a string, then the filename key contains
the name of the file whose contents we are to use.
If the dict contains a true value for the key delete_after_use,
the file shoul... |
def team_matches(self, team, event=None, year=None, simple=False, keys=False):
"""
Get list of matches team has participated in.
:param team: Team to get matches of.
:param year: Year to get matches from.
:param event: Event to get matches from.
:param simple: Get only v... | Get list of matches team has participated in.
:param team: Team to get matches of.
:param year: Year to get matches from.
:param event: Event to get matches from.
:param simple: Get only vital data.
:param keys: Only get match keys rather than their full data.
:return: L... |
def add_console_message(self, message_type, message):
"""add messages in the console_messages list
"""
for m in message.split("\n"):
if m.strip():
self.console_messages.append((message_type, m)) | add messages in the console_messages list |
def append(self, element):
'''
Append a PileupElement to this Pileup. If an identical PileupElement is
already part of this Pileup, do nothing.
'''
assert element.locus == self.locus, (
"Element locus (%s) != Pileup locus (%s)"
% (element.locus, self.locus... | Append a PileupElement to this Pileup. If an identical PileupElement is
already part of this Pileup, do nothing. |
def get_command_from_module(
command_module,
remote_connection: environ.RemoteConnection
):
"""
Returns the execution command to use for the specified module, which may
be different depending upon remote connection
:param command_module:
:param remote_connection:
:return:
""... | Returns the execution command to use for the specified module, which may
be different depending upon remote connection
:param command_module:
:param remote_connection:
:return: |
def connect(self, url=None):
"""
Connect to the bugzilla instance with the given url. This is
called by __init__ if a URL is passed. Or it can be called manually
at any time with a passed URL.
This will also read any available config files (see readconfig()),
which may s... | Connect to the bugzilla instance with the given url. This is
called by __init__ if a URL is passed. Or it can be called manually
at any time with a passed URL.
This will also read any available config files (see readconfig()),
which may set 'user' and 'password', and others.
If... |
def _number_of_line(member_tuple):
"""Try to return the number of the first line of the definition of a
member of a module."""
member = member_tuple[1]
try:
return member.__code__.co_firstlineno
except AttributeError:
pass
try:
return inspect.findsource(member)[1]
exc... | Try to return the number of the first line of the definition of a
member of a module. |
def _GetSectionNames(self, pefile_object):
"""Retrieves all PE section names.
Args:
pefile_object (pefile.PE): pefile object.
Returns:
list[str]: names of the sections.
"""
section_names = []
for section in pefile_object.sections:
section_name = getattr(section, 'Name', b'')
... | Retrieves all PE section names.
Args:
pefile_object (pefile.PE): pefile object.
Returns:
list[str]: names of the sections. |
def service_messages(self, short_name):
"""Get the messages stored for a service.
Args:
short_name (string): The short name of the service to get messages for
Returns:
list(ServiceMessage): A list of the ServiceMessages stored for this service
"""
if sh... | Get the messages stored for a service.
Args:
short_name (string): The short name of the service to get messages for
Returns:
list(ServiceMessage): A list of the ServiceMessages stored for this service |
def is_null(*symbols):
""" True if no nodes or all the given nodes are either
None, NOP or empty blocks. For blocks this applies recursively
"""
from symbols.symbol_ import Symbol
for sym in symbols:
if sym is None:
continue
if not isinstance(sym, Symbol):
re... | True if no nodes or all the given nodes are either
None, NOP or empty blocks. For blocks this applies recursively |
def logical_name(self):
"""The logical name of the seat.
This is an identifier to group sets of devices within the compositor.
Returns:
str: The logical name of this seat.
"""
pchar = self._libinput.libinput_seat_get_logical_name(self._handle)
return string_at(pchar).decode() | The logical name of the seat.
This is an identifier to group sets of devices within the compositor.
Returns:
str: The logical name of this seat. |
def stream_interactions(self):
"""Generate a temporal ordered stream of interactions.
Returns
-------
nd_iter : an iterator
The iterator returns a 4-tuples of (node, node, op, timestamp).
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_pat... | Generate a temporal ordered stream of interactions.
Returns
-------
nd_iter : an iterator
The iterator returns a 4-tuples of (node, node, op, timestamp).
Examples
--------
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> G.add_path([... |
def add(self, *tasks):
""" Interfaces the GraphNode `add` method
"""
nodes = [x.node for x in tasks]
self.node.add(*nodes)
return self | Interfaces the GraphNode `add` method |
def _get_multiparts(response):
"""
From this
'multipart/parallel; boundary="874e43d27ec6d83f30f37841bdaf90c7"; charset=utf-8'
get this
--874e43d27ec6d83f30f37841bdaf90c7
"""
boundary = None
for part in response.headers.get('Content-Type', '').split(';'):
... | From this
'multipart/parallel; boundary="874e43d27ec6d83f30f37841bdaf90c7"; charset=utf-8'
get this
--874e43d27ec6d83f30f37841bdaf90c7 |
def victim_pivot(self, victim_resource):
"""Pivot point on Victims for this resource.
This method will return all *resources* (group, indicators, task,
etc) for this resource that are associated with the provided victim id.
**Example Endpoints URI's**
+--------------+---------... | Pivot point on Victims for this resource.
This method will return all *resources* (group, indicators, task,
etc) for this resource that are associated with the provided victim id.
**Example Endpoints URI's**
+--------------+-------------------------------------------------------------... |
def getall(self, key, default=_marker):
"""Return a list of all values matching the key."""
identity = self._title(key)
res = [v for i, k, v in self._impl._items if i == identity]
if res:
return res
if not res and default is not _marker:
return default
... | Return a list of all values matching the key. |
def compile_pattern_list(self, patterns):
'''This compiles a pattern-string or a list of pattern-strings.
Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
those. Patterns may also be None which results in an empty list (you
might do this if waiting for an EOF or TIM... | This compiles a pattern-string or a list of pattern-strings.
Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
those. Patterns may also be None which results in an empty list (you
might do this if waiting for an EOF or TIMEOUT condition without
expecting any pattern)... |
def _clearPrices(self):
""" Clears prices according to auction type.
"""
for offbid in self.offers + self.bids:
if self.auctionType == DISCRIMINATIVE:
offbid.clearedPrice = offbid.price
elif self.auctionType == FIRST_PRICE:
offbid.clearedPr... | Clears prices according to auction type. |
def collect(self):
"""
Overrides the Collector.collect method
"""
if psutil is None:
self.log.error('Unable to import module psutil')
return {}
for port_name, port_cfg in self.ports.iteritems():
port = int(port_cfg['number'])
stat... | Overrides the Collector.collect method |
def enumerate_dynamic_imports(tokens):
"""
Returns a dictionary of all dynamically imported modules (those inside of
classes or functions) in the form of {<func or class name>: [<modules>]}
Example:
>>> enumerate_dynamic_modules(tokens)
{'myfunc': ['zlib', 'base64']}
"""
importe... | Returns a dictionary of all dynamically imported modules (those inside of
classes or functions) in the form of {<func or class name>: [<modules>]}
Example:
>>> enumerate_dynamic_modules(tokens)
{'myfunc': ['zlib', 'base64']} |
def handle_moban_file(moban_file, options):
"""
act upon default moban file
"""
moban_file_configurations = load_data(None, moban_file)
if moban_file_configurations is None:
raise exceptions.MobanfileGrammarException(
constants.ERROR_INVALID_MOBAN_FILE % moban_file
)
... | act upon default moban file |
def execute_proc(procname, args=()):
"""
Execute a stored procedure. Returns the number of affected rows.
"""
ctx = Context.current()
with ctx.mdr:
cursor = ctx.execute_proc(procname, args)
row_count = cursor.rowcount
_safe_close(cursor)
return row_count | Execute a stored procedure. Returns the number of affected rows. |
def remove_formatting_codes(line, irc=False):
"""Remove girc control codes from the given line."""
if irc:
line = escape(line)
new_line = ''
while len(line) > 0:
try:
if line[0] == '$':
line = line[1:]
if line[0] == '$':
ne... | Remove girc control codes from the given line. |
def _init_metadata(self):
"""stub"""
self._inline_regions_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
'inline_regions'),
'element_label': 'set of inline regions',... | stub |
def modify(connect_spec, dn, directives):
'''Modify an entry in an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:param directives:
Iterable of directives... | Modify an entry in an LDAP database.
:param connect_spec:
See the documentation for the ``connect_spec`` parameter for
:py:func:`connect`.
:param dn:
Distinguished name of the entry.
:param directives:
Iterable of directives that indicate how to modify the entry.
E... |
def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
"""Expand python variables in a string.
The depth argument indicates how many frames above the caller should
be walked to look for the local namespace where to expand variables.
The global namespace for expansion is alway... | Expand python variables in a string.
The depth argument indicates how many frames above the caller should
be walked to look for the local namespace where to expand variables.
The global namespace for expansion is always the user's interactive
namespace. |
def trash(self, request, **kwargs):
"""Psuedo-deletes a `Content` instance and removes it from the ElasticSearch index
Content is not actually deleted, merely hidden by deleted from ES index.import
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
... | Psuedo-deletes a `Content` instance and removes it from the ElasticSearch index
Content is not actually deleted, merely hidden by deleted from ES index.import
:param request: a WSGI request object
:param kwargs: keyword arguments (optional)
:return: `rest_framework.response.Response` |
def genl_msg_parser(ops, who, nlh, pp):
"""https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L85.
Positional arguments:
ops -- nl_cache_ops class instance.
who -- sockaddr_nl class instance.
nlh -- nlmsghdr class instance.
pp -- nl_parser_param class instance.
Returns:
... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L85.
Positional arguments:
ops -- nl_cache_ops class instance.
who -- sockaddr_nl class instance.
nlh -- nlmsghdr class instance.
pp -- nl_parser_param class instance.
Returns:
Integer, cmd_msg_parser() output. |
def parse_basic_type_str(old_normalizer):
"""
Modifies a normalizer to automatically parse the incoming type string. If
that type string does not represent a basic type (i.e. non-tuple type) or is
not parsable, the normalizer does nothing.
"""
@functools.wraps(old_normalizer)
def new_normal... | Modifies a normalizer to automatically parse the incoming type string. If
that type string does not represent a basic type (i.e. non-tuple type) or is
not parsable, the normalizer does nothing. |
def cat_trials(x3d):
"""Concatenate trials along time axis.
Parameters
----------
x3d : array, shape (t, m, n)
Segmented input data with t trials, m signals, and n samples.
Returns
-------
x2d : array, shape (m, t * n)
Trials are concatenated along the second axis.
See... | Concatenate trials along time axis.
Parameters
----------
x3d : array, shape (t, m, n)
Segmented input data with t trials, m signals, and n samples.
Returns
-------
x2d : array, shape (m, t * n)
Trials are concatenated along the second axis.
See also
--------
cut_s... |
def from_tuples_array(tuples):
"""
Creates a new StringValueMap from a list of key-value pairs called tuples.
The method is similar to [[fromTuples]] but tuples are passed as array instead of parameters.
:param tuples: a list of values where odd elements are keys and the following even ... | Creates a new StringValueMap from a list of key-value pairs called tuples.
The method is similar to [[fromTuples]] but tuples are passed as array instead of parameters.
:param tuples: a list of values where odd elements are keys and the following even elements are values
:return: a newly creat... |
def stop(self):
"""Send a TX_DELETE message to cancel this task.
This will delete the entry for the transmission of the CAN-message
with the specified can_id CAN identifier. The message length for the command
TX_DELETE is {[bcm_msg_head]} (only the header).
"""
log.debug... | Send a TX_DELETE message to cancel this task.
This will delete the entry for the transmission of the CAN-message
with the specified can_id CAN identifier. The message length for the command
TX_DELETE is {[bcm_msg_head]} (only the header). |
def write(self, target, *args, **kwargs):
"""Write this `SegmentList` to a file
Arguments and keywords depend on the output format, see the
online documentation for full details for each format.
Parameters
----------
target : `str`
output filename
N... | Write this `SegmentList` to a file
Arguments and keywords depend on the output format, see the
online documentation for full details for each format.
Parameters
----------
target : `str`
output filename
Notes
----- |
def subdivide(network, pores, shape, labels=[]):
r'''
It trim the pores and replace them by cubic networks with the sent shape.
Parameters
----------
network : OpenPNM Network Object
pores : array_like
The first group of pores to be replaced
shape : array_like
The shape of... | r'''
It trim the pores and replace them by cubic networks with the sent shape.
Parameters
----------
network : OpenPNM Network Object
pores : array_like
The first group of pores to be replaced
shape : array_like
The shape of cubic networks in the target locations
Notes
... |
def print_objective(x):
"""Calculate the objective value and prints it."""
value = 0
for minp, maxp in rectangles:
x_proj = np.minimum(np.maximum(x, minp), maxp)
value += (x - x_proj).norm()
print('Point = [{:.4f}, {:.4f}], Value = {:.4f}'.format(x[0], x[1], value)) | Calculate the objective value and prints it. |
def collapse_pane(self, side):
"""
Toggle collapsing the left or right panes.
"""
# TODO: this is too tied to one configuration, need to figure
# out how to generalize this
hsplit = self.w['hpnl']
sizes = hsplit.get_sizes()
lsize, msize, rsize = sizes
... | Toggle collapsing the left or right panes. |
def icon(self):
"""
Returns the icon filepath for this plugin.
:return <str>
"""
path = self._icon
if not path:
return ''
path = os.path.expandvars(os.path.expanduser(path))
if path.startswith('.'):
base_path = os.path... | Returns the icon filepath for this plugin.
:return <str> |
def get_registry_records_by_keyword(keyword=None):
"""Get all the registry records (names and values) whose name
contains the specified keyword or, if keyword is None, return
all registry items
:param keyword: The keyword that has to be contained in the record name
:type keyword: str or None
... | Get all the registry records (names and values) whose name
contains the specified keyword or, if keyword is None, return
all registry items
:param keyword: The keyword that has to be contained in the record name
:type keyword: str or None
:returns: Dictionary mapping the names of the found record... |
def _updateVariantAnnotationSets(self, variantFile, dataUrl):
"""
Updates the variant annotation set associated with this variant using
information in the specified pysam variantFile.
"""
# TODO check the consistency of this between VCF files.
if not self.isAnnotated():
... | Updates the variant annotation set associated with this variant using
information in the specified pysam variantFile. |
def list_keyvaults(access_token, subscription_id, rgname):
'''Lists key vaults in the named resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
Returns:
HTTP res... | Lists key vaults in the named resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
Returns:
HTTP response. 200 OK. |
def do_help(self, line):
"""Displays help information."""
print ""
print "Perfdump CLI provides a handful of simple ways to query your"
print "performance data."
print ""
print "The simplest queries are of the form:"
print ""
print "\t[slowest|fastest] [te... | Displays help information. |
def title(self) -> str:
"""Get/Set title string of this document."""
title_element = _find_tag(self.head, 'title')
if title_element:
return title_element.textContent
return '' | Get/Set title string of this document. |
def get(self, mode, metric):
"""Get the history for the given metric and mode."""
if mode not in self._values:
logging.info("Metric %s not found for mode %s", metric, mode)
return []
return list(self._values[mode][metric]) | Get the history for the given metric and mode. |
def serial_udb_extra_f4_send(self, sue_ROLL_STABILIZATION_AILERONS, sue_ROLL_STABILIZATION_RUDDER, sue_PITCH_STABILIZATION, sue_YAW_STABILIZATION_RUDDER, sue_YAW_STABILIZATION_AILERON, sue_AILERON_NAVIGATION, sue_RUDDER_NAVIGATION, sue_ALTITUDEHOLD_STABILIZED, sue_ALTITUDEHOLD_WAYPOINT, sue_RACING_MODE, force_mavlink1=... | Backwards compatible version of SERIAL_UDB_EXTRA F4: format
sue_ROLL_STABILIZATION_AILERONS : Serial UDB Extra Roll Stabilization with Ailerons Enabled (uint8_t)
sue_ROLL_STABILIZATION_RUDDER : Serial UDB Extra Roll Stabilization with Rudder Enabled (uint8_t)
... |
def filepaths(path, exclude=(), hidden=True, empty=True):
"""
Return list of absolute, sorted file paths
path: Path to file or directory
exclude: List of file name patterns to exclude
hidden: Whether to include hidden files
empty: Whether to include empty files
Raise PathNotFoundError if p... | Return list of absolute, sorted file paths
path: Path to file or directory
exclude: List of file name patterns to exclude
hidden: Whether to include hidden files
empty: Whether to include empty files
Raise PathNotFoundError if path doesn't exist. |
def save_failed_dump(self):
"""
Save dump of failed request for debugging.
This method is called then fatal network exception is raised.
The saved dump could be used for debugging the reason of the failure.
"""
# try/except for safety, to not break live spiders
... | Save dump of failed request for debugging.
This method is called then fatal network exception is raised.
The saved dump could be used for debugging the reason of the failure. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.