code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def add_unknown_members(self, members):
"""Add a new member to the unknown members list
:param member: member name
:type member: str
:return: None
"""
if not isinstance(members, list):
members = [members]
if not hasattr(self, 'unknown_members'):
... | Add a new member to the unknown members list
:param member: member name
:type member: str
:return: None |
def DownloadPqlResultToList(self, pql_query, values=None):
"""Downloads the results of a PQL query to a list.
Args:
pql_query: str a statement filter to apply (the query should not include
the limit or the offset)
[optional]
values: A dict of python objects or a list of raw S... | Downloads the results of a PQL query to a list.
Args:
pql_query: str a statement filter to apply (the query should not include
the limit or the offset)
[optional]
values: A dict of python objects or a list of raw SOAP values to bind
to the pql_query.
Returns:
... |
def extract_build(self, path='.', tests=None, full_symbols=False):
"""
Download and extract the build and requested extra artifacts
@type path:
@param path:
@type tests:
@param tests:
@type full_symbols:
@param full_symbols:
"""
if self.... | Download and extract the build and requested extra artifacts
@type path:
@param path:
@type tests:
@param tests:
@type full_symbols:
@param full_symbols: |
def write_nochr_reads(in_file, out_file, config):
"""Write a BAM file of reads that are not mapped on a reference chromosome.
This is useful for maintaining non-mapped reads in parallel processes
that split processing by chromosome.
"""
if not file_exists(out_file):
with file_transaction(co... | Write a BAM file of reads that are not mapped on a reference chromosome.
This is useful for maintaining non-mapped reads in parallel processes
that split processing by chromosome. |
def rsa_eq(key1, key2):
"""
Only works for RSAPublic Keys
:param key1:
:param key2:
:return:
"""
pn1 = key1.public_numbers()
pn2 = key2.public_numbers()
# Check if two RSA keys are in fact the same
if pn1 == pn2:
return True
else:
return False | Only works for RSAPublic Keys
:param key1:
:param key2:
:return: |
def process_summary(summaryfile, **kwargs):
"""Extracting information from an albacore summary file.
Only reads which have a >0 length are returned.
The fields below may or may not exist, depending on the type of sequencing performed.
Fields 1-14 are for 1D sequencing.
Fields 1-23 for 2D sequencin... | Extracting information from an albacore summary file.
Only reads which have a >0 length are returned.
The fields below may or may not exist, depending on the type of sequencing performed.
Fields 1-14 are for 1D sequencing.
Fields 1-23 for 2D sequencing.
Fields 24-27, 2-5, 22-23 for 1D^2 (1D2) sequ... |
def route_filter_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific route filter.
:param name: The name of the route table to query.
:param resource_group: The resource group name assigned to the
route filter.
CLI Example:
.. code-bl... | .. versionadded:: 2019.2.0
Get details about a specific route filter.
:param name: The name of the route table to query.
:param resource_group: The resource group name assigned to the
route filter.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.route_filter_get te... |
def descendants(self, line_data):
"""
BFS graph algorithm
:param line_data: line_data(dict) with line_data['line_index'] or line_index(int)
:return: list of line_data(dict)
"""
# get start node
try:
start = line_data['line_index']
except TypeEr... | BFS graph algorithm
:param line_data: line_data(dict) with line_data['line_index'] or line_index(int)
:return: list of line_data(dict) |
def set_video_pos(self, x1, y1, x2, y2):
"""
Set the video position on the screen
Args:
x1 (int): Top left x coordinate (px)
y1 (int): Top left y coordinate (px)
x2 (int): Bottom right x coordinate (px)
y2 (int): Bottom right y coordinate (px)
... | Set the video position on the screen
Args:
x1 (int): Top left x coordinate (px)
y1 (int): Top left y coordinate (px)
x2 (int): Bottom right x coordinate (px)
y2 (int): Bottom right y coordinate (px) |
def ApproximateDistance(degree_lat1, degree_lng1, degree_lat2, degree_lng2):
"""Compute approximate distance between two points in meters. Assumes the
Earth is a sphere."""
# TODO: change to ellipsoid approximation, such as
# http://www.codeguru.com/Cpp/Cpp/algorithms/article.php/c5115/
lat1 = math.radians(de... | Compute approximate distance between two points in meters. Assumes the
Earth is a sphere. |
def fetchable_partitions(self):
"""Return set of TopicPartitions that should be Fetched."""
fetchable = set()
for partition, state in six.iteritems(self.assignment):
if state.is_fetchable():
fetchable.add(partition)
return fetchable | Return set of TopicPartitions that should be Fetched. |
def query_file(self, file_sha, verbose=False):
"""Query the VirusTotal Service
Args:
file_sha (str): The file sha1 or sha256 hash
url (str): The domain/url to be queried (default=None)
"""
# Sanity check sha hash input
if len(file_sha) not in [6... | Query the VirusTotal Service
Args:
file_sha (str): The file sha1 or sha256 hash
url (str): The domain/url to be queried (default=None) |
def add_descendants(self, node, updateset=None):
"auxiliary function: add all descendants of node to someset"
someset = set()
startnode = self.tab[node]
defout = startnode.default[0]
if defout is not None:
someset.add(defout)
for kwd, matchnode in startnode.n... | auxiliary function: add all descendants of node to someset |
def write_files(template, destination='./dxf'):
"""
For a dict, write each value to destination/key
"""
os.makedirs(destination)
for key, value in template.items():
with open(os.path.join(destination, key), 'w') as f:
f.write(replace_whitespace(value, insert=False)) | For a dict, write each value to destination/key |
def _create_batch_runner_action(self):
"""Create action for batch runner dialog."""
icon = resources_path('img', 'icons', 'show-batch-runner.svg')
self.action_batch_runner = QAction(
QIcon(icon),
self.tr('Batch Runner'), self.iface.mainWindow())
self.action_batch_... | Create action for batch runner dialog. |
def _cfg_exists(self, cfg_str):
"""Check a partial config string exists in the running config.
:param cfg_str: config string to check
:return : True or False
"""
ios_cfg = self._get_running_config()
parse = HTParser(ios_cfg)
cfg_raw = parse.find_lines("^" + cfg_s... | Check a partial config string exists in the running config.
:param cfg_str: config string to check
:return : True or False |
def _get_case_file_paths(tmp_dir, case, training_fraction=0.95):
"""Obtain a list of image paths corresponding to training or eval case.
Args:
tmp_dir: str, the root path to which raw images were written, at the
top level having meta/ and raw/ subdirs.
case: bool, whether obtaining file paths for tra... | Obtain a list of image paths corresponding to training or eval case.
Args:
tmp_dir: str, the root path to which raw images were written, at the
top level having meta/ and raw/ subdirs.
case: bool, whether obtaining file paths for training (true) or eval
(false).
training_fraction: float, the ... |
def set_servers(self, node_couplets):
"""Set the current collection of servers. The entries are 2-tuples of
contexts and nodes.
"""
node_couplets_s = set(node_couplets)
if node_couplets_s != self.__node_couplets_s:
_logger.info("Servers have changed. NEW: %s REMOVE... | Set the current collection of servers. The entries are 2-tuples of
contexts and nodes. |
def run(self):
"""Run the App main logic.
This method should contain the core logic of the App.
"""
# read inputs
indent = int(self.tcex.playbook.read(self.args.indent))
json_data = self.tcex.playbook.read(self.args.json_data)
# get the playbook variable type
... | Run the App main logic.
This method should contain the core logic of the App. |
def _map_val2color(val, vmin, vmax, colorscale=None):
""" Maps a value val in [vmin, vmax] to the corresponding color in
the colorscale
returns the rgb color code of that color
"""
colorscale = colorscale or colorscale_default
if vmin >= vmax:
raise ValueError("vmin should be < ... | Maps a value val in [vmin, vmax] to the corresponding color in
the colorscale
returns the rgb color code of that color |
def _wrap_field(field):
"""Improve Flask-RESTFul's original field type"""
class WrappedField(field):
def output(self, key, obj):
value = _fields.get_value(key if self.attribute is None else self.attribute, obj)
# For all fields, when its value was null (None), return null direct... | Improve Flask-RESTFul's original field type |
def clean_old_jobs():
'''
Clean out minions's return data for old jobs.
Normally, hset 'ret:<jid>' are saved with a TTL, and will eventually
get cleaned by redis.But for jobs with some very late minion return, the
corresponding hset's TTL will be refreshed to a too late timestamp, we'll
do manu... | Clean out minions's return data for old jobs.
Normally, hset 'ret:<jid>' are saved with a TTL, and will eventually
get cleaned by redis.But for jobs with some very late minion return, the
corresponding hset's TTL will be refreshed to a too late timestamp, we'll
do manually cleaning here. |
def __multiscale_gc_hi2lo_run(self): # , pyed):
"""
Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph.
In first step is performed normal GC on low resolution data
Second step construct finer grid on edges of segmentation from first
step.
The... | Run Graph-Cut segmentation with simplifiyng of high resolution multiscale graph.
In first step is performed normal GC on low resolution data
Second step construct finer grid on edges of segmentation from first
step.
There is no option for use without `use_boundary_penalties` |
def aug_sysargv(cmdstr):
""" DEBUG FUNC modify argv to look like you ran a command """
import shlex
argv = shlex.split(cmdstr)
sys.argv.extend(argv) | DEBUG FUNC modify argv to look like you ran a command |
def get_event_triggers(self):
"""
Returns dict of supported events.
Key = Event Type
List = Channels that have that event activated
"""
events = {}
nvrflag = False
event_xml = []
url = '%s/ISAPI/Event/triggers' % self.root_url
try:
... | Returns dict of supported events.
Key = Event Type
List = Channels that have that event activated |
def Delete(self):
"""Delete server.
https://t3n.zendesk.com/entries/59220824-Delete-Server
>>> clc.v2.Server("WA1BTDIAPI219").Delete().WaitUntilComplete()
0
"""
return(clc.v2.Requests(clc.v2.API.Call('DELETE','servers/%s/%s' % (self.alias,self.id),session=self.session),alias=self.alias,session=self.sessi... | Delete server.
https://t3n.zendesk.com/entries/59220824-Delete-Server
>>> clc.v2.Server("WA1BTDIAPI219").Delete().WaitUntilComplete()
0 |
def update_travis_deploy_password(encrypted_password):
"""Update the deploy section of the .travis.yml file
to use the given encrypted password.
"""
config = load_yaml_config(TRAVIS_CONFIG_FILE)
config["deploy"]["password"] = dict(secure=encrypted_password)
save_yaml_config(TRAVIS_CONFIG_FILE,... | Update the deploy section of the .travis.yml file
to use the given encrypted password. |
def vpn_gateways(self):
"""Instance depends on the API version:
* 2018-04-01: :class:`VpnGatewaysOperations<azure.mgmt.network.v2018_04_01.operations.VpnGatewaysOperations>`
"""
api_version = self._get_api_version('vpn_gateways')
if api_version == '2018-04-01':
fr... | Instance depends on the API version:
* 2018-04-01: :class:`VpnGatewaysOperations<azure.mgmt.network.v2018_04_01.operations.VpnGatewaysOperations>` |
def start_poll(args):
"""Starts a poll."""
if args.type == 'privmsg':
return "We don't have secret ballots in this benevolent dictatorship!"
if not args.msg:
return "Polls need a question."
ctrlchan = args.config['core']['ctrlchan']
poll = Polls(question=args.msg, submitter=args.nick... | Starts a poll. |
def construct_formset(self):
"""
Overrides construct_formset to attach the model class as
an attribute of the returned formset instance.
"""
formset = super(InlineFormSetFactory, self).construct_formset()
formset.model = self.inline_model
return formset | Overrides construct_formset to attach the model class as
an attribute of the returned formset instance. |
def _expand_group_by_fields(cls, model, fields):
"""
Expand FK fields into all related object's fields to avoid future
lookups.
:param fields: fields to "group by"
:return: expanded fields
"""
# Containers for resulting fields and related model fields
res... | Expand FK fields into all related object's fields to avoid future
lookups.
:param fields: fields to "group by"
:return: expanded fields |
def calculate_similar_artists(output_filename, model_name="als"):
""" generates a list of similar artists in lastfm by utiliizing the 'similar_items'
api of the models """
artists, users, plays = get_lastfm()
# create a model from the input data
model = get_model(model_name)
# if we're trainin... | generates a list of similar artists in lastfm by utiliizing the 'similar_items'
api of the models |
def fail(p_queue, host=None):
if host is not None:
return _path(_c.FSQ_FAIL, root=_path(host, root=hosts(p_queue)))
'''Construct a path to the fail dir for a queue'''
return _path(p_queue, _c.FSQ_FAIL) | Construct a path to the fail dir for a queue |
def _find_navigation_coefs(self):
"""Find navigation coefficients for the current time
The navigation Chebyshev coefficients are only valid for a certain time interval. The header entry
SatelliteStatus/Orbit/OrbitPolynomial contains multiple coefficients for multiple time intervals. Find the
... | Find navigation coefficients for the current time
The navigation Chebyshev coefficients are only valid for a certain time interval. The header entry
SatelliteStatus/Orbit/OrbitPolynomial contains multiple coefficients for multiple time intervals. Find the
coefficients which are valid for the no... |
def _wrapped_unsigned_mul(a, b):
"""
Perform wrapped unsigned multiplication on two StridedIntervals.
:param a: The first operand (StridedInterval)
:param b: The second operand (StridedInterval)
:return: The multiplication result
"""
if a.bits != b.bits:
... | Perform wrapped unsigned multiplication on two StridedIntervals.
:param a: The first operand (StridedInterval)
:param b: The second operand (StridedInterval)
:return: The multiplication result |
def axes_grid(n, sharex=False, sharey=False, subplot_kw=None, **fig_kw):
'''Finds a reasonable arrangement of n axes. Returns (fig, axes) tuple.
For keyword arguments descriptions, see matplotlib.pyplot.subplots'''
r = np.floor(np.sqrt(n))
r, c = int(r), int(np.ceil(n / r))
fig, axes = plt.subplots(nrows=r, n... | Finds a reasonable arrangement of n axes. Returns (fig, axes) tuple.
For keyword arguments descriptions, see matplotlib.pyplot.subplots |
def _validate_filter_fields(self, filter_by):
"""
:param filter_by: dict
:raises: pybomb.exceptions.InvalidFilterFieldException
"""
for filter_field in filter_by:
if (
filter_field not in self.RESPONSE_FIELD_MAP
or not self.RESPONSE_FIE... | :param filter_by: dict
:raises: pybomb.exceptions.InvalidFilterFieldException |
def _use_memcache(self, key, options=None):
"""Return whether to use memcache for this key.
Args:
key: Key instance.
options: ContextOptions instance, or None.
Returns:
True if the key should be cached in memcache, False otherwise.
"""
flag = ContextOptions.use_memcache(options)
... | Return whether to use memcache for this key.
Args:
key: Key instance.
options: ContextOptions instance, or None.
Returns:
True if the key should be cached in memcache, False otherwise. |
def ln_norm(x, mu, sigma=1.0):
""" Natural log of scipy norm function truncated at zero """
return np.log(stats.norm(loc=mu, scale=sigma).pdf(x)) | Natural log of scipy norm function truncated at zero |
def friction_plate_Martin_1999(Re, plate_enlargement_factor):
r'''Calculates Darcy friction factor for single-phase flow in a
Chevron-style plate heat exchanger according to [1]_.
.. math::
\frac{1}{\sqrt{f_f}} = \frac{\cos \phi}{\sqrt{0.045\tan\phi
+ 0.09\sin\phi + f_0/\cos(\phi)}} +... | r'''Calculates Darcy friction factor for single-phase flow in a
Chevron-style plate heat exchanger according to [1]_.
.. math::
\frac{1}{\sqrt{f_f}} = \frac{\cos \phi}{\sqrt{0.045\tan\phi
+ 0.09\sin\phi + f_0/\cos(\phi)}} + \frac{1-\cos\phi}{\sqrt{3.8f_1}}
.. math::
f... |
def _find_primary_without_dot_start(self, offset):
"""It tries to find the undotted primary start
It is different from `self._get_atom_start()` in that it
follows function calls, too; such as in ``f(x)``.
"""
last_atom = offset
offset = self._find_last_non_space_char(la... | It tries to find the undotted primary start
It is different from `self._get_atom_start()` in that it
follows function calls, too; such as in ``f(x)``. |
def _getStateAnomalyVector(self, state):
"""
Returns a state's anomaly vertor converting it from spare to dense
"""
vector = numpy.zeros(self._anomalyVectorLength)
vector[state.anomalyVector] = 1
return vector | Returns a state's anomaly vertor converting it from spare to dense |
def prepare_fields(fields):
"""Возвращает новый словарь с данными, подготовленными
для сериализации в JSON.
"""
def process_item(value):
if not isinstance(value, NUMERIC_TYPES):
if isinstance(value, six.string_types):
# encode utf-8 to unicode, if necessary
... | Возвращает новый словарь с данными, подготовленными
для сериализации в JSON. |
def stop(self):
"""
Stop the monitoring thread of the plugin.
The super-class will send the stop signal on the monitor-IP queue,
which prompts the loop to stop.
"""
super(Multi, self).stop()
self.monitor_thread.join()
logging.info("Multi-plugin health m... | Stop the monitoring thread of the plugin.
The super-class will send the stop signal on the monitor-IP queue,
which prompts the loop to stop. |
def description(self) -> str:
'''Test name in nose output (intended to be overridden).'''
return '{0.uuid.hex}—{1}'.format(self, self.context.module) | Test name in nose output (intended to be overridden). |
def find_motif34(m, n=None):
'''
This function returns all motif isomorphs for a given motif id and
class (3 or 4). The function also returns the motif id for a given
motif matrix
1. Input: Motif_id, e.g. 1 to 13, if class is 3
Motif_class, number of nodes, 3... | This function returns all motif isomorphs for a given motif id and
class (3 or 4). The function also returns the motif id for a given
motif matrix
1. Input: Motif_id, e.g. 1 to 13, if class is 3
Motif_class, number of nodes, 3 or 4.
Output: Motif_matrices, ... |
def delete_namespaced_pod_template(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_pod_template # noqa: E501
delete a PodTemplate # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True... | delete_namespaced_pod_template # noqa: E501
delete a PodTemplate # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_pod_template(name, namespace, async_req=True)
... |
def ns(symbol):
'''generates a namespace x::y::z statement from a symbol'''
if symbol.type and symbol.type.is_primitive:
return ''
return '{0}::'.format('::'.join(symbol.module.name_parts)) | generates a namespace x::y::z statement from a symbol |
def _list_images(self, root):
"""
Description : generate list for lip images
"""
self.labels = []
self.items = []
valid_unseen_sub_idx = [1, 2, 20, 22]
skip_sub_idx = [21]
if self._mode == 'train':
sub_idx = ['s' + str(i) for i in range(1, 35... | Description : generate list for lip images |
def task_postponed(self):
""" Track (if required) postponing event and do the same job as :meth:`.WScheduleRecord.task_postponed`
method do
:return: None
"""
tracker = self.task().tracker_storage()
if tracker is not None and self.track_wait() is True:
details = self.task().event_details(WTrackerEvents.w... | Track (if required) postponing event and do the same job as :meth:`.WScheduleRecord.task_postponed`
method do
:return: None |
def clone(self, **kwargs):
"""Create a modified version of |ASN.1| schema object.
The `clone()` method accepts the same set arguments as |ASN.1|
class takes on instantiation except that all arguments
of the `clone()` method are optional.
Whatever arguments are supplied, they ar... | Create a modified version of |ASN.1| schema object.
The `clone()` method accepts the same set arguments as |ASN.1|
class takes on instantiation except that all arguments
of the `clone()` method are optional.
Whatever arguments are supplied, they are used to create a copy
of `se... |
def gen_weights(self, f_target):
"""Generate a set of weights over the basis functions such
that the target forcing term trajectory is matched.
f_target np.array: the desired forcing term trajectory
"""
# calculate x and psi
x_track = self.cs.rollout()
... | Generate a set of weights over the basis functions such
that the target forcing term trajectory is matched.
f_target np.array: the desired forcing term trajectory |
def register_axis(key=None):
"""Returns a decorator registering an axis class in the axis type registry.
If no key is provided, the class name is used as a key. A key is provided
for each core bqplot axis so that the frontend can use this key regardless
of the kernel language.
"""
def wrap(axis... | Returns a decorator registering an axis class in the axis type registry.
If no key is provided, the class name is used as a key. A key is provided
for each core bqplot axis so that the frontend can use this key regardless
of the kernel language. |
def threshold(self, front_thresh=0.0, rear_thresh=100.0):
"""Creates a new DepthImage by setting all depths less than
front_thresh and greater than rear_thresh to 0.
Parameters
----------
front_thresh : float
The lower-bound threshold.
rear_thresh : float
... | Creates a new DepthImage by setting all depths less than
front_thresh and greater than rear_thresh to 0.
Parameters
----------
front_thresh : float
The lower-bound threshold.
rear_thresh : float
The upper bound threshold.
Returns
-------... |
def fit(self, X, y=None):
"""
The fit method is the primary drawing input for the frequency
distribution visualization. It requires vectorized lists of
documents and a list of features, which are the actual words
from the original corpus (needed to label the x-axis ticks).
... | The fit method is the primary drawing input for the frequency
distribution visualization. It requires vectorized lists of
documents and a list of features, which are the actual words
from the original corpus (needed to label the x-axis ticks).
Parameters
----------
X : n... |
def _bottom_position(self, resource):
"""
Place watermark to bottom position
:param resource: Image.Image
:return: Image.Image
"""
image = self._get_scaled_image(resource)
left = int(round(resource.size[0] // 2 - image.size[0] // 2))
upper = int(round(res... | Place watermark to bottom position
:param resource: Image.Image
:return: Image.Image |
def cal_p(self, v, temp):
"""
calculate total pressure at given volume and temperature
:param v: unit-cell volume in A^3
:param temp: temperature in K
:return: pressure in GPa
:note: 2017/05/10 temp must be numpy array. If not, such as list,
create an error.... | calculate total pressure at given volume and temperature
:param v: unit-cell volume in A^3
:param temp: temperature in K
:return: pressure in GPa
:note: 2017/05/10 temp must be numpy array. If not, such as list,
create an error. |
def init_csv(movies_data, csv_file_path, delimiter):
"""Initialize csv movies database.
:param movies_data: Data about movies
:type movies_data: tuple[tuple]
:param csv_file_path: Path to csv file with movies data
:type csv_file_path: str
:param delimiter: Csv file's delimiter
:type delim... | Initialize csv movies database.
:param movies_data: Data about movies
:type movies_data: tuple[tuple]
:param csv_file_path: Path to csv file with movies data
:type csv_file_path: str
:param delimiter: Csv file's delimiter
:type delimiter: str |
def optimize(self, graph):
"""
Build a dictionary mapping each pair of nodes to a number (the distance between them).
@type graph: graph
@param graph: Graph.
"""
for center in self.centers:
shortest_routes = shortest_path(graph, center)[1]
... | Build a dictionary mapping each pair of nodes to a number (the distance between them).
@type graph: graph
@param graph: Graph. |
def set_default_option(cls, key, value):
"""Class method. Set the default value of the option `key` (string)
to `value` for all future instances of the class.
Note that this does not affect existing instances or the instance
called from."""
cls._default_options.update(cls._optio... | Class method. Set the default value of the option `key` (string)
to `value` for all future instances of the class.
Note that this does not affect existing instances or the instance
called from. |
def run_backup(self):
"""The actual backup is performed. The data for all added classes is
extracted and written to a file per class where each line (terminated
by a line feed character) is the JSON representing a single object.
Those files are all archived in a single gzip'ed tarball wh... | The actual backup is performed. The data for all added classes is
extracted and written to a file per class where each line (terminated
by a line feed character) is the JSON representing a single object.
Those files are all archived in a single gzip'ed tarball which is
stored in the AWS ... |
def _connect_mitogen_su(spec):
"""
Return ContextService arguments for su as a first class connection.
"""
return {
'method': 'su',
'kwargs': {
'username': spec.remote_user(),
'password': spec.password(),
'python_path': spec.python_path(),
... | Return ContextService arguments for su as a first class connection. |
def match_url(self, path, method='GET'):
""" Find a callback bound to a path and a specific HTTP method.
Return (callback, param) tuple or (None, {}).
method: HEAD falls back to GET. HEAD and GET fall back to ALL.
"""
path = path.strip().lstrip('/')
handler, param... | Find a callback bound to a path and a specific HTTP method.
Return (callback, param) tuple or (None, {}).
method: HEAD falls back to GET. HEAD and GET fall back to ALL. |
def set_polygon_offset(self, factor=0., units=0.):
"""Set the scale and units used to calculate depth values
Parameters
----------
factor : float
Scale factor used to create a variable depth offset for
each polygon.
units : float
Multiplie... | Set the scale and units used to calculate depth values
Parameters
----------
factor : float
Scale factor used to create a variable depth offset for
each polygon.
units : float
Multiplied by an implementation-specific value to create a
... |
def previous_visit(self):
"""Returns the previous visit for this request or None.
Requires attr `visit_model_cls`.
"""
previous_visit = None
if self.appointment:
appointment = self.appointment
while appointment.previous_by_timepoint:
try:
... | Returns the previous visit for this request or None.
Requires attr `visit_model_cls`. |
async def delete(self):
"""
Delete this message
:return: bool
"""
return await self.bot.delete_message(self.chat.id, self.message_id) | Delete this message
:return: bool |
def time_correlation_direct_by_mtx_vec_prod(P, mu, obs1, obs2=None, time=1, start_values=None, return_P_k_obs=False):
r"""Compute time-correlation of obs1, or time-cross-correlation with obs2.
The time-correlation at time=k is computed by the matrix-vector expression:
cor(k) = obs1' diag(pi) P^k obs2
... | r"""Compute time-correlation of obs1, or time-cross-correlation with obs2.
The time-correlation at time=k is computed by the matrix-vector expression:
cor(k) = obs1' diag(pi) P^k obs2
Parameters
----------
P : ndarray, shape=(n, n) or scipy.sparse matrix
Transition matrix
obs1 : ndarr... |
def max(self):
"""
Compute the max across records.
"""
return self._constructor(self.values.max(axis=self.baseaxes, keepdims=True)) | Compute the max across records. |
def reg_score_function(X, y, mean, scale, shape, skewness):
""" GAS Poisson Regression Update term using gradient only - native Python function
Parameters
----------
X : float
datapoint for the right hand side variable
y : float
datapoint for the tim... | GAS Poisson Regression Update term using gradient only - native Python function
Parameters
----------
X : float
datapoint for the right hand side variable
y : float
datapoint for the time series
mean : float
location parameter for the Po... |
def read_array(self, dtype, count=-1, out=None):
"""Return numpy array from file in native byte order."""
fh = self._fh
dtype = numpy.dtype(dtype)
if count < 0:
size = self._size if out is None else out.nbytes
count = size // dtype.itemsize
else:
... | Return numpy array from file in native byte order. |
def genCompleteTypes( compoundSig ):
"""
Generator function used to iterate over each complete,
top-level type contained in in a signature. Ex::
"iii" => [ 'i', 'i', 'i' ]
"i(ii)i" => [ 'i', '(ii)', 'i' ]
"i(i(ii))i" => [ 'i', '(i(ii))', 'i' ]
"""
i = 0
s... | Generator function used to iterate over each complete,
top-level type contained in in a signature. Ex::
"iii" => [ 'i', 'i', 'i' ]
"i(ii)i" => [ 'i', '(ii)', 'i' ]
"i(i(ii))i" => [ 'i', '(i(ii))', 'i' ] |
async def delete(self, *, reason=None):
"""|coro|
Deletes the channel.
You must have :attr:`~.Permissions.manage_channels` permission to use this.
Parameters
-----------
reason: Optional[:class:`str`]
The reason for deleting this channel.
Shows ... | |coro|
Deletes the channel.
You must have :attr:`~.Permissions.manage_channels` permission to use this.
Parameters
-----------
reason: Optional[:class:`str`]
The reason for deleting this channel.
Shows up on the audit log.
Raises
------... |
def apply(self, doc, split, train, **kwargs):
"""Extract candidates from the given Context.
:param doc: A document to process.
:param split: Which split to use.
:param train: Whether or not to insert new FeatureKeys.
"""
logger.debug(f"Document: {doc}")
# Get al... | Extract candidates from the given Context.
:param doc: A document to process.
:param split: Which split to use.
:param train: Whether or not to insert new FeatureKeys. |
def saveProfile( self ):
"""
Saves the current profile to the current settings from the view widget.
"""
manager = self.parent()
prof = manager.currentProfile()
# save the current profile
save_prof = manager.viewWidget().saveProfile()
prof.setX... | Saves the current profile to the current settings from the view widget. |
def check_query_data(self, query_data):
"""
All items in a `querylist` must at least have `queryset` key and a
`serializer_class` key. Any querylist item lacking both those keys
will raise a ValidationError
"""
for key in self.required_keys:
if key not in quer... | All items in a `querylist` must at least have `queryset` key and a
`serializer_class` key. Any querylist item lacking both those keys
will raise a ValidationError |
def sort_elements_by_child_values(obj_pyxb, child_name_list):
"""In-place sort simple or complex elements in a PyXB object by values they contain
in child elements.
Args:
obj_pyxb: PyXB object
child_name_list: list of str
List of element names that are direct children of the PyXB objec... | In-place sort simple or complex elements in a PyXB object by values they contain
in child elements.
Args:
obj_pyxb: PyXB object
child_name_list: list of str
List of element names that are direct children of the PyXB object. |
def write_report(storage_dic, output_file, sample_id):
""" Writes a report from multiple samples.
Parameters
----------
storage_dic : dict or :py:class:`OrderedDict`
Storage containing the trimming statistics. See :py:func:`parse_log`
for its generation.
output_file : str
Pa... | Writes a report from multiple samples.
Parameters
----------
storage_dic : dict or :py:class:`OrderedDict`
Storage containing the trimming statistics. See :py:func:`parse_log`
for its generation.
output_file : str
Path where the output file will be generated.
sample_id : str... |
def kepler_lcdict_to_pkl(lcdict, outfile=None):
'''This writes the `lcdict` to a Python pickle.
Parameters
----------
lcdict : lcdict
This is the input `lcdict` to write to a pickle.
outfile : str or None
If this is None, the object's Kepler ID/EPIC ID will determined from the
... | This writes the `lcdict` to a Python pickle.
Parameters
----------
lcdict : lcdict
This is the input `lcdict` to write to a pickle.
outfile : str or None
If this is None, the object's Kepler ID/EPIC ID will determined from the
`lcdict` and used to form the filename of the outp... |
def _extract_delta(expr, idx):
"""Extract a "simple" Kronecker delta containing `idx` from `expr`.
Assuming `expr` can be written as the product of a Kronecker Delta and a
`new_expr`, return a tuple of the sympy.KroneckerDelta instance and
`new_expr`. Otherwise, return a tuple of None and the original ... | Extract a "simple" Kronecker delta containing `idx` from `expr`.
Assuming `expr` can be written as the product of a Kronecker Delta and a
`new_expr`, return a tuple of the sympy.KroneckerDelta instance and
`new_expr`. Otherwise, return a tuple of None and the original `expr`
(possibly converted to a :c... |
def upload_from_filename(
self, filename, content_type=None, client=None, predefined_acl=None
):
"""Upload this blob's contents from the content of a named file.
The content type of the upload will be determined in order
of precedence:
- The value passed in to this method (... | Upload this blob's contents from the content of a named file.
The content type of the upload will be determined in order
of precedence:
- The value passed in to this method (if not :data:`None`)
- The value stored on the current blob
- The value given by ``mimetypes.guess_type`... |
def plot_density(population, # pylint: disable=too-many-arguments, too-many-locals
bins=100, new_fig=True, subplot=111, levels=None, plane='xy',
colorlabel='Nodes per unit area', labelfontsize=16,
color_map='Reds', no_colorbar=False, threshold=0.01,
n... | Plots the 2d histogram of the center
coordinates of segments in the selected plane. |
def get_logical_plan(cluster, environ, topology, role=None):
'''
Get the logical plan state of a topology in a cluster
:param cluster:
:param environ:
:param topology:
:param role:
:return:
'''
params = dict(cluster=cluster, environ=environ, topology=topology)
if role is not None:
params['role']... | Get the logical plan state of a topology in a cluster
:param cluster:
:param environ:
:param topology:
:param role:
:return: |
def backup_bios_config(irmc_info):
"""backup current bios configuration
This function sends a BACKUP BIOS request to the server. Then when the bios
config data are ready for retrieving, it will return the data to the
caller. Note that this operation may take time.
:param irmc_info: node info
:... | backup current bios configuration
This function sends a BACKUP BIOS request to the server. Then when the bios
config data are ready for retrieving, it will return the data to the
caller. Note that this operation may take time.
:param irmc_info: node info
:return: a dict with following values:
... |
def as_p(self, show_leaf=True, current_linkable=False, class_current="active_link"):
"""
It returns breadcrumb as p
"""
return self.__do_menu("as_p", show_leaf, current_linkable, class_current) | It returns breadcrumb as p |
def _did_count(self, connection):
""" Called when count if finished """
self.current_connection = connection
response = connection.response
count = 0
callback = None
if 'X-Nuage-Count' in response.headers:
count = int(response.headers['X-Nuage-Count'])
... | Called when count if finished |
def open_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS):
"""
Opens a new handle to the process.
The new handle is stored in the L{hProcess} property.
@warn: Normally you should call L{get_handle} instead, since it's much
"smarter" and tries to reuse handles and me... | Opens a new handle to the process.
The new handle is stored in the L{hProcess} property.
@warn: Normally you should call L{get_handle} instead, since it's much
"smarter" and tries to reuse handles and merge access rights.
@type dwDesiredAccess: int
@param dwDesiredAccess:... |
def get_tm_session(session_factory, transaction_manager):
"""
Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.
This function will hook the session to the transaction manager which
will take care of committing any changes.
- When using pyramid_tm it will automatically be committed... | Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.
This function will hook the session to the transaction manager which
will take care of committing any changes.
- When using pyramid_tm it will automatically be committed or aborted
depending on whether an exception is raised.
- ... |
def from_raw_query(cls, query_string):
"""Parse raw string to query.
Given a raw string (typically typed by the user),
parse to a structured format and initialize the class.
"""
try:
node_tree = grammar.parse(query_string)
except IncompleteParseError:
... | Parse raw string to query.
Given a raw string (typically typed by the user),
parse to a structured format and initialize the class. |
def loadNelderMeadData(name):
'''
Reads the progress of a parallel Nelder-Mead search from a text file, as
created by saveNelderMeadData().
Parameters
----------
name : string
Name of the txt file from which to read search progress.
Returns
-------
simplex : np.array
... | Reads the progress of a parallel Nelder-Mead search from a text file, as
created by saveNelderMeadData().
Parameters
----------
name : string
Name of the txt file from which to read search progress.
Returns
-------
simplex : np.array
The current state of the simplex of para... |
def _set_ldp_sync(self, v, load=False):
"""
Setter method for ldp_sync, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv4/af_ipv4_unicast/af_ipv4_attributes/ldp_sync (container)
If this variable is read-only (config: false) in the
source YANG file, then _s... | Setter method for ldp_sync, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv4/af_ipv4_unicast/af_ipv4_attributes/ldp_sync (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ldp_sync is considered as a private
method. B... |
def execute_setup(self): # type: () -> Dict[str,str]
"""
for really surprising things like a dict foo in setup(**foo)
consider python3 setup.py --version
:return:
"""
ver = execute_get_text("python setup.py --version")
if not ver:
return None
... | for really surprising things like a dict foo in setup(**foo)
consider python3 setup.py --version
:return: |
def save(self, X=None, w=None, A=None):
"""Save one "page" of history at a given time.
.. note::
This method is used internally by `SMC` to store the state of the
particle system at each time t. In most cases, users should not
have to call this method directly.
... | Save one "page" of history at a given time.
.. note::
This method is used internally by `SMC` to store the state of the
particle system at each time t. In most cases, users should not
have to call this method directly. |
def disconnect(self):
"""Deinitialize the DAP I/O pins"""
try:
self._link.disconnect()
self._protocol = None
self._invalidate_cached_registers()
except DAPAccess.Error as exc:
six.raise_from(self._convert_exception(exc), exc) | Deinitialize the DAP I/O pins |
def read_url(url):
"""Reads given URL as JSON and returns data as loaded python object."""
logging.debug('reading {url} ...'.format(url=url))
token = os.environ.get("BOKEH_GITHUB_API_TOKEN")
headers = {}
if token:
headers['Authorization'] = 'token %s' % token
request = Request(url, heade... | Reads given URL as JSON and returns data as loaded python object. |
def _finalize_block_blob(self, ud, metadata):
# type: (Uploader, blobxfer.models.upload.Descriptor, dict) -> None
"""Finalize Block blob
:param Uploader self: this
:param blobxfer.models.upload.Descriptor ud: upload descriptor
:param dict metadata: metadata dict
"""
... | Finalize Block blob
:param Uploader self: this
:param blobxfer.models.upload.Descriptor ud: upload descriptor
:param dict metadata: metadata dict |
def __del_running_bp_from_all_threads(self, bp):
"Auxiliary method."
for (tid, bpset) in compat.iteritems(self.__runningBP):
if bp in bpset:
bpset.remove(bp)
self.system.get_thread(tid).clear_tf() | Auxiliary method. |
def content(self):
"""Return the entire section content."""
return _bfd.section_get_content(self.bfd, self._ptr, 0, self.size) | Return the entire section content. |
def _check_stream(stream):
'''Check that the stream is a file'''
if not isinstance(stream, type(_sys.stderr)):
raise TypeError("The stream given ({}) is not a file object.".format(stream)) | Check that the stream is a file |
def recurse(name,
source,
keep_source=True,
clean=False,
require=None,
user=None,
group=None,
dir_mode=None,
file_mode=None,
sym_mode=None,
template=None,
context=None,
replace... | Recurse through a subdirectory on the master and copy said subdirectory
over to the specified path.
name
The directory to set the recursion in
source
The source directory, this directory is located on the salt master file
server and is specified with the salt:// protocol. If the di... |
def other_set_producer(socket, which_set, image_archive, patch_archive,
groundtruth):
"""Push image files read from the valid/test set TAR to a socket.
Parameters
----------
socket : :class:`zmq.Socket`
PUSH socket on which to send images.
which_set : str
Whic... | Push image files read from the valid/test set TAR to a socket.
Parameters
----------
socket : :class:`zmq.Socket`
PUSH socket on which to send images.
which_set : str
Which set of images is being processed. One of 'train', 'valid',
'test'. Used for extracting the appropriate im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.