code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_my_contributions(self, *args, **kwargs):
"""Return a get_content generator of subreddits.
The Subreddits generated are those where the session's user is a
contributor.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter can... | Return a get_content generator of subreddits.
The Subreddits generated are those where the session's user is a
contributor.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered. |
def encode(self, word, version=2):
"""Return the Caverphone code for a word.
Parameters
----------
word : str
The word to transform
version : int
The version of Caverphone to employ for encoding (defaults to 2)
Returns
-------
str... | Return the Caverphone code for a word.
Parameters
----------
word : str
The word to transform
version : int
The version of Caverphone to employ for encoding (defaults to 2)
Returns
-------
str
The Caverphone value
Exa... |
def register_plugin(self):
"""Register plugin in Spyder's main window"""
ipyconsole = self.main.ipyconsole
treewidget = self.fileexplorer.treewidget
self.main.add_dockwidget(self)
self.fileexplorer.sig_open_file.connect(self.main.open_file)
self.register_widget_sh... | Register plugin in Spyder's main window |
def bootstrap_falsealarmprob(lspinfo,
times,
mags,
errs,
nbootstrap=250,
magsarefluxes=False,
sigclip=10.0,
npeaks=No... | Calculates the false alarm probabilities of periodogram peaks using
bootstrap resampling of the magnitude time series.
The false alarm probability here is defined as::
(1.0 + sum(trialbestpeaks[i] > peak[j]))/(ntrialbestpeaks + 1)
for each best periodogram peak j. The index i is for each bootstra... |
def _harvest_lost_resources(self):
"""Return lost resources to pool."""
with self._lock:
for i in self._unavailable_range():
rtracker = self._reference_queue[i]
if rtracker is not None and rtracker.available():
self.put_resource(rtracker.re... | Return lost resources to pool. |
def add_dataset_to_collection(dataset_id, collection_id, **kwargs):
"""
Add a single dataset to a dataset collection.
"""
collection_i = _get_collection(collection_id)
collection_item = _get_collection_item(collection_id, dataset_id)
if collection_item is not None:
raise HydraError("... | Add a single dataset to a dataset collection. |
async def create_table(**data):
"""
RPC method for creating table with custom name and fields
:return event id
"""
table = data.get('table')
try:
clickhouse_queries.create_table(table, data)
return 'Table was successfully created'
except ServerException as e:
excep... | RPC method for creating table with custom name and fields
:return event id |
def serializer(metadata_prefix):
"""Return etree_dumper instances.
:param metadata_prefix: One of the metadata identifiers configured in
``OAISERVER_METADATA_FORMATS``.
"""
metadataFormats = current_app.config['OAISERVER_METADATA_FORMATS']
serializer_ = metadataFormats[metadata_prefix]['ser... | Return etree_dumper instances.
:param metadata_prefix: One of the metadata identifiers configured in
``OAISERVER_METADATA_FORMATS``. |
def add(self, media_type, media_file, title=None, introduction=None):
"""
新增其它类型永久素材
详情请参考
http://mp.weixin.qq.com/wiki/14/7e6c03263063f4813141c3e17dd4350a.html
:param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
:param media_file: 要上传的文件,一个 File-object... | 新增其它类型永久素材
详情请参考
http://mp.weixin.qq.com/wiki/14/7e6c03263063f4813141c3e17dd4350a.html
:param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
:param media_file: 要上传的文件,一个 File-object
:param title: 视频素材标题,仅上传视频素材时需要
:param introduction: 视频素材简介,仅上传视频素材时需要
... |
def generate_s3_url(files):
"""Takes files from React side, creates
SolveBio Object containing signed S3 URL."""
if files:
vault = g.client.Vault.get_personal_vault()
files = json.loads(files)
objects = []
for i in xrange(len(files)):
obj = g.client.Object.create(... | Takes files from React side, creates
SolveBio Object containing signed S3 URL. |
def generate_url(self, name: str, **kwargs) -> str:
""" generate url with urlgenerator used by urldispatch"""
return self.urlmapper.generate(name, **kwargs) | generate url with urlgenerator used by urldispatch |
def process(self, metric):
"""
process a single metric
@type metric: diamond.metric.Metric
@param metric: metric to process
@rtype None
"""
for rule in self.rules:
rule.process(metric, self) | process a single metric
@type metric: diamond.metric.Metric
@param metric: metric to process
@rtype None |
def background_color(self, node, depth):
"""Create a (unique-ish) background color for each node"""
if self.color_mapping is None:
self.color_mapping = {}
color = self.color_mapping.get(node.key)
if color is None:
depth = len(self.color_mapping)
red = ... | Create a (unique-ish) background color for each node |
def name(self):
"""Global name."""
return ffi.string(
lib.EnvGetDefglobalName(self._env, self._glb)).decode() | Global name. |
def form_invalid(self, form, prefix=None):
""" If form invalid return error list in JSON response """
response = super(FormAjaxMixin, self).form_invalid(form)
if self.request.is_ajax():
data = {
"errors_list": self.add_prefix(form.errors, prefix),
}
... | If form invalid return error list in JSON response |
def scaleBy(self, value, origin=None):
"""
Scale the object.
>>> obj.transformBy(2.0)
>>> obj.transformBy((0.5, 2.0), origin=(500, 500))
**value** must be an iterable containing two
:ref:`type-int-float` values defining the x and y
values to scale the ob... | Scale the object.
>>> obj.transformBy(2.0)
>>> obj.transformBy((0.5, 2.0), origin=(500, 500))
**value** must be an iterable containing two
:ref:`type-int-float` values defining the x and y
values to scale the object by. **origin** defines the
point at with the s... |
def make_request_fn():
"""Returns a request function."""
if FLAGS.cloud_mlengine_model_name:
request_fn = serving_utils.make_cloud_mlengine_request_fn(
credentials=GoogleCredentials.get_application_default(),
model_name=FLAGS.cloud_mlengine_model_name,
version=FLAGS.cloud_mlengine_model_... | Returns a request function. |
def rpc_get_subdomains_owned_by_address(self, address, **con_info):
"""
Get the list of subdomains owned by an address.
Return {'status': True, 'subdomains': ...} on success
Return {'error': ...} on error
"""
if not check_address(address):
return {'error': 'In... | Get the list of subdomains owned by an address.
Return {'status': True, 'subdomains': ...} on success
Return {'error': ...} on error |
def get_oauth_data(self, code, client_id, client_secret, state):
''' Get Oauth data from HelloSign
Args:
code (str): Code returned by HelloSign for our callback url
client_id (str): Client id of the associated app
client_secret (str): Secret ... | Get Oauth data from HelloSign
Args:
code (str): Code returned by HelloSign for our callback url
client_id (str): Client id of the associated app
client_secret (str): Secret token of the associated app
Returns:
A HSAccessTokenAuth... |
def next_call(self, for_method=None):
"""Start expecting or providing multiple calls.
.. note:: next_call() cannot be used in combination with :func:`fudge.Fake.times_called`
Up until calling this method, calls are infinite.
For example, before next_call() ... ::
>>> from... | Start expecting or providing multiple calls.
.. note:: next_call() cannot be used in combination with :func:`fudge.Fake.times_called`
Up until calling this method, calls are infinite.
For example, before next_call() ... ::
>>> from fudge import Fake
>>> f = Fake().pro... |
def subgraph(self, nodelist):
"""Return a CouplingMap object for a subgraph of self.
nodelist (list): list of integer node labels
"""
subcoupling = CouplingMap()
subcoupling.graph = self.graph.subgraph(nodelist)
for node in nodelist:
if node not in subcouplin... | Return a CouplingMap object for a subgraph of self.
nodelist (list): list of integer node labels |
def _opt_soft(eigvectors, rot_matrix, n_clusters):
"""
Optimizes the PCCA+ rotation matrix such that the memberships are exclusively nonnegative.
Parameters
----------
eigenvectors : ndarray
A matrix with the sorted eigenvectors in the columns. The stationary eigenvector should
be f... | Optimizes the PCCA+ rotation matrix such that the memberships are exclusively nonnegative.
Parameters
----------
eigenvectors : ndarray
A matrix with the sorted eigenvectors in the columns. The stationary eigenvector should
be first, then the one to the slowest relaxation process, etc.
... |
def create_fresh_child_cgroup(self, *subsystems):
"""
Create child cgroups of the current cgroup for at least the given subsystems.
@return: A Cgroup instance representing the new child cgroup(s).
"""
assert set(subsystems).issubset(self.per_subsystem.keys())
createdCgrou... | Create child cgroups of the current cgroup for at least the given subsystems.
@return: A Cgroup instance representing the new child cgroup(s). |
def closure(self, relation, depth=float('inf')):
"""Finds all the ancestors of the synset using provided relation.
Parameters
----------
relation : str
Name of the relation which is recursively used to fetch the ancestors.
Returns
-------
list of ... | Finds all the ancestors of the synset using provided relation.
Parameters
----------
relation : str
Name of the relation which is recursively used to fetch the ancestors.
Returns
-------
list of Synsets
Returns the ancestors of the synset via given r... |
def PyParseIntCast(string, location, tokens):
"""Return an integer from a string.
This is a pyparsing callback method that converts the matched
string into an integer.
The method modifies the content of the tokens list and converts
them all to an integer value.
Args:
string (str): original string.
... | Return an integer from a string.
This is a pyparsing callback method that converts the matched
string into an integer.
The method modifies the content of the tokens list and converts
them all to an integer value.
Args:
string (str): original string.
location (int): location in the string where the ... |
def get_backward_star(self, node):
"""Given a node, get a copy of that node's backward star.
:param node: node to retrieve the backward-star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's backward star.
:raises: ValueError -- No such node exis... | Given a node, get a copy of that node's backward star.
:param node: node to retrieve the backward-star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's backward star.
:raises: ValueError -- No such node exists. |
def t_B_SEQUENCE_COMPACT_START(self, t):
r"""
\-\ + (?= -\ )
# ^ ^ sequence indicator
| \-\ + (?= [\{\[]\ | [^:\n]*:\s )
# ^ ^ ^^^ map indicator
# ^ ^ flow indicator
"""
indent_status, curr_depth, n... | r"""
\-\ + (?= -\ )
# ^ ^ sequence indicator
| \-\ + (?= [\{\[]\ | [^:\n]*:\s )
# ^ ^ ^^^ map indicator
# ^ ^ flow indicator |
def GetCellValueNoFail (self, column, row = None):
""" get a cell, if it does not exist fail
note that column at row START AT 1 same as excel
"""
if row == None:
(row, column) = ParseCellSpec(column)
cell = Get... | get a cell, if it does not exist fail
note that column at row START AT 1 same as excel |
def ParseOptions(cls, options, output_module):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
output_module (OutputModule): output module to configure.
Raises:
BadConfigObject: when the output module object does not have the
SetServerInform... | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
output_module (OutputModule): output module to configure.
Raises:
BadConfigObject: when the output module object does not have the
SetServerInformation method. |
def stop(self):
""" Stop logging with this logger.
"""
if not self.active:
return
self.removeHandler(self.handlers[-1])
self.active = False
return | Stop logging with this logger. |
def process_files(self):
"""
Processes all the files associated with this Node. Files are downloaded if not present in the local storage.
Creates and processes a NodeFile containing this Node's metadata.
:return: A list of names of all the processed files.
"""
file_names ... | Processes all the files associated with this Node. Files are downloaded if not present in the local storage.
Creates and processes a NodeFile containing this Node's metadata.
:return: A list of names of all the processed files. |
def GetColorfulSearchPropertiesStr(self, keyColor='DarkGreen', valueColor='DarkCyan') -> str:
"""keyColor, valueColor: str, color name in class ConsoleColor"""
strs = ['<Color={}>{}</Color>: <Color={}>{}</Color>'.format(keyColor if k in Control.ValidKeys else 'DarkYellow', k, valueColor,
... | keyColor, valueColor: str, color name in class ConsoleColor |
def cudnn_compatible_lstm(units, n_hidden, n_layers=1, trainable_initial_states=None, seq_lengths=None, initial_h=None,
initial_c=None, name='cudnn_lstm', reuse=False):
""" CuDNN Compatible LSTM implementation.
It should be used to load models saved with CudnnLSTMCell to run on CPU... | CuDNN Compatible LSTM implementation.
It should be used to load models saved with CudnnLSTMCell to run on CPU.
Args:
units: tf.Tensor with dimensions [B x T x F], where
B - batch size
T - number of tokens
F - features
n_hidden: dim... |
def _reversedict(d):
"""
Internal helper for generating reverse mappings; given a
dictionary, returns a new dictionary with keys and values swapped.
"""
return dict(list(zip(list(d.values()), list(d.keys())))) | Internal helper for generating reverse mappings; given a
dictionary, returns a new dictionary with keys and values swapped. |
def date_range(data):
"""Returns the minimum activity start time and the maximum activity end time
from the active entities response. These dates are modified in the following
way. The hours (and minutes and so on) are removed from the start and end
times and a *day* is added to the end time. These are ... | Returns the minimum activity start time and the maximum activity end time
from the active entities response. These dates are modified in the following
way. The hours (and minutes and so on) are removed from the start and end
times and a *day* is added to the end time. These are the dates that should
be ... |
def deleteMultipleByPks(self, pks):
'''
deleteMultipleByPks - Delete multiple objects given their primary keys
@param pks - List of primary keys
@return - Number of objects deleted
'''
if type(pks) == set:
pks = list(pks)
if len(pks) == 1:
return self.deleteByPk(pks[0])
objs = self.mdl.obje... | deleteMultipleByPks - Delete multiple objects given their primary keys
@param pks - List of primary keys
@return - Number of objects deleted |
def imp_print(self, text, end):
"""Catch UnicodeEncodeError"""
try:
PRINT(text, end=end)
except UnicodeEncodeError:
for i in text:
try:
PRINT(i, end="")
except UnicodeEncodeError:
PRINT("?", end="")
PRINT("", end=end) | Catch UnicodeEncodeError |
def gauss_fltr_astropy(dem, size=None, sigma=None, origmask=False, fill_interior=False):
"""Astropy gaussian filter properly handles convolution with NaN
http://stackoverflow.com/questions/23832852/by-which-measures-should-i-set-the-size-of-my-gaussian-filter-in-matlab
width1 = 3; sigma1 = (width1-1) / 6;... | Astropy gaussian filter properly handles convolution with NaN
http://stackoverflow.com/questions/23832852/by-which-measures-should-i-set-the-size-of-my-gaussian-filter-in-matlab
width1 = 3; sigma1 = (width1-1) / 6;
Specify width for smallest feature of interest and determine sigma appropriately
sigma... |
def find_distributions(path_item, only=False):
"""Yield distributions accessible via `path_item`"""
importer = get_importer(path_item)
finder = _find_adapter(_distribution_finders, importer)
return finder(importer, path_item, only) | Yield distributions accessible via `path_item` |
def cancel_order(self, order_id: str) -> str:
"""Cancel an order by ID."""
self.log.debug(f'Canceling order id={order_id} on {self.name}')
if self.dry_run: # Don't cancel if dry run
self.log.warning(f'DRY RUN: Order cancelled on {self.name}: id={order_id}')
return order... | Cancel an order by ID. |
def format_section(stream, section, options, doc=None):
"""format an options section using the INI format"""
if doc:
print(_comment(doc), file=stream)
print("[%s]" % section, file=stream)
_ini_format(stream, options) | format an options section using the INI format |
def sanitize_config_loglevel(level):
'''
Kinda sorta backport of loglevel sanitization for Python 2.6.
'''
if sys.version_info[:2] != (2, 6) or isinstance(level, (int, long)):
return level
lvl = None
if isinstance(level, basestring):
lvl = logging._levelNames.get(level)
if no... | Kinda sorta backport of loglevel sanitization for Python 2.6. |
def recompute_if_necessary(self, ui):
"""Recompute the data on a thread, if necessary.
If the data has recently been computed, this call will be rescheduled for the future.
If the data is currently being computed, it do nothing."""
self.__initialize_cache()
if self.__cached_val... | Recompute the data on a thread, if necessary.
If the data has recently been computed, this call will be rescheduled for the future.
If the data is currently being computed, it do nothing. |
def predict(self, y, t=None, return_cov=True, return_var=False):
"""
Compute the conditional predictive distribution of the model
You must call :func:`GP.compute` before this method.
Args:
y (array[n]): The observations at coordinates ``x`` from
:func:`GP.co... | Compute the conditional predictive distribution of the model
You must call :func:`GP.compute` before this method.
Args:
y (array[n]): The observations at coordinates ``x`` from
:func:`GP.compute`.
t (Optional[array[ntest]]): The independent coordinates where the... |
def from_tuple(self, t):
"""
Set this person from tuple
:param t: Tuple representing a person (sitting[, id])
:type t: (bool) | (bool, None | str | unicode | int)
:rtype: Person
"""
if len(t) > 1:
self.id = t[0]
self.sitting = t[1]
... | Set this person from tuple
:param t: Tuple representing a person (sitting[, id])
:type t: (bool) | (bool, None | str | unicode | int)
:rtype: Person |
def parse_path(path):
"""Parse a rfc 6901 path."""
if not path:
raise ValueError("Invalid path")
if isinstance(path, str):
if path == "/":
raise ValueError("Invalid path")
if path[0] != "/":
raise ValueError("Invalid path")
return path.split(_PATH_SEP)[1:]
elif isinstance(path, (tup... | Parse a rfc 6901 path. |
def repair(self, verbose=False, joincomp=False,
remove_smallest_components=True):
"""Performs mesh repair using MeshFix's default repair
process.
Parameters
----------
verbose : bool, optional
Enables or disables debug printing. Disabled by default.
... | Performs mesh repair using MeshFix's default repair
process.
Parameters
----------
verbose : bool, optional
Enables or disables debug printing. Disabled by default.
joincomp : bool, optional
Attempts to join nearby open components.
remove_small... |
def setup(cls, configuration=None, **kwargs):
# type: (Optional['Configuration'], Any) -> None
"""
Set up the HDX configuration
Args:
configuration (Optional[Configuration]): Configuration instance. Defaults to setting one up from passed arguments.
**kwargs: See ... | Set up the HDX configuration
Args:
configuration (Optional[Configuration]): Configuration instance. Defaults to setting one up from passed arguments.
**kwargs: See below
user_agent (str): User agent string. HDXPythonLibrary/X.X.X- is prefixed. Must be supplied if remoteckan ... |
def cloud_cover_to_ghi_linear(self, cloud_cover, ghi_clear, offset=35,
**kwargs):
"""
Convert cloud cover to GHI using a linear relationship.
0% cloud cover returns ghi_clear.
100% cloud cover returns offset*ghi_clear.
Parameters
-----... | Convert cloud cover to GHI using a linear relationship.
0% cloud cover returns ghi_clear.
100% cloud cover returns offset*ghi_clear.
Parameters
----------
cloud_cover: numeric
Cloud cover in %.
ghi_clear: numeric
GHI under clear sky conditions.
... |
def insert_child(self, child_pid):
"""Add the given PID to the list of children PIDs."""
self._check_child_limits(child_pid)
try:
# TODO: Here add the check for the max parents and the max children
with db.session.begin_nested():
if not isinstance(child_pi... | Add the given PID to the list of children PIDs. |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'interval') and self.interval is not None:
_dict['interval'] = self.interval
if hasattr(self, 'event_type') and self.event_type is not None:
_dict['event_type']... | Return a json dictionary representing this model. |
def create_instances(self, config_list):
"""Creates multiple virtual server instances.
This takes a list of dictionaries using the same arguments as
create_instance().
.. warning::
This will add charges to your account
Example::
# Define the instance ... | Creates multiple virtual server instances.
This takes a list of dictionaries using the same arguments as
create_instance().
.. warning::
This will add charges to your account
Example::
# Define the instance we want to create.
new_vsi = {
... |
def min(self, axis=None, skipna=True, *args, **kwargs):
"""
Return the minimum value of the Array or minimum along
an axis.
See Also
--------
numpy.ndarray.min
Index.min : Return the minimum value in an Index.
Series.min : Return the minimum value in a Se... | Return the minimum value of the Array or minimum along
an axis.
See Also
--------
numpy.ndarray.min
Index.min : Return the minimum value in an Index.
Series.min : Return the minimum value in a Series. |
def _findLocation(self, reference_name, start, end):
"""
return a location key form the locationMap
"""
try:
# TODO - sequence_annotations does not have build?
return self._locationMap['hg19'][reference_name][start][end]
except:
return None | return a location key form the locationMap |
def columnInfo(self):
"""
display metadata about the table, size, number of rows, columns and their data type
"""
code = "proc contents data=" + self.libref + '.' + self.table + ' ' + self._dsopts() + ";ods select Variables;run;"
if self.sas.nosub:
print(code)
... | display metadata about the table, size, number of rows, columns and their data type |
def GetSortedEvents(self, time_range=None):
"""Retrieves the events in increasing chronological order.
Args:
time_range (Optional[TimeRange]): time range used to filter events
that fall in a specific period.
Yield:
EventObject: event.
"""
filter_expression = None
if time_... | Retrieves the events in increasing chronological order.
Args:
time_range (Optional[TimeRange]): time range used to filter events
that fall in a specific period.
Yield:
EventObject: event. |
def empty_line_count_at_the_end(self):
"""
Return number of empty lines at the end of the document.
"""
count = 0
for line in self.lines[::-1]:
if not line or line.isspace():
count += 1
else:
break
return count | Return number of empty lines at the end of the document. |
def _add_params_docstring(params):
""" Add params to doc string
"""
p_string = "\nAccepts the following paramters: \n"
for param in params:
p_string += "name: %s, required: %s, description: %s \n" % (param['name'], param['required'], param['description'])
return p_string | Add params to doc string |
def sc_zoom_coarse(self, viewer, event, msg=True):
"""Interactively zoom the image by scrolling motion.
This zooms by adjusting the scale in x and y coarsely.
"""
if not self.canzoom:
return True
zoom_accel = self.settings.get('scroll_zoom_acceleration', 1.0)
... | Interactively zoom the image by scrolling motion.
This zooms by adjusting the scale in x and y coarsely. |
def export_configuration_generator(self, sql, sql_args):
"""
Generator for :class:`meteorpi_model.ExportConfiguration`
:param sql:
A SQL statement which must return rows describing export configurations
:param sql_args:
Any variables required to populate the quer... | Generator for :class:`meteorpi_model.ExportConfiguration`
:param sql:
A SQL statement which must return rows describing export configurations
:param sql_args:
Any variables required to populate the query provided in 'sql'
:return:
A generator which produces :... |
def _mutect2_filter(broad_runner, in_file, out_file, ref_file):
"""Filter of MuTect2 calls, a separate step in GATK4.
"""
params = ["-T", "FilterMutectCalls", "--reference", ref_file, "--variant", in_file, "--output", out_file]
return broad_runner.cl_gatk(params, os.path.dirname(out_file)) | Filter of MuTect2 calls, a separate step in GATK4. |
def decode_list_offset_response(cls, response):
"""
Decode OffsetResponse_v2 into ListOffsetResponsePayloads
Arguments:
response: OffsetResponse_v2
Returns: list of ListOffsetResponsePayloads
"""
return [
kafka.structs.ListOffsetResponsePayload(t... | Decode OffsetResponse_v2 into ListOffsetResponsePayloads
Arguments:
response: OffsetResponse_v2
Returns: list of ListOffsetResponsePayloads |
def gatk_rnaseq_calling(data):
"""Use GATK to perform gVCF variant calling on RNA-seq data
"""
from bcbio.bam import callable
data = utils.deepish_copy(data)
tools_on = dd.get_tools_on(data)
if not tools_on:
tools_on = []
tools_on.append("gvcf")
data = dd.set_tools_on(data, tools... | Use GATK to perform gVCF variant calling on RNA-seq data |
def doFindAny(self, WHAT={}, SORT=[], SKIP=None, MAX=None, LOP='AND', **params):
"""This function will perform the command -findany."""
self._preFind(WHAT, SORT, SKIP, MAX, LOP)
for key in params:
self._addDBParam(key, params[key])
return self._doAction('-findany') | This function will perform the command -findany. |
def find_by_ids(ids, _connection=None, page_size=100, page_number=0,
sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos identified by a list of Brightcove video ids
"""
if not isinstance(ids, (list, tuple)):
err = "Video.find_by_i... | List all videos identified by a list of Brightcove video ids |
def _try_switches(self, lines, index):
"""
For each switch in the Collector object, pass a list of string,
representing lines of text in a file, and an index to the current
line to try to flip the switch. A switch will only flip on if the line
passes its 'test_on' method, and wil... | For each switch in the Collector object, pass a list of string,
representing lines of text in a file, and an index to the current
line to try to flip the switch. A switch will only flip on if the line
passes its 'test_on' method, and will only flip off if the line
passes its 'test_off' m... |
def get_least_orbits(atom_index, cell, site_symmetry, symprec=1e-5):
"""Find least orbits for a centering atom"""
orbits = _get_orbits(atom_index, cell, site_symmetry, symprec)
mapping = np.arange(cell.get_number_of_atoms())
for i, orb in enumerate(orbits):
for num in np.unique(orb):
... | Find least orbits for a centering atom |
def _set_preferences(self, node):
'''
Set preferences.
:return:
'''
pref = etree.SubElement(node, 'preferences')
pacman = etree.SubElement(pref, 'packagemanager')
pacman.text = self._get_package_manager()
p_version = etree.SubElement(pref, 'version')
... | Set preferences.
:return: |
def get_tms_layers(self,
catid,
bands='4,2,1',
gamma=1.3,
highcutoff=0.98,
lowcutoff=0.02,
brightness=1.0,
contrast=1.0):
"""Get list of urls and bound... | Get list of urls and bounding boxes corrsponding to idaho images for a given catalog id.
Args:
catid (str): Catalog id
bands (str): Bands to display, separated by commas (0-7).
gamma (float): gamma coefficient. This is for on-the-fly pansharpening.
highcutoff (float)... |
def getAltitudeFromLatLon(self, lat, lon):
"""Get the altitude of a lat lon pair, using the four neighbouring
pixels for interpolation.
"""
# print "-----\nFromLatLon", lon, lat
lat -= self.lat
lon -= self.lon
# print "lon, lat", lon, lat
if lat < 0.0 ... | Get the altitude of a lat lon pair, using the four neighbouring
pixels for interpolation. |
def _process_outgoing_msg(self, sink_iter):
"""For every message we construct a corresponding RPC message to be
sent over the given socket inside given RPC session.
This function should be launched in a new green thread as
it loops forever.
"""
LOG.debug('NetworkControll... | For every message we construct a corresponding RPC message to be
sent over the given socket inside given RPC session.
This function should be launched in a new green thread as
it loops forever. |
def format_label(sl, fmt=None):
"""
Combine a list of strings to a single str, joined by sep.
Passes through single strings.
:param sl:
:return:
"""
if isinstance(sl, str):
# Already is a string.
return sl
if fmt:
return fmt.format(*sl)
return ' '.join(str(s... | Combine a list of strings to a single str, joined by sep.
Passes through single strings.
:param sl:
:return: |
def get_confidence_interval(self, node, interval = (0.05, 0.95)):
'''
If temporal reconstruction was done using the marginal ML mode, the entire distribution of
times is available. This function determines the 90% (or other) confidence interval, defined as the
range where 5% of probabili... | If temporal reconstruction was done using the marginal ML mode, the entire distribution of
times is available. This function determines the 90% (or other) confidence interval, defined as the
range where 5% of probability is below and above. Note that this does not necessarily contain
the highest... |
def store_tmp(self, tmp, content, reg_deps=None, tmp_deps=None, deps=None):
"""
Stores a Claripy expression in a VEX temp value.
If in symbolic mode, this involves adding a constraint for the tmp's symbolic variable.
:param tmp: the number of the tmp
:param content: a Claripy ex... | Stores a Claripy expression in a VEX temp value.
If in symbolic mode, this involves adding a constraint for the tmp's symbolic variable.
:param tmp: the number of the tmp
:param content: a Claripy expression of the content
:param reg_deps: the register dependencies of the content
... |
def create_group(groupname, gid, system=True):
"""
Creates a new user group with a specific id.
:param groupname: Group name.
:type groupname: unicode
:param gid: Group id.
:type gid: int or unicode
:param system: Creates a system group.
"""
sudo(addgroup(groupname, gid, system)) | Creates a new user group with a specific id.
:param groupname: Group name.
:type groupname: unicode
:param gid: Group id.
:type gid: int or unicode
:param system: Creates a system group. |
def chimera_elimination_order(m, n=None, t=None):
"""Provides a variable elimination order for a Chimera graph.
A graph defined by chimera_graph(m,n,t) has treewidth max(m,n)*t.
This function outputs a variable elimination order inducing a tree
decomposition of that width.
Parameters
---------... | Provides a variable elimination order for a Chimera graph.
A graph defined by chimera_graph(m,n,t) has treewidth max(m,n)*t.
This function outputs a variable elimination order inducing a tree
decomposition of that width.
Parameters
----------
m : int
Number of rows in the Chimera latti... |
def create_cli(create_app=None):
"""Create CLI for ``inveniomanage`` command.
:param create_app: Flask application factory.
:returns: Click command group.
.. versionadded: 1.0.0
"""
def create_cli_app(info):
"""Application factory for CLI app.
Internal function for creating th... | Create CLI for ``inveniomanage`` command.
:param create_app: Flask application factory.
:returns: Click command group.
.. versionadded: 1.0.0 |
def _startProductionCrewNode(self, name, attrs):
"""Process the start of a node under xtvd/productionCrew"""
if name == 'crew':
self._programId = attrs.get('program')
elif name == 'member':
self._role = None
self._givenname = None
self._surname = ... | Process the start of a node under xtvd/productionCrew |
def validate_jsonschema_from_file(self, json_string, path_to_schema):
"""
Validate JSON according to schema, loaded from a file.
*Args:*\n
_json_string_ - JSON string;\n
_path_to_schema_ - path to file with JSON schema;
*Raises:*\n
JsonValidatorError
*E... | Validate JSON according to schema, loaded from a file.
*Args:*\n
_json_string_ - JSON string;\n
_path_to_schema_ - path to file with JSON schema;
*Raises:*\n
JsonValidatorError
*Example:*\n
| *Settings* | *Value* |
| Library | JsonValidator |
... |
def update_target(self, name, current, total):
"""Updates progress bar for a specified target."""
self.refresh(self._bar(name, current, total)) | Updates progress bar for a specified target. |
def calc_gs_kappa(b, ne, delta, sinth, nu):
"""Calculate the gyrosynchrotron absorption coefficient κ_ν.
This is Dulk (1985) equation 36, which is a fitting function assuming a
power-law electron population. Arguments are:
b
Magnetic field strength in Gauss
ne
The density of electrons ... | Calculate the gyrosynchrotron absorption coefficient κ_ν.
This is Dulk (1985) equation 36, which is a fitting function assuming a
power-law electron population. Arguments are:
b
Magnetic field strength in Gauss
ne
The density of electrons per cubic centimeter with energies greater than 10 ... |
def __search_ca_path(self):
"""
Get CA Path to check the validity of the server host certificate on the client side
"""
if "X509_CERT_DIR" in os.environ:
self._ca_path = os.environ['X509_CERT_DIR']
elif os.path.exists('/etc/grid-security/certificates'):
s... | Get CA Path to check the validity of the server host certificate on the client side |
def apply_thresholds(input, thresholds, choices):
"""
Return one of the choices depending on the input position compared to thresholds, for each input.
>>> apply_thresholds(np.array([4]), [5, 7], [10, 15, 20])
array([10])
>>> apply_thresholds(np.array([5]), [5, 7], [10, 15, 20])
array([10])
... | Return one of the choices depending on the input position compared to thresholds, for each input.
>>> apply_thresholds(np.array([4]), [5, 7], [10, 15, 20])
array([10])
>>> apply_thresholds(np.array([5]), [5, 7], [10, 15, 20])
array([10])
>>> apply_thresholds(np.array([6]), [5, 7], [10, 15, 20])
... |
def RgbToYiq(r, g, b):
'''Convert the color from RGB to YIQ.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (y, i, q) tuple in the range:
y[0...1],
... | Convert the color from RGB to YIQ.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (y, i, q) tuple in the range:
y[0...1],
i[0...1],
q[0...1]
... |
def logprob(self, action_sample, pd_params):
""" Log-likelihood """
means = pd_params[:, :, 0]
log_std = pd_params[:, :, 1]
std = torch.exp(log_std)
z_score = (action_sample - means) / std
return - (0.5 * ((z_score**2 + self.LOG2PI).sum(dim=-1)) + log_std.sum(dim=-1)) | Log-likelihood |
def refresh_content(self, order=None, name=None):
"""
Re-download all submissions and reset the page index
"""
order = order or self.content.order
# Preserve the query if staying on the current page
if name is None:
query = self.content.query
else:
... | Re-download all submissions and reset the page index |
def exec_context(self, **kwargs):
"""Base environment for evals, the stuff that is the same for all evals. Primarily used in the
Caster pipe"""
import inspect
import dateutil.parser
import datetime
import random
from functools import partial
from ambry.val... | Base environment for evals, the stuff that is the same for all evals. Primarily used in the
Caster pipe |
def genslices_ndim(ndim, shape):
"""Generate all possible slice tuples for 'shape'."""
iterables = [genslices(shape[n]) for n in range(ndim)]
yield from product(*iterables) | Generate all possible slice tuples for 'shape'. |
def _update_dates(self, **update_props):
"""
Update operation for ArcGIS Dates metadata
:see: gis_metadata.utils._complex_definitions[DATES]
"""
tree_to_update = update_props['tree_to_update']
xpath_root = self._data_map['_dates_root']
if self.dates:
... | Update operation for ArcGIS Dates metadata
:see: gis_metadata.utils._complex_definitions[DATES] |
def start_update(self, draw=None, queues=None):
"""
Conduct the formerly registered updates
This method conducts the updates that have been registered via the
:meth:`update` method. You can call this method if the
:attr:`auto_update` attribute of this instance is True and the
... | Conduct the formerly registered updates
This method conducts the updates that have been registered via the
:meth:`update` method. You can call this method if the
:attr:`auto_update` attribute of this instance is True and the
`auto_update` parameter in the :meth:`update` method has been ... |
def calculate_subgraph_edge_overlap(
graph: BELGraph,
annotation: str = 'Subgraph'
) -> Tuple[
Mapping[str, EdgeSet],
Mapping[str, Mapping[str, EdgeSet]],
Mapping[str, Mapping[str, EdgeSet]],
Mapping[str, Mapping[str, float]],
]:
"""Build a DatafFame to show the overlap between diffe... | Build a DatafFame to show the overlap between different sub-graphs.
Options:
1. Total number of edges overlap (intersection)
2. Percentage overlap (tanimoto similarity)
:param graph: A BEL graph
:param annotation: The annotation to group by and compare. Defaults to 'Subgraph'
:return: {subgrap... |
def prox_gradf_lim(xy, step, boundary=None):
"""Forward-backward step: gradient, followed by projection"""
return prox_lim(prox_gradf(xy,step), step, boundary=boundary) | Forward-backward step: gradient, followed by projection |
def signature(self, name=None):
"""Return our function signature as a string.
By default this function uses the annotated name of the function
however if you need to override that with a custom name you can
pass name=<custom name>
Args:
name (str): Optional name to ... | Return our function signature as a string.
By default this function uses the annotated name of the function
however if you need to override that with a custom name you can
pass name=<custom name>
Args:
name (str): Optional name to override the default name given
... |
def getstate(self):
"""
Returns QUEUED, -1
INITIALIZING, -1
RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255
"""
# the jobstore never existed
if not os.path.exists(self.jobst... | Returns QUEUED, -1
INITIALIZING, -1
RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255 |
def list_objects(self, path='', relative=False, first_level=False,
max_request_entries=None):
"""
List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only fi... | List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only first level objects.
Else, returns full tree.
max_request_entries (int): If specified, maximum entries return... |
def prepare_cookies(self, cookies):
"""Prepares the given HTTP cookie data.
This function eventually generates a ``Cookie`` header from the
given cookies using cookielib. Due to cookielib's design, the header
will not be regenerated if it already exists, meaning this function
ca... | Prepares the given HTTP cookie data.
This function eventually generates a ``Cookie`` header from the
given cookies using cookielib. Due to cookielib's design, the header
will not be regenerated if it already exists, meaning this function
can only be called once for the life of the
... |
def combine_sj_out(
fns,
external_db,
total_jxn_cov_cutoff=20,
define_sample_name=None,
verbose=False,
):
"""Combine SJ.out.tab files from STAR by filtering based on coverage and
comparing to an external annotation to discover novel junctions.
Parameters
----------
fns : list... | Combine SJ.out.tab files from STAR by filtering based on coverage and
comparing to an external annotation to discover novel junctions.
Parameters
----------
fns : list of strings
Filenames of SJ.out.tab files to combine.
external_db : str
Filename of splice junction information fr... |
def delete_branch(self, project, repository, name, end_point):
"""
Delete branch from related repo
:param self:
:param project:
:param repository:
:param name:
:param end_point:
:return:
"""
url = 'rest/branch-utils/1.0/projects/{project}/... | Delete branch from related repo
:param self:
:param project:
:param repository:
:param name:
:param end_point:
:return: |
def rerun(version="3.7.0"):
"""
Rerun last example code block with specified version of python.
"""
from commandlib import Command
Command(DIR.gen.joinpath("py{0}".format(version), "bin", "python"))(
DIR.gen.joinpath("state", "examplepythoncode.py")
).in_dir(DIR.gen.joinpath("state")).r... | Rerun last example code block with specified version of python. |
def config_default(dest):
""" Create a default configuration file.
\b
DEST: Path or file name for the configuration file.
"""
conf_path = Path(dest).resolve()
if conf_path.is_dir():
conf_path = conf_path / LIGHTFLOW_CONFIG_NAME
conf_path.write_text(Config.default())
click.echo(... | Create a default configuration file.
\b
DEST: Path or file name for the configuration file. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.