content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def resize_bilinear_nd(t, target_shape):
"""Bilinear resizes a tensor t to have shape target_shape.
This function bilinearly resizes a n-dimensional tensor by iteratively
applying tf.image.resize_bilinear (which can only resize 2 dimensions).
For bilinear interpolation, the order in which it is applied ... | 5,357,700 |
def _parse_disambiguate(disambiguatestatsfilename):
"""Parse disambiguation stats from given file.
"""
disambig_stats = [-1, -1, -1]
with open(disambiguatestatsfilename, "r") as in_handle:
header = in_handle.readline().strip().split("\t")
if header == ['sample', 'unique species A pairs',... | 5,357,701 |
def clean_vigenere(text):
"""Convert text to a form compatible with the preconditions imposed by Vigenere cipher."""
return ''.join(ch for ch in text.upper() if ch.isupper()) | 5,357,702 |
def close_room(room_name):
"""Close a room to anonymous users.
members only documentation:
https://xmpp.org/extensions/xep-0045.html#enter-members
Parameters
----------
room_name: string
The name of the room you want to destroy.
"""
client = _connect()
client.send(
... | 5,357,703 |
def select_artist(df_by_artists, df_rate):
"""This method selects artists which perform the same genre as
artists were given
:param df_by_artists:
:param df_rate:
"""
# save the indices of artists, which include any of the genres in the genre profile
list_of_id = []
for index, row in... | 5,357,704 |
def generate_uuid(class_name: str, identifier: str) -> str:
""" Generate a uuid based on an identifier
:param identifier: characters used to generate the uuid
:type identifier: str, required
:param class_name: classname of the object to create a uuid for
:type class_name: str, required
"""
... | 5,357,705 |
def fetch(model, key):
"""Fetch by ID."""
return db.session.query(model).get(key) | 5,357,706 |
def construct_filename(prefix: str, suffix: Optional[str] = '.csv') -> str:
"""Construct a filename containing the current date.
Examples
--------
.. code:: python
>>> filename = construct_filename('my_file', '.txt')
>>> print(filename)
'my_file_31_May_2019.txt'
Parameters... | 5,357,707 |
def make_friedman_model(point1, point2):
"""
Makes a vtk line source from two set points
:param point1: one end of the line
:param point2: other end of the line
:returns: The line
"""
line = vtkLineSource()
line.SetPoint1(point1)
line.SetPoint2(point2)
return line | 5,357,708 |
def test_fixture(request):
"""
This is a test fixture
"""
self = request.node.cls
def finalizer():
teardown(self)
request.addfinalizer(finalizer)
setup(self) | 5,357,709 |
def display_repositories_by_owner( repository_tups ):
"""Group summary display by repository owner."""
repository_tups_by_owner = {}
for repository_tup in repository_tups:
name, owner, changeset_revision = repository_tup
if owner:
if owner in repository_tups_by_owner:
... | 5,357,710 |
def breadcrumbs_pcoa_plot(pcl_fname, output_plot_fname, **opts):
"""Use breadcrumbs `scriptPcoa.py` script to produce principal
coordinate plots of pcl files.
:param pcl_fname: String; file name of the pcl-formatted taxonomic profile
to visualize via `scriptPcoa.py`.
:param output... | 5,357,711 |
def _parse_xml(buff):
"""\
Parses XML and returns the root element.
"""
buff.seek(0)
return etree.parse(buff).getroot() | 5,357,712 |
def delete_left_buckets(
request: pytest.FixtureRequest, storage_client: SupabaseStorageClient
):
"""Ensures no test buckets are left when a test that created a bucket fails"""
def finalizer():
for bucket in temp_test_buckets_ids:
try:
storage_client.empty_bucket(bucket.... | 5,357,713 |
def After(interval):
""" After waits for the duration to elapse and then sends the current time
on the returned channel.
It is equivalent to Timer(interval).c
"""
return Timer(interval).c | 5,357,714 |
def f_score(r: float, p: float, b: int = 1):
"""
Calculate f-measure from recall and precision.
Args:
r: recall score
p: precision score
b: weight of precision in harmonic mean
Returns:
val: value of f-measure
"""
try:
val = (1 + b ** 2) * (p * r) / (b *... | 5,357,715 |
def is_container_system_config_file(file):
"""Determine whether a given file is one of the files created by setup_container_system_config().
@param file: Absolute file path as string.
"""
if not file.startswith("/etc/"):
return False
return file in [os.path.join("/etc", f.decode()) for f in ... | 5,357,716 |
def show_inventory():
"""Show the user what is in stock."""
context = {
'inventory': [ # Could contain any items
{'name': 'apple', 'price': 1.00},
{'name': 'banana', 'price': 1.20},
{'name': 'carrot', 'price': 2.00},
]
}
return render_template('sho... | 5,357,717 |
def sweep(airfoils, res, min_alfa=4, write_file=True, plots_on=False, panels=200):
"""
Runs a large sweep over airfoil and re range
@param airfoils iterable of NACA numbers to sweep over
@param res iterable reynolds numbers to sweep over
@param write_file boolean indicating whether or not ... | 5,357,718 |
def grid_optimizer(
data,
params,
args,
xset,
yset=None,
verbose=False,
visualize=False,
save_path=None):
"""
This function optimizes the ESN parameters, x and y, over a specified
range of values. The optimal values are determined by minimizing... | 5,357,719 |
def main(cli_args):
"""Run all given Robot Framework data sources in parallel."""
robot_parallel = RobotParallel()
try:
robot_parallel.parse_arguments(cli_args)
robot_parallel.execute(worker, (cpu_count() * 2) - 1)
robot_parallel.flush_stdout()
# pylint: disable=broad-except
... | 5,357,720 |
async def test_meta(httpx_mock: HTTPXMock):
"""Test the meta information."""
httpx_mock.add_response(json=RESPONSE_VALID)
client = Luftdaten(SENSOR_ID)
await client.get_data()
assert client.meta["sensor_id"] == 1
assert client.meta["latitude"] == 48.792
assert client.meta["longitude"] == 9... | 5,357,721 |
def rebuild_schema(doc, r, df):
"""Rebuild the schema for a resource based on a dataframe"""
import numpy as np
# Re-get the resource in the doc, since it may be different.
try:
r = doc.resource(r.name)
except AttributeError:
# Maybe r is actually a resource name
r = doc.res... | 5,357,722 |
def compute_similarity(image, reference):
"""Compute a similarity index for an image compared to a reference image.
Similarity index is based on a the general algorithm used in the AmphiIndex algorithm.
- identify slice of image that is a factor of 256 in size
- rebin image slice down to a (25... | 5,357,723 |
def _create_npu_quantization(
scale,
zero_point,
):
"""This is a helper function to capture a list
of arguments to create Vela NpuQuantization object
"""
# Scale could be an ndarray if per-channel quantization is available
if not isinstance(scale, tvm.tir.expr.Load):
if isinstance(sc... | 5,357,724 |
def article_markdown(text):
""" 对传入的text文本进行markdown """
renderer = ArticleRenderer()
markdown = mistune.Markdown(renderer=renderer)
return markdown(text) | 5,357,725 |
def tf_pywt_wavelet_decomposition(patch_vec, patch_size, name, wavelet_type, level, mode):
"""
:param patch_vec:
:param patch_size:
:param name:
:param wavelet_type:
:param level:
:param mode:
:return:
"""
# TODO: docstring
# Convert input values for pywt
wavelet_type =... | 5,357,726 |
def launch_pycompss_application(app,
func,
log_level="off", # type: str
o_c=False, # type: bool
debug=False, # type: bool
... | 5,357,727 |
def plot_48hours(i, url, sorted_dts, sorted_dts2=None, save=False):
"""
包含了两条线!
"""
# print(url)
# print("实际传播开始和结束时间:", sorted_dts[0], sorted_dts[-1])
plt.figure(figsize=(10, 6))
ts = cal_ts_48hours(sorted_dts)
ts.plot()
if sorted_dts2:
ts2 = cal_ts_48hours(sorted_dts2)
... | 5,357,728 |
def print_variables_by_scope():
"""Prints trainable variables by scope."""
vars = [(v.name, v.shape.as_list()) for v in tf.trainable_variables()]
vars = sorted(vars, key=lambda x: x[0])
last_scope = None
scope_n_params = 0
for i, (name, shape) in enumerate(vars):
current_scope = name.s... | 5,357,729 |
def insert_into_crime_report(summary: tuple):
"""
:param summary:
:return:
"""
connection = connect_to_db()
usr = connection.cursor()
usr.execute("INSERT INTO CrimeReport VALUES (?,?,?,?,?,?,?,?,?,?,?)", summary)
connection.commit()
connection.close() | 5,357,730 |
def _gen_key(user_id, key_name):
""" Tuck this into UserManager """
try:
manager = users.UserManager.instance()
private_key, fingerprint = manager.generate_key_pair(user_id, key_name)
except Exception as ex:
return {'exception': ex}
return {'private_key': private_key, 'fingerprin... | 5,357,731 |
def svhn_loader(size=None,root="./shvn",set="train",batch_size=32,mean=0.5,std=0.5,transform="default",download=True,target_transform=None,**loader_args):
"""
:param size:
:param root:
:param set:
:param batch_size:
:param mean:
:param std:
:param transform:
:param download:
:pa... | 5,357,732 |
def get_supervisees():
"""Pull the supervisor specifications out of the entry point."""
eps = list(pkg_resources.iter_entry_points(ENTRY_POINT_GROUP))
return dict((ep.name, ep.load()) for ep in eps) | 5,357,733 |
def delete_account(password_for):
"""
function to delete the credentials of a given account
"""
Credentials.delete_account(password_for) | 5,357,734 |
def object_context(name, sesh, conf, data=None, params=None):
"""Creates a CDMI object with the given file name, and deletes it when the ``with`` context exits.
Does no testing of return codes or any sort of validity. It does only call delete if the status code was 201
however.
To use it::
wi... | 5,357,735 |
def test_withdraw_interactive_invalid_asset(
client, acc1_usd_withdrawal_transaction_factory
):
"""
`GET /withdraw/interactive_withdraw` fails with invalid asset_code.
"""
acc1_usd_withdrawal_transaction_factory()
response = client.get(
f"/withdraw/interactive_withdraw?transaction_id=2&a... | 5,357,736 |
def test_allocate_asset_dust_order_simple(
worker, other_worker, do_initial_allocation, maintain_until_allocated, base_account
):
"""Make dust order, check if it canceled and closer opposite order placed."""
do_initial_allocation(worker, worker.mode)
num_sell_orders_before = len(worker.sell_orders)
... | 5,357,737 |
async def index(request):
"""
This is the view handler for the "/" url.
**Note: returning html without a template engine like jinja2 is ugly, no way around that.**
:param request: the request object see http://aiohttp.readthedocs.io/en/stable/web_reference.html#request
:return: aiohttp.web.Respons... | 5,357,738 |
def adtg(s, t, p):
"""
Calculates adiabatic temperature gradient as per UNESCO 1983 routines.
Parameters
----------
s(p) : array_like
salinity [psu (PSS-78)]
t(p) : array_like
temperature [℃ (ITS-90)]
p : array_like
pressure [db]
Returns
-------
ad... | 5,357,739 |
def segm_set_center_levels(name, seg_labels, path_out, levels=DISTANCE_LEVELS):
""" set segmentation levels according distance inside object imsegm
:param str name: image name
:param ndarray seg_labels:
:param str path_out: path for output
:param [float] levels: distance levels fro segmentation lev... | 5,357,740 |
def calculate_ion_mz(seq: str,
ion: str = 'M',
charge: int = 0
) -> float:
"""
given a peptide sequence and ion type, count the number of atoms, accounting for ion
type and whether cysteines are measured by IAA
- ion type
M: full peptid... | 5,357,741 |
def get_all_sub_folders(folder_path):
"""get all sub folders to list
Parameters
----------
folder_path : str
Returns
-------
list
"""
sub_folders = []
for path in os.listdir(folder_path):
full_path = os.path.join(folder_path, path)
if os.path.isdir(full_path):
... | 5,357,742 |
def calculate_correlation(type_, df, col1, col2):
"""Calculate the defined correlation coefficient.
This function accepts the type of correlation coefficient to be calculated, the data frame and the two column.
It returns the calculated coefficient.
Keyword arguments:
type_ -- type of corr... | 5,357,743 |
def hhc_to_int(s):
"""Parse a number expressed in sortable hhc as an integer (or long).
>>> hhc_to_int('-')
0
>>> hhc_to_int('.')
1
>>> hhc_to_int('~')
65
>>> hhc_to_int('.-')
66
>>> hhc_to_int('..')
67
>>> hhc_to_int('.XW')
6700
>>> hhc_to_int('----..')
67
... | 5,357,744 |
def initializeSens(P, B, idxs):
"""
This function initializes the sensitivities using the bicriteria algorithm, to be the distance between each
point to it's closest flat from the set of flats B divided by the sum of distances between self.P.P and B.
:param B: A set of flats where each flat is rep... | 5,357,745 |
def _label_plot(title="Untitled Plot", xlabel="x axis", ylabel="y axis") -> None:
"""Apply titles and axis labels to a plot."""
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel) | 5,357,746 |
def fast_knn(data, k=3, eps=0, p=2, distance_upper_bound=np.inf, leafsize=10, idw=util_idw.shepards):
""" Impute using a variant of the nearest neighbours approach
Basic idea: Impute array with a basic mean impute and then use the resulting complete
array to construct a KDTree. Use this KDTree to compute n... | 5,357,747 |
def role_generator(role):
"""Closure function returning a role function."""
return lambda *args, **kwargs: role.run(*args, **kwargs) | 5,357,748 |
def pick_slices(img, num_slices_per_view):
"""
Picks the slices to display in each dimension,
skipping any empty slices (without any segmentation at all).
"""
slices = list()
for view in range(len(img.shape)):
dim_size = img.shape[view]
non_empty_slices = np.array(
... | 5,357,749 |
def cate2(request):
"""
DB에서 Cate2의 분류 이름을 반환
"""
cate1 = Cate1.objects.get(cate1_name=request.GET.get('cate1'))
cate2 = list(map(lambda cate2 : cate2['cate2_name'],
Cate2.objects.filter(cate1=cate1).values('cate2_name')))
json_data = json.dumps({'cate2': cate2})
return HttpRespons... | 5,357,750 |
def get_single_endpoint(name):
"""
TODO - Add docstring
"""
class EndpointWithID(Resource):
def get(self, pid):
return get_with_id(name, pid), 200
# TODO - Add `get.__doc__`
EndpointWithID.__name__ = name
return EndpointWithID | 5,357,751 |
def dayChange():
"""
Day Change
Calculates and stores in a dictionary the total current change in position
value since yesterday, which is (current_price - lastday_price)* qty.
:return: dictionary
"""
daychange = dict()
for position in portfolio:
# Strings are returned from API; ... | 5,357,752 |
def look_for_section(line):
"""Look for one of the sections in a line of text."""
for key in SECTIONS:
if line.startswith(key):
return key
return None | 5,357,753 |
def check_rootfolders():
"""Create log and model folder"""
folders_util = [args.root_log, args.root_model,
os.path.join(args.root_log, args.store_name),
os.path.join(args.root_model, args.store_name)]
for folder in folders_util:
if not os.path.exists(folder):
... | 5,357,754 |
def SetStrucIdx(sid, index):
"""
Change structure index
@param sid: structure type ID
@param index: new index of the structure
@return: != 0 - ok
@note: See GetFirstStrucIdx() for the explanation of
structure indices and IDs.
"""
s = idaapi.get_struc(sid)
if not s:
... | 5,357,755 |
def extract_user_dict_from_tweet( tweet: Tweet ):
"""Takes the other_data field from a tweet object and
extracts the data for the user from it.
It returns a dictionary rather than a User model object
because we might want to try looking up whether the user
exists before creating a new user object.
... | 5,357,756 |
def in_scope(repository_data):
"""Return whether the given repository is in scope for the configuration.
Keyword arguments:
repository_data -- data for the repository
"""
if "scope" in repository_data["configuration"] and repository_data["configuration"]["scope"] == "all":
return True
... | 5,357,757 |
def run_image_container_checks(
image_container: Union[AICSImage, Reader],
set_scene: str,
expected_scenes: Tuple[str, ...],
expected_current_scene: str,
expected_shape: Tuple[int, ...],
expected_dtype: np.dtype,
expected_dims_order: str,
expected_channel_names: Optional[List[str]],
... | 5,357,758 |
def collect_validation_helper(package_names: str) -> Type[ValidationHelper]:
"""Finds subclasses of the validate.ValidationHelper from a
list of package names.
Args:
package_names: A list of Python package names as strings.
Returns:
A validator class that are subclasses of validate.Val... | 5,357,759 |
def heartbeat(request):
"""Test that ElasticSearch is operationnal.
:param request: current request object
:type request: :class:`~pyramid:pyramid.request.Request`
:returns: ``True`` is everything is ok, ``False`` otherwise.
:rtype: bool
"""
indexer = request.registry.indexer
try:
... | 5,357,760 |
def _load_edge_data(graph, regions):
"""Load and return all relevant edges from the graph."""
has_seat = _load_edges_from_query(
graph,
'SELECT inV().@rid AS in_rid, outV().@rid AS out_rid FROM Has_Seat')
# The edges in the existing dataset point from parent to child region / settlement.
... | 5,357,761 |
def get_story_assignee(jira_sheet, process):
""" Accessor for Story Assignee
Accessor method for retrieving the value for Story Assignee on the
JIRA Stories Sheet.
There is a check to make certain the process in question is amongst those
qualified to exist.
Args:
jira_sheet: A variabl... | 5,357,762 |
def predict_mhalo(obs_dsigma, mock_use, logms_mod_tot, logms_mod_inn, sig_logms=None):
"""Halo mass and its scatter in each bin.
Parameters
----------
obs_dsigma: list
List of observed DeltaSigma profiles.
mock_use: numpy array
UniverseMachine mock catalog.
logms_mod_tot : ndarr... | 5,357,763 |
def create_agent_model(env, lr=1e-4, h_size=128, epsilon=0.2, beta=1e-3, max_step=5e6, normalize=False, num_layers=2):
"""
Takes a Unity environment and model-specific hyper-parameters and returns the
appropriate PPO agent model for the environment.
:param env: a Unity environment.
:param lr: Learni... | 5,357,764 |
def decode_to_sequence(encoded_sequence: Bytes) -> List[RLP]:
"""
Decodes a rlp encoded byte stream assuming that the decoded data
should be of type `Sequence` of objects.
Parameters
----------
encoded_sequence :
An RLP encoded Sequence.
Returns
-------
decoded : `Sequence[... | 5,357,765 |
def list_field_override_choices(override_map=None, html=True):
"""
This returns either a list of allowable choices, or an HTML-formatted unordered list (default).
"""
if override_map:
if html:
choices = '<b>These are the allowable field override choices for field name:<ul>'
... | 5,357,766 |
def add_create_subcommand(subparser_factory):
"""Add a subparser for the create subcommand."""
create_help = "Create and load a database from an sql dump file."
subparser = subparser_factory.add_parser('create', help=create_help,
description=create_help)
db... | 5,357,767 |
def setup(app):
""" some tools for markdown parsing """
config = {
# 'url_resolver': lambda url: github_doc_root + url,
'auto_toc_tree_section': 'Contents',
'enable_eval_rst': True,
}
app.add_config_value('recommonmark_config', config, True)
app.add_transform(AutoStructify)
... | 5,357,768 |
def get_logger(initial_level=logging.DEBUG):
"""Gets the named logger"""
logger = logging.getLogger('ungoogled')
if logger.level == logging.NOTSET:
logger.setLevel(initial_level)
if not logger.hasHandlers():
console_handler = logging.StreamHandler()
console_handler... | 5,357,769 |
def config_logger(name, log_file, file_level, console_level):
"""Configure the logger that should be used by all modules in this
package.
This method sets up a logger, such that all messages are written to console
and to an extra logging file. Both outputs will be the same, except that
a message log... | 5,357,770 |
def _safe_resolve_url(url):
"""
Previously, resolve_url_lazy would fail if the url was a unicode object.
See <https://github.com/fusionbox/django-authtools/issues/13> for more
information.
Thanks to GitHub user alanwj for pointing out the problem and providing
this solution.
"""
return ... | 5,357,771 |
def get_metrics(
reset: bool = False, include_custom: bool = True, raise_errors: bool = True,
) -> pd.DataFrame:
"""
Returns table of available metrics used for CV.
Example
-------
>>> from pycaret.datasets import get_data
>>> boston = get_data('boston')
>>> from pycaret.regression im... | 5,357,772 |
def get_unique_wikilinks(filepath):
"""Get UNIQUE wikilinks from a md file.
The links' order of appearance in the file IS preserved in the output.
This accounts for:
- Aliases / alt text, so [[Lorem ipsum|L.I.]]
will be represented as 'Lorem ipsum'.
- Header text links, so [[Lorem ipsum#Dummy t... | 5,357,773 |
def parse_single_example(serialized_example, params):
"""Parses a singel serialized TFExample string."""
decoder = tf_example_decoder.TfExampleDecoder()
data = decoder.decode(serialized_example)
image = data['image']
source_id = data['source_id']
source_id = dataloader_utils.process_source_id(source_id)
h... | 5,357,774 |
def AddDiskScopeFlag(parser):
"""Adds --disk-scope flag."""
parser.add_argument(
'--disk-scope',
choices={'zonal':
'The disk specified in --disk is interpreted as a '
'zonal disk in the same zone as the instance',
'regional':
'The disk specifie... | 5,357,775 |
def eval_blocking(lamb, mu, k):
"""Finds the blocking probability of a queue.
Args:
lamb (float): The rate into the queue.
mu (float): The rate out of the queue.
k (int): Maximum number of customers able to be in the queue.
"""
rho = lamb/mu
return rho**k*((1-rho)/(1-rho**(k... | 5,357,776 |
def report_insurance_event(event_dict, autoID) :
"""
Send insurance event to insurance cloud endpoint
params:
event_dict: event_type, speed, gps-coordinates, time
autoID: object that containers drivername, driverID, vehicle_model and vehicleID
returns:
a dictionary that captures all the info... | 5,357,777 |
def get_dependent_columns(covar):
"""
Get the list of dependent columns
:param covar: The covariance matrix
:return: Dependent columns
"""
ind_columns = (np.where(~covar.any(axis=1))[0]).tolist()
dep_columns_z = []
for i in range(0, covar.shape[0]):
if i not in ind_columns:
... | 5,357,778 |
def ProcessMSA():
"""Convert the MSA for use with PSI-Blast"""
#Check the inputs
if os.path.isfile(args.wildtype) == False:
print "ProcessMSA Error: The path to the file with the wild-type sequence is missing"
quit()
if os.path.isfile(args.msa) == False:
print "ProcessMSA Error:... | 5,357,779 |
def results_to_answers(guess_hints, answers):
"""Provide remaining valid answers matching a list of guesses and
corresponding hints
"""
gh_stack = guess_hints.copy()
new_ans = answers.copy()
while len(gh_stack) > 0:
gh = gh_stack.pop()
guess = gh[0]
hint = gh[1]
... | 5,357,780 |
def plt_figure(title, xlabel, ylabel, x_list, y_list, x_lim, y_lim):
"""
- 通过各参数,画出一张折线图
"""
plt.figure()
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if x_lim:
plt.xlim(x_lim)
if y_lim:
plt.ylim(y_lim)
plt.plot(x_list, y_list) | 5,357,781 |
def traverse_backward(outputs, fn):
"""Backward traversal function through the graph.
Traverses the graph going from outputs to inputs. The provided function is
applied once to each module reached this way. This function is used to
implement other functionality that requires traversing the graph. ``fn`... | 5,357,782 |
def get_archive_map(data: DataFrame, row_col: Optional[str] = "ROW") -> Series:
"""
Get a series mapping object names to archive names
:param data: Dataset with archive names as ARCHIVE column and object names
in index
:type data: DataFrame
:param row_col: column with rol index, de... | 5,357,783 |
def gain_ratio(x_mat: ndarray, y_row: ndarray, prop: int, prop_values: Iterable, gain_value: float = None) -> float:
"""
计算使用属性 prop 对样本集进行划分的信息增益率,值越大表示使用属性 prop 进行划分
所获得的纯度提升越大。此方法对可取值数目较少的属性有所偏好
:param x_mat: 特征向量组,行数 m 表示样本数,列数 n 表示特征数
:param y_row: 输出向量。是一个只有一个维度的行向量,要和 x_mat 匹配
:param pro... | 5,357,784 |
def _LengthError(e: ByteList):
"""Check if the length of the EDID is a multiple of 128.
Args:
e: The list form of the EDID to be checked.
Returns:
A list of error.Error objects, or None.
"""
if not len(e) % 128:
return None
else:
return [
error.Error(
... | 5,357,785 |
def generate_states(
start: int = 0,
stop: int = 14,
n_states: int = 100,
parity: Union[str, int] = "both"
):
"""
Generate correct string for input to `kshell_ui.py` when asked for
which states to calculate. Copy the string generated by this
function and paste it into `kshell_ui.py` ... | 5,357,786 |
def __single_auc_score__(feature_i,
clf,
cv_indices,
X,
y,
sample_weight=None):
"""Method determining the 'area under curve' for a single test set.
This function is intended for internal ... | 5,357,787 |
def IntCurveSurface_ThePolygonToolOfHInter_Bounding(*args):
"""
:param thePolygon:
:type thePolygon: IntCurveSurface_ThePolygonOfHInter &
:rtype: Bnd_Box
"""
return _IntCurveSurface.IntCurveSurface_ThePolygonToolOfHInter_Bounding(*args) | 5,357,788 |
def identity_show(client, resource_group_name, account_name):
"""
Show the identity for Azure Cognitive Services account.
"""
sa = client.get(resource_group_name, account_name)
return sa.identity if sa.identity else {} | 5,357,789 |
def parsing_input(program_parameters):
"""
Parses apart the command line or qsub submission file to get all user input parameters
for analyzing the data. Function also prints all user parameters to
command line, so a user can monitor the inputs. Also, default settings are
set in this function and ... | 5,357,790 |
def normalize_country_code(country_code):
""" Normalize country codes a bit by making capitalization consistent and
removing trailing comments (and other words). """
if not country_code:
return country_code
country_code = re.match(r'^(\w+)', country_code).group(1)
return country_code.upp... | 5,357,791 |
def get_angle(p1, p2):
"""Get the angle between two points."""
return math.atan2(p2[1] - p1[1], p2[0] - p1[0]) | 5,357,792 |
def test_thanks(client):
"""Test thanks page."""
rv = client.get('/thanks/test10.jpg&&10')
assert b'Thanks' in rv.data | 5,357,793 |
def list_accessors(gltf):
"""
アクセサーを列挙する
:param gltf: glTFオブジェクト
:return: アクセッサー列挙(generator)
"""
for skin in gltf['skins']:
yield skin['inverseBindMatrices']
for mesh in gltf['meshes']:
for primitive in mesh['primitives']:
yield primitive['indices']
... | 5,357,794 |
def per_application():
"""
:return:
a seeder function that always returns 1, ensuring at most one delegate is ever spawned
for the entire application.
"""
return lambda msg: 1 | 5,357,795 |
def get_job_information(url):
""" Uses bs4 to grab the information from each job container based on the url.
Parameters
----------
url : str
Career builder url of any job
Returns
------
job_data : dict
Contains Job Name, Company Name, Job Location, Description, S... | 5,357,796 |
def idiv(self, other):
"""Compute the element-wise division.
Parameters
----------
other : Union[dragon.Tensor, number]
The value to divide.
Returns
-------
dragon.Tensor
The self.
See Also
--------
`dragon.math.div(...)`_
"""
return _apply_binary_op([... | 5,357,797 |
def getAudioMetadata(fileRef):
"""Extract metadata for audio file"""
args = [config.mediaInfoExe]
args.append("--Output=EBUCore")
args.append(fileRef)
# Command line as string (used for logging purposes only)
cmdStr = " ".join(args)
status, out, err = shared.launchSubProcess(args)
# C... | 5,357,798 |
def simulation_test(**kwargs):
"""Decorate a unit test and mark it as a simulation test.
The arguments provided to this decorator will be passed to
:py:meth:`~reviewbot.tools.testing.testcases.BaseToolTestCase
.setup_simulation_test`.
Args:
**kwargs (dict):
Keyword arguments to... | 5,357,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.