content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def check_cardinality(attribute_name: str,
analysis: run_metadata_pb2.Analysis
) -> Union[None, str]:
"""Check whether the cardinality exceeds the predefined threshold
Args:
attribute_name: (string),
analysis: (run_metadata_pb2.Analysis), analysis that contai... | 5,335,000 |
def create_df_from(dataset):
"""
Selects a method, based on the given dataset name, and creates the corresponding dataframe.
When adding a new method, take care to have as index the ASN and the column names to be of the format "dataset_name_"+"column_name" (e.g., the column "X" from the dataset "setA", shou... | 5,335,001 |
def install_mysql():
""" ripped from http://www.muhuk.com/2010/05/how-to-install-mysql-with-fabric/
"""
with settings(hide('warnings', 'stderr'), warn_only=True):
result = sudo('dpkg-query --show mysql-server')
if result.failed is False:
warn('MySQL is already installed')
return
... | 5,335,002 |
def test_magnet_cuboid_Bfield():
"""test cuboid field"""
mag = np.array(
[
(0, 0, 0),
(1, 2, 3),
(1, 2, 3),
(1, 2, 3),
(1, 2, 3),
(2, 2, 2),
(2, 2, 2),
(1, 1, 1),
(1, 1, 1),
]
)
di... | 5,335,003 |
def plasma_fractal(mapsize=256, wibbledecay=3):
"""
Generate a heightmap using diamond-square algorithm.
Return square 2d array, side length 'mapsize', of floats in range 0-255.
'mapsize' must be a power of two.
"""
assert (mapsize & (mapsize - 1) == 0)
maparray = np.empty((mapsize, mapsize), dtype=np.flo... | 5,335,004 |
def reduce_puzzle(values):
"""Reduce a Sudoku puzzle by repeatedly applying all constraint strategies
Parameters
----------
values(dict)
a dictionary of the form {'box_name': '123456789', ...}
Returns
-------
dict or False
The values dictionary after continued application o... | 5,335,005 |
def read_ids():
"""
Reads the content from a file as a tuple and returns the tuple
:return: node_id, pool_id (or False if no file)
"""
if not const.MEMORY_FILE.exists():
return False
with open(const.MEMORY_FILE, 'rb') as f:
data = pickle.load(f)
assert type(data) is tuple... | 5,335,006 |
def _match_caller_callee_argument_dimension_(program, callee_function_name):
"""
Returns a copy of *program* with the instance of
:class:`loopy.kernel.function_interface.CallableKernel` addressed by
*callee_function_name* in the *program* aligned with the argument
dimensions required by *caller_knl*... | 5,335,007 |
def fix_arp_2():
"""Fixes net.ipv4.conf.all.arp_ignore"""
vprint("Fixing ARP setting")
exe("sysctl -w net.ipv4.conf.all.arp_ignore=1") | 5,335,008 |
def new_automation_jobs(issues):
"""
:param issues: issues object pulled from Redmine API
:return: returns a new subset of issues that are Status: NEW and match a term in AUTOMATOR_KEYWORDS)
"""
new_jobs = {}
for issue in issues:
# Only new issues
if issue.status.name == 'New':
... | 5,335,009 |
def resolve_test_data_path(test_data_file):
"""
helper function to ensure filepath is valid
for different testing context (setuptools, directly, etc.)
:param test_data_file: Relative path to an input file.
:returns: Full path to the input file.
"""
if os.path.exists(test_data_file):
... | 5,335,010 |
def pit_two_sats_sqlserver(context):
"""
Define the structures and metadata to perform PIT load
"""
context.vault_structure_type = "pit"
context.hashed_columns = {
"STG_CUSTOMER_DETAILS": {
"CUSTOMER_PK": "CUSTOMER_ID",
"HASHDIFF": {"is_hashdiff": True,
... | 5,335,011 |
def test_query_non_ascii(client):
"""Test if query strings with non-ascii characters work.
There was a bug that forced query strings to be all ascii. The
bug only occured with Python 2. It was fixed in change 8d5132d.
"""
# String literal with unicode characters that will be understood
# by b... | 5,335,012 |
def make_data(revs, word_idx_map, max_l=50, filter_h=3, val_test_splits=[2, 3], validation_num=500000):
"""
Transforms sentences into a 2-d matrix.
"""
version = begin_time()
train, val, test = [], [], []
for rev in revs:
sent = get_idx_from_sent_msg(rev["m"], word_idx_map, max_l, True)
... | 5,335,013 |
def init(param_test):
"""
Initialize class: param_test
"""
# initialization
param_test.default_args_values = {'di': 6.85, 'da': 7.65, 'db': 7.02}
default_args = ['-di 6.85 -da 7.65 -db 7.02'] # default parameters
param_test.default_result = 6.612133606
# assign default params
if no... | 5,335,014 |
def add_width_to_df(df):
"""Adds an extra column "width" to df which is the angular width of the CME
in degrees.
"""
df = add_helcats_to_df(df, 'PA-N [deg]')
df = add_helcats_to_df(df, 'PA-S [deg]')
df = add_col_to_df(df, 'PA-N [deg]', 'PA-S [deg]', 'subtract', 'width', abs_col=True)
return ... | 5,335,015 |
def main():
"""Run P4 commands to collect metrics."""
desc = """Examine p4 changes and jobs to report metrics."""
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('--after', type=int,
help="select changes after (and including) the given change")
args = p... | 5,335,016 |
def save(
basename: str,
model: Model,
format_input: FormatInput,
format_output: FormatOutput,
) -> None:
"""save model, format_input, format_output
Args:
basename (str): dirname + label, e.g., xxxx/best
model (Model): target model
format_input (FormatInput): target form... | 5,335,017 |
def test_simple_import(barred_tac_list_importer, logger, db_conn):
"""Verify that the valid barred list data can be successfully imported into the db."""
expect_success(barred_tac_list_importer, 6, db_conn, logger) | 5,335,018 |
def checkSeconds(seconds, timestamp):
""" Return a string depending on the value of seconds
If the block is mined since one hour ago, return timestamp
"""
if 3600 > seconds > 60:
minute = int(seconds / 60)
if minute == 1:
return '{} minute ago'.format(minute)
retu... | 5,335,019 |
def test_value_in_dict_none(allow_false_empty):
"""
Test that :py:func:`riboviz.utils.value_in_dict` returns ``False`
if a key has value ``None`` regardless of the value of
``allow_false_empty``.
:param allow_false_empty: Value for ``allow_false_empty`` \
parameter
:type allow_false_empty: ... | 5,335,020 |
def strict_application(
library: pd.DataFrame, config: Config, errors: list
) -> _DfGenerator:
"""
Apply the recorded template to each row of reactants in the library
to make new, false reactions.
:param library: the reaction library
:param config: the configuration
:param errors: a list to... | 5,335,021 |
def get_netrange_end(asn_cidr):
"""
:param str asn_cidr: ASN CIDR
:return: ipv4 address of last IP in netrange
:rtype: str
"""
try:
last_in_netrange = \
ip2long(str(ipcalc.Network(asn_cidr).host_first())) + \
ipcalc.Network(asn_cidr).size() - 2
except ValueEr... | 5,335,022 |
def load_from_file(filepath, column_offset=0, prefix='', safe_urls=False, delimiter='\s+'):
"""
Load target entities and their labels if exist from a file.
:param filepath: Path to the target entities
:param column_offset: offset to the entities column (optional).
:param prefix: URI prefix (Ex: htt... | 5,335,023 |
def validate_types(validator, schema, services, rsc_type, rscs):
"""Validate the basic types in the schema."""
properties = schema['definitions'][rsc_type]['properties']
# Go through the schema; find the strings, integers, and enums and
# change them to invalid values and verify that the validator catc... | 5,335,024 |
def create_app(*, config_object: Config) -> connexion.App:
"""Create app instance."""
connexion_app = connexion.App(
__name__, debug=config_object.DEBUG, specification_dir="spec/"
)
flask_app = connexion_app.app
flask_app.config.from_object(config_object)
connexion_app.add_api("api.yaml... | 5,335,025 |
def load_plugins(descr: str, package: str, plugin_class: Any,
specs: TList[TDict[str, Any]] = None) -> \
TDict[Union[str, int], Any]:
"""
Load and initialize plugins from the given directory
:param descr: plugin description
:param package: plugin package name relative to afterg... | 5,335,026 |
def _get_repos_info(db: Session, user_id: int):
"""Returns data for all starred repositories for a user.
The return is in a good format for the frontend.
Args:
db (Session): sqlAlchemy connection object
user_id (int): User id
Returns:
list[Repository(dict)]:repo_info = {
... | 5,335,027 |
def handler(signum, _):
""" signal handler """
if(signum == signal.SIGUSR1):
if controller:
controller.reload(verbose=True)
return
print(f' interupt has been caught ({signum}), shutting down...')
if controller:
controller.shutdown()
exit(0) | 5,335,028 |
def ultimate_oscillator(close_data, low_data):
"""
Ultimate Oscillator.
Formula:
UO = 100 * ((4 * AVG7) + (2 * AVG14) + AVG28) / (4 + 2 + 1)
"""
a7 = 4 * average_7(close_data, low_data)
a14 = 2 * average_14(close_data, low_data)
a28 = average_28(close_data, low_data)
uo = 100 * ((a7... | 5,335,029 |
async def test_ws_setup_depose_mfa(opp, opp_ws_client):
"""Test set up mfa module for current user."""
opp.auth = await auth_manager_from_config(
opp,
provider_configs=[
{
"type": "insecure_example",
"users": [
{
... | 5,335,030 |
def generate_csrf(request: StarletteRequest,
secret_key: str,
field_name: str):
"""Generate a new token, store it in the session and return a time-signed
token. If a token is already present in the session, it will be used to
generate a new time signed token. The time-sig... | 5,335,031 |
def get_completions():
"""
Returns the global completion list.
"""
return completionList | 5,335,032 |
def list_pars(names_only=True, kind=None):
"""
Print all parameters in all models.
If *names_only* then only print the parameter name, not the models it
occurs in.
"""
partable = find_pars(kind)
if names_only:
print(columnize(list(sorted(partable.keys()))))
else:
for k, ... | 5,335,033 |
def breadth_first_search():
"""
BFS Algorithm
"""
initial_state = State(3, 3, "left", 0, 0)
if initial_state.is_goal():
return initial_state
frontier = list()
explored = set()
frontier.append(initial_state)
while frontier:
state = frontier.pop(0)
if state.is_g... | 5,335,034 |
def rankSimilarity(df, top = True, rank = 3):
""" Returns the most similar documents or least similar documents
args:
df (pandas.Dataframe): row, col = documents, value = boolean similarity
top (boolean): True: most, False: least (default = True)
rank (int): number of top or bo... | 5,335,035 |
def create_database():
"""
If this script is run directly, create all the tables necessary to run the
application.
"""
try:
Episodes.create_table()
except:
logi("Error happened.")
print("All tables created") | 5,335,036 |
def vvd(val, valok, dval, func, test, status):
"""Mimic routine of erfa/src/t_erfa_c.c (to help copy & paste)"""
assert quantity_allclose(val, valok * val.unit, atol=dval * val.unit) | 5,335,037 |
def change_controller(move_group, second_try=False):
"""
Changes between motor controllers
move_group -> Name of required move group.
"""
global list_controllers_service
global switch_controllers_service
controller_map = {
'gripper': 'cartesian_motor_controller',
'whole_... | 5,335,038 |
def base64_encode(text):
"""<string> -- Encode <string> with base64."""
return base64.b64encode(text.encode()).decode() | 5,335,039 |
def test_netconf_edit_config_bad_operation(ssh, nornir, sros_config_payload):
"""Test NETCONF edit-config, unsupported default operation."""
# Create Fake RPC Object class. Set 'ok' attr to True.
response_rpc = FakeRpcObject()
response_rpc.set_ok(set=True)
# Create a Mock Object. Assign 'edit-config... | 5,335,040 |
def _signed_bin(n):
"""Transform n into an optimized signed binary representation"""
r = []
while n > 1:
if n & 1:
cp = _gbd(n + 1)
cn = _gbd(n - 1)
if cp > cn: # -1 leaves more zeroes -> subtract -1 (= +1)
r.append(-1)
n +=... | 5,335,041 |
def hurricanes():
"""Manages hurricanes indices"""
pass | 5,335,042 |
def load_tests(loader, tests, pattern):
"""Provide a TestSuite to the discovery process."""
test_dir = os.path.join(os.path.dirname(__file__), name)
return driver.build_tests(test_dir, loader,
host=data['host'],
port=data['port'],
... | 5,335,043 |
def powderfit(powder, scans=None, peaks=None, ki=None, dmono=3.355,
spacegroup=1):
"""Fit powder peaks of a powder sample to calibrate instrument wavelength.
First argument is either a string that names a known material (currently
only ``'YIG'`` is available) or a cubic lattice parameter. Th... | 5,335,044 |
def replace_me(value, as_comment=False):
"""
** ATTENTION **
CALLING THIS FUNCTION WILL MODIFY YOUR SOURCE CODE. KEEP BACKUPS.
Replaces the current souce code line with the given `value`, while keeping
the indentation level. If `as_comment` is True, then `value` is inserted
as a Python comment ... | 5,335,045 |
def get_neighbor_v6_by_ids(obj_ids):
"""Return NeighborV6 list by ids.
Args:
obj_ids: List of Ids of NeighborV6's.
"""
ids = list()
for obj_id in obj_ids:
try:
obj = get_neighbor_v6_by_id(obj_id).id
ids.append(obj)
except exceptions.NeighborV6DoesNot... | 5,335,046 |
def decode_b64_to_image(b64_str: str) -> [bool, np.ndarray]:
"""解码base64字符串为OpenCV图像, 适用于解码三通道彩色图像编码.
:param b64_str: base64字符串
:return: ok, cv2_image
"""
if "," in b64_str:
b64_str = b64_str.partition(",")[-1]
else:
b64_str = b64_str
try:
img = base64.b64decode(b64_... | 5,335,047 |
def check_propag_dists(dims, dx, t, v_min, v_max, f_min, f_max):
"""
Calculate propagation distance across
the model covered by the fastest waves.
Parameters
----------
dims : tuple
dx : float
Size of the spatial grid cell [m].
t : s
f_min : float
Min. frequency present in the source fun... | 5,335,048 |
def _get_index_videos(course, pagination_conf=None):
"""
Returns the information about each video upload required for the video list
"""
course_id = str(course.id)
attrs = [
'edx_video_id', 'client_video_id', 'created', 'duration',
'status', 'courses', 'transcripts', 'transcription_s... | 5,335,049 |
def launch_emulator_win(emulator_id='Pixel_4_API_26', debug=False):
"""
This for **Windows OS**
The Function will launch the emulator for testing if needed.
If id is not explicitly provided then the default *Pixel-4 emulator with API 26* will launch.
:param emulator_id: pass id of the emulator ... | 5,335,050 |
def get_user_by_api_key(api_key, active_only=False):
"""
Get a User object by api_key, whose attributes match those in the database.
:param api_key: API key to query by
:param active_only: Set this flag to True to only query for active users
:return: User object for that user ID
:raises UserDoe... | 5,335,051 |
def get_pixel_values_of_line(img, x0, y0, xf, yf):
"""
get the value of a line of pixels.
the line defined by the user using the corresponding first and last
pixel indices.
Parameters
----------
img : np.array.
image on a 2d np.array format.
x0 : int
raw number of the st... | 5,335,052 |
def _filter_out_variables_not_in_dataframe(X, variables):
"""Filter out variables that are not present in the dataframe.
Function removes variables that the user defines in the argument `variables`
but that are not present in the input dataframe.
Useful when ussing several feature selection procedures... | 5,335,053 |
def file_format(input_files):
"""
Takes all input files and checks their first character to assess
the file format. 3 lists are return 1 list containing all fasta files
1 containing all fastq files and 1 containing all invalid files
"""
fasta_files = []
fastq_files = []
invalid_files = [... | 5,335,054 |
def autodiscover():
"""
Goes and imports the permissions submodule of every app in INSTALLED_APPS
to make sure the permission set classes are registered correctly.
"""
global LOADING
if LOADING:
return
LOADING = True
import imp
from django.conf import settings
for app i... | 5,335,055 |
def sub_vector(v1: Vector3D, v2: Vector3D) -> Vector3D:
"""Substract vector V1 from vector V2 and return resulting Vector.
Keyword arguments:
v1 -- Vector 1
v2 -- Vector 2
"""
return [v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2]] | 5,335,056 |
def create_validity_dict(validity_period):
"""Convert a validity period string into a dict for issue_certificate().
Args:
validity_period (str): How long the signed certificate should be valid for
Returns:
dict: A dict {"Value": number, "Type": "string" } representation of the
... | 5,335,057 |
def analyse_latency(cid):
"""
Parse the resolve_time and download_time info from cid_latency.txt
:param cid: cid of the object
:return: time to resolve the source of the content and time to download the content
"""
resolve_time = 0
download_time = 0
with open(f'{cid}_latency.txt', 'r') a... | 5,335,058 |
def run_module():
"""
Main Ansible module function
"""
# Module argument info
module_args = {
'facts': {
'type': 'bool',
'required': False,
'default': FACTS_DEFAULT
},
'facts_verbose': {
'type': 'boo... | 5,335,059 |
def process_ref(paper_id):
"""Attempt to extract arxiv id from a string"""
# if user entered a whole url, extract only the arxiv id part
paper_id = re.sub("https?://arxiv\.org/(abs|pdf|ps)/", "", paper_id)
paper_id = re.sub("\.pdf$", "", paper_id)
# strip version
paper_id = re.sub("v[0-9]+$", ... | 5,335,060 |
def augment_test_func(test_func):
"""Augment test function to parse log files.
`tools.create_tests` creates functions that run an LBANN
experiment. This function creates augmented functions that parse
the log files after LBANN finishes running, e.g. to check metrics
or runtimes.
Note: The naiv... | 5,335,061 |
def test_invoice_get_invoices(session):
"""Assert that get_invoices works."""
payment_account = factory_payment_account()
payment = factory_payment()
payment_account.save()
payment.save()
i = factory_invoice(payment_id=payment.id, account_id=payment_account.id)
i.save()
invoices = Invoi... | 5,335,062 |
def get_cuda_arch_flags(cflags):
"""
For an arch, say "6.1", the added compile flag will be
``-gencode=arch=compute_61,code=sm_61``.
For an added "+PTX", an additional
``-gencode=arch=compute_xx,code=compute_xx`` is added.
"""
# TODO(Aurelius84):
return [] | 5,335,063 |
def nstep_td(env, pi, alpha=1, gamma=1, n=1, N_episodes=1000,
ep_max_length=1000):
"""Evaluates state-value function with n-step TD
Based on Sutton/Barto, Reinforcement Learning, 2nd ed. p. 144
Args:
env: Environment
pi: Policy
alpha: Step size
gamma: Discount facto... | 5,335,064 |
def open_file(path):
"""more robust open function"""
return open(path, encoding='utf-8') | 5,335,065 |
def main():
"""Create the README.md file from template and code documentation."""
shell_commands, shell_commands_toc = _create_commands_docs()
configuration, configuration_toc = _create_configuration_docs()
print(f"Rendering documentation for v{VERSION}")
output = templating.render(
"../doc... | 5,335,066 |
def test_subscribe(env):
"""Check async. interrupt if a process terminates."""
def child(env):
yield env.timeout(3)
return 'ohai'
def parent(env):
child_proc = env.process(child(env))
subscribe_at(child_proc)
try:
yield env.event()
except Interru... | 5,335,067 |
def _run(data_iterator, iterations):
"""ループして速度を見るための処理。"""
with tk.utils.tqdm(total=batch_size * iterations, unit="f") as pbar:
while True:
for X_batch, y_batch in data_iterator:
assert len(X_batch) == batch_size
assert len(y_batch) == batch_size
... | 5,335,068 |
def has_flag(compiler, flagname):
"""Return a boolean indicating whether a flag name is supported on
the specified compiler.
"""
import tempfile
fd, fname = tempfile.mkstemp('.cpp', 'main', text=True)
with os.fdopen(fd, 'w') as f:
f.write('int main (int argc, char **argv) { return 0; }')... | 5,335,069 |
def _parse_data(f, dtype, shape):
"""Parses the data."""
dtype_big = np.dtype(dtype).newbyteorder(">")
count = np.prod(np.array(shape))
# See: https://github.com/numpy/numpy/issues/13470
use_buffer = type(f) == gzip.GzipFile
if use_buffer:
data = np.frombuffer(f.read(), dtype_big, count)... | 5,335,070 |
def test_target(target # type: Any
):
"""
A simple decorator to declare that a case function is associated with a particular target.
>>> @test_target(int)
>>> def case_to_test_int():
>>> ...
This is actually an alias for `@case_tags(target)`, that some users may find a bit... | 5,335,071 |
def plot_spatial(adata, color, img_key="hires", show_img=True, **kwargs):
"""Plot spatial abundance of cell types (regulatory programmes) with colour gradient
and interpolation (from Visium anndata).
This method supports only 7 cell types with these colours (in order, which can be changed using reorder_cma... | 5,335,072 |
def stats_by_group(df):
"""Calculate statistics from a groupby'ed dataframe with TPs,FPs and FNs."""
EPSILON = 1e-10
result = df[['tp', 'fp', 'fn']].sum().reset_index().assign(
precision=lambda x: (x['tp'] + EPSILON) /
(x['tp'] + x['fp'] + EPSILON),
recall=lambda x: (x['tp'] ... | 5,335,073 |
def uncolorize(text):
""" Attempts to remove color and reset flags from text via regex pattern
@text: #str text to uncolorize
-> #str uncolorized @text
..
from redis_structures.debug import uncolorize
uncolorize('\x1b[0;34mHello world\x1b[1;m')
# -> 'He... | 5,335,074 |
def in_this_prow(prow):
"""
Returns a bool describing whether this processor inhabits `prow`.
Args:
prow: The prow.
Returns:
The bool.
"""
return prow == my_prow() | 5,335,075 |
def _keypair_from_file(key_pair_file: str) -> Keypair:
"""Returns a Solana KeyPair from a file"""
with open(key_pair_file) as kpf:
keypair = kpf.read()
keypair = keypair.replace("[", "").replace("]", "")
keypair = list(keypair.split(","))
keypair = [int(i) for i in keypair]
r... | 5,335,076 |
def val_to_bitarray(val, doing):
"""Convert a value into a bitarray"""
if val is sb.NotSpecified:
val = b""
if type(val) is bitarray:
return val
if type(val) is str:
val = binascii.unhexlify(val.encode())
if type(val) is not bytes:
raise BadConversion("Couldn't get... | 5,335,077 |
def unpack_uint64_from(buf, offset=0):
"""Unpack a 64-bit unsigned integer from *buf* at *offset*."""
return _uint64struct.unpack_from(buf, offset)[0] | 5,335,078 |
def del_none(dictionary):
"""
Recursively delete from the dictionary all entries which values are None.
Args:
dictionary (dict): input dictionary
Returns:
dict: output dictionary
Note:
This function changes the input parameter in place.
"""
for key, value in list(dic... | 5,335,079 |
def get_model(model_dir, suffix=""):
"""return model file, model spec object, and list of extra data items
this function will get the model file, metadata, and extra data
the returned model file is always local, when using remote urls
(such as v3io://, s3://, store://, ..) it will be copied locally.
... | 5,335,080 |
def test_attached_solr_export_records(et_code, rset_code, basic_exporter_class,
record_sets, new_exporter,
assert_all_exported_records_are_indexed):
"""
For AttachedRecordExporter classes that load data into Solr, the
`export_record... | 5,335,081 |
def get_table_header(driver):
"""Return Table columns in list form """
header = driver.find_elements(By.TAG_NAME, value= 'th')
header_list = [item.text for index, item in enumerate(header) if index < 10]
return header_list | 5,335,082 |
def ref_count() -> Callable[[ConnectableObservable], Observable]:
"""Returns an observable sequence that stays connected to the
source as long as there is at least one subscription to the
observable sequence.
"""
from rx.core.operators.connectable.refcount import _ref_count
return _ref_count() | 5,335,083 |
async def test_edit():
"""Test editing a paste."""
p = create_paste("test_edit")
with pytest.raises(ValueError):
await p.edit(content="NI")
content = p.content
token = await p.save(site=TEST_SITE)
assert p.id is not None
assert p._token == token
await p.edit(get_content("test_ed... | 5,335,084 |
def teach(fn, collection):
"""Concurrently digest each item in the collection with
the provided function.
>>> tmap(save_to_disk, documents)
"""
threads = [threading.Thread(target=fn, args=(item,)) for item in collection]
each("start", threads)
each("join", threads) | 5,335,085 |
def no_dry_run(f):
"""A decorator which "disables" a function during a dry run.
A can specify a `dry_run` option in the `devel` section of `haas.cfg`.
If the option is present (regardless of its value), any function or
method decorated with `no_dry_run` will be "disabled." The call will
be logged (... | 5,335,086 |
def radius_provider_modify(handle, name, **kwargs):
"""
modifies a radius provider
Args:
handle (UcsHandle)
name (string): radius provider name
**kwargs: key-value pair of managed object(MO) property and value, Use
'print(ucscoreutils.get_meta_info(<classid>).confi... | 5,335,087 |
def main():
""" Main function. """
logging.basicConfig(level=logging.INFO)
args = parse_args()
logging.info(f'Commandline:\n{" ".join(sys.argv)}')
cfg = Config.fromfile(args.config)
update_config = f' --update_config {args.update_config}' if args.update_config else ''
if is_clustering_ne... | 5,335,088 |
async def test_failed_to_log_in(mock_login, mock_logout, hass):
"""Testing exception at login results in False."""
from pexpect import exceptions
conf_dict = {
DOMAIN: {
CONF_PLATFORM: "unifi_direct",
CONF_HOST: "fake_host",
CONF_USERNAME: "fake_user",
... | 5,335,089 |
def _read_table(table_node):
"""Return a TableData object for the 'table' element."""
header = []
rows = []
for node in table_node:
if node.tag == "th":
if header:
raise ValueError("cannot handle multiple headers")
elif rows:
raise ValueErr... | 5,335,090 |
def test_cascade_action_record_delete(app, db, location, record, generic_file,
force, num_of_recordbuckets):
"""Test cascade action on record delete, with force false."""
record_id = record.id
bucket_id = record.files.bucket.id
# check before
assert len(Records... | 5,335,091 |
def postorder(root: Node):
"""
Post-order traversal visits left subtree, right subtree, root node.
>>> postorder(make_tree())
[4, 5, 2, 3, 1]
"""
return postorder(root.left) + postorder(root.right) + [root.data] if root else [] | 5,335,092 |
def merge_triangulations(groups):
"""
Each entry of the groups list is a list of two (or one) triangulations.
This function takes each pair of triangulations and combines them.
Parameters
----------
groups : list
List of pairs of triangulations
Returns
-------
... | 5,335,093 |
def make_vrt_list(feat_list, band=None):
"""
take a list of stac features and band(s) names and build gdal
friendly vrt xml objects in list.
band : list, str
Can be a list or string of name of band(s) required.
"""
# imports
from lxml import etree as et
from rasterio.crs imp... | 5,335,094 |
def make_dataset(list_file, outdir, categories_path, featurizer_path, sample_rate, window_size, shift, auto_scale=True,
noise_path=None, max_noise_ratio=0.1, noise_selection=0.1, use_cache=False):
"""
Create a dataset given the input list file, a featurizer, the desired .wav sample rate,
c... | 5,335,095 |
def compute_relative_pose(cam_pose, ref_pose):
"""Compute relative pose between two cameras
Args:
cam_pose (np.ndarray): Extrinsic matrix of camera of interest C_i (3,4).
Transforms points in world frame to camera frame, i.e.
x_i = C_i @ x_w (taking into account homogeneous dime... | 5,335,096 |
def add_execute_parser(execute):
"""
``execute`` command parser configuration
"""
execute.add_argument(
'-d', '--deployment-id',
required=True,
help='A unique ID for the deployment')
execute.add_argument(
'-w', '--workflow',
dest='workflow_id',
help='T... | 5,335,097 |
def compat_chr(item):
"""
This is necessary to maintain compatibility across Python 2.7 and 3.6.
In 3.6, 'chr' handles any unicode character, whereas in 2.7, `chr` only handles
ASCII characters. Thankfully, the Python 2.7 method `unichr` provides the same
functionality as 3.6 `chr`.
:param item... | 5,335,098 |
def cli_cosmosdb_cassandra_table_update(client,
resource_group_name,
account_name,
keyspace_name,
table_name,
default_tt... | 5,335,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.