code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def vera_request(self, **kwargs):
"""Perfom a vera_request for this scene."""
request_payload = {
'output_format': 'json',
'SceneNum': self.scene_id,
}
request_payload.update(kwargs)
return self.vera_controller.data_request(request_payload) | Perfom a vera_request for this scene. |
def load(self, filename):
"""Load a FoLiA XML file.
Argument:
filename (str): The file to load
"""
#if LXE and self.mode != Mode.XPATH:
# #workaround for xml:id problem (disabled)
# #f = open(filename)
# #s = f.read().replace(' xml:id=', ' id... | Load a FoLiA XML file.
Argument:
filename (str): The file to load |
def phase_from_polarizations(h_plus, h_cross, remove_start_phase=True):
"""Return gravitational wave phase
Return the gravitation-wave phase from the h_plus and h_cross
polarizations of the waveform. The returned phase is always
positive and increasing with an initial phase of 0.
Parameters
--... | Return gravitational wave phase
Return the gravitation-wave phase from the h_plus and h_cross
polarizations of the waveform. The returned phase is always
positive and increasing with an initial phase of 0.
Parameters
----------
h_plus : TimeSeries
An PyCBC TmeSeries vector that contain... |
def refresh(self):
"""Refreshes the editor panels (resize and update margins)."""
logger.debug('Refresh panels')
self.resize()
self._update(self.editor.contentsRect(), 0,
force_update_margins=True) | Refreshes the editor panels (resize and update margins). |
def _slice_pad_length(num_items, length, overlap=0):
"""Calculate the padding length needed for sliced samples in order not to discard data.
Parameters
----------
num_items : int
Number of items in dataset before collating.
length : int
The length of each of the samples.
overlap... | Calculate the padding length needed for sliced samples in order not to discard data.
Parameters
----------
num_items : int
Number of items in dataset before collating.
length : int
The length of each of the samples.
overlap : int, default 0
The extra number of items in curre... |
def get_associated_groups(self, element):
"""Returns a list of groups that an element (reaction, metabolite, gene)
is associated with.
Parameters
----------
element: `cobra.Reaction`, `cobra.Metabolite`, or `cobra.Gene`
Returns
-------
list of `cobra.Gro... | Returns a list of groups that an element (reaction, metabolite, gene)
is associated with.
Parameters
----------
element: `cobra.Reaction`, `cobra.Metabolite`, or `cobra.Gene`
Returns
-------
list of `cobra.Group`
All groups that the provided object i... |
def set_org_processor(request):
"""
Simple context processor that automatically sets 'org' on the context if it
is present in the request.
"""
if getattr(request, "org", None):
org = request.org
pattern_bg = org.backgrounds.filter(is_active=True, background_type="P")
pattern_... | Simple context processor that automatically sets 'org' on the context if it
is present in the request. |
def choices_label(choices: tuple, value) -> str:
"""
Iterates (value,label) list and returns label matching the choice
:param choices: [(choice1, label1), (choice2, label2), ...]
:param value: Value to find
:return: label or None
"""
for key, label in choices:
if key == value:
... | Iterates (value,label) list and returns label matching the choice
:param choices: [(choice1, label1), (choice2, label2), ...]
:param value: Value to find
:return: label or None |
def resolve_address_location(proc, location):
"""Expand fields in Location namedtuple. If:
'.': get fields from stack
function/module: get fields from evaluation/introspection
location file and line number: use that
"""
curframe = proc.curframe
if location == '.':
filename ... | Expand fields in Location namedtuple. If:
'.': get fields from stack
function/module: get fields from evaluation/introspection
location file and line number: use that |
def _classic_get_full_block(grouped_dicoms):
"""
Generate a full datablock containing all timepoints
"""
# For each slice / mosaic create a data volume block
data_blocks = []
for index in range(0, len(grouped_dicoms)):
logger.info('Creating block %s of %s' % (index + 1, len(grouped_dicom... | Generate a full datablock containing all timepoints |
def get_permission_object(self):
"""
Override this method to provide the object to check for permission
against. By default uses ``self.get_object()`` as provided by
``SingleObjectMixin``. Returns None if there's no ``get_object``
method.
"""
if not isinstance(sel... | Override this method to provide the object to check for permission
against. By default uses ``self.get_object()`` as provided by
``SingleObjectMixin``. Returns None if there's no ``get_object``
method. |
def preprocess(train_dataset, output_dir, eval_dataset=None, checkpoint=None, cloud=None):
"""Blocking version of preprocess_async(). The only difference is that it blocks the caller
until the job finishes, and it does not have a return value.
"""
with warnings.catch_warnings():
warnings.simplefilter("ig... | Blocking version of preprocess_async(). The only difference is that it blocks the caller
until the job finishes, and it does not have a return value. |
def push_entity(self, entity):
"""Registers or updates an entity and returns the entity_json with an ID"""
if entity.id:
print('Updating {} entity'.format(entity.name))
self.update(entity)
else:
print('Registering {} entity'.format(entity.name))
en... | Registers or updates an entity and returns the entity_json with an ID |
def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
for lim i... | Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`. |
def apply_splice(a,splice):
"mutate a *and* return it. a as list, splice as diff.Delta."
a[splice.a:splice.b]=splice.text # text isn't always text. See diff comments.
return a | mutate a *and* return it. a as list, splice as diff.Delta. |
def get_used_fields(payload):
"""
Get a list containing the names of the fields that are used in the
xso.Query.
:param payload: Query object o be
:type payload: :class:`~aioxmpp.ibr.Query`
:return: :attr:`list`
"""
return [
tag
for tag, descriptor in payload.CHILD_MAP.it... | Get a list containing the names of the fields that are used in the
xso.Query.
:param payload: Query object o be
:type payload: :class:`~aioxmpp.ibr.Query`
:return: :attr:`list` |
def wsgi(self, environ, start_response):
""" The bottle WSGI-interface. """
try:
environ['bottle.app'] = self
request.bind(environ)
response.bind()
out = self._handle(environ)
out = self._cast(out, request, response)
# rfc2616 secti... | The bottle WSGI-interface. |
def recwalk(inputpath, sorting=True):
'''Recursively walk through a folder. This provides a mean to flatten out the files restitution (necessary to show a progress bar). This is a generator.'''
# If it's only a single file, return this single file
if os.path.isfile(inputpath):
abs_path = fullpath(in... | Recursively walk through a folder. This provides a mean to flatten out the files restitution (necessary to show a progress bar). This is a generator. |
def subkey(self, path):
"""
path:
of the form "K" where K is an integer index, or "K/N" where N is usually
a 0 (deposit address) or 1 (change address)
"""
t = path.split("/")
if len(t) == 2:
n, for_change = t
else:
n, = t
... | path:
of the form "K" where K is an integer index, or "K/N" where N is usually
a 0 (deposit address) or 1 (change address) |
def create_birthday(min_age=18, max_age=80):
"""
Create a random birthday fomr someone between the ages of min_age and max_age
"""
age = random.randint(min_age, max_age)
start = datetime.date.today() - datetime.timedelta(days=random.randint(0, 365))
return start - datetime.timedelta(days=age * 3... | Create a random birthday fomr someone between the ages of min_age and max_age |
def request_acquisition(self, acquisition_request):
"""RequestAcquisition.
[Preview API]
:param :class:`<ExtensionAcquisitionRequest> <azure.devops.v5_1.gallery.models.ExtensionAcquisitionRequest>` acquisition_request:
:rtype: :class:`<ExtensionAcquisitionRequest> <azure.devops.v5_1.gall... | RequestAcquisition.
[Preview API]
:param :class:`<ExtensionAcquisitionRequest> <azure.devops.v5_1.gallery.models.ExtensionAcquisitionRequest>` acquisition_request:
:rtype: :class:`<ExtensionAcquisitionRequest> <azure.devops.v5_1.gallery.models.ExtensionAcquisitionRequest>` |
def _init_env(self):
'''
Initialize some Salt environment.
'''
from salt.config import minion_config
from salt.grains import core as g_core
g_core.__opts__ = minion_config(self.DEFAULT_MINION_CONFIG_PATH)
self.grains_core = g_core | Initialize some Salt environment. |
def mpsse_set_clock(self, clock_hz, adaptive=False, three_phase=False):
"""Set the clock speed of the MPSSE engine. Can be any value from 450hz
to 30mhz and will pick that speed or the closest speed below it.
"""
# Disable clock divisor by 5 to enable faster speeds on FT232H.
se... | Set the clock speed of the MPSSE engine. Can be any value from 450hz
to 30mhz and will pick that speed or the closest speed below it. |
def from_arrow_type(at):
""" Convert pyarrow type to Spark data type.
"""
import pyarrow.types as types
if types.is_boolean(at):
spark_type = BooleanType()
elif types.is_int8(at):
spark_type = ByteType()
elif types.is_int16(at):
spark_type = ShortType()
elif types.is_... | Convert pyarrow type to Spark data type. |
def _var_and_skew(self, catchments, as_rural=False):
"""
Calculate L-CV and L-SKEW from a single catchment or a pooled group of catchments.
Methodology source: Science Report SC050050, para. 6.4.1-6.4.2
"""
if not hasattr(catchments, '__getitem__'): # In case of a single catchm... | Calculate L-CV and L-SKEW from a single catchment or a pooled group of catchments.
Methodology source: Science Report SC050050, para. 6.4.1-6.4.2 |
def quantile(x, q):
"""
Calculates the q quantile of x. This is the value of x greater than q% of the ordered values from x.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:param q: the quantile to calculate
:type q: float
:return: the value of this feature
... | Calculates the q quantile of x. This is the value of x greater than q% of the ordered values from x.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:param q: the quantile to calculate
:type q: float
:return: the value of this feature
:return type: float |
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise Sal... | .. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure |
def get_prtflds_all(self):
"""When converting to a namedtuple, get all possible fields in their original order."""
flds = []
dont_add = set(['_parents', 'method_flds', 'relationship_rev', 'relationship'])
# Fields: GO NS enrichment name ratio_in_study ratio_in_pop p_uncorrected
#... | When converting to a namedtuple, get all possible fields in their original order. |
def positionAt( self, location, fixedX = None, fixedY = None ):
"""
Calculates the position at the inputed location.
:param location <XConnectionLocation>
:param fixedX <float> || None
:param fixedY <float> || None
... | Calculates the position at the inputed location.
:param location <XConnectionLocation>
:param fixedX <float> || None
:param fixedY <float> || None
:return <QPointF> |
def is_logged_in(username=None):
"""Checks if user is logged in if `username`
is passed check if specified user is logged in
username can be a list"""
if username:
if not isinstance(username, (list, tuple)):
username = [username]
return 'simple_logged_in' in session and get_u... | Checks if user is logged in if `username`
is passed check if specified user is logged in
username can be a list |
def nltk_download(name, ignore_errors=True):
r"""Like nltk.download, but be quiet about it, and get a room (separate python process)
Does some simple whitespace normalization on `name`, but doesn't yet do fuzzy matching
Caches the normalized names of packages already attempted, so they aren't re-tried
... | r"""Like nltk.download, but be quiet about it, and get a room (separate python process)
Does some simple whitespace normalization on `name`, but doesn't yet do fuzzy matching
Caches the normalized names of packages already attempted, so they aren't re-tried
>>> nltk_download('nonexistent dataset name', ig... |
def replace_namespaced_cron_job_status(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_cron_job_status # noqa: E501
replace status of the specified CronJob # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP re... | replace_namespaced_cron_job_status # noqa: E501
replace status of the specified CronJob # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_cron_job_status(name, name... |
def _sort_dd_skips(configs, dd_indices_all):
"""Given a set of dipole-dipole configurations, sort them according to
their current skip.
Parameters
----------
configs: Nx4 numpy.ndarray
Dipole-Dipole configurations
Returns
-------
dd_configs_sorted: dict
dictionary with ... | Given a set of dipole-dipole configurations, sort them according to
their current skip.
Parameters
----------
configs: Nx4 numpy.ndarray
Dipole-Dipole configurations
Returns
-------
dd_configs_sorted: dict
dictionary with the skip as keys, and arrays/lists with indices to
... |
def parse_field(fld, selectable, aggregated=True, default_aggregation='sum'):
""" Parse a field object from yaml into a sqlalchemy expression """
# An aggregation is a callable that takes a single field expression
# None will perform no aggregation
aggregation_lookup = {
'sum': func.sum,
... | Parse a field object from yaml into a sqlalchemy expression |
def initial_distribution_samples(self):
r""" Samples of the initial distribution """
res = np.empty((self.nsamples, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :] = self._sampled_hmms[i].stationary_distribution
return res | r""" Samples of the initial distribution |
def _no_trailing_whitespace(relative_path, contents, linter_options):
r"""Check that every file ends with a single \n."""
del relative_path
del linter_options
trailing_whitespace = re.compile(r"(?<![ \t\r\n])[ \t]+$")
for index, line in enumerate(contents):
for space in trailing_whitespace... | r"""Check that every file ends with a single \n. |
def merge_vertices(mesh,
digits=None,
textured=True,
uv_digits=4):
"""
Removes duplicate vertices based on integer hashes of
each row.
Parameters
-------------
mesh : Trimesh object
Mesh to merge vertices on
digits : int
H... | Removes duplicate vertices based on integer hashes of
each row.
Parameters
-------------
mesh : Trimesh object
Mesh to merge vertices on
digits : int
How many digits to consider for vertices
If not specified uses tol.merge
textured : bool
If True, for textured meshes onl... |
def diff(ctx, files, metrics, all, detail):
"""Show the differences in metrics for each file."""
config = ctx.obj["CONFIG"]
if not exists(config):
handle_no_cache(ctx)
if not metrics:
metrics = get_default_metrics(config)
logger.info(f"Using default metrics {metrics}")
else... | Show the differences in metrics for each file. |
def add_simmanager_api(self, mock):
'''Add org.ofono.SimManager API to a mock'''
iface = 'org.ofono.SimManager'
mock.AddProperties(iface, {
'BarredDialing': _parameters.get('BarredDialing', False),
'CardIdentifier': _parameters.get('CardIdentifier', new_iccid(self)),
'FixedDialing':... | Add org.ofono.SimManager API to a mock |
def memoized_property(func=None, key_factory=per_instance, **kwargs):
"""A convenience wrapper for memoizing properties.
Applied like so:
>>> class Foo(object):
... @memoized_property
... def name(self):
... pass
Is equivalent to:
>>> class Foo(object):
... @property
... @memoized_me... | A convenience wrapper for memoizing properties.
Applied like so:
>>> class Foo(object):
... @memoized_property
... def name(self):
... pass
Is equivalent to:
>>> class Foo(object):
... @property
... @memoized_method
... def name(self):
... pass
Which is equivalent to:
>... |
def neuron_postproc(traj, result_list):
"""Postprocessing, sorts computed firing rates into a table
:param traj:
Container for results and parameters
:param result_list:
List of tuples, where first entry is the run index and second is the actual
result of the corresponding run.
... | Postprocessing, sorts computed firing rates into a table
:param traj:
Container for results and parameters
:param result_list:
List of tuples, where first entry is the run index and second is the actual
result of the corresponding run.
:return: |
def timeCall(*funcAndArgs, **kwargs):
r"""Return the time (in ms) it takes to call a function (the first
argument) with the remaining arguments and `kwargs`.
Examples:
To find out how long ``func('foo', spam=1)`` takes to execute, do:
``timeCall(func, foo, spam=1)``
"""
func, args = func... | r"""Return the time (in ms) it takes to call a function (the first
argument) with the remaining arguments and `kwargs`.
Examples:
To find out how long ``func('foo', spam=1)`` takes to execute, do:
``timeCall(func, foo, spam=1)`` |
def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None,
offset=0, header=False):
"""Append a field with a TZTimeOnly value from components.
:param tag: Integer or string FIX tag number.
:param h: Hours, in range 0 to 23.
:param m: Minut... | Append a field with a TZTimeOnly value from components.
:param tag: Integer or string FIX tag number.
:param h: Hours, in range 0 to 23.
:param m: Minutes, in range 0 to 59.
:param s: Optional seconds, in range 0 to 59 (60 for leap second).
:param ms: Optional milliseconds, in r... |
def fetch(task_id, wait=0, cached=Conf.CACHED):
"""
Return the processed task.
:param task_id: the task name or uuid
:type task_id: str or uuid
:param wait: the number of milliseconds to wait for a result
:type wait: int
:param bool cached: run this against the cache backend
:return: th... | Return the processed task.
:param task_id: the task name or uuid
:type task_id: str or uuid
:param wait: the number of milliseconds to wait for a result
:type wait: int
:param bool cached: run this against the cache backend
:return: the full task object
:rtype: Task |
def is_youtube_subtitle_file_supported_language(language):
"""
Check if the language code `language` (string) is a valid language code in the
internal language id format `{primary_code}` or `{primary_code}-{subcode}`
ot alternatively if it s YouTube language code that can be mapped to one of
the lan... | Check if the language code `language` (string) is a valid language code in the
internal language id format `{primary_code}` or `{primary_code}-{subcode}`
ot alternatively if it s YouTube language code that can be mapped to one of
the languages in the internal represention. |
def forwards(self, orm):
"Write your forwards methods here."
orm.Project.objects.update(label=F('name'))
orm.Cohort.objects.update(label=F('name'))
orm.Sample.objects.update(name=F('label')) | Write your forwards methods here. |
def geno(self, y, from_bounds=None,
copy_if_changed=True, copy_always=False,
repair=None, archive=None):
"""maps the phenotypic input argument into the genotypic space,
that is, computes essentially the inverse of ``pheno``.
By default a copy is made only to prevent to... | maps the phenotypic input argument into the genotypic space,
that is, computes essentially the inverse of ``pheno``.
By default a copy is made only to prevent to modify ``y``.
The inverse of the user-defined transformation (if any)
is only needed if external solutions are injected, it ... |
def request_args(self):
'''
Returns the arguments passed with the request in a dictionary.
Returns both URL resolved arguments and query string arguments.
'''
kwargs = {}
kwargs.update(self.request.match_info.items())
kwargs.update(self.request.query.items())
... | Returns the arguments passed with the request in a dictionary.
Returns both URL resolved arguments and query string arguments. |
def show_system_monitor_output_switch_status_report_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_system_monitor = ET.Element("show_system_monitor")
config = show_system_monitor
output = ET.SubElement(show_system_monitor, "output")
... | Auto Generated Code |
def set_thread_params(
self, enable=None, count=None, count_offload=None, stack_size=None, no_wait=None):
"""Sets threads related params.
:param bool enable: Enable threads in the embedded languages.
This will allow to spawn threads in your app.
.. warning:: Threads... | Sets threads related params.
:param bool enable: Enable threads in the embedded languages.
This will allow to spawn threads in your app.
.. warning:: Threads will simply *not work* if this option is not enabled.
There will likely be no error, just no execution of your t... |
def main():
"""Create Lambda events."""
logging.basicConfig(format=LOGGING_FORMAT)
log = logging.getLogger(__name__)
parser = argparse.ArgumentParser(description=main.__doc__)
add_debug(parser)
add_app(parser)
add_env(parser)
add_properties(parser)
add_region(parser)
args = pars... | Create Lambda events. |
def offset(self, index=0):
"""Offset the camera pointing to be centred on a particular CCD."""
eta = self._geometry[self.camera][index]["ra"]
xi = self._geometry[self.camera][index]["dec"]
ra = self.origin.ra - (eta/math.cos(self.dec.radian))*units.degree
dec = self.origin.dec - ... | Offset the camera pointing to be centred on a particular CCD. |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ParticipantContext for this ParticipantInstance
:rtype: twilio.rest.api.v2010.account.conference.... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ParticipantContext for this ParticipantInstance
:rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantContext |
def optimize_lambda(self, validation):
'''
Returns the index of :py:attr:`self.lambda_arr` that minimizes the
validation scatter in the segment with minimum at the lowest value
of :py:obj:`lambda`, with
fractional tolerance :py:attr:`self.leps`.
:param numpy.ndarray vali... | Returns the index of :py:attr:`self.lambda_arr` that minimizes the
validation scatter in the segment with minimum at the lowest value
of :py:obj:`lambda`, with
fractional tolerance :py:attr:`self.leps`.
:param numpy.ndarray validation: The scatter in the validation set \
... |
def lookup(self, keys, read_consistency=None, transaction=None):
"""
Lookup some entities by key.
.. seealso::
https://cloud.google.com/datastore/docs/reference/rest/v1/projects/lookup
:param keys: the keys to lookup.
:type keys: list
:param read_consistency... | Lookup some entities by key.
.. seealso::
https://cloud.google.com/datastore/docs/reference/rest/v1/projects/lookup
:param keys: the keys to lookup.
:type keys: list
:param read_consistency: the read consistency to use. default, strong or eventual.
... |
def adjust_obscov_resfile(self, resfile=None):
"""reset the elements of obscov by scaling the implied weights
based on the phi components in res_file so that the total phi
is equal to the number of non-zero weights.
Parameters
----------
resfile : str
residua... | reset the elements of obscov by scaling the implied weights
based on the phi components in res_file so that the total phi
is equal to the number of non-zero weights.
Parameters
----------
resfile : str
residual file to use. If None, residual file with case name is
... |
def glyph(dataset, orient=True, scale=True, factor=1.0, geom=None):
"""
Copies a geometric representation (called a glyph) to every
point in the input dataset. The glyph may be oriented along
the input vectors, and it may be scaled according to scalar
data or vector magnitude.
... | Copies a geometric representation (called a glyph) to every
point in the input dataset. The glyph may be oriented along
the input vectors, and it may be scaled according to scalar
data or vector magnitude.
Parameters
----------
orient : bool
Use the active v... |
def input(self):
"""
Return a list of all the aesthetics covered by
the scales.
"""
lst = [s.aesthetics for s in self]
return list(itertools.chain(*lst)) | Return a list of all the aesthetics covered by
the scales. |
def run(self):
"""主函数"""
fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), 'ThostFtdcUserApiStruct.h'), 'r')
fpy = open(os.path.join(self.out_path, 'ctp_struct.cs'), 'w', encoding='utf-8')
fpy.write('\n')
fpy.write('using System.Runtime.InteropServices;\n')
fpy.wri... | 主函数 |
def close(self, reply_code=200, reply_text=''):
"""Close Channel.
:param int reply_code: Close reply code (e.g. 200)
:param str reply_text: Close reply text
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
... | Close Channel.
:param int reply_code: Close reply code (e.g. 200)
:param str reply_text: Close reply text
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
... |
def res(self):
"""Get all target values found and corresponding parametes."""
params = [dict(zip(self.keys, p)) for p in self.params]
return [
{"target": target, "params": param}
for target, param in zip(self.target, params)
] | Get all target values found and corresponding parametes. |
def all_entities(self, is_active=True):
"""
Return all the entities in the group.
Because groups can contain both individual entities, as well
as whole groups of entities, this method acts as a convenient
way to get a queryset of all the entities in the group.
"""
... | Return all the entities in the group.
Because groups can contain both individual entities, as well
as whole groups of entities, this method acts as a convenient
way to get a queryset of all the entities in the group. |
def __replace_coord_variables(text, x_and_y, req_len, idx):
"""
Replace x and y with their coordinates and replace pi with value of pi.
:param text: text: base text to modify
:param x_and_y: location x and y
:param req_len: amount of required resources
:param idx: index ... | Replace x and y with their coordinates and replace pi with value of pi.
:param text: text: base text to modify
:param x_and_y: location x and y
:param req_len: amount of required resources
:param idx: index of resource we are working on
:return: str |
def validate(self, format, args):
'''Validate input parameters with given format.
This function also checks for wildcards for recursive mode.
'''
fmtMap = {
'cmd': 'Command',
's3': 's3 path',
'local': 'local path'
}
fmts = format.split('|')
if len(fmts) != len(args):
... | Validate input parameters with given format.
This function also checks for wildcards for recursive mode. |
def run(data, samples, noreverse, maxindels, force, ipyclient):
""" run the major functions for clustering within samples """
## list of samples to submit to queue
subsamples = []
## if sample is already done skip
for sample in samples:
## If sample not in state 2 don't try to cluster it.
... | run the major functions for clustering within samples |
def center_str(txt, font_name, font_size, offset=0):
"""Center a string on the x axis of a reportslab canvas"""
return -(text_width(txt, font_name, font_size) / 2.0) + offset | Center a string on the x axis of a reportslab canvas |
def job_factory(self):
"""
Create concrete jobs. The concrete jobs is following dictionary.
jobs = {
'PLUGINNAME-build_items': {
'method': FUNCTION_OBJECT,
'interval': INTERVAL_TIME ,
}
...
}
If ConcreteJob insta... | Create concrete jobs. The concrete jobs is following dictionary.
jobs = {
'PLUGINNAME-build_items': {
'method': FUNCTION_OBJECT,
'interval': INTERVAL_TIME ,
}
...
}
If ConcreteJob instance has "build_discovery_items",
"b... |
def register_comm_target(kernel=None):
"""Register the jupyter.widget comm target"""
if kernel is None:
kernel = get_ipython().kernel
kernel.comm_manager.register_target('jupyter.widget', Widget.handle_comm_opened) | Register the jupyter.widget comm target |
def _steal_content(self, other_page):
"""
Call ImgDoc.steal_page() instead
"""
other_doc = other_page.doc
other_doc_pages = other_doc.pages[:]
other_doc_nb_pages = other_doc.nb_pages
other_page_nb = other_page.page_nb
to_move = [
(other_page._... | Call ImgDoc.steal_page() instead |
def read_tf_records(batch_size, tf_records, num_repeats=1,
shuffle_records=True, shuffle_examples=True,
shuffle_buffer_size=None, interleave=True,
filter_amount=1.0):
"""
Args:
batch_size: batch size to return
tf_records: a list of tf_r... | Args:
batch_size: batch size to return
tf_records: a list of tf_record filenames
num_repeats: how many times the data should be read (default: One)
shuffle_records: whether to shuffle the order of files read
shuffle_examples: whether to shuffle the tf.Examples
shuffle_buf... |
def amazon_s3(self, scene, bands):
"""
Amazon S3 downloader
"""
sat = self.scene_interpreter(scene)
# Always grab MTL.txt and QA band if bands are specified
if 'BQA' not in bands:
bands.append('QA')
if 'MTL' not in bands:
bands.append('M... | Amazon S3 downloader |
def poll(poll, msg, server):
"""Given a question and answers, present a poll"""
poll = remove_smart_quotes(poll.replace(u"\u2014", u"--"))
try:
args = ARGPARSE.parse_args(shlex.split(poll)).poll
except ValueError:
return ERROR_INVALID_FORMAT
if not 2 < len(args) < len(POLL_EMOJIS) ... | Given a question and answers, present a poll |
def rpcexec(self, payload):
""" Manual execute a command on API (internally used)
param str payload: The payload containing the request
return: Servers answer to the query
rtype: json
raises RPCConnection: if no connction can be made
raises Unauthoriz... | Manual execute a command on API (internally used)
param str payload: The payload containing the request
return: Servers answer to the query
rtype: json
raises RPCConnection: if no connction can be made
raises UnauthorizedError: if the user is not authorized
... |
def add_event_subscriber(self, name, ws):
"""
Add a new websocket subscriber to an event.
name -- name of the event
ws -- the websocket
"""
if name in self.available_events:
self.available_events[name]['subscribers'].add(ws) | Add a new websocket subscriber to an event.
name -- name of the event
ws -- the websocket |
def score(self, testing_features, testing_labels):
"""estimates accuracy on testing set"""
# print("test features shape:",testing_features.shape)
# print("testing labels shape:",testing_labels.shape)
yhat = self.predict(testing_features)
return self.scoring_function(testing_label... | estimates accuracy on testing set |
def heuristic_crossover(random, candidates, args):
"""Return the offspring of heuristic crossover on the candidates.
It performs heuristic crossover (HX), which is similar to the
update rule used in particle swarm optimization. This function
also makes use of the bounder function as specified in the ... | Return the offspring of heuristic crossover on the candidates.
It performs heuristic crossover (HX), which is similar to the
update rule used in particle swarm optimization. This function
also makes use of the bounder function as specified in the EC's
``evolve`` method.
.. note::
Th... |
def release(self, sim_size):
"""
The memory release primitive for this heap implementation. Decreases the position of the break to deallocate
space. Guards against releasing beyond the initial heap base.
:param sim_size: a size specifying how much to decrease the break pointer by (may b... | The memory release primitive for this heap implementation. Decreases the position of the break to deallocate
space. Guards against releasing beyond the initial heap base.
:param sim_size: a size specifying how much to decrease the break pointer by (may be symbolic or not) |
def find_group_consistencies(groups1, groups2):
r"""
Returns a measure of group consistency
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> groups1 = [[1, 2, 3], [4], [5, 6]]
>>> groups2 = [[1, 2], [4], [5, 6]]
>>> common_groups = find_grou... | r"""
Returns a measure of group consistency
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> groups1 = [[1, 2, 3], [4], [5, 6]]
>>> groups2 = [[1, 2], [4], [5, 6]]
>>> common_groups = find_group_consistencies(groups1, groups2)
>>> result... |
def clear_source(self):
"""Removes the source.
raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.Resourc... | Removes the source.
raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* |
def setAndDrawInspectorById(self, identifier):
""" Sets the inspector and draw the contents.
Does NOT trigger any actions, so the check marks in the menus are not updated. To
achieve this, the user must update the actions by hand (or call
getInspectorActionById(identifier).t... | Sets the inspector and draw the contents.
Does NOT trigger any actions, so the check marks in the menus are not updated. To
achieve this, the user must update the actions by hand (or call
getInspectorActionById(identifier).trigger() instead). |
def _transform(self, data, transform, step_size):
'''
Transform the data. If the transform is not supported by this series,
returns the data unaltered.
'''
if callable(transform):
data = transform(data, step_size)
return data | Transform the data. If the transform is not supported by this series,
returns the data unaltered. |
def _read_var_data(self):
""" Iterate over the block of this bpch file and return handlers
in the form of `BPCHDataBundle`s for access to the data contained
therein.
"""
var_bundles = OrderedDict()
var_attrs = OrderedDict()
n_vars = 0
while self.fp.tel... | Iterate over the block of this bpch file and return handlers
in the form of `BPCHDataBundle`s for access to the data contained
therein. |
def toarray(self):
"""
Convert blocks to local ndarray
"""
if self.mode == 'spark':
return self.values.unchunk().toarray()
if self.mode == 'local':
return self.values.unchunk() | Convert blocks to local ndarray |
def extend(self, records):
"""
records - MUST HAVE FORM OF
[{"value":value}, ... {"value":value}] OR
[{"json":json}, ... {"json":json}]
OPTIONAL "id" PROPERTY IS ALSO ACCEPTED
"""
if self.settings.read_only:
Log.error("Index opened in read ... | records - MUST HAVE FORM OF
[{"value":value}, ... {"value":value}] OR
[{"json":json}, ... {"json":json}]
OPTIONAL "id" PROPERTY IS ALSO ACCEPTED |
def connect(url='https://github.com', token=None):
"""
Create a GitHub session for making requests
"""
gh_session = None
if url == 'https://github.com':
gh_session = create_session(token)
else:
gh_session = create_enterprise_session(url, token)
if gh_session is None:
... | Create a GitHub session for making requests |
def is_safe_to_wait(
lock_expiration: BlockExpiration,
reveal_timeout: BlockTimeout,
block_number: BlockNumber,
) -> SuccessOrError:
""" True if waiting is safe, i.e. there are more than enough blocks to safely
unlock on chain.
"""
# reveal timeout will not ever be larger than th... | True if waiting is safe, i.e. there are more than enough blocks to safely
unlock on chain. |
def loadtxt_asdict(fn, **kwargs):
"""Return what is returned from loadtxt as a dict.
The 'unpack' keyword is enforced to True.
The keys in the dict is the column numbers loaded. It is the
integers 0...N-1 for N loaded columns, or the numbers in usecols."""
kwargs.update(unpack=True)
d = loadtx... | Return what is returned from loadtxt as a dict.
The 'unpack' keyword is enforced to True.
The keys in the dict is the column numbers loaded. It is the
integers 0...N-1 for N loaded columns, or the numbers in usecols. |
def _patch_path(path):
r"""
Paths have a max length of api.MAX_PATH characters (260). If a target path
is longer than that, it needs to be made absolute and prepended with
\\?\ in order to work with API calls.
See http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx for
details.
"""
if path.starts... | r"""
Paths have a max length of api.MAX_PATH characters (260). If a target path
is longer than that, it needs to be made absolute and prepended with
\\?\ in order to work with API calls.
See http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx for
details. |
def load(self, config):
"""Load the password from the configuration file."""
password_dict = {}
if config is None:
logger.warning("No configuration file available. Cannot load password list.")
elif not config.has_section(self._section):
logger.warning("No [%s] se... | Load the password from the configuration file. |
def handle(self, *args, **options):
"""Create new app"""
quickstart = Quickstart()
try:
quickstart.create_app(os.path.join(settings.BASE_DIR, 'apps'), options.get('name'))
self.stdout.write(
self.style.SUCCESS("Successfully created app ({name}), don't for... | Create new app |
def _update_config_location(self,directory,files=None):
"""Loads location and applies to all files in given
files list (or if none, all files in flickr DB)
google reverse GEO to figure out location lat/long
file can contain things like:
Australia
Sydney, Australia
... | Loads location and applies to all files in given
files list (or if none, all files in flickr DB)
google reverse GEO to figure out location lat/long
file can contain things like:
Australia
Sydney, Australia
Holcomb Campground, California.
If image already has Lat... |
def get(cls, channel, start, end, pad=None, scaled=None,
dtype=None, verbose=False, allow_tape=None, **kwargs):
"""Get data for this channel from frames or NDS
This method dynamically accesses either frames on disk, or a
remote NDS2 server to find and return data for the given inter... | Get data for this channel from frames or NDS
This method dynamically accesses either frames on disk, or a
remote NDS2 server to find and return data for the given interval
Parameters
----------
channel : `str`, `~gwpy.detector.Channel`
the name of the channel to rea... |
def add(self, *widgets):
'''
Place @widgets under the blitting hand of the Container(). Each arg
must be a Widget(), a fellow Container(), or an iterable. Else, things
get ugly...
'''
for w in widgets:
if is_widget(w):
if w not in self.widget... | Place @widgets under the blitting hand of the Container(). Each arg
must be a Widget(), a fellow Container(), or an iterable. Else, things
get ugly... |
def is_iframe(self, el):
"""Check if element is an `iframe`."""
return ((el.name if self.is_xml_tree(el) else util.lower(el.name)) == 'iframe') and self.is_html_tag(el) | Check if element is an `iframe`. |
def filter(self, callback=None):
"""
Run a filter over each of the items.
:param callback: The filter callback
:type callback: callable or None
:rtype: Collection
"""
if callback:
return self.__class__(list(filter(callback, self.items)))
ret... | Run a filter over each of the items.
:param callback: The filter callback
:type callback: callable or None
:rtype: Collection |
def get_ports_count(context, filters=None):
"""Return the number of ports.
The result depends on the identity of the user making the request
(as indicated by the context) as well as any filters.
: param context: neutron api request context
: param filters: a dictionary with keys that are valid keys... | Return the number of ports.
The result depends on the identity of the user making the request
(as indicated by the context) as well as any filters.
: param context: neutron api request context
: param filters: a dictionary with keys that are valid keys for
a port as listed in the RESOURCE_ATTRI... |
def _discover_meta_cols(self, **kwargs):
"""Return the subset of `kwargs` values (not keys!) matching
a `meta` column name"""
cols = set(['exclude'])
for arg, value in kwargs.items():
if isstr(value) and value in self.meta.columns:
cols.add(value)
retu... | Return the subset of `kwargs` values (not keys!) matching
a `meta` column name |
def validate(self, value):
"""
Validates the value provided is a valid email address,
at least, on paper.
:param value: <str>
:return: <bool>
"""
if isinstance(value, (str, unicode)) and not re.match(self.__pattern, value):
raise orb.errors.ColumnVal... | Validates the value provided is a valid email address,
at least, on paper.
:param value: <str>
:return: <bool> |
def ingest_from_blob(self, blob_descriptor, ingestion_properties):
"""Enqueuing an ingest command from azure blobs.
:param azure.kusto.ingest.BlobDescriptor blob_descriptor: An object that contains a description of the blob to be ingested.
:param azure.kusto.ingest.IngestionProperties ingestion_... | Enqueuing an ingest command from azure blobs.
:param azure.kusto.ingest.BlobDescriptor blob_descriptor: An object that contains a description of the blob to be ingested.
:param azure.kusto.ingest.IngestionProperties ingestion_properties: Ingestion properties. |
def p_OperationRest(p):
"""OperationRest : ReturnType OptionalIdentifier "(" ArgumentList ")" ";"
"""
p[0] = model.Operation(return_type=p[1], name=p[2], arguments=p[4]) | OperationRest : ReturnType OptionalIdentifier "(" ArgumentList ")" ";" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.