content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def postprocess(output, length_1, length_2):
"""Post process the output of the inferred alignment."""
score, paths, sw_params = tf.nest.map_structure(
functools.partial(tf.squeeze, axis=0), output)
# Stacks SW params, flipping sign of gap penalties for convenience.
substitution_scores, gap_open, gap_exten... | 5,287,900 |
def test_stackedblocks_with_params():
"""
Test StackedBlocks when all layers have trainable params
"""
aes = [Autoencoder(100, 50, 'tanh', 'tanh'),
Autoencoder(50, 10, 'tanh', 'tanh')]
sb = StackedBlocks(aes)
_params = set([p for l in sb._layers for p in l._params])
assert sb._p... | 5,287,901 |
def cli():
"""命令集"""
pass | 5,287,902 |
def select_random_word() -> str:
"""Selects a random word from the lexicon."""
next_word = lexicon.sample(RandomWordSelectStrategy())
print(f"Chose: {next_word}!")
return next_word | 5,287,903 |
def edit_profile(request, username=None):
"""Edit user profile."""
# If a username is specified, we are editing somebody else's profile.
user = None
if username:
username = username.replace(" ", "+")
if username != request.user.username:
try:
user = User.obje... | 5,287,904 |
def split_at_pattern(text, pattern):
"""
Split a string where a pattern begins
"""
obj = regex.search(pattern, text)
if obj:
start = obj.start()
return text[0:start], text[start:]
else:
return text, "" | 5,287,905 |
def store_deepdeps(roots:List[Ref])->List[Ref]:
""" Return an exhaustive list of dependencies for the `roots` references.
References themselves are also included """
frontier=set(roots)
processed=set()
while frontier:
ref = frontier.get() #FIXME
processed.add(ref)
for dep in store_deps(ref):
... | 5,287,906 |
def focal_lossIII(prediction_tensor,
target_tensor,
weights,
gamma=2.,
epsilon=0.00001,
):
"""Compute loss function.
This function was adapted from the Tensorflow issues section on GitHub.
Args:
prediction_tens... | 5,287,907 |
def grouper(iterable: Iterable[_T], n: int) -> Generator[Iterable[_T], None, None]:
"""
given a iterable, yield that iterable back in chunks of size n. last item will be any size.
"""
for i in range(math.ceil(len(iterable) / n)):
yield iterable[i * n : i * n + n] | 5,287,908 |
def stack_lag_h5_maker(f, f2, buffer=2, shift_to_the_right_by=0):
"""
Parameters
----------
f : h5 file with SINGLE FRAMES this is ment to be a test program. if used long term I will change this part
f2 :
buffer :
shift_to_the_right_by :
Returns
-------
"""
h5c = image_too... | 5,287,909 |
def draw_vertical_bar(info:pd.Series)->plt.Figure:
"""Dibuja un vertical bar chart basado en un analisis previamente hecho
Args:
info (pd.Series): Los datos a graficar
Returns:
[plt.Figure]: La figura armada
"""
plt.bar(info.index, height=info)
return plt.gcf() | 5,287,910 |
def bash_live(
command: str,
cwd: str = None,
exception: Type[Exception] = Exception,
prefix: str = "",
logfile = None
) -> None:
"""Run a command in bash shell in live mode to fetch output when it is available
:param command: the command to run
:param cwd: directory where to run the command (defaults to curren... | 5,287,911 |
def set_seed_iftrue(condition, seed=10):
"""
Fix the seed for random test.
Parameters
----------
seed : int
Random seed passed to np.random.seed
Returns
-------
decorator : function
Decorator which, when applied to a function, sets the
random seed before running t... | 5,287,912 |
def get_current_utc_time():
"""Return string representation of current time in UTC."""
utcnow = datetime.datetime.utcnow()
return str(utcnow.timestamp()) | 5,287,913 |
def _split_extension_test(ctx):
"""Unit tests for paths.split_extension."""
env = unittest.begin(ctx)
# Try some degenerate cases.
asserts.equals(env, ("", ""), paths.split_extension(""))
asserts.equals(env, ("/", ""), paths.split_extension("/"))
asserts.equals(env, ("foo", ""), paths.split_ext... | 5,287,914 |
def get_cluster_details():
"""
Gets the credentials from the config file
"""
config = configparser.ConfigParser()
config.read_file(open('dwh.cfg'))
KEY = config.get('AWS','KEY')
SECRET = config.get('AWS','SECRET')
DWH_CLUSTER_TYPE = config.g... | 5,287,915 |
def get_publication_comments(project, publication_id):
"""
List all comments for the given publication
"""
connection = db_engine.connect()
publications = get_table("publication")
publication_comments = get_table("publication_comment")
statement = select([publications.c.publication_comment_i... | 5,287,916 |
def parse_genapp_customer(genapp_record: Dict) -> Optional[X12Demographics]:
"""
Parses a GenApp Customer from a JSON response to a X12Demographics model
:param genapp_record: The GenApp Customer record
:return: The X12Demographics model for the customer record
"""
no_match_found = genapp_record... | 5,287,917 |
def test_mlflow_metrics_dataset_saved_and_logged(tmp_path, tracking_uri, data, prefix):
"""Check if MlflowMetricsDataSet can be saved in catalog when filepath is given,
and if logged in mlflow.
"""
mlflow.set_tracking_uri(tracking_uri.as_uri())
mlflow_client = MlflowClient(tracking_uri=tracking_uri.... | 5,287,918 |
def download_and_install(args: argparse.Namespace, url: str):
"""Download the asset and install it
Args:
args (Namespace): CLI arguments
url (str): The asset download URL"""
with tempfile.TemporaryFile() as zip_file_w:
download_to_file(zip_file_w, url)
with zipfile.ZipFile(zip_file_w, mode="r") a... | 5,287,919 |
def cons (l,v):
"""
Add the value :code:`v` at the begining of the list :code:`l`.
:param l: The list, possibly empty.
:type l: dict
:param v: The value to be added.
:type v: Any
UC: not compatible with iterators
"""
if l["head"] == None:
l["head"] = l["tail"] = __new_cell ... | 5,287,920 |
def configure_master():
"""
Configures the master node after rpm install
"""
common.setup_user()
common.setup_common_configurations()
__setup_master_specific_conf_files()
__setup_hawq_user_profile()
__create_local_dirs() | 5,287,921 |
def assert_(val: bool, msg: Literal["1.5.1"]):
"""
usage.scipy: 1
"""
... | 5,287,922 |
def make_dirs(directory: Union[str, Path], mode: int = 0o777) -> bool:
"""Wrapper around os.makedirs to make it suitable for using
in a multithreaded/multiprocessing enviroment: Unlike the
regular function, this wrapper does not throw an exception if
the directory already exists, which may happen if ano... | 5,287,923 |
def get_best_shift(img):
"""
DESCRIPTION: Calculate the center of mass of the input image
and return the best shift amount to center an image on the character.
INPUT: Image
OUTPUT: Calculated shift amount for x and y directions
"""
# Calculate the center of mass through scipy
center_y, c... | 5,287,924 |
def patch_copyfile():
"""
Used to monkey patch shutil.copyfile()
"""
if shutil.copyfile != copyfile:
shutil._orig_copyfile = shutil.copyfile
shutil.copyfile = copyfile | 5,287,925 |
def main():
"""
The main function to execute upon call.
Returns
-------
int
returns integer 0 for safe executions.
"""
print("Program to check positive, negative, or zero input.")
temp = check_number_sign()
return 0 | 5,287,926 |
def read_openPMD_params( filename ):
"""
Extract the time and some openPMD parameters from a file
Parameter
---------
filename: string
The path to the file from which parameters should be extracted
Returns
-------
A tuple with:
- A float corresponding to the time of this it... | 5,287,927 |
def save_pcap_task(files, save_dir, session_threshold):
"""
This method takes all files in a list (full path names) and uses the method save_pcap that converts a pcap to h5 format
:param files:
:param session_threshold:
:return:
"""
for fullname in files:
print('Currently saving file... | 5,287,928 |
def class_to_val(raw_scores):
"""
Finds the highest softmax for each class
:param raw_scores: tensor (batch, verts, classes)
:return: highest class (batch, verts)
"""
cls = torch.argmax(raw_scores, dim=2)
val = (cls + 0.5) / DEEPCONTACT_NUM_BINS
return val | 5,287,929 |
def map_arg(**maps):
"""
Apply a mapping on certains argument before calling the original function.
Args:
maps (dict): {key: map_func}
"""
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
argmap = inspect.getcallargs(func, *args, **kwargs)
... | 5,287,930 |
def installIfNeeded(moduleName, nameOnPip=None, notes="", log=print):
""" Installs a Python library using pip, if it isn't already installed. """
from pkgutil import iter_modules
# Check if the module is installed
if moduleName not in [tuple_[1] for tuple_ in iter_modules()]:
log("Installing " ... | 5,287,931 |
def test_can_load_established_ontologies(ontology_uri):
"""
Test that we can load some commonly used ontologies.
"""
ontology = Ontology.load(ontology_uri)
assert_that(ontology.__terms__, is_not(empty())) | 5,287,932 |
def create_spark_session():
"""Create an apache spark session on AWS"""
spark = SparkSession \
.builder \
.config("spark.jars.packages", "org.apache.hadoop:hadoop-aws:2.7.0") \
.getOrCreate()
return spark | 5,287,933 |
def evaluate(model, dataset):
""" Evaluates model on all dataset images. Assumes all images have corresponding pose labels.
"""
loc_err_acc = []
loc_encoded_err_acc = []
ori_err_acc = []
ori_encoded_err_acc = []
distances_acc = []
esa_scores_acc = []
# Variance used only for prob. ... | 5,287,934 |
def clean_catalog(ukidss_catalog, clean_band='K_1', badclass=-9999,
maxerrbits=41, minerrbits=0, maxpperrbits=60):
"""
Attempt to remove 'bad' entries in a catalog.
Parameters
----------
ukidss_catalog : `~astropy.io.fits.BinTableHDU`
A FITS binary table instance from the ... | 5,287,935 |
def setmask(arr, x1=None, x2=None):
"""setmask(arr, x1, x2)
arr = 1D arr
x1 = lower value
x2 = upper value
by default it returns a mask that
is the full range of arr
returns
=======
mask, x1, x2
if input x1 and x2 are out of bounds
then it sets x1 and x2 to the boundry of arr... | 5,287,936 |
def test_ensure_config(configuration):
"""This is just to make sure the autouse fixture is doing what I expect."""
assert get_configuration() == configuration | 5,287,937 |
def test_local_normalized_cross_correlation():
"""
Testing computed local normalized cross correlation function between images using image.local_normalized_cross_correlation by comparing to precomputed.
"""
tensor_true = np.array(range(24)).reshape((2, 1, 2, 3, 2))
tensor_pred = 0.6 * np.ones((2, 1,... | 5,287,938 |
def get_tree(splits):
"""Convert a dict keyed by splits into the equivalent tree.
The dict values should be dicts appropriate for the params input to
TreeBuilder.create_edge.
"""
Edge = TreeBuilder().create_edge
# Create a star from the tips
tips = []
the_rest = []
for split, params... | 5,287,939 |
def create_hash(secret: str, url: str) -> str:
"""Create a hash of the secret and url."""
s = f'{secret}{url}'
return str(hashlib.md5(s.encode()).hexdigest()[0:8]) | 5,287,940 |
def load_defaults(db):
"""
Adds default jurisdiction types:
* control_group
* tier
* cluster
Adds default configuration for each of the three jurisdiction types
Adds default userdata templates
"""
pd = PROVISIONER_DEFAULTS
# jurisdiction types
for jt in PROVISIONER_DEF... | 5,287,941 |
def check_pii_annotations_yml(repo_path, all_results):
"""
TODO(jinder)
"""
all_results[module_dict_key][".pii_annotations.yml"] = file_exists(
repo_path, ".pii_annotations.yml"
) | 5,287,942 |
def get_model_name(model):
"""Obtains the model name for a Scikit-Learn, ML Studio estimator
Obtains the model name for Scikit-Learn estimators, ML Studio estimators,
and GridSearchCV and RandomSearchCV objects
Parameters
----------
model : BaseEstimator, GridSearchCV, RandomSearchCV
... | 5,287,943 |
def create_script_to_chars():
"""Returns a mapping from script to defined characters, based on script and
extensions, for all scripts."""
load_data()
result = collections.defaultdict(set)
for cp in _defined_characters:
if cp in _script_data:
result[_script_data[cp]].add(cp)
... | 5,287,944 |
def get_filter():
"""
Вывод товаров на странице каталогов
:return: context
"""
price = dict()
seller = Seller.objects.values('title', 'title_en').all()
price['max'] = math.ceil(seller.aggregate(max=Max('catalog__price')).get('max'))
price['min'] = math.floor(seller.aggregate(min=Min('ca... | 5,287,945 |
def email_weekly_orders_csv(current_menu_meal_totals):
"""
Emails all the current admins an email containing every users current order.
Email contains a csv file as well.
Returns total emails sent and the email for every admin.
"""
all_orders = get_all_users_orders()
user_login_url = get_log... | 5,287,946 |
def ConvTranspose(out_chan: int,
filter_shape: Sequence[int],
strides: Optional[Sequence[int]] = None,
padding: str = Padding.VALID.name,
W_std: float = 1.0,
b_std: Optional[float] = None,
dimension_numbers: Opti... | 5,287,947 |
def wait_for_result_is_none(method, timeout, wait_msg=None):
"""Calls the method until the return value is None."""
count = 0
end_time = time.time() + timeout
while True:
try:
result = method()
if result is None:
return True
except:
pa... | 5,287,948 |
def restoreLastState():
"""
Restores the most recently pushed clipboard state, but does not
remove it from the archive stack. Replaces current clipboard contents.
Returns nothing. Stack must not be empty.
"""
# Preconditions:
assert( len( _archiveStack ) > 0 )
state = _archiv... | 5,287,949 |
def connect(db_uri):
"""Connect to a database to record deployments.
:param db_uri: Database URI to connect to
:return: SQLAlchemy session for interacting with this database
"""
engine = create_engine(db_uri, convert_unicode=True)
session = scoped_session(sessionmaker(autocommit=False, autoflus... | 5,287,950 |
def final_run_could_be_extended(values, end_idx):
"""Heuristically see if the value run at end_idx could be extended
Returns true if there is a run at end_idx, if end_idx is not the last
value, and if the value after end_idx could be part of a run.
To keep this constant-time, we aren't checking if the... | 5,287,951 |
def request_nodes_http(url: str) -> None:
"""Request the status over HTTP
:param url: the base URL
"""
nodes = HttpClient(url).request_cluster_hw_status()
rows = []
for node in nodes:
for gpu in node['gpus']:
rows.append(_gpu2row(gpu, node['host']))
print_table(rows) | 5,287,952 |
def merge_filename(filename, pat, sep):
"""
Apply a merging pattern to a filename.
Sections of the base filename are kept according to the provided pattern.
Args:
filename: The filename to merge.
pat: The merging pattern to use.
sep: String separating filename sections.
Re... | 5,287,953 |
def test_parse_user_data_raise_missing_variable() -> None:
"""Test parse_user_data."""
with pytest.raises(MissingVariable):
parse_user_data({"name": "tom"}, "name: ${name}, last: $last and $$", "test") | 5,287,954 |
async def fetch_geoloc_web(ip: IPAddress) -> Optional[Geolocation]:
"""Fetch geolocation data based on ip (using ip-api)."""
url = f"http://ip-api.com/line/{ip}"
async with http.get(url) as resp:
if not resp or resp.status != 200:
log("Failed to get geoloc data: request failed.", Ansi.L... | 5,287,955 |
def task_query(job_key=None, hosts=None, job_keys=None):
"""Creates TaskQuery optionally scoped by a job(s) or hosts.
Arguments:
job_key -- AuroraJobKey to scope the query by.
hosts -- list of hostnames to scope the query by.
job_keys -- list of AuroraJobKeys to scope the query by.
"""
return TaskQuery(
... | 5,287,956 |
def reset_selection():
"""Deselect all selected nodes
"""
clear_selection_recursive() | 5,287,957 |
def previous_scheduled_day(date, first_trading_day, is_scheduled_day_hook):
"""
Returns the previous session date in the calendar before the provided date.
Parameters
----------
date : Timestamp
The date whose previous date is needed.
Returns
-------
Timestamp
The previ... | 5,287,958 |
def preorder_elements(t):
"""通过生成器遍历二叉树,先根序遍历"""
stack = []
while t is not None or stack:
while t is not None:
yield t.data
stack.append(t.right)
t = t.left
t = stack.pop() | 5,287,959 |
def measure_distance_euclidean(point1, point2):
"""Return euclidean distance between two shapely Points as float."""
if (type(point1) != Point) or (type(point2) != Point):
raise TypeError("Only Points are supported as arguments, got {} and {}".format(point1, point2))
return point1.distance(point2) | 5,287,960 |
def bootstrap(app_id, service_name):
"""
# generate a demo app
"""
from rest_arch import __version__
app_slug = package_name = app_id.split('.')[1]
mapping = dict(app_id=app_id,
service=service_name,
package=package_name,
app_slug=app_slug... | 5,287,961 |
def _unpack_asf_image(data):
"""Unpack image data from a WM/Picture tag. Return a tuple
containing the MIME type, the raw image data, a type indicator, and
the image's description.
This function is treated as "untrusted" and could throw all manner
of exceptions (out-of-bounds, etc.). We should clea... | 5,287,962 |
def dicenet_w3d2(**kwargs):
"""
DiCENet x1.5 model from 'DiCENet: Dimension-wise Convolutions for Efficient Networks,'
https://arxiv.org/abs/1906.03516.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.... | 5,287,963 |
def patch_vertices(vertices,pole, width):
"""
find 'vertices' within the cone of 'width' degrees around 'pole'
"""
return [i for i,v in enumerate(vertices) if np.abs(np.dot(v,pole)) > np.abs(np.cos(np.pi*width/180))] | 5,287,964 |
def test_frame_dropna():
"""
Tests whether the monkey patching of ('pandas.core.frame', 'dropna') works
"""
test_code = cleandoc("""
import pandas as pd
df = pd.DataFrame([0, 2, 4, 5, None], columns=['A'])
assert len(df) == 5
df = df.dropna()
assert len(d... | 5,287,965 |
def plot_gcam_reclassified(gcam_df, landclass, start_yr=2015, through_yr=2100, interval=5):
"""Plot GCAM landclass allocation over a time period reclassified to Demeter land cover types."""
yrs = [str(i) for i in range(start_yr, through_yr + interval, interval)]
lc_mapping = gcam_to_demeter_lc_map()
... | 5,287,966 |
def train(model):
"""Train the model."""
# Training dataset.
dataset_train = CarlaDataset()
dataset_train.load_carla(args.dataset, "train")
dataset_train.prepare()
# Validation dataset
dataset_val = CarlaDataset()
dataset_val.load_carla(args.dataset, "val")
dataset_val.prepare()
... | 5,287,967 |
def test_dataset_add_with_copy(tmpdir, runner, project, client):
"""Test adding data to dataset with copy."""
import os
import stat
# create a dataset
result = runner.invoke(cli, ["dataset", "create", "my-dataset"])
assert 0 == result.exit_code
assert "OK" in result.output
paths = []
... | 5,287,968 |
def get_sigmas_index(indices):
"""Takes a tuple and gives back a length-16 array with a single 1.
Parameters
----------
indices: a tuple of two integers, each one between 0 and 3.
Examples
--------
>>> get_sigmas_index((1, 0))
array([ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0... | 5,287,969 |
def test_histogram1D_to_from_existing_histogram(logging_mixin: Any) -> None:
""" Test passing a Histogram1D to ``from_existing_histogram``. It should return the same object. """
h_input = histogram.Histogram1D(
bin_edges=np.array([0, 1, 2]),
y=np.array([2.3, 5.4]),
errors_squared=np.arra... | 5,287,970 |
def authenticated():
"""Utility function checking if the current user is logged in or not."""
fas_user = None
try:
fas_user = flask.g.fas_user
except (RuntimeError, AttributeError):
pass
return fas_user is not None | 5,287,971 |
def _get_or_create_workspace(auth, subscription_id, resource_group_name, workspace_name, location):
"""
Gets or creates a workspace.
:param auth:
:type auth: azureml.core.authentication.AbstractAuthentication
:param subscription_id:
:type subscription_id: str
:param resource_group_nam... | 5,287,972 |
def backup_file(directory, filename):
""" Backup a given file by appending .bk to the end """
origfile = join(directory, filename)
backupfile = origfile + '.bk'
if exists(backupfile):
os.remove(backupfile)
if exists(origfile):
os.rename(origfile, backupfile) | 5,287,973 |
def add_calculated_fields(*,
current_item: Dict[str, Any],
initial_status,
current_status,
position_list,
lap_list,
total,
charging_proces... | 5,287,974 |
def nusmv(ctx, model, trace, outfile):
"""Generates a nuSMV encoding of the model.
If the trace is given then it's incorporated into the model.
"""
dawnet = getTraceModel(model, trace)
dawnetnusmv.process_model(dawnet, outfile=outfile if outfile else sys.stdout,
solve=c... | 5,287,975 |
def test_allow_unverified_option(httpsserver):
"""Ensure that we allow unverified servers if the user passes a flag."""
api = Api(domain=httpsserver.url, verify=False)
api.login('test@test.com', 'test')
api.logout()
api.refresh_token()
# Also ensure that the RestResource works as well
res... | 5,287,976 |
def check_if_all_passed(statuses):
# type: (Dict[str, str]) -> bool
"""
Check if all items in supplied `statuses` dict passed parsing and conversion.
:param statuses: dictionary init info statuses (files/nodes to their status)
:type statuses: dict
:return: boolean indicating if all files and no... | 5,287,977 |
def get_database_connection():
"""Returns a connection to Redis DB or creates a new one if it does not already exist."""
global _database
try:
return _database
except NameError:
config = get_config()
_database = redis.Redis(host=config['redis_db_address'],
... | 5,287,978 |
def _get_config(**kwargs):
"""
Return configuration
"""
config = {
"filter_id_regex": [".*!doc_skip"],
"filter_function_regex": [],
"replace_text_regex": {},
"proccesser": "highstate_doc.proccesser_markdown",
"max_render_file_size": 10000,
"note": None,
... | 5,287,979 |
def describe_environment_managed_actions(EnvironmentName=None, EnvironmentId=None, Status=None):
"""
Lists an environment's upcoming and in-progress managed actions.
See also: AWS API Documentation
:example: response = client.describe_environment_managed_actions(
EnvironmentName='strin... | 5,287,980 |
def get_neon_core_root():
"""
Determines the root of the available/active Neon Core. Should be the immediate parent directory of 'neon_core' dir
Returns:
Path to the core directory containing 'neon_core'
"""
site = sysconfig.get_paths()['platlib']
if exists(join(site, 'neon_core')):
... | 5,287,981 |
def signal_framing(
signal: Union[torch.Tensor, ComplexTensor],
frame_length: int,
frame_step: int,
bdelay: int,
do_padding: bool = False,
pad_value: int = 0,
indices: List = None,
) -> Union[torch.Tensor, ComplexTensor]:
"""Expand `signal` into several frames, with each frame of length ... | 5,287,982 |
def test_abstract_classes():
"""很多时候我们会觉得mongoengine.Document提供的方法不够多, 我们会想要自定义
一些方法。为了减少冗余代码, 我们想要将通用的方法以继承的方式实现。这时, 我们
需要建立一个新的Document的基类, 然后用户的类都从这个基类继承而来。
具体做法如下:
Ref: http://docs.mongoengine.org/guide/defining-documents.html?#abstract-classes
"""
class ExtendedDocument(Document):
... | 5,287,983 |
def evaluate_conditional(string: str, fields: Dict[str, str]) -> bool:
""" Evaluates a conditional from $string on a Anki card template
using the field values $fields. """
field_name = get_field_name(string)
if field_name not in fields:
logger.warning("Field '{}' from conditional '{}' not define... | 5,287,984 |
def has_all_channels(stream, channels, starttime, endtime):
"""Check whether all channels have any data within time range.
Parameters
----------
stream: obspy.core.Stream
The input stream we want to make certain has data
channels: array_like
The list of channels that we want to have... | 5,287,985 |
def world_xyzn_im_to_pts(world_xyz, world_n):
"""Makes a 10K long XYZN pointcloud from an XYZ image and a normal image."""
# world im + world normals -> world points+normals
is_valid = np.logical_not(np.all(world_xyz == 0.0, axis=-1))
world_xyzn = np.concatenate([world_xyz, world_n], axis=-1)
world_xyzn... | 5,287,986 |
def clean_email_default(email, allowed_domains):
"""
Clean email address and check if it has allowed domain
:param email: emailadress in string
:param allowed_domains: FQDN of allowed domain of mail
:return: cleaned lowercase email addresss string or ValidationError
"""
email = email.strip(... | 5,287,987 |
def GetSourceImages(local_dir, pro):
"""Downloads the various sources that we need.
Of note: Because Express does not include ATL, there's an additional download
of the 7.1 WDK which is the latest publically accessible source for ATL. When
|pro| this is not necessary (and CHROME_HEADLESS always implies Pro).
... | 5,287,988 |
def add_binary_prefix(value: float) -> str:
"""
Function that converts a number to his version with Binary prefix
@input value (an integer)
@example:
>>> add_binary_prefix(65536)
'64.0 kilo'
"""
for prefix in BinaryUnit:
numerical_part = value / (2**prefix.value)
if numer... | 5,287,989 |
def status_statement(current, final, count, chr=None):
""" Print progress statements for long processes
:param current: current iteration number
:param final: total number of iterations
:param count: number of print statements total
:param chr: print chromosome information of current progress
... | 5,287,990 |
def exhibit_type(elem):
"""Returns the exhibit type of the file."""
val = attr_val(elem, 'exhibitType')
if val is None:
return 'EX-101'
return val | 5,287,991 |
def get_mailboxes_v2():
"""
Get all mailboxes - including unverified mailboxes
Output:
- mailboxes: list of mailbox dict
"""
user = g.user
mailboxes = []
for mailbox in Mailbox.query.filter_by(user_id=user.id):
mailboxes.append(mailbox)
return (
jsonify(mailboxe... | 5,287,992 |
def angle_to_direction(input_angle, full=False, level=3):
"""Convert the meteorological angle to directional text.
Works for angles greater than or equal to 360 (360 -> N | 405 -> NE)
and rounds to the nearest angle (355 -> N | 404 -> NNE)
Parameters
----------
input_angle : numeric or array-l... | 5,287,993 |
def decode_packets(data, error_callback=None, check_crc=True, resync=True):
"""
Generator function to decode packets from a bitstream
The bitstream may be presented as either a bitarray, a file object or a socket
"""
if isinstance(data, bitarray):
logger.debug('decoding packets fro... | 5,287,994 |
def test_get_object_self_and_multiple_admins(
client_admin_factory,
employee_factory,
request_factory,
):
"""
The employee should be able to fetch their own record if their are
multiple admins for the client company.
Regression test for GH-113.
https://github.com/comp523-jarvis/timetra... | 5,287,995 |
def test_can_crud_url():
"""
Tests that full get/set/delete functionality is
available for the url property
"""
path = "path"
d = DatasetFile(path)
url = "http://mysite.com"
assert d.url is None
d.url = url
assert d.url is url
del(d.url)
assert d.url is None | 5,287,996 |
def met_setup_fixture():
"""Patch Met Éireann setup entry."""
with patch(
"homeassistant.components.met_eireann.async_setup_entry", return_value=True
):
yield | 5,287,997 |
def asset(ses, ticker_sym):
""" function that returns a single asset object given for a given ticker
"""
return _assets_response_handle(_get_assets_json(
ses, ticker=ticker_sym), ticker=ticker_sym) | 5,287,998 |
def test_truth():
"""This test checks whether running the same config twice produces the same cosmos
sampler properties
"""
# The config dict to write some images to a MEDS file
i_run = 0
seed = 1234
pixel_scale = 0.26
g1,g2 = 0.01, 0.
stamp_size=32
nobj=100
n_per_obj=1
... | 5,287,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.