content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import warnings
def set_showlib(name):
"""Set library for live video view"""
out = CDDMConfig.showlib
if name not in ("matplotlib", "cv2", "pyqtgraph"):
raise ValueError("Unsupported library")
if name == "cv2" and not CV2_INSTALLED:
warnings.warn("cv2 is not installed so it can n... | a076465bcc8e69bc27a6957df9fd604909adcb39 | 62,373 |
def repr(x):
""" Return the string representation of 'x'.
"""
if hasattr(x, '__repr__'):
if callable(x):
return x.__repr__(x)
return x.__repr__()
JS("""
if (x === null)
return "null";
if (x === undefined)
return "undefined";
var t ... | ea99baf8e122c17cd4227abed04386f90c18bd6e | 62,375 |
def combineBoundingBoxes(a, b):
""" Retrun wxRect as a combination of source bounding boxes """
x1 = min(a.GetX(), b.GetX())
y1 = min(a.GetY(), b.GetY())
x2 = max(a.GetX() + a.GetWidth(), b.GetX() + b.GetWidth())
y2 = max(a.GetY() + a.GetHeight(), b.GetY() + b.GetHeight())
# Beware that we canno... | 03a05881550790e6fef1f1da265aef34cbc05f32 | 62,376 |
import tqdm
def UCB(bandits, horizon, eps=0.1):
"""
requires :
Bandit - List with Bandit objects as elements already
initiated with respective probability values.
returns :
reg - Expected cumulative Regret
Simulates the Upper Confidence Bound algorithm
- at time t define
U... | ce7e0d6c9991971dcaff820e12c9a10a606cc960 | 62,377 |
def separate_graph(edges):
""" Split graph into disconnected components.
Args:
edges (:class:`numpy.ndarray`): edges of the graph.
Returns:
An array of indices indicating the component each edge belongs to.
"""
separator = MeshSeparator(edges);
separator.set_connectivity_type(M... | 7229d61498bbc10aa9c388fd70a2a01d28d10898 | 62,378 |
def get_init_time(run_time, fetch_metadata):
"""Determine the most recent init time for which all forecast data is
available."""
run_finish = (pd.Timedelta(fetch_metadata['delay_to_first_forecast']) +
pd.Timedelta(fetch_metadata['avg_max_run_length']))
freq = fetch_metadata['update_fre... | b409c49ea41eee91421a0229539cc62e00d5960b | 62,379 |
def sum_fibs(limit):
"""Sums even Fibonacci numbers upto `limit`
Args:
limit (int) : The limit the sum will be calculated to
Returns:
int : The sum of even Fibonacci numbers upto `limit`
"""
previous = 0
current = 1
future = 1
result = 0
while True:
future ... | 7e515e46880240f670bfd47fb54ac72768aac841 | 62,380 |
from typing import Dict
def associations_to_all_features(
table: str,
cohort_id: str,
obj: AllFeaturesAssociation = Body(
...,
example=ASSOCIATIONS_TO_ALL_FEATURES_EXAMPLE,
),
conn=Depends(get_db),
api_key: APIKey = Depends(get_api_key),
) -> Dic... | fa241a642d1eaa76192006c1493ca3c57466a600 | 62,381 |
def Tc(grav):
"""Function to Calculate Gas Critical Temperature in °R"""
#grav gas specific gravity
return 169.2 + 349.5 * grav - 74 * grav ** 2 | 3ad5f19b9868b05b77482db31080107723c3b303 | 62,382 |
def get_laram_details():
"""
"""
return render_template("alarmdetails.html") | cb66dff10542cff31a3f2f036450e9ab481228f9 | 62,383 |
def _combine_dict(train_dict, eval_dict, train_idx, eval_idx):
"""Recursive helper function that combines dict of tensors from two splits
into one tensor using provided indices
Parameters
----------
train_dict : dict
Dict containing tensors from `train_split`. Format
expected to ma... | 8f1969efafd04297df762df7b898c6a6b23f3ffb | 62,384 |
def get_training_datasets_dir() -> str:
"""
Get the training datasets directory of the project.
"""
return f"{get_data_dir()}/training_datasets" | 5e31b381c7380bffe9fb47c595e848e98b433492 | 62,385 |
def _Backward3a_T_Ps(P, s):
"""Backward equation for region 3a, T=f(P,s)
>>> "%.7f" % _Backward3a_T_Ps(20,3.8)
'628.2959869'
>>> "%.7f" % _Backward3a_T_Ps(100,4)
'705.6880237'
"""
I=[-12, -12, -10, -10, -10, -10, -8, -8, -8, -8, -6, -6, -6, -5, -5, -5, -4, -4, -4, -2, -2, -1, -1, 0, 0, ... | 90e87dd41a590e4c138165d07e67416706c04aef | 62,386 |
def sample_normalize(masked_counts, settings):
"""Normalize a UMI count table sample-wise."""
filter_level = settings["copyStableLevel"]
filter_values = settings["copyStableValues"]
col = masked_counts.columns
all_values = col.get_level_values(filter_level)
if filter_values == "none":
fi... | 8d09bebe40327a6ef492a3ead4624de254b88eeb | 62,387 |
def collect_nested_symbols(normalized_symbol):
"""
from a symbol object, collect nested symbols
:param normalized_symbol: used to collect nested symbols
:return: iterable of nested symbols
"""
dict_values = collect_nested_symbols_in_object_dict(normalized_symbol)
nested_code_objects = collec... | ac35ceb7b4c4d693e7e4698a8faa77ab6fa9616a | 62,388 |
def ptp_header16():
"""
This method returns the ptp header definition
"""
return read_template('template/headers/ptp16.txt') | 022a66a5502b5bf0819bc9bf069b7362cb6e153b | 62,389 |
def update_graph(ctg_value, num_value, chart_choice):
"""
This function will update the plot base on the radio button and the selection from two dropdown bar
param ctg_value: this is the category value selection from the dropdown bar
param num_value: this is the numerical value selection from the dropd... | c346d1e0d324066cf3b40c323a9cfcc5f922095e | 62,390 |
def parse_expression(src):
"""Returns the AST of given identifier.
Args:
src: A piece of code that represents a single Python expression
Returns:
A gast.AST object.
Raises:
ValueError: if src does not consist of a single Expression.
"""
node = parse_str(src)
assert isinstance(node, gast.Modul... | 477efdfb9c4c19ba652928d73316f127f750cd4e | 62,391 |
def constrain_rgb(rgb, inplace=False):
"""
If the requested RGB shade contains a negative weight for
one of the primaries, it lies outside the colour gamut
accessible from the given triple of primaries. Desaturate
it by adding white, equal quantities of R, G, and B, enough
to make RGB all posit... | 64291cea625d6ef495e2203fbc77cfec3d14a896 | 62,392 |
def changeFrom12To24(aString):
"""
Changes the format from am/pm to 24h system.
:param aString: String representing an hour value.
:return:
"""
if aString == "1":
aString = "13"
if aString == "2":
aString = "14"
if aString == "3":
aString = "15"
if aString == ... | 3a5432a4d1dc6672445b0df9ccb09edd335dacce | 62,393 |
def is_git_repo(repo_path):
"""Checks if a given path is a git repo
Args:
repo_path (os.path): path to the dir that needs to be tested to see if the dir is a git repo
Returns:
bool: True if path is a git repo.
"""
try:
_ = git.Repo(repo_path).git_dir
return True
... | 11d40690f8973b3307a340094596cbaf161a7490 | 62,394 |
from typing import Tuple
def _get_planar_roi_reference_item(
group_item: ContainerContentItem,
) -> Tuple[Code, ContentItem]:
"""Get the content item representing a planar measurement group's ROI.
Parameters
----------
group_item: highdicom.sr.ContainerContentItem
SR Content Item represen... | 618595341bdaf32d747488855df8d1e982b532e4 | 62,395 |
def _parse_to_last_comment(comments):
"""Unpack to get the last comment (hence the -1) or give '' when there is none"""
return [(c[-1]['comment'] if hasattr(c, '__len__') else '') for c in comments] | ecde5f3d6df3278c5ac1e600241c1afd2f553a1b | 62,396 |
def softmax_cross_entropy_with_logits(labels, logits, name=None):
"""Compute the softmax cross entropy with contiguous labels.
Examples:
```python
labels = tf.constant([[0., 1., ], [1., 0.]], dtype=tf.float32)
logits = tf.constant([[0.5, 0.5], [0.3, 0.7]], dtype=tf.float32)
print(tf.nn.softmax... | d297ec996ff97b7db79290529a3c2585ac15dc0b | 62,397 |
def parse_since(since_str):
"""A utility function to help parse a since string."""
if since_str == 'all':
since_date = None
else:
try:
since_date = parse_date_relative(since_str)
except TypeError:
since_date = None
return since_date | 03b40e1e17571967361c2b487c762b6de2913f96 | 62,399 |
def extract_command(text):
"""
Extracts the command from `text` (minus the '/') if `text` is a command (see is_command).
If `text` is not a command, this function returns None.
Examples:
extract_command('/help'): 'help'
extract_command('/help@BotName'): 'help'
extract_command('/search black... | f73e3a01b22ef8bf612c8a06fd2d3636657cba16 | 62,400 |
def get_files_array(path):
"""
get files as array
"""
files = []
for file in files_collect(path):
files.append(file)
return files | 48a8b5b8f89fcf51b8e751f48fa39b8111c7afbb | 62,401 |
def complete_tree_pair(aidx, bidx, adoc, bdoc, ops, adoc_range=None, bdoc_range=None):
"""this function extend the subphrases to their matching subtrees.
Returns:
[Span, Span]: the extended aspan, and bspan
"""
if is_punct_phrase(aidx, adoc) and is_punct_phrase(bidx, bdoc):
return a... | b97cd5623f13c0891b64b33c1858186cdf6a71cf | 62,402 |
import re
def decompose_molecule(molecule, n=1):
"""
Returns the chemical constituents of the molecule, and their number.
Parameters
----------
molecule : str
A molecule in standard chemical notation,
e.g. 'CO2', 'HCO3' or 'B(OH)4'.
Returns
-------
All elements i... | a332f40d5d20c349abe97569ce0129c7e9d03543 | 62,403 |
from typing import Union
from typing import Optional
def set_chat_description(token: str,
chat_id: Union[int, str],
description: Optional[str] = None
) -> bool:
"""Use this method to change the description of a group,
a supergroup or a... | b47a1fb2374b73cde21d9a8eece47f2611fd7bc8 | 62,405 |
def converte_int_char(inteiro):
"""Converte um inteiro para um caractere segundo a tabela ASCII
com correção do valor do inteiro, segundo enunciado e uso da função chr(), para que:
0 = '_' = , 1 = 'a' = , 2 = 'b', ..., 26 = 'z' e 27 = '.'
Args:
inteiro (int): inteiro a ser convertido em carac... | e7550dec4aa3e4a82729728befcb566e9d8315d0 | 62,406 |
def create_iterable_dataset(torch_transforms_module, pipeline_results):
"""
Create a PyTorch iterable dataset that loads samples from pipeline results.
:param torch_transforms_module: The imported torch.transforms module.
:param pipeline_results: Pipeline results iterator.
:return: Dataset that has... | 1de2f8be910da07e1a63e177f59d9bf0467edbe1 | 62,407 |
import json
def add_flow(req):
"""
:param req:
:return:
"""
r = {}
post_args=req.POST
f = flowgroup()
f.name = post_args.get('title')
try:
r['msg'] = '%s saved.' % (f.name)
r['status'] = '200'
f.save()
return HttpResponse(json.dumps(r, ensure_ascii... | 6ea4ed871b2b5363fcca519eb0fbc27c4886da5a | 62,408 |
def subset_gctoo(gctoo, row_bool=None, col_bool=None, rid=None, cid=None,
ridx=None, cidx=None, exclude_rid=None, exclude_cid=None):
""" Extract a subset of data from a GCToo object in a variety of ways.
The order of rows and columns will be preserved.
Args:
gctoo (GCToo object)
... | 2513c5449ac294ea9e79ac69f09b58ec9579d154 | 62,409 |
def dtype(request, device):
"""Run a test case in single and double precision."""
return request.param | 8196d76b2edd4bd66253b675f4636b77208f7617 | 62,410 |
import ipdb
def reduce(*event_lists):
"""
intersect all events of multiple sources to one dict of date: summary
"""
result = {}
for cal_items in event_lists:
for item in cal_items:
try:
ref = item['start'].get('date', None) or item['start'].get('dateTime')
... | f247481bb193aebbe8cb9b038347af2b409c2ae4 | 62,411 |
from typing import Dict
from typing import Callable
def is_current_builder() -> Dict[str, Callable]:
"""Inject a function to evaluate whether or not a result is current."""
def is_current(result: dict) -> bool:
"""Determine whether the result is the current version."""
if result['submitted_dat... | 35b44ee27a24ecb09f6e76245aab4619971dc17e | 62,412 |
from io import StringIO
def download_image(session, url):
"""" dumps image into memory """
dl = session.get(url, stream=True)
img = StringIO()
img.write(dl.content)
img.seek(0) # rewind to beginning
return img | ed3ab31b0eb3419e34085585aeb742252713be51 | 62,413 |
def scale_alpha(range=None, name=None, breaks=None, labels=None, limits=None, na_value=None, guide=None, trans=None,
format=None):
"""
Scale for alpha.
Parameters
----------
range : list
The range of the mapped aesthetics result.
name : str
The name of the scale ... | 02626c2f8c347e4cf757a5c08da5bd88674531ed | 62,414 |
def formation_energy_table(
defect_phase_diagram: DefectPhaseDiagram,
chempot_limits: dict = None,
fermi_level: float = 0,
hide_cols: list = None,
show_key: bool = True,
pd_facets: list = None,
):
"""
Prints the formation energy tables for either a single chemical potential limit (i.... | 9ecec1588f3367a8a33241562d1aa9d34da717ba | 62,415 |
def get_attr_info(key, convention, normalized):
"""Get information about the MMD fields.
Input
=====
key: str
MMD element to check
convention: str
e.g., acdd or acdd_ext
normalized: dict
a normalized version of the mmd_elements dict (keys are, e.g.,
'personnel>or... | 53e6d389935fead65173c3fd66d3608daa9c7ebc | 62,416 |
def unpad(x, pad_width):
"""
func to unpad slice (FOR LINUX)
----------
x : ndarray
image array
pad_width : tuple
tuple fed to np.pad
Returns
-------
ndarray
unpadded img
"""
slices = []
for c in pad_width:
e = None if c[1] == 0 else -c[1]
... | bedab5694f287d1ccd84f4240306c9d18cb38b8a | 62,417 |
def hello_world():
"""..."""
jsn = request.json
c = conn.cursor()
c.execute("insert into User values ({},{},{},{},{},{})".format(jsn['user_id'],
jsn['email_address'],
j... | d6187a1fd0a73cff75523ce3d4f45e9987e0c59d | 62,418 |
from pkg_resources import resource_filename
def get_ffxml_path():
"""
Return the path where OpenMM ffxml forcefield files are stored in this package.
Returns
-------
path : str
The absolute path where OpenMM ffxml forcefield files are stored in this package
"""
filename = resource... | 29b9d3de56560ce6ddd690ffe944fe890c80f0ed | 62,420 |
def evaluate_semeval_monolingual(vectors, lang):
"""
Get a semeval score for a single monolingual test set.
"""
spearman_score = measure_correlation(spearmanr, vectors, read_semeval_monolingual(lang))
pearson_score = measure_correlation(pearsonr, vectors, read_semeval_monolingual(lang))
score = ... | a529d58ad064f84683f1afcc4a6d4a6ca24c5f25 | 62,421 |
def exists_type(curs: Cursor, type_name: str) -> int:
"""Does type exists?"""
schema, name = fq_name_parts(type_name)
q = """select count(1) from pg_namespace n, pg_type t
where t.typnamespace = n.oid
and n.nspname = %s and t.typname = %s"""
curs.execute(q, [schema, name])
re... | fdbfd1670db81ff9317e9ea04d4e4ac4b3db7230 | 62,422 |
def override(args, overrides):
"""override optional arguments with arguments from the config file"""
args_dict = vars(args)
for key, value in overrides['args'].items():
if key == 'config':
raise utils.FatalException('argument "%s" specified in the config '
'override could... | 4ec582bf506a82852496756bf8e67ee3997ad92a | 62,424 |
def _infer_decision_threshold(y_proba: np.ndarray,
y_true: np.ndarray,
default_dt: float,
results_at_recall: float=None) -> float:
"""infer decision threshold based on given recall value, """
if results_at_recall:
... | f64f1f433c9b74420601961ad69ed2c1bdc17bd5 | 62,425 |
def toggle_doors(doors, skip):
"""Toggle every skip door in doors.
doors is an array of elements where a false value represents a
closed door and a true value represents an open door.
If skip is 1, toggle door #1, #2, #3...
If skip is 2, toggle door #2, #4, #6...
Returns doors
"""
for... | 7631bbc860c4bfa9a7c236a07ebfdb1092bd351c | 62,426 |
def has_year(line):
"""
:type line: FrekiLine
:rtype: bool
"""
return bool(line.search(year_str)) | b24ca4cc25174a62733f49c026f501d1832fac11 | 62,427 |
import math
def presion_vapor_tmed(tmed):
"""
calcula la presión del vapor en saturación a la temperatura media kPa
param: tmed : temperatura media
"""
return 0.6108*math.exp(17.27*tmed/(tmed+237.3)) | 968fc144037e57d688a8f0f5e19a0d7779e5bc9b | 62,428 |
from typing import Tuple
def double(user: str, num: int = 0) -> Tuple[str, str, str]:
"""Return JSON Object."""
return ("OK", "text/plain", f"{user}-{num}") | 57a540ff9cd021847dff39f6ee02960c527f0b36 | 62,431 |
def reward_fixture():
""" Reward for 4 state MDP, reward of 1 for single state, 0 elsewhere """
return np.array([0, 0, 0, 1]) | 9cb33d03137d3921da7e8b82403d98f52db020d1 | 62,432 |
import re
def find_first_arg_pos(bracket_offset, curr_line, args=None):
""" find_first_arg_pos(bracket_offset : int, curr_line : str) -> [int, int]
Arguments:
bracket_offset - The position of the bracket in the current line e.g
" ( list 'timey 'wimey )" --> 4
" ( list 'timey 'wimey ... | 33732d7c0141b4d1c5e9942a299e2be9c64f4813 | 62,433 |
def get_col_dim(col):
"""
Get the physical dimension of a column by its name.
Args:
col (str): the name of the column.
Returns:
str: the physical dimensions of the given column.
"""
for dim in DIM_COL.keys():
if col in DIM_COL[dim]:
return dim | ede5df4189caa156a40708292f0c2d838712792c | 62,434 |
def prerank(rnk, gene_sets, outdir='GSEA_Prerank', pheno_pos='Pos', pheno_neg='Neg',
min_size=15, max_size=500, permutation_num=1000, weighted_score_type=1,
ascending=False, processes=1, figsize=(6.5,6), format='pdf',
graph_num=20, no_plot=False, seed=None, verbose=False):
""" Ru... | 5b94e1d52b87671aea9a8090010f1a8040d044c3 | 62,435 |
def metade(valor=0, formatc=False):
"""
-> Dá a metade de um valor.
Parâmetros opcionais
:param valor: Valor que será dobrado.
:param formatc: Booleano que indica se a formatação no valor será feita
:return: Valor dividido em dois com a formatação ou não.
"""
res = valor / 2
return r... | 83b25300b2b476fa0ec7b78ed5390d223b431376 | 62,436 |
def get_repo_url(mead_tag, nexus_base_url, prefix="hudson-", suffix=""):
"""
Creates repository Nexus group URL composed of:
<nexus_base_url>/content/groups/<prefix><mead_tag><suffix>
:param mead_tag: name of the MEAD tag used to create the proxy URL in settings.xml
:param nexus_base_url: the b... | b422b46da7c039575c9dbfd5ce5bf7157e64f9b4 | 62,438 |
def remove_false_deletes(tokenized, text):
""" Sometimes a statement like 'Removing the 'x' from the end of
paragraph can be confused as removing the paragraph. Ensure that
doesn't happen here. Likely this method needs a little more work. """
contains_delete = bool(matching(tokenized, tokens.Verb, verb=... | 16c7b479ad2d98a15ac9cd9d9f4f678af24dffa4 | 62,439 |
import functools
import warnings
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
@functools.wraps(func)
def new_func(*args, **kwargs):
warnings.simplefilter('always', D... | 7886ce0db1e81b3856222fb1ea3f6b2080b18474 | 62,440 |
def get_manufacturer(metadata):
"""Extract scanner manufacturer from DICOM tags."""
if [0x8, 0x70] in list(metadata.keys()):
manufacturer = metadata[0x8, 0x70].value
if 'Siemens' in manufacturer or 'SIEMENS' in manufacturer:
manufacturer = 0.0
elif 'Philips' in manufacturer ... | 9814f026d1ce6c8c83dbcd2b6132a80d5ea7fdac | 62,441 |
def count_times(func):
"""
Checks how many times a function repeats.
:param func: dictionary in the format (k, v): (name of brodmann area, name of the functions)
"""
times = dict()
for val in func.values():
for v in val:
inc = 1
v = v.split("\t\t")[1]
... | 0080eaf022f1de61cc9e4a06ffec1a87c5cc8980 | 62,442 |
import itertools
def GetBoundingBoxOfCoordinates(coordinates):
"""Returns smallest box containing all lat/long coordinates in given list.
Args:
coordinates: list of (lat, lon) 2-tuples.
Returns:
BoundingBox object.
"""
# Latitude is easy
north = max(x[0] for x in coordinates)
south = min(x[0] f... | ff5d556831c650c7178a703200d2ea3620b1cf53 | 62,443 |
def trunc_sequence(df: pd.DataFrame, max_len: int = -1) -> pd.DataFrame:
"""
Truncate the length of the passed
in dataframe to the max length.
:param df: pd.DataFrame, The dataframe to truncate.
:param max_len: int, The length to truncate the df to.
:return: pd.DataFrame
"""
return df.truncate(after=(max_len... | 16466e4fef170cd10171d327cc7903862b1deaca | 62,444 |
import typing
async def wait_for_component(
client: discord.Client,
component: typing.Union[str, dict, list] = None,
message: typing.Union[discord.Message, int, list] = None,
check=None,
timeout=None,
) -> ComponentContext:
"""
Helper function - wrapper around 'client.wait_for("component",... | bec60ec84d7ad03318272be30b459eb3e83f9703 | 62,445 |
def max_eigenvalue_constraint(x_vec, max_eigenvalue):
"""
This function defines an inequality constraint on the maximum eigenvalue of a SPD matrix.
The value returned by the function is positive if the inequality constraints is satisfied.
Parameters
----------
:param x_vec: SPD matrix in Mandel... | 02810dbe9f57a11548de123d5278d896002f021f | 62,446 |
def guess_timezone_by_ip(ip, only_name=False):
"""Given an `ip` with guess timezone using geoip2.
Returns a tuple of (tz_offets, tz_name, tz_formated).
`None` is returned if it can't guess a timezone.
For this to work you need to set tz_utils.GEOIP_DATA_LOCATION
You can get this database from http:... | d2be11536a06f5f9b6770b546404bc58e0ba762c | 62,447 |
def get_insert_cmd(insert_fields, table, update_cmd=None):
"""
Creates the insert command to use with an insertion to a PostgreSQL database,
given the table and the fields to be inserted
Parameters
----------
insert_fields: list of strs
Fields of data that will be inserted
table: st... | d026911c0574bc2f8a52ede5bbb72b48d81272f8 | 62,448 |
def XCAFDoc_LayerTool_GetID(*args):
"""
:rtype: Standard_GUID
"""
return _XCAFDoc.XCAFDoc_LayerTool_GetID(*args) | 6afb65fdc6c6da71181a57fb9bc1e34c5abd07f4 | 62,449 |
def kojak(kojak_txt: str, perc_inter: str, perc_intra: str, out_file: str,
version: str = "2.0-dev", max_charge: int = 8,
decoy_prefix: str = "decoy_", to_pin: bool = False) -> None:
"""
Convert Kojak search results to xenith tab-delimited format.
For conversion, the Kojak searches must... | df709826dbe8e702ae2b362120638d16623caddb | 62,451 |
import logging
def extract_df(dic=input, file=None):
"""
:param dic: global input parameters that can be altered in the config.py file
:param file: str: name of the file containing a sieving sample
:return: dataframe of sieving sample
"""
df = pd.read_excel(file, engine="openpyxl", header=Non... | 5c491074eaac0886313304f14457730495926b28 | 62,452 |
from typing import Dict
from typing import Any
def generate_artificial_data(params_dict: Dict[str, Any]):
"""Generate artificial biomarker data.
Args:
params_dict: Parameters for the data to generate (see
parameters of :func:`generate_artificial_classification_data`).
Returns:
... | e6779756a7d61234dd6b464743bec90e8b1c3f40 | 62,453 |
def serialize(gtp_command, gtp_response):
"""Serialize a GTP response as a string.
Needs the command we are responding to so we can match the sequence
number.
"""
return '%s%s %s\n\n' % (
'=' if gtp_response.success else '?',
'' if gtp_command.sequence is None else str(gtp_command.s... | 32412766b3d1db92a8aae653dbf8b11a761e35b1 | 62,454 |
def create_entry(request):
"""Creates a new entry or shows the create form"""
if request.method == 'POST':
new_entry = EntryForm(request.POST)
if new_entry.is_valid():
# create the entry
util.save_entry(new_entry.cleaned_data['title'], new_entry.cleaned_data['entry'])
... | 0562bbc939e6bdcc5c3fb1bef4a572fc0439bc50 | 62,455 |
def after(f, chain=False):
"""Runs f with the result of the decorated function."""
def decorator(g):
@wraps(g)
def h(*args, **kargs):
if chain:
return f(g(*args, **kargs))
else:
r = g(*args, **kargs)
f(*args, **kargs)
... | b4897684320927a86915335084f3da7ae126dec5 | 62,457 |
def fill_template(template_pack, predictions, eoa_id, pad_id, eos_id):
"""
:param template: [batch_size, max_seq_len]
:param mask: [batch_size, max_seq_len]
:param predictions: a list of tensors
:return:
"""
def _transpose(a):
"""
:param a: mask_num * batch_size * undefined_l... | 2d0ff6a31688608755188772ed6b87cac05fa620 | 62,458 |
from kotti.resources import get_root
def root(db_session):
"""returns Kotti's 'root' node."""
return get_root() | 165f71869534832541b292b33512abf70e035f1f | 62,459 |
from typing import Optional
from typing import Dict
from typing import List
from typing import Any
from typing import cast
def call_service(
ctx: Configuration,
domain: str,
service: str,
service_data: Optional[Dict] = None,
) -> List[Dict[str, Any]]:
"""Call a service."""
try:
req = r... | 8eb97e1be3efcddac5f6b982c1bed29f84259c9c | 62,460 |
def list_entries():
"""Return entries to be displayed in rofi."""
return(['']) | 76223be8cc86d9b9592edd1849ac1a8862c4d01c | 62,461 |
def eval(y_true, y_pred, normalize=False, verbose=3):
"""Evaluate the results in a two-class model.
Parameters
----------
y_true : array-like
True labels of the classes.
y_pred : array-like
Predicted labels.
normalize : bool, optional
Normalize the values in the confusio... | dd26ee9b70af25a11323fa420d5ac4709afa0fd2 | 62,463 |
import copy
def add_missing_fields(og_layout, tab):
"""
Adds missing fields to the layout.
"""
layout = copy.deepcopy(og_layout)
missing_fields = tab.get_missing_fields(layout.get("content"))
if not missing_fields:
return og_layout
tab_data = tab.get_from_tabs(layout.get("content")... | 040f47606c5b89a52ed9defc4a9dbdda56c4cb2a | 62,464 |
def collate_effect_size(counts, powers, alpha):
"""Calculates the effects for power values
Parameters
----------
counts : array
the number of samples used to calculate the power
powers : {list, ndarray}
list of arrays of power values. If there are multiple power arrays,
each... | f8171545e5b7a11a42da081a070be8232dd81199 | 62,465 |
def sample_dirichlet_multinomial(dirichlet_alphas:np.ndarray, num_samples:int) -> np.ndarray:
""" Sample from a Dirichlet-multinomial distribution
Parameters
----------
dirichlet_alphas : numpy.ndarray
The concentration parameters for the Dirichlet distribution
num_samples : int
Th... | 8cfe8a5fd8465d82612e176973c3a23d45eebd04 | 62,466 |
def lift_hand(env_lift, tot_reward):
""" Lift hand with set action velocities
env_lift: Mujoco environment
tot_reward: Total cumulative reward
"""
# action only used to move hand, not recorded in replay buffer and is NOT used to update policy
action = np.array([wrist_lift_velocity, finger_lift_v... | ccba8cee7a92bb60672d4ca09b351cc0666c6083 | 62,468 |
import torch
def get_autoencode_minibatch(
lines, word2ind, index, batch_size,
max_len, add_start=True, add_end=True
):
"""Prepare minibatch."""
if add_start and add_end:
lines = [
['<s>'] + line + ['</s>']
for line in lines[index:index + batch_size]
]
elif ... | 953785f3042e4800e7343c886d84218e6be5b171 | 62,469 |
def read_file(path):
"""
Return the contents of a file
Arguments:
- path: path to the file
Returns:
- contents of the file
"""
with open(path, 'r') as file:
return file.read().rstrip() | 85d64985da7c9ea15b314d25b42ad2bc6491a111 | 62,470 |
def build_scaler_train_and_test_datasets(
label,
train_features,
test_feature,
df,
test_size,
seed,
scaler_cast_to_type="float32",
min_feature_range=-1,
max_feature_range=1):
"""build_scaler_train_and_test_datasets
:param label: log label
... | da94aa27d78c22dfaaa03e441f83519d0c4b179d | 62,471 |
def _entitlements(ctx):
"""Returns the entitlement file to be used for codesigning."""
# Use the entitlements from the internal provider if it's present (to support
# rules that manipulate them before passing them to the bundler); otherwise,
# use the file that was provided instead.
if getattr(ctx.... | d177c53a4d74319203d197fbe3561b5d4de3a6bf | 62,472 |
def dwconv_block(
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
padding: int = 1,
dilation: int = 1,
bias: bool = False,
use_bn: bool = True,
bn_eps: float = 1e-5,
activation=(lambda: nn.ReLU(inplace=True))
):
... | 4cf99e00f04a4d8e6fbb2ba75601fd4879898409 | 62,473 |
def test_db():
"""Provide an in-memory database for testing."""
return SqliteDatabase(':memory:') | 97c13d2a6bd3c8cc49349f480be1983b1aa29147 | 62,474 |
def get_venv_packages(venv_path):
# type: (str) -> Set[str]
"""
Returns the packages installed in the virtual environment using the
package index file.
"""
with open(get_index_filename(venv_path)) as reader:
return set(p.strip() for p in reader.read().split('\n') if p.strip()) | 6aae4c5bd8d663a25b41205fd6ae4e3a2b02368d | 62,475 |
def get_roi_ious(rois, gt_boxes):
"""
Get IoU per Reion Proposals (Column 1 == GT Box1, Column 2 == GT Box2 ...)
"""
roi_ious = np.zeros([len(rois), len(gt_boxes)])
for i in range(len(rois)):
for j in range(len(gt_boxes)):
roi_ious[i, j] = get_iou(boxA_pts=rois[i], boxB_pts=... | 0a6b67e18efd16e58b3ae1428cc7bca227d6e5d7 | 62,476 |
import tempfile
import base64
def _setup_conn(**kwargs):
"""
Setup kubernetes API connection singleton
"""
kubeconfig = kwargs.get("kubeconfig") or __salt__["config.option"](
"kubernetes.kubeconfig")
kubeconfig_data = kwargs.get("kubeconfig_data") or __salt__[
"config.option"]("kub... | 95635f66ae1df336c9f725bd281fb8bccac057cb | 62,477 |
from datetime import datetime
import json
def get_co2_latest():
"""
Returns the co2 values for the most recent day.
"""
if request.method == 'GET':
try:
session = co2DB.create_session()
date = datetime.now().replace(hour=0, minute=0)
if date == None:
... | 7e40218227024f7f9e7a53134502361b642cd428 | 62,478 |
def get_default_db_file():
"""Returns default location of db file"""
return DEFAULT_DB_LOCATION | 25f374ea1392a63d7ad557800241ee1ff8b74e7f | 62,480 |
def dashboard_post(request, status='all', category='all', page=1):
"""Dashboard"""
list_count = settings.DASHBOARD_LIST_COUNT
if int(page) < 1:
return redirect('blogs:dashboard_post', status, category, 1)
current_page = int(page) - 1
start_at = current_page * list_count
end_at = start_... | 91620494da8ca1ee766888d78fe04a1a2451dd90 | 62,481 |
def next_power_2(x: int) -> int:
"""Return the smallest power of 2 greater than or equal to x"""
return 1 << (x-1).bit_length() | f5361250c1a6ef8228adcfd0aeab478484e7239b | 62,483 |
def ismir2015_evaluate(niter=0, **kwargs):
"""
inputs:
niter - number of permutation test iterations to run [0=none]
**kwargs - key-word arguments for tsne analysis function {harmonic_}tsne_all()
ref_idx - reference audio file, all audio warped to this [9]
dfun - distance function to use [bregma... | 737814eb30bd97fa679134d63e97869893125fb1 | 62,484 |
def create_new_pet(
obj_in: PetCreationForm,
current_user=Depends(get_current_user)
):
"""
Add a new pet to DB
"""
if obj_in.owner != current_user["id"]:
raise HTTPException(
status.HTTP_403_FORBIDDEN,
"You are not authorised for this operation."
)
n... | e48d134f8e8e77fe4abd827dcab65d9af6af0492 | 62,485 |
def get_rnai_essentiality(symbol: str) -> float:
"""Get essentiality of the gene in the RNAi experiments."""
return _get_essentiality(symbol, "rnai") | fde9f7f748c79cb85b15fb649848a574057d5e5a | 62,486 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.