code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def read_socket_input(connection, socket_obj):
"""Read from the network layer and processes all data read. Can
support both blocking and non-blocking sockets.
Returns the number of input bytes processed, or EOS if input processing
is done. Any exceptions raised by the socket are re-raised.
"""
... | Read from the network layer and processes all data read. Can
support both blocking and non-blocking sockets.
Returns the number of input bytes processed, or EOS if input processing
is done. Any exceptions raised by the socket are re-raised. |
def variantAnnotationsGenerator(self, request):
"""
Returns a generator over the (variantAnnotaitons, nextPageToken) pairs
defined by the specified request.
"""
compoundId = datamodel.VariantAnnotationSetCompoundId.parse(
request.variant_annotation_set_id)
dat... | Returns a generator over the (variantAnnotaitons, nextPageToken) pairs
defined by the specified request. |
def deactivate_in_ec(self, ec_index):
'''Deactivate this component in an execution context.
@param ec_index The index of the execution context to deactivate in.
This index is into the total array of contexts, that
is both owned and participating contexts.... | Deactivate this component in an execution context.
@param ec_index The index of the execution context to deactivate in.
This index is into the total array of contexts, that
is both owned and participating contexts. If the value
of ec_index... |
def get_tracerinfo(tracerinfo_file):
"""
Read an output's tracerinfo.dat file and parse into a DataFrame for
use in selecting and parsing categories.
Parameters
----------
tracerinfo_file : str
Path to tracerinfo.dat
Returns
-------
DataFrame containing the tracer informati... | Read an output's tracerinfo.dat file and parse into a DataFrame for
use in selecting and parsing categories.
Parameters
----------
tracerinfo_file : str
Path to tracerinfo.dat
Returns
-------
DataFrame containing the tracer information. |
def filter_by(self, string):
"""Filters treeview"""
self._reatach()
if string == '':
self.filter_remove()
return
self._expand_all()
self.treeview.selection_set('')
children = self.treeview.get_children('')
for item in children:
... | Filters treeview |
def CRRAutility(c, gam):
'''
Evaluates constant relative risk aversion (CRRA) utility of consumption c
given risk aversion parameter gam.
Parameters
----------
c : float
Consumption value
gam : float
Risk aversion
Returns
-------
(unnamed) : float
Utilit... | Evaluates constant relative risk aversion (CRRA) utility of consumption c
given risk aversion parameter gam.
Parameters
----------
c : float
Consumption value
gam : float
Risk aversion
Returns
-------
(unnamed) : float
Utility
Tests
-----
Test a val... |
def add_file_recursive(self, filename, trim=False):
"""Add a file and all its recursive dependencies to the graph.
Args:
filename: The name of the file.
trim: Whether to trim the dependencies of builtin and system files.
"""
assert not self.final, 'Trying to mutate ... | Add a file and all its recursive dependencies to the graph.
Args:
filename: The name of the file.
trim: Whether to trim the dependencies of builtin and system files. |
def unwrap_state_dict(self, obj: Dict[str, Any]) -> Union[Tuple[str, Any], Tuple[None, None]]:
"""Unwraps a marshalled state previously wrapped using :meth:`wrap_state_dict`."""
if len(obj) == 2:
typename = obj.get(self.type_key)
state = obj.get(self.state_key)
if typ... | Unwraps a marshalled state previously wrapped using :meth:`wrap_state_dict`. |
def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True):
"""Evaluates by creating a MultiIndex containing evaluated data and index.
See `LazyResult`
Returns
-------
MultiIndex
MultiIndex with evaluated data.
"""
... | Evaluates by creating a MultiIndex containing evaluated data and index.
See `LazyResult`
Returns
-------
MultiIndex
MultiIndex with evaluated data. |
def create_parser(self, prog_name, subcommand):
"""
Customize the parser to include option groups.
"""
parser = optparse.OptionParser(
prog=prog_name,
usage=self.usage(subcommand),
version=self.get_version(),
option_list=self.get_o... | Customize the parser to include option groups. |
def has_active_condition(self, condition, instances):
"""
Given a list of instances, and the condition active for
this switch, returns a boolean representing if the
conditional is met, including a non-instance default.
"""
return_value = None
for instance in insta... | Given a list of instances, and the condition active for
this switch, returns a boolean representing if the
conditional is met, including a non-instance default. |
def xpathNextAncestor(self, ctxt):
"""Traversal function for the "ancestor" direction the
ancestor axis contains the ancestors of the context node;
the ancestors of the context node consist of the parent of
context node and the parent's parent and so on; the nodes
are ord... | Traversal function for the "ancestor" direction the
ancestor axis contains the ancestors of the context node;
the ancestors of the context node consist of the parent of
context node and the parent's parent and so on; the nodes
are ordered in reverse document order; thus the paren... |
def set(self, instance, value, **kw): # noqa
"""Set the value of the refernce field
"""
ref = []
# The value is an UID
if api.is_uid(value):
ref.append(api.get_object_by_uid(value))
# The value is already an object
if api.is_at_content(value):
... | Set the value of the refernce field |
def _make_examples(bam_file, data, ref_file, region_bed, out_file, work_dir):
"""Create example pileup images to feed into variant calling.
"""
log_dir = utils.safe_makedir(os.path.join(work_dir, "log"))
example_dir = utils.safe_makedir(os.path.join(work_dir, "examples"))
if len(glob.glob(os.path.jo... | Create example pileup images to feed into variant calling. |
def rewrite_references_json(json_content, rewrite_json):
""" general purpose references json rewriting by matching the id value """
for ref in json_content:
if ref.get("id") and ref.get("id") in rewrite_json:
for key, value in iteritems(rewrite_json.get(ref.get("id"))):
ref[k... | general purpose references json rewriting by matching the id value |
def prepare_check(data):
"""Prepare check for catalog endpoint
Parameters:
data (Object or ObjectID): Check ID or check definition
Returns:
Tuple[str, dict]: where first is ID and second is check definition
"""
if not data:
return None, {}
if isinstance(data, str):
... | Prepare check for catalog endpoint
Parameters:
data (Object or ObjectID): Check ID or check definition
Returns:
Tuple[str, dict]: where first is ID and second is check definition |
def _copyAllocatedStates(self):
"""If state is allocated in CPP, copy over the data into our numpy arrays."""
# Get learn states if we need to print them out
if self.verbosity > 1 or self.retrieveLearningStates:
(activeT, activeT1, predT, predT1) = self.cells4.getLearnStates()
self.lrnActiveSta... | If state is allocated in CPP, copy over the data into our numpy arrays. |
def merge_dicts(base, updates):
"""
Given two dicts, merge them into a new dict as a shallow copy.
Parameters
----------
base: dict
The base dictionary.
updates: dict
Secondary dictionary whose values override the base.
"""
if not base:
base = dict()
if not u... | Given two dicts, merge them into a new dict as a shallow copy.
Parameters
----------
base: dict
The base dictionary.
updates: dict
Secondary dictionary whose values override the base. |
def _get_new_column_header(self, vcf_reader):
"""Returns a standardized column header.
MuTect sample headers include the name of input alignment, which is
nice, but doesn't match up with the sample names reported in Strelka
or VarScan. To fix this, we replace with NORMAL and TUMOR using... | Returns a standardized column header.
MuTect sample headers include the name of input alignment, which is
nice, but doesn't match up with the sample names reported in Strelka
or VarScan. To fix this, we replace with NORMAL and TUMOR using the
MuTect metadata command line to replace them... |
def submit_vasp_directory(self, rootdir, authors, projects=None,
references='', remarks=None, master_data=None,
master_history=None, created_at=None,
ncpus=None):
"""
Assimilates all vasp run directories beneath a ... | Assimilates all vasp run directories beneath a particular
directory using BorgQueen to obtain structures, and then submits thhem
to the Materials Project as SNL files. VASP related meta data like
initial structure and final energies are automatically incorporated.
.. note::
... |
def table_to_csv(table, engine, filepath, chunksize=1000, overwrite=False):
"""
Export entire table to a csv file.
:param table: :class:`sqlalchemy.Table` instance.
:param engine: :class:`sqlalchemy.engine.base.Engine`.
:param filepath: file path.
:param chunksize: number of rows write to csv e... | Export entire table to a csv file.
:param table: :class:`sqlalchemy.Table` instance.
:param engine: :class:`sqlalchemy.engine.base.Engine`.
:param filepath: file path.
:param chunksize: number of rows write to csv each time.
:param overwrite: bool, if True, avoid to overite existing file.
**中文... |
def fetch_uri(self, uri, start=None, end=None):
"""fetch sequence for URI/CURIE of the form namespace:alias, such as
NCBI:NM_000059.3.
"""
namespace, alias = uri_re.match(uri).groups()
return self.fetch(alias=alias, namespace=namespace, start=start, end=end) | fetch sequence for URI/CURIE of the form namespace:alias, such as
NCBI:NM_000059.3. |
async def login(self, email: str, password: str) -> bool:
"""Login to the profile."""
login_resp = await self._request(
'post',
API_URL_USER,
json={
'version': '1.0',
'method': 'Signin',
'param': {
'E... | Login to the profile. |
def respects_language(fun):
"""Decorator for tasks with respect to site's current language.
You can use this decorator on your tasks together with default @task
decorator (remember that the task decorator must be applied last).
See also the with-statement alternative :func:`respect_language`.
**Ex... | Decorator for tasks with respect to site's current language.
You can use this decorator on your tasks together with default @task
decorator (remember that the task decorator must be applied last).
See also the with-statement alternative :func:`respect_language`.
**Example**:
.. code-block:: pytho... |
def connection_key(self):
"""
Return an index key used to cache the sampler connection.
"""
return "{host}:{namespace}:{username}".format(host=self.host, namespace=self.namespace, username=self.username) | Return an index key used to cache the sampler connection. |
def _layout(dict_vars, dict_vars_extra):
"""Print nicely [(var, description)] from phyvars"""
desc = [(v, m.description) for v, m in dict_vars.items()]
desc.extend((v, baredoc(m.description))
for v, m in dict_vars_extra.items())
_pretty_print(desc, min_col_width=26) | Print nicely [(var, description)] from phyvars |
def http_purge_url(url):
"""
Do an HTTP PURGE of the given asset.
The URL is run through urlparse and must point to the varnish instance not the varnishadm
"""
url = urlparse(url)
connection = HTTPConnection(url.hostname, url.port or 80)
path = url.path or '/'
connection.request('PURGE',... | Do an HTTP PURGE of the given asset.
The URL is run through urlparse and must point to the varnish instance not the varnishadm |
def load_external_components(typesys):
"""Load all external types defined by iotile plugins.
This allows plugins to register their own types for type annotations and
allows all registered iotile components that have associated type libraries to
add themselves to the global type system.
"""
# F... | Load all external types defined by iotile plugins.
This allows plugins to register their own types for type annotations and
allows all registered iotile components that have associated type libraries to
add themselves to the global type system. |
def xml_compare(expected, found):
"""Checks equality of two ``ElementTree`` objects.
:param expected: An ``ElementTree`` object.
:param found: An ``ElementTree`` object.
:return: ``Boolean``, whether the two objects are equal.
"""
# if comparing the same ET object
if expected == found:
... | Checks equality of two ``ElementTree`` objects.
:param expected: An ``ElementTree`` object.
:param found: An ``ElementTree`` object.
:return: ``Boolean``, whether the two objects are equal. |
def get_output_structure(self):
'''Determine the structure from the output'''
bohr_to_angstrom = 0.529177249
# determine the number of atoms
natoms = int(float(self._get_line('number of atoms/cell', self.outputf).split('=')[-1]))
# determine the initial lattice parameter
... | Determine the structure from the output |
def format_message(self, msg):
"""format message."""
return {'timestamp': int(msg.created * 1000),
'message': self.format(msg),
'stream': self.log_stream or msg.name,
'group': self.log_group} | format message. |
def get_tournament_prize_pool(self, leagueid=None, **kwargs):
"""Returns a dictionary that includes community funded tournament prize pools
:param leagueid: (int, optional)
:return: dictionary of prize pools, see :doc:`responses </responses>`
"""
if 'leagueid' not in kwargs:
... | Returns a dictionary that includes community funded tournament prize pools
:param leagueid: (int, optional)
:return: dictionary of prize pools, see :doc:`responses </responses>` |
def todegdec(origin):
"""
Convert from [+/-]DDD°MMM'SSS.SSSS" or [+/-]DDD°MMM.MMMM' to [+/-]DDD.DDDDD
"""
# if the input is already a float (or can be converted to float)
try:
return float(origin)
except ValueError:
pass
# DMS format
m = dms_re.search(origin)
if m:
... | Convert from [+/-]DDD°MMM'SSS.SSSS" or [+/-]DDD°MMM.MMMM' to [+/-]DDD.DDDDD |
def to_dict(self):
"""
Prepare a JSON serializable dict for read-only purposes.
Includes storages and IP-addresses.
Use prepare_post_body for POST and .save() for PUT.
"""
fields = dict(vars(self).items())
if self.populated:
fields['ip_addresses'] = ... | Prepare a JSON serializable dict for read-only purposes.
Includes storages and IP-addresses.
Use prepare_post_body for POST and .save() for PUT. |
def import_data(self, data):
"""Import additional data for tuning
Parameters
----------
data:
a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'
"""
_completed_num = 0
for trial_info in data:
logger.info("I... | Import additional data for tuning
Parameters
----------
data:
a list of dictionarys, each of which has at least two keys, 'parameter' and 'value' |
def scan_forever(queue, *args, **kwargs):
"""Return an infinite iterator over an fsq queue that blocks waiting
for the queue trigger. Work is yielded as FSQWorkItem objects when
available, assuming the default generator (FSQScanGenerator) is
in use.
Essentially, this function wraps fsq.... | Return an infinite iterator over an fsq queue that blocks waiting
for the queue trigger. Work is yielded as FSQWorkItem objects when
available, assuming the default generator (FSQScanGenerator) is
in use.
Essentially, this function wraps fsq.scan() and blocks for more work.
It takes... |
def _ProcessAudio(self, tag, wall_time, step, audio):
"""Processes a audio by adding it to accumulated state."""
event = AudioEvent(wall_time=wall_time,
step=step,
encoded_audio_string=audio.encoded_audio_string,
content_type=audio.content_typ... | Processes a audio by adding it to accumulated state. |
def run(self, plugins, context, callback=None, callback_args=[]):
"""Commence asynchronous tasks
This method runs through the provided `plugins` in
an asynchronous manner, interrupted by either
completion or failure of a plug-in.
Inbetween processes, the GUI is fed information
... | Commence asynchronous tasks
This method runs through the provided `plugins` in
an asynchronous manner, interrupted by either
completion or failure of a plug-in.
Inbetween processes, the GUI is fed information
from the task and redraws itself.
Arguments:
plu... |
def polylog2(x):
r'''Simple function to calculate PolyLog(2, x) from ranges 0 <= x <= 1,
with relative error guaranteed to be < 1E-7 from 0 to 0.99999. This
is a Pade approximation, with three coefficient sets with splits at 0.7
and 0.99. An exception is raised if x is under 0 or above 1.
Pa... | r'''Simple function to calculate PolyLog(2, x) from ranges 0 <= x <= 1,
with relative error guaranteed to be < 1E-7 from 0 to 0.99999. This
is a Pade approximation, with three coefficient sets with splits at 0.7
and 0.99. An exception is raised if x is under 0 or above 1.
Parameters
--------... |
def decrypt_file(file, key):
"""
Decrypts the file ``file``.
The encrypted file is assumed to end with the ``.enc`` extension. The
decrypted file is saved to the same location without the ``.enc``
extension.
The permissions on the decrypted file are automatically set to 0o600.
See also :f... | Decrypts the file ``file``.
The encrypted file is assumed to end with the ``.enc`` extension. The
decrypted file is saved to the same location without the ``.enc``
extension.
The permissions on the decrypted file are automatically set to 0o600.
See also :func:`doctr.local.encrypt_file`. |
def get(method, hmc, uri, uri_parms, logon_required):
"""Operation: List Logical Partitions of CPC (empty result in DPM
mode."""
cpc_oid = uri_parms[0]
query_str = uri_parms[1]
try:
cpc = hmc.cpcs.lookup_by_oid(cpc_oid)
except KeyError:
raise Inval... | Operation: List Logical Partitions of CPC (empty result in DPM
mode. |
def koji_instance(config, message, instance=None, *args, **kw):
""" Particular koji instances
You may not have even known it, but we have multiple instances of the koji
build system. There is the **primary** buildsystem at
`koji.fedoraproject.org <http://koji.fedoraproject.org>`_ and also
secondar... | Particular koji instances
You may not have even known it, but we have multiple instances of the koji
build system. There is the **primary** buildsystem at
`koji.fedoraproject.org <http://koji.fedoraproject.org>`_ and also
secondary instances for `ppc <http://ppc.koji.fedoraproject.org>`_, `arm
<ht... |
def get_bss_load(_, data):
"""http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n935.
Positional arguments:
data -- bytearray data to read.
Returns:
Dict.
"""
answers = {
'station count': (data[1] << 8) | data[0],
'channel utilisation': data[2] /... | http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n935.
Positional arguments:
data -- bytearray data to read.
Returns:
Dict. |
def add_file(self, file_obj):
"""
Add new file into the storage.
Args:
file_obj (file): Opened file-like object.
Returns:
obj: Path where the file-like object is stored contained with hash\
in :class:`.PathAndHash` object.
Raises:
... | Add new file into the storage.
Args:
file_obj (file): Opened file-like object.
Returns:
obj: Path where the file-like object is stored contained with hash\
in :class:`.PathAndHash` object.
Raises:
AssertionError: If the `file_obj` is not fi... |
def _Close(self):
"""Closes the file-like object."""
# pylint: disable=protected-access
super(EWFFile, self)._Close()
for file_object in self._file_objects:
file_object.close()
self._file_objects = [] | Closes the file-like object. |
def bucket_policy_to_dict(policy):
"""Produce a dictionary of read, write permissions for an existing bucket policy document"""
import json
if not isinstance(policy, dict):
policy = json.loads(policy)
statements = {s['Sid']: s for s in policy['Statement']}
d = {}
for rw in ('Read', '... | Produce a dictionary of read, write permissions for an existing bucket policy document |
def centroid(self):
'''
Return the geometric center.
'''
if self.v is None:
raise ValueError('Mesh has no vertices; centroid is not defined')
return np.mean(self.v, axis=0) | Return the geometric center. |
def save_aggregate_report_to_elasticsearch(aggregate_report,
index_suffix=None,
monthly_indexes=False):
"""
Saves a parsed DMARC aggregate report to ElasticSearch
Args:
aggregate_report (OrderedDict): A parsed for... | Saves a parsed DMARC aggregate report to ElasticSearch
Args:
aggregate_report (OrderedDict): A parsed forensic report
index_suffix (str): The suffix of the name of the index to save to
monthly_indexes (bool): Use monthly indexes instead of daily indexes
Raises:
AlreadySaved |
def _save_if_needed(request, response_content):
""" Save data to disk, if requested by the user
:param request: Download request
:type request: DownloadRequest
:param response_content: content of the download response
:type response_content: bytes
"""
if request.save_response:
file_p... | Save data to disk, if requested by the user
:param request: Download request
:type request: DownloadRequest
:param response_content: content of the download response
:type response_content: bytes |
def get_representation(self, prefix="", suffix="\n"):
"""return the string representation of the current object."""
res = prefix + "Section " + self.get_section_name().upper() + suffix
return res | return the string representation of the current object. |
def get_decode_value(self):
"""Return the key value based on it's storage type."""
if self._store_type == PUBLIC_KEY_STORE_TYPE_HEX:
value = bytes.fromhex(self._value)
elif self._store_type == PUBLIC_KEY_STORE_TYPE_BASE64:
value = b64decode(self._value)
elif self.... | Return the key value based on it's storage type. |
async def connect(self, hostname=None, port=None, tls=False, **kwargs):
""" Connect to a server, optionally over TLS. See pydle.features.RFC1459Support.connect for misc parameters. """
if not port:
if tls:
port = DEFAULT_TLS_PORT
else:
port = rfc14... | Connect to a server, optionally over TLS. See pydle.features.RFC1459Support.connect for misc parameters. |
def require_condition(cls, expr, message, *format_args, **format_kwds):
"""
used to assert a certain state. If the expression renders a false
value, an exception will be raised with the supplied message
:param: message: The failure message to attach to the raised Buzz
:param... | used to assert a certain state. If the expression renders a false
value, an exception will be raised with the supplied message
:param: message: The failure message to attach to the raised Buzz
:param: expr: A boolean value indicating an evaluated expression
:param: format_arg... |
def credentials(self):
"""google.auth.credentials.Credentials: Credentials to use for queries
performed through IPython magics
Note:
These credentials do not need to be explicitly defined if you are
using Application Default Credentials. If you are not using
... | google.auth.credentials.Credentials: Credentials to use for queries
performed through IPython magics
Note:
These credentials do not need to be explicitly defined if you are
using Application Default Credentials. If you are not using
Application Default Credentials, m... |
def search_channels(self, query, limit=25, offset=0):
"""Search for channels and return them
:param query: the query string
:type query: :class:`str`
:param limit: maximum number of results
:type limit: :class:`int`
:param offset: offset for pagination
:type offs... | Search for channels and return them
:param query: the query string
:type query: :class:`str`
:param limit: maximum number of results
:type limit: :class:`int`
:param offset: offset for pagination
:type offset: :class:`int`
:returns: A list of channels
:rt... |
def _patch_expand_paths(self, settings, name, value):
"""
Apply ``SettingsPostProcessor._patch_expand_path`` to each element in
list.
Args:
settings (dict): Current settings.
name (str): Setting name.
value (list): List of paths to patch.
Ret... | Apply ``SettingsPostProcessor._patch_expand_path`` to each element in
list.
Args:
settings (dict): Current settings.
name (str): Setting name.
value (list): List of paths to patch.
Returns:
list: Patched path list to an absolute path. |
def assertSameType(a, b):
"""
Raises an exception if @b is not an instance of type(@a)
"""
if not isinstance(b, type(a)):
raise NotImplementedError("This operation is only supported for " \
"elements of the same type. Instead found {} and {}".
format(type(a), type(b))... | Raises an exception if @b is not an instance of type(@a) |
def _path_polygon(self, points):
"Low-level polygon-drawing routine."
(xmin, ymin, xmax, ymax) = _compute_bounding_box(points)
if invisible_p(xmax, ymax):
return
self.setbb(xmin, ymin)
self.setbb(xmax, ymax)
self.newpath()
self.moveto(xscale(points[0]... | Low-level polygon-drawing routine. |
def _revert_categories(self):
"""
Inplace conversion to categories.
"""
for column, dtype in self._categories.items():
if column in self.columns:
self[column] = self[column].astype(dtype) | Inplace conversion to categories. |
def vx(self,*args,**kwargs):
"""
NAME:
vx
PURPOSE:
return x velocity at time t
INPUT:
t - (optional) time at which to get the velocity
vo= (Object-wide default) physical scale for velocities to use to convert
use_physical= use to ove... | NAME:
vx
PURPOSE:
return x velocity at time t
INPUT:
t - (optional) time at which to get the velocity
vo= (Object-wide default) physical scale for velocities to use to convert
use_physical= use to override Object-wide default for using a physical sc... |
def export_node(bpmn_graph, export_elements, node, nodes_classification, order=0, prefix="", condition="", who="",
add_join=False):
"""
General method for node exporting
:param bpmn_graph: an instance of BpmnDiagramGraph class,
:param export_elements: a dictionary ob... | General method for node exporting
:param bpmn_graph: an instance of BpmnDiagramGraph class,
:param export_elements: a dictionary object. The key is a node ID, value is a dictionary of parameters that
will be used in exported CSV document,
:param node: networkx.Node object,
... |
def _add_none_handler(validation_callable, # type: Callable
none_policy # type: int
):
# type: (...) -> Callable
"""
Adds a wrapper or nothing around the provided validation_callable, depending on the selected policy
:param validation_callable:
... | Adds a wrapper or nothing around the provided validation_callable, depending on the selected policy
:param validation_callable:
:param none_policy: an int representing the None policy, see NonePolicy
:return: |
def symmetric_difference_update(self, that):
"""
Update the set, keeping only elements found in either *self* or *that*,
but not in both.
"""
_set = self._set
_list = self._list
_set.symmetric_difference_update(that)
_list.clear()
_list.update(_set... | Update the set, keeping only elements found in either *self* or *that*,
but not in both. |
def get_first_n_queues(self, n):
"""
Run through the sequence until n queues are created and return
them. If fewer are created, return those plus empty iterables to
compensate.
"""
try:
while len(self.queues) < n:
self.__fetch__()
except StopIteration:
pass
values = list(self.queues.values())
... | Run through the sequence until n queues are created and return
them. If fewer are created, return those plus empty iterables to
compensate. |
def _shuffled_order(w, h):
"""
Generator for the order of 4-byte values.
32bit channels are also encoded using delta encoding,
but it make no sense to apply delta compression to bytes.
It is possible to apply delta compression to 2-byte or 4-byte
words, but it seems it is not the best way eithe... | Generator for the order of 4-byte values.
32bit channels are also encoded using delta encoding,
but it make no sense to apply delta compression to bytes.
It is possible to apply delta compression to 2-byte or 4-byte
words, but it seems it is not the best way either.
In PSD, each 4-byte item is spli... |
def add(self, doc, attributes=None):
"""Adds a document to the index.
Before adding documents to the index it should have been fully
setup, with the document ref and all fields to index already having
been specified.
The document must have a field name as specified by the ref (... | Adds a document to the index.
Before adding documents to the index it should have been fully
setup, with the document ref and all fields to index already having
been specified.
The document must have a field name as specified by the ref (by default
this is 'id') and it should h... |
def _read_header(stream, decoder, strict=False):
"""
Read AMF L{Message} header from the stream.
@type stream: L{BufferedByteStream<pyamf.util.BufferedByteStream>}
@param decoder: An AMF0 decoder.
@param strict: Use strict decoding policy. Default is C{False}. Will raise a
L{pyamf.DecodeErr... | Read AMF L{Message} header from the stream.
@type stream: L{BufferedByteStream<pyamf.util.BufferedByteStream>}
@param decoder: An AMF0 decoder.
@param strict: Use strict decoding policy. Default is C{False}. Will raise a
L{pyamf.DecodeError} if the data that was read from the stream does not
... |
def choose_one(things):
"""Returns a random entry from a list of things"""
choice = SystemRandom().randint(0, len(things) - 1)
return things[choice].strip() | Returns a random entry from a list of things |
def account_settings_update(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/account_settings#update-account-settings"
api_path = "/api/v2/account/settings.json"
return self.call(api_path, method="PUT", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/account_settings#update-account-settings |
def parse_datetime(value: Union[datetime, StrIntFloat]) -> datetime:
"""
Parse a datetime/int/float/string and return a datetime.datetime.
This function supports time zone offsets. When the input contains one,
the output uses a timezone with a fixed offset from UTC.
Raise ValueError if the input i... | Parse a datetime/int/float/string and return a datetime.datetime.
This function supports time zone offsets. When the input contains one,
the output uses a timezone with a fixed offset from UTC.
Raise ValueError if the input is well formatted but not a valid datetime.
Raise ValueError if the input isn'... |
def save(self, filesto, upload_to=None, name=None, secret=None, prefix=None,
allowed=None, denied=None, max_size=None, **kwargs):
"""
Except for `filesto`, all of these parameters are optional, so only
bother setting the ones relevant to *this upload*.
filesto
: A... | Except for `filesto`, all of these parameters are optional, so only
bother setting the ones relevant to *this upload*.
filesto
: A `werkzeug.FileUploader`.
upload_to
: Relative path to where to upload
secret
: If True, instead of the original filename, a ... |
def _create_response_future(self, query, parameters, trace, custom_payload,
timeout, execution_profile=EXEC_PROFILE_DEFAULT,
paging_state=None, host=None):
""" Returns the ResponseFuture before calling send_request() on it """
prepared_sta... | Returns the ResponseFuture before calling send_request() on it |
def call_sockeye_train(model: str,
bpe_dir: str,
model_dir: str,
log_fname: str,
num_gpus: int,
test_mode: bool = False):
"""
Call sockeye.train with specified arguments on prepared inputs. Will r... | Call sockeye.train with specified arguments on prepared inputs. Will resume
partial training or skip training if model is already finished. Record
command for future use.
:param model: Type of translation model to train.
:param bpe_dir: Directory of BPE-encoded input data.
:param model_dir: Model... |
def update_status(self, helper, status):
""" update the helper """
if status:
self.status(status[0])
# if the status is ok, add it to the long output
if status[0] == 0:
self.add_long_output(status[1])
# if the status is not ok, add it to t... | update the helper |
def get_available_user_FIELD_transitions(instance, user, field):
"""
List of transitions available in current model state
with all conditions met and user have rights on it
"""
for transition in get_available_FIELD_transitions(instance, field):
if transition.has_perm(instance, user):
... | List of transitions available in current model state
with all conditions met and user have rights on it |
def acorr(blk, max_lag=None):
"""
Calculate the autocorrelation of a given 1-D block sequence.
Parameters
----------
blk :
An iterable with well-defined length. Don't use this function with Stream
objects!
max_lag :
The size of the result, the lags you'd need. Defaults to ``len(blk) - 1``,
... | Calculate the autocorrelation of a given 1-D block sequence.
Parameters
----------
blk :
An iterable with well-defined length. Don't use this function with Stream
objects!
max_lag :
The size of the result, the lags you'd need. Defaults to ``len(blk) - 1``,
since any lag beyond would result in z... |
def as_dict(self):
"""json friendly dict representation of Kpoints"""
d = {"comment": self.comment, "nkpoints": self.num_kpts,
"generation_style": self.style.name, "kpoints": self.kpts,
"usershift": self.kpts_shift,
"kpts_weights": self.kpts_weights, "coord_type": ... | json friendly dict representation of Kpoints |
def coroutine(func):
"""
Initializes coroutine essentially priming it to the yield statement.
Used as a decorator over functions that generate coroutines.
.. code-block:: python
# Basic coroutine producer/consumer pattern
from translate import coroutine
@coroutine
def ... | Initializes coroutine essentially priming it to the yield statement.
Used as a decorator over functions that generate coroutines.
.. code-block:: python
# Basic coroutine producer/consumer pattern
from translate import coroutine
@coroutine
def coroutine_foo(bar):
t... |
def get_properties(self):
"""
Add property to variables in BIF
Returns
-------
dict: dict of type {variable: list of properties }
Example
-------
>>> from pgmpy.readwrite import BIFReader, BIFWriter
>>> model = BIFReader('dog-problem.bif').get_mo... | Add property to variables in BIF
Returns
-------
dict: dict of type {variable: list of properties }
Example
-------
>>> from pgmpy.readwrite import BIFReader, BIFWriter
>>> model = BIFReader('dog-problem.bif').get_model()
>>> writer = BIFWriter(model)
... |
def get_results(self, hql, schema='default', fetch_size=None, hive_conf=None):
"""
Get results of the provided hql in target schema.
:param hql: hql to be executed.
:type hql: str or list
:param schema: target schema, default to 'default'.
:type schema: str
:para... | Get results of the provided hql in target schema.
:param hql: hql to be executed.
:type hql: str or list
:param schema: target schema, default to 'default'.
:type schema: str
:param fetch_size: max size of result to fetch.
:type fetch_size: int
:param hive_conf: ... |
def create_cursor(self, name=None):
"""
Returns an active connection cursor to the database.
"""
return Cursor(self.client_connection, self.connection, self.djongo_connection) | Returns an active connection cursor to the database. |
def placeholder(type_):
"""Returns the EmptyVal instance for the given type"""
typetuple = type_ if isinstance(type_, tuple) else (type_,)
if any in typetuple:
typetuple = any
if typetuple not in EMPTY_VALS:
EMPTY_VALS[typetuple] = EmptyVal(typetuple)
return EMPTY_VALS[typetuple] | Returns the EmptyVal instance for the given type |
def get_resource_by_urn(self, urn):
"""Fetch the resource corresponding to the input CTS URN.
Currently supports
only HucitAuthor and HucitWork.
:param urn: the CTS URN of the resource to fetch
:return: either an instance of `HucitAuthor` or of `HucitWork`
"""
... | Fetch the resource corresponding to the input CTS URN.
Currently supports
only HucitAuthor and HucitWork.
:param urn: the CTS URN of the resource to fetch
:return: either an instance of `HucitAuthor` or of `HucitWork` |
def proto_avgRange(theABF,m1=None,m2=None):
"""experiment: generic VC time course experiment."""
abf=ABF(theABF)
abf.log.info("analyzing as a fast IV")
if m1 is None:
m1=abf.sweepLength
if m2 is None:
m2=abf.sweepLength
I1=int(abf.pointsPerSec*m1)
I2=int(abf.pointsPerSec*m2... | experiment: generic VC time course experiment. |
def get_recipe_env(self, arch, with_flags_in_cc=True):
"""
Adds openssl recipe to include and library path.
"""
env = super(ScryptRecipe, self).get_recipe_env(arch, with_flags_in_cc)
openssl_recipe = self.get_recipe('openssl', self.ctx)
env['CFLAGS'] += openssl_recipe.inc... | Adds openssl recipe to include and library path. |
def hash_file(filepath: str) -> str:
"""Return the hexdigest MD5 hash of content of file at `filepath`."""
md5 = hashlib.md5()
acc_hash(filepath, md5)
return md5.hexdigest() | Return the hexdigest MD5 hash of content of file at `filepath`. |
def exception_handle(method):
"""Handle exception raised by requests library."""
def wrapper(*args, **kwargs):
try:
result = method(*args, **kwargs)
return result
except ProxyError:
LOG.exception('ProxyError when try to get %s.', args)
raise Proxy... | Handle exception raised by requests library. |
def revcomp(sequence):
"returns reverse complement of a string"
sequence = sequence[::-1].strip()\
.replace("A", "t")\
.replace("T", "a")\
.replace("C", "g")\
.replace("G", "c").upper()
return... | returns reverse complement of a string |
def handle_message(self, msg):
"""Issues an `inspection` service message based on a PyLint message.
Registers each message type upon first encounter.
:param utils.Message msg: a PyLint message
"""
if msg.msg_id not in self.msg_types:
self.report_message_type(msg)
... | Issues an `inspection` service message based on a PyLint message.
Registers each message type upon first encounter.
:param utils.Message msg: a PyLint message |
def __search(self, obj, item, parent="root", parents_ids=frozenset({})):
"""The main search method"""
if self.__skip_this(item, parent):
return
elif isinstance(obj, strings) and isinstance(item, strings):
self.__search_str(obj, item, parent)
elif isinstance(obj... | The main search method |
def all(self, data={}, **kwargs):
""""
Fetch All Refund
Returns:
Refund dict
"""
return super(Refund, self).all(data, **kwargs) | Fetch All Refund
Returns:
Refund dict |
def _parse_sections(self):
""" parse sections and TOC """
def _list_to_dict(_dict, path, sec):
tmp = _dict
for elm in path[:-1]:
tmp = tmp[elm]
tmp[sec] = OrderedDict()
self._sections = list()
section_regexp = r"\n==* .* ==*\n" # '==... | parse sections and TOC |
def on_any_event(self, event):
"""File created or modified"""
if os.path.isfile(event.src_path):
self.callback(event.src_path, **self.kwargs) | File created or modified |
def startProcesses(self):
"""Create and start python multiprocesses
Starting a multiprocess creates a process fork.
In theory, there should be no problem in first starting the multithreading environment and after that perform forks (only the thread requestin the fork is copied)... | Create and start python multiprocesses
Starting a multiprocess creates a process fork.
In theory, there should be no problem in first starting the multithreading environment and after that perform forks (only the thread requestin the fork is copied), but in practice, all kinds of weird... |
def init_debug(self):
"""Initialize debugging features, such as a handler for USR2 to print a trace"""
import signal
def debug_trace(sig, frame):
"""Interrupt running process, and provide a python prompt for interactive
debugging."""
self.log('Trace signal r... | Initialize debugging features, such as a handler for USR2 to print a trace |
def push_resource_cache(resourceid, info):
"""
Cache resource specific information
:param resourceid: Resource id as string
:param info: Dict to push
:return: Nothing
"""
if not resourceid:
raise ResourceInitError("Resource id missing")
if not... | Cache resource specific information
:param resourceid: Resource id as string
:param info: Dict to push
:return: Nothing |
def _get_dirs(user_dir, startup_dir):
'''
Return a list of startup dirs
'''
try:
users = os.listdir(user_dir)
except WindowsError: # pylint: disable=E0602
users = []
full_dirs = []
for user in users:
full_dir = os.path.join(user_dir, user, startup_dir)
if os... | Return a list of startup dirs |
def get_asset_form_for_create(self, asset_record_types):
"""Gets the asset form for creating new assets.
A new form should be requested for each create transaction.
arg: asset_record_types (osid.type.Type[]): array of asset
record types
return: (osid.repository.Asset... | Gets the asset form for creating new assets.
A new form should be requested for each create transaction.
arg: asset_record_types (osid.type.Type[]): array of asset
record types
return: (osid.repository.AssetForm) - the asset form
raise: NullArgument - ``asset_record... |
def kernels_initialize(self, folder):
""" create a new kernel in a specified folder from template, including
json metadata that grabs values from the configuration.
Parameters
==========
folder: the path of the folder
"""
if not os.path.isdir(fold... | create a new kernel in a specified folder from template, including
json metadata that grabs values from the configuration.
Parameters
==========
folder: the path of the folder |
def mask(self):
"""
Returns mask associated with this layer.
:return: :py:class:`~psd_tools.api.mask.Mask` or `None`
"""
if not hasattr(self, "_mask"):
self._mask = Mask(self) if self.has_mask() else None
return self._mask | Returns mask associated with this layer.
:return: :py:class:`~psd_tools.api.mask.Mask` or `None` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.