code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def iterprogress( sized_iterable ):
"""
Iterate something printing progress bar to stdout
"""
pb = ProgressBar( 0, len( sized_iterable ) )
for i, value in enumerate( sized_iterable ):
yield value
pb.update_and_print( i, sys.stderr ) | Iterate something printing progress bar to stdout |
def session(self):
"""
Get session object to benefit from connection pooling.
http://docs.python-requests.org/en/master/user/advanced/#session-objects
:rtype: requests.Session
"""
if self._session is None:
self._session = requests.Session()
self.... | Get session object to benefit from connection pooling.
http://docs.python-requests.org/en/master/user/advanced/#session-objects
:rtype: requests.Session |
def remove_device(self, device: Union[DeviceType, str]) -> None:
"""Remove the given |Node| or |Element| object from the actual
|Nodes| or |Elements| object.
You can pass either a string or a device:
>>> from hydpy import Node, Nodes
>>> nodes = Nodes('node_x', 'node_y')
... | Remove the given |Node| or |Element| object from the actual
|Nodes| or |Elements| object.
You can pass either a string or a device:
>>> from hydpy import Node, Nodes
>>> nodes = Nodes('node_x', 'node_y')
>>> node_x, node_y = nodes
>>> nodes.remove_device(Node('node_y'))... |
def get_dsn(d):
"""
Get the dataset name from a record
:param dict d: Metadata
:return str: Dataset name
"""
try:
return d["dataSetName"]
except Exception as e:
logger_misc.warn("get_dsn: Exception: No datasetname found, unable to continue: {}".format(e))
exit(1) | Get the dataset name from a record
:param dict d: Metadata
:return str: Dataset name |
def check_ontology(fname):
"""
reads the ontology yaml file and does basic verifcation
"""
with open(fname, 'r') as stream:
y = yaml.safe_load(stream)
import pprint
pprint.pprint(y) | reads the ontology yaml file and does basic verifcation |
def normalize_path(path):
"""
Convert a path to its canonical, case-normalized, absolute version.
"""
return os.path.normcase(os.path.realpath(os.path.expanduser(path))) | Convert a path to its canonical, case-normalized, absolute version. |
def _authn_response(self, in_response_to, consumer_url,
sp_entity_id, identity=None, name_id=None,
status=None, authn=None, issuer=None, policy=None,
sign_assertion=False, sign_response=False,
best_effort=False, encrypt_asse... | Create a response. A layer of indirection.
:param in_response_to: The session identifier of the request
:param consumer_url: The URL which should receive the response
:param sp_entity_id: The entity identifier of the SP
:param identity: A dictionary with attributes and values that are
... |
def only_newer(copy_func):
"""
Wrap a copy function (like shutil.copy2) to return
the dst if it's newer than the source.
"""
@functools.wraps(copy_func)
def wrapper(src, dst, *args, **kwargs):
is_newer_dst = (
dst.exists()
and dst.getmtime() >= src.getmtime()
... | Wrap a copy function (like shutil.copy2) to return
the dst if it's newer than the source. |
def canonicalize_edge(edge_data: EdgeData) -> Tuple[str, Optional[Tuple], Optional[Tuple]]:
"""Canonicalize the edge to a tuple based on the relation, subject modifications, and object modifications."""
return (
edge_data[RELATION],
_canonicalize_edge_modifications(edge_data.get(SUBJECT)),
... | Canonicalize the edge to a tuple based on the relation, subject modifications, and object modifications. |
def plugin_for(cls, model):
'''
Find and return a plugin for this model. Uses inheritance to find a model where the plugin is registered.
'''
logger.debug("Getting a plugin for: %s", model)
if not issubclass(model, Model):
return
if model in cls.plugins:
... | Find and return a plugin for this model. Uses inheritance to find a model where the plugin is registered. |
def LoadFromXml(self, node, handle):
""" Method updates the object from the xml representation of the managed object. """
self.SetHandle(handle)
if node.hasAttributes():
# attributes = node._get_attributes()
# attCount = attributes._get_length()
attributes = node.attributes
attCount = len(attributes)
... | Method updates the object from the xml representation of the managed object. |
def get_src_or_dst(mode, path_type):
"""
User sets the path to a LiPD source location
:param str mode: "read" or "write" mode
:param str path_type: "directory" or "file"
:return str path: dir path to files
:return list files: files chosen
"""
logger_directory.info("enter set_src_or_dst")... | User sets the path to a LiPD source location
:param str mode: "read" or "write" mode
:param str path_type: "directory" or "file"
:return str path: dir path to files
:return list files: files chosen |
def main(master_dsn, slave_dsn, tables, blocking=False):
"""DB Replication app.
This script will replicate data from mysql master to other databases(
including mysql, postgres, sqlite).
This script only support a very limited replication:
1. data only. The script only replicates data, so you have ... | DB Replication app.
This script will replicate data from mysql master to other databases(
including mysql, postgres, sqlite).
This script only support a very limited replication:
1. data only. The script only replicates data, so you have to make sure
the tables already exists in slave db.
2. ... |
def main(verbose=True):
"""Build and debug an application programatically
For a list of GDB MI commands, see https://www.sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI.html
"""
# Build C program
find_executable(MAKE_CMD)
if not find_executable(MAKE_CMD):
print(
'Could not fin... | Build and debug an application programatically
For a list of GDB MI commands, see https://www.sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI.html |
def deserialize_properties(props_struct: struct_pb2.Struct) -> Any:
"""
Deserializes a protobuf `struct_pb2.Struct` into a Python dictionary containing normal
Python types.
"""
# Check out this link for details on what sort of types Protobuf is going to generate:
# https://developers.google.com/... | Deserializes a protobuf `struct_pb2.Struct` into a Python dictionary containing normal
Python types. |
def do_pot(self):
"""
Sync the template with the python code.
"""
files_to_translate = []
log.debug("Collecting python sources for pot ...")
for source_path in self._source_paths:
for source_path in self._iter_suffix(path=source_path, suffix=".py"):
... | Sync the template with the python code. |
def IDENTITY(val):
'''
This is a basic "equality" index keygen, primarily meant to be used for
things like::
Model.query.filter(col='value')
Where ``FULL_TEXT`` would transform a sentence like "A Simple Sentence" into
an inverted index searchable by the words "a", "simple", and/or "sentenc... | This is a basic "equality" index keygen, primarily meant to be used for
things like::
Model.query.filter(col='value')
Where ``FULL_TEXT`` would transform a sentence like "A Simple Sentence" into
an inverted index searchable by the words "a", "simple", and/or "sentence",
``IDENTITY`` will only ... |
def near_reduce(self, coords_set, threshold=1e-4):
"""
Prunes coordinate set for coordinates that are within
threshold
Args:
coords_set (Nx3 array-like): list or array of coordinates
threshold (float): threshold value for distance
"""
unique_coord... | Prunes coordinate set for coordinates that are within
threshold
Args:
coords_set (Nx3 array-like): list or array of coordinates
threshold (float): threshold value for distance |
def prepare_searchlight_mvpa_data(images, conditions, data_type=np.float32,
random=RandomType.NORANDOM):
""" obtain the data for activity-based voxel selection using Searchlight
Average the activity within epochs and z-scoring within subject,
while maintaining the 3D brain... | obtain the data for activity-based voxel selection using Searchlight
Average the activity within epochs and z-scoring within subject,
while maintaining the 3D brain structure. In order to save memory,
the data is processed subject by subject instead of reading all in before
processing. Assuming all sub... |
async def synchronize(self, pid, vendor_specific=None):
"""Send an object synchronization request to the CN."""
return await self._request_pyxb(
"post",
["synchronize", pid],
{},
mmp_dict={"pid": pid},
vendor_specific=vendor_specific,
) | Send an object synchronization request to the CN. |
def p_compilerDirective(p):
"""compilerDirective : '#' PRAGMA pragmaName '(' pragmaParameter ')'"""
directive = p[3].lower()
param = p[5]
if directive == 'include':
fname = param
if p.parser.file:
if os.path.dirname(p.parser.file):
fname = os.path.join(os.path... | compilerDirective : '#' PRAGMA pragmaName '(' pragmaParameter ') |
def start(self):
"""
Starts the #ThreadPool. Must be ended with #stop(). Use the context-manager
interface to ensure starting and the #ThreadPool.
"""
if self.__running:
raise RuntimeError('ThreadPool already running')
[t.start() for t in self.__threads]
self.__running = True | Starts the #ThreadPool. Must be ended with #stop(). Use the context-manager
interface to ensure starting and the #ThreadPool. |
def get_reply(self, message):
"""
根据 message 的内容获取 Reply 对象。
:param message: 要处理的 message
:return: 获取的 Reply 对象
"""
session_storage = self.session_storage
id = None
session = None
if session_storage and hasattr(message, "source"):
id ... | 根据 message 的内容获取 Reply 对象。
:param message: 要处理的 message
:return: 获取的 Reply 对象 |
def pip_r(self, requirements, raise_on_error=True):
"""
Install all requirements contained in the given file path
Waits for command to finish.
Parameters
----------
requirements: str
Path to requirements.txt
raise_on_error: bool, default True
... | Install all requirements contained in the given file path
Waits for command to finish.
Parameters
----------
requirements: str
Path to requirements.txt
raise_on_error: bool, default True
If True then raise ValueError if stderr is not empty |
def grid_widgets(self):
"""Put widgets in the grid"""
sticky = {"sticky": "nswe"}
self.label.grid(row=1, column=1, columnspan=2, **sticky)
self.dropdown.grid(row=2, column=1, **sticky)
self.entry.grid(row=2, column=2, **sticky)
self.button.grid(row=3, column=1, columnspan... | Put widgets in the grid |
def __clear_covers(self):
"""Clear all covered matrix cells"""
for i in range(self.n):
self.row_covered[i] = False
self.col_covered[i] = False | Clear all covered matrix cells |
def get_rest_token(self):
"""
Returns an auth token for making calls to eventhub REST API.
:rtype: str
"""
uri = urllib.parse.quote_plus(
"https://{}.{}/{}".format(self.sb_name, self.namespace_suffix, self.eh_name))
sas = self.sas_key.encode('utf-8')
... | Returns an auth token for making calls to eventhub REST API.
:rtype: str |
def parse_data(data, type, **kwargs):
"""
Return an OSM networkx graph from the input OSM data
Parameters
----------
data : string
type : string ('xml' or 'pbf')
>>> graph = parse_data(data, 'xml')
"""
suffixes = {
'xml': '.osm',
'pbf': '.pbf',
}
try:
... | Return an OSM networkx graph from the input OSM data
Parameters
----------
data : string
type : string ('xml' or 'pbf')
>>> graph = parse_data(data, 'xml') |
def get_visible_elements(self, locator, params=None, timeout=None):
"""
Get elements both present AND visible in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the element not be found.
:p... | Get elements both present AND visible in the DOM.
If timeout is 0 (zero) return WebElement instance or None, else we wait and retry for timeout and raise
TimeoutException should the element not be found.
:param locator: locator tuple
:param params: (optional) locator params
:pa... |
def visible_to_user(self, user):
"""Get a list of visible polls for a given user (usually request.user).
These visible polls will be those that either have no groups
assigned to them (and are therefore public) or those in which
the user is a member.
"""
return Poll.obj... | Get a list of visible polls for a given user (usually request.user).
These visible polls will be those that either have no groups
assigned to them (and are therefore public) or those in which
the user is a member. |
def get_version_from_tag(tag_name: str) -> Optional[str]:
"""Get git hash from tag
:param tag_name: Name of the git tag (i.e. 'v1.0.0')
:return: sha1 hash of the commit
"""
debug('get_version_from_tag({})'.format(tag_name))
check_repo()
for i in repo.tags:
if i.name == tag_name:
... | Get git hash from tag
:param tag_name: Name of the git tag (i.e. 'v1.0.0')
:return: sha1 hash of the commit |
def _gamma_difference_hrf(tr, oversampling=50, time_length=32., onset=0.,
delay=6, undershoot=16., dispersion=1.,
u_dispersion=1., ratio=0.167):
""" Compute an hrf as the difference of two gamma functions
Parameters
----------
tr : float
scan... | Compute an hrf as the difference of two gamma functions
Parameters
----------
tr : float
scan repeat time, in seconds
oversampling : int, optional (default=16)
temporal oversampling factor
time_length : float, optional (default=32)
hrf kernel length, in seconds
onset... |
def load(self, path):
"""
Load the catalog from file
Parameters
----------
path: str
The path to the file
"""
# Get the object
DB = joblib.load(path)
# Load the attributes
self.catalog = DB.catalog
se... | Load the catalog from file
Parameters
----------
path: str
The path to the file |
def clean_single_word(word, lemmatizing="wordnet"):
"""
Performs stemming or lemmatizing on a single word.
If we are to search for a word in a clean bag-of-words, we need to search it after the same kind of preprocessing.
Inputs: - word: A string containing the source word.
- lemmatizing: ... | Performs stemming or lemmatizing on a single word.
If we are to search for a word in a clean bag-of-words, we need to search it after the same kind of preprocessing.
Inputs: - word: A string containing the source word.
- lemmatizing: A string containing one of the following: "porter", "snowball" o... |
def get_index_list(self, as_json=False):
""" get list of indices and codes
params:
as_json: True | False
returns: a list | json of index codes
"""
url = self.index_url
req = Request(url, None, self.headers)
# raises URLError or HTTPError
resp ... | get list of indices and codes
params:
as_json: True | False
returns: a list | json of index codes |
def main():
"""Parse the command-line arguments and run the tool."""
parser = argparse.ArgumentParser(description = 'XMPP version checker',
parents = [XMPPSettings.get_arg_parser()])
parser.add_argument('source', metavar = 'SOURCE',
... | Parse the command-line arguments and run the tool. |
def add_side_to_basket(self, item, quantity=1):
'''
Add a side to the current basket.
:param Item item: Item from menu.
:param int quantity: The quantity of side to be added.
:return: A response having added a side to the current basket.
:rtype: requests.Response
... | Add a side to the current basket.
:param Item item: Item from menu.
:param int quantity: The quantity of side to be added.
:return: A response having added a side to the current basket.
:rtype: requests.Response |
def simple_cache(func):
"""
Save results for the :meth:'path.using_module' classmethod.
When Python 3.2 is available, use functools.lru_cache instead.
"""
saved_results = {}
def wrapper(cls, module):
if module in saved_results:
return saved_results[module]
saved_resu... | Save results for the :meth:'path.using_module' classmethod.
When Python 3.2 is available, use functools.lru_cache instead. |
def check(actions, request, target=None):
"""Check user permission.
Check if the user has permission to the action according
to policy setting.
:param actions: list of scope and action to do policy checks on,
the composition of which is (scope, action). Multiple actions
are treated as ... | Check user permission.
Check if the user has permission to the action according
to policy setting.
:param actions: list of scope and action to do policy checks on,
the composition of which is (scope, action). Multiple actions
are treated as a logical AND.
* scope: service type man... |
def unpack_directory(filename, extract_dir, progress_filter=default_filter):
""""Unpack" a directory, using the same interface as for archives
Raises ``UnrecognizedFormat`` if `filename` is not a directory
"""
if not os.path.isdir(filename):
raise UnrecognizedFormat("%s is not a directory" % (f... | Unpack" a directory, using the same interface as for archives
Raises ``UnrecognizedFormat`` if `filename` is not a directory |
def add_plugins(self, page, placeholder):
"""
Add a "TextPlugin" in all languages.
"""
for language_code, lang_name in iter_languages(self.languages):
for no in range(1, self.dummy_text_count + 1):
add_plugin_kwargs = self.get_add_plugin_kwargs(
... | Add a "TextPlugin" in all languages. |
def register(self, receiver_id, receiver):
"""Register a receiver."""
assert receiver_id not in self.receivers
self.receivers[receiver_id] = receiver(receiver_id) | Register a receiver. |
def wrap(ptr, base=None):
"""Wrap the given pointer with shiboken and return the appropriate QObject
:returns: if ptr is not None returns a QObject that is cast to the appropriate class
:rtype: QObject | None
:raises: None
"""
if ptr is None:
return None
ptr = long(ptr) # Ensure typ... | Wrap the given pointer with shiboken and return the appropriate QObject
:returns: if ptr is not None returns a QObject that is cast to the appropriate class
:rtype: QObject | None
:raises: None |
def indian_punctuation_tokenize_regex(self, untokenized_string: str):
"""A trivial tokenizer which just tokenizes on the punctuation boundaries.
This also includes punctuation, namely the the purna virama ("|") and
deergha virama ("॥"), for Indian language scripts.
:type untokenized_str... | A trivial tokenizer which just tokenizes on the punctuation boundaries.
This also includes punctuation, namely the the purna virama ("|") and
deergha virama ("॥"), for Indian language scripts.
:type untokenized_string: str
:param untokenized_string: A string containing one of more sente... |
def destroy(self):
""" Custom destructor that deletes the fragment and removes
itself from the adapter it was added to.
"""
#: Destroy fragment
fragment = self.fragment
if fragment:
#: Stop listening
fragment.setFragmentListener(None)
... | Custom destructor that deletes the fragment and removes
itself from the adapter it was added to. |
def fake_getaddrinfo(
host, port, family=None, socktype=None, proto=None, flags=None):
"""drop-in replacement for :py:func:`socket.getaddrinfo`"""
return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP,
'', (host, port))] | drop-in replacement for :py:func:`socket.getaddrinfo` |
def _load_multipolygon(tokens, string):
"""
Has similar inputs and return value to to :func:`_load_point`, except is
for handling MULTIPOLYGON geometry.
:returns:
A GeoJSON `dict` MultiPolygon representation of the WKT ``string``.
"""
open_paren = next(tokens)
if not open_paren == '... | Has similar inputs and return value to to :func:`_load_point`, except is
for handling MULTIPOLYGON geometry.
:returns:
A GeoJSON `dict` MultiPolygon representation of the WKT ``string``. |
def next_color(self):
"""
Returns the next color. Currently returns a random
color from the Colorbrewer 11-class diverging BrBG palette.
Returns
-------
next_rgb_color: tuple of ImageColor
"""
next_rgb_color = ImageColor.getrgb(random.choice(BrBG_11.hex_... | Returns the next color. Currently returns a random
color from the Colorbrewer 11-class diverging BrBG palette.
Returns
-------
next_rgb_color: tuple of ImageColor |
def create_client(self, client_id, client_secret):
"""
Create a new client for use by applications.
"""
assert self.is_admin, "Must authenticate() as admin to create client"
return self.uaac.create_client(client_id, client_secret) | Create a new client for use by applications. |
def import_signed(cls, name, certificate, private_key):
"""
Import a signed certificate and private key as a client protection CA.
This is a shortcut method to the 3 step process:
* Create CA with name
* Import certificate
* Import private ke... | Import a signed certificate and private key as a client protection CA.
This is a shortcut method to the 3 step process:
* Create CA with name
* Import certificate
* Import private key
Create the CA::
ClientProtectionCA.i... |
def add_function(self, func):
""" Record line profiling information for the given Python function.
"""
try:
# func_code does not exist in Python3
code = func.__code__
except AttributeError:
import warnings
warnings.warn("Could not extract a... | Record line profiling information for the given Python function. |
def pipeline_name(self):
"""
Get pipeline name of current stage instance.
Because instantiating stage instance could be performed in different ways and those return different results,
we have to check where from to get name of the pipeline.
:return: pipeline name.
"""
... | Get pipeline name of current stage instance.
Because instantiating stage instance could be performed in different ways and those return different results,
we have to check where from to get name of the pipeline.
:return: pipeline name. |
def rectify_acquaintance_strategy(
circuit: circuits.Circuit,
acquaint_first: bool=True
) -> None:
"""Splits moments so that they contain either only acquaintance gates
or only permutation gates. Orders resulting moments so that the first one
is of the same type as the previous one.
... | Splits moments so that they contain either only acquaintance gates
or only permutation gates. Orders resulting moments so that the first one
is of the same type as the previous one.
Args:
circuit: The acquaintance strategy to rectify.
acquaint_first: Whether to make acquaintance moment firs... |
def get_tpm_status(d_info):
"""Get the TPM support status.
Get the TPM support status of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:returns: TPM support status
"""
# note:
# Get TPM support status : ipmi cmd '0xF5', valid flags '0xC0'
#
# $ ipm... | Get the TPM support status.
Get the TPM support status of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:returns: TPM support status |
def get_wd(self, path):
"""
Returns the watch descriptor associated to path. This method
presents a prohibitive cost, always prefer to keep the WD
returned by add_watch(). If the path is unknown it returns None.
@param path: Path.
@type path: str
@return: WD or N... | Returns the watch descriptor associated to path. This method
presents a prohibitive cost, always prefer to keep the WD
returned by add_watch(). If the path is unknown it returns None.
@param path: Path.
@type path: str
@return: WD or None.
@rtype: int or None |
def quantile(self, q, dim=None, interpolation='linear',
numeric_only=False, keep_attrs=None):
"""Compute the qth quantile of the data along the specified dimension.
Returns the qth quantiles(s) of the array elements for each variable
in the Dataset.
Parameters
... | Compute the qth quantile of the data along the specified dimension.
Returns the qth quantiles(s) of the array elements for each variable
in the Dataset.
Parameters
----------
q : float in range of [0,1] (or sequence of floats)
Quantile to compute, which must be betw... |
def QA_SU_save_index_list(engine, client=DATABASE):
"""save index_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_index_list(client=client) | save index_list
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) |
def create_cluster(cluster_dict, datacenter=None, cluster=None,
service_instance=None):
'''
Creates a cluster.
Note: cluster_dict['name'] will be overridden by the cluster param value
config_dict
Dictionary with the config values of the new cluster.
datacenter
N... | Creates a cluster.
Note: cluster_dict['name'] will be overridden by the cluster param value
config_dict
Dictionary with the config values of the new cluster.
datacenter
Name of datacenter containing the cluster.
Ignored if already contained by proxy details.
Default value ... |
def gdalwarp(src, dst, options):
"""
a simple wrapper for :osgeo:func:`gdal.Warp`
Parameters
----------
src: str, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset`
the input data set
dst: str
the output data set
options: dict
additional parameters passed t... | a simple wrapper for :osgeo:func:`gdal.Warp`
Parameters
----------
src: str, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset`
the input data set
dst: str
the output data set
options: dict
additional parameters passed to gdal.Warp; see :osgeo:func:`gdal.WarpOption... |
def horz_offset(self, offset):
"""
Set the value of ./c:manualLayout/c:x@val to *offset* and
./c:manualLayout/c:xMode@val to "factor". Remove ./c:manualLayout if
*offset* == 0.
"""
if offset == 0.0:
self._remove_manualLayout()
return
manual... | Set the value of ./c:manualLayout/c:x@val to *offset* and
./c:manualLayout/c:xMode@val to "factor". Remove ./c:manualLayout if
*offset* == 0. |
def add_lifecycle_delete_rule(self, **kw):
"""Add a "delete" rule to lifestyle rules configured for this bucket.
See https://cloud.google.com/storage/docs/lifecycle and
https://cloud.google.com/storage/docs/json_api/v1/buckets
.. literalinclude:: snippets.py
:start-after... | Add a "delete" rule to lifestyle rules configured for this bucket.
See https://cloud.google.com/storage/docs/lifecycle and
https://cloud.google.com/storage/docs/json_api/v1/buckets
.. literalinclude:: snippets.py
:start-after: [START add_lifecycle_delete_rule]
:end-bef... |
def randomBinaryField(self):
"""
Return random bytes format.
"""
lst = [
b"hello world",
b"this is bytes",
b"awesome django",
b"djipsum is awesome",
b"\x00\x01\x02\x03\x04\x05\x06\x07",
b"\x0b\x0c\x0e\x0f"
]
... | Return random bytes format. |
def savefig(filename, path="figs", fig=None, ext='eps', verbose=False, **kwargs):
"""
Save the figure *fig* (optional, if not specified, latest figure in focus) to *filename* in the path *path* with extension *ext*.
*\*\*kwargs* is passed to :meth:`matplotlib.figure.Figure.savefig`.
"""
filename ... | Save the figure *fig* (optional, if not specified, latest figure in focus) to *filename* in the path *path* with extension *ext*.
*\*\*kwargs* is passed to :meth:`matplotlib.figure.Figure.savefig`. |
def _find(api_method, query, limit, return_handler, first_page_size, **kwargs):
''' Takes an API method handler (dxpy.api.find*) and calls it with *query*,
and then wraps a generator around its output. Used by the methods below.
Note that this function may only be used for /system/find* methods.
'''
... | Takes an API method handler (dxpy.api.find*) and calls it with *query*,
and then wraps a generator around its output. Used by the methods below.
Note that this function may only be used for /system/find* methods. |
def get_data_dir(module_name: str) -> str:
"""Ensure the appropriate Bio2BEL data directory exists for the given module, then returns the file path.
:param module_name: The name of the module. Ex: 'chembl'
:return: The module's data directory
"""
module_name = module_name.lower()
data_dir = os.... | Ensure the appropriate Bio2BEL data directory exists for the given module, then returns the file path.
:param module_name: The name of the module. Ex: 'chembl'
:return: The module's data directory |
def do_list_cap(self, line):
"""list_cap <peer>
"""
def f(p, args):
for i in p.netconf.server_capabilities:
print(i)
self._request(line, f) | list_cap <peer> |
def modified_Wilson_Tc(zs, Tcs, Aijs):
r'''Calculates critical temperature of a mixture according to
mixing rules in [1]_. Equation
.. math::
T_{cm} = \sum_i x_i T_{ci} + C\sum_i x_i \ln \left(x_i + \sum_j x_j A_{ij}\right)T_{ref}
For a binary mxiture, this simplifies to:
.. math::
... | r'''Calculates critical temperature of a mixture according to
mixing rules in [1]_. Equation
.. math::
T_{cm} = \sum_i x_i T_{ci} + C\sum_i x_i \ln \left(x_i + \sum_j x_j A_{ij}\right)T_{ref}
For a binary mxiture, this simplifies to:
.. math::
T_{cm} = x_1 T_{c1} + x_2 T_{c2} + C[x_1 ... |
def mavlink_packet(self, msg):
'''handle an incoming mavlink packet'''
if not isinstance(self.checklist, mp_checklist.CheckUI):
return
if not self.checklist.is_alive():
return
type = msg.get_type()
master = self.master
if type == 'HEARTBEAT':
... | handle an incoming mavlink packet |
def main():
"""Provide main CLI entrypoint."""
if os.environ.get('DEBUG'):
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
# botocore info is spammy
logging.getLogger('botocore').setLevel(logging.ERROR)
cli_arguments = fix_hyphen_co... | Provide main CLI entrypoint. |
def references_json_authors(ref_authors, ref_content):
"build the authors for references json here for testability"
all_authors = references_authors(ref_authors)
if all_authors != {}:
if ref_content.get("type") in ["conference-proceeding", "journal", "other",
... | build the authors for references json here for testability |
def convtable2dict(convtable, locale, update=None):
"""
Convert a list of conversion dict to a dict for a certain locale.
>>> sorted(convtable2dict([{'zh-hk': '列斯', 'zh-hans': '利兹', 'zh': '利兹', 'zh-tw': '里茲'}, {':uni': '巨集', 'zh-cn': '宏'}], 'zh-cn').items())
[('列斯', '利兹'), ('利兹', '利兹'), ('巨集', '宏'), ('... | Convert a list of conversion dict to a dict for a certain locale.
>>> sorted(convtable2dict([{'zh-hk': '列斯', 'zh-hans': '利兹', 'zh': '利兹', 'zh-tw': '里茲'}, {':uni': '巨集', 'zh-cn': '宏'}], 'zh-cn').items())
[('列斯', '利兹'), ('利兹', '利兹'), ('巨集', '宏'), ('里茲', '利兹')] |
def viewAt(self, point):
"""
Looks up the view at the inputed point.
:param point | <QtCore.QPoint>
:return <projexui.widgets.xviewwidget.XView> || None
"""
widget = self.childAt(point)
if widget:
return projexui.ancestor(widget, XView)
... | Looks up the view at the inputed point.
:param point | <QtCore.QPoint>
:return <projexui.widgets.xviewwidget.XView> || None |
def insert_or_merge_entity(self, table_name, entity, timeout=None):
'''
Merges an existing entity or inserts a new entity if it does not exist
in the table.
If insert_or_merge_entity is used to merge an entity, any properties from
the previous entity will be retained if the re... | Merges an existing entity or inserts a new entity if it does not exist
in the table.
If insert_or_merge_entity is used to merge an entity, any properties from
the previous entity will be retained if the request does not define or
include them.
:param str table_name:
... |
def run_ppm_server(pdb_file, outfile, force_rerun=False):
"""Run the PPM server from OPM to predict transmembrane residues.
Args:
pdb_file (str): Path to PDB file
outfile (str): Path to output HTML results file
force_rerun (bool): Flag to rerun PPM if HTML results file already exists
... | Run the PPM server from OPM to predict transmembrane residues.
Args:
pdb_file (str): Path to PDB file
outfile (str): Path to output HTML results file
force_rerun (bool): Flag to rerun PPM if HTML results file already exists
Returns:
dict: Dictionary of information from the PPM ... |
def _use_tables(objs):
''' Whether a collection of Bokeh objects contains a TableWidget
Args:
objs (seq[Model or Document]) :
Returns:
bool
'''
from ..models.widgets import TableWidget
return _any(objs, lambda obj: isinstance(obj, TableWidget)) | Whether a collection of Bokeh objects contains a TableWidget
Args:
objs (seq[Model or Document]) :
Returns:
bool |
def update_replication_schedule(self, schedule_id, schedule):
"""
Update a replication schedule.
@param schedule_id: The id of the schedule to update.
@param schedule: The modified schedule.
@return: The updated replication schedule.
@since: API v3
"""
return self._put("replications/%s"... | Update a replication schedule.
@param schedule_id: The id of the schedule to update.
@param schedule: The modified schedule.
@return: The updated replication schedule.
@since: API v3 |
def align_transcriptome(fastq_file, pair_file, ref_file, data):
"""
bowtie2 with settings for aligning to the transcriptome for eXpress/RSEM/etc
"""
work_bam = dd.get_work_bam(data)
base, ext = os.path.splitext(work_bam)
out_file = base + ".transcriptome" + ext
if utils.file_exists(out_file)... | bowtie2 with settings for aligning to the transcriptome for eXpress/RSEM/etc |
def proj_path(*path_parts):
# type: (str) -> str
""" Return absolute path to the repo dir (root project directory).
Args:
path (str):
The path relative to the project root (pelconf.yaml).
Returns:
str: The given path converted to an absolute path.
"""
path_parts = p... | Return absolute path to the repo dir (root project directory).
Args:
path (str):
The path relative to the project root (pelconf.yaml).
Returns:
str: The given path converted to an absolute path. |
def between(arg, lower, upper):
"""
Check if the input expr falls between the lower/upper bounds
passed. Bounds are inclusive. All arguments must be comparable.
Returns
-------
is_between : BooleanValue
"""
lower = as_value_expr(lower)
upper = as_value_expr(upper)
op = ops.Betw... | Check if the input expr falls between the lower/upper bounds
passed. Bounds are inclusive. All arguments must be comparable.
Returns
-------
is_between : BooleanValue |
def all_tags_of_type(self, type_or_types, recurse_into_sprites = True):
"""
Generator for all tags of the given type_or_types.
Generates in breadth-first order, optionally including all sub-containers.
"""
for t in self.tags:
if isinstance(t, type_or_types):
... | Generator for all tags of the given type_or_types.
Generates in breadth-first order, optionally including all sub-containers. |
def _output(cls, fluents: Sequence[FluentPair]) -> Sequence[tf.Tensor]:
'''Converts `fluents` to tensors with datatype tf.float32.'''
output = []
for _, fluent in fluents:
tensor = fluent.tensor
if tensor.dtype != tf.float32:
tensor = tf.cast(tensor, tf.fl... | Converts `fluents` to tensors with datatype tf.float32. |
def parse_file(self, fpath):
'''
Read a file on the file system (relative to salt's base project dir)
:returns: A file-like object.
:raises IOError: If the file cannot be found or read.
'''
sdir = os.path.abspath(os.path.join(os.path.dirname(salt.__file__),
... | Read a file on the file system (relative to salt's base project dir)
:returns: A file-like object.
:raises IOError: If the file cannot be found or read. |
def fost_hmac_url_signature(
key, secret, host, path, query_string, expires):
"""
Return a signature that corresponds to the signed URL.
"""
if query_string:
document = '%s%s?%s\n%s' % (host, path, query_string, expires)
else:
document = '%s%s\n%s' % (host, path, expires)
... | Return a signature that corresponds to the signed URL. |
def configuration(self):
"""
:rtype: twilio.rest.flex_api.v1.configuration.ConfigurationList
"""
if self._configuration is None:
self._configuration = ConfigurationList(self)
return self._configuration | :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationList |
def cleanup(self, ctime=None):
'''
This method is called iteratively by the connection owning it.
Its job is to control the size of cache and remove old entries.
'''
ctime = ctime or time.time()
if self.last_cleanup:
self.average_cleanup_time.add_point(ctime -... | This method is called iteratively by the connection owning it.
Its job is to control the size of cache and remove old entries. |
def _run_program(self, bin, fastafile, params=None):
"""
Run AMD and predict motifs from a FASTA file.
Parameters
----------
bin : str
Command used to run the tool.
fastafile : str
Name of the FASTA input file.
params : dict, opt... | Run AMD and predict motifs from a FASTA file.
Parameters
----------
bin : str
Command used to run the tool.
fastafile : str
Name of the FASTA input file.
params : dict, optional
Optional parameters. For some of the tools required par... |
def enumerate_sources(self):
""" Return a list of (source_id, source_name) tuples """
sources = []
for source_id in range(1, 17):
try:
name = yield from self.get_source_variable(source_id, 'name')
if name:
sources.append((source_id,... | Return a list of (source_id, source_name) tuples |
def _tidy(self) -> None:
"""
Removes overlaps, etc., and sorts.
"""
if self.no_overlap:
self.remove_overlap(self.no_contiguous) # will sort
else:
self._sort() | Removes overlaps, etc., and sorts. |
def compile(self, options=[]):
"""
Compiles the program object to PTX using the compiler options
specified in `options`.
"""
try:
self._interface.nvrtcCompileProgram(self._program, options)
ptx = self._interface.nvrtcGetPTX(self._program)
retur... | Compiles the program object to PTX using the compiler options
specified in `options`. |
def cmdline_split(s: str, platform: Union[int, str] = 'this') -> List[str]:
"""
As per
https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex.
Multi-platform variant of ``shlex.split()`` for command-line splitting.
For use with ``subprocess``, for ``argv`` inje... | As per
https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex.
Multi-platform variant of ``shlex.split()`` for command-line splitting.
For use with ``subprocess``, for ``argv`` injection etc. Using fast REGEX.
Args:
s:
string to split
... |
def insert(name, table='filter', family='ipv4', **kwargs):
'''
.. versionadded:: 2014.1.0
Insert a rule into a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain ... | .. versionadded:: 2014.1.0
Insert a rule into a chain
name
A user-defined name to call this rule by in another part of a state or
formula. This should not be an actual rule.
table
The table that owns the chain that should be modified
family
Networking family, either i... |
def calc_mean(c0, c1=[]):
""" Calculates the mean of the data."""
if c1 != []:
return (numpy.mean(c0, 0) + numpy.mean(c1, 0)) / 2.
else:
return numpy.mean(c0, 0) | Calculates the mean of the data. |
def add_interrupt_callback(gpio_id, callback, edge='both', \
pull_up_down=PUD_OFF, threaded_callback=False, \
debounce_timeout_ms=None):
"""
Add a callback to be executed when the value on 'gpio_id' changes to
the edge specified via the 'edge' parameter (default='both').
`pull_up_down` ... | Add a callback to be executed when the value on 'gpio_id' changes to
the edge specified via the 'edge' parameter (default='both').
`pull_up_down` can be set to `RPIO.PUD_UP`, `RPIO.PUD_DOWN`, and
`RPIO.PUD_OFF`.
If `threaded_callback` is True, the callback will be started
inside a Thread.
If ... |
def dataframe_except(df, *cols, **filters):
'''
dataframe_except(df, k1=v1, k2=v2...) yields df after selecting all the columns in which the
given keys (k1, k2, etc.) have been selected such that the associated columns in the dataframe
contain only the rows whose cells match the given values.
da... | dataframe_except(df, k1=v1, k2=v2...) yields df after selecting all the columns in which the
given keys (k1, k2, etc.) have been selected such that the associated columns in the dataframe
contain only the rows whose cells match the given values.
dataframe_except(df, col1, col2...) selects all columns ex... |
def fcoe_get_login_input_fcoe_login_vlan(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_login = ET.Element("fcoe_get_login")
config = fcoe_get_login
input = ET.SubElement(fcoe_get_login, "input")
fcoe_login_vlan = ET.SubElement(... | Auto Generated Code |
def _create_config_translation(cls, config, lang):
"""
Creates a translation for the given ApphookConfig
Only django-parler kind of models are currently supported.
``AutoCMSAppMixin.auto_setup['config_translated_fields']`` is used to fill in the data
of the instance for all the... | Creates a translation for the given ApphookConfig
Only django-parler kind of models are currently supported.
``AutoCMSAppMixin.auto_setup['config_translated_fields']`` is used to fill in the data
of the instance for all the languages.
:param config: ApphookConfig instance
:par... |
def ticket1to2(old):
"""
change Ticket to refer to Products and not benefactor factories.
"""
if isinstance(old.benefactor, Multifactor):
types = list(chain(*[b.powerupNames for b in
old.benefactor.benefactors('ascending')]))
elif isinstance(old.benefactor, InitializerBenefac... | change Ticket to refer to Products and not benefactor factories. |
def get_boot_device(self):
"""Get the current boot device for the node.
Provides the current boot device of the node. Be aware that not
all drivers support this.
:raises: InvalidParameterValue if any connection parameters are
incorrect.
:... | Get the current boot device for the node.
Provides the current boot device of the node. Be aware that not
all drivers support this.
:raises: InvalidParameterValue if any connection parameters are
incorrect.
:raises: MissingParameterValue if a requ... |
def set_project_path(self, path):
"""
Sets the project path and disables the project search in the combobox
if the value of path is None.
"""
if path is None:
self.project_path = None
self.model().item(PROJECT, 0).setEnabled(False)
if s... | Sets the project path and disables the project search in the combobox
if the value of path is None. |
def _calculate_cloud_ice_perc(self):
""" Return the percentage of pixels that are either cloud or snow with
high confidence (> 67%).
"""
self.output('Calculating cloud and snow coverage from QA band', normal=True, arrow=True)
a = rasterio.open(join(self.scene_path, self._get_full... | Return the percentage of pixels that are either cloud or snow with
high confidence (> 67%). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.