content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _lst_for_pes(pes_dct, run_pes_idxs):
""" Get a dictionary of requested species matching the PES_DCT format
"""
red_pes_dct = {}
for (form, pidx, sidx), chnls in pes_dct.items():
# Grab PES if idx in run_pes_idx dct
run_chnl_idxs = run_pes_idxs.get(pidx, None)
if run_chnl_idx... | 5,290,700 |
def cholesky_decomposition(matrix):
"""
Compute the Cholesky decomposition of a symmetric positive definite matrix
"""
# compute the decomposition
gsl.linalg_cholesky_decomp(matrix.data)
# and return the matrix
return matrix | 5,290,701 |
def assert_results_close(res1: InferenceResult,
res2: InferenceResult,
log_pf_tol=1e-9,
mp_mse_tol=1e-9):
"""
:param log_pf_tol: Absolute tolerance for log partition function.
:param mp_mse_tol: Absolute tolerance for mean square err... | 5,290,702 |
def _cvt_names_to_graph(srcpath, destpath):
"""Translates model pathnames into pathnames in term of
our 'fake' graph nodes @xin, @bin, @bout, and @xout.
"""
srcvar, _ = _split_expr(srcpath)
srccompname, _, srcvarname = srcvar.partition('.')
destcompname, _, destvarname = destpath.partition(... | 5,290,703 |
def test_running_no_change(test, running):
"""
running state test, no change required case.
"""
with patch.dict(virt.__opts__, {"test": test}):
update_mock = MagicMock(return_value={"definition": False})
start_mock = MagicMock(return_value=0)
with patch.dict(
virt.__s... | 5,290,704 |
def jobs_command(num_jobs=-1, dirty_flag=False, allow_unknown=False,
default_to_all=True):
"""
Base options for jobs that take a list of jobs names.
Expects a *base_dir* argument, so normally used after ``@repos_command``.
Number of jobs accepted in argument can be controlled with *nu... | 5,290,705 |
def math_pow(x, y):
"""Implement the SQLite3 math built-in 'pow' via Python.
"""
try:
return math.pow(x, y)
except:
pass | 5,290,706 |
def grid_search(estimator, param_grid, X_train, y_train, X_test, y_test, batch_size=10000, nn=False):
""" Performs grid search over parameter grid.
Function iterates over the combinations of parameters in the parameter grid. Trains the estimator on the X_train.
Evaluation is done on both the training set a... | 5,290,707 |
def run_refinement_scoring_example(train_path, test_path, with_tuning=False):
""" Function launch example with error modeling for classification task
:param train_path: path to the csv file with training sample
:param test_path: path to the csv file with test sample
:param with_tuning: is it need to tu... | 5,290,708 |
def get_voted_content_for_user(user):
"""Returns a dict where:
- The key is the content_type model
- The values are list of id's of the different objects voted by the user
"""
if user.is_anonymous():
return {}
user_votes = {}
for (ct_model, object_id) in user.votes.values_li... | 5,290,709 |
def get_bbx_from_seg(label):
"""
Get a bounding box from a binary mask
"""
border_list = [-1, 40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 520, 560, 600, 640, 680]
img_width = 480
img_length = 640
rows = np.any(label, axis=1)
cols = np.any(label, axis=0)
rmin, rmax = n... | 5,290,710 |
def odd_occurences_in_array(a):
"""
Finds the odd number of occurences of an element in an array.
XOR of all elements gives us odd occurring element.
Note that XOR of two elements is 0 if both elements are same and XOR of a number x with 0 is x
:param a
"""
result = 0
for number in a:
... | 5,290,711 |
def new_pm():
""" function that is called when you visit /portfolio_manager/new, creates a new PM """
token = request.headers.get("token")
headers = {"Content-type": "application/x-www-form-urlencoded", "token": token}
message, info = verify_token(token)
if message != None:
return create_... | 5,290,712 |
def search_filter_order():
"""
set order of search filters to be used in searches
"""
search_filter_order = questionary.select(
"Specify the order of search filters to be used in searches:",
choices=list(SearchFilterOrderOption),
default=SearchFilterOrderOption[CURRENT_SETTINGS["... | 5,290,713 |
def _data_aug_fn(image, ground_truth):
"""Data augmentation function."""
ground_truth = cPickle.loads(ground_truth)
ground_truth = list(ground_truth)
annos = ground_truth[0]
mask = ground_truth[1]
h_mask, w_mask, _ = np.shape(image)
# mask
mask_miss = np.ones((h_mask, w_mask), ... | 5,290,714 |
def test_create_new_superuser():
"""Test creating a new superuser"""
user = get_user_model().objects.create_superuser("test@testing.com", "test123")
assert user.is_superuser
assert user.is_staff | 5,290,715 |
def to_envelopes(path,num_bands,freq_lims,downsample=True):
"""Generate amplitude envelopes from a full path to a .wav, following
Lewandowski (2012).
Parameters
----------
filename : str
Full path to .wav file to process.
num_bands : int
Number of frequency bands to use.
fre... | 5,290,716 |
def make_folder(l: str) -> None:
"""Make a folder if it does not exist
Parameters
----------
l : str
The folder name and path
"""
Path(l).mkdir(parents=True, exist_ok=True)
return | 5,290,717 |
def upload_tgen_config_file():
"""
Upload Tgen Config File on T-rex
"""
localpath = '/usr/src/app/vsperf/trex_cfg.yaml'
if not os.path.exists(localpath):
print("TGEN config File does not exist................[Failed]")
return
remotepath = '~/trex_cfg.yaml'
check_trex_config_c... | 5,290,718 |
def separe_liste(points):
"""
Parameters
----------
points : TYPE
DESCRIPTION.
Returns
-------
points_1 : TYPE
DESCRIPTION.
points_2 : TYPE
DESCRIPTION.
"""
centroide = trouver_coordonnees_centroide(points)
distances = []
for point in points:
... | 5,290,719 |
def fdq(node_results, Qstar, average_times=False, average_nodes=False):
"""
Compute fraction delivered quality (FDQ), equations modified from [1].
The metric can be averaged over times and/or nodes.
Parameters
----------
node_results : pd.Panel
A pandas Panel containing node result... | 5,290,720 |
def lambda_handler(event: dict, _context: dict):
"""Sample Lambda function that notifies back the Step function that invoked it,
using the Task Token id passed along with its payload
Parameters
----------
event: dict, required
Input event to the Lambda function
Requires a valid task... | 5,290,721 |
def build_point_shapefile(
driver_name, layer_name, path, data, prj, coord_trans):
"""This function creates and saves a point geometry shapefile to disk.
It specifically only creates one 'Id' field and creates as many features
as specified in 'data'
driver_name - A string specifying... | 5,290,722 |
def read_documents(*paths, uri=False):
"""
Read and parse documents from the filesystem or remote URLs (yaml or json).
Note that a single yaml file can contain multiple documents.
This function will load any dates in the documents as strings. In
Data Cube we store JSONB in PostgreSQL and it will t... | 5,290,723 |
def delete_service(service_handle):
"""See: DeleteService function
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682562(v=vs.85).aspx
"""
DeleteService_Fn = windll.Advapi32.DeleteService #BOOL WINAPI DeleteService(
DeleteService_Fn.argtypes = [ #
wintypes.SC_HANDLE # _In_ SC_HANDLE hServ... | 5,290,724 |
def dns_installation(instance, arg, verbose=True):
""" Install bind9 package on the remote instance and configure name resolution for his own domain name """
if install(instance, {"module":"bind9"}, verbose=False) == 1:
return 1
# execute_command(instance, {"command":["truncate", "-s", "0", "/etc/bi... | 5,290,725 |
def manjsa_od(n):
"""Sešteje soda fib.števila, ki niso večja od 4miljonov"""
a = 1
b = 2
vsota = b
seznam = [a, b]
while a + b <= n:
seznam += [a + b]
if (a + b) % 2 == 0:
vsota += (a + b)
x = a
a = b
b = x + b #tu a dobi vrednost b-ja, b pa vr... | 5,290,726 |
def get_inv_aliases():
"""Return a mapping from target to list of sources for all alias
targets in either the default alias table or the unknown_flag alias
table."""
inv_aliases = collections.defaultdict(list)
standard_aliases = add_aliases.read_default_emoji_aliases()
for k, v in standard_aliases.iterite... | 5,290,727 |
def region_expand(
region: RegionLike,
expansion: Union[int, List[int], Tuple[int, int]],
) -> Union[Tuple[int, int], sublime.Region]:
"""
@brief Expand the region by given amount.
@param region The region
@param expansion The amount of left/right expansion
@return the expanded region
... | 5,290,728 |
def median(embedding, neighbors, verbose=False):
"""Initialize points onto an existing embedding by placing them in the
median position of their nearest neighbors on the reference embedding.
Parameters
----------
embedding: TSNEEmbedding
neighbors: np.ndarray
verbose: bool
Returns
... | 5,290,729 |
def test_segment_lookup():
"""Basic validations to ensure that the segment lookup loads"""
assert len(SEGMENT_LOOKUP) > 0
assert "GE" in SEGMENT_LOOKUP
assert "GS" in SEGMENT_LOOKUP
assert "IEA" in SEGMENT_LOOKUP
assert "ISA" in SEGMENT_LOOKUP
assert "ST" in SEGMENT_LOOKUP
assert "SE" i... | 5,290,730 |
def check_file_tab(file_name):
"""
Check if any files contain tabs and return the number of tabs.
"""
f = open(file_name, "r+b")
key_positions = []
for num, line in enumerate(f, 1):
if b'\t' in line:
key_positions.append(num)
if len(key_positions) > 0:
# If there... | 5,290,731 |
def checkExtention(files):
"""
This function will check extention of each file.
"""
for file in files:
if file.name.lower().split(".")[-1] not in ['pdf', "jpeg", "png", "jpg"]:
return file.name + " is not accepted. We accept only 'pdf', 'jpeg', 'png', 'jpg' file format."
return ... | 5,290,732 |
def accuracy(output, target, topk=(1,)):
"""Derived directly from the reference NIPS2017 Workshop.
Computes the precision@k for the specified values of k, used for semi-supervised learning.
"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = p... | 5,290,733 |
def merge_pairs(seq1,
seq2,
qual1,
qual2,
ins1=None,
ins2=None,
q_cutoff=10,
minimum_q_delta=5):
"""
Combine paired-end reads into a single sequence.
Manage discordant base calls on the basis of ... | 5,290,734 |
def activation_func(func_type, z):
"""
Implements the different kind of activation functions including:
sigm - sigmoidal
tanh - hyperbolic tangent
relu - Rectfied
step - Heavside (binary step 0 or 1)
"""
if func_type == 'sigm':
return (1 / (1 + np.exp(-... | 5,290,735 |
def subtract_of_matrices_set():
"""
Принтует в stdout результаты теста по вычитанию матриц.
"""
@out
def test(shape: tuple):
a = create_random_matrix(shape)
b = create_random_matrix(shape)
c = subtract_of_matrices(a, b)
print(f"Calculated subtract of matrices with si... | 5,290,736 |
def get_check_option():
"""
得到和检查用户输入的参数,返回参数对象
"""
logger.debug(sys.argv)
usage = 'usage: python %prog [options]' \
'\nsample1:python %prog --host="127.0.0.1" --username="root" --port=43306 --password="" --schema=test --table="test5"' \
'\n' \
'sample2:python %p... | 5,290,737 |
def find_bubbles(G, path_d, mermap):
"""
We find all cases where n' -> n1 -> n3
n' -> n2 -> n3
(that is, n3 has > 1 incoming) and n1, n2 each have only one incoming and one outgoing
<i> make sure that n1 and n2 is not used in the same path (which indicates in-gene repeat?)
... | 5,290,738 |
def main():
"""main"""
args = get_args()
input_file = args.input
out_file = args.output
keyword = args.keyword.lower()
skip = set(map(str.lower, args.skip))
if not os.path.isfile(input_file):
die('"{}" is not a file'.format(input_file))
print('Processing "{}"'.format(input_file... | 5,290,739 |
def main(args: argparse.Namespace) -> bool:
"""GPG Key Validator
Args:
args (argparse.Namespace): arguments
Raises:
Exception: Local GPG Error
Exception: Platform GPG Error
Returns:
bool: Valid or not
"""
project_key_id: str = ""
if args.key:
# User... | 5,290,740 |
def ldns_dnssec_zone_sign_nsec3_flg(*args):
"""LDNS buffer."""
return _ldns.ldns_dnssec_zone_sign_nsec3_flg(*args) | 5,290,741 |
def sub(x, y):
"""values are subtracted and return"""
return y - x | 5,290,742 |
def _to_numpy_array(arr):
"""
Help function for converting an iterable to a Numpy array.
:param arr: Array we want to convert.
:type arr: Iterable[float]
:return: Input array converted to a Numpy array.
:rtype: :class:`Numpy array <numpy.ndarray>`
>>> _to_numpy_array([1.0, 2.0, 3.0])
a... | 5,290,743 |
def infer_dependency(op):
"""
Infer the dependency of all operations with the
given op as the last operation.
Operator A is depending on B if A uses the output(s) of B.
Args:
op: an Operator instance, e.g. the loss operation.
Return:
a Counter instance with the operation as the... | 5,290,744 |
def test_array_short():
"""Test [write|read]_array function with `short` data."""
__delete_testfile()
write_values = [
random.choice(range(-32768, 32768)) for _ in range(NUMBER_ENTRIES)
]
with open(TEST_FILE, "ab") as test_file:
write_array(test_file, write_values, "short")
re... | 5,290,745 |
def spirale(couleur, largeur):
""" Dessine avec turtle une spirale
paramètres :
- couleur : la couleur à utiliser
- largeur : la largeur du tracé"""
turtle.color(couleur)
turtle.width(largeur)
for i in range(100):
turtle.circle(i * (largeur / 2), 90) | 5,290,746 |
def write_wrangler_to_file(template_variables, template, destination):
"""
Write wrangler symbols to a template.
"""
with open(template, "r") as input:
data = input.read()
data = replace_template_variables(template_variables, data)
with open(destination, "w") as output:
... | 5,290,747 |
def softmax_loss(x, y):
"""
Computes the loss and gradient for softmax classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth
class for the ith input.
- h: Vector of labels, of shape (N,) where h[i] is the label for x[i] and
0 <= h[i] < C
Re... | 5,290,748 |
def stopOscProgress(request):
"""中止该SQL的pt-OSC进程"""
workflowId = request.POST['workflowid']
sqlID = request.POST['sqlID']
if workflowId == '' or workflowId is None or sqlID == '' or sqlID is None:
context = {"status":-1 ,'msg': 'workflowId或sqlID参数为空.', "data":""}
return HttpResponse(json... | 5,290,749 |
def search(request: HttpRequest):
"""
搜索界面的呈现逻辑
分成搜索个人和搜索小组两个模块,每个模块的呈现独立开,有内容才呈现,否则不显示
搜索个人:
支持使用姓名搜索,支持对未设为不可见的昵称和专业搜索
搜索结果的呈现采用内容/未公开表示,所有列表为people_filed
搜索小组
支持使用小组名、小组类型搜索、一级负责人姓名
小组的呈现内容由拓展表体现,不在这个界面呈现具体成员
add by syb:
... | 5,290,750 |
def extract_length(value):
"""
extract length data from a provided value
Returns a tuple of a detected length value and a length unit. If no unit
type can be extracted, it will be assumed that the provided value has no
unit.
Args:
value: the value to parse
Returns:
the len... | 5,290,751 |
def get_session(role_arn, region_name):
"""
Returns a session for the specified accountId
"""
sts_connection = boto3.client('sts')
acct_a = sts_connection.assume_role(
RoleArn=PIVOTAL_ROLE,
RoleSessionName='AWS-Tower'
)
access_key = acct_a['Credentials']['AccessKeyId']
s... | 5,290,752 |
def hgm(args):
"""
Main entry function for hgm module. Runs homGeneMapping after extracting exons and non-coding introns from the
annotation. Exons and non-coding introns are not stored in the database to make predictions go faster.
When we are running homGeneMapping on non-CGP data, we have no new anno... | 5,290,753 |
def get_node_by_name(node_name):
"""
Returns pymxs node object with the given name, if exists in the scene; otherwise returns None
:param node_name: str, name of the node we want to retrieve
:return: variant, pymxs object or None
"""
return rt.getNodeByName(str(node_name)) | 5,290,754 |
def main():
""" Demo for video restoration models.
Note that we accept video as input/output, when 'input_dir'/'output_dir'
is set to the path to the video. But using videos introduces video
compression, which lowers the visual quality. If you want actual quality,
please save them as separate image... | 5,290,755 |
def get_cache_file_metadata_path(cache_file_path):
"""Return metadata file path for a cache file."""
return '%s%s' % (cache_file_path, CACHE_METADATA_FILE_EXTENSION) | 5,290,756 |
def undo_grad_transforms(grad, tasks, transformers):
"""DEPRECATED. DO NOT USE."""
logger.warning(
"undo_grad_transforms is DEPRECATED and will be removed in a future version of DeepChem. "
"Manually implement transforms to perform force calculations.")
for transformer in reversed(transformers):
i... | 5,290,757 |
def check_agency_status(msg):
"""
checks to see if message contains an agency slug
(i.e., char string between two # hashtags)
and, if so, looks up to see what if any agency it belongs to.
returns agency name
"""
slug = check_agency_hashtag(msg)
# sender_agency = check_sender_agency(msg)
... | 5,290,758 |
def euclidean_distance(x: np.array, y: np.array) -> float:
"""Calculates euclidean distance.
This function calculates euclidean distance between
two points x and y in Euclidean n-space.
Args:
x, y: points in Euclidean n-space.
Returns:
length of the line segment connecting giv... | 5,290,759 |
def transform_geojson_wgs_to_epsg(geojson, EPSG):
"""
Takes a geojson dictionary and converts it from WGS84 (EPSG:4326) to desired EPSG
Parameters
----------
geojson: dict
a geojson dictionary containing a 'geometry' key, in WGS84 coordinates
EPSG: int
numeric code for the EPSG ... | 5,290,760 |
def time_offset(tds, insttime, utctime):
"""Calculate and apply time offset to SBE56 time series
Parameters
----------
tds : xarray.DataArray
SBE56 data structure
insttime : np.datetime64
Instrument time at end of time series
utctime : np.datetime64
UTC... | 5,290,761 |
def gaussian_kernel(kernel_shape: tuple, centre: tuple, sigma: float, amplitude: int = 1) -> np.ndarray:
"""Returns a 2D Gaussian kernel array."""
y, x = np.ogrid[0:kernel_shape[0], 0:kernel_shape[1]]
h = np.exp(-(pow(x - centre[0], 2) + pow(y - centre[1], 2)) / (2. * sigma * sigma))
h[h < np.finfo(h.dt... | 5,290,762 |
def bccb4f621e70(Foo, Bar):
"""Let notation."""
Injector.let(bar=Bar) | 5,290,763 |
def test_namespace_pruebas(setup):
"""test_namespace_pruebas asserts that namespaces obtains the expected value on a simple file.
"""
assert setup._generatorfind() == [['Clase1_1', 'Clase1_2', 'firstn'], \
['Clase1_1', 'Clase1_3', 'firstn'], \
['Clase2_1', 'Clase2_2', 'firstn'], ['primera', ... | 5,290,764 |
def web_hook():
"""
transfer station of teambition's webhook to feishu's webhook
"""
# resolve teambition's request, maybe we need some authentication
signature = request.headers.get('X-Signature', '')
response = request.json
type = response['event']
task_state_map = {'task.create'... | 5,290,765 |
def flip_op(input, dims):
"""
Reverse the order of a n-D tensor along given axis in dims.
.. note::
`flow.flip` makes a copy of :attr:`input`'s data. This is different from NumPy's `np.flip`,
which returns a view in constant time. Since copying a tensor's data is more work than viewing... | 5,290,766 |
def deserialize_timestamp_from_binance(time: int) -> Timestamp:
"""Deserializes a timestamp from a binance api query result entry
Kraken has timestamps in integer but also including milliseconds
Can throw DeserializationError if the data is not as expected
"""
if not isinstance(time, int):
... | 5,290,767 |
def intersect(set_a, set_b):
"""
"""
return [x for x in set_a if x in set_b] | 5,290,768 |
def gauss(matrix, free_column: list, level_of_details: int = 3):
"""
Решает СЛАУ методом Гаусса
Args:
matrix (Matrix): матрица, относительно которой требуется решение
free_column (list): столбец свободных членов
level_of_details (int): уровень детализации (меньше число - больше дета... | 5,290,769 |
def import_custom_ops():
"""Import custom and contrib ops needed by this software."""
# TODO(rbg): Consider moving into either model_builder or
# DetectionModelHelper
dyndep.InitOpsLibrary('@/caffe2/caffe2/contrib/nccl:nccl_ops')
ops_path = '@/experimental/deeplearning/rgirdhar/VideoPose/lib/ops'
... | 5,290,770 |
def refine_general(splits, sigma, n=1, combine=lambda a,
b: a + b, key=lambda a: a):
""" Do a general refinement of up to n steps """
oldsplits = splits[:]
N = splits[-1]
counter = 0
k = len(splits)
n = n or np.inf
while counter < n:
splits = [bestsplit_general(sp... | 5,290,771 |
def matrix_exponential(matrix:tf.Tensor, dt):
"""Computes the matrix exponential of one or more square matrices.
$$exp(A) = \sum_{n=0}^\infty A^n/n!$$
The exponential is computed using a combination of the scaling and squaring
method and the Pade approximation. Details can be found in:
Nicholas J. H... | 5,290,772 |
def enumerate_param(param, values):
"""Builds a dictionary of an enumerated parameter, using the param string and some values.
If values is not a list, tuple, or set, it will be coerced to a list
with a single item.
Example:
enumerate_param('MarketplaceIdList.Id', (123, 345, 4343))
Returns:
... | 5,290,773 |
def enumerate_paths(src):
"""flatten out a nested dictionary into an iterable
DIODE metadata is a nested dictionary;
One could easily query a particular scene and scan, but sequentially
enumerating files in a nested dictionary is troublesome. This function
recursively traces out and aggregates the l... | 5,290,774 |
def tweet_decode(tweet):
""" Gets data from tweet and returns a simplified data structure
tweet = {
'full_text': 'This is a tweet #hello #world http://t.co/13456',
'urls': [ 'http://en.wikipedia.org/' ]
'hashtags': [ '#hello', '#world' ]
}
"""
tweet_simple... | 5,290,775 |
def unpack_reports(runner):
"""Unpack reports mentioned in the runner configuration"""
assert os.path.exists(runner["archive"])
name = runner["name"]
archive = runner["archive"]
cmd = f"unzip -q -o -d {name} {archive}"
print(cmd)
subprocess.run(cmd, shell=True, check=True) | 5,290,776 |
def load_clonotypes_csv_general(fname: str, single_return: bool = True) -> pd.DataFrame:
"""
Load clonotypes.csv file. This file is expected to be a comma-delimited table with columns
"clonotype_id" and "cdr3s_aa".
Returned data frame is the df contained in fname with added columns TRA_aa and TRB_aa
... | 5,290,777 |
def test_eta2kparr_wrong_unit():
"""Test eta must be frequncy Quantity."""
test_eta = 200 * 1e-9 * units.m
test_z = 9.19508
pytest.raises(units.UnitsError, cosmo.eta2kparr, test_eta, test_z) | 5,290,778 |
def pattern_search(search_pattern):
"""
Search for search_pattern in pattern. Convert from hex if needed
Looking for needle in haystack
"""
needle = search_pattern
try:
if needle.startswith("0x"):
# Strip off '0x', convert to ASCII and reverse
needle = needle[2:]... | 5,290,779 |
def suite():
"""Define all the tests of the module."""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(SearchV2TestCase))
return suite | 5,290,780 |
def send_password_reset_email(user):
"""generate the password reset emails"""
token = user.get_reset_password_token()
send_email(_('[Microblog] Reset Your Password'),
sender=current_app.config['ADMINS'][0],
recipients=[user.email],
text_body=render_template('emai... | 5,290,781 |
def manhattan_distance(pointA: tuple[int], pointB: tuple[int]) -> int:
"""Returns the Manhattan distance between points A and B, assuming a weight of 1"""
return abs(pointA[0] - pointB[0]) + abs(pointA[1] - pointB[1]) | 5,290,782 |
def SysFont(name, size, bold=False, italic=False, constructor=None):
"""pygame.font.SysFont(name, size, bold=False, italic=False, constructor=None) -> Font
create a pygame Font from system font resources
This will search the system fonts for the given font
name. You can also enable bold o... | 5,290,783 |
def forecast(latitude: float, longitude: float) -> list[Forecast]:
"""Main function for retrieving forecast for a longitude and latitude"""
loop = asyncio.get_event_loop()
*information, request = loop.run_until_complete(_get_gridpoint(latitude, longitude))
res = loop.run_until_complete(_get_forecast(req... | 5,290,784 |
def get_berkeley_format():
"""Creates a configuration for images saved in Berkeley format.
Returns:
the configuration.
"""
config = {}
config['image_name'] = '{}/image_aux1/encoded'
config['state_name'] = '{}/endeffector_pos'
config['action_name'] = '{}/action'
config['state_dim'] = 3
config['act... | 5,290,785 |
def cxyz_to_xyzc( v ):
"""
Takes a torch array and returns it as a numpy array on the cpu
:param v: torch array
:return: numpy array
"""
dim = len(v.shape)-2
if dim ==2:
v = v.permute(0,2,3,1)
if dim ==3:
v = v.permute(0,2,3,4,1)
return v | 5,290,786 |
def start_flow():
"""
Starts the oauth flow. This will return a dict which causes a redirect to the providers page.
"""
LOG.debug("Read OAuth id/secret: none? %s/%s", CLIENT_ID is None, CLIENT_SECRET is None)
github = OAuth2Session(CLIENT_ID, scope=SCOPE)
authorization_url, state = github.aut... | 5,290,787 |
def collect_all_jxs(batch_num, out_path, now, db_conn):
"""Collects all junctions and their annotations for every cancer type.
:param batch_num:
:param out_path:
:param now:
:param conn:
returns None
"""
logging.info('starting collect all jxs function')
all_cancers = list(
... | 5,290,788 |
def monorail_api_method(
request_message, response_message, **kwargs):
"""Extends endpoints.method by performing base checks."""
time_fn = kwargs.pop('time_fn', time.time)
method_name = kwargs.get('name', '')
method_path = kwargs.get('path', '')
http_method = kwargs.get('http_method', '')
def new_decora... | 5,290,789 |
def _extend_dict(main_dict: Union[PerArraySequenceDict, PerArrayDict],
added_dict: Union[PerArraySequenceDict, PerArrayDict]):
"""
We can't do anything like main_dpp.extend(added_dpp).
Doing as in nibabel.streamlines.tests.test_tractogram.
"""
for k, v in added_dict.items():
... | 5,290,790 |
def symlink_dazzdb(actualdir, db_prefix):
"""Symlink elements of dazzler db.
For now, 3 files.
"""
symlink(os.path.join(actualdir, '.%s.bps'%db_prefix))
symlink(os.path.join(actualdir, '.%s.idx'%db_prefix))
symlink(os.path.join(actualdir, '%s.db'%db_prefix)) | 5,290,791 |
def expool(CONST_STRING):
"""expool(ConstSpiceChar * CONST_STRING)"""
return _cspyce0.expool(CONST_STRING) | 5,290,792 |
def deeplab_pascal(save_path='models/deeplab_restnet101.pt'):
""" Download and save deeplab model
Args:
save_path (str, optional): Path to save deeplab model. Must end with '.pt' or '.pth'. Default: 'models/deeplab_restnet101.pt'
"""
if save_path[-3:] != '.pt' and save_path[-4:] != '.pth':
... | 5,290,793 |
def run():
"""Initialise the application in either GUI or CLI mode"""
# Create app, but don't show the frame if command line is being used
# For each file in the input list, load the file (abort if load fails),
# then do a standard export, plus compilation if needed
# If any override flags are set,... | 5,290,794 |
def stackop(func, stack):
"""Returns a function, that operates on the elements of a given stack.
Example for creating a multiply stack operation,
which takes two arguments:
>>> stack = [1, 2, 3, 4]
>>> multiply = stackop(lambda x, y: x * y, stack)
>>> multiply()
>>> stack
... | 5,290,795 |
def get_seed_catalog(seedname="DeveloperSeed"):
"""Returns the developer seed sucatalog"""
try:
seed_catalogs = read_plist(SEED_CATALOGS_PLIST)
return seed_catalogs.get(seedname)
except (OSError, IOError, ExpatError, AttributeError, KeyError) as err:
log.warn(err)
return "" | 5,290,796 |
def generate_all_valid_patterns():
"""Generate all valid dot patterns, as strings representing 16 bit binary numbers.
Valid patterns are made up of dots and blanks in an 8x2 pattern which are
- made up of exactly 10 dots, where 4 dots always make up the left-most and right-most column
- not rot... | 5,290,797 |
def get_id(serving_name):
"""
Gets the id of a serving with a given name
Example use-case:
>>> from hops import serving
>>> serving.get_id(serving_name)
Args:
:serving_name: name of the serving to get the id for
Returns:
the id of the serving, None if Serving does not ex... | 5,290,798 |
def saveTiffStack(file, array, mode="L"):
"""
Save 3D image stack as a compressed multipage tiff
@param file: complete file path to .tif file save location
@type file: string
@param array: 3D input array of images to be saved
@type array: numpy.ndarray
@param mode: mode for converting 2D ar... | 5,290,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.