content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_params(cls, instance, ignore=None):
"""Retrieve the initialization parameters corresponding to a class
This helper function retrieves the parameters of function __init__ for
class 'cls' and returns the value for these parameters in object
'instance'. When using a composition pattern (e.g. with ... | c4de5cedfb4fbd2479acdf00aaf97ff8ee184cae | 590,720 |
import json
import base64
def claim_dict(encoded_token):
"""
This function returns a dictionary of claims from a string JWT.
Check the token's signature elsewhere.
"""
# split the three components
_, payload, _ = encoded_token.split('.')
# decode the payload in the dictionary of claims
... | 08e829d6e6b80eafe0669d520f61cceff0610d41 | 590,724 |
import torch
def generate_default_mask(data, dim1=None):
"""
Returns a default mask which allows the model to attend over all positions.
:param data: The data of shape (sequence_len, batch_size)
:param dim1: The first dimension of the mask. If none, it is equal to sequence_len.
:return:
"""
... | 7980aa7599cb843156123061008041ae082890af | 590,728 |
def make_onehot(int_list, one_hot_length):
"""Convert each int to a one-hot vector.
A one-hot vector is 0 everywhere except at the index equal to the
encoded value.
For example: 5 as a one-hot vector is [0, 0, 0, 0, 0, 1, 0, 0, 0, ...]
Args:
int_list: A list of ints, each of which will get a one-hot en... | 5878a8b7f4653b37cf6c90002b1400deec132aa1 | 590,729 |
import math
def shannon_index(data: list):
"""考虑了variety/balance,Shamono & Weaver(1962)。
Shannon指数是生态文献中比较流行的多样性指数,
也叫Shannon Diversity Index、Shannon-Wiener指数、Shannon-Weaver指数和Shannon Entropy。
Args:
data(list): 列表中存放不同(物种)分类的出现次数
Returns:
float: Shannon Diversity Index
"""
... | 06f4ab848883cd6d5c84d4c96aba0aa9084f728a | 590,730 |
def read_data(file_path='data.txt', verbose=False):
"""
params:
- file_path: path to file that contains data (default: 'data.txt')
- verbose: whether to print information (default: False)
return: a tuple that consists of the following:
- n: number of data instances
- m: number of features o... | ebd9841e96369bb3dc43e110720d791e1e41093e | 590,737 |
def get_tapis_abaco_image(base_url):
"""
Determine the docker image name for a tapis notebook associated with a base_url.
"""
# designsafe tenant:
if 'agave.designsafe-ci.org' in base_url:
return 'taccsciapps/jupyteruser-ds-abaco:1.2.14'
return None | 3ceb981ceed72dabfdb9adfa7e5572f7afe24411 | 590,742 |
def _identify_buffer_measurements(df):
"""Identify the rows of df where 'Sample ID' column contains "buffer" or "blank".
Return a list of indices.
"""
# first find variations on 'blank' and 'buffer' using boolean indexing
buffers = df.loc[
(df["Sample ID"].str.contains("lan")) | (df["S... | 8084595b4937cf75cefd403819b63d9c7ae89e23 | 590,743 |
import math
def get_phase_law(N, d, wavelength, phi):
"""Computes a phase law given N (number of elements),
d (spacing between elements in m), wavelength (in m)
and phi (beam steering angle).
"""
phase_law = [];
for n in range(N):
phase_law.append(-2 * math.pi * n * d / wavelength * ma... | 7a6be2d6b3ff4b583e47f114e8cf15a566dc5864 | 590,744 |
def flatten_dataset(features):
"""
Flattens a multidimensional dataset down to 1 dimension to feed into SVM.
"""
nsamples, nx, ny = features.shape
reshaped_data = features.reshape((nsamples, nx*ny))
return reshaped_data | 151e2650f999640221b101508ed81c5c59d5079b | 590,746 |
def invertx(x, y, **kwargs):
"""Multiply x by -1"""
return -x, y | 9bf88da135687f8a853af16dc39876547d436539 | 590,748 |
def get_n_most_max_character_counts_tuple(dictionary, n):
"""Returns a tuple containing the character with the n'th highest count in the dictionary along with its count
>>> get_n_most_max_character_counts_tuple(dictionary, 5)
('x', 1234)
>>> get_n_most_max_character_counts_tuple(dictionary, 6)
('y'... | c2e801879c8569d4a3ce41fb662b6f1bb2e19736 | 590,751 |
def isclose(mat1, mat2, tol=1e-6):
"""
check element-wise if two tensors are close within some tolerance.
Either tensot can be replaced by a scalar
"""
return (mat1 - mat2).abs_().lt(tol) | 61122b1e581a7c3b37e8fbde5325efc051906a6b | 590,752 |
import random
import torch
def _get_bert_for_sequence_classification_sample_data_with_random_shapes(device):
"""Returns sample data with random shape to be used with BertForSequenceClassification model"""
x = random.randint(1,100)
y = random.randint(1,100)
input_ids = torch.randint(0, 100, (x, y), dt... | d7349af6cfc12fb5c5a53270ece947120123aefc | 590,754 |
def total_kicks(meta):
"""
Adds up the total number of kicks from the match metadata.
Args:
meta: Match metadata (dict).
Returns:
Number of kicks (int).
"""
return meta["kicks_red"] + meta["kicks_blue"] | 56abb5a06b07131188de0d02ded2a9de3895aba6 | 590,758 |
import re
def slugify(value):
"""
Turns str into slug value
:param str value: Regular string to slugify
"""
value = re.sub(r'[^\w\s-]', '', value.lower()).strip()
return re.sub(r'[-\s]+', '-', value) | 8ca7737e0d6080f73f862abb356e05748c39b055 | 590,759 |
def laysin(cols, rows, c):
""" Given the center and the amount of rows and columns,
return in which bin the axes is in.
"""
dx, dy = 1.0/cols, 1.0/rows
x, y = int(c[0]/dx), int(c[1]/dy)
return x + y*cols | a847d32d77234a52b89828f85596d6b45a5feab0 | 590,763 |
def tokens_to_text(token_list):
"""Convert a list of binja tokens to plain text
Mostly useful for testing
"""
return ''.join([tok.text for tok in token_list]) | 9aae7abd351578f52b37de28ae886ffa3fee06a7 | 590,764 |
def changeCase(seq):
"""Change case to capital of a sequence string."""
return seq.replace('a','A').replace('t','T').replace('c','C').replace('g','G').replace('n','N') | ae1fa89f866586207db27881746b5837d3e4c8a0 | 590,765 |
import warnings
def _infer_max_treedepth(fit):
"""Extract max treedepth from a StanFit4Model instance."""
try:
return fit.stan_args[0]["ctrl"]["sampling"]["max_treedepth"]
except:
warnings.warn("Unable to determine max_treedepth. " + "Using value of 10.")
return 10 | eb51c93a3b9596740167213a40de641e9abd0f58 | 590,768 |
def triangular_wave(x, period, amplitude):
"""
Returns a triangular wave evaluated at x, given its period and amplitude.
Equation source: https://en.wikipedia.org/wiki/Triangle_wave
"""
return (4*amplitude/period) * abs(((x - period/4) % period) - period/2) - amplitude | 21b80beef284360e631572db80ad6a081946f4d0 | 590,770 |
def rec_getattr(obj, attr, default):
"""Get object's attribute. May use dot notation.
>>> class C(object): pass
>>> a = C()
>>> a.b = C()
>>> a.b.c = 4
>>> rec_getattr(a, 'b.c')
4
"""
if obj is None:
return default
else:
if '.' not in attr:
return get... | c7bda54b0a07fecdacb485f02f7765f6221d837a | 590,772 |
import requests
def _make_request(method: str, url: str, **kwargs) -> requests.Response:
"""Make a request. Raises an exception if unsuccessful."""
resp = requests.request(method, url, **kwargs)
if resp.status_code < 200 or resp.status_code >= 300:
resp.raise_for_status()
return resp | 23a37d876d9c7fc53feb13415e62f5a42c0f54d6 | 590,773 |
import array
def round_float32(x_double):
"""
Uses the array module to retun a (truncated) 32-bit float
representation of a python floating point number (double)
"""
return array.array('f', [x_double])[0] | b614f83123d90bafc8d72c8fc723aae24331b3b2 | 590,777 |
import shutil
def workdir(_workdir, tmp_path):
"""Make a fresh copy of the prepared analysis directory"""
path = tmp_path / "analysis"
shutil.copytree(_workdir, path)
return path | 8468f44516ea37bfc32d1ab229a2aca36b0f244d | 590,778 |
def almost_there(n):
"""
Given an integer n, return True if n is within 10 of either 100 or 200
:param n:int
:return: bool
almost_there(90) --> True
almost_there(104) --> True
almost_there(150) --> False
almost_there(209) --> True
"""
return (abs(100 - n) <= 10) or (abs(200 - n) ... | a3cc766f8f1e8db023bb4c41c833fed6fd85a857 | 590,780 |
async def user_exists(app, username):
"""Check if a user exists by username.
Parameters
----------
app : aiohttp.web.Application
The aiohttp application instance
username : str
The username of the user
Returns
-------
exists : bool
True if the user exists, False ... | d807f95042f63ef124147161843b338cbe8ae4d1 | 590,783 |
def fmt_app_name(appname):
"""Format a sysl_pb2.AppName as a syntactically valid string."""
return ' :: '.join(appname.part) | 531f60a311136d7a97767287a64298dc2add59d4 | 590,788 |
def bytes_to_kb(num_bytes):
"""
Converts bytes to kilobytes.
Parameters:
num_bytes number of bytes
Returns:
number of kilobytes
"""
return num_bytes / 1024.0 | 9d483a0e0898e1d48e1831952a1eff0efa56b701 | 590,789 |
def cast(val, typ=int):
"""Attempts to cast the given value to the given type otherwise None is
returned."""
try:
val = typ(val)
except:
val = None
return val | 2b95409e06a79fcb9446dc3c0873dd317fc49b25 | 590,790 |
import re
def clean_link(link):
"""Normalize source, this is needed since some source has http, or www.
and others doesn't"""
if link.startswith('http') or link.startswith('https'):
link = re.sub(r'http[s]?://', '', link)
if link.startswith('www.'):
link = re.sub(r'www\.', '', link)
... | d43ccf3de256a6448691fca2e38b78aff38f3683 | 590,793 |
def pertenece_a_base(ns: str, b: int) -> bool:
"""Determina si un número pertenece a una base dada.
:param ns: Número a evaluar.
:type ns: str
:param b: Base a evaluar.
:type b: int
:return: True si pertenece a la base, False en caso contrario.
>>> pertenece_a_base('35235', 6)
True
... | 494b9a0442b9188e523d3ce8737e9808ab2bec0b | 590,797 |
def mark_number(number, board):
"""
Given a number and a board, mark the number on the board if found
and return the board
"""
for r, row in enumerate(board):
for c, cell in enumerate(row):
if cell == number:
# Mark the cell by overwriting it with -1 and return th... | 645685e0343b1a7ef4b0f0c569802a537065e991 | 590,799 |
def datetime(value):
"""Formats datetime object to a yyyy-mm-dd hh:mm string."""
return value.strftime('%Y-%m-%d %H:%M') | dfccfcf6086d7cb3ea8887ac40229a78f76e3f8a | 590,802 |
def join_namespace(namespace, ident):
"""
Joins a namespace and a bare identifier into a full identifier.
>>> join_namespace('a', 'b')
'a:b'
>>> join_namespace('', 'b')
':b'
"""
return ':'.join([namespace, ident]) | f1d7329ab69b4cfc788c4be64530187954ce871b | 590,810 |
def full_serialize(grading_feedback_schema, grading_data):
"""
Serialize grading_data as a "Grading feedback" JSON schema object and return the resulting JSON string.
"""
GradingFeedback = grading_feedback_schema["classes"].GradingFeedback
schema_object = GradingFeedback(**grading_data)
return s... | 35ec65f4962c693f87b8821b2c814651349cec7c | 590,811 |
import operator
def evaluate_slice_index(arg):
"""
Helper function to convert a slice argument to an integer, and raise
TypeError with a suitable message on failure.
"""
if hasattr(arg, "__index__"):
return operator.index(arg)
else:
raise TypeError(
"slice indices ... | 7111a9cac162b18b14140cc682edb6aebea2a999 | 590,815 |
def query_resource_id(manageiq, resource_type, resource_name):
""" Query the resource name in ManageIQ.
Returns:
the resource id if it exists in manageiq, Fail otherwise.
"""
resource = manageiq.find_collection_resource_by(resource_type, name=resource_name)
if resource:
return resou... | 5c4c229fcb328a7e71e73d3bc198364385dcf61d | 590,816 |
def scrape(soup):
"""
スクレイピングして結果を Dict で返す
Parameters
----------
soup : BeautifulSoup
BeautifulSoup オブジェクト
Returns
-------
scrapedDict : dict
スクレイピング結果を格納した辞書
"""
# 辞書 (Dict) を用意する
# 格納順序を保持する場合は 'import collections' し 'collections.OrderedDict()' で初期化する
scrapedDict = {}
# ... | 0e2ee4d8ab06684442752d349f8508235908f9e7 | 590,818 |
def zero_separation(n):
"""Zero separation in normalized r based on radial order n."""
return 1 / n ** 2 | 6e0cf98b814aed8ececa859836ee3dccb3de87ee | 590,821 |
def process_labels(labels:str):
"""
Takes a string of phonemes as input and outputs a list of lowercase phonemes
"""
return labels.lower().split() | 46ba0f224d4c2636279601bb166ee20bc94c0fb4 | 590,822 |
def is_category_malicious(category, reputation_params):
"""
determine if category is malicious in reputation_params
"""
return category and category.lower() in reputation_params['malicious_categories'] | d015f0313a0a02989fee7ed56bfaff35f7da1456 | 590,824 |
def parse_gerber_number(strnumber, frac_digits):
"""
Parse a single number of Gerber coordinates.
:param strnumber: String containing a number in decimal digits
from a coordinate data block, possibly with a leading sign.
:type strnumber: str
:param frac_digits: Number of digits used for the fra... | ebeb69a2283bdb0455ac4bdda67b6f557a455360 | 590,827 |
def dict_to_lists(d : dict):
"""
Flattens a dict into keys and values, in the same order
:param d: dict to flatten
:return: list of keys, list of values
"""
keys = d.keys()
return keys, [d[k] for k in keys] | d5618c3dc63e9d4e4741db00e1799cd9187c254b | 590,828 |
def escape_string_killers(msg):
"""Helper method to fix string escape in teeworlds commands"""
return msg.replace('"', '\\"') | 4087817421de9f0b9e244e55ad810352193128a9 | 590,829 |
def is_empty_form(form):
"""
Considered empty if it passes validation but
doesn't have data
"""
if form.is_valid() and not form.cleaned_data:
return True
else:
# form has errors(isn't valid) or
# it doesn't have errors and contains data
return False | 65e80ae5680019a9db7fd23470468075211d7e4f | 590,832 |
import pickle
def read_pickle(pkl_path):
"""Returns loaded data from a pickle file."""
with open(pkl_path, 'rb') as f:
data = pickle.load(f)
return data | 219eac3d35c3cc10408921467e2749a93d276d96 | 590,835 |
def load_xyz(xyz_fname):
"""
Load a .xyz file into PySCF mol format
"""
with open(xyz_fname, "r") as f:
lines = f.readlines()
# Remove header
lines = lines[2:]
output = []
for line in lines:
elems = line.split()
atom = elems[0].capitalize()
x = float(e... | 1d5130c0da9ab5433b0ef8a2ddbe2b8e9e848994 | 590,836 |
def IF(logical, value1, value2) -> str:
"""
Creates an IF statement
>>> IF(1=1, 0, 1)
'IF(1=1, 0, 1)'
"""
return "IF({}, {}, {})".format(logical, value1, value2) | b92bc85f160069c799a48caf4aa30213faeae434 | 590,837 |
def remove_last_slash(path):
""" Remove the last slash in the given path [if any] """
if path.endswith("/"):
path = path[:-1]
return path | 1e6e33b5b6653513a2b4cd1fd4723afc62922111 | 590,840 |
from typing import List
def get_submission_lines(submission_filename: str) -> List[str]:
"""Returns the lines of a submission file.
Args:
submission_filename (str): path of the csv submission file.
Returns:
List[str]: lines of the submission file.
"""
with open(submission_filenam... | a7bdbb863c02359d5022f0c6f0df1547bb2fb8ca | 590,841 |
def __has_methods(obj, *methods):
"""
For ducktype testers.
Tests for methods to exist on objects.
:param obj:
:param methods: (variadic)
:return:
"""
for method in methods:
if not hasattr(obj, method) or not callable(getattr(obj, method)):
return False
return Tru... | 3f00c11df18470c9f0219c0cd3ec09b2ca5adfe8 | 590,844 |
def has_logs(gerrit_review):
"""
If a gerrit review exists, create a link to the review
"""
if gerrit_review:
return "https://gerrit.opnfv.org/gerrit/#/c/%s" % gerrit_review
return False | 112a5546bee2b5bd35f97a5d82ab5b0ac84d8852 | 590,845 |
import functools
import asyncio
def async_test(f):
"""
Decorator to transform async unittest coroutines into normal test methods
"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
loop = asyncio.get_event_loop()
loop.run_until_complete(f(*args, **kwargs))
return wrapper | 2698381dbfbdd5611967c2418f77fc688e621f59 | 590,846 |
def split(path):
"""Parse a full path and return the collection and the resource name
If the path ends by a '/' that's a collection
:param path: a path in the collection
:type path: str
:return: a pair with the collection name and the resource/collection name
:type: tuple
"""
if pa... | f3e86e0a8c11ecda8dd2be33c238acf5a376ee65 | 590,849 |
def remove(ele, lst):
"""
remove all occurences of an element from a list
"""
pops = []
for i in range(len(lst)):
if lst[i] == ele: pops.append(i)
return [lst[i] for i in range(len(lst)) if i not in pops] | 9604ea4d482b0ab1c045ca5f20bc47475280f7c0 | 590,850 |
def parse_subnets_by_tag(subnets, tag_key, tag_value, return_key='id'):
"""
Args:
subnets (list): List of dictionaries of the subnets that were created.
tag_key (str): The tag key you are searching by.
tag_value (str): The value of the tag you want to search by.
Kwargs:
retu... | f61d483b89aff91e44dd161a18d19a6319752109 | 590,853 |
def _transform_and_shift(affine_transform, col_indices, row_indices, cellxh, cellyh):
"""
Transforms indices to coordinates and applies a half pixel shift
Args:
affine_transform (object): The affine transform.
col_indices (1d array): The column indices.
row_indices (1d array): The ... | 8a71d216b82109032070b9e3131336117067d155 | 590,855 |
def nested_docfield_unwrapper(field: str, hitdict, value: dict) -> dict:
""" Unwraps the JSON for nested fields in a document that was returned from a search """
if isinstance(value, dict):
for (sf, sf_v) in value.items():
nested_docfield_unwrapper(field + '.' + sf, hitdict, sf_v)
else:
... | ca389f9113ba876cb6bd5c9aa2ff3ecf66e83de8 | 590,861 |
def sum_first_n_squares(n: int) -> int:
"""Finds the sum of the squares of the integers from 1 to n."""
return n * (n + 1) * (2 * n + 1) // 6 | 02b8d4d9668de07fb9a3d41af066c51be810df2f | 590,864 |
def intcode_six(parameter_list, code_list, i):
"""If first parameter is zero, sets instruction pointer to second parameter. Returns i"""
if parameter_list[0] == 0:
i = parameter_list[1]
return i | c62910ab47d339b31972ea1afe1a3f31d849ad34 | 590,865 |
def betamax_parametrized_session(betamax_parametrized_recorder):
"""Generate a session that has Betamax already installed.
See `betamax_parametrized_recorder` fixture.
:param betamax_parametrized_recorder:
A recorder fixture with a configured request session.
:returns:
An instantiated ... | 06be87e7adcb003bb36557c3f4926d9d9c4e20a6 | 590,867 |
import torch
def effective_sample_size(log_weights):
"""Kish effective sample size; log weights don't have to be normalized"""
return torch.exp(2*torch.logsumexp(log_weights, dim=0) - torch.logsumexp(2*log_weights, dim=0)) | 1979a33f040c9d703e4bbaf8338b7b260ddbb223 | 590,868 |
import operator
def sort_dict_by_value(dict_, reverse=True):
"""
按照values排序字典
:param dict_: 待排序字典
:param reverse: 默认从大到小
:return: 排序后的字典
"""
return sorted(dict_.items(), key=operator.itemgetter(1), reverse=reverse) | db687b84187f123cf3019827dd8a32ec4c770109 | 590,873 |
def set(field, val):
"""
Set a given field to ``val``.
"""
def transform(doc):
doc[field] = val
return transform | 1c96efbca17e3135cc52d5bca1a016b8d8175d46 | 590,874 |
def islist(x):
"""Is an object a python list"""
return type(x) is list | 5adb3e878dd6f504eb392b07ca1ca4dfb499d908 | 590,878 |
import re
def segment(text):
"""。や文末記号で文を分割する関数
Args:
text (string): テキスト
Returns:
list of string: 分割されたテキストの配列
"""
# 改行削除
text = text.replace("\n", "")
# 。!?の後に改行追加
pattern = re.compile(r"(。|!|?|\?|\!)")
text = pattern.sub(r"\1\n", text)
# 改行で分割
splited =... | dbc37241d181f9f0a9a712a7e076139fe55c7a88 | 590,880 |
from pathlib import Path
def find_files(src_path: Path, glob_pattern: str) -> list[Path]:
"""
Returns a list of path objects to the files matching the glob pattern.
Searches in `src_path`
"""
files = src_path.glob(glob_pattern)
paths = [Path(file) for file in files]
return paths | 32a1428a33f4a98a46c4a21a64b2653bdf673657 | 590,882 |
import re
def is_a_number(x):
"""This function determines if its argument, x, is in the
format of a number. It can be number can be in integer, floating
point, scientific, or engineering format. The function returns True if the
argument is formattted like a number, and False otherwise."""
num... | f74e8de1e865793ce1e57e85ed09c8846b9203cd | 590,883 |
def partition_fxn(output_str):
""" Parses the MESSPF output file string for the parition function
and related information for a single species.
:param output_str: string of lines for MESSPF output file
:type output_str: str
:return temps: List of temperatures
:rtype: float(... | 281cbe123765d9b8352a503f5a32910e543080ad | 590,885 |
def compare_strings_in_list(list_of_strings):
"""Compares the list of strings recursively, failing fast when it finds more than 1 non-matching character.
:param list_of_strings: The list of strings to iterate through, which gets smaller by one with each loop.
:return: The two strings that match.
-----... | d949762065c5d7db53c68d10283703d72aa31bc4 | 590,887 |
from typing import Any
def _is_tuple(item: Any) -> bool:
"""Verifies if item instance is a tuple.
Args:
item: an item to verify.
Returns:
`True` if verified, `False` otherwise.
"""
return isinstance(item, tuple) | 569f39adfc13dfd093784e51aa1abdb4daae63c8 | 590,894 |
def is_in_element(coords, data_labeled):
"""
Evaluate if the given coords are in a element.
Parameters
---------
coords: Tuple
Contains the indices to check
data_labeled : NdArray
Data with elements labeled
Returns
---------
Boolean
True if coords point to a... | 85968c2f034955cf74f5ef47afcf9d4aaf5bde2e | 590,895 |
def split_dict(inp, *keyses):
"""Split an input dict into multiple dicts according to lists of keys
Args:
ind (dict): input dictionary, usually kwargs
*keyses (tuple of lists): Variable length argument list that
contains keys to split. That is, keyses itself is a tuple
... | 7b4209af2d3c45053c31124433120a7daaacf3ed | 590,897 |
def region(lat, lon):
""" Return the SRTM1 region number of a given lat, lon.
Map of regions:
http://dds.cr.usgs.gov/srtm/version2_1/SRTM1/Region_definition.jpg
"""
if 38 <= lat and lat < 50 and -125 <= lon and lon < -111:
return 1
if 38 <= lat and lat < 50 and -111 <= ... | a7e2cb007b3b22f11f6106ea184acbec91edd079 | 590,898 |
def get_channels_first_permutation(spatial):
"""Returns a permutation to make a (N, ..., C) array into (N, C, ...)."""
return [0, spatial + 1] + list(range(1, spatial + 1)) | 4ff047e50ce2c300b872f3e95d799991b27c4e69 | 590,905 |
def generateDiscretizedValue(value, point_ranges, min_value, max_value):
"""
Generate discrete symbol based on range
This function computes the discrete symbol representation of the value based
on the point ranges supplied. The representation will be lowerRange..upperRange.
Note: point_ranges must ... | cf4d8c162b417a56a2d0116a8d2f4e2bdf90d90c | 590,906 |
from typing import Callable
def find_first_match(condition: Callable) -> int:
"""
:param condition: Condition that number needs to match.
The condition is assumed to be valid for all integers staring from an initial value.
:return: First integer for which condition is valid.
"""
... | 93fbcc04e78352139675f277f8391bd0bcb83daf | 590,910 |
def _get_includes(header):
"""
Returns list of include directives
Parameters
----------
header : str
CppHeader
Returns
-------
includes : list
List of include directive strings
"""
includes = []
for inc in header.includes:
includes.append(f'#include ... | 5fd214a33a0fbec8ac823266f26b3befabc8a458 | 590,911 |
import torch
def xyxy2xywh(xyxy):
"""Convert bounding box enconding from [x1, y1, x2, y2] to [x, y, w, h]."""
# the input tensor must have four components in the last dimension
xywh = torch.zeros_like(xyxy)
xywh[:, 0] = (xyxy[:, 0] + xyxy[:, 2]) / 2
xywh[:, 1] = (xyxy[:, 1] + xyxy[:, 3]) / 2
x... | 67e2a3db9a5194d88284a7c2180cf3c1292ae1ac | 590,917 |
def create_uniform_grid(low, high, bins=(10, 10)):
"""Define a uniformly-spaced grid that can be used to discretize a space.
Parameters
----------
low : array_like
Lower bounds for each dimension of the continuous space.
high : array_like
Upper bounds for each dimension of the c... | 321e96b718db9b35eb50e6e98c20ae3888797a0e | 590,921 |
def url_path_param_quoting(param):
"""Quote URL path parameters
Convert '/' to _FORWARDSLASH_ - otherwise is interpreted as additional path parameter
gunicorn processes the path prior to Falcon and interprets the
correct quoting of %2F into a slash
"""
return param.replace("/", "_FORWAR... | 9bb82b8756307f5d630c8535904791a5d1d81f97 | 590,940 |
def listify(llist):
"""Encapsulate l with list[] if not."""
return [llist] if not isinstance(llist, list) else llist | b3eafb26df08bc84e1a23be033a45ae292e793eb | 590,946 |
def fibonacci(n):
"""
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(10)
55
"""
if n < 2:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2) | f3c1ec3aaf852e101d443629a46fc67fe6bc2392 | 590,950 |
def elem_resolution(elem):
"""formatting of element name to remove resolution for ELEMENT2 instrument"""
elem = elem.replace('(LR)', '').replace('(MR)', '').replace('(HR)', '')
return elem | c0fce764197d710b1ecab647cbc6871c80d64887 | 590,952 |
import json
def recv(fh):
"""
Receive a JSON-encoded message from the given file object.
"""
s = fh.readline()
return json.loads(s) | 1d9987f60979ccd8f3ff950397fcf02f5a259001 | 590,954 |
def certificate_signing_status_get(handle):
"""
This api checks the status of the certificate generation request
submitted previously
Args:
handle (Imchandle)
Returns:
Status of the certificate generation activity (string)
"""
mo = handle.query_classid("GenerateCertificate... | 9aac30e09790e440028d19a7c118e527faf5254f | 590,959 |
def brg_to_rgb(brg_colour):
"""Reorders RGB colour value used by DAWN's LED strip to standard RGB order"""
return (
brg_colour[1],
brg_colour[2],
brg_colour[0]
) | 9ca9cfb5dd5a9c4ee4bf913b2b577ecef73bb4e4 | 590,960 |
async def rollover(es, params):
"""
Runs a rollover operation against Elasticsearch.
It expects the parameter hash to contain a key "alias" specifying the alias to rollover
as well as a key "body" containing the actual rollover request and associated conditions.
"""
await es.indices.rollover(a... | e58f65a71b7fe62894b8d0267773404a4a5582d2 | 590,962 |
import importlib
def _load_player(modulename, package='.'):
"""
Load a Player class given the name of a module.
:param modulename: where to look for the Player class (name of a module)
:param package: where to look for the module (relative package)
:return: the Player class (a class object)
... | 7a6de7116fb3d664d01811473114eff5c29900ad | 590,963 |
def to_domain(pre, org):
"""Appends pre to org to create a domain name"""
return pre + "." + org["Domain"] | f613ebfbfe6a2c5cf5e0a668c9f6661cc34e411c | 590,967 |
def shift_tier(vector, base_name, left_orders, right_orders, oob="∅"):
"""
Compute shifted versions of a vector.
Parameters
----------
vector : list
Vector to be shifted.
base_name : str
Base name of the tier.
left_orders: list of int
List of left contexts to include... | dc0180abff2d30416bda6047b2e05d067c427b0a | 590,969 |
def _new_versions(quay, conda):
"""Calculate the versions that are in conda but not on quay.io."""
sconda = set(conda)
squay = set(quay) if quay else set()
return sconda - squay | 433d6ec5bc7db3a114e8cd330575d7fde580f0c0 | 590,972 |
from bs4 import BeautifulSoup
def extract_text(html: str) -> str:
"""Extract plaintext from HTML."""
soup = BeautifulSoup(html, 'html.parser')
plaintexts = [p.text for p in soup.find_all(['h1', 'h2', 'h3', 'p'])]
return ' '.join(plaintexts) | b2c3b3c53577a8020319d59b4064b027c71a03ec | 590,976 |
def RotInv(R):
"""Inverts a rotation matrix
:param R: A rotation matrix
:return: The inverse of R
Example Input:
R = np.array([[0, 0, 1],
[1, 0, 0],
[0, 1, 0]])
Output:
np.array([[0, 1, 0],
[0, 0, 1],
[1,... | cfd9bcde6fccc088f987edd296d97a39f0a25dfd | 590,977 |
def valid_sec(string):
"""Check if string is a valid IP address section"""
if len(string) == 0:
return False
num = int(string)
if string != str(num):
# invalid string like "000" -- only one "0" is okay
return False
return num >= 0 and num <= 255 | 412f8409add9b480730b2d619293f1117de961e8 | 590,978 |
def head_compose(*decomposition_functions):
"""Compose the first function with all the remaining functions."""
main_decomposition_function = decomposition_functions[0]
argument_decomposition_functions = [f for f in decomposition_functions[1:]]
def head_composition(in_graph_component):
graph_com... | bc15ad9a0a9fddf76de5730a3fb419c47973a1fb | 590,979 |
def previous_series_is_sbref(seqinfo, index):
"""
Checks if the previous series is a SBRef image
seqinfo: list with the sequences information
index: index of the series, so the previous series would be index-1
"""
return (
index > 0
and seqinfo[index - 1].series_description.lower... | 172797780b752fc9f06cad0eeeb386e48879638e | 590,980 |
def deps(dict_1040):
"""
A function to calculate no. of dependents.
This currently goes up to 4 dependents.
"""
dep_count = 0
#while
counter = 1
while counter <= 4 and dict_1040["Dep" + str(counter)]["FN_LN"] != "":
counter += 1
dep_count += 1
return dep_count | f38d426322b39903fda5e4e549635ad1bba2cbfb | 590,981 |
def isstream(stream):
"""Check that the term passed as an argument is a stream-term.
A stream-term is a compound term of the form '$stream'(N), where N is an
integer that uniquely identify the stream."""
return ((stream.name == "$stream") and
stream.arity == 1 and
isinstance(st... | 6c77f544482695ee076520ac6b6360dd8fdd1245 | 590,987 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.