content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def normalize_inputs(py_dict: dict) -> dict:
"""Normalize a dictionary of inputs to contiguous numpy arrays."""
return {k: (Tensor(v) if isinstance(v, np.ndarray) else v)
for k, v in py_dict.items()} | 5,316,400 |
def get_task_definition_arns():
"""List all task definition ARNs."""
client = get_client("ecs")
return client.list_task_definitions() | 5,316,401 |
def clean_column(df, column):
"""
Function to return clean column text. Pass each cell to a cleaner
and return the cleaned text for that specific column
:params:
--------
:df dataframe(): containing the column
:column str(): in which column the text is located
:returns:
---... | 5,316,402 |
def get_sheet():
"""
Get selected sheet or active view if sheet
:return: Sheet
:rtype: DB.ViewSheet
"""
sheets = get_selected_by_cat(DB.BuiltInCategory.OST_Sheets, as_list=True)
if sheets:
if len(sheets) > 1:
raise ScriptError("Please select only one sheet") # FIXME
... | 5,316,403 |
def augment_cost_function(
cost_function: CostFunction,
cost_function_augmentations: Optional[Iterable[FunctionAugmentation]] = None,
gradient_augmentations: Optional[Iterable[FunctionAugmentation]] = None,
):
"""Augment a function and its gradient.
Args:
cost_function: a function to be aug... | 5,316,404 |
def main():
"""
Start the client, connect to 127.0.0.1:80 and use 2 remote flash shared
objects.
"""
client = rtmp_protocol.RtmpClient('127.0.0.1', 80, '', '', '', '')
client.connect([])
so_name = SO('so_name')
client.shared_object_use(so_name)
so2_name = SO('so2_name')
... | 5,316,405 |
def edit_name(request, name, editable_authorities):
"""View to edit an existing Name object."""
# Much of the code here is a duplicate or close copy of the code
# in create_name.
number_name_part_forms = 2
number_name_note_forms = 1
name_part_forms = []
name_note_forms = []
assertion = n... | 5,316,406 |
def create_convolutional_autoencoder_model_2d(input_image_size,
number_of_filters_per_layer=(32, 64, 128, 10),
convolution_kernel_size=(5, 5),
deconvolution_kernel_size=(5, 5)
... | 5,316,407 |
def _from_yaml(
conf,
routing_strategy: Dict[str, Callable] = routing_strategy_factories,
label_instance_function: Callable = add_instance_label,
) -> Component:
"""Returns component from YAML decorated with cell for caching and autonaming.
Args:
conf: dict.
routing_strategy: for ea... | 5,316,408 |
def simple_experiment(K, y, n_folds=5, iterations=10000, subjects=False,
verbose=True, data_name='', plot=True,
random_state=None):
"""
"""
acc, acc_null, p_value = apply_svm(K, y, n_folds=n_folds,
iterations=iterations,
... | 5,316,409 |
def to_volume(data):
"""Ensure that data is a numpy 3D array."""
assert isinstance(data, np.ndarray)
if data.ndim == 2:
data = data[np.newaxis,...]
elif data.ndim == 3:
pass
elif data.ndim == 4:
assert data.shape[0]==1
data = np.squeeze(data, axis=0)
else:
... | 5,316,410 |
def search_down(*args):
"""
search_down(sflag) -> bool
Is the 'SEARCH_DOWN' bit set?
@param sflag (C++: int)
"""
return _ida_search.search_down(*args) | 5,316,411 |
def assign_number_to_top_categories(paths):
"""Assign numbers to the top categories
returned by split_path for consistency"""
cats = {}
def assign_number(path):
name = path[0][1]
n = cats.setdefault(name, len(cats) + 1)
return [(n, name)] + path[1:]
return map(assign_number,... | 5,316,412 |
def instrument_parameters_odim5(radar, odim_file):
"""
Builds the dictionary 'instrument_parameters' in the radar instance,
using the parameter metadata in the input odim5 file.
Parameters
----------
radar : Radar
Py-ART radar structure
odim_file : str
Complete path and fil... | 5,316,413 |
def topodstostep_DecodeVertexError(*args):
"""
* Returns a new shape without undirect surfaces.
:param E:
:type E: TopoDSToStep_MakeVertexError
:rtype: Handle_TCollection_HAsciiString
"""
return _TopoDSToStep.topodstostep_DecodeVertexError(*args) | 5,316,414 |
def sort_keywords(scores):
"""
:param scores: A dictionary of lemmas and their corresponding scores,
assigned by the pagerank algorithm
:return: The same dictionary, sorted in descending order
"""
sorted_lemmas = [lemma for lemma in sorted(scores, key=scores.get, reverse=True)]
return sorte... | 5,316,415 |
def main(table_name='accounts_bot'):
"""
Запускает add_friends.add_all_new_friends() для каждого бота в отдельном потоке
:param table_name: Имя таблицы с ботами в БД
:type table_name: str
"""
cur = interaction_with_db.get_cursor()
cur.execute("SELECT id FROM {}".format(table_name))
id_b... | 5,316,416 |
def test_valid_contructor(input, deque):
"""Test valid constructor using by dequeuing after instantiation"""
assert Queue(input).dequeue() == deque | 5,316,417 |
def DecodeControlTuples(ldapControlTuples,knownLDAPControls=None):
"""
Returns list of readily decoded ResponseControl objects
ldapControlTuples
Sequence-type of 3-tuples returned by _ldap.result4() containing
the encoded ASN.1 control values of response controls.
knownLDAPControls
Dictionary... | 5,316,418 |
def transform_geom(
src_crs,
dst_crs,
geom,
antimeridian_cutting=True,
antimeridian_offset=10.0,
precision=-1):
"""Transform geometry from source coordinate reference system into target.
Parameters
------------
src_crs: CRS or dict
Source coordina... | 5,316,419 |
def part_one(data: str) -> int:
"""The best possible cookie score given the ingredient properties from data."""
total_quantity = 100
ingredients = [parse_ingredient(line) for line in data.splitlines()]
# There are 4 ingredients total in the input, so nothing is lost here.
quantities = [total_quantit... | 5,316,420 |
def test_actor_initialisation(dummy_actor):
""" test actor attributes initialization"""
assert dummy_actor.state.alive is True | 5,316,421 |
def skip_if_quick(func):
"""Decorator to skip tests if quick option is used."""
@wraps(func)
def wrapper(*args):
# C0111: *Missing docstring*
# pylint: disable=C0111
# W0212: *Access to a protected member %%s of a client class*
# pylint: disable=W0212
if args[0]._opts... | 5,316,422 |
def _build_edges(wave, sampling_type):
"""
Calculates edges of bins of given wavelength given the center value of the
bin and the type of sampling.
Parameters
----------
wave : numpy.ndarray
Array with the wavelengths.
sampling_type : string
Sampling type of the array. It ca... | 5,316,423 |
def put_dkim_authority():
"""
PUT /domains/<domain>/dkim_authority
:return:
"""
data = {
"self": "false"
}
request = client.domains_dkimauthority.put(domain=domain, data=data)
print(request.json()) | 5,316,424 |
def file_readlines(fn):
"""Open file with name `fn`, return open(fn).readlines()."""
fd = open(fn, 'r')
lst = fd.readlines()
fd.close()
return lst | 5,316,425 |
def filter_table(table, **kwargs):
"""Retrieve the filtered rows
Parameters
----------
table: astropy.table.Table, pandas.DataFrame
The table to filter
param: str
The parameter to filter by, e.g. 'Teff'
value: str, float, int, sequence
The criteria to filter by,
... | 5,316,426 |
def get_cached_skin_path():
"""
Get the value of the #SKINSPATH# variable.
This can be collected from various installation locations,
since there are numerous ways to install Rainmeter.
The easiest solution is, if the user tells Sublime Rainmeter,
that he installed Rainmeter in a specific fold... | 5,316,427 |
def printerr(value):
"""Print to stderr"""
try:
print(value.strip().decode("utf-8"))
except UnicodeDecodeError:
print("printout DecodeError:", value) | 5,316,428 |
def func_dispatch(func: Callable = None, *, default: bool, clazz=None):
"""
Value-based dynamic-dispatch function decorator.
Transforms a function into a dynamic dispatch function, which has different
behaviors depending upon the value of its first positional parameter. The
decorated function acts ... | 5,316,429 |
def access_controlled_app(app):
"""
An app where all the routes are access-controlled to the 'buyer' role, and there are some login routes if we need.
"""
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
# simulate loading... | 5,316,430 |
def get_local_content_list(filename, encoding):
"""Return the file content with status"""
textl = []
stat = False
try:
with open(filename, 'r', encoding=encoding) as f:
textl = ''.join([f.read(), '\n']).splitlines()
stat = True
except Exception as e:
log.excep... | 5,316,431 |
def check_pods_status(run_name: str, namespace: str, status: PodStatus, app_name: NAUTAAppNames = None) -> bool:
"""
Returns true if all pods related to a given run have given status.
:param run_name: name of a run - obligatory
:param namespace: namespace where run is located - obligatory
:para... | 5,316,432 |
def searchContact(app):
""" Accept a searchterm from user and search for it in the tree.
"""
contact = raw_input("Enter name: ")
try:
print app.searchContact(contact)
except Exception as e:
logger.debug(traceback.format_exc())
print "Error in searching contact: " + str(e) | 5,316,433 |
def retrieve_account(community, platform_type, platform_identifier, blah, community_platform_id=None):
"""Helper method to get a specific linked account."""
result = LinkedAccount.objects.filter(community=community, platform_type=platform_type,
platform_identifier=platform_identifier)
if community_p... | 5,316,434 |
def _read(obj):
"""
Try to read from a url, file or string.
Parameters
----------
obj : str, unicode, or file-like
Returns
-------
raw_text : str
"""
if is_url(obj):
with urlopen(obj) as url:
text = url.read()
elif hasattr(obj, "read"):
text = ob... | 5,316,435 |
def __leastsq_fit(tomo_data, weights=None, trace=None, beta=None):
"""
Reconstruct a state from unconstrained least-squares fitting.
Args:
tomo_data (list[dict]): state or process tomography data.
weights (list or array or None): weights to use for least squares
fitting. The def... | 5,316,436 |
def test_delete_upstream_negative():
"""
Negative test trying to delete a non-existant upstream.
"""
mock_run = MagicMock(
return_value={
"retcode": 70,
"stdout": (
'Clearing runtime parameter "remote-name" for component '
'"federation-upst... | 5,316,437 |
def test_filter_by_property_strict_n_components():
"""Tests that the FilterByPropertyTypes filter works
correctly when strict mode and n_components is set.
"""
property_types = ["Density", "EnthalpyOfVaporization", "EnthalpyOfMixing"]
substance_entries = [
(("CC",), (True, True, False)),
... | 5,316,438 |
async def testpoint(mockserver: server.MockserverFixture) -> TestpointFixture:
"""Testpoint fixture returns testpoint session instance that works
as decorator that registers testpoint handler. Original function is
wrapped with :ref:`AsyncCallQueue`
:param name: testpoint name
:returns: decorator
... | 5,316,439 |
def teardown_module(module):
"""Stop patches and enable logging output"""
patch.stopall()
logging.disable(logging.NOTSET) | 5,316,440 |
def cfg(c=[], all=None):
"""returns parsed config for section <endpoint> - if not exists, builds it
When interactive auth is requred we do not write - i.e. only valid for cur.
session.
To avoid frequent password queries, call GL.setup function.
"""
try:
return c[0][FLG.endpoint_name]
... | 5,316,441 |
def JIRATOSQLdatetimeformat(datetime_in):
"""
removes certain characters from fields returned by Jira requests, in order to facilitate insertion into SQL tables
would need to be written differently for a production application, to handle escape characters etc. more intelligently
parameters:
str_in (string): the s... | 5,316,442 |
def _split_and_reshape_to_ndarrays(flat_v, sizes, shapes):
"""Split and reshape a single flat vector to make a list of ndarrays."""
xp = chainer.cuda.get_array_module(flat_v)
sections = np.cumsum(sizes)
vs = xp.split(flat_v, sections)
return [v.reshape(shape) for v, shape in zip(vs, shapes)] | 5,316,443 |
def simSpikes(coef,M_k,M_h,dt):
"""
simSpikes- function to simulate
"""
print(np.exp(np.dot(M,coef))[1:10])
M = np.hstack(M_k,M_h)
length = M.shape[0]
print(length)
tsp = []
jbin = 0
tspnext = random.expovariate(1)
rprev = 0
nsp = 0
#bhlen = M_h.shape[] #... | 5,316,444 |
def apply_lookup(dataframe, group_type):
"""
converts df[group_type] from ids to names
dataframe : df
group_type : string
returns : df
"""
print("applying look up")
print("working with {}".format(group_type))
df = dataframe.copy(deep=True)
df[group_type] = (
df[group_ty... | 5,316,445 |
def perm_float_literal(
fn: ca.FuncDef, ast: ca.FileAST, indices: Indices, region: Region, random: Random
) -> None:
"""Converts a Float Literal"""
cands: List[ca.Constant] = []
class Visitor(ca.NodeVisitor):
def visit_Constant(self, node: ca.Constant) -> None:
if node.type == "floa... | 5,316,446 |
def install_spacy(lang):
"""Tries to create a spacy object; if it fails, downloads the dataset"""
print(f'Determining if SpaCy for language "{lang}" is installed...')
if lang in SPACY_LANGUAGE_MAP:
try:
spacy.load(SPACY_LANGUAGE_MAP[lang])
print(f"SpaCy is installed and ava... | 5,316,447 |
def make_url_parser(global_conf, directory, base_python_name,
index_names=None, hide_extensions=None,
ignore_extensions=None,
**constructor_conf):
"""
Create a URLParser application that looks in ``directory``, which
should be the directory for the... | 5,316,448 |
def get_user_labels_from_storage(label_storage_file: str) -> UserLabels:
"""
get all labels from label storage file
Returns:
UserLabels: all labels
Raises:
FileNotFoundError: if label storage file not found
ValueError: if version mismatch
Error: if parse failed or other err... | 5,316,449 |
def add_memo():
"""
Insert a memo into the database.
"""
try:
date = arrow.get(request.args.get('date', 0, type=str),
'YYYY/MM/DD').naive
text = request.args.get('text', 0, type=str)
record = {"type": "dated_memo",
"date": date,
... | 5,316,450 |
def items_JSON():
"""Returns JSON object with all items"""
# Get all items
items = getItemAll(session)
# Return JSON object
return jsonify(Items=[i.serialize for i in items]) | 5,316,451 |
def delete_hsm_configuration(HsmConfigurationIdentifier=None):
"""
Deletes the specified Amazon Redshift HSM configuration.
See also: AWS API Documentation
Exceptions
:example: response = client.delete_hsm_configuration(
HsmConfigurationIdentifier='string'
)
:type... | 5,316,452 |
def unescape(value, escape = "\\"):
"""
Unescapes the provided string value using the provided escape
character as the reference for the unescape operation.
This is considered to be a very expensive operation and so it
should be used carefully.
:type value: String
:param value: Th... | 5,316,453 |
def __num_elems(shape):
"""Returns the number of elements in the given shape
Args:
shape: TensorShape
Return:
tot_elems: int
"""
tot_elems = 1
for s in shape:
tot_elems *= int(s)
return tot_elems | 5,316,454 |
def ocrRawCaptcha(image):
"""
recognize a captcha from http://bkxk.xmu.edu.cn/xsxk/login.html without preprocessing
:param image: image data of the captcha
:return: a string with four character
"""
images, _ = processImg.processImg(image)
result = ocrCaptchas(images)
return result | 5,316,455 |
def read_JSON(path: OpenFile) -> Optional[Any]:
"""
Attempt to read a JSON file. Returns False if the file doesn't exist.
:param path: the path of the file to read
"""
try:
with open(path, "r") as f:
return json.load(f)
except IOError:
return None | 5,316,456 |
def adoptionSearch(cursor, search):
# search = data_params['search']
"""Return the result based on Mo's search input"""
lower_search = search.lower()
query = f"SELECT DISTINCT Adopter.email, AdoptionApplication.application_num, AdoptionApplication.date, " \
f"AdoptionApplication.co_applicant... | 5,316,457 |
def onc_datetime(date_time, timezone="Canada/Pacific"):
"""Return a string representation of a date/time in the particular
ISO-8601 extended format required by the Ocean Networks Canada (ONC)
data web services API.
:arg date_time: Date/time to transform into format required by
ONC d... | 5,316,458 |
def clean(ctx):
"""Remove the build directory."""
if os.path.isdir(conf.OUTPUT_PATH):
shutil.rmtree(conf.OUTPUT_PATH) | 5,316,459 |
def req(retry=3, proxy=False, timeout=30, concurren=1):
""" 通过装饰器来给出可选的配置。 """
def call(func):
req = ReqParse(func, retry=retry, proxy=proxy, timeout=timeout, concurren=concurren)
return req
return call | 5,316,460 |
def _read(f):
"""Read a file's contents, autodetecting whether the arg is a file or filename,
and treating '-' as as indication to read from stdin."""
if type(f) is str:
if f == "-":
return sys.stdin.read()
else:
with open(f, "r") as ff:
return ff.read... | 5,316,461 |
def find_utils():
"""Find all the utilities used by this script"""
utils = dict()
for bin in ['xl', 'qemu-img', 'killall']:
res = lookup_bin(bin)
if not res:
log.error('Cannot find required program: ' + str(bin))
sys.exit(1)
utils[bin] = res
# unpack is ... | 5,316,462 |
def getHandValue(cards):
"""Returns value of cards."""
value = 0
numberOfAces = 0
for card in cards:
rank = card[0]
if rank == 'A':
numberOfAces += 1
elif rank in ('K','Q','J'):
value += 10
else:
value += int(rank)
value += number... | 5,316,463 |
def zigzag(n: int = 8) -> Dict:
"""
ZigZag encoder & decoder
Args:
n: size of chunk
Returns:
dictionary of encoder and decoder
"""
idx_zigzag = []
for a in sorted((p % n + p // n, (p % n, p // n)[(p % n - p // n) % 2], p) for p in range(n * n)):
idx_zigzag.append(a... | 5,316,464 |
def return_auth_error(handler, message):
"""
Return authorization error
"""
response= {}
handler._transforms = []
handler.set_status(AUTHORIZTION_ERROR_CODE)
response['err']= message
handler.write(response)
handler.finish() | 5,316,465 |
def get_lr(optimizer):
"""Get current learning rate
Parameters
----------
optimizer : obj
An optimizer object.
Returns
-------
lr
Current learning rate.
"""
for param_group in optimizer.param_groups:
return param_group["lr"] | 5,316,466 |
def get_business_by_id(business_ids):
"""
Gets the business details for all the business_id's that are provided (
:param business_ids: This takes a single business id or a list of business ids
:type business_ids: list
:return: business
:rtype: dict
"""
logger.info("Attempting to fetch bu... | 5,316,467 |
def load_target_class(input_dir):
"""Loads target classes."""
with tf.gfile.Open(os.path.join(input_dir, 'data.csv')) as f:
return {row[0]: int(row[2]) for row in csv.reader(f)} | 5,316,468 |
def get_model(model_config, local_data, backend='torch'):
"""
Arguments:
local_data (object): the model to be instantiated is responsible for the given data.
Returns:
model (torch.Module): the instantiated model.
"""
for func in register.model_dict.values():
model = func(mode... | 5,316,469 |
def ping(context, hosts, limit=''):
"""
Ansible command to run setup module on needed hosts
"""
_run_basic_command(context, hosts, 'ping', limit) | 5,316,470 |
def twilio_secure(func):
"""Wrap a view function to ensure that every request comes from Twilio."""
@wraps(func)
def wrapper(*a, **kw):
if validate_twilio_request():
return func(*a, **kw)
return Response("Not a valid Twilio request", status=403)
return wrapper | 5,316,471 |
def benchmark_share_get(workers, protocol, dtype, n_workers):
"""
This function benchmarks the share_get_functions.
Args:
workers (dict): workers used for sharing data
protocol (str): the name of the protocol
dtype (int): data type
n_workers (int): number of workers
"""... | 5,316,472 |
def get_batch_dataset(record_file, parser, config):
"""
训练数据集TFRecordDataset的batch生成器。
Args:
record_file: 训练数据tf_record路径
parser: 数据存储的格式
config: 超参数
"""
num_threads = tf.constant(config.num_threads, dtype=tf.int32)
dataset = tf.data.TFRecordDataset(record_file).map(
... | 5,316,473 |
def find_bundles_rescalings(
bundles: Iterable[InstanceBundle]
) -> Tuple[Tuple[List[InstanceBundle], Rescaling], ...]:
"""Finds a rescaling parameters for each subset of compatible instances.
Args:
bundles: Iterable of bundles to extract rescaling values from.
Returns:
Tuple of su... | 5,316,474 |
def test_fv_creator():
"""
Checks whether the first order cascade is in the freequency window.
"""
class int_fwm1(object):
def __init__(self):
self.N = 14
self.nt = 2**self.N
int_fwm = int_fwm1()
lam_p1 = 1000
lam_s = 1200
#fv, where = fv_creator(lam_p1,... | 5,316,475 |
def assert_not_in(val, iteratables, errmsg=''):
"""
assert val not equal any item in [iteratables (e.g. a list)]
"""
if val in iteratables:
assert False, 'val :%s in iteratables. ErrMsg:%s' % (val, errmsg) | 5,316,476 |
def test_main_0_int_format(mock_cel_environment_integer, caplog, capsys):
"""
GIVEN slurp option AND formatted output AND int expr
WHEN eval
THEN correct internal object use.
"""
argv = ["-n", "-f", "#8x", "339629869*11"]
status = celpy.__main__.main(argv)
assert status == 0
assert m... | 5,316,477 |
def get_ordinal_suffix(number):
"""Receives a number int and returns it appended with its ordinal suffix,
so 1 -> 1st, 2 -> 2nd, 4 -> 4th, 11 -> 11th, etc.
Rules:
https://en.wikipedia.org/wiki/Ordinal_indicator#English
- st is used with numbers ending in 1 (e.g. 1st, pronounced first)... | 5,316,478 |
def get_greppable(string):
"""Simply produces a string that -- when grepped -- will omit listing the grep process in a grep listing.
"""
return string.replace(string[0], '[%s]' % string[0], 1) | 5,316,479 |
def print_progress_bar(iteration, total, prefix='Progress:', suffix='', decimals=1, length=None, fill='█', background=' '):
""" Text-based progress bar for Terminal/CLI.
Generate progress bar out of a loop.
Example:
Progress: [█████████████████████████████████████████████ ] 90.0%
Args:
... | 5,316,480 |
def disable_colors():
"""
Disables colors to the terminal.
"""
rich_console.no_color = True | 5,316,481 |
def is_convergent_pair(p, rules):
"""Is the critical pair convergent?"""
u , v = p
n1, n2 = list(normalforms(u, rules)), list(normalforms(v, rules))
return n1 == n2 | 5,316,482 |
def main(args=None):
"""The main routine."""
if args is None:
args = sys.argv[1:]
multiprocessing.freeze_support()
errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(2)
root = tk.Tk()
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
root.geometry(f'{width... | 5,316,483 |
def is_userti(*args):
"""
is_userti(ea) -> bool
"""
return _ida_nalt.is_userti(*args) | 5,316,484 |
def players_player_id_get(player_id): # noqa: E501
"""Retrieve a single player's record
Returns a player record # noqa: E501
:param player_id: ID of player to return
:type player_id: str
:rtype: Player
"""
return 'do some magic!' | 5,316,485 |
def zero_array(array):
"""
Method to zero an array of data with the initial values.
:param array: Array of data - rows are time points, columns are signals.
:return: Zero'd numpy array
:rtype: np.ndarray
"""
init = array[:, 0]
zerod = np.apply_along_axis(lambda x: x - init, 0, array)
... | 5,316,486 |
def convert2pcm(wave_path, pcm_path):
""" Convert recorded files to pcm """
y, sr = librosa.load(wave_path, sr=32000)
y = librosa.to_mono(y)
y = librosa.resample(y, 32000, 16000)
sf.write(wave_path, y, 16000, format='wav', endian='little', subtype='PCM_16')
wav2pcm(wave_path, pcm_path) | 5,316,487 |
def view_file(file: Union[str, Path], safe=False):
"""Attempts to open the target file using the system-default viewer for the file type.
Args:
file(str): absolute path to the target file
safe(bool): if passed will first copy the file to a temp location
Returns:
obj(str): the pat... | 5,316,488 |
def _stemmatological_costs_factory(
max_del_len: int = 5, frag_start: float = 10.0, frag_end: float = 10.0
) -> Callable:
"""
Define and return a function for computing candidate costs for a "stemmatological" distance matrix.
:param max_del_len: The maximum length of deletion block.
:param frag_sta... | 5,316,489 |
def run_tsk(tsk, spc_dct, spc_name,
thy_dct, es_keyword_dct,
run_prefix, save_prefix,
print_debug=False):
""" Execute the specified electronic structure task.
:param tsk: name of task
:type tsk: str
:param spc_dct:
:type spc_dct:
:param sp... | 5,316,490 |
def test_conll_dataset(shared_datadir, dummy_vocabs):
"""Test the CoNLL dataset loader for single examples.
"""
token_vocab, char_vocab, label_vocab = dummy_vocabs
assert len(token_vocab) == 6 + 2 # plus 2 special tokens
assert len(char_vocab) == 26 * 2 + 2
assert len(label_vocab) == 5 + 2
... | 5,316,491 |
def results_by_parameter(res, param, sort_by=None, sort_desc=False,
crossvalid_use_measurment='validation',
crossvalid_reduce=False,
crossvalid_reduce_fn=None):
"""
Takes a list of evaluation results `res` returned by a LDA evaluation fu... | 5,316,492 |
def test_wi(spectral_index_test_data):
"""Test for PlantCV."""
index_array = spectral_index.wi(spectral_index_test_data.load_hsi(), distance=20)
assert np.shape(index_array.array_data) == (1, 1600) and np.nanmax(index_array.pseudo_rgb) == 255 | 5,316,493 |
def setup(override: str=''):
"""Initializes the static configuration variables used in the
PaperRank system. Provides a method to override base configuration.
Keyword Arguments:
override {str} -- File name in the `config/` directory
that may be used to override the `base.json` configura... | 5,316,494 |
def generate_case_study(
sampling_method: NormalSamplingMethod, cmap: CommitMap,
case_study_version: int, project_name: str, **kwargs: tp.Any
) -> CaseStudy:
"""
Generate a case study for a given project.
This function will draw `num_samples` revisions from the history of the
given project and ... | 5,316,495 |
def show_banner():
"""
Display banner
"""
print("")
print(C.CYN, "*** ", C.WHT, "rainwatch", C.OFF)
print(C.CYN, "*** ", C.CYN, "Version", __version__, "(" + __date__ + ")", C.OFF)
print(C.CYN, "*** ", C.GRN, "Copyright (c) 2016 J. Hipps / Neo-Retro Group", C.OFF)
print(C.CYN, "*** ", C.... | 5,316,496 |
def is_checkbox(field):
"""
Boolean filter for form fields to determine if a field is using a checkbox
widget.
"""
return isinstance(field.field.widget, forms.CheckboxInput) | 5,316,497 |
def build_info_str(username: str, name_len: int, remaining_chip: int, action: str,
chip: int, is_waiting: bool, countdown: int) -> str:
"""Build a string to explain action of a user
Args:
username (str): user name
name_len (int): characters to show the name
remaining_... | 5,316,498 |
def main(argv: Union[List[str], None] = None) -> int:
"""Drive the derivation."""
argv = sys.argv[1:] if argv is None else argv
if len(argv) != 0:
print("Usage: indexer")
return 2
alphabet = tuple('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
table = {f'{k}{j}': '<td> </td>' for k in... | 5,316,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.