content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def main():
"""Main execution."""
def download_ratings_for_project_id(project_id):
if project_id in all_ratings.keys():
return None # already downloaded this project's ratings
for _ in range(MAX_TRIES_PER_URL):
try:
url = f'https://search.worldbank.org/ap... | 5,310,800 |
def partition_sort(arr):
"""
An idyllic variant of quicksort, powered by numpy.partition.
"""
if arr.shape[0] < 2:
return arr
mid = arr.shape[0] // 2
partitioned = np.partition(arr, mid)
sm = partition_sort(partitioned[:mid])
lg = partition_sort(partitioned[(mid+1):])
... | 5,310,801 |
def _phase_from_label(label):
"""Return the phase from a label"""
# Returns None if label is invalid
label = label.replace("+", "", 1).replace("1", "", 1).replace("j", "i", 1)
phases = {"": 0, "-i": 1, "-": 2, "i": 3}
if label not in phases:
raise QiskitError("Invalid Pauli phase label '{}'"... | 5,310,802 |
def test_run_all():
"""
Test if it runs all the munin plugins
"""
mock = MagicMock(return_value="uptime.value 0.01")
with patch.dict(munin.__salt__, {"cmd.run": mock}), patch(
"salt.modules.munin.list_plugins", MagicMock(return_value=["uptime"])
):
assert munin.run_all() == {"upt... | 5,310,803 |
def test_lightningd_still_loading(node_factory, bitcoind, executor):
"""Test that we recognize we haven't got all blocks from bitcoind"""
mock_release = Event()
# This is slow enough that we're going to notice.
def mock_getblock(r):
conf_file = os.path.join(bitcoind.bitcoin_dir, 'bitcoin.conf'... | 5,310,804 |
def subject_topic(field: Field = None) -> Optional[str]:
"""
Returns an uppercase topic to be used in the subject segment of the call
number based on MARC tag 650. Valid only for BPL call numbers.
Examples: programming language, name of operating system, etc.
Args:
field: p... | 5,310,805 |
def test_scheduler_celery_timeout_ny(execute_mock):
"""
Reports scheduler: Test scheduler setting celery soft and hard timeout
"""
with app.app_context():
report_schedule = insert_report_schedule(
type=ReportScheduleType.ALERT,
name="report",
crontab="0 4 * *... | 5,310,806 |
def inverse_metric_tensor(basis):
"""
Compute the inverse metric tensor for a basis.
:param basis: Basis (square matrix with basis vectors as columns).
:return: Inverse metric tensor.
"""
g = metric_tensor(basis)
if not isinstance(g, np.ndarray):
# Assume scalar
return 1 / g... | 5,310,807 |
def save_data(filename, value1, operation, value2, result,log_1_counter):
"""Save data function"""
log_1_counter=log_1_counter+1
"""Save data function"""
logger.debug(f'saving details of {filename}..')
with open('demo.log','a') as append_file:
append_file.write(f'Filename:{filename} -Record ... | 5,310,808 |
def get_all_annots(annotations):
"""
All annotations
"""
all_annots = set()
for genome in annotations.keys():
for annot_name in annotations[genome].keys():
all_annots.add(annot_name)
logging.info(' No. of annotation columns: {}'.format(len(all_annots)))
return sorted(all... | 5,310,809 |
def main():
"""
*The main function used when ``csvtools.py`` run as a single script from the cl*
"""
########## PRE-IMPORT SETUP ##########
relativePathToProjectRoot = "../../../"
import dryxPython.projectsetup as dps
projectSetup = dps.projectSetup(
dbConn=False,
relativePat... | 5,310,810 |
def get(guild):
"""
Gets a single GuildSettings Object representing the settings of that guild
:param guild:
:return Single GuildSettings Object: :type GuildSettings:
"""
return GuildSettings(guild) | 5,310,811 |
def process_attachments(path_to_content_file: Path, set_of_links: set[str], note_paths: set[Path],
source_absolute_root):
"""
Generate sets of attachment links from content.
The sets of links based on the status of that links.
all - all links found in the content that are no... | 5,310,812 |
def delete_instance_template(template_name: str):
"""Returns a ProcessResult from running the command to delete the
measure_worker template for this |experiment|."""
command = [
'gcloud', 'compute', 'instance-templates', 'delete', template_name
]
return new_process.execute(command) | 5,310,813 |
def create(body):
"""
Create a new grid.
:param (dict) body: A mapping of body param names to values.
:returns: (requests.Response) Returns response directly from requests.
"""
url = build_url(RESOURCE)
return request('post', url, json=body) | 5,310,814 |
def arr(shape=None, element_type=float,
interval=None,
data=None, copy=True,
file_=None,
order='C'):
"""
Compact and flexible interface for creating numpy arrays,
including several consistency and error checks.
- *shape*: length of each dimension, tuple or int
- *d... | 5,310,815 |
def evaluate_template(template: str, prefix="$", sufix="$"):
"""Evaluate a string template; replace all queries by their values
Queries in the template are delimited by prefix and sufix.
Queries should evaluate to strings and should not cause errors.
"""
return Context().evaluate_template(template, ... | 5,310,816 |
def rsp_fixpeaks(peaks, troughs=None):
"""Correct RSP peaks.
Low-level function used by `rsp_peaks()` to correct the peaks found by `rsp_findpeaks()`.
Doesn't do anything for now for RSP. See `rsp_peaks()` for details.
Parameters
----------
peaks : list or array or DataFrame or Series or dict
... | 5,310,817 |
def get_dfu_devices(*args, **kwargs):
"""Returns a list of USB device which are currently in DFU mode.
Additional filters (like idProduct and idVendor) can be passed in to
refine the search.
"""
# convert to list for compatibility with newer pyusb
return list(usb.core.find(*args, find_all=True,
... | 5,310,818 |
def emailWeeklyOrders():
"""
Emails all the current admins an email containing every users current order.
Returns total emails sent and the email for every admin.
"""
all_orders = get_all_users_orders()
user_login_url = get_login_url()
current_date = datetime.date.today()
context = ... | 5,310,819 |
def content_type(suffix: str) -> str:
"""
Gets the Content-Type header for a type of file.
Arguments:
suffix: Filename suffix.
"""
suffix = normalize_suffix(suffix)
return _content_types.get(suffix, _default_content_type) | 5,310,820 |
def revdocs2reverts(rev_docs, radius=defaults.RADIUS, use_sha1=False,
resort=False, verbose=False):
"""
Converts a sequence of page-partitioned revision documents into a sequence
of reverts.
:Params:
rev_docs : `iterable` ( `dict` )
a page-partitioned sequence of... | 5,310,821 |
def get_ghcn_stid(config, stid):
"""
After code by Luke Madaus.
Gets the GHCN station ID from the 4-letter station ID.
"""
main_addr = 'ftp://ftp.ncdc.noaa.gov/pub/data/noaa'
site_directory = '%s/site_data' % config['THETAE_ROOT']
# Check to see that isd-history.txt exists
stations_fil... | 5,310,822 |
def compare_pair(p1, p2, cp1, cp2):
"""Given comparison functions for the first and second part of
the pair, compare the two pairs using the two functions under
lexicographic order.
"""
res1 = cp1(p1[0], p2[0])
if res1 != EQUAL:
return res1
else:
return cp2(p1[1], p2[1]) | 5,310,823 |
def scan(
cli_call_name: str, module: str, package: Optional[str], verbose: bool, help: Optional[str]
) -> CommandTrie:
"""
This crawls all of the modules below us and imports them recursively
:return:
"""
root_module = importlib.import_module(module, package=package)
root_path = root_module... | 5,310,824 |
def train_epoch(net, train_iter, loss, updater, device, use_random_iter):
"""Train a net within one epoch (defined in Chapter 8)."""
state, timer = None, d2l.Timer()
metric = d2l.Accumulator(2) # Sum of training loss, no. of tokens
for X, Y in train_iter:
if state is None or use_random_iter:
... | 5,310,825 |
def read_tcp_pac(link_packet, byteorder, link_layer_parser, seconds, suseconds):
"""read tcp data.http only build on tcp, so we do not need to support other protocols."""
state, source, dest, tcp_packet = read_ip_pac(link_packet, byteorder, link_layer_parser)
if state == 0:
return 0, None
tcp_b... | 5,310,826 |
def basic_metrics(predict, label):
"""
Methods that returns:
true positive
true negative
false positive
false negative
Args:
predict: prediction
label: labels
Returns:
true_pos, true_neg, false_pos, false_neg, sum
"""
true_pos = int(sum(n... | 5,310,827 |
def save_model(args, sess, saver, global_step):
"""
Saves a tensorflow model.
Args:
args (arguments class): arguments to train the RNN.
sess (tf.session): session to save and sample.
saver (tf.saver): object to save tf trained variables.
global_step (int): current global wei... | 5,310,828 |
def hail_metadata(t_path):
"""Create a metadata plot for a Hail Table or MatrixTable.
Parameters
----------
t_path : str
Path to the Hail Table or MatrixTable files.
Returns
-------
:class:`bokeh.plotting.figure.Figure` or :class:`bokeh.models.widgets.panels.Tabs` or :class:`bokeh.... | 5,310,829 |
def partition_create(cmd_ctx, cpc, **options):
"""
Create a partition in a CPC.
In addition to the command-specific options shown in this help text, the
general options (see 'zhmc --help') can also be specified right after the
'zhmc' command name.
"""
cmd_ctx.execute_cmd(lambda: cmd_partiti... | 5,310,830 |
def test_outschema_dict_structure():
"""
Test the types of the keys in the inpschemadict
"""
outputschema = OutputSchemaDict.fromVersion('0.34')
EXPECTED_TYPES = {
'tag_paths': CaseInsensitiveDict,
'unique_attribs': CaseInsensitiveDict,
'unique_path_attribs': CaseInsensitiv... | 5,310,831 |
def persist_state(request):
"""Persist arbitrary string in cache.
It will be matched when the user returns from the OAuth server login
page.
"""
state = uuid.uuid4().hex
redirect_url = request.validated['querystring']['redirect']
expiration = float(facebook_conf(request, 'cache_ttl_seconds')... | 5,310,832 |
def refactor_lambda(astref, srcpos, argsig, body, cntrl, ecntrl):
"""Update lambda so it captures free variables"""
clist = [] # Definition argument signature
newlist = [] # New list is new item list
_find_refs(argsig, srcpos, body, cntrl, ecntrl, clist, newlist)
if clist:
# Get the ... | 5,310,833 |
def rebind_comboBox(comboBox):
"""
Rebind Up and Down key events to open menu instead of crashing
"""
comboBox._entryWidget.unbind("<Up>")
comboBox._entryWidget.unbind("<Down")
comboBox._entryWidget.bind("<Up>", lambda e,cb=comboBox: __comboBox_postList(e,cb))
comboBox._entryWidget.bind("<Do... | 5,310,834 |
def register_model_wrapper(name: str) -> Callable[[Type], Type]:
"""
Register a model wrapper so that it is available via the CLI.
>>> @register_model_wrapper("my_model_name")
... class MyModelWrapper:
... pass
"""
def _inner(cls_):
global MODEL_WRAPPER_REGISTRY
MODEL_W... | 5,310,835 |
def check_non_empty(object_name: str, engine: sqlalchemy.engine.base.Engine):
"""Check if a Snowflake object has a COUNT() > 0."""
with engine.connect() as con:
count = con.execute(f"SELECT COUNT(*) FROM {object_name}").fetchone()[0]
return count > 0 | 5,310,836 |
def importManeshFiles():
""" import data from Manesh text files, convert to dataframe, concatenate and filter """
# the raw BP data from Manesh came in 2 files, one for my data and one for Adam Guss's data
rawBPdan = pd.read_table(r"October2016\DanOlson_SFRE_V5_Test3\Strain_Sample_BrkPnts.Test3.txt.Tabbed")... | 5,310,837 |
def construct_select_bijlagen_query(bericht_uri):
"""
Construct a SPARQL query for retrieving all bijlages for a given bericht.
:param bericht_uri: URI of the bericht for which we want to retrieve bijlagen.
:returns: string containing SPARQL query
"""
q = """
PREFIX schema: <http://sche... | 5,310,838 |
def tologodds(df, y):
"""
Converts column `y` of dataframe `df` to its trimmed logodds.
Name is preserved.
"""
return df.assign(**{y: df[y].pipe(lambda x: trimmed(logodds, x))}) | 5,310,839 |
async def bienvenue(ctx, nouveau_membre: discord.Member):
"""
Commande: bienvenue
Affiche un message texte de bienvenue pour une personne dont le speudo est en paramètre.
:param nouveau_membre: pseudo d'un membre discord
:type nouveau_membre: discord.Member
"""
pseudo=nouveau... | 5,310,840 |
def sync(config_name: str, running):
"""Starts Maestral in the console. Quit with Ctrl-C."""
if running == "gui":
click.echo("Maestral GUI is already running. Please quit the GUI "
"before starting the daemon.")
return
elif running == "daemon":
click.echo("Maestra... | 5,310,841 |
def ha(name, iterations=1, progress=False):
"""Test an OpenStack deployment."""
data.load_config(name)
deployment = data.load_deployment(name)
test_object = HATest(deployment, progress)
local = "./results/{0}/".format(deployment.name)
run_cmd("mkdir -p {}".format(local))
for controller in d... | 5,310,842 |
def user_demand_tmp(user_demand: UserDemand) -> List[Dict]:
"""
Log global user demand.
:param scheduler: the scheduler
:return: list of records for logging
"""
result = [{"value": user_demand.value}]
return result | 5,310,843 |
def _serve_all(config_file_path, aergo1, aergo2,
privkey_name=None, privkey_pwd=None):
""" For testing, run all validators in different threads """
with open(config_file_path, "r") as f:
config_data = json.load(f)
validator_indexes = [i for i in range(len(config_data['validators']))]
... | 5,310,844 |
def process_css(css_source, tabid, base_uri):
"""
Wraps urls in css source.
>>> url = 'http://blue360media.com/style.css'
>>> process_css('@import "{}"'.format(url), 0, url) # doctest: +ELLIPSIS
'@import "/proxy?..."'
"""
def _absolutize_css_import(match):
return '@import "{}"'.form... | 5,310,845 |
def get_Meraki_Organization(MERAKI_API_KEY):
"""
Get the Meraki Organizations that the API KEY has access to.
:param MERAKI_API_KEY:
:return:
"""
url = '{}/organizations'.format(BASE_URL)
hdrs = {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Cisco-Meraki-API-Key": MERAKI_API_KEY
... | 5,310,846 |
def check_convergence(x):
""" Check for convergence of the sampler
"""
return False | 5,310,847 |
def get_repo_names(url: str = "users/dyvenia/repos") -> List[str]:
"""
Get public repositories names from Dyvenia.
Args:
url (str, optional): API url. Defaults to "users/dyvenia/repos".
Returns:
List[str]: List of repository names
"""
repos = requests.get(BASE_URL + url)
re... | 5,310,848 |
def split(
iterable: Iterable[T],
edges: Iterable[U],
cmp: Optional[Callable[[T, U], bool]] = None,
) -> Iterator[List[T]]:
"""Yield lists of items from ``iterable`` grouped by ``edges``
By default this function will insert a split before an item that is equal to an
edge but this can be adjuste... | 5,310,849 |
def get_pixar_usd_binaries_path():
"""
Returns binaries directory of Pixar USD library
:return: str
"""
pixar_usd_path = get_usd_path()
if not pixar_usd_path:
return
pixar_usd_bin_path = os.path.join(pixar_usd_path, 'bin')
if not os.path.isdir(pixar_usd_bin_path):
LOGGE... | 5,310,850 |
def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear',
preview=False):
"""
Make a thumbnail of image in *infile* with output filename *thumbfile*.
See :doc:`/gallery/misc/image_thumbnail_sgskip`.
Parameters
----------
infile : str or file-like
The... | 5,310,851 |
def where_op(condition, x, y):
"""Return a tensor of elements selected from either :attr:`x` or :attr:`y`, depending on :attr:`condition`.
If the element in condition is larger than 0,
it will take the `x` element, else it will take the `y` element
.. note::
The tensors :attr:`condition`, :at... | 5,310,852 |
def get_out_dir(key: str) -> str:
"""
Return the output directory
:param key: output product
"""
return OTD[key] | 5,310,853 |
def extract_features(smda_report, file_path):
"""
extract file features from given workspace
args:
smda_report (smda.common.SmdaReport): a SmdaReport
file_path: path to the input file
yields:
Tuple[Feature, VA]: a feature and its location.
"""
for file_handler in FILE_HANDLE... | 5,310,854 |
def jet_fire_api521(Tvessel):
"""
Incident heat flux of 100 kW/m2
"""
alpha = 0.75
e_flame = 0.33
e_surface = 0.75
h = 40
Tflame = 900 + 273.15
Tradiative = 1100 + 273.15
return stefan_boltzmann(alpha, e_flame, e_surface, h, Tflame, Tradiative, Tvessel) | 5,310,855 |
def ewma(values, window):
"""
Numpy-based implementation of EMA
"""
weights = np.exp(np.linspace(-1., 0., window))
weights /= weights.sum()
ema = np.convolve(weights, values)[window-1:-window+1]
return ema | 5,310,856 |
def prepare_loss_weights(
labels,
pos_cls_weight=1.0,
neg_cls_weight=1.0,
loss_norm_type=LossNormType.NormByNumPositives,
dtype=torch.float32,
):
"""get cls_weights and reg_weights from labels.
"""
cared = labels >= 0
# cared: [N, num_anchors]
positives = labels > 0
negatives... | 5,310,857 |
def upload_json_to_s3(paths: dict,
save_name: str,
selected_files: list):
"""Save json file to s3
Args:
paths (dict): dictionary of paths from yml file
save_name (str): name of json to be saved
selected_files (list): list of file paths to be st... | 5,310,858 |
def capture_output(
command: str, ip: Optional[str] = None, **kwargs
) -> ADBCommandResult:
"""
Execute an adb command on the given device and return the result
:param command: command to execute
:param ip: device id
:param kwargs: if contains the 'args' key, its value is passed as ... | 5,310,859 |
def _setup_logging():
""" Setup stdout logging for this script """
LOGGER.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # noqa: E501
handler.setFormatter(f... | 5,310,860 |
def run_stream_with_retcode(*cmd, **kwargs):
"""Runs a git command as context manager yielding stdout as a PIPE.
stderr is dropped to avoid races if the process outputs to both stdout and
stderr.
Raises subprocess2.CalledProcessError on nonzero return code.
"""
kwargs.setdefault('stderr', subprocess2.DEVN... | 5,310,861 |
def email_verified(form, field):
"""Check to see that the user's email address is confirmed."""
user = User.query.filter_by(email=field.data.lower()).first()
if not user.email_verified:
error = Markup("Email address not confirmed. Please "
"check your email.")
raise Va... | 5,310,862 |
def add_to_leftmost(branch, val):
"""adds value to the leftmost part of the branch and returns the modified branch and 0.
OR returns unchanged change and val if the val cannot be added"""
if val == 0:
return branch, val
if type(branch) is int:
return branch + val, 0
# add to children... | 5,310,863 |
def normalize_list_of_dict_into_dict(alist):
"""
Info is generated as a list of dict
objects with a single key.
@alist - the list in question.
@return - normalized dict with multiple keys
"""
result = {}
for element in alist:
for key in element.keys():
... | 5,310,864 |
def hashhex(s):
"""Returns a heximal formated SHA1 hash of the input string."""
h = hashlib.sha1()
h.update(s)
return h.hexdigest() | 5,310,865 |
def decripteaza(mesaj):
"""Funcția va primi un mesaj criptat folosind cifrul lui Caesar și
va încearca să îl decripteze.
"""
cnt = 0
lst = []
for char in mesaj:
if char.isalpha():
char = chr(ord('a') + (ord(char) - ord(mesaj[0])) % 26)
if cnt > 3 and mesaj[cnt-2] ... | 5,310,866 |
def move_streamlines(streamlines, output_space, input_space=None):
"""Applies a linear transformation, given by affine, to streamlines.
Parameters
----------
streamlines : sequence
A set of streamlines to be transformed.
output_space : array (4, 4)
An affine matrix describing the ta... | 5,310,867 |
def prerank(rnk, gene_sets, outdir='gseapy_out', pheno_pos='Pos', pheno_neg='Neg',
min_size=15, max_size=500, permutation_n=1000, weighted_score_type=1,
ascending=False, figsize=[6.5,6], format='pdf', graph_num=20, seed=None):
""" Run Gene Set Enrichment Analysis with pre-ranked correlation ... | 5,310,868 |
def get_args():
"""Get our arguments"""
parser = argparse.ArgumentParser()
parser.add_argument('filename', metavar='F', type=str, nargs=1,
help='File to load')
parser.add_argument('-a', '--annealing', action='store_true',
default=False,
... | 5,310,869 |
def read_results(folder, name):
"""
reads in cluster results
"""
tree_fname = os.path.join(folder, name + '.dg_01')
clu_fname = os.path.join(folder, name + '.dg_01.lab')
tree = np.loadtxt(tree_fname)
clu = np.loadtxt(clu_fname)
return clu, tree | 5,310,870 |
def save_mlf(file_name, mlf_dict, lab_ext='lab'):
"""
Load Master Label Files (MLF), e.g. applied in HTK toolkit or KALDI
file_name: file path to the MLF
mlf_dict: dictionary. {file_id: list_of_events}
lab_ext: extension of aligned files inside MLF file
"""
header = '#!MLF!#\n'
... | 5,310,871 |
def planets(id='', name=''):
"""
Return a planet.
Like: Hoth, Naboo, etc.
"""
response = Render.show(id, name, 'planets')
return response | 5,310,872 |
def literal(string):
"""
If `string` is a valid literal in NTriples syntax, return its value, lang tag and type.
Use `None` if there is no language tag or no datatype.
If `string` is not a valid literal return `None`.
"""
match = literal.pattern.match(string)
if not match:
return Non... | 5,310,873 |
def make_error_logger(name, level, filename):
"""
Création d'un Logger d'erreur
:param name: nom du logger
:param level: niveau de logging
:param filename: nom du fichier d'erreur
:return: logger
"""
formatter = logging.Formatter("%(asctime)s %(levelname)s - %(message)s",
... | 5,310,874 |
def generator(samples, batch_size=32):
"""
use generator to avoid large memory consumption
"""
num_samples = len(samples)
while 1: # Loop forever so the generator never terminates
sklearn.utils.shuffle(samples)
for offset in range(0, num_samples, batch_size):
batch_sample... | 5,310,875 |
def correlate(a, b, shift, demean=True, normalize=True, domain='freq'):
"""
Cross-correlation of signals a and b with specified maximal shift.
:type a: :class:`~numpy.ndarray`, :class:`~obspy.core.trace.Trace`
:param a: first signal
:type b: :class:`~numpy.ndarray`, :class:`~obspy.core.trace.Trace`... | 5,310,876 |
def transpose(a, perm=None, conjugate=False):
"""
Transposes a.
Parameters
----------
a : tensor
A Tensor.
perm : int
A permutation of the dimensions of a.
conjugate : bool
Setting it to True is mathematically equivalent to ms.math.conj(ms.transpose(input)).
Ret... | 5,310,877 |
def get_user_idle_time():
"""
Return the amount of time (in seconds) that the user is said to be idle.
This is normally obtained from a lack of keyboard and/or mouse input.
"""
if system == 'Windows':
return get_user_idle_time_windows()
elif system == 'Darwin':
return get_user_idle_time_mac()
raise NotImplem... | 5,310,878 |
def kwargs_from_config(
config: Dict[str, Any],
required_keys: Iterable[str],
optional_keys: Iterable[str],
renames: Optional[Iterable[Tuple[str, str]]] = None,
) -> Dict[str, Any]:
"""
Extract from a dictionary a dictionary with only those keys specified as required_keys or optional_keys.
K... | 5,310,879 |
def as_array(a, dtype=DEFAULT_FLOAT_DTYPE):
"""
Converts given :math:`a` variable to *ndarray* with given type.
Parameters
----------
a : object
Variable to convert.
dtype : object
Type to use for conversion.
Returns
-------
ndarray
:math:`a` variable conver... | 5,310,880 |
def round_filters(filters, global_params):
"""Round number of filters based on depth multiplier."""
multiplier = global_params.width_coefficient
divisor = global_params.depth_divisor
min_depth = global_params.min_depth
if not multiplier:
return filters
filters *= multiplier
min_dept... | 5,310,881 |
async def test_setup_component_and_test_service(hass):
"""Set up the demo platform and call service."""
calls = async_mock_service(hass, DOMAIN_MP, SERVICE_PLAY_MEDIA)
config = {
tts.DOMAIN: {"platform": "demo"},
media_player.DOMAIN: {"platform": "demo"},
notify.DOMAIN: {
... | 5,310,882 |
def equal_opportunity(confusion_matrix_list: List[np.ndarray],
tolerance: float = 0.2,
label_index: int = 0) -> np.ndarray:
"""
Checks for equal opportunity between all of the sub-populations.
This function checks if **true positive rate** difference of all group... | 5,310,883 |
def validate(integrations: Dict[str, Integration], config):
"""Handle dependencies for integrations."""
# check for non-existing dependencies
for integration in integrations.values():
if not integration.manifest:
continue
validate_dependencies(integration)
# check that ... | 5,310,884 |
def determine_qc_protocol(project):
"""
Determine the QC protocol for a project
Arguments:
project (AnalysisProject): project instance
Return:
String: QC protocol for the project
"""
# Standard protocols
if project.info.paired_end:
protocol = "standardPE"
else:
... | 5,310,885 |
def RunDeltaTest():
"""Runs delta testing between two different Predator revisions."""
argparser = argparse.ArgumentParser(
description=('Delta test is a script to report the differences between '
'analysis results of two local repo revisions. Local git '
'checkouts are u... | 5,310,886 |
def entitydata_list_url_query(viewname, kwargs, query_params, more_params):
"""
Helper function for generatinglist URLs
"""
list_url=reverse(viewname, kwargs=kwargs)
return uri_with_params(list_url, query_params, more_params) | 5,310,887 |
def _adaptive_order_weno3_robust(q,
i,
j,
recons,
keep_positive,
eps=1.0e-17,
c1=1.0,
c2=... | 5,310,888 |
def patch_and_fit_physio(time_series, replicates, patch=3, mask=None,
mode='gn', verbose=0):
"""Extract patches from an fMRI time + replicate series and fit parameters.
Parameters
----------
time_series : (replicates, *input_shape) tensor_like
fMRI time series.
repl... | 5,310,889 |
def verify_file_exists(file_name, file_location):
"""
Function to verify if a file exists
:type file_name: String
:param file_name: The name of file to check
:type file_location: String
:param file_location: The location of the file, derive from the os module
:rtype: Boolean
:return: r... | 5,310,890 |
def plot_cdfs(x, y, ccdf=False):
"""plot cumulative density functions for each column in x, based on
the classification specified in y.
Parameters
----------
x : DataFrame
the experiments to use in the cdfs
y : ndaray
the categorization for the data
ccdf : bool, optional
... | 5,310,891 |
def make_shell_context():
"""Pre-populate the shell environment when running run.py shell."""
return dict(app=keeper_app, db=db, models=models) | 5,310,892 |
def _MaybeClosing(fileobj):
"""Returns closing context manager, if given fileobj is not None.
If the given fileobj is none, return nullcontext.
"""
return (contextlib.closing if fileobj else NullContext)(fileobj) | 5,310,893 |
def get_project_page(pid, cache_directory=settings.CACHE_DIRECTORY):
"""Get a project page rendered in HTML given a project ID.
Args:
pid (int): project ID.
cache_directory (str): the directory where cached projects are stored.
Returns:
A string containing the HTML for ... | 5,310,894 |
def is_slot_bound(module, device, slot):
"""Checks whether a specific slot in a given device is bound to clevis.
Return: <boolean> <error>"""
_unused, err = get_jwe(module, device, slot)
if err:
return False, err
return True, None | 5,310,895 |
def get_model(model_path):
"""
downloads the model located in model_path.
"""
model_repo = Path(__file__).resolve().parent / "trained-models"
# if trained model is not already cloned
if not model_repo.exists():
url="https://github.com/neuronets/trained-models.git"
data... | 5,310,896 |
def to_matplotlib(img):
"""Returns a view of the image from Bob format to matplotlib format.
This function works with images, batches of images, videos, and higher
dimensional arrays that contain images.
Parameters
----------
img : numpy.ndarray
A N dimensional array containing an image... | 5,310,897 |
def scan_creditors(days, quit_early):
"""Start a process that garbage-collects inactive creditors.
The specified number of days determines the intended duration of a
single pass through the creditors table. If the number of days is
not specified, the value of the configuration variable
APP_CREDITOR... | 5,310,898 |
def test_gt_lt_ne_conditions(df, right):
"""
Test output for multiple conditions.
"""
filters = ["A", "B", "E", "Integers", "Numeric", "Dates"]
expected = (
df[["A", "B", "E"]]
.merge(right[["Integers", "Numeric", "Dates"]], how="cross")
.loc[
lambda df: df.A.gt(... | 5,310,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.