content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def read_ult_meta(filebase):
"""Convenience fcn for output of targeted metadata."""
meta = _parse_ult_meta(filebase)
return (meta["NumVectors"],
meta["PixPerVector"],
meta["ZeroOffset"],
meta["Angle"],
meta["PixelsPerMm"],
meta["FramesPerSec"],
... | 18,400 |
def safe_identifiers_iterable(val_list: Iterable[str]) -> List[str]:
"""
Returns new list, all with safe identifiers.
"""
return [safe_identifier(val) for val in val_list] | 18,401 |
def encode_varint(value, write):
""" Encode an integer to a varint presentation. See
https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints
on how those can be produced.
Arguments:
value (int): Value to encode
write (function): Called per byte that needs ... | 18,402 |
def heap_sort(li):
""" [list of int] => [list of int]
Heap sort: divides its input into a sorted and an unsorted region,
and it iteratively shrinks the unsorted region by extracting the
largest element from it and inserting it into the sorted region.
It does not waste time with a linear-time scan of... | 18,403 |
def vector_field(v, t, inf_mat, state_meta):
"""vector_field returns the temporal derivative of a flatten state vector
:param v: array of shape (1,mmax+1+(nmax+1)**2) for the flatten state vector
:param t: float for time (unused)
:param inf_mat: array of shape (nmax+1,nmax+1) representing the infection... | 18,404 |
def newton(start, loss_fn, *args, lower=0, upper=None, epsilon=1e-9):
"""
Newton's Method!
"""
theta, origin, destination = args[0], args[1], args[2]
if upper is None:
upper = 1
start = lower
while True:
if loss_fn(start, theta, origin, destination) > 0:
start ... | 18,405 |
def eval_det_cls(pred, gt, iou_thr=None):
"""Generic functions to compute precision/recall for object detection for a
single class.
Args:
pred (dict): Predictions mapping from image id to bounding boxes \
and scores.
gt (dict): Ground truths mapping from image id to bounding box... | 18,406 |
def replace_images(fpath):
""" Takes a path to a note and edits the note to insert image data.
params:
fpath: path to note
Output: None, writes new note with image data
"""
with open(fpath, 'r') as f:
line1 = f.readline() # get rid of the first xml tag line
note = f.read()
... | 18,407 |
def parse_g2o(path: pathlib.Path, pose_count_limit: int = 100000) -> G2OData:
"""Parse a G2O file. Creates a list of factors and dictionary of initial poses."""
with open(path) as file:
lines = [line.strip() for line in file.readlines()]
pose_variables: List[jaxfg.geometry.LieVariableBase] = []
... | 18,408 |
def register_content_widgets(content_widgets):
""" Run custom add-on package installation code to add custom
site specific content widgets
@param content_widgets: Dictionary of custom content widgets
"""
widget_settings = api.portal.get_registry_record(
name='ade25.widgets.widget_settin... | 18,409 |
def find_stops(input_handle, output_handle, offset, compact):
"""Almost stop codon finder.
:arg stream input_handle: Open readable handle to a FASTA file.
:arg stream output_handle: Open writable handle to a file.
:arg int offset: Position of the CDS start in the reference sequence.
:arg bool compa... | 18,410 |
def _som_actor(env):
"""
Construct the actor part of the model and return it.
"""
nactions = np.product(env.action_shape)
model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=(1,) + env.observation_space.shape))
model.add(keras.layers.Dense(400))
model.add(keras.... | 18,411 |
def fido(ctx):
"""
Manage FIDO applications.
"""
try:
ctx.obj['controller'] = Fido2Controller(ctx.obj['dev'].driver)
except Exception as e:
logger.debug('Failed to load Fido2Controller', exc_info=e)
ctx.fail('Failed to load FIDO 2 Application.') | 18,412 |
def main():
"""
This is a simple wrapper for fugashi so you can test it from the command line.
Like the mecab binary, it treats each line of stdin as one sentence. You can
pass tagger arguments here too.
"""
args = ' '.join(sys.argv[1:])
# This should work if you specify a different diction... | 18,413 |
def sendEmail():
"""email sender"""
send_email('Registration ATS',
['manavshrivastava@hotmail.com'],
'Thanks for registering ATS!',
'<h3>Thanks for registering with ATS!</h3>')
return "email sent to manavshrivastava@hotmail.com... | 18,414 |
def Pvalue(chi2, df):
"""Returns the p-value of getting chi2 from a chi-squared distribution.
chi2: observed chi-squared statistic
df: degrees of freedom
"""
return 1 - scipy.stats.chi2.cdf(chi2, df) | 18,415 |
def _ya_testmatch_():
"""
test function the forest matching algorithm
basically this creates two graphs and associated
"""
c1 = np.array([[0],[-1],[1],[0.5],[1.5]])
parents = np.array([0, 0, 0, 2, 2])
g1 = fo.Forest(5,parents)
c2 = np.array([[-1],[1],[0.5],[1.5]]) #c1 + 0.0
parents... | 18,416 |
def template(template_lookup_key: str) -> str:
"""Return template as string."""
with open(template_path(template_lookup_key), "r") as filepath:
template = filepath.read()
return template | 18,417 |
def filter_rows(df, condition, reason):
"""
:param reason:
:param df:
:param condition: boolean, true for row to keep
:return: filter country_city_codes df
"""
n_dropped = (condition == False).sum()
print(
f"\nexcluding {n_dropped} locations ({n_dropped / df.shape[0]:.1%}) due to... | 18,418 |
def parse_projected_dos(f):
"""Parse `projected_dos.dat` output file."""
data = np.loadtxt(f)
projected_dos = {"frequency_points": data[:, 0], "projected_dos": data[:, 1:].T}
pdos = orm.XyData()
pdos_list = [pd for pd in projected_dos["projected_dos"]]
pdos.set_x(projected_dos["frequency_points"... | 18,419 |
def get_from_parameters(a, b, c, alpha, beta, gamma):
"""
Create a Lattice using unit cell lengths and angles (in degrees).
This code is modified from the pymatgen source code [1]_.
Parameters
----------
a : :class:`float`:
*a* lattice parameter.
b : :class:`float`:
*b* la... | 18,420 |
def random_chinese_name():
"""生成随机中文名字
包括的名字格式:2个字名字**,3个字名字***,4个字名字****
:return:
"""
name_len = random.choice([i for i in range(4)])
if name_len == 0:
name = random_two_name()
elif name_len == 1:
name = random_three_name()
elif name_len == 2:
name = random_thr... | 18,421 |
def copy_dir_with_s3(s3_old_path, s3_new_path, raise_when_no_exist=True):
"""Copies files from one S3 Path to another
Args:
s3_old_path(S3Path): Output path of the file to be uploaded
s3_new_path(S3Path): Output path of the file to be uploaded
raise_when_no_exist(bool, optional): Raise ... | 18,422 |
def power_list(lists: [list]) -> list:
""" power set across the options of all lists """
if len(lists) == 1:
return [[v] for v in lists[0]]
grids = power_list(lists[:-1])
new_grids = []
for v in lists[-1]:
for g in grids:
new_grids.append(g + [v])
return new_grids | 18,423 |
def send_email(from_email, to, subject, message, html=True):
"""
Send emails to the given recipients
:param from_email:
:param to:
:param subject:
:param message:
:param html:
:return: Boolean value
"""
try:
email = EmailMessage(subject, message, from_email, to)
p... | 18,424 |
def set_default_locale(code):
"""Sets the default locale, used in get_closest_locale().
The default locale is assumed to be the language used for all strings
in the system. The translations loaded from disk are mappings from
the default locale to the destination locale. Consequently, you don't
need... | 18,425 |
def attack(health, power, percent_to_hit):
"""Calculates health from percent to hit and power of hit
Parameters:
health - integer defining health of attackee
power - integer defining damage of attacker
percent to hit - float defining percent chance to hit of attacker
Returns: new h... | 18,426 |
def signal_requests_mock_factory(requests_mock: Mocker) -> Mocker:
"""Create signal service mock from factory."""
def _signal_requests_mock_factory(
success_send_result: bool = True, content_length_header: str = None
) -> Mocker:
requests_mock.register_uri(
"GET",
"h... | 18,427 |
def test_dwt_denoise_trace():
""" Check that sample data fed into dwt_denoise_trace() can be processed
and that the returned signal is reasonable (for just one trace)"""
# Loma Prieta test station (nc216859)
data_files, origin = read_data_dir('geonet', 'us1000778i', '*.V1A')
trace = []
trace = ... | 18,428 |
def get_networks(project_id=None,
auth_token=None):
"""
Get a list of all routed networks
"""
url = CATALOG_HOST + "/routednetwork"
try:
response_body = _api_request(url=url,
http_method="GET",
project... | 18,429 |
def main(url, out_path):
"""[summary]
Parameters
----------
url : string
URL to download zip file from (must be a zip file with no password)
out_path : string
Path to extract the zip file contents to
Example
----------
main(f"https://archive.ics.uci.edu/ml/machine-lear... | 18,430 |
def setup_module(mod):
"""Sets up the pytest environment."""
testsuite_run_time = time.asctime(time.localtime(time.time()))
logger.info("Testsuite start time: {}".format(testsuite_run_time))
logger.info("=" * 40)
logger.info("Running setup_module to create topology")
# This function initiates ... | 18,431 |
def click_event(event, x, y, flags, params):
"""
Crop an image based on the clicked detected face
"""
# event is triggered with a mouse click
if event == cv2.EVENT_LBUTTONUP:
for location in face_locations:
# unpack the coordinates from the location tuple
top, right... | 18,432 |
def _download_(args):
""" To be used within _ZTFDownloader_.download_data()
url, fileout,overwrite,verbose = args
"""
url, fileout, overwrite, verbose, wait = args
download_single_url(url, fileout=fileout, overwrite=overwrite, verbose=verbose, wait=wait) | 18,433 |
def feature_registration(source,target, MIN_MATCH_COUNT = 12):
"""
Obtain the rigid transformation from source to target
first find correspondence of color images by performing fast registration
using SIFT features on color images.
The corresponding depth values of the matching keypoints is then use... | 18,434 |
def set_metadata(testbench_config, testbench):
"""
Perform the direct substitutions from the sonar testbench metadata into the
the testbench
Args:
testbench_config (Testbench): Sonar testbench description
testbench (str): The testbench template
"""
for key, value in testbench_co... | 18,435 |
def index(a, x):
"""Locate the leftmost value exactly equal to x"""
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError | 18,436 |
def convert_secondary_type_list(obj):
"""
:type obj: :class:`[mbdata.models.ReleaseGroupSecondaryType]`
"""
type_list = models.secondary_type_list()
[type_list.add_secondary_type(convert_secondary_type(t)) for t in obj]
return type_list | 18,437 |
def get_fdr_output(D, foutname):
"""Runs fdr and returns all relevant output."""
slm = SLM(FixedEffect(1), FixedEffect(1))
for key in D.keys():
setattr(slm, key, D[key])
# run fdr
Q = fdr(slm)
Q_out = {}
Q_out["Q"] = Q
with open(foutname, "wb") as handle:
pickle.dump(... | 18,438 |
def run(inputs, parameters = None):
"""Function to be callled by DOE and optimization. Design Variables are
the only inputs.
:param inputs: {'sma', 'linear', 'sigma_o'}"""
def thickness(x, t, chord):
y = af.Naca00XX(chord, t, [x], return_dict = 'y')
thickness_at_x = y['... | 18,439 |
def test_sa_question_creation() -> None:
"""Assert the creation and return values of a Question."""
for test_case in cases:
question = parser.Question(str(test_case["filename"]))
assert test_case["filename"] == question.filename
assert test_case["question_type"] == question.type
... | 18,440 |
def load_data(path):
"""Load JSON data."""
with open(path) as inf:
return json.load(inf) | 18,441 |
def test_new_dividends(mocker, capsys):
"""Различные варианты включения и не включения в статус."""
mocker.patch.object(div_status, "_new_div_all", return_value=SMART_LAB_DF)
mocker.patch.object(div, "dividends", side_effect=[PLZL_DF, T_DF, KZOS_DF, TTLK_DF])
assert div_status.new_dividends(("TTLK", "T... | 18,442 |
def unwatch(message):
"""
Unsubscribe from real-time updates for the specified
ticker
"""
log.info(f"Cancelling subscription to {message.ticker} data")
req_id = ib.next_request_id()
subId = subscriptions[message.ticker]
if subId:
# ib.cancelTickByTickData(subId)
ib.cancelMktData(subId)
del ... | 18,443 |
def get_extension(file_path):
"""
get_extension(file)
Gets the extension of the given file.
Parameters
----------
file_path
A path to a file
Returns
-------
str
Returns the extension of the file if it exists or None otherwise.
The Returning extension con... | 18,444 |
def game_state_post_save(sender, instance, created, **kwargs):
"""
When a new Game State is created, initialize the initial values
"""
if created:
# starting resources
for resource, quantity in STARTING['Resources'].iteritems():
resource = Resource.objects.get(name=resource)
... | 18,445 |
def rank_in_group(df, group_col, rank_col, rank_method="first"):
"""Ranks a column in each group which is grouped by another column
Args:
df (pandas.DataFrame): dataframe to rank-in-group its column
group_col (str): column to be grouped by
rank_col (str): column to be ranked for... | 18,446 |
def get_layer_options(layer_options, local_options):
"""
Get parameters belonging to a certain type of layer.
Parameters
----------
layer_options : list of String
Specifies parameters of the layer.
local_options : list of dictionary
Specifies local parameters in a model function... | 18,447 |
def expr(term:Vn,add:Vt,expr:Vn)->Vn:
"""
expr -> term + expr
"""
return {"add":[term,expr]} | 18,448 |
def gene_box(cohort, order='median', percentage=False):
"""Box plot with counts of filtered mutations by gene.
percentage computes fitness as the increase with respect to
the self-renewing replication rate lambda=1.3.
Color allows you to use a dictionary of colors by gene.
Returns a figu... | 18,449 |
def _clip_and_count(
adata: AnnData,
target_col: str,
*,
groupby: Union[str, None, List[str]] = None,
clip_at: int = 3,
inplace: bool = True,
key_added: Union[str, None] = None,
fraction: bool = True,
) -> Union[None, np.ndarray]:
"""Counts the number of identical entries in `target_... | 18,450 |
def create_training_patches(images, patch_size, patches_per_image=1, patch_stride=None):
"""
Returns a batch of image patches, given a batch of images.
Args:
images (list, numpy.array): Batch of images.
patch_size (tuple, list): The (width, height) of the patch to
return.
... | 18,451 |
def get_prover_options(prover_round_tag='manual',
prover_round=-1) -> deephol_pb2.ProverOptions:
"""Returns a ProverOptions proto based on FLAGS."""
if not FLAGS.prover_options:
tf.logging.fatal('Mandatory flag --prover_options is not specified.')
if not tf.gfile.Exists(FLAGS.prover_opt... | 18,452 |
def bracketpy(pystring):
"""Find CEDICT-style pinyin in square brackets and correct pinyin.
Looks for square brackets in the string and tries to convert its
contents to correct pinyin. It is assumed anything in square
brackets is CC-CEDICT-format pinyin.
e.g.: "拼音[pin1 yin1]" will be converted int... | 18,453 |
def run_validate_dictionary(args: Namespace, unknown: Optional[List[str]] = None) -> None:
"""
Wrapper function for running dictionary validation
Parameters
----------
args: :class:`~argparse.Namespace`
Parsed command line arguments
unknown: list[str]
Parsed command line argumen... | 18,454 |
def get_ram_usage_bytes(size_format: str = 'M'):
"""
Size formats include K = Kilobyte, M = Megabyte, G = Gigabyte
"""
total = psutil.virtual_memory().total
available = psutil.virtual_memory().available
used = total - available
# Apply size
if size_format == 'K':
used = used / 1... | 18,455 |
def test_rebase_and_update_remote(mock_repo, monkeypatch):
"""
GIVEN Rebaser initialized correctly
WHEN rebase_and_update_remote is called
THEN a tag is created
AND remote.fetch is called twice to catch remote updates during the rebase
AND git.push is called
"""
monkeypatch.setattr(time,... | 18,456 |
def weighted_crossentropy(weights, name='anonymous'):
"""A weighted version of tensorflow.keras.objectives.categorical_crossentropy
Arguments:
weights = np.array([0.5,2,10]) # Class one at 0.5, class 2 twice the normal weights, class 3 10x.
name: string identifying the loss to differentiate whe... | 18,457 |
def FullBackTraceAll(cmd_args=[]):
""" Show full backtrace across the interrupt boundary for threads running on all processors.
Syntax: fullbtall
Example: fullbtall
"""
for processor in IterateLinkedList(kern.globals.processor_list, 'processor_list') :
print "\n" + GetProcessorSummar... | 18,458 |
def _get_package_type(id):
"""
Given the id of a package this method will return the type of the
package, or 'dataset' if no type is currently set
"""
pkg = model.Package.get(id)
if pkg:
return pkg.type or u'dataset'
return None | 18,459 |
def _find_protruding_dimensions(f, care, fol):
"""Return variables along which `f` violates `care`."""
vrs = joint_support([f, care], fol)
dims = set()
for var in vrs:
other_vars = vrs - {var}
f_proj = fol.exist(other_vars, f)
care_proj = fol.exist(other_vars, care)
if (c... | 18,460 |
def prepare_data(train_mode, dataset="Train"):
"""
Args:
dataset: choose train dataset or test dataset
For train dataset, output data would be ['.../t1.bmp',
'.../t2.bmp',..., 't99.bmp']
"""
# Defines list of data path lists for different folders of training... | 18,461 |
def simulate_relatedness(genotypes, relatedness=.5, n_iter=1000, copy=True):
"""
Simulate relatedness by randomly copying genotypes between individuals.
Parameters
----------
genotypes : array_like
An array of shape (n_variants, n_samples, ploidy) where each
element of the array is... | 18,462 |
def pages_substitute(content):
"""
Substitute tags in pages source.
"""
if TAG_USERGROUPS in content:
usergroups = UserGroup.objects.filter(is_active=True).order_by('name')
replacement = ", ".join(f"[{u.name}]({u.webpage_url})" for u in usergroups)
content = content.replace(TAG_U... | 18,463 |
def vcfanno(vcf, out_file, conf_fns, data, basepath=None, lua_fns=None):
"""
annotate a VCF file using vcfanno (https://github.com/brentp/vcfanno)
"""
if utils.file_exists(out_file):
return out_file
if lua_fns is None:
lua_fns = []
vcfanno = config_utils.get_program("vcfanno", da... | 18,464 |
def clean(params: dict) -> str:
"""
Build clean rules for Makefile
"""
clean = "\t@$(RM) -rf $(BUILDDIR)\n"
if params["library_libft"]:
clean += "\t@make $@ -C " + params["folder_libft"] + "\n"
if params["library_mlx"] and params["compile_mlx"]:
clean += "\t@make $@ -C " + params["folder_mlx"] + "\n"
retur... | 18,465 |
def mathematica(quero: str, meta: str = '') -> bool:
"""mathematica
Rudimentar mathematical operations (boolean result)
Args:
quero (_type_, optional): _description_. Defaults to str.
Returns:
bool: True if evaluate to True.
"""
# neo_quero = quero.replace(' ', '').replace('('... | 18,466 |
def fasta2vcf(f):
"""convert fasta to vcf dataframe
Input
-----
Fasta file, _ref is recognized as ref and _alt is used as alt, these are two keywords
Output
------
vcf dataframe: chr, pos, name, ref, alt, reference sequence
"""
my_dict = {}
for r in SeqIO.parse(f, "fasta"):
my_dict[r.... | 18,467 |
def test_calc_job_node_get_builder_restart(aiida_localhost):
"""Test the `CalcJobNode.get_builder_restart` method."""
original = orm.CalcJobNode(
computer=aiida_localhost, process_type='aiida.calculations:core.arithmetic.add', label='original'
)
original.set_option('resources', {'num_machines': ... | 18,468 |
def checkout(path, commit, create = False):
""" Checks out a new branch in SL
:cwd: path to the git repo
:commit: String, name for the new branch
:create: create new or expect it to exist
"""
command = ["git", "checkout"]
if create:
command.append("-b")
command.append(commit)
... | 18,469 |
def time_pet(power,energy):
"""Usage: time_pet(power,energy)"""
return energy/power | 18,470 |
def compute_sigma0(
T,
S,
**kwargs,
):
"""
compute the density anomaly referenced to the surface
"""
return compute_rho(T, S, 0, **kwargs) - 1000 | 18,471 |
def find_rise_offsets(
connection,
reference_zeta_mm=None):
"""Determine rising curves
"""
cursor = connection.cursor()
compute_rise_offsets(cursor, reference_zeta_mm)
cursor.close()
connection.commit() | 18,472 |
def get_neighbors_radius(nelx, nely, coord, connect, radius):
""" Check neighboring elements that have the centroid within the predetermined radius.
Args:
nelx (:obj:`int`): Number of elements on the x axis.
nely (:obj:`int`): Number of elements on the x axis
coord (:obj:`numpy.array`):... | 18,473 |
def merge_with(obj, *sources, **kwargs):
"""
This method is like :func:`merge` except that it accepts customizer which is invoked to produce
the merged values of the destination and source properties. If customizer returns ``None``,
merging is handled by this method instead. The customizer is invoked wi... | 18,474 |
def count_class_nbr_patent_cnt(base_data_list, calculate_type):
"""
统计在所有数据中不同分类号对应的专利数量
:param base_data_list:
:return:
"""
class_number_patent_cnt_dict = dict()
for base_data in base_data_list:
class_number_value = base_data[const.CLASS_NBR]
calculate_class_number_... | 18,475 |
def SetVariable(output, variable_name, value):
"""Sets a CMake variable."""
output.write('set(')
output.write(variable_name)
output.write(' "')
output.write(CMakeStringEscape(value))
output.write('")\n') | 18,476 |
def plot_pta_L(df):
"""
INPUTS
-df: pandas dataframe containing the data to plot
OUTPUTS
-saves pta graphs in .html
"""
title = generate_title_run_PTA(df, "Left Ear", df.index[0])
labels = {"title": title,
"x": "Frequency (Hz)",
"y": "Hearing Threshold (dB HL... | 18,477 |
def error(text):
"""Safely echo an error to STDERR."""
output = text
if sys.stderr.isatty():
output = format_for_tty(text, [TEXT_ERROR, TEXT_BOLD])
stderr_log.error(output) | 18,478 |
def create_graph(edge_num: int, edge_list: list) -> dict:
"""
Create a graph expressed with adjacency list
:dict_key : int (a vertex)
:dict_value : set (consisted of vertices adjacent to key vertex)
"""
a_graph = {i: set() for i in range(edge_num)}
for a, b in edge_list:
a_graph... | 18,479 |
def msg_warn(message):
"""
Log a warning message
:param message: the message to be logged
"""
to_stdout(" (!) {message}".format(message=message),
colorf=yellow, bold=True)
if _logger:
_logger.warn(message) | 18,480 |
def multikey_fkg_allowing_type_hints(
namespace: Optional[str],
fn: Callable,
to_str: Callable[[Any], str] = repr) -> Callable[[Any], List[str]]:
"""
Equivalent of :func:`dogpile.cache.util.function_multi_key_generator`, but
using :func:`inspect.signature` instead.
Also modified... | 18,481 |
def get_current_version() -> str:
"""Read the version of the package.
See https://packaging.python.org/guides/single-sourcing-package-version
"""
version_exports = {}
with open(VERSION_FILE) as file:
exec(file.read(), version_exports) # pylint: disable=exec-used
return version_exports["... | 18,482 |
def seed_story(text_dict):
"""Generate random seed for story."""
story_seed = random.choice(list(text_dict.keys()))
return story_seed | 18,483 |
def __default_proto_version_inject():
"""
modified the value to default_proto_version if there are multiple allow version
"""
import minecraft.networking.connection as connection
from minecraft.networking.connection import Connection
red, connection_class = redbaron_util.read_class(Connection)
connect_method = ... | 18,484 |
def rename_file(directory, oldfilename, newfilename):
"""renames a file in a directory
:param directory: the name of the directory containing the file
to be renamed
:type directory: path
:param oldfilename: original name of the file
:type oldfilename: string
:param newfile... | 18,485 |
def detect_conda_env():
"""Inspect whether `sys.executable` is within a conda environment and if it is,
return the environment name and Path of its prefix. Otherwise return None, None"""
prefix = Path(sys.prefix)
if not (prefix / 'conda-meta').is_dir():
# Not a conda env
return None, Non... | 18,486 |
def _get_rel_att_inputs(d_model, n_heads): # pylint: disable=invalid-name
"""Global relative attentions bias initialization shared across the layers."""
assert d_model % n_heads == 0 and d_model % 2 == 0
d_head = d_model // n_heads
bias_initializer = init.RandomNormalInitializer(1e-6)
context_bias_layer = c... | 18,487 |
def two_time_pad():
"""A one-time pad simply involves the xor of a message with a key to produce a ciphertext: c = m ^ k.
It is essential that the key be as long as the message, or in other words that the key not be repeated for two distinct message blocks.
Your task:
In this problem you will b... | 18,488 |
def same_datatypes(lst):
"""
Überprüft für eine Liste, ob sie nur Daten vom selben Typ enthält. Dabei spielen Keys, Länge der Objekte etc. eine Rolle
:param lst: Liste, die überprüft werden soll
:type lst: list
:return: Boolean, je nach Ausgang der Überprüfung
"""
datatype = type(lst[0]).__... | 18,489 |
def _show_stat_wrapper_Progress(count, last_count, start_time, max_count, speed_calc_cycles,
width, q, last_speed, prepend, show_stat_function, add_args,
i, lock):
"""
calculate
"""
count_value, max_count_value, speed, tet, ttg, = Pro... | 18,490 |
def _to_base58_string(prefixed_key: bytes):
"""
Convert prefixed_key bytes into Es/EC strings with a checksum
:param prefixed_key: the EC private key or EC address prefixed with the appropriate bytes
:return: a EC private key string or EC address
"""
prefix = prefixed_key[:PREFIX_LENGTH]
as... | 18,491 |
def import_report_from_stdin():
"""Parse a report from stdin."""
content = six.StringIO()
for line in fileinput.input([]):
content.write(line)
content.seek(0)
if not content:
return
import_report_from_email(content) | 18,492 |
def round_int(n, d):
"""Round a number (float/int) to the closest multiple of a divisor (int)."""
return round(n / float(d)) * d | 18,493 |
def process(sample_nxs_list, mt_nxs_list, parameter_yaml):
"""process a series of files using a fixed set of parameters
This implementation just shows one way of processing a batch job,
where the processing parameters stay fixed except for
the sample and emtpy can nexus files.
For more complex bat... | 18,494 |
def test_default_parameter_in_args():
"""
>>> from allure_commons.utils import represent
>>> allure_report = getfixture('allure_report')
>>> assert_that(allure_report,
... has_test_case('test_default_parameter_in_args',
... has_step('First step',
... ... | 18,495 |
def zipdir(dir, zip_path):
"""Create a zip file from a directory.
The zip file contains the contents of dir, but not dir itself.
Args:
dir: (str) the directory with the content to place in zip file
zip_path: (str) path to the zip file
"""
with zipfile.ZipFile(zip_path, 'w', zipfile... | 18,496 |
def merge_array_list(arg):
"""
Merge multiple arrays into a single array
:param arg: lists
:type arg: list
:return: The final array
:rtype: list
"""
# Check if arg is a list
if type(arg) != list:
raise errors.AnsibleFilterError('Invalid value type, should... | 18,497 |
def load_callbacks(boot, bootstrap, jacknife,
out, keras_verbose, patience):
"""
Specifies Keras callbacks, including checkpoints, early stopping,
and reducing learning rate.
Parameters
----------
boot
bootstrap
jacknife
out
keras_verbose
patience
batc... | 18,498 |
def build_sentence_model(cls, vocab_size, seq_length, tokens, transitions,
num_classes, training_mode, ground_truth_transitions_visible, vs,
initial_embeddings=None, project_embeddings=False, ss_mask_gen=None, ss_prob=0.0):
"""
Construct a classifier which makes... | 18,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.