content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def score_vectore(vector):
"""
:type vector: list of float
:return:
"""
x = 0.
y = 0.
for i in range(0, len(vector)):
if i % 2 == 0:
if vector[i] > 12:
x += vector[i]
else:
y += vector[i] + min(vector[i-1], vector[i])
return x, y | 49,100 |
def loudness_contour_equivalence(mean_loudness_value, phon_ref_value):
""" Function that serves for the validation of the hearing model presented in Annex F of ECMA-74.
Parameters
----------
Returns
-------
"""
# Conversion to phons of the loudness result that is in sones.
... | 49,101 |
def sound():
"""
Play a sound
:header sound_name: is the filename with the extension (must be inside the sounds folder)
"""
check_api_key()
sound_name = get_body('sound_name')
threading.Thread(target=playsound(path + "/sounds/" + sound_name)).start()
return jsonify("OK") | 49,102 |
def _compound_register(upper, lower):
"""Return a property that provides 16-bit access to two registers."""
def get(self):
return (upper.fget(None) << 8) | lower.fget(None)
def set(self, value):
upper.fset(None, value >> 8)
lower.fset(None, value)
return property(get, set) | 49,103 |
def cuda_library(copts = [], **kwargs):
"""Wrapper over cc_library which adds default CUDA options."""
native.cc_library(copts = cuda_default_copts() + copts, **kwargs) | 49,104 |
def start_cron_threads():
"""Start threads to trigger essential cron jobs."""
request_timeout = 10 * 60 # 10 minutes.
def trigger(interval_seconds, target):
"""Trigger a cron job."""
while True:
time.sleep(interval_seconds)
try:
url = 'http://{host}/{target}'.format(
ho... | 49,105 |
def get_file_extension(path: str) -> str:
"""Returns extension of the file"""
return os.path.basename(path).split(".")[-1] | 49,106 |
def get_joining_type_property(value, is_bytes=False):
"""Get `JOINING TYPE` property."""
obj = unidata.ascii_joining_type if is_bytes else unidata.unicode_joining_type
if value.startswith('^'):
negated = value[1:]
value = '^' + unidata.unicode_alias['joiningtype'].get(negated, negated)
... | 49,107 |
def test_hit_extra_parameters(responses):
"""The request can include extra parameters."""
ocireg = OCIRegistry("https://fakereg.com", "test-image")
# fake a 200 response
responses.add(responses.PUT, "https://fakereg.com/api/stuff")
# try it
response = ocireg._hit("PUT", "https://fakereg.com/ap... | 49,108 |
def select_record_fields(
record: dict,
fields: List[str]) -> dict:
"""
Selects a subset of fields from a dictionary
"""
return {k: record.get(k, None) for k in fields} | 49,109 |
def to_TProfile2D(
fName,
fTitle,
data,
fEntries,
fTsumw,
fTsumw2,
fTsumwx,
fTsumwx2,
fTsumwy,
fTsumwy2,
fTsumwxy,
fTsumwz,
fTsumwz2,
fSumw2,
fBinEntries,
fBinSumw2,
fXaxis,
fYaxis,
fZaxis=None,
fScalefactor=1.0,
fZmin=0.0,
fZmax=0.... | 49,110 |
def test_init(name, prior_bounds):
"""Test the init method with the allowed types of inputs"""
reparam = Reparameterisation(parameters=name, prior_bounds=prior_bounds)
assert reparam.parameters == ['x1']
assert reparam.prime_parameters == ['x1_prime']
assert_equal(reparam.prior_bounds, {'x1': np.arr... | 49,111 |
def check_project_auth(project_type, project_id, action_id=PROJECT_MANAGE_FLOW):
"""
判断用户是否有相应操作的权限
project.manage_flow:校验用户是否有数据开发的权限,如果无此权限,则没有对查询或笔记进行增删改的权限
project.retrieve:校验用户是否有项目观察的权限,如果无此权限,则没有查看笔记报告的权限
:param project_type: 项目类型
:param project_id: 项目id
:param action_id: 动作id
""... | 49,112 |
def decode_check(string: str, digestfunc=sha256d_32) -> bytes:
"""
Convert base58 encoded string to bytes and verify checksum.
"""
result = decode(string)
return verify_checksum(result, digestfunc) | 49,113 |
def label_by_wic(grasp_wic, exclude_C0=False):
"""Label each grasp by the whiskers it contains
grasp_wic : DataFrame
Index: grasp keys. Columns: whisker. Values: binarized contact.
exclude_C0 : bool
If False, group by all whiskers.
If True, ignore C0, and group only by C1, ... | 49,114 |
def selectBestFeature(dataSet: list):
"""
计算信息增益,挑选最好的特征值
:param dataSet: 数据集
:return:
"""
# 不使用最后一列标签列
best_feature_idx = 0
gain = float('-inf')
for feature_idx in range(len(dataSet[0])-1):
gain_tmp = calcOneFeatureGain(dataSet, feature_idx)
if gain_tmp > gain:
... | 49,115 |
def lookup_remote(app, config):
"""
Once configuration is complete, build the Remote
"""
try:
remote_url = config.gitref_remote_url
if not remote_url:
raise AttributeError
except AttributeError:
raise ValueError("Could not determine gitref_remote_url, must set exp... | 49,116 |
async def test_execute_with_data(opp, caplog):
"""Test executing a script."""
caplog.set_level(logging.WARNING)
source = """
opp.states.set('test.entity', data.get('name', 'not set'))
"""
opp.async_add_executor_job(execute, opp, "test.py", source, {"name": "paulus"})
await opp.async_block_till_... | 49,117 |
def __interact_instances(client, action: Callable, status: str) -> dict:
"""
Interacts with the instances. It executes the callable from action.
:param client: Sagemaker boto3 client.
:param action: a callable (e.g. client.start_notebook_instance).
:param status: A status that will be verified befor... | 49,118 |
def _chordfinisher(*args, **kwargs):
"""
Needs to run at the end of a chord to delay the variant parsing step.
http://stackoverflow.com/questions/
15123772/celery-chaining-groups-and-subtasks-out-of-order-execution
"""
return "FINISHED VARIANT FINDING." | 49,119 |
def plot_reg_path(model, marker='o', highlight_c="orange", include_n_coef=False, figsize=None, fontsize=None):
"""Plots path of an L1/L2 regularized sklearn.linear_model.LogisticRegressionCV.
Produces two adjacent plots.
The first is a plot of mean coefficient values vs penalization strength.
The second... | 49,120 |
def update_wordcloud_title():
""" Update the figure wordcloud_title.jpg """
data = pd.read_csv('AllGAN-r2.tsv',delimiter='\t', encoding='utf-8')
# tmp_data = data['Title'].split(" ") for x in data
# count_list = list([list(x) for x in data['Title'].value_counts().reset_index().values])
# wordcloud ... | 49,121 |
def create_object_count(app=None):
"""fetches all models of the passed in app and returns a
dict containg the name of each class and the number of instances"""
if app:
models = ContentType.objects.filter(app_label=app)
result = []
for x in models:
modelname = x.model
... | 49,122 |
def unique_name(prefix: str, collection) -> str:
"""
Prepares a unique name that is not
in the collection (yet).
Parameters
----------
prefix
The prefix to use.
collection
Name collection.
Returns
-------
A unique name.
"""
if prefix not in collection:
... | 49,123 |
async def get_pic(image_type: str, group_id: int, sender: int) -> list:
"""
Return random pics message
Args:
image_type: The type of picture to return
image type list:
setu: hPics(animate R-15)
setu18: hPics(animate R-18)
real: hPics(real ... | 49,124 |
def DefineIons():
"""
Define all the ion types we care about.
(This function is repetitive, but easy enough to maintain since the zoo of ion types
is pretty small...the scores should be in a datafile, though!)
"""
IonB = IonClass("b")
IonB.GetPeakMass = lambda L, P:L+1
IonB.GetPRMMass ... | 49,125 |
def loop_resolve(graph, loads):
""" The solution is some rotation of the current state"""
pass | 49,126 |
def agent_action_to_environment(noop_action, agent_action):
"""
Turn an agent action (an integer) into an environment action.
This should match `environment_action_batch_to_agent_actions`,
e.g. if attack=1 action was mapped to agent_action=0, then agent_action=0
should be mapped back to attack=1.
... | 49,127 |
def dispatch(req):
"""run the command specified in req.args; returns an integer status code"""
err = None
try:
status = _rundispatch(req)
except error.StdioError as e:
err = e
status = -1
ret = _flushstdio(req.ui, err)
if ret:
status = ret
return status | 49,128 |
def test_check_transform_matrix_not_transform_1d() -> None:
"""verify raised exception for 1d matrix that is not a transform"""
xform = AutomataTransforms(base_universe_instance_1d())
assert len(BAD_TRANSFORM_1D) > 0
for matrix in BAD_TRANSFORM_1D:
assert isinstance(matrix[0][0], int)
ex... | 49,129 |
def get_settings(from_db=False):
"""
Use this to get latest system settings
"""
if not from_db and 'custom_settings' in current_app.config:
return current_app.config['custom_settings']
s = Setting.query.order_by(desc(Setting.id)).first()
app_environment = current_app.config.get('ENV', 'p... | 49,130 |
def get_currency_crosses_list(base=None, second=None):
"""
This function retrieves all the available currency crosses from Investing.com and returns them as a
:obj:`dict`, which contains not just the currency crosses names, but all the fields contained on
the currency_crosses file is columns is None, ot... | 49,131 |
def define_git_repo(*, name: 'name',
repo, treeish=None):
"""Define [NAME/]git_clone rule."""
(define_parameter.namedtuple_typed(GitRepoInfo, name + 'git_repo')
.with_default(GitRepoInfo(repo=repo, treeish=treeish)))
relpath = get_relpath()
@rule(name + 'git_clone')
@rule... | 49,132 |
def solve_lineage_instance(
_target_nodes,
prior_probabilities=None,
method="hybrid",
threads=8,
hybrid_cell_cutoff=200,
hybrid_lca_cutoff=None,
time_limit=1800,
max_neighborhood_size=10000,
seed=None,
num_iter=-1,
weighted_ilp=False,
fuzzy=False,
probabilistic=False,... | 49,133 |
def split_in_chunks(
data,
chunk_size,
train_size=None,
val_size=None,
test_size=None,
shuffle=True,
seed=None,
):
"""Split data into train-test, where chunks of data are held together
Assume `data` is a list of numpy arrays
"""
chunks = []
for rollout in data:
f... | 49,134 |
def test(conf_dict, args):
"""
run predict
"""
vocab = utils.load_vocab(args.vocab_path)
simnet_process = reader.SimNetProcessor(args, vocab)
# load auc method
metric = fluid.metrics.Auc(name="auc")
with open("predictions.txt", "w") as predictions_file:
# Get model path
m... | 49,135 |
def test_ll_modif():
"""
Test of the three geometry operations that can be applied to LineLoop instances :
- offset
- round_corner_explicit
- round_corner_incircle
geometry (check with plots) : OK, gmsh model : OK
"""
name = "test_LineLoop_offset_round_corners"
gmsh.mode... | 49,136 |
def fetch_googlenet_architecture(caffemodel_parsed=None,
caffemodel_protobuffer=None):
"""Fetch a pickled version of the caffe model, represented as list of
dictionaries."""
default_filename = os.path.join(GOOGLENET_PATH, 'bvlc_googlenet.pickle')
if caffemodel_parsed is... | 49,137 |
def check_id(id):
"""
Check whether a id is valid
:param id: The id
:return: The result
"""
return bool(re.match(r"^[a-f0-9]{24}$", id)) | 49,138 |
def totaled_tbr_no_lgtm(cc, sql_time_specification):
"""Counts the number of commits with a TBR that have not been lgtm'ed
in a given timeframe
Args:
cc(cursor)
sql_time_specification(str): a sql command to limit the dates of the
returned results
Return:
count(i... | 49,139 |
def normalize_text(text: str) -> str:
"""Normalize the text to remove accents
and ensure all the characters are valid
ascii symbols.
Args:
text : Input text
Returns:
Output text
"""
nfkd_form = unicodedata.normalize("NFKD", text)
only_ascii = nfkd_form.encode("ASCII", "... | 49,140 |
def main(config, serve, verbose):
"""
Nēnē: A no-frills static site generator.
Builds a static HTML website from sources, templates, and configuration
found in the current directory.
"""
console = rich.console.Console(stderr=True, quiet=not verbose)
console.print(":building_construction: [... | 49,141 |
def rotate_y(x, z, cosangle, sinangle):
"""3D rotaion around *y* (roll). *x* and *z* are values or arrays.
Positive rotation is for positive *sinangle*. Returns *xNew, zNew*."""
return cosangle*x + sinangle*z, -sinangle*x + cosangle*z | 49,142 |
def json_file_upload(contents, file_names, dates):
"""
Reads a JSON file from disk and saves it in the default path
The goal is to keep that file over there for the Draw JSON
Function to read and draw it.
Args:
ontents, file_names, dates: inputs from the Dash UI
"""
global arm, dp
... | 49,143 |
def plot_cov(cov, info, exclude=(), colorbar=True, proj=False, show_svd=True,
show=True, verbose=None):
"""Plot Covariance data.
Parameters
----------
cov : instance of Covariance
The covariance matrix.
info : dict
Measurement info.
exclude : list of str | str
... | 49,144 |
def populate_activity(values):
"""
Populates the activity tracker with FitBit data.
Outputs progress bar to terminal.
:param nested list values: fitbit data to input to activity tracker.
"""
with click.progressbar(length=2, label='Modifying activity tracker') as bar:
rng = activity_rng_... | 49,145 |
def install_primitives(directory_or_archive, prompt=True):
"""Install primitives from the provided directory"""
tmp_dir = get_installation_temp_dir()
try:
# if it isn't local, download it. if remote, it must be archive
if not (os.path.isdir(directory_or_archive) or os.path.isfile(directory_... | 49,146 |
def ask_credential(login=None, password=None):
""" Ask for a login and a password when not specified.
Parameters
----------
login: str, default None
a login.
password: str, defualt None
a password.
Returns
-------
login: str, default None
a login.
password: ... | 49,147 |
def zeros_like(a, dtype=None, bohrium=None):
"""
Return an array of zeros with the same shape and type as a given array.
With default parameters, is equivalent to ``a.copy().fill(0)``.
Parameters
----------
a : array_like
The shape and data-type of `a` define these same attributes of
... | 49,148 |
def get(handler, parameters, url_parameters, ids_parameters):
"""GET method"""
query = handler.session.query(Tournament)
guild_id = None
for key, values in url_parameters.items():
if key in vars(Tournament):
for value in values:
if key == "server_id":
... | 49,149 |
def test_ngrdi():
"""Test ngrdi"""
assert al.ngrdi(read_input(input1)) == -0.02
assert al.ngrdi(read_input(input2)) == 0.14 | 49,150 |
def rand():
"""
Returns a random number.
"""
return random.random() | 49,151 |
def read_counters():
"""read_counters()
Get current counts and reset counters.
:rtype: list(int)
:raises PapiInvalidValueError: One or more of the arguments is invalid
(this error should not happen with PyPAPI).
:raises PapiSystemError: A system or C library call failed inside PAPI.
"... | 49,152 |
def is_monotonic_decreasing(series_or_index):
"""
Return boolean scalar if values in the object are
monotonic_decreasing.
Returns
-------
Scalar
"""
return check_monotonic(series_or_index, decreasing=True, strict=False) | 49,153 |
def mprint(m,fmt):
"""
This function will print a VSIPL matrix or vector suitable for pasting into Octave or Matlab.
usage: mprint(<vsip matrix/vector>, fmt)
fmt is a string corresponding to a simple fmt statement.
For instance '%6.5f' prints as 6 characters wide with 5 decimal dig... | 49,154 |
def get_stationxml_filename(str_or_fct, network, station, channels,
starttime, endtime):
"""
Helper function getting the filename of a StationXML file.
:param str_or_fct: The string or function to be evaluated.
:type str_or_fct: function or str
:param network: The networ... | 49,155 |
def fetch_reviews(app_id, page_num):
"""Fetch a single page of reviews for a given app_id.
:param app_id: The ID of the app in the app store.
:param page_num: The page of reviews to fetch.
:return: A list of Review objects.
"""
# page=1 is the same as if the "page" param was left off.
url =... | 49,156 |
def graph_push_point(graph_id):
"""
Push points to graph
"""
request_data, error = parseHTTPRequest(request, ["value"])
if error:
response = jsonify({
"error": error
})
return response, 422
try:
# data = {"value":10, "date": datetime.datetime.... | 49,157 |
def test_branch_property():
"""Assert that the branch property returns the current branch."""
atom = ATOMClassifier(X_bin, y_bin, random_state=1)
assert isinstance(atom.branch, Branch) | 49,158 |
def test_page_number_to_filename(
base_name, total_pages, page_number, extension, expected
):
"""Verify the filename generation for pages
"""
result = Base.page_to_filename(
base_name, total_pages, page_number, extension
)
assert result == expected | 49,159 |
def or_operator():
"""|: Bitwise "or" operator."""
class _Operand:
def __or__(self, other):
return " ~or~ ".join(('east coast', other))
return _Operand() | 'dirty south' | 49,160 |
def computeAlignmentScores(vocabulary, sub_mat, gap_open, gap_extend):
"""
Pre-computes the alignment scores between all the k-mer pairs
Args:
vocabulary (list [str]): The list of all possible k-mers
sub_mat (dict[tuple[str,str],int]): Substitution matrix as represented in Bio.SubsMat.MatrixInfo.blosum objects
... | 49,161 |
def setup(version, verbose=True):
"""
:param version:
Supported version values (examples):
1. Unstable versions:
- unstable/master:2020-12-20T00:11:59Z
- unstable/enterprise:2020-08-18T14:49:18Z
- unstable/branch-4.1:2020-05-30T08:27:59Z
... | 49,162 |
def _get_version(basename):
"""Returns the _get_next_version of a file."""
match = re.search(r"\(\d*\)", basename)
if match:
v = int(match.group(0)
.replace('(', '')
.replace(')', ''))
return v
return 0 | 49,163 |
def list_tags():
"""Show all the known tags."""
streets_with_tags = (
db.session.query(Street).filter(Street.tags != None).all() # noqa
)
all_tags = set()
for street in streets_with_tags:
all_tags.update(set(street.tags))
all_tags = sorted(list((all_tags)))
return render_t... | 49,164 |
def test_malformed_malware():
"""Tests that a Malware object missing fields cannot be created."""
with pytest.raises(ValidationError):
Malware(name='asd') | 49,165 |
def get_records(field_id):
"""Return TOP 10 records for selected field"""
if not request.is_xhr:
abort(403)
if field_id == 0:
field_id = session.get('current_field_id', 2)
field = Field.query.get(field_id)
records = field.records.limit(10)
top_10 = []
for record in records:... | 49,166 |
def self_play_iterator_creator(hparams, num_workers, jobid):
"""create a self play iterator. There are iterators that will be created here.
A supervised training iterator used for supervised learning. A full text
iterator and structured iterator used for reinforcement learning self play.
Full text iterators fee... | 49,167 |
def _migrate_skill_contents_to_latest_schema(versioned_skill_contents):
"""Holds the responsibility of performing a step-by-step, sequential update
of the skill contents structure based on the schema version of the input
skill contents dictionary. If the current skill_contents schema changes, a
new conv... | 49,168 |
def utf8_product_page():
"""
Single product page with utf8 content.
"""
with open('data/product_utf8.html') as f:
return ''.join(f) | 49,169 |
def detect_Nir2011(dat_orig, s_freq, time, opts):
"""Spindle detection based on Nir et al. 2011
Parameters
----------
dat_orig : ndarray (dtype='float')
vector with the data for one channel
s_freq : float
sampling frequency
time : ndarray (dtype='float')
vector with the ... | 49,170 |
def is_indel(variant):
"""Is variant an indel?
An indel event is simply one where the size of at least one of the alleles
is > 1.
Args:
variant: third_party.nucleus.protos.Variant.
Returns:
True if the alleles in variant indicate an insertion/deletion event
occurs at this site.
"""
# redact... | 49,171 |
def parse_rcv_compra_registro_csv_file(
rut: Rut,
input_file_path: str,
n_rows_offset: int = 0,
max_n_rows: int = None,
) -> Iterable[Tuple[Optional[RcRegistroDetalleEntry], int, Dict[str, object], Dict[str, object]]]:
"""
Parse entries from an RC ("Registro de Compras") / "registro" (CSV file).... | 49,172 |
def project_access_required(f):
"""Decorator function to verify the users access to the project."""
@functools.wraps(f)
def verify_project_access(current_user, project, *args, **kwargs):
"""Verifies that the user has been granted access to the project."""
if project["id"] is None:
... | 49,173 |
def bm():
""" '-' button click."""
buf = buffer.get()
text = label_text.get()
if len(buf.split()) == 0 and float(text) == 0:
buffer.set('0 - ')
if len(buf.split()) == 0 and float(text) != 0:
buffer.set(text + ' - ')
label_text.set('0')
if len(buf.split()) == 1 an... | 49,174 |
def downloadRangesHelper(imageCount : int, downloadRange, downloadIndex):
"""Helper function for calculating download ranges and/or download index"""
# expected output should be [x,y], where x = zero-based image index start,
# and y = the amount of images in a post.
# check if downloadRange and downloa... | 49,175 |
def host_battle(game, province, rounds):
""""
Host games concurrently based on the number of threads.
:param game: game name
:param province: province where battle occurs
:param rounds: number of rounds to be hosted
"""
switch = 'g -T'
threads = []
max_threads = yaml.load(open('./b... | 49,176 |
def app_group(parent):
"""Configures app CLI group"""
# Disable too many branches.
#
# pylint: disable=R0912
formatter = cli.make_formatter(cli.AppPrettyFormatter)
@parent.group()
def app():
"""Manage applications"""
pass
@app.command()
@click.option('-m', '--manife... | 49,177 |
def removeProduct(product, connection=None):
"""
Remove a product tuple from the database.
Args:
products (str): The product to be removed from the database.
connection (sqlite3.Connection, optional): A connection to the database.
Returns:
bool: True if successful, false otherwise.
... | 49,178 |
def test_props(mocked_config, logger): # noqa: F811
"""Verify that a consumer instance have its own several properties and returns."""
host = 'abc_host'
port = 23345
topic = 'abc_topic'
# verifies consumer properties
consumer = KConsumer(config=mocked_config, kafka_host=host, kafka_port=port,
... | 49,179 |
def insert_example_users():
""" Insert hypothetical users """
nick = User(id=1, name="nick")
elon = User(id=2, name="elonmusk")
DB.session.add(nick)
DB.session.add(elon)
DB.session.commit() | 49,180 |
def health():
"""Return information about the health of the queue in a format that
can be turned into JSON.
"""
output = {'queue': {}, 'errors': {}}
output['queue']['all-jobs'] = Job.objects.all().count()
output['queue']['not-executed'] = Job.objects.filter(executed=None).count()
output['que... | 49,181 |
def pdsspect(inlist=None):
"""Run pdsspect from python shell or command line with arguments
Parameters
----------
inlist : :obj:`list`
A list of file names/paths to display in the pdsspect
Examples
--------
From the command line:
To view all images from current directory
... | 49,182 |
def test_select_c_parameter_sheet_ok_zero(monkeypatch):
"""
select_c_parameter_sheet(正常系0件)のテスト
"""
core = create_ita1core()
core.restobj.rest_set_config(get_configs())
config = {}
host_name = 'host1'
operation_name = 'pytest'
menu_id = ''
monkeypatch.setattr(core.restobj, 'res... | 49,183 |
def help(ctx, detail):
"""Show help and exit."""
# pylint: disable=redefined-builtin
logger.info('', err=True)
if not detail:
logger.info(ctx.parent.get_help())
else:
out = """\
Summary
=======
21 allows developers to earn bitcoin on every HTTP request. Your
installation includ... | 49,184 |
def _make_library(ydir):
"""
Make JSON library of YANG modules.
Args:
ydir (str): Name of the directory with YANG (sub)modules.
"""
for infile in os.listdir(ydir):
if not infile.endswith(".yang"):
continue
with open(
"{ydir}/{infile}".format(ydir=ydir,... | 49,185 |
def build_confirmation_msg(message_template: str, variables_arr: [], record):
"""Returns the full confirmation email as a string
Note: some email services also support sending HTML for future purposes.
"""
inserts = []
for variable in variables_arr:
inserts.append(record['fields'][variable.strip()])
mes... | 49,186 |
def _get_freq_label_by_month(date_value: str) -> str:
"""Gets frequency label for the date value which is aggregated by month.
Args:
date_value (str): The date value.
Returns:
str: The date value aggregated by month.
"""
if bool(re.match(r"^\d{4}M\d{1,2}$", date_value)):
re... | 49,187 |
def get_depth_metrics(pred, gt, mask=None):
"""
params:
pred: [N,1,H,W]. torch.Tensor
gt: [N,1,H,W]. torch.Tensor
"""
if mask is not None:
num = torch.sum(mask) # the number of non-zeros
pred = pred[mask]
gt = gt[mask]
else:
num = pred.numel()
num = ... | 49,188 |
def run_ica(raw, n_components, max_pca_components=100,
n_pca_components=64, noise_cov=None, random_state=None,
algorithm='parallel', fun='logcosh', fun_args=None,
verbose=None, picks=None, start=None, stop=None, start_find=None,
stop_find=None, ecg_ch=None, ecg_score_func... | 49,189 |
def align(
seqfile: PathLike,
outfile: PathLike,
seqdb: PathLike,
is_viral: bool,
keep_insertions: bool,
tempdir: PathLike,
num_cpu: int = 8,
) -> None:
"""An attempt to match the following text from DeepSequence:
For each analyzed protein (target sequence), multiple sequence alignm... | 49,190 |
def main(cmd_args):
"""Run training."""
parser = get_parser()
args, _ = parser.parse_known_args(cmd_args)
from espnet.utils.dynamic_import import dynamic_import
model_class = dynamic_import(args.model_module)
assert issubclass(model_class, TTSInterface)
model_class.add_arguments(parser)
... | 49,191 |
def remove_member(context, request):
"""Remove a member from the given group."""
# Currently, we only support removing the requesting user
if request.matchdict.get("userid") == "me":
userid = request.authenticated_userid
else:
raise HTTPBadRequest('Only the "me" user value is currently s... | 49,192 |
def convert_length(length, original_unit="kilometers", final_unit="kilometers"):
"""
:param length: length to be converted
:param original_unit: original unit of the length
:param final_unit: return unit of the length
:return: the converted length
"""
if not isinstance(length, (float, int))... | 49,193 |
def pytest_ignore_collect(path, config): # pylint: disable = unused-argument
"""return True to prevent considering this path for collection.
This hook is consulted for all files and directories prior to
calling more specific hooks.
"""
relative_path = os.path.relpath(str(path), os.path.dirname(__... | 49,194 |
def load_model_db(FLAGS):
"""
Load model database.
"""
# load models
if not os.path.exists(FLAGS.models_save_dir):
sys.exit("Model file " + FLAGS.model_save_dir + " does not exist!")
else:
return pickle.load(open(FLAGS.model_save_dir, "r")) | 49,195 |
def get_value_larger(threshold, value, step, direction, size_x, size_y):
"""Function for looping until correct coordinate is found"""
matrix = [[0 for _ in range(size_x)] for _ in range(size_y)]
current_x = size_x / 2
current_y = size_y / 2
while value <= threshold:
for _ in range(0, 2):
... | 49,196 |
def get_daq_device_inventory(interface_type, number_of_devices=100):
# type: (InterfaceType, int) -> list[DaqDeviceDescriptor]
"""
Gets a list of :class:`DaqDeviceDescriptor` objects that can be used
as the :class:`DaqDevice` class parameter to create DaqDevice objects.
Args:
interface_type... | 49,197 |
def prYellow(skk):
"""Prints Yellow text to Console"""
print("\033[93m{}\033[00m".format(skk)) | 49,198 |
def statement_passive_verb(stmt_type):
"""Return the passive / state verb form of a statement type.
Parameters
----------
stmt_type : str
The lower case string form of a statement type, for instance,
'phosphorylation'.
Returns
-------
str
The passive/state verb form... | 49,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.