content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import argparse
def parse_arguments():
"""Parse Text2Text model evaluation arguments"""
parser = argparse.ArgumentParser(
description="Calculate precision and recall for text item outputs, where both ground truth target items and predicted items are text-based. "
)
parser.add_argument(
... | 835e0ddabe827d70993e0060bef7796422bff19b | 685,864 |
def find_extended_row_candidates(frnum, row_candidates, traces):
"""
Attempt to add further traces to each of the row candidates.
row_candidates = find_extended_row_candidates(frnum, row_candidates, traces)
At this stage, a single trace may appear in multiple row candidates.
Only one of the re... | bf05367553fd86daebbb1df316314c1de5acf254 | 685,865 |
def is_even(number: int) -> bool:
"""
Info:
Check if a number is even, if so return True if not return False
Paramaters:
number: int - The number to check if is even.
Usage:
is_even(number)
Returns:
bool
"""
return number % 2 == 0 | d1e4f389e9bbff79e84a6bc7f779db3fb590e307 | 685,866 |
def check_valid(subset_json):
"""Helper to check if a file is valid, given a subset json instance
Args:
subset_json: Defined subset json file data
Returns:
bool: True/false value for validity
"""
if subset_json is None:
return lambda path: True
def curry(image_path):
... | 5a0c08bd60f134c2aef1e02239f38716607ae958 | 685,867 |
def string_to_decimal(string):
"""
"""
numbers = string.split("/")
return float(numbers[0]) / float(numbers[1]) | 354f70ca5f0bf3f493a3905552216f15a7b00b83 | 685,868 |
def greedy_decode(logits, labels):
"""Decode argmax of logits and squash in CTC fashion."""
label_dict = {n: c for n, c in enumerate(labels)}
prev_c = None
out = []
for n in logits.argmax(axis=1):
c = label_dict.get(n, "") # if not in labels, then assume it's ctc blank char
if c != ... | fa04e502eee713beafab10e86ff7f2ed5116fb42 | 685,869 |
def step_id_padded(value):
"""Return the test id from the test step object, index padded to 2.
:param value: The test value
"""
return f"{value.step_index:02d}-{value.user_input}-{value.comment}" | ad0bda6fe3a5ae9cf5c4a18c530afd6616bf5cf8 | 685,870 |
def irc_prefix(var):
"""
Prefix a string with the irc_
:param var: Variable to prefix
:return: Prefixed variable
"""
if isinstance(var, str):
return 'irc_%s' % var.lower() | 13a22ef74844c939b14fb26078b6ab4c93948408 | 685,871 |
from typing import Optional
import os
import sys
def _handle_title(title: Optional[str]) -> str:
"""Return title, or if title is None then return a decent default title."""
if title is None:
title = os.path.basename(sys.argv[0])
return title | e30532ba0b5b9f3f2a6beb3b749f9d0f281ef722 | 685,872 |
def get_data_files(filepath, prefix, num_epochs, num_features=41,
model_type='lstm'):
"""
model folder of type: type_prefix_features
model file of type: prefix_features_epochs.model
means and stddev file of type: means/stddev_prefix_numfeatures.npy
"""
num_epochs = str(num_epo... | fa71549b3208b5ef27f9f1c6d0304d9be31602be | 685,873 |
def success_email_subject_msid_author(identity, msid, author):
"""email subject for a success email with msid and author values"""
return u"{identity}JATS posted for article {msid:0>5}, author {author}".format(
identity=identity, msid=str(msid), author=author
) | c65f946e87140c9c28166daa0e664a994910b559 | 685,874 |
import os
def file_sizes(*fns):
"""Get file sizes in Bytes.
Args:
fns (str): File names.
Returns:
tuple(int): File sizes.
"""
return tuple([os.stat(fn).st_size for fn in fns]) | bba344ffff356400e16b5f81ff7861481bb3af67 | 685,875 |
import string
def fix_name(g):
"""the name is like: org_chr_start_stop but we may have changed start, stop
>>> f = dict(name='name', start=2, end=3, strand='+', chr='chr3',
... type='CDS', attrs={'match':'amatch', 'ID': 'at2g26540_4_5'})
>>> fix_name(f)
>>> f
{'start': 2, 'chr': 'c... | 8043b08e8d3ae7d51d38cf8b3580cfb81a9ca850 | 685,876 |
def calcul_esp(points):
"""
Renvoie l'esperance de chaque catégorie en fonction de sa classe
Parameters
----------
points : list
liste de points
Returns
-------
esperance_par_classe : list
liste d'entiers
"""
dim_point = len(points[0]) - 1
esperance = []
... | 72e16fd62a58707e17d69b25dfe395bb6a3e4358 | 685,877 |
import os
def getcwd_or_default (default=None) :
"""
Returns the current working directory or default if it cannot be found.
Parameters
----------
default : str, optional
Returns
-------
str
"""
if (default is None) :
if (os.name == "nt") :
home_drive = os.environ.get("HOMEDRIVE", "C:"... | d377791e02647af66bcb4a0f49244d33a7a001fd | 685,878 |
def _TotalSeconds(delta):
"""Re-implementation of datetime.timedelta.total_seconds() for Python 2.6."""
return delta.days * 24 * 60 * 60 + delta.seconds | 14ce5f521d8c5a6a6cff110e5d5c0851d42156a8 | 685,879 |
def add_match_to_profile(profile, match, ismap=True, nucl=None):
"""Merge current read-gene matches to master profile.
Parameters
----------
profile : dict
Master gene profile.
match : dict
Read-gene matches.
ismap : bool, optional
Whether matches are a read-to-gene(s) m... | 0431ec934881ccf2bb72f2367e6a1afcbcc38e5d | 685,880 |
def wildcard_filter( input_string ):
"""
A helper function which filters out a wildcard string containing
'ANY' and converts it to 'N/A'.
"""
if str(input_string).strip() == 'ANY':
return 'N/A'
else:
return input_string | e719ed05a22aaca2face9e95445c8f93ac2f8d0b | 685,881 |
import builtins
def _create_binned_data(bin_numbers, unique_bin_numbers, values, vv):
""" Create hashmap of bin ids to values in bins
key: bin number
value: list of binned data
"""
bin_map = dict()
for i in unique_bin_numbers:
bin_map[i] = []
for i in builtins.range(len(bin_numbers... | 5564faaa8586782fc8879a1b536387bbf8cb12bd | 685,882 |
import os
def remap_index_fn(ref_file):
"""Map sequence references to equivalent bismark indexes
"""
return os.path.join(os.path.dirname(os.path.dirname(ref_file)), "bismark") | b7ad1163fb3b0b535dbbd7fe4837d4e4e27548c7 | 685,883 |
def get_human_ccy_mask(ccy):
"""Function that convert exchange to human-readable format"""
# {"ccy":"USD","base_ccy":"UAH","buy":"24.70000","sale":"25.05000"}
return "{} / {} : {} / {}".format(ccy["ccy"], ccy["base_ccy"], ccy["buy"], ccy["sale"]) | 461c20727d6b303874dc5c5b79a0ddab374b5716 | 685,884 |
import requests
def fetch_info(imdb_id, response='json', plot='full', tomatoes=True):
"""
E.g. http://www.omdbapi.com/?i=tt1024648&plot=short&r=json&tomatoes=true
"""
url = 'http://www.omdbapi.com/?i=' + imdb_id
url += '&plot=' + plot
url += '&r=' + response
url += '&tomatoes=' + str(tomat... | dcc0d2bfd7b20104ab5051ddee8d10b946d74514 | 685,885 |
def readComparison(infile):
"""
read comparison files into a list
: param infile: a TAB-delimited file containing 5 field and the first one is the coordinate of split sub-matrix
"""
mylist = []
with open(infile) as f:
for line in f:
position = line.strip().split()
... | ee0447ec45b3c8f51023548d98e507fd593458e4 | 685,887 |
def add_prefix(signal_names, wip_signal, prefix="wip_"):
"""Add prefix to signal if there is a WIP signal.
Parameters
----------
signal_names: List[str]
Names of signals to be exported
prefix : "wip_"
prefix for new/non public signals
wip_signal : List[str] or bool
a lis... | 7a8df5ee4a9181672ab841e4d2609f34cc853c97 | 685,888 |
def array(num_elements, element_func, *element_func_args):
"""
Returns array of elements with a length of num_elements.
Every element is generated by a call to element_func(*element_func_args).
"""
return [element_func(*element_func_args) for _ in range(num_elements)] | 859fd68cac9d3bb3d932aa329651eec4297d32e4 | 685,889 |
def deg_dms(decimal_degree):
"""
Convert angle in degrees to degree, minute, second tuple
:param degree: Angle in degrees
:return: (degree, minutes, second)
Example:
>>> import units as u
>>>
>>> u.dms_deg((45, 23, 34))
45.39277777777778
>>>
... | d487aab58f6837b74bf257c5a5b364da01aaae86 | 685,890 |
def extract_from_result_id(result_id):
"""Extract default uuid string repr from compressed format."""
delimiters = [8, 4, 4, 4, 12]
uuid = "urn:uuid:"
for delimiter in delimiters:
if uuid != "urn:uuid:":
uuid += "-"
uuid += result_id[:delimiter]
result_id = result_id[... | 0fd8361fd65be201bd7e1ab00230d976d2ceefe8 | 685,891 |
def _last_test(test):
"""Returns True if given test is the last one."""
parent_tests = tuple(test.parent.testcases)
return parent_tests.index(test) == (len(parent_tests) - 1) | 075ec9fb00d880265a081b942396ac61bcf2bfcb | 685,892 |
import requests
def ask_for_numbers():
"""helper function to get numbers from other pi"""
requests.get("http://zero2.local:5000/get_num", timeout=(20,0.02))
return 1 | 43563aa16f317843639455caa55e2a0d8dd06a54 | 685,893 |
import re
import sys
def get_igo_id(file_name):
""" Extracts IGO ID from intput BAM filename.
:param file_name: string e.g. "/PITT_0452_AHG2THBBXY_A1___P10344_C___13_cf_IGO_10344_C_20___hg19___MD.bam"
:return: string e.g. "10344_C_20"
"""
regex = "IGO_([a-zA-Z0-9_]*?)___"
match... | 63407cfaff67dc0b477db9e57e84c9e6f5643f1c | 685,894 |
def compare_posts(fetched, stored):
"""
Checks if there are new posts
"""
i=0
for post in fetched:
if not fetched[post] in [stored[item] for item in stored]:
i+=1
return i | b23f9cc02030c4ee14ff983012863e35a24feaab | 685,896 |
def GetPassDay(strDatetime, endDatetime):
"""获取日期间隔天数(忽略小时,不是时间的间隔天数)
@return int ( >0 if endDatetime>strDatetime else <=0)
"""
strDate = strDatetime.date()
endDate = endDatetime.date()
return (endDate - strDate).days | 7ca794f16a7a66b4999c43301110b89fb61b5b87 | 685,897 |
def build_query(filters, page, request):
"""
Construye el query de búsqueda a partir de los filtros.
"""
if filters.jur:
q = filters.buildQuery().order_by('carrera__nombre')
else:
q = filters.buildQuery().order_by('jurisdiccion__nombre', 'carrera__nombre')
return q | 825f155d77dcb0df5b1cc5b07e7d525b6edf76fd | 685,898 |
def required_jenkins_settings(settings):
""" Checks if all settings required for interacting with jenkins build are set """
try:
return all([ settings.get('jenkins', setting) != '' for setting in ['url', 'username', 'password', 'job_name', 'build_num'] ])
except KeyError:
return False | 7e8aa7e0feaab08d46f5927f991406aebe29db3e | 685,900 |
def MCMC_settings():
"""==================================
Set your preferences for the MCMC sampling.
=================================="""
mc = dict()
mc['Nwalkers'] = 100 ## number of walkers
mc['Nburnsets']= 2 ## number of burn-in sets
mc['Nburn'] = 4000 ## length of each burn-in ... | 5d860bd0348d0ccc5e5e66e61b001d5994b8734a | 685,901 |
def find_id(concept, h):
"""
:type concept: Collection.iterable
"""
id_found = 0
for e in concept:
if e['id'] == h:
return id_found
id_found += 1
return None | 64d1520d58f689bf7e6bd2d5569d8b249775f3ee | 685,902 |
from typing import Union
def getNumeric(param: str) -> Union[float, int]:
"""
Function that returns a numeric from a random data string.
:param data:
:return:
"""
if not isinstance(param, str):
return param
if "." in param:
return float(param)
return int(param) | cd4130d0809e6779ea5a8c60cf376724125716b3 | 685,903 |
import requests
def _return_response_and_status_code(response, json_results=True):
""" Output the requests response content or content as json and status code
:rtype : dict
:param response: requests response object
:param json_results: Should return JSON or raw content
:return: dict containing th... | 1e432e667596b36b38b117cf9fe17c6e80b2baa1 | 685,904 |
from pathlib import Path
def paths():
"""Gets common paths for tests running uploads"""
top_level = Path(__file__).parents[1] / "data"
input = top_level / "data_octree"
return top_level, input | 0882f4e960a2e7207d1d7f728159c1172cbfc920 | 685,906 |
def prune_wv(df, vocab, extra=["UUUNKKK"]):
"""Prune word vectors to vocabulary."""
items = set(vocab).union(set(extra))
return df.filter(items=items, axis='index') | 1e42a8426a5b931f9d611f7773d7d018c85ca507 | 685,907 |
def calc_bmr(weight, height, age):
"""
:param weight: weight in kg
:param height: height in cm
:param age: age in years
:return: bmr
"""
return 10 * weight + 6.25 * height - 5 * float(age) | dd28926a00cd8217b0498aabb05900cdc6af1f52 | 685,908 |
import csv
def check_diff_genes(diffpeak, outputfile, diffgenes, condition):
"""
:param diffpeak:
:param outputfile:
:param diffgenes:
:param condition:
:return:
"""
genes_in_data = dict()
with open(diffgenes, 'r') as genefile:
header = genefile.readline().strip().split()
... | 65f7000f6ec94804e020f9cc3487fbb3c2a37973 | 685,909 |
def addressInNetwork(ip, net):
"""
Is an address in a network
"""
return ip & net == net | ea2983d96c79bf7e72e304cdc715ad983906b2d1 | 685,911 |
from socket import gethostname
def host_local_machine(local_hosts=None):
""" Returns True if its a recognized local host
Keyword Arguments:
local_hosts {list str} -- List of namaes of local hosts (default: {None})
Returns:
[bool] -- True if its a recognized local host False other... | 3ad2ba6b5368ab6d70d3ffcbc415316c02a9928f | 685,912 |
def print_msg(msg):
"""Print message in console."""
def green_msg(msg):
"""Make message green color in console."""
return '\033[92m{0}\033[00m'.format(msg)
print(green_msg('\n{}\n'.format(msg))) | 96851002cfd698d1c3f8d55ae33d436d770ef9ed | 685,913 |
import torch
def get_all_pairs_indices(labels, ref_labels=None):
"""
Given a tensor of labels, this will return 4 tensors.
The first 2 tensors are the indices which form all positive pairs
The second 2 tensors are the indices which form all negative pairs
"""
if ref_labels is None:
ref... | a3db5bfa5d064f0901ea6f6bbd6457356c74e3ba | 685,914 |
from typing import Set
def _negative_to_positive_state_indexes(indexes: Set[int], n_entries) -> Set[int]:
""" Convert negative indexes of an iterable to positive ones
Parameters
----------
indexes: Set[int]
indexes to check and convert
n_entries: int
total number of entries
R... | 65a66766a1eef881393ee5b89d6785f0ebcab6a5 | 685,916 |
import importlib
def collection_import():
"""These tests run assuming that the awx_collection folder is inserted
into the PATH before-hand by collection_path_set.
But all imports internally to the collection
go through this fixture so that can be changed if needed.
For instance, we could switch to... | 9c6e2a67c69434583ffbd9e63b070ef9462074ce | 685,917 |
import math
def distance(point_one, point_two):
"""Calculates the Euclidean distance from point_one to point_two
"""
return math.sqrt((point_two[0] - point_one[0]) ** 2 + (point_two[1] - point_one[1]) ** 2) | 92fe5b28046f6eb96fa6552e750ca62010d700da | 685,918 |
def matches_have_unknown(matches, licensing):
"""
Return True if any of the LicenseMatch in `matches` has an unknown license.
"""
for match in matches:
exp = match.rule.license_expression_object
if any(key in ('unknown', 'unknown-spdx') for key in licensing.license_keys(exp)):
... | a64a4377b86cac05125d5c26e8325716f548f0e7 | 685,919 |
def mvt(a, b, fx = lambda x: x):
"""
Mean value theorem
Params:
a: start of interval
b: end of interval
fx: function
Returns:
f_c: derivative of some point c that is a <= c <= b
"""
return (fx(b) - fx(a))/(b - a) | d35e6cbaed79a0430ac33a02a95bd9cc7ad14477 | 685,920 |
def atom(token):
"""
输入:字符
输出:整型,浮点型,或者字符
"""
# 无法用 if else 语句,必须要先转化token,再判断是否是相应数据类型,但是转化失败就无法判断了
# 所以为了转化失败,让解释器不抛出错误,我们使用token
# 而要用 if else 的高级语句 try except
# if isinstance(token, int):
# return int(token)
# elif isinstance(token, float):
# return floa... | 8c1845fff9c2cb23e11e7ccf9d46cbd593109bf6 | 685,921 |
def dag_paths(dag):
""" :return A frozenset containing every path (v1,v2,...,vn) such that each vi is nested within @dag and
is a direct element of at most one set.
:param @dag A nested structure of elements where each element is a string, a tuple or a frozenset. """
if dag == ():
return {()}
... | 09c2ae1b098348f98553f7d5b4299b8af61a149f | 685,922 |
import random
def get_personal_info_param():
"""
Assemble params for get_personal_info
:return: Params in dict
"""
param_dict = dict()
param_dict['menuid'] = 'customerinfo'
param_dict['pageid'] = str(random.random())
return param_dict | 4e92557b88e67efe6ed4d700cf4258f13f352e66 | 685,924 |
def function_check(x,limits,numerical_cols):
"""
True: outside hypercube
False: not outside hypercube
"""
result = False
for col in numerical_cols:
l_max = limits[col+'_max'][0]
l_min = limits[col+'_min'][0]
# If its outside from some of the limits, then its... | e80ef7497da73f2e1b363de26ad383c757785ae2 | 685,925 |
import argparse
def get_options():
"""
Parse and return the arguments provided by the user.
"""
parser = argparse.ArgumentParser(description='Launch crab over multiple datasets.')
parser.add_argument('--submit', action='store_true', dest='submit',
help='Submit all the task... | 7c46a574622856ce0874ee2a0d849a8ffd5db8b5 | 685,926 |
def add_prefix(prefix, split, string):
"""
Adds a prefix to the given string
:param prefix: str, prefix to add to the string
:param split: str, split character
:param string: str, string to add prefix to
:return: str
"""
return split.join([prefix, string]) | 0f0e29be17ec771425617bd550ef99a61cd42062 | 685,927 |
import textwrap
import asyncio
import os
async def create_sample_datasets_and_visualisations():
"""Creates one of each type of dataset/visualisation
WARNING: removes any pre-existing datasets/visualisations
Creates 5 datasets/visualisations:
1) Master dataset, available to all, with DIT source tag
... | f8dd919c7a8c346adb9eb0992cc17e100bc3fc1b | 685,928 |
import pathlib
def md_files(file_list):
"""Get list of markdown files from the repository file list"""
md_files = []
while file_list:
git_file = file_list.pop()
if pathlib.Path(git_file.name).suffix == ".md":
md_files.append(git_file)
return md_files | bf41715fac814c0b8bc467aab8787b611c41ac5f | 685,929 |
import math
def next_byte_power(value):
"""Calculate the next power of 2 from a value."""
char_bit = 8
byte_length = int(math.ceil(value.bit_length() / char_bit))
return 2 ** (char_bit * byte_length) | ea17b98507f9cdcba6a16e74e07e269e007923c1 | 685,930 |
import numpy
def skew(r):
"""
Calculates the Skew matrix
Attributes:
r: vector
Return:
S: Skew symmetric matrix
"""
S = numpy.array( [ [0, -r[2], r[1] ],
[ r[2], 0, -r[0] ],
[ -r[1], r[0], ... | c63d97845ac48824d6fadebd275f087778d2f549 | 685,931 |
def rank_mirnas(all_data, genes):
"""
Calculate total score for each miRNA and sort rows in descending order.
:param all_data: dict
:param genes: list of genes
:return:
"""
condensed_rows = list()
for mirna, row in all_data.items():
mirna_score = 0
mirna_row = tuple()
gene_nr = len(genes)
for i in range... | 45396d43c748f57774e86400e68a992c045c99da | 685,932 |
def get_area_codes():
"""
Returns:
An array of US phone area codes
"""
area_codes = [
205, 251, 256, 334, 938, # Alabama
907, 250, # Alaska
480, 520, 602, 623, 928, # Arizona
327, 479, 501, 870, # Arkansas
209, 213, 310, 323, 408, 415, 424, 442, 510,... | f8887102ff7a2016137dc08a73ab2c29391d104e | 685,933 |
def serialize_structures(storage):
"""
Serializes storage structures into dict.
:param dict storage: Storage dict.
:return: Serialized storage.
:rtype: dict
"""
return {
"tasks": [list(t._asdict().values()) for t in storage["tasks"]],
"groups": [list(g._asdict().values()) f... | b19f18b41ac15dfc4e8776c97c741a33e8858933 | 685,934 |
def apply_twice(f, x):
"""Return f(f(x))
>>> apply_twice(square, 2)
16
>>> from math import sqrt
>>> apply_twice(sqrt, 16)
2.0
"""
return f(f(x)) | 19f0e6350e47926134bc6173a264c89d5ab9b6a3 | 685,937 |
def extract_wikipedia_page(line):
"""Extracts the Wikipedia page for an entity"""
if "sitelinks" in line and "enwiki" in line["sitelinks"]:
return line["sitelinks"]["enwiki"]["title"].strip().replace(" ", "_")
return None | 079d76967266e4248c340dd45e94d4a0c713ad11 | 685,938 |
def _get_port_interface_id_index(dbapi, host):
"""
Builds a dictionary of ports indexed by interface id.
"""
ports = {}
for port in dbapi.ethernet_port_get_by_host(host.id):
ports[port.interface_id] = port
return ports | 048844dda9e7069e195f6c6f8818c9b0d655bb08 | 685,940 |
def get_stability(data, for_next_minutes=None, **kwargs):
"""Pass."""
if data.is_running:
if data.is_correlation_finished:
return "Discover is running but correlation has finished", True
return "Discover is running and correlation has NOT finished", False
next_mins = data.next_... | 11b2a9b8cb576cf80cd7dbe4aa2d58f6a4543999 | 685,941 |
import random
def random_correct_answer_message(correct_answer, points):
""" Return a random encouraging phrase for getting a right answer """
phrases = [
"Nailed it!",
"Nice one!",
"Great work!",
"You got it!",
"Woohoo, nice job!",
"You're amazing!",
"C... | da019a5a0eba651fb85f622498341c15557589cd | 685,943 |
def is_protein_family(bio_ontology, node):
"""Return True if the given ontology node is a protein family."""
if bio_ontology.get_ns(node) == 'FPLX':
return True
return False | 7de9a5b7a11a4267a3a7904b6f9160cf9f9dc253 | 685,944 |
import re
def camel_to_snake(s: str) -> str:
"""Convert a string from camelCase string to snake_case.
Args:
s: String to be converted.
Returns:
A string where camelCase words have been converted to snake_case.
"""
return re.sub(r'(?<!^)(?=[A-Z])', '_', s).lower() | e29b5f7027be0692cecc9cbd145c864815b7cadc | 685,945 |
def inputNumber(message):
""" Get an input number from user. Prompt is str @message
"""
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
... | 14f9f87757fb50337b4b589b8f7d166ff52521e6 | 685,946 |
def generate_linear_costlist(max_torsions=5):
"""
1 1
2 1
1 2
3 1
2 2
1 3
etc
"""
combos = []
for i in range(max_torsions):
for j in range(i):
combo = [i-j, j+1]
combos.append(combo)
return combos | caa4e05cd19b08e45b1d11a3017fe01814c3ff6d | 685,949 |
import torch
from typing import Optional
def all_in_bounds(
x: torch.Tensor,
low: Optional[float] = None,
high: Optional[float] = None,
a_tol: float = 0.,
) -> bool:
"""Check if tensor values respect lower and upper bound.
:param x:
The tensor.
:param low:
The lower bound.... | 5f146707ba5dc01244ee25cfd02e7f37dca36d24 | 685,950 |
def get_nfunc_list(fit_func, adaptive, data, nfunc_max_dict):
"""Makes nfunc list."""
nfunc_max = nfunc_max_dict[fit_func.__name__[:2]]
if adaptive:
nfunc_list = [nfunc_max]
else:
nfunc_list = list(range(1, nfunc_max + 1))
if fit_func.__name__[:2] == 'nn':
if fit_func.__name_... | 86cc756ded4376c2e42f38b9a6fe2a4dee59a1e7 | 685,952 |
def favicon():
"""favicon."""
return('NOK', 'text/plain', '') | 2e74260664dd9cb90de933d1e1144f4e90f8c256 | 685,953 |
def d3(x):
"""Evaluate the estimate 3*x**2+2*x+1."""
return (3*x+2)*x+1 | 84b8c37237540a9cc01ebe161c536228388b77f7 | 685,954 |
def find_age_breakpoints_from_dicts(age_dict):
"""
Convert a dictionary of age groups back into the list of breakpoints.
"""
breakpoints_with_repetition = []
breakpoints = []
# add all age breakpoints to a temporary list that allows repetition
for key in age_dict:
for i in age_dict... | 259ab6140ff8712632788687ae8d23e5a90dc168 | 685,955 |
def circle_diam_rad(radius):
"""Usage: Find circle's diameter from radius"""
return radius*2 | 18c8c50c3f20fe7cf2f331c6f3fede7988c7f94d | 685,956 |
def prompt_output(cli_input, converted=None):
"""Return expected output of simple_command, given a commandline cli_input string."""
return f'Opt: {cli_input}\n{converted or cli_input}\n' | beceecf80039452e68acb02005ab35ce939be735 | 685,957 |
import shlex
import subprocess
def _get_process_results(command):
"""Gets a subprocess result based on the given arguments
param - Parameters, including program. Eg: alpr -c eu -j img.jpg
return - [results, error]
"""
# Generate and slpit up commands (required by subprocess)
command_args = s... | 6479be6aa58dbb03eabbbb8277b455a752d716be | 685,958 |
def only_for_board_and_development(boards):
"""
Create a filter that is only considered when the given board matches and
when development is toggled.
"""
def _inner(context):
return context["board"] in boards and context["development"]
return _inner | b12d6f8d5aa45993375bdf2e7ff2a605fa5f4ee1 | 685,959 |
import pickle
def pickle_loader(data):
"""YAML tag for loading pickle files."""
with open(data, "rb") as f:
data = pickle.load(f)
return data | dfa22df1c8bb875c6a483a0d4cf2f0c81e7d6f10 | 685,960 |
def convert_environment_id_string_to_int(
environment_id: str
) -> int:
"""
Converting the string that describes the environment id into an int which needed for the http request
:param environment_id: one of the environment_id options
:return: environment_id represented by an int
"""
try... | 31f2927d554bd7008faa43a3e7540860106a4a95 | 685,961 |
import grp
def get_gid_from_group(group):
"""Return GID from group name
Looks up GID matching the supplied group name;
returns None if no matching name can be found.
NB returned GID will be an integer.
"""
try:
return grp.getgrnam(group).gr_gid
except KeyError as ex:
ret... | e6e41240d3a57edd05d144dd912e981869623ab8 | 685,962 |
def check_pseudo_overlap(x1, x2, y1, y2):
"""
check for overlaps [x1, x2] and [y1, y2]
should only be true if these overlap
"""
return max(x1, y1) <= min(x2, y2) | b0b737da1746fecbddf9458fc40c9151da277ac1 | 685,963 |
import numpy as np
def readDataFromCsv(filename, readNames):
"""Read data from .csv file into an array.
Output: a numpy array"""
data = np.genfromtxt(filename, delimiter = ',', names=readNames)
return data | 3ff73bb78392b9e513f97a6f391e242c9b64c13e | 685,964 |
import base64
def base85_encode(string: str) -> bytes:
"""
>>> base85_encode("")
b''
>>> base85_encode("12345")
b'0etOA2#'
>>> base85_encode("base 85")
b'@UX=h+?24'
"""
# encoded the input to a bytes-like object and then a85encode that
return base64.a85encode(string.encode("utf... | 046d623abb4c7d5dfc65159ca82e81508be1cc5a | 685,965 |
from pathlib import Path
def image_file_path(instance, filename, ext='.jpg'):
"""Returns the path with modified file name for the image files.
Args:
instance (object): instance of the file being uploaded.
filename (str): current name of the file.
Returns:
str: new file path.
... | ae3d3facad13afd8f92f4ac5c834b8944462018c | 685,966 |
def merge_variables(variables, name=None, **kwargs):
"""Merge/concatenate a list of variables along the row axis.
Parameters
----------
variables : :obj:`list`
A list of Variables to merge.
name : :obj:`str`
Optional name to assign to the output Variable. By default, uses the
... | e239ae680e525dc3302ca099932b67d3221c96da | 685,967 |
def replace_fields(field_list, *pairs):
"""Given a list of field names and one or more pairs,
replace each item named in a pair by the pair.
fl = 'one two three'.split()
replace_fields(fl, ('two', 'spam'))
# ['one', ('two', 'spam'), 'three']
"""
result = list(field_list)
for field_name,... | 1745bc45df00bd4475bb01d9eb20b420cd24f6fc | 685,968 |
from typing import Optional
def rsubstringstartingwith(sub: str, s: str) -> Optional[str]:
"""
>>> rsubstringstartingwith('://', 'database://foo')
'foo'
>>> rsubstringstartingwith('://', 'database://foo://bar')
'bar'
>>> rsubstringstartingwith('://', 'foo')
None
"""
try:
re... | b22172992a96eb7842e5fbc065b0a10608f2366e | 685,969 |
def parse_bool(x, true=('true', 'yes', '1', 'on'), add_true=(),
false=('false', 'no', '0', 'off'), add_false=()):
"""Parse boolean string.
Parameters
----------
x : bool or str
Boolean value as `bool` or `str`.
true : list of str
List of accepted string representation... | eced20795d3455a38d0dc4f11d4805b60a7aa03d | 685,970 |
def get_space_from_string(space_str):
"""
Convert space with P, T, G, M to int
"""
M = 1024
G = 1024 * M
T = 1024 * G
P = 1024 * T
if 'M' in space_str:
return int(float(space_str.split('M')[0]) * M)
elif 'G' in space_str:
return int(float(space_str.split('G')[0]) * G... | 34f28b1c20497a8bafdf9b08a6b9db9e4c61bc3f | 685,971 |
async def read_vlq(stream):
"""
Reads a VLQ from a stream, and returns both the parsed value and the bytes belonging to it.
:param stream: A stream object, with readexactly() defined.
:return: int, bytes: The parsed value and unparsed value of the VLQ.
"""
raw_bytes = b""
value = 0
while... | af456b20ddb654ab76e8ca8e14fcff749b2cd301 | 685,972 |
def findPath(g, start_vertex, end_vertex, poids = 0, path=None):
""" find a path from start_vertex to end_vertex in graph """
if path == None:
path = []
graph = g.gDict()
path = path + [start_vertex]
if start_vertex == end_vertex:
return (path,poids)
if start_vertex not in graph:... | bd36b3d0309cefa211bf1e879c56eda717625f52 | 685,973 |
def get_top_fitness(dirty_values):
"""Return top fitness value.
Returns the top fitness values of a
:class:`~paddy.Paddy_Runner.PFARunner`, solely, for each iteration as a
list when passed a dictionary with the structure type of
:attr:`~paddy.Paddy_Runner.PFARunner.top_values`.
Parameters
... | 7c930b0ce8e053256cbbd693502e2dc3374f8aba | 685,974 |
def generate_statline(statid, version, time, date, lc, vh):
"""
Genera una línea de estadísticas.
:param statid: ID de la línea
:param version: Versión
:param time: Tiempo de compilación
:param date: Fecha de compilación
:param lc: Número de líneas
:param vh: Version hash
:return:
... | b14bb4fa04bd0c84d276959e7eba8fc40f6950de | 685,975 |
def moles_to_pressure(volume: float, moles: float, temperature: float) -> float:
"""
Convert moles to pressure.
Ideal gas laws are used.
Temperature is taken in kelvin.
Volume is taken in litres.
Pressure has atm as SI unit.
Wikipedia reference: https://en.wikipedia.org/wiki/Gas_l... | 43c7f5346da68db758dfae6e256260054cfd5d39 | 685,976 |
def get_file_names(in_list):
"""Makes a list of each index[1] in a list of lists
This method is deployed in the get_medical_image_list route
:param in_list: list of lists containing patient medical
images and file names
:return: list containing file names
"""
temp = list()... | 8bb61ba487bbdb5e880e9c82b04ceaaea364f483 | 685,977 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.