content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def Username(i, delegates, usernames):
"""
Returns delegates dictionary with username of delegate
from usernames.json file.
"""
name = delegates[i]['Name']
if name in usernames:
delegates[i]['Username'] = usernames[name]
else:
delegates[i]['Username'] = ('NEWBIE')
return... | 30de4899f391f0aad680d8699b05e8f29b2ba14c | 648,005 |
def one_dec_places(x, pos):
"""
Adds 1/10th decimal to plot ticks.
"""
return '%.1f' % x | bca037dc98da23694f0af43b05bc90829e65b327 | 648,006 |
def fortranindex (i,j,k,Nx,Ny,Nz):
"""x changes fastest"""
return i+j*Nx+k*Nx*Ny | 1356894b8445ef5ec51fe331c288ac3c578c0bec | 648,007 |
import sys
def main(func=None):
"""Main Decorator"""
def decorator(main_function):
if main_function.__module__ == '__main__':
returned = main_function()
try:
sys.exit(int(returned))
except (TypeError, ValueError):
sys.exit(0)
if c... | 5a61b18b2fad435aa87b410c83b179d3991e6f81 | 648,008 |
def st_dev_normalisation(compiled, sample_cols):
"""Standardize by dividing the peptide ratio for each concentration by the SD for this peptide overall"""
df = compiled.copy()
df[sample_cols] = (df[sample_cols].T / df[sample_cols].std(axis=1)).T
return df | 195fe0f89e58c3377c431eebf14d42aacf27f025 | 648,009 |
def calculate_fcc_nc(listA, listB):
"""
Calculates the fraction of common elements between two lists
not taking into account chain IDs. Much Slower.
"""
largest,smallest = sorted([listA, listB], key=len)
ncommon = len([ele for ele in largest if ele in smallest])
return (ncommon, ncommon... | 65dbe7ec21f96a827684be5cba22e64ff0416205 | 648,010 |
def fac(n):
"""Returns the factorial of n"""
if n < 2:
return 1
else:
return n * fac(n - 1) | 765a8147befe8cafd4633cf80369fffb467e7097 | 648,011 |
import os
def check_dirs(dirs) :
"""Returns absolute paths and raise exception if dir does not exist"""
absdirs = []
for d in dirs :
if not os.path.isdir(d) :
raise Exception("ERROR: {} is not found!".format(d))
else :
absdirs.append(os.path.abspath(d))
return a... | bbb7a95a1e5b6f43df15b2a7985cbda40280f36c | 648,012 |
def remove_blank_spaces(syllables) -> list:
"""Given a list of letters, remove any blank spaces or empty strings.
>>> remove_blank_spaces(['', 'a', ' ', 'b', ' ', 'c', ''])
['a', 'b', 'c']
"""
cleaned = []
for syl in syllables:
if syl == " " or syl == '':
pass
else:
... | 3cf83c5867fd002c09ac5f109744e6fd9c43a6da | 648,013 |
import argparse
import sys
def get_args():
"""
Get arguments.
@return: Arguments namespace.
@rtype: _AttributeHolder
"""
parser = argparse.ArgumentParser(
description='Make predictions based on trained/tested model.'
)
group = parser.add_mutually_exclusive_group()
group.... | 18111e84870b1df74cdec90a553a677cb2930dfe | 648,014 |
import math
def cosine(vector1, vector2):
"""
:param vector1:
:param vector2:
:return:
"""
dot = sum([a*b for a,b in zip(vector1, vector2)])
mag1 = math.sqrt(sum([a**2 for a in vector1]))
mag2 = math.sqrt(sum([a**2 for a in vector2]))
return round(dot/(mag1*mag2),3)*100 | 6b7a05565ce3c0479e04af9ef86807d42e0e8330 | 648,015 |
def get_widget_content(burl, nonavbar, funcname, noflexheight):
""" xxx """
box_content = ''
box_class = 'box'
box_vh = 'height:100vh;width:100vw;margin-left:-15px;'+\
'overflow-x:hidden;overflow-y:hidden;'
if nonavbar is None:
box_class = 'box-top'
box_vh = 'height:89vh;'
... | eabcb1da218380e1d7e3d6b97fe3cb2abaf1af5e | 648,017 |
from typing import Tuple
def format_numbers(nums: Tuple) -> str:
"""Format an array of numbers.
Parameters
----------
lst : Tuple
Array with numbers to be formatted
Returns
-------
str
String with number formatted
Example
-------
>>> format_numbers((2, 3, 10,... | 359c6fb72420d35b916965da25c9bbba77c05587 | 648,018 |
import json
def get_countries_metadata(fname="countries-readable.json"):
"""Read a database file containing information about different countries.
Specifically, we are interested in the capital and population of each country, because
we will use this information to disambiguate records, by giving more we... | 21caf95392ad61ac0db7c75c19ab4d12cccd7a53 | 648,020 |
def build_token_dict(vocab):
"""build bi-directional mapping between index and token"""
token_to_idx, idx_to_token = {}, {}
next_idx = 1
vocab_sorted = sorted(list(vocab)) # make sure it's the same order everytime
for token in vocab_sorted:
token_to_idx[token] = next_idx
idx_to_toke... | 5a9c5102ecbfefc1d7eda536353861a568de8924 | 648,021 |
import re
def get_config(input_image, no_data_config):
"""Read config json file for valid pixel value ranges per band and image type.
Args:
input_image (str): Name of the image file - must contain image type e.g. sentinel2, planet_4m.
no_data_config (dict): Config dictionary as found in json ... | 9d7d8e08be1a669a280959155c1f97fc4d688f9e | 648,022 |
def clean_text(txt):
"""Remove unnecessary spaces."""
return ' '.join(txt.strip().split()) | 41d62148588a65f7e480bdde8888679744a8f365 | 648,024 |
import sys
import os
def rel_path(relative_path: str) -> str:
"""Get path with a relative path, pyinstaller compatible."""
if hasattr(sys, '_MEIPASS'):
dir_path = getattr(sys, "_MEIPASS")
elif getattr(sys, 'frozen', False):
dir_path = os.path.dirname(sys.executable)
else:
dir_p... | a865e4215306dfc38583de878c52be77d7a922af | 648,025 |
from typing import Type
from typing import TypeVar
def is_type_var(annotation: Type) -> bool:
"""Returns True if the annotation is a TypeVar."""
return isinstance(annotation, TypeVar) | 58ed89427a65ea777ca0426a7090325e8dc6e930 | 648,026 |
def remove_prefix(text: str) -> str:
"""
Removes prefix of a text based on : sign.
"""
return text.split(":", maxsplit=1)[1] if ":" in text else text | 0b0e98cab6f7f22fe1481374ef43d3992a052623 | 648,027 |
def is_experiment_related(title):
"""Check if the title is experiment related."""
name = title.split(":")[1].lower()
long_keywords = [
"method",
"material",
"experimental"
# "materials and method",
# "methods and material",
# "experimental framework",
... | e865f52fb3f1683f106e40f2cf08ac74e6385638 | 648,028 |
import os
import sys
def get_script_dir():
"""Try to reliably get the directory of the current script."""
try:
return os.path.dirname(__file__)
except NameError:
return os.path.dirname(os.path.realpath(sys.argv[0])) | d24ea9b975a1b4b1e843a0e73466804d5022ea83 | 648,029 |
def is_magic_5gon_ring(elements):
"""
Return True if elements (10-vector) form a "magic" ring
"""
total = sum(elements[0:3])
return sum(elements[2:5]) == total and sum(elements[4:7]) == total \
and sum(elements[6:9]) == total and elements[1] + sum(elements[8:10]) == total | 43672432e2bbd93b8d8e97a3134848c321570934 | 648,030 |
def create_config(tmp_path):
"""Helper to create the config."""
def create_config(text):
test_file = tmp_path / "charmcraft.yaml"
test_file.write_text(text)
return tmp_path
return create_config | b182a205cfdd693f4c6bf93e31cd0b98e4da0ce6 | 648,032 |
import subprocess
def get_terminal_width():
""" -> #int width of the terminal window """
# http://www.brandonrubin.me/2014/03/18/python-snippet-get-terminal-width/
command = ['tput', 'cols']
try:
width = int(subprocess.check_output(command))
except OSError as e:
print(
... | 34ebe3968b394f4313113c2ae971f1ef63fe2895 | 648,033 |
import sys
def get_python_version():
"""Get a 3 element tuple with the python version"""
return sys.version_info[:3] | 1fa7879385ae26f9ef78b960ac652a500942fb35 | 648,034 |
def max_retention(frequencies):
"""Calculate the amount of seconds in a retention unit."""
sec_dict = {
'minute': 60,
'hourly': 3600,
'daily': 86400,
'weekly': 604800,
'monthly': 2592000,
'quarterly': 7776000,
'yearly': 31536000
}
secs = []
fo... | 88f0f9a36ff244fc134245765d1afd3b0143ea96 | 648,036 |
def _rad_fit_ ( data , model , *args , **kwargs ) :
""" fitting
>>> model = ...
>>> data = ...
>>> data.fitTo ( model , ... )
>>> data.Fit ( model , ... ) ## ditto
"""
return model.fitTo ( data , *args , **kwargs ) | 0031969e64c5531fffde7fe1eafd27a2285a1195 | 648,037 |
import argparse
def parseArgs():
"""
function to parse command line parameters
"""
# init argument parser object
prs = argparse.ArgumentParser(description='Convert dotbracket format to ct')
# add some options
prs.add_argument('infile', action='store', type=str,
help=... | 7eaa8c1c7906d414ea1c0340c03bc508cc08e2ed | 648,038 |
def get_flow(name):
"""Return flow implementation or None if not found"""
try:
return eval('{}.Flow'.format(name))
except NameError:
return None | ae1c2a6c613a65391f044df27b5645cc6d78bcbe | 648,039 |
import os
def get_safe_env(env=None):
"""Returns the environment "env" (or a copy of "os.environ" by default)
modified to avoid side-effects caused by user's ~/.gitconfig"""
if env is None:
env = os.environ.copy()
# On Windows it's not enough to set "HOME" to a non-existing
# directory. G... | 544a85b17b727114486d19224eb54adbf887ac1f | 648,040 |
def securitygroup_rules_preview(context, request, leftcol_width=3, rightcol_width=9):
""" Security group rules preview, used in Launch Instance and Create Launch Configuration wizards.
"""
return dict(
leftcol_width=leftcol_width,
rightcol_width=rightcol_width,
) | 6ffc1027ae2252959d2453fab26aad8821e26df8 | 648,041 |
def collapsed(cube, *args, **kwargs):
"""Collapses the cube with given arguments.
The cell methods of the output cube will match the cell methods
from the input cube. Any cell methods generated by the iris
collapsed method will not be retained.
Args:
cube (iris.cube.Cube):
A Cu... | 08ee8afe141a160c890850c399a8242b952e7345 | 648,042 |
def parse_requirements(filename):
""" load requirements from a pip requirements file """
lineiter = (line.strip() for line in open(filename))
return [
line
for line in lineiter
if line and not line.startswith("#") and not line.startswith('git+')
] | 838b05c9bc2238f8c420ba9bd9c834ddff0dd3d4 | 648,043 |
import csv
def load_csv(filename, label_col):
"""
Loads a csv file containin the data, parses it
and returns numpy arrays the containing the training
and testing data along with their labels.
:param filename: the filename
:return: tuple containing train, test data np arrays and labels
"""... | 30b4b6dcbeaa33fee40cdea81a063dbb3354eb16 | 648,044 |
def _build_payload(host_args, event, opts, index_extracted_fields):
"""
Construct the payload that will be posted to Splunk
"""
payload = {'host': host_args['fqdn'],
'index': opts['index'],
'sourcetype': opts['sourcetype'],
'event': event}
# Potentially ... | 744f765b4e6f8d6614e1ed707ead573717d2bd60 | 648,045 |
import numpy as np
def load_np(file_path):
"""
Loader for hypnograms stored in numpy arrays (npz, npy).
Returns:
np.ndarray of sleep stages
"""
arr = np.load(file_path)
if not isinstance(arr, np.ndarray):
# npz
keys = list(arr.keys())
assert len(keys) == 1
... | de0b16417905c9450858ff66f61ae2270f108fdd | 648,046 |
import requests
import json
def cas_2_smiles(cas):
"""
Args:
cas: string, cas number (xxx-yyy-zzz) Length is not fixed
Returns: string, smiles
"""
assert len(cas.split("-")) == 3 # check cas number
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/{cas}/json"
resp... | 7671d8633180a10c754fceb17f7ef2278aa52c44 | 648,047 |
def doi(record):
"""
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
doi = record.get('doi')
if doi is not None:
if 'link' not in record:
record['link'] = []
for item in record['link']:
if 'doi' in item:
... | 050033bb28b77f2cb433c2e79c4a817c111a3002 | 648,048 |
def split_event(line):
"""Splits a line into tokens divided by one or more spaces."""
tokens = list(filter(None, line.split(' '))) # split by whitespace
return (tokens[1], *tokens[-4:]) | bdd10ec191fa4cfe08e1be240c4ec00d9ba59a31 | 648,049 |
def parameter_substitutions_for_sample(
sample, labels, sample_id, relative_path_to_sample
):
"""
:param sample : The sample to do substitution for.
:param labels : The column labels of the sample.
:param sample_id : The merlin sample id for this sample.
:param relative_path_to_sample : The rela... | 6a049ffb4d292508b4fc25f871cc28dccc3a25db | 648,050 |
import torch
def soft_jaccard_score(
y_pred: torch.Tensor, y_true: torch.Tensor, smooth=0.0, eps=1e-7, dims=None
) -> torch.Tensor:
"""
:param y_pred:
:param y_true:
:param smooth:
:param eps:
:return:
Shape:
- Input: :math:`(N, NC, *)` where :math:`*` means
any n... | 20aab58a49054e2596ff8086da4e9eea12683494 | 648,051 |
def get_public_party_max_size() -> int:
"""get_public_party_max_size() -> int
(internal)
"""
return int() | 6f04dd60592da026670d5bba9aefa311c8a06e84 | 648,052 |
def get_dirty_items(item_list, flag_list):
"""
Returns each item in item_list where not flag in flag_list
Args:
item_list (list):
flag_list (list):
Returns:
dirty_items
"""
assert len(item_list) == len(flag_list)
dirty_items = [item for (item, flag) in zip(item_list... | a704cf40fb85edf5e49251eae7443127340a1c71 | 648,053 |
import argparse
def parseCmd():
"""Parse command line arguments
Returns:
dictionary: Dictionary with arguments
"""
parser = argparse.ArgumentParser(description='TSEBRA: Transcript Selector for BRAKER\n\n' \
+ 'TSEBRA combines gene predictions by selecing ' \
+ 'transcripts bas... | d14ef4475506d615fa496a703a63095cdea6ba48 | 648,054 |
import os
def overlapFilename(col, row, edge, tempDir):
"""
Return the filename used for the overlap array
"""
fname = '{}_{}_{}.npy'.format(edge, col, row)
return os.path.join(tempDir, fname) | a66184c6beeec7ac08f6867c70a6868cd0331c00 | 648,055 |
import re
def repair_email(email, exp = re.compile(r'\w+\.*\w+@\w+\.(\w+\.*)*\w+')):
"""
Given an email string, fix it
"""
s = exp.search(email)
if s is None:
return ""
elif s.group() is not None:
return s.group()
else:
return "" | f6865d4eb321799667ee0117ff36c885cc2d2b10 | 648,056 |
def natural_bounds(rank, nb_ingredients):
"""
Computes the upper and lower bounds of the proportion of an ingredient depending on its rank and the number of
ingredients in the product given that they are in decreasing proportion order.
Examples:
>>> natural_bounds(2, 4)
(0.0, 50.0)
... | b6f04bb039c38370da21ab6430fc24e92b7831fe | 648,058 |
def get_next_value(df, group, column):
"""Group by a column and return the next value of a column.
For example, group by customer and get the value of their next order.
Args:
df: Pandas DataFrame.
group: Column name to groupby
column: Column value to return.
Returns:
Or... | f228568f8b10aec6c874a848f936af05f1bce5bd | 648,059 |
import torch
def group_std(x: torch.Tensor, groups: int = 32, eps: float = 1e-5):
"""JIT-d helper to do group standard deviation."""
N, C, H, W = x.size()
x = x.view(N, groups, C // groups, H, W).contiguous()
var = torch.var(x, dim=(2, 3, 4), keepdim=True).expand_as(x)
return (var + eps).sqrt_().v... | 4c887564113225d57b9161f4eda77b13f2ec8551 | 648,060 |
def get_sequence(lines):
"""Returns sequence string.
"""
if lines:
seq_line = ''.join(lines)
seq = seq_line.split('(')[1].split(') def')[0].strip('\n\\')
else:
seq = ''
return seq | ab66a91571e3694fdd5e33ef31a59af191405fda | 648,061 |
def getEdition():
"""Returns the "edition" of the Vision client - "standard",
"limited", or "panel".
Returns:
str: The edition of the Vision module that is running the
client.
"""
return "standard" | 509ea1e04fe537bc37131382de92cef190c41324 | 648,062 |
def all_names(kp):
"""
:param kp: объект PyKeePass
:return:
"""
names = []
for index, item in enumerate(kp.entries):
names.append(f"{index + 1}. {item.title if item.title else ''}{' ' + item.url if item.url else ''}")
return names | d0e32d4840b8a50f407be4725e891c97b1515d20 | 648,063 |
def parse_sample_inf(args):
"""Parse sample informations and return as dictionary"""
sample_groups = {}
group_handle = open(args.info)
header = group_handle.readline()
for line in group_handle:
split_line = line[:-1].split('\t')
sample_groups[split_line[0]] = split_line[1]
groups... | 92e8d63f9756fba3062e3c0bd5abe1a940e7f4bc | 648,064 |
def rsub():
"""-: Right operand substract operator."""
class _Operand:
def __rsub__(self, other):
return "inferior to {}".format(other)
return 7 - _Operand() | 64438721d3b0a9fbb54f31d6b0a8cbce05c6681e | 648,065 |
def _is_float(value):
""" Check whether a value is a float or not.
"""
try:
value = float(value)
return True
except (TypeError, ValueError):
return False | a397182150797f1dda04b6db0803f7ad2e4f4c5e | 648,066 |
import binascii
def TruncatedHash(hash_ctor, trunc_octets):
"""Return a new hash type derived from the given hash_ctor type, truncated
to the given number of octets.
"""
def __init__(self, *args, **kwargs):
self._hstate = hash_ctor(*args, **kwargs)
def __getattr__(self, name):
ret... | f7c48e3f4317cab5a5231e582238c2c483175e0f | 648,067 |
import argparse
def build_arg_parser():
"""
Builds a standard argument parser with arguments for executing sample
setup script
-s, --testbed_setup
-t, --testbed_validate
-c, --testbed_cleanup
-o, --iso_cleanup
-e, --samples_setup
-r, --samples
-i, --samples_incremental
-l,... | 807e23d8e0fedd3a224d86afa30f2815f7455bf7 | 648,068 |
from typing import Dict
def merge_freqs(tfs1: Dict[str, int], tfs2: Dict[str, int]) -> Dict[str, int]:
"""
Merges term-frequencies from tfs1 and tfs2 dictionaries.
This is an inplace operation i.e. It updates the largest dictionary in the argument inplace
and returns that as result.
"""
# keep... | 5550d253697dfbaafcae1a3c8b9beb530ab99462 | 648,069 |
def dash_board_list_json_answer():
"""return list of dashboards (/api/search?limit=10&query=&tag=)"""
return """{"dashboards":[{"id":4,"title":"TyProd Storage","slug":"typrod-storage","tags":[],"isStarred":false},{"id":1,"title":"TyProd.oldJava","slug":"typrod-oldjava","tags":[],"isStarred":false},{"id":5,"titl... | 61f136f9af9230bba3acc2b2ae0d6fdd2f8b6920 | 648,070 |
import math
def classify_fixxation(eye_x, eye_y, d_time, treshhold):
"""
a function that classifies fixxations based on a threshhold in pixel per second
:param eye_x: an indexable datastructure with the x eye coordinates
:param eye_y: an indexable datastructure with the y eye coor... | 2e2c3cdf6c746eaeb921f7300e5e7c255f9f8f48 | 648,071 |
def extract_end_bits(num_bits, pixel):
"""
Extracts the last num_bits bits of each value of a given pixel.
example for BW pixel:
num_bits = 5
pixel = 214
214 in binary is 11010110.
The last 5 bits of 11010110 are 10110.
^^^^^
The inte... | 470d57ad81431ed59e682e133e561603ff6fe1d8 | 648,072 |
import codecs
import json
def load(path):
"""Loads a single Zeppelin notebook. For now just a wrapper around json.load"""
with codecs.open(path, mode="r", encoding="UTF-8") as fr:
try:
return json.load(fr)
except json.JSONDecodeError:
return {} | b88ee6454dc603d6b324a91f879dc167e433f442 | 648,073 |
import math
def isSend(Keypoints):
"""Three points on one line
Args:
Keypoints :Three points
"""
a_2 =(Keypoints[0][0] - Keypoints[1][0])**2 + (Keypoints[0][1] - Keypoints[1][1])**2
b_2 =(Keypoints[1][0] - Keypoints[2][0])**2 + (Keypoints[1][1] - Keypoints[2][1])**2
c_2 =(Keypoints[0]... | ad921884f7adf88c23e343c897e1d3bd30ffa0d0 | 648,074 |
from typing import List
def find_positions(arr: List[str],
mask: List[bool]) -> List[int]:
"""Set positions and tokens.
Args:
tokens: List of tokens and untokens.
mask: Mask for tokens.
Returns:
List of positions of tokens.
"""
pos... | d89a8ab51c4437c55c666b3670f9e09a13e478a5 | 648,075 |
def unpack_fraction(num: str) -> str:
"""Returns unpacked fraction string 5/2 -> 2 1/2"""
numbers = [int(n) for n in num.split("/") if n]
if not (len(numbers) == 2 and numbers[0] > numbers[1]):
return num
numerator, denominator = numbers
over = numerator // denominator
rem = numerator % ... | f79ed174669f184974728a245d3f120b93a02c14 | 648,076 |
import os
def getSasUutClaimedPpaBoundaryFilePath(config_filename):
"""Get the absolute file path SAS UUT claimed PPA boundary to be stored.
Args:
config_filename: The absolute file path of the configuration file used in PCR.1 test.
It is required to differentiate SAS UUT claimed PPA boundary stored as... | b11e83bda2edd287eafbd80760e97badc5614ab1 | 648,077 |
def _get_val(v):
"""get val from a function or a value"""
if callable(v):
return v()
return v | 1017cf4e7026cd5fb0da0a90aa63e48aec2c26da | 648,078 |
def create_json(tmp_intent_list):
"""
| create json document
|
| Args:
| tmp_intent_list(list): list of intents
|
| Returns:
| new_intent(dict): json dict
"""
outputs = {}
new_intent = {}
for lines in tmp_intent_list:
for line in lines[0:]:
... | daae57f93d3223e9d376ff5df45f0793417fb7e6 | 648,079 |
import json
def get_history_compile_info():
"""获取历史编译信息"""
try:
with open('compile_info', 'r') as f:
result = json.load(f)
except:
result = {
'plat': '',
'arch': '',
'mode': '',
'py_version': 0,
'boost_root': '',
... | ef0aba5f0c70c0306a558b5feb486b7f8e50a5e1 | 648,081 |
import functools
def cache(user_function):
""" simple polyfill for python < 3.9 """
return functools.lru_cache(maxsize=None)(user_function) | 7309f72790dca67de1c3d1ca79aed3dae7e95fd7 | 648,082 |
def get_attributes_display_map(obj, attributes):
"""Returns attributes associated with an object,
as dict of Attribute: AttributeValue values.
Args:
attributes: Attribute Iterable
"""
display_map = {}
for attribute in attributes:
value = obj.attributes.get(str(attribute.pk))
... | c3fb73bb2163c0b896e363d4697939639b502b5d | 648,083 |
import json
def search_for_game_id(game_name: str):
"""
Searches all_games_data.json file for occurences of game_name phrase, and saves findings to
found_games_data.json file.
:param game_name: string containing name of the game
:return: list containing found games as well as their id's
"""
... | 670bd8844afb879878c7dd498300ca78f9fc3e3b | 648,084 |
import json
def Append_dataset(inputDeviceIds, inputDates, inputDatasetName, inputDbName):
"""
Append dataset.json file with user inputs
"""
output = {}
#get deviceIds and dates as array from user inputs
deviceIds = inputDeviceIds.split(",")
dates = inputDates.split(",")
#create data... | 6e56ddbf7e0a7ca0f89a85bb84f48bd48f578f98 | 648,085 |
def valid_image_array(image_array):
"""
Returns `True` if and image array is valid.
An image array is valid if it is in grayscale (having 2 dimensions) or in color
(having 3 dimensions)
:param image_array: Image as an array
:type image_array: :class:`~numpy:numpy.ndarray`
:return: Returns `... | f2f0b22f750c4bc0cd42fdb951dd839f0c02eebd | 648,086 |
def run_mgmt_command(capsys):
"""Function fixture that runs a python manage.py with arguments
and returns the stdout and stderr as a tuple.
"""
def f(cmd_class, argv=None):
argv = argv or []
cmd = cmd_class()
cmd.run_from_argv(["manage.py"] + argv)
out, err = capsys.read... | 52d1b2e4bc438bbc5df28224e434d6c4d98784b4 | 648,087 |
def matrix_to_images(data_matrix, mask):
"""
Unmasks rows of a matrix and writes as images
ANTsR function: `matrixToImages`
Arguments
---------
data_matrix : numpy.ndarray
each row corresponds to an image
array should have number of columns equal to non-zero voxels in the mask
... | d07a356fb22bf6f5a87074906c9d7c8053e29002 | 648,088 |
def generate_config(context):
""" Entry point for the deployment resources. """
resources = []
managed_zone_name = context.properties.get('zoneName')
dnsname = context.properties['dnsName']
managed_zone_description = context.properties['description']
name_servers = '$(ref.' + context.env['name... | 30dd067ac48728fce7967de0b616ce7f3996fcf2 | 648,089 |
def filter_events(events, version_label=None, request_id=None, env_name=None):
"""
Method filters events by their version_label, request_id, or env_name if supplied,
or any combination if multiple are specified.
:param events: A list of `events` returned by the `DescribeEvents` API
:param version_l... | 8338d7f93b1b36eb1561de7d6dead358aab7acef | 648,090 |
def counter_to_dict(counter):
"""
Converts counter to dictionary, also replaces the numpy value to an int
"""
dic = {}
for key, value in counter.items():
dic[key] = int(value)
return dic | d9df8c98937c1e0c984662fabcb649e7aca3a69f | 648,091 |
def monster_in_cutout(monster, cutout):
"""
Return True if monster is in cutout.
"""
for i_monster, char_monster in enumerate(monster):
if char_monster == "#" and cutout[i_monster] == ".":
return False
else:
return True | e98875e097e174d5b2555fb29f87666096edb3b4 | 648,093 |
import os
def make_data_files_absolute(data_files, prefix):
"""Using setuptools data files are put under the egg install directory
if the datafiles are relative paths. We don't want this. Data files
like man pages, documentation, templates etc. should be installed
in a directory outside of th... | 510376fd91d52610dc4b87c680bf790a20e50519 | 648,094 |
def minimal_json42():
"""Minimal valid JSON for DataCite 4.2."""
return {
'identifier': {
'identifierType': 'DOI',
'identifier': '10.1234/foo.bar',
},
'creators': [
{'name': 'Nielsen, Lars Holm'},
],
'titles': [
{'title': 'M... | 2b78cd76aabf039bf0beaa8ba6c75ed96ba07763 | 648,095 |
def _query_single_line(query):
"""Reformats a query string to remove newlines and extra spaces
:param query: The query to log. This will work for anything that will
result in a string after str() is applied to it. Be aware of this
conversion. E.g. sqlalchemy's TextClause objects.
"""
re... | 5ccd3b589887d43d1ecf6e7fecf288bdd92cd96b | 648,096 |
def slack_escape(text):
"""
Escapes special characters for Slack API.
https://api.slack.com/docs/message-formatting#how_to_escape_characters
"""
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
return text | 9d3d6bc86894f69365973394d0037bdd3eb23ece | 648,097 |
import random
import math
def random_erasing(img,mean = [0.4914, 0.4822, 0.4465],sl = 0.02,sh = 0.4,r1 = 0.3):
"""sl: min erasing area
sh: max erasing area
r1: min aspect ratio
mean: erasing value"""
img = img.copy()
for attempt in range(100):
area = img.shape[0] * img.shape[1]... | 5324b9721ba8c1b4280937ca619073f8c44506f4 | 648,098 |
from collections import Counter
def _get_majority_class(y):
"""Get the majority class.
Note that if two or more classes have the same occurrences, one of them is returned arbitrarily.
"""
mc = Counter(y).most_common()
return mc[0][0] | c95f31fac5701c95eeef7714f025ba9ce6bd0bc2 | 648,099 |
def format_alignment (query, subject, q_start, q_end, s_start, s_end, hsp_match, sub_start_end_in_pdb, html=False):
"""
'GAIAAIMQKG'
'WDEFAKGAVRAIMQAG'
7 16 1 10
<pre>
"""
# query = 'GAIAAIMQKG'
# subject = 'WDEFAKGAVRAIMQAG'
# q_start, q_end, s_start, s_end = 1, 10, 7, 16,
# h... | be0ca7fdafe18f5fc5fead2d34c0e9ab4ca1af8a | 648,100 |
def custom_validator(language, inputs, options, attrs, md):
"""Custom validator."""
okay = True
for k in inputs.keys():
if k != 'opt':
okay = False
break
if okay:
if inputs['opt'] != "A":
okay = False
else:
options['opt'] = inputs[... | cca95c3fb0f093373934f33256dca88a5f361ad0 | 648,101 |
def parse_sha256sum_file(filename):
"""
Takes a SHA256 checksum file and returns the values as a dict
:param filename: The file with SHA256 checksums
:return Mapping: Check sums from file
"""
with open(filename, 'r') as file:
string = file.read()
string = string.rstrip()
# Parse... | cc7e4a5df45d14ad5411a6d013dd407d06c0f4e6 | 648,103 |
import os
def fixture_file():
"""
This fixture return a path to the test fixture file.
"""
return os.path.join(
'settings',
'basic',
'fixture_to_include.py',
) | 9de119cf3c70bddd4d6fd15481bc8b8964f5eb15 | 648,104 |
import time
import calendar
def isodate(now=int(time.time()), utc=False, short=False):
"""
This function converts seconds since epoch into ISO 8601 timestamp
"""
if utc:
my_time_u = time.gmtime(now)
if short:
return time.strftime("%Y%m%dT%H%M%SZ", my_time_u)
else:
... | c13d81a71110c7d9e231fa883142a305e78dbe97 | 648,105 |
import random
def freq_sample(freq: float, sample: float):
"""
Down or up sample a frequency based on a sample size. Sub unit frequencies are
rounded probabalistically.
:param freq: pre sampled frequency (integer)
:param sample: sample size (float)
:return: new frequency (integer)
"""
... | e7b894a66ec9c5e980055190563e0bab5286594e | 648,106 |
def chopnetOutputNode(chopnet):
"""Returns the chopnode inside the given chopnet that currently has its display flag set"""
for n in chopnet.children():
if n.isAudioFlagSet():
return n | a5b0d05d6b0daab6f700006fe5ef9dcb377ac4cc | 648,107 |
def paginate(page_size: int, *contents) -> list:
"""Break the contents into pages to fit a Discord message."""
contents = list(contents)
pages = []
if isinstance(contents[0], str):
page = contents.pop(0)
for item in contents:
if len(page) >= page_size:
pages.... | 747835b23dd73272161bcd734a9b342733c9f64d | 648,108 |
import os
import sys
def read_samplesheet(samplesheet_path):
"""
Read Samplesheet.csv and extract relevant information.
Assumes Samplesheet has preset header, and no lines are present past [data]
line.
Returns a dictionry (Assumes unique Sample_Name)
{sample_Name: sample_ID}
"""
# Ch... | 7f6c04d03b12733cd2e52a5436ef498290335f4e | 648,109 |
import uuid
def as_uuid(key: str) -> str:
""" Turn the given key into a uuid version 3. """
return str(uuid.uuid3(uuid.NAMESPACE_DNS, key)) | d770b41631fad272923e5f647cbb4cc95a602c77 | 648,110 |
def check_citation_type(citation, violation_description):
"""A helper function used in filter_citations_by_type to extract the citation by desciprtion.
"""
#### EXERCISE: Implement boolean conditional checking against violation_description here
if citation['Violation Description']:
return citat... | 4c04483fd9d49703929087518dd755a4f73bf4af | 648,112 |
def test_user(user_num):
"""Pre-defined user variables for testing purposes"""
users = {
"1": (5, "", 3, True, True, True, True, True),
"2": (0, "", 3, False, False, False, False, False),
"3": (2, "", 4, True, True, False, False, True),
"4": (1, "", 5, False, False, True, True, F... | b98d0fea48a1bb96a14c46528ee0754dd90f7d0e | 648,113 |
def ensure_tuple_size(tup, dim):
"""Returns a copy of `tup` with `dim` values by either shortened or padded with zeros as necessary."""
tup = tuple(tup) + (0,) * dim
return tup[:dim] | bcabaebbac248bfaee4daad5c6ac1f35fc7572a6 | 648,114 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.