content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def multiclass_jaccard_loss_softmax(logits, labels, weight_class_sample_prob=False, weight_class_global_prob=False, train_class_probs=None, name='loss'):
""" multiclass Jaccard loss measure, softmax is applied internally on the y_preds
Args:
logits the predicted logits with shape [batchsize, ..., c... | 5,297,900 |
def encrypteddatadecoder(data):
"""
parses EncryptedData object
yields (algorithm-oid, iv, itercount, data)
"""
t, l, v = get_tlv(data)
version, content = der_decode(v)
ctyp, algo, content = der_decode(content[1])
algoid, params = der_decode(algo[1])
iv, itercount = der_decode(params... | 5,297,901 |
def get_testbed_vars():
"""
returns the testbed variables in a dictionary
:return: testbed variables dictionary
:rtype: dict
"""
return getwa().get_testbed_vars() | 5,297,902 |
def sign_user(user_data, fields=None):
"""Sign user data."""
signer = Signer(current_app.config['SECRET_KEY'], salt='newdle-users')
return dict(
user_data,
signature=signer.get_signature(
_get_signature_source_bytes(user_data, fields)
).decode('ascii'),
) | 5,297,903 |
def svn_repos_parse_dumpstream3(*args):
"""svn_repos_parse_dumpstream3(svn_stream_t * stream, svn_repos_parse_fns3_t parse_fns, void * parse_baton, svn_boolean_t deltas_are_text, svn_cancel_func_t cancel_func, apr_pool_t pool) -> svn_error_t"""
return _repos.svn_repos_parse_dumpstream3(*args) | 5,297,904 |
def decode_string_six_bits(binary: str, max_chars: int) -> str:
"""Decode binary string by decoding every sequence of six bits.
Args:
binary (str): Binary string
max_chars (int): Maximum length of resulting string
Raises:
ConvertException: Resulting string too large
Returns:
... | 5,297,905 |
def apply_scbc(ds, mizuroute_exe, bmorph_config, client=None, save_mults=False, **tqdm_kwargs):
"""
Applies Spatially Consistent Bias Correction (SCBC) by
bias correcting local flows and re-routing them through
mizuroute. This method can be run in parallel by providing
a `dask client`.
Paramete... | 5,297,906 |
def whois(ip_address):
"""Whois client for Python"""
whois_ip = str(ip_address)
try:
query = socket.gethostbyname(whois_ip)
except Exception:
query = whois_ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("whois.ripe.net", 43))
s.send(query.encode("utf8") +... | 5,297,907 |
def get_interesting_columns_all2D(datapath, column_indices, number_of_spectra,
n_rows):
"""
This will return a LIST of 2D DATA SETS. Each 2D spectrum in the list
will just be from the columns chosen by the user.
"""
n_columns = len(column_indices)
all_relevant... | 5,297,908 |
def oned_bump_combined():
"""
display all 1d traveling bump figures in one.
"""
fig = plt.figure(figsize=(10,4))
"""
oned_const_vel
#(oned_const_vel_bump,[],['oned_const_vel_bump_fig.pdf']),
"""
############################################################################... | 5,297,909 |
def canonicalize_RefCityCountyCode(apps, schema_editor):
"""Update existing city and county names to canonicalized form."""
RefCityCountyCode.canonicalize() | 5,297,910 |
def get_det_coords(size: int, spacing: float) -> np.ndarray:
"""Compute pixel-center positions for 2D detector
The centers of the pixels of a detector are usually not aligned to
a pixel grid. If we center the detector at the origin, odd images
will have a pixel at zero, whereas even images will have tw... | 5,297,911 |
def inverse_document_frequency(word, document_number, document_frequency):
"""Calculate idf value of a word
Args:
word: the word to be scored.
document_number: number of documents in dataset.
document_frequency: Frequency of a word in documents dataset, i.e.
if a document ha... | 5,297,912 |
def str_to_acemask(lvl, is_object):
"""Return the acemask from a simplified access level
:param lvl: the access level to map, in "none, "read", "write" or
"read/write"
:type lvl: str
:param is_object: defined if the level corresponds to a data object or a
coll... | 5,297,913 |
def main(bibtex, html, no_overwrite):
"""
Given paths to a BIBTEX and HTML file, program will find all instances of "\cite{}" within <p> tags
and replace with a link to the DOI / URL in the bibtex entry.
"""
# Check files exist
for input_file in [bibtex, html]:
assert os.path.exists(inpu... | 5,297,914 |
def min_probabilities(p=0.0):
"""
!! OBSOLETE FUNCTION !!
:param p: p percentage, int(0 < p < 1)
:return: list of families with min(can be tuned) probabilities larger than p
"""
min_prob = []
with open(saved_feature_path + '/prob_of_each_sample_25families', 'rb') as fp:
prob = pickl... | 5,297,915 |
def BRANCH_DESCRIPTOR(
project: ProjectHandle,
branch: BranchHandle,
urls: Optional[UrlFactory]
) -> Dict[str, Any]:
"""Dictionary serialization for branch descriptor.
Parameters
----------
project: vizier.engine.project.base.ProjectHandle
Handle for the containing... | 5,297,916 |
def evaluate_lenet5(train_set_x, train_set_y, valid_set_x, valid_set_y, test_set_x, test_set_y,
learning_rate=0.1, n_epochs=10,
nkerns=[20, 50], batch_size=BATCH_SIZE):
""" Demonstrates lenet on MNIST dataset
:type learning_rate: float
:param learning_rate: learning ... | 5,297,917 |
def check_se(se):
"""
Ensure that standard error is a float greater than zero.
Parameters
----------
se : float
a float with the standard error of the restricted regression.
Returns
-------
"""
if (type(se) is not float and type(se) is not int) or se < 0:
sys.exit(... | 5,297,918 |
def require_volume_exists(f):
"""Decorator to require the specified volume to exist.
Requres the wrapped function to use context and volume_id as
their first two arguments.
"""
def wrapper(context, volume_id, *args, **kwargs):
db.api.volume_get(context, volume_id)
return f(context,... | 5,297,919 |
def longitudinal_distance(reference: StateSE2, other: Point2D) -> float:
"""
Longitudinal distance from a point to a reference pose
:param reference: the reference pose
:param other: the query point
:return: the longitudinal distance
"""
return float(
np.cos(reference.heading) * (oth... | 5,297,920 |
def _log_bessel_kve_bwd(aux, g):
"""Reverse mode impl for bessel_kve."""
v, z = aux
dtype = dtype_util.common_dtype([v, z], tf.float32)
numpy_dtype = dtype_util.as_numpy_dtype(dtype)
log_kve = _log_bessel_kve_custom_gradient(v, z)
grad_z = tfp_math.log_add_exp(
_log_bessel_kve_custom_gradient(v - 1.,... | 5,297,921 |
def send_message_via_backend(msg, backend=None, orig_phone_number=None):
"""send sms using a specific backend
msg - outbound message object
backend - MobileBackend object to use for sending; if None, use
msg.outbound_backend
orig_phone_number - the originating phone number to use when sending; th... | 5,297,922 |
def check(text):
"""Check the text."""
err = "misc.bureaucratese"
msg = "'{}' is bureaucratese."
bureaucratese = [
"meet with your approval",
"meets with your approval",
]
return existence_check(text, bureaucratese, err, msg, join=True) | 5,297,923 |
def main(model_name='map_learning', exp_name='localization_all_maps', azimuth=12, snr=0.2, freq_bands=24, max_freq=20000, elevations=25, mean_subtracted_map=True, ear='ipsi', n_trials=100, normalization_type='sum_1', sigma_smoothing=0, sigma_gauss_norm=1, clean=False):
""" Learns the elevation spectra map gradually... | 5,297,924 |
def create_label_colormap(no_class=7, dataset=None):
"""Creates a label colormap used in Cityscapes segmentation benchmark.
Returns:
A Colormap for visualizing segmentation results.
"""
# GTA 19 Classes
if (dataset == 'GTA') or ( no_class == 19) :
colormap = np.array([
#... | 5,297,925 |
def confirm_current_token(token_type: str, revoked: bool = True) -> User:
"""
验证token
:param jti: str jti字符串
:param token_type: str token类型
:param revoked 是否撤销token
:return (state, user)
"""
try:
jti = get_raw_jwt()["jti"]
token = TokenBlackList.where(jti=jti, token_type... | 5,297,926 |
def rotate_image(img, max_rot_angle, dim=32):
"""Rotate image."""
# Pad image
padding = int(dim * 1.5)
padded_img, (x1, y1) = pad_image(img, padding=padding)
# Rotate image
rotation_deg = np.random.uniform(-max_rot_angle, max_rot_angle)
x_np = padded_img.permute(1, 2, 0).numpy()
x_np = ndimage.rotate(x... | 5,297,927 |
def test_deploy_raiden_save_info_false(mock_deploy, mock_verify, get_accounts, get_private_key):
""" Calling deploy raiden command with --save_info False"""
(signer,) = get_accounts(1)
priv_key = get_private_key(signer)
with NamedTemporaryFile() as privkey_file:
privkey_file.write(bytearray(priv... | 5,297,928 |
def simplify_control(A, B, x0, u0):
"""
Given the linarized A and B matrices corresponding to the state:
x = [u, v, w, p, q, r, phi, th, dpsi, x_r, y_r, z_r]
u = [T, a, e, r]
this function simplifies the model to assume the body rates p, q, r
are directly controlled, by essentially just removing the ro... | 5,297,929 |
def hdot_chart_line(datum: int) -> str:
"""Produce one line of a dot chart (without the label)."""
return lit.HDOT_ONE * datum | 5,297,930 |
def move_cursor(user):
"""行動予定表内で、指定した人の位置にカーソルを移動"""
tn.write('R{}\n'.format(userdata.userdata[user][1]))
tn.write('C0\n')
#print('R{}\n'.format(userdata.userdata[user][1]))
#print('C0\n') | 5,297,931 |
def align_features_to_words(roberta, features, alignment):
"""
Align given features to words. Without assert.
Args:
roberta (RobertaHubInterface): RoBERTa instance
features (torch.Tensor): features to align of shape `(T_bpe x C)`
alignment: alignment between BPE tokens and words ret... | 5,297,932 |
def img_one_day(request, date):
"""
get one-day detected faces
:param request:http request
:param date: the day client chose
:return:url list of one-day detected faces, formatted with JSon
"""
result_list = reader.get_one_day_img(date)
return HttpResponse(json.dumps(result_list)) | 5,297,933 |
def prepare(model_name):
"""Run all steps to prepare the environment before a functional test run.
:param model: Name of model to add
:type bundle: str
"""
zaza.controller.add_model(
model_name,
config=deployment_env.get_model_settings(),
region=deployment_env.get_cloud_regi... | 5,297,934 |
def do_targets(
subparsers,
parent, # type: argparse.ArgumentParser
completer, # type: CompositeActionCompletionFinder
): # type: (...) -> None
"""Command line parsing for all `coverage analyze targets` commands."""
targets = subparsers.add_parser(
'targets',
help='ana... | 5,297,935 |
def get_date_age(date):
"""
Take a datetime and return its "age" as a string.
The age can be in second, minute, hour, day, month or year. Only the
biggest unit is considered, e.g. if it's 2 days and 3 hours, "2 days" will
be returned.
Make sure date is not in the future, or else it won't work.
... | 5,297,936 |
def SubtractHistogram(histogram_json, start_histogram_json):
"""Subtracts a previous histogram from a histogram. Both parameters are json
serializations of histograms."""
start_histogram = json.loads(start_histogram_json)
# It's ok if the start histogram is empty (we had no data, maybe even no
# histogram at ... | 5,297,937 |
def lev_from_alignment(x_y_alignment_list, lengths):
"""
Given a list of aligned pairs and a list of lengths, computes the
Levenshtein for each pair in the list. Returns a list of distances.
:param x_y_alignment_list: a list where each element is itself a list
containing tuples representing the... | 5,297,938 |
def get_shortest_path_lengths(G: nx.Graph, origin_nodes: list, destination_nodes: list, weight: str):
"""
This function calculates the shortest paths based on weight parameter.
---
Args:
origin_nodes (list): list of origin nodes
destination_nodes (list): list of destination nodes
... | 5,297,939 |
def do_performance_metric_get_hsm_summary(cs, args):
"""Gets hsm summary."""
performance_metric = cs.performance_metrics.get_hsm_summary()
if isinstance(performance_metric, dict):
utils.print_dict(performance_metric)
else:
utils.print_dict(performance_metric._info) | 5,297,940 |
def evaluateAllQuestions(groundtruth_list, predictions_list):
""" Prints classification report for all questions
Parameters
----------
groundtruth_list :
list of event tuples for all questions
predictions_list :
list of event tuples for all questions
"""
questions = ["Type 1... | 5,297,941 |
def _front_left_tire_pressure_supported(data):
"""Determine if front left tire pressure is supported."""
return data["status"]["tirePressure"]["frontLeftTirePressurePsi"] is not None | 5,297,942 |
def display_error(error_message):
"""Display an error message and exit.
@param error_message: the error message to be displayed
"""
print(f"[bold red][ ERROR ]:[/bold red] {error_message}")
exit(-1) | 5,297,943 |
def index_exists(name: str) -> bool:
"""
Check if an index with this name exists
"""
return es.indices.exists(index=name) | 5,297,944 |
def sslwrap_simple (sock, keyfile=None, certfile=None):
"""A replacement for the old socket.ssl function. Designed
for compability with Python 2.5 and earlier. Will disappear in
Python 3.0."""
ssl_sock = _ssl.sslwrap(sock._sock, 0, keyfile, certfile, CERT_NONE,
PROTOCOL_S... | 5,297,945 |
def test_boutiques_spec_2():
""" testing spec: providing partial input/output fields names"""
btask = BoshTask(
name="NA",
zenodo_id="1482743",
infile=Infile,
maskfile="test_brain.nii.gz",
input_spec_names=["infile"],
output_spec_names=[],
)
assert len(bt... | 5,297,946 |
def count_missing_doc_types(articles):
"""
:param articles A PyMongo collection of articles
:return: int: Number or articles without a a 'doc_type' property or having
it equal to the empty string ('')
"""
return articles.count_documents(
{"$or": [{"doc_type": {"$exists": False}}, {"doc_t... | 5,297,947 |
def assert_equal(actual: Literal["numeric"], desired: Literal["numeric"]):
"""
usage.scipy: 4
"""
... | 5,297,948 |
def segment_length(p1 : np.ndarray, p2 : np.ndarray):
"""
p1 (2,)
p2 (2,)
"""
return npla.norm(p2-p1) | 5,297,949 |
def get_file_messages(fn, verbosity=0):
"""Returns a list of messages from an individual JSON file"""
channel = path.basename(path.dirname(fn))
msgs = []
for conv in load(open(fn)):
if conv['type'] == 'message' and 'text' in conv and conv['text'] and 'client_msg_id' in conv:
id, user... | 5,297,950 |
def calculate_average(storage):
"""
Function prototype:
calculate_average(storage)
Function parameters (required):
storage - a list of tuples with RGB values; this list will be iterated and, using the values obtained,
will find the average RGB value
Function parameters ... | 5,297,951 |
def parse_args():
""" Parses the arguments of the command line """
parser = argparse.ArgumentParser(
description="Checks a file for british and american spellings")
parser.add_argument('files', metavar="files", type=str, nargs='+',
help='file where to check the spellings')
retu... | 5,297,952 |
def update():
""" """
lan_object = Languages()
lan_object.update()
message = lan_object.message
status = lan_object.status
data = {
"success": True,
}
return data | 5,297,953 |
def convert_keras(model, name=None, doc_string='', target_opset=None,
channel_first_inputs=None, debug_mode=False, custom_op_conversions=None):
# type: (keras.Model, str, str, int, [], bool, {}) -> onnx.ModelProto
"""
:param model: keras model
:param name: the converted onnx model inte... | 5,297,954 |
def combineSeries(series, methods=MethodType.Unknown, reverse=False, squeeze=False, warn=True, shapeTolerance=0.01,
spacingTolerance=0.1):
"""Combines a series into an N-D Numpy array and returns some information about the volume
Many of the parameters are from the :meth:`sortSeries` function... | 5,297,955 |
def now_int():
"""
Returns the current POSIX time as an integer.
:return: integer POSIX time
"""
now = datetime.now() - datetime(1970, 1, 1)
return int(now.total_seconds()) | 5,297,956 |
def gradient_pred(model, ref, ref_rc, alt, alt_rc, mutation_positions, out_annotation_all_outputs,
output_filter_mask=None, out_annotation=None):
"""Gradient-based (saliency) variant effect prediction
Based on the idea of [saliency maps](https://arxiv.org/pdf/1312.6034.pdf) the gradient-based... | 5,297,957 |
def compute_fid_from_activations(fake_activations, real_activations):
"""Returns the FID based on activations.
Args:
fake_activations: NumPy array with fake activations.
real_activations: NumPy array with real activations.
Returns:
A float, the Frechet Inception Distance.
"""
logging.info("Comput... | 5,297,958 |
def test_wrong_union_nested_in_optional(
assert_errors,
parse_ast_tree,
code,
annotation_template,
default_options,
mode,
):
"""Ensures that `Union` nested in `Optional` annotations are forbidden."""
tree = parse_ast_tree(mode(annotation_template.format(code)))
visitor = SemanticAnn... | 5,297,959 |
def _load_defaults() -> None:
"""
Pulls the defaults from the QCA folder
"""
# Find the config
load_path = None
test_paths = [os.getcwd(), os.path.join(os.path.expanduser('~'), ".qcarchive")]
if "DQM_CONFIG_PATH" in os.environ:
test_paths.insert(0, os.environ["DQM_CONFIG_PATH"])
... | 5,297,960 |
def homoRunForOneVariant(chr_fa_seq, variant):
"""
Calculate and return the length of the largest homopolymer
touching this variant. Compute homopolymer lengths on the
left and right, and return the largest.
Args:
chr_fa_seq: A fasta sequence of chromosome in `varianti.CHROM`
varian... | 5,297,961 |
def _get_exon_junction_dict(metadata_list, strand):
""" Creates an auxiliary dictionary used for filtering. Assigns to each junction all overlapping exon pairs.
Parameters
----------
metadata_list: List(Output_metadata).
Returns
-------
exon_dict: dict. (read_frame, pos_mid_1, pos_mid_2, v... | 5,297,962 |
def handle_encoding_upload_json(project_id, dp_id, clk_json, receipt_token, uses_blocking, parent_span):
"""
Take user provided upload information - accepting multiple formats - and eventually
injest into the database.
Encodings uploaded directly in the JSON are first quarantined in the object store,
... | 5,297,963 |
def _align_dtypes(
df_a: pd.DataFrame, df_b: pd.DataFrame
) -> Tuple[List[int], pd.DataFrame, pd.DataFrame]:
"""Try to enforce the dtypes of non-object type of one dataframe
on the other. Return a list of index values for those columns
where it is not possible and the two dataframes (one of them
tra... | 5,297,964 |
def matrix_cfpq(
graph: nx.MultiDiGraph,
cfg: CFG,
start_nodes: Set[int] = None,
final_nodes: Set[int] = None,
start_variable: Variable = Variable("S"),
) -> Set[Tuple[int, int]]:
"""
Context-Free Path Querying based on matrix multiplication
Parameters
----------
graph: nx.Multi... | 5,297,965 |
def module_loaded(module):
"""
Checks if the specified kernel-module has been loaded.
:param module: Name of the module to check
:return: True if the module is loaded, False if not.
"""
return any(s.startswith(module) for s in open("/proc/modules").readlines()) | 5,297,966 |
def IsMonophyleticForTaxa(tree,
taxa,
support=None):
"""check if a tree is monophyletic for a list of taxa.
Arguments
---------
tree : :class:`Tree`
Tree to analyse
taxa : list
List of taxa
support : float
Minimum bo... | 5,297,967 |
def cleanfieldlower(value):
"""
remove spaces and convert to lower case
so flag error
"""
if not value:
return None
value = str(value)
value = value.strip()
value = value.lower()
return value | 5,297,968 |
def bs_preprocess(html):
"""remove distracting whitespaces and newline characters
(c) mail-group of beautifulsoup4"""
pat = re.compile('(^[\s]+)|([\s]+$)', re.MULTILINE)
html = re.sub(pat, '', html) # remove leading and trailing whitespaces
return html | 5,297,969 |
def query_done_cb(request, server_id):
"""
A callback for query completion notification. When the query is done,
BeeswaxServer notifies us by sending a GET request to this view.
"""
message_template = '<html><head></head>%(message)s<body></body></html>'
message = {'message': 'error'}
try:
query_histo... | 5,297,970 |
def get_user_info(request):
"""
A helper function which uses the user information in the request to get the Player object (which also contains the
user object).
:param request: A html request with user data (specifically username)
:return: None if no user found, otherwise the Player object.
"""... | 5,297,971 |
def enthalpyliq(temp=None,pres=None,dliq=None,chkvals=False,
chktol=_CHKTOL,temp0=None,pres0=None,dliq0=None,chkbnd=False,
mathargs=None):
"""Calculate ice-liquid liquid water enthalpy.
Calculate the specific enthalpy of liquid water for ice and liquid
water in equilibrium.
:arg temp: ... | 5,297,972 |
def dataset(directory, images_file, labels_file):
"""Download and parse MNIST dataset."""
images_file = download(directory, images_file)
labels_file = download(directory, labels_file)
check_image_file_header(images_file)
check_labels_file_header(labels_file)
def decode_image(image):
#... | 5,297,973 |
def summary(map: 'World') -> None:
"""Log how many territories each player has"""
ownership = defaultdict(lambda: 0) # type: 'Dict[str, int]'
for t in map.territories:
if t.owner:
ownership[t.owner.name] += 1
logger.info(dict(ownership)) | 5,297,974 |
def web3_get_code_sha256_hash(web3, addr):
"""
web3: Web3
addr: address in hex string
"""
code = web3.eth.getCode(to_checksum_address(addr))
return compute_code_sha256_hash(code) | 5,297,975 |
def complete_cluster(cluster: Cluster, host: Host) -> Cluster:
"""Add service, component and host to cluster"""
cluster.host_add(host)
service = cluster.service_add(name="first_service")
cluster.hostcomponent_set((host, service.component(name="first_service_component_1")))
return cluster | 5,297,976 |
def year_range(entry):
"""Show an interval of employment in years."""
val = ""
if entry.get("start_date") is None or entry["start_date"]["year"]["value"] is None:
val = "unknown"
else:
val = entry["start_date"]["year"]["value"]
val += "-"
if entry.get("end_date") is None or ent... | 5,297,977 |
def test_init(mock_main):
"""
Action : Test init call.
Expected Results : Init correctly called.
Returns: N/A.
"""
init()
mock_main.assert_called_once() | 5,297,978 |
def hamming_dist(a,b):
"""Return number of non-equal entries of a and b."""
return np.linalg.norm(a-b,ord=1) | 5,297,979 |
def find_images(directory: str, dest_ext: str, src_ext=None,
output_dir=None) -> None:
"""Examines a directory and returns images that can be converted
Arguments:
directory -- the directory to look for files in
dest_ext -- the extension that files should ahve after conversion
src_ex... | 5,297,980 |
def prepare_splitfile_sql(sql: str, image_mapper: Callable) -> Tuple[str, str]:
"""
Transform an SQL query to prepare for it to be used in a Splitfile SQL command and validate it.
The rules are:
* Only basic DDL (CREATE/ALTER/DROP table) and DML (SELECT/INSERT/UPDATE/DELETE) are permitted.
* Al... | 5,297,981 |
def grr_hostname(line):
"""Returns hostname of the selected client.
Args:
line: A string representing arguments passed to the magic command.
Returns:
String representing hostname of a client.
Raises:
NoClientSelectedError: Client is not selected to perform this operation.
"""
del line # Unus... | 5,297,982 |
def halo_bias(cosmo, halo_mass, a, overdensity=200):
"""Tinker et al. (2010) halo bias
Args:
cosmo (:obj:`Cosmology`): Cosmological parameters.
halo_mass (float or array_like): Halo masses; Msun.
a (float): Scale factor.
overdensity (float): Overdensity parameter (default: 200).... | 5,297,983 |
def main():
"""
Execute action from playbook
"""
command = NetAppONTAPCommand()
command.apply() | 5,297,984 |
def settlements(ctx, asset, limit):
""" Show pending settlement orders of a bitasset
"""
from bitshares.asset import Asset
asset = Asset(asset, full=True)
if not asset.is_bitasset:
print_message("{} is not a bitasset.".format(asset["symbol"]), "warning")
sys.exit(1)
calls = asse... | 5,297,985 |
def battery(data):
"""
Gets battery percentage from subscribed ROS topic and
converts it into a percentage out of 100.
"""
global batteryLevel
message_creator.batteryLevel = batteryLevel
# this function was found empirically through multiple tests
# with a turtlebot. It is an estimate... | 5,297,986 |
def test_targets():
"""Returns the test targets which contain the main package and tests folder
"""
return [package_name(), 'tests'] | 5,297,987 |
def advanceboundary(repo, tr, targetphase, nodes):
"""Add nodes to a phase changing other nodes phases if necessary.
This function move boundary *forward* this means that all nodes
are set in the target phase or kept in a *lower* phase.
Simplify boundary to contains phase roots only."""
phcache = ... | 5,297,988 |
def setup(bot: commands.Bot):
"""Initiate cog"""
bot.add_cog(InfoLookup(bot)) | 5,297,989 |
def LU_lndet(matrix, permutation, sign):
"""
Compute the determinant of {matrix} given its LU decomposition
"""
# easy enough
return gsl.linalg_LU_lndet(matrix.data) | 5,297,990 |
def _sample_household_cluster(sampler, bin_lower, bin_upper, reference_age, n):
"""
Return list of ages in a household/location based on mixing matrix and reference person age
"""
ages = [reference_age] # The reference person is in the household/location
if n > 1:
idx = np.digitize(refere... | 5,297,991 |
def genChirpVC(Vclamp=-70,Rm=100,amp=10,graphToo=False):
"""Create a voltage-clamp sine protocol.
Vclamp - center of clamped voltage (mV)
Rm - membrane resistance (Mohm)
amp - amplitude of sine (deviation Vclamp, in mV)
"""
xs,ys,zi=genSine()
ys=ys*amp+Vclamp
genATF(xs,ys,'stimulus-VC.atf')
graphData(... | 5,297,992 |
def extract_BIO_tagged_tokens(text, source_spans, tokenizer):
""" Разобьем на bio-токены по безпробельной разметке """
tokens_w_tags = []
for span in source_spans:
s,e,tag = span
tokens = tokenizer(text[s:e])
if tag == 'Other':
tokens_w_tags += [(token,ta... | 5,297,993 |
def delete_user(id):
"""Get a particular user with it's ID and delete it."""
user = Users.query.get(id)
if user.role_id is 1:
return jsonify({
"message": "YOU DON'T WANNA DO THAT! YOU CANT DELETE AN ADMIN",
"status": 400
}), 400
user.delete()
return jsonify({
... | 5,297,994 |
def test_saving_observables_with_callable_expression(dummy_hdf5_file: str):
"""
Tests that callable observables can be (de)serialized into and from a HDF5 file
Parameters
----------
dummy_hdf5_file: str
Path to the temporal file to use during the test
"""
dummy_callable = str
t... | 5,297,995 |
def run(cfg):
"""Main function."""
# Logging
# wandb.init(project=cfg.experiment_name)
# Creating working directory
if not os.path.exists(cfg.path):
os.makedirs(cfg.path)
# Getting the objects
torch.cuda.empty_cache()
if cfg.test_size != 0.0:
trainloader, valloader, te... | 5,297,996 |
def _wait_for_iscsi_daemon(attempts=10):
"""Wait for the ISCSI daemon to start."""
# here, iscsi daemon is considered not running in case
# tgtadm is not able to talk to tgtd to show iscsi targets
cmd = ['tgtadm', '--lld', 'iscsi', '--mode', 'target', '--op', 'show']
_execute(cmd, "ISCSI daemon didn... | 5,297,997 |
def find_ifgs_for_dates(ifg_dir, master_date, slc_dates=None):
"""Find all the interferograms for a set of SLC dates and a given master
date.
Arguments
---------
ifg_dir : str
The directory to search for interferograms. Interferograms should be
named as SLAVE_MASTER.nc where SLAVE and M... | 5,297,998 |
def configure_extensions(flask_app, cli):
"""configure flask extensions
"""
db.init_app(flask_app)
cors.init_app(flask_app)
db.app = flask_app
bcrypt.init_app(flask_app)
if cli is True:
migrate.init_app(flask_app, db)
return flask_app | 5,297,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.