code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
... | Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which Zypper refers to the repo
url, mirrorlist or baseurl
the URL for Zypper to reference
enabled
Enable or disable (Tru... |
def cleanup(arctic_lib, symbol, version_ids, versions_coll, shas_to_delete=None, pointers_cfgs=None):
"""
Helper method for cleaning up chunks from a version store
"""
pointers_cfgs = set(pointers_cfgs) if pointers_cfgs else set()
collection = arctic_lib.get_top_level_collection()
version_ids = ... | Helper method for cleaning up chunks from a version store |
def setDataFrame(self, dataFrame, copyDataFrame=False, filePath=None):
"""
Setter function to _dataFrame. Holds all data.
Note:
It's not implemented with python properties to keep Qt conventions.
Raises:
TypeError: if dataFrame is not of type pandas.core.frame.D... | Setter function to _dataFrame. Holds all data.
Note:
It's not implemented with python properties to keep Qt conventions.
Raises:
TypeError: if dataFrame is not of type pandas.core.frame.DataFrame.
Args:
dataFrame (pandas.core.frame.DataFrame): assign dataFr... |
def getAttributeNode(self, attr: str) -> Optional[Attr]:
"""Get attribute of this node as Attr format.
If this node does not have ``attr``, return None.
"""
return self.attributes.getNamedItem(attr) | Get attribute of this node as Attr format.
If this node does not have ``attr``, return None. |
def processes(self, plantuml_text):
"""Processes the plantuml text into the raw PNG image data.
:param str plantuml_text: The plantuml markup to render
:returns: the raw image data
"""
url = self.get_url(plantuml_text)
try:
response, content = self.ht... | Processes the plantuml text into the raw PNG image data.
:param str plantuml_text: The plantuml markup to render
:returns: the raw image data |
def add(name, function_name, cron):
""" Create an event """
lambder.add_event(name=name, function_name=function_name, cron=cron) | Create an event |
def verify(self, verifier, consumer_key=None, consumer_secret=None,
access_token=None, access_token_secret=None):
"""
After converting the token into verifier, call this to finalize the
authorization.
"""
# Stored values can be supplied to verify
self.consu... | After converting the token into verifier, call this to finalize the
authorization. |
def disvecinf(self, x, y, aq=None):
'''Can be called with only one x,y value'''
if aq is None: aq = self.model.aq.find_aquifer_data(x, y)
rv = np.zeros((2, self.nparam, aq.naq))
if aq == self.aq:
qxqy = np.zeros((2, aq.naq))
qxqy[:, :] = self.bessel.disbeslsho(flo... | Can be called with only one x,y value |
def desaturate(c, k=0):
"""
Utility function to desaturate a color c by an amount k.
"""
from matplotlib.colors import ColorConverter
c = ColorConverter().to_rgb(c)
intensity = 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]
return [intensity * k + i * (1 - k) for i in c] | Utility function to desaturate a color c by an amount k. |
def add_marker_to_qtls(qtlfile, mapfile, outputfile='qtls_with_mk.csv'):
"""This function adds to a list of QTLs, the closest marker to the
QTL peak.
:arg qtlfile: a CSV list of all the QTLs found.
The file should be structured as follow::
Trait, Linkage group, position, other columns
... | This function adds to a list of QTLs, the closest marker to the
QTL peak.
:arg qtlfile: a CSV list of all the QTLs found.
The file should be structured as follow::
Trait, Linkage group, position, other columns
The other columns will not matter as long as the first three
col... |
def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only images of current node
"""
super(NodeImageList, self).initial(request, *args, **kwargs)
# en... | Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only images of current node |
def _setSampleSizeBytes(self):
"""
updates the current record of the packet size per sample and the relationship between this and the fifo reads.
"""
self.sampleSizeBytes = self.getPacketSize()
if self.sampleSizeBytes > 0:
self.maxBytesPerFifoRead = (32 // self.sampl... | updates the current record of the packet size per sample and the relationship between this and the fifo reads. |
def get_authorizations_for_resource_and_function(self, resource_id, function_id):
"""Gets a list of ``Authorizations`` associated with a given resource.
Authorizations related to the given resource, including those
related through an ``Agent,`` are returned. In plenary mode, the
returne... | Gets a list of ``Authorizations`` associated with a given resource.
Authorizations related to the given resource, including those
related through an ``Agent,`` are returned. In plenary mode, the
returned list contains all known authorizations or an error
results. Otherwise, the returned... |
def from_seqfeature(s, **kwargs):
"""
Converts a Bio.SeqFeature object to a gffutils.Feature object.
The GFF fields `source`, `score`, `seqid`, and `frame` are assumed to be
stored as qualifiers. Any other qualifiers will be assumed to be GFF
attributes.
"""
source = s.qualifiers.get('sour... | Converts a Bio.SeqFeature object to a gffutils.Feature object.
The GFF fields `source`, `score`, `seqid`, and `frame` are assumed to be
stored as qualifiers. Any other qualifiers will be assumed to be GFF
attributes. |
def remove_straddlers(events, time, s_freq, toler=0.1):
"""Reject an event if it straddles a stitch, by comparing its
duration to its timespan.
Parameters
----------
events : ndarray (dtype='int')
N x M matrix with start, ..., end samples
time : ndarray (dtype='float')
vector w... | Reject an event if it straddles a stitch, by comparing its
duration to its timespan.
Parameters
----------
events : ndarray (dtype='int')
N x M matrix with start, ..., end samples
time : ndarray (dtype='float')
vector with time points
s_freq : float
sampling frequency
... |
def ekopr(fname):
"""
Open an existing E-kernel file for reading.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopr_c.html
:param fname: Name of EK file.
:type fname: str
:return: Handle attached to EK file.
:rtype: int
"""
fname = stypes.stringToCharP(fname)
handle... | Open an existing E-kernel file for reading.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopr_c.html
:param fname: Name of EK file.
:type fname: str
:return: Handle attached to EK file.
:rtype: int |
def build_machine(system_info,
core_resource=Cores,
sdram_resource=SDRAM,
sram_resource=SRAM):
"""Build a :py:class:`~rig.place_and_route.Machine` object from a
:py:class:`~rig.machine_control.machine_controller.SystemInfo` object.
.. note::
Lin... | Build a :py:class:`~rig.place_and_route.Machine` object from a
:py:class:`~rig.machine_control.machine_controller.SystemInfo` object.
.. note::
Links are tested by sending a 'PEEK' command down the link which
checks to see if the remote device responds correctly. If the link
is dead, no... |
def calibrate(self, data, key):
"""Data calibration."""
# logger.debug('Calibration: %s' % key.calibration)
logger.warning('Calibration disabled!')
if key.calibration == 'brightness_temperature':
# self._ir_calibrate(data, key)
pass
elif key.calibration =... | Data calibration. |
def get_app_name(self):
"""
Return the appname of the APK
This name is read from the AndroidManifest.xml
using the application android:label.
If no label exists, the android:label of the main activity is used.
If there is also no main activity label, an empty string is ... | Return the appname of the APK
This name is read from the AndroidManifest.xml
using the application android:label.
If no label exists, the android:label of the main activity is used.
If there is also no main activity label, an empty string is returned.
:rtype: :class:`str` |
def gather_votes(self, candidates):
"""Gather votes for the given candidates from the agents in the
environment.
Returned votes are anonymous, i.e. they cannot be tracked to any
individual agent afterwards.
:returns:
A list of votes. Each vote is a list of ``(artifa... | Gather votes for the given candidates from the agents in the
environment.
Returned votes are anonymous, i.e. they cannot be tracked to any
individual agent afterwards.
:returns:
A list of votes. Each vote is a list of ``(artifact, preference)``
-tuples sorted in... |
def _do_link_patterns(self, text):
"""Caveat emptor: there isn't much guarding against link
patterns being formed inside other standard Markdown links, e.g.
inside a [link def][like this].
Dev Notes: *Could* consider prefixing regexes with a negative
lookbehind assertion to atte... | Caveat emptor: there isn't much guarding against link
patterns being formed inside other standard Markdown links, e.g.
inside a [link def][like this].
Dev Notes: *Could* consider prefixing regexes with a negative
lookbehind assertion to attempt to guard against this. |
def _prompt_choice(var_name, options):
'''
Prompt the user to choose between a list of options, index each one by adding an enumerator
based on https://github.com/audreyr/cookiecutter/blob/master/cookiecutter/prompt.py#L51
:param var_name: The question to ask the user
:type var_name: ``str``
... | Prompt the user to choose between a list of options, index each one by adding an enumerator
based on https://github.com/audreyr/cookiecutter/blob/master/cookiecutter/prompt.py#L51
:param var_name: The question to ask the user
:type var_name: ``str``
:param options: A list of options
:type option... |
def find_by_id(cls, id):
"""
Finds a single document by its ID. Throws a
NotFoundException if the document does not exist (the
assumption being if you've got an id you should be
pretty certain the thing exists)
"""
obj = cls.find_one(cls._id_spec(id))
if n... | Finds a single document by its ID. Throws a
NotFoundException if the document does not exist (the
assumption being if you've got an id you should be
pretty certain the thing exists) |
def get_commands(self, command_name, **kwargs):
"""get fe_command from command name and keyword arguments
wrapper for build_commands()
implements FEI4 specific behavior
"""
chip_id = kwargs.pop("ChipID", self.chip_id_bitarray)
commands = []
if command_n... | get fe_command from command name and keyword arguments
wrapper for build_commands()
implements FEI4 specific behavior |
def sortByColumn(self, column, order=QtCore.Qt.AscendingOrder):
"""
Overloads the default sortByColumn to record the order for later \
reference.
:param column | <int>
order | <QtCore.Qt.SortOrder>
"""
super(XTreeWidget, self).so... | Overloads the default sortByColumn to record the order for later \
reference.
:param column | <int>
order | <QtCore.Qt.SortOrder> |
def get_service_health(service_id: str) -> str:
"""Get the health of a service using service_id.
Args:
service_id
Returns:
str, health status
"""
# Check if the current and actual replica levels are the same
if DC.get_replicas(service_id) != DC.... | Get the health of a service using service_id.
Args:
service_id
Returns:
str, health status |
def set_repo_permission(self, repo, permission):
"""
:calls: `PUT /teams/:id/repos/:org/:repo <http://developer.github.com/v3/orgs/teams>`_
:param repo: :class:`github.Repository.Repository`
:param permission: string
:rtype: None
"""
assert isinstance(repo, github... | :calls: `PUT /teams/:id/repos/:org/:repo <http://developer.github.com/v3/orgs/teams>`_
:param repo: :class:`github.Repository.Repository`
:param permission: string
:rtype: None |
def colorbar(ax, im, fig=None, loc="right", size="5%", pad="3%"):
"""
Adds a polite colorbar that steals space so :func:`matplotlib.pyplot.tight_layout` works nicely.
.. versionadded:: 1.3
Parameters
----------
ax : :class:`matplotlib.axis.Axis`
The axis to plot to.
im : :class:`m... | Adds a polite colorbar that steals space so :func:`matplotlib.pyplot.tight_layout` works nicely.
.. versionadded:: 1.3
Parameters
----------
ax : :class:`matplotlib.axis.Axis`
The axis to plot to.
im : :class:`matplotlib.image.AxesImage`
The plotted image to use for the colorbar.
... |
def init_layout(self):
""" Set the checked state after all children have
been populated.
"""
super(AndroidRadioGroup, self).init_layout()
d = self.declaration
w = self.widget
if d.checked:
self.set_checked(d.checked)
else:
... | Set the checked state after all children have
been populated. |
def detailxy(self, canvas, button, data_x, data_y):
"""Motion event in the pick fits window. Show the pointing
information under the cursor.
"""
if button == 0:
# TODO: we could track the focus changes to make this check
# more efficient
chviewer = se... | Motion event in the pick fits window. Show the pointing
information under the cursor. |
def make_back_author_contributions(self, body):
"""
Though this goes in the back of the document with the rest of the back
matter, it is not an element found under <back>.
I don't expect to see more than one of these. Compare this method to
make_article_info_competing_interests(... | Though this goes in the back of the document with the rest of the back
matter, it is not an element found under <back>.
I don't expect to see more than one of these. Compare this method to
make_article_info_competing_interests() |
def get_usedby_aql(self, params):
"""
Возвращает запрос AQL (без репозитория), из файла конфигурации
:param params:
:return:
"""
if self._usedby is None:
return None
_result = {}
params = self.merge_valued(params)
for k, v in self._use... | Возвращает запрос AQL (без репозитория), из файла конфигурации
:param params:
:return: |
def _multiplyThroughputs(self):
''' Overrides base class in order to deal with opaque components.
'''
index = 0
for component in self.components:
if component.throughput != None:
break
index += 1
return BaseObservationMode._multiplyThrough... | Overrides base class in order to deal with opaque components. |
def _set_LED(self, status):
"""
_set_LED: boolean -> None
Sets the status of the remote LED
"""
# DIO pin 1 (LED), active low
self.hw.remote_at(
dest_addr=self.remote_addr,
command='D1',
parameter='\x04' if status else '\x05') | _set_LED: boolean -> None
Sets the status of the remote LED |
def remove_unweighted_sources(graph: BELGraph, key: Optional[str] = None) -> None:
"""Prune unannotated nodes on the periphery of the sub-graph.
:param graph: A BEL graph
:param key: The key in the node data dictionary representing the experimental data. Defaults to
:data:`pybel_tools.constants.WEIGHT... | Prune unannotated nodes on the periphery of the sub-graph.
:param graph: A BEL graph
:param key: The key in the node data dictionary representing the experimental data. Defaults to
:data:`pybel_tools.constants.WEIGHT`. |
def open(self, url):
"""
Open a WSDL at the specified I{url}.
First, the WSDL attempted to be retrieved from
the I{object cache}. After unpickled from the cache, the
I{options} attribute is restored.
If not found, it is downloaded and instantiated using the
I{fn}... | Open a WSDL at the specified I{url}.
First, the WSDL attempted to be retrieved from
the I{object cache}. After unpickled from the cache, the
I{options} attribute is restored.
If not found, it is downloaded and instantiated using the
I{fn} constructor and added to the cache for t... |
def weld_standard_deviation(array, weld_type):
"""Returns the *sample* standard deviation of the array.
Parameters
----------
array : numpy.ndarray or WeldObject
Input array.
weld_type : WeldType
Type of each element in the input array.
Returns
-------
WeldObject
... | Returns the *sample* standard deviation of the array.
Parameters
----------
array : numpy.ndarray or WeldObject
Input array.
weld_type : WeldType
Type of each element in the input array.
Returns
-------
WeldObject
Representation of this computation. |
def same(*values):
"""
Check if all values in a sequence are equal.
Returns True on empty sequences.
Examples
--------
>>> same(1, 1, 1, 1)
True
>>> same(1, 2, 1)
False
>>> same()
True
"""
if not values:
return True
first, rest = values[0], values[1:]
... | Check if all values in a sequence are equal.
Returns True on empty sequences.
Examples
--------
>>> same(1, 1, 1, 1)
True
>>> same(1, 2, 1)
False
>>> same()
True |
def update_path(self, path):
"""
There are EXTENDED messages which don't include any routers at
all, and any of the EXTENDED messages may have some arbitrary
flags in them. So far, they're all upper-case and none start
with $ luckily. The routers in the path should all be
... | There are EXTENDED messages which don't include any routers at
all, and any of the EXTENDED messages may have some arbitrary
flags in them. So far, they're all upper-case and none start
with $ luckily. The routers in the path should all be
LongName-style router names (this depends on the... |
def _attributeLinesToDict(attributeLines):
"""Converts a list of obo 'Term' lines to a dictionary.
:param attributeLines: a list of obo 'Term' lines. Each line contains a key
and a value part which are separated by a ':'.
:return: a dictionary containing the attributes of an obo 'Term' entry.
... | Converts a list of obo 'Term' lines to a dictionary.
:param attributeLines: a list of obo 'Term' lines. Each line contains a key
and a value part which are separated by a ':'.
:return: a dictionary containing the attributes of an obo 'Term' entry.
NOTE: Some attributes can occur multiple times in... |
def is_cozy_registered():
'''
Check if a Cozy is registered
'''
req = curl_couchdb('/cozy/_design/user/_view/all')
users = req.json()['rows']
if len(users) > 0:
return True
else:
return False | Check if a Cozy is registered |
def update(self, membershipId, isModerator=None, **request_parameters):
"""Update a team membership, by ID.
Args:
membershipId(basestring): The team membership ID.
isModerator(bool): Set to True to make the person a team moderator.
**request_parameters: Additional re... | Update a team membership, by ID.
Args:
membershipId(basestring): The team membership ID.
isModerator(bool): Set to True to make the person a team moderator.
**request_parameters: Additional request parameters (provides
support for parameters that may be added... |
def get_asset_form_for_update(self, asset_id=None):
"""Gets the asset form for updating an existing asset.
A new asset form should be requested for each update
transaction.
:param asset_id: the ``Id`` of the ``Asset``
:type asset_id: ``osid.id.Id``
:return: the asset fo... | Gets the asset form for updating an existing asset.
A new asset form should be requested for each update
transaction.
:param asset_id: the ``Id`` of the ``Asset``
:type asset_id: ``osid.id.Id``
:return: the asset form
:rtype: ``osid.repository.AssetForm``
:raise... |
def create_initial_tree(channel):
""" create_initial_tree: Create initial tree structure
Args:
channel (Channel): channel to construct
Returns: tree manager to run rest of steps
"""
# Create channel manager with channel data
config.LOGGER.info(" Setting up initial channel s... | create_initial_tree: Create initial tree structure
Args:
channel (Channel): channel to construct
Returns: tree manager to run rest of steps |
def _open_interface(self, client, uuid, iface, key):
"""Open an interface on a connected device.
Args:
client (string): The client id who is requesting this operation
uuid (int): The id of the device we're opening the interface on
iface (string): The name of the inte... | Open an interface on a connected device.
Args:
client (string): The client id who is requesting this operation
uuid (int): The id of the device we're opening the interface on
iface (string): The name of the interface that we're opening
key (string): The key to au... |
async def handle_exception(self, exc: Exception, action: str, request_id):
"""
Handle any exception that occurs, by sending an appropriate message
"""
if isinstance(exc, APIException):
await self.reply(
action=action,
errors=self._format_errors... | Handle any exception that occurs, by sending an appropriate message |
def _get_2d_plot(self, label_stable=True, label_unstable=True,
ordering=None, energy_colormap=None, vmin_mev=-60.0,
vmax_mev=60.0, show_colorbar=True,
process_attributes=False, plt=None):
"""
Shows the plot using pylab. Usually I won't do i... | Shows the plot using pylab. Usually I won't do imports in methods,
but since plotting is a fairly expensive library to load and not all
machines have matplotlib installed, I have done it this way. |
def interface_endpoints(self):
"""Instance depends on the API version:
* 2018-08-01: :class:`InterfaceEndpointsOperations<azure.mgmt.network.v2018_08_01.operations.InterfaceEndpointsOperations>`
"""
api_version = self._get_api_version('interface_endpoints')
if api_version == ... | Instance depends on the API version:
* 2018-08-01: :class:`InterfaceEndpointsOperations<azure.mgmt.network.v2018_08_01.operations.InterfaceEndpointsOperations>` |
def auth(self, encoded):
""" Validate integrity of encoded bytes """
message, signature = self.split(encoded)
computed = self.sign(message)
if not hmac.compare_digest(signature, computed):
raise AuthenticatorInvalidSignature | Validate integrity of encoded bytes |
def stopService(self):
"""
Gracefully stop the service.
Returns:
defer.Deferred: a Deferred which is triggered when the service has
finished shutting down.
"""
self._service.factory.stopTrying()
yield self._service.factory.stopFactory()
... | Gracefully stop the service.
Returns:
defer.Deferred: a Deferred which is triggered when the service has
finished shutting down. |
def create(self, request, *args, **kwargs):
"""
Run **POST** against */api/alerts/* to create or update alert. If alert with posted scope and
alert_type already exists - it will be updated. Only users with staff privileges can create alerts.
Request example:
.. code-block:: jav... | Run **POST** against */api/alerts/* to create or update alert. If alert with posted scope and
alert_type already exists - it will be updated. Only users with staff privileges can create alerts.
Request example:
.. code-block:: javascript
POST /api/alerts/
Accept: appli... |
def check_date_str_format(s, default_time="00:00:00"):
"""Check the format of date string"""
try:
str_fmt = s
if ":" not in s:
str_fmt = '{} {}'.format(s, default_time)
dt_obj = datetime.strptime(str_fmt, "%Y-%m-%d %H:%M:%S")
return RET_OK, dt_obj
except ValueE... | Check the format of date string |
def keywords_for(*args):
"""
Return a list of ``Keyword`` objects for the given model instance
or a model class. In the case of a model class, retrieve all
keywords for all instances of the model and apply a ``weight``
attribute that can be used to create a tag cloud.
"""
# Handle a model i... | Return a list of ``Keyword`` objects for the given model instance
or a model class. In the case of a model class, retrieve all
keywords for all instances of the model and apply a ``weight``
attribute that can be used to create a tag cloud. |
def fix_symbol_store_path(symbol_store_path = None,
remote = True,
force = False):
"""
Fix the symbol store path. Equivalent to the C{.symfix} command in
Microsoft WinDbg.
If the symbol store path environment variable hasn't be... | Fix the symbol store path. Equivalent to the C{.symfix} command in
Microsoft WinDbg.
If the symbol store path environment variable hasn't been set, this
method will provide a default one.
@type symbol_store_path: str or None
@param symbol_store_path: (Optional) Symbol store pa... |
def feeds(self):
"""List GitHub's timeline resources in Atom format.
:returns: dictionary parsed to include URITemplates
"""
url = self._build_url('feeds')
json = self._json(self._get(url), 200)
del json['ETag']
del json['Last-Modified']
urls = [
... | List GitHub's timeline resources in Atom format.
:returns: dictionary parsed to include URITemplates |
def add_to_matching_blacklist(db, entity):
"""Add entity to the matching blacklist.
This function adds an 'entity' o term to the matching blacklist.
The term to add cannot have a None or empty value, in this case
a InvalidValueError will be raised. If the given 'entity' exists in the
registry, the ... | Add entity to the matching blacklist.
This function adds an 'entity' o term to the matching blacklist.
The term to add cannot have a None or empty value, in this case
a InvalidValueError will be raised. If the given 'entity' exists in the
registry, the function will raise an AlreadyExistsError exceptio... |
def connect(self, host='127.0.0.1', port=3306, user='root', password='', database=None):
""" Connect to the database specified """
if database is None:
raise exceptions.RequiresDatabase()
self._db_args = { 'host': host, 'port': port, 'user': user, 'password': password, 'database': ... | Connect to the database specified |
def clear_title(self):
"""Removes the title.
:raise: ``NoAccess`` -- ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
metadata = Metadata(**settings.METADATA['title'])
... | Removes the title.
:raise: ``NoAccess`` -- ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* |
async def debug(self, client_id, conn_string, command, args):
"""Send a debug command to a device on behalf of a client.
See :meth:`AbstractDeviceAdapter.send_script`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will... | Send a debug command to a device on behalf of a client.
See :meth:`AbstractDeviceAdapter.send_script`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter.
... |
def print_vertical(vertical_rows, labels, color, args):
"""Print the whole vertical graph."""
if color:
sys.stdout.write(f'\033[{color}m') # Start to write colorized.
for row in vertical_rows:
print(*row)
sys.stdout.write('\033[0m') # End of printing colored
print("-" * len(row) +... | Print the whole vertical graph. |
def transfer(sendContext, receiveContext, chunkSize):
""" Transfer (large) data from sender to receiver. """
try:
chunkSize = receiveContext.chunkSize
except AttributeError:
pass
if sendContext is not None and receiveContext is not None:
with receiveContext as writer:
... | Transfer (large) data from sender to receiver. |
def of(fixture_classes: Iterable[type], context: Union[None, 'torment.TestContext'] = None) -> Iterable['torment.fixtures.Fixture']:
'''Obtain all Fixture objects of the provided classes.
**Parameters**
:``fixture_classes``: classes inheriting from ``torment.fixtures.Fixture``
:``context``: a ... | Obtain all Fixture objects of the provided classes.
**Parameters**
:``fixture_classes``: classes inheriting from ``torment.fixtures.Fixture``
:``context``: a ``torment.TestContext`` to initialize Fixtures with
**Return Value(s)**
Instantiated ``torment.fixtures.Fixture`` objects for each... |
def routing(routes, request):
"""Definition for route matching : helper"""
# strip trailing slashes from request path
path = request.path.strip('/')
# iterate through routes to match
args = {}
for name, route in routes.items():
if route['path'] == '^':
# this section exists... | Definition for route matching : helper |
def _enable_l1_keepalives(self, command):
"""
Enables L1 keepalive messages if supported.
:param command: command line
"""
env = os.environ.copy()
if "IOURC" not in os.environ:
env["IOURC"] = self.iourc_path
try:
output = yield from gns3s... | Enables L1 keepalive messages if supported.
:param command: command line |
def __parse_identities(self, json):
"""Parse identities using Sorting Hat format.
The Sorting Hat identities format is a JSON stream on which its
keys are the UUID of the unique identities. Each unique identity
object has a list of identities and enrollments.
When the unique id... | Parse identities using Sorting Hat format.
The Sorting Hat identities format is a JSON stream on which its
keys are the UUID of the unique identities. Each unique identity
object has a list of identities and enrollments.
When the unique identity does not have a UUID, it will be conside... |
def retrieve(self, key):
"""Retrieves a cached array if possible."""
column_file = os.path.join(self._hash_dir, '%s.json' % key)
cache_file = os.path.join(self._hash_dir, '%s.npy' % key)
if os.path.exists(cache_file):
data = np.load(cache_file)
if os.path.exists(... | Retrieves a cached array if possible. |
def load_image(name, n, m=None, gpu=None, square=None):
"""Function to load images with certain size."""
if m is None:
m = n
if gpu is None:
gpu = 0
if square is None:
square = 0
command = ('Shearlab.load_image("{}", {}, {}, {}, {})'.format(name,
n, m, gpu, squ... | Function to load images with certain size. |
def tablestructure(tablename, dataman=True, column=True, subtable=False,
sort=False):
"""Print the structure of a table.
It is the same as :func:`table.showstructure`, but without the need to open
the table first.
"""
t = table(tablename, ack=False)
six.print_(t.showstructur... | Print the structure of a table.
It is the same as :func:`table.showstructure`, but without the need to open
the table first. |
def get_all_preordered_namespace_hashes( self ):
"""
Get all oustanding namespace preorder hashes that have not expired.
Used for testing
"""
cur = self.db.cursor()
namespace_hashes = namedb_get_all_preordered_namespace_hashes( cur, self.lastblock )
return namespa... | Get all oustanding namespace preorder hashes that have not expired.
Used for testing |
def feed_arthur():
""" Feed Ocean with backend data collected from arthur redis queue"""
logger.info("Collecting items from redis queue")
db_url = 'redis://localhost/8'
conn = redis.StrictRedis.from_url(db_url)
logger.debug("Redis connection stablished with %s.", db_url)
# Get and remove que... | Feed Ocean with backend data collected from arthur redis queue |
def path(self):
''' Get the path of the wrapped folder '''
if isinstance(self.dir, Directory):
return self.dir._path
elif isinstance(self.dir, ROOT.TDirectory):
return self.dir.GetPath()
elif isinstance(self.dir, _FolderView):
return self.dir.path()
... | Get the path of the wrapped folder |
def list(self, entity=None):
"""
Returns a dictionary of data, optionally filtered for a given entity.
"""
uri = "/%s" % self.uri_base
if entity:
uri = "%s?entityId=%s" % (uri, utils.get_id(entity))
resp, resp_body = self._list(uri, return_raw=True)
re... | Returns a dictionary of data, optionally filtered for a given entity. |
def start_server_background(port):
"""Start the newtab server as a background process."""
if sys.version_info[0] == 2:
lines = ('import pydoc\n'
'pydoc.serve({port})')
cell = lines.format(port=port)
else:
# The location of newtabmagic (normally $IPYTHONDIR/extension... | Start the newtab server as a background process. |
def write(self, output_io):
'''Write a taxonomy to an open stream out in GG format. Code calling this
function must open and close the io object.'''
for name, tax in self.taxonomy.items():
output_io.write("%s\t%s\n" % (name, '; '.join(tax))) | Write a taxonomy to an open stream out in GG format. Code calling this
function must open and close the io object. |
def set_triggered_by_event(self, value):
"""
Setter for 'triggered_by_event' field.
:param value - a new value of 'triggered_by_event' field. Must be a boolean type. Does not accept None value.
"""
if value is None or not isinstance(value, bool):
raise TypeError("Trig... | Setter for 'triggered_by_event' field.
:param value - a new value of 'triggered_by_event' field. Must be a boolean type. Does not accept None value. |
def bind(self, attribute, cls, buffer, fmt, *, offset=0, stride=0, divisor=0, normalize=False) -> None:
'''
Bind individual attributes to buffers.
Args:
location (int): The attribute location.
cls (str): The attribute class. Valid values are ``f``, ``i`` ... | Bind individual attributes to buffers.
Args:
location (int): The attribute location.
cls (str): The attribute class. Valid values are ``f``, ``i`` or ``d``.
buffer (Buffer): The buffer.
format (str): The buffer format.
Keyword Arg... |
def plotloc(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None,
tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400):
""" Make a light-weight loc figure """
fields = ['l1', 'm1', 'sizes', 'colors', 'snrs', 'key']
if not circleinds: circl... | Make a light-weight loc figure |
def _add_rg(unmapped_file, config, names):
"""Add the missing RG header."""
picard = broad.runner_from_path("picard", config)
rg_fixed = picard.run_fn("picard_fix_rgs", unmapped_file, names)
return rg_fixed | Add the missing RG header. |
def format_help(self):
"""Override help doc to add cell args. """
if not self._cell_args:
return super(CommandParser, self).format_help()
else:
# Print the standard argparse info, the cell arg block, and then the epilog
# If we don't remove epilog before calling the super, then epilog wil... | Override help doc to add cell args. |
def HandleSimpleResponses(
self, timeout_ms=None, info_cb=DEFAULT_MESSAGE_CALLBACK):
"""Accepts normal responses from the device.
Args:
timeout_ms: Timeout in milliseconds to wait for each response.
info_cb: Optional callback for text sent from the bootloader.
R... | Accepts normal responses from the device.
Args:
timeout_ms: Timeout in milliseconds to wait for each response.
info_cb: Optional callback for text sent from the bootloader.
Returns:
OKAY packet's message. |
def mkdir(self, mdir, parents=False):
"""Make a directory.
Note that this will not error out if the directory already exists
(that is how the PutDirectory Manta API behaves).
@param mdir {str} A manta path, e.g. '/trent/stor/mydir'.
@param parents {bool} Optional. Default false... | Make a directory.
Note that this will not error out if the directory already exists
(that is how the PutDirectory Manta API behaves).
@param mdir {str} A manta path, e.g. '/trent/stor/mydir'.
@param parents {bool} Optional. Default false. Like 'mkdir -p', this
will create p... |
def visible(self, request):
'''
Checks the both, check_visible and apply_visible, against the owned model and it's instance set
'''
return self.apply_visible(self.get_queryset(), request) if self.check_visible(self.model, request) is not False else self.get_queryset().none() | Checks the both, check_visible and apply_visible, against the owned model and it's instance set |
def DictProduct(dictionary):
"""Computes a cartesian product of dict with iterable values.
This utility function, accepts a dictionary with iterable values, computes
cartesian products of these values and yields dictionaries of expanded values.
Examples:
>>> list(DictProduct({"a": [1, 2], "b": [3, 4]}))
... | Computes a cartesian product of dict with iterable values.
This utility function, accepts a dictionary with iterable values, computes
cartesian products of these values and yields dictionaries of expanded values.
Examples:
>>> list(DictProduct({"a": [1, 2], "b": [3, 4]}))
[{"a": 1, "b": 3}, {"a": 1, "b"... |
def from_table(table, fields=None):
""" Return a Query for the given Table object
Args:
table: the Table object to construct a Query out of
fields: the fields to return. If None, all fields will be returned. This can be a string
which will be injected into the Query after SELECT, or a lis... | Return a Query for the given Table object
Args:
table: the Table object to construct a Query out of
fields: the fields to return. If None, all fields will be returned. This can be a string
which will be injected into the Query after SELECT, or a list of field names.
Returns:
A Quer... |
def dictionary_merge(a, b):
"""merges dictionary b into a
Like dict.update, but recursive
"""
for key, value in b.items():
if key in a and isinstance(a[key], dict) and isinstance(value, dict):
dictionary_merge(a[key], b[key])
continue
a[key] = b[key]
return... | merges dictionary b into a
Like dict.update, but recursive |
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Adds the "Send to Twitter" checkbox after the "status" field,
provided by any ``Displayable`` models. The approach here is
quite a hack, however the sane approach of using a custom
form with a boolean field defined, and the... | Adds the "Send to Twitter" checkbox after the "status" field,
provided by any ``Displayable`` models. The approach here is
quite a hack, however the sane approach of using a custom
form with a boolean field defined, and then adding it to the
formssets attribute of the admin class fell ap... |
def collect_conflicts_between(
context: ValidationContext,
conflicts: List[Conflict],
cached_fields_and_fragment_names: Dict,
compared_fragment_pairs: "PairSet",
parent_fields_are_mutually_exclusive: bool,
field_map1: NodeAndDefCollection,
field_map2: NodeAndDefCollection,
) -> None:
"""... | Collect all Conflicts between two collections of fields.
This is similar to, but different from the `collectConflictsWithin` function above.
This check assumes that `collectConflictsWithin` has already been called on each
provided collection of fields. This is true because this validator traverses each
... |
def reconnect(self):
'''
Try to reconnect and re-authenticate with the server.
'''
log.debug('Closing the SSH socket.')
try:
self.ssl_skt.close()
except socket.error:
log.error('The socket seems to be closed already.')
log.debug('Re-opening... | Try to reconnect and re-authenticate with the server. |
def get_children_graph(self, item_ids=None, language=None, forbidden_item_ids=None):
"""
Get a subgraph of items reachable from the given set of items through
the 'child' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
languag... | Get a subgraph of items reachable from the given set of items through
the 'child' relation.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter out items which are not
available in the given language
... |
def _write_nex(self, mdict, nlocus):
"""
function that takes a dictionary mapping names to sequences,
and a locus number, and writes it as a NEXUS file with a mrbayes
analysis block given a set of mcmc arguments.
"""
## create matrix as a string
max_name_len =... | function that takes a dictionary mapping names to sequences,
and a locus number, and writes it as a NEXUS file with a mrbayes
analysis block given a set of mcmc arguments. |
def print_common_terms(common_terms):
"""Print common terms for each pair of word sets.
:param common_terms: Output of get_common_terms().
"""
if not common_terms:
print('No duplicates')
else:
for set_pair in common_terms:
set1, set2, terms = set_pair
print('{... | Print common terms for each pair of word sets.
:param common_terms: Output of get_common_terms(). |
def clean(self):
"""
Authenticate the given username/email and password. If the fields
are valid, store the authenticated user for returning via save().
"""
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
self._user = auth... | Authenticate the given username/email and password. If the fields
are valid, store the authenticated user for returning via save(). |
def profile(self, profile):
"""Set the current profile.
Args:
profile (dict): The profile data.
"""
# clear staging data
self._staging_data = None
# retrieve language from install.json or assume Python
lang = profile.get('install_json', {}).get('progr... | Set the current profile.
Args:
profile (dict): The profile data. |
def draw_triangle(a, b, c, color, draw):
"""Draws a triangle with the given vertices in the given color."""
draw.polygon([a, b, c], fill=color) | Draws a triangle with the given vertices in the given color. |
def clear_n_of_m(self):
"""stub"""
if (self.get_n_of_m_metadata().is_read_only() or
self.get_n_of_m_metadata().is_required()):
raise NoAccess()
self.my_osid_object_form._my_map['nOfM'] = \
int(self._n_of_m_metadata['default_object_values'][0]) | stub |
def genome_alignment_iterator(fn, reference_species, index_friendly=False,
verbose=False):
"""
build an iterator for an MAF file of genome alignment blocks.
:param fn: filename or stream-like object to iterate over.
:param reference_species: which species in the a... | build an iterator for an MAF file of genome alignment blocks.
:param fn: filename or stream-like object to iterate over.
:param reference_species: which species in the alignment should be treated
as the reference?
:param index_friendly: if True, buffering is disa... |
def get_structure_seqs(pdb_file, file_type):
"""Get a dictionary of a PDB file's sequences.
Special cases include:
- Insertion codes. In the case of residue numbers like "15A", "15B", both residues are written out. Example: 9LPR
- HETATMs. Currently written as an "X", or unknown amino acid.
... | Get a dictionary of a PDB file's sequences.
Special cases include:
- Insertion codes. In the case of residue numbers like "15A", "15B", both residues are written out. Example: 9LPR
- HETATMs. Currently written as an "X", or unknown amino acid.
Args:
pdb_file: Path to PDB file
Retu... |
def add_motifs(self, args):
"""Add motifs to the result object."""
self.lock.acquire()
# Callback function for motif programs
if args is None or len(args) != 2 or len(args[1]) != 3:
try:
job = args[0]
logger.warn("job %s failed", job)
... | Add motifs to the result object. |
def __get_jp(self, extractor_processor, sub_output=None):
"""Tries to get name from ExtractorProcessor to filter on first.
Otherwise falls back to filtering based on its metadata"""
if sub_output is None and extractor_processor.output_field is None:
raise ValueError(
... | Tries to get name from ExtractorProcessor to filter on first.
Otherwise falls back to filtering based on its metadata |
def _find_penultimate_layer(model, layer_idx, penultimate_layer_idx):
"""Searches for the nearest penultimate `Conv` or `Pooling` layer.
Args:
model: The `keras.models.Model` instance.
layer_idx: The layer index within `model.layers`.
penultimate_layer_idx: The pre-layer to `layer_idx`.... | Searches for the nearest penultimate `Conv` or `Pooling` layer.
Args:
model: The `keras.models.Model` instance.
layer_idx: The layer index within `model.layers`.
penultimate_layer_idx: The pre-layer to `layer_idx`. If set to None, the nearest penultimate
`Conv` or `Pooling` laye... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.