content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def listUpTo(num):
"""
Returns a lists of integers from 1 up to num
"""
return list(range(1, num + 1)) | aa15d7e14912bdaf3bc8801c4b853c8b392db021 | 29,330 |
def mirror(matrix):
"""Mirror a matrix."""
return [reversed(_row) for _row in matrix] | 778405db16d5865a555db44538e0e11d9c9258f9 | 29,332 |
def is_category_suspicious(category, reputation_params):
"""
determine if category is suspicious in reputation_params
"""
return category and category.lower() in reputation_params['suspicious_categories'] | 864aa520eba53c2e0ea2a6d2fbd3f0172bcab05f | 29,335 |
from typing import Iterable
def replace_symbols_with_values(list_of_lists, replacements):
"""
Take iteratively a list of lists (at any depth level) and replace strings with
the corresponding values in the ``replacements`` dictionary, leaving other
types of values (floats, ints, ...) untouched.
:return: a new list_of_lists with the same shape, with strings replaced by numbers.
:raise ValueError: if one of the values is not found
"""
if isinstance(list_of_lists, str): # Check this first, a str is also Iterable
try:
return replacements[list_of_lists]
except KeyError:
raise ValueError("Unknown replacement '{}'".format(list_of_lists))
elif isinstance(list_of_lists, Iterable):
return [
replace_symbols_with_values(elem, replacements=replacements)
for elem in list_of_lists
]
else:
return list_of_lists | d3ab32e2527ad2e29515aa727676f8cbc86c9ee0 | 29,336 |
def _return_value(resource, key):
""" Return the value from the resource """
return resource[key] | 80cc72be0955e1b931422288dc84ede1d2098334 | 29,339 |
def handled_float(value, default=0):
"""
Returns ``float(value)`` if value is parseable by ``float()``.
Otherwise returns ``default``.
"""
ret_val = default
try:
ret_val = float(value)
except (TypeError, ValueError):
pass
return ret_val | d905695486c05ed11413307d3f5877ff905654d4 | 29,343 |
def group_by_company(devices):
"""Group a list of devices by company."""
grouped = {}
for dev in devices:
try:
grouped[dev['company']['name']].append(dev)
except KeyError:
grouped[dev['company']['name']] = [dev]
return grouped | 9b5b1c56a95132a8777e3206116819e528483a43 | 29,344 |
def first(items):
"""
Get the first item from an iterable.
Warning: It consumes from a generator.
:param items: an iterable
:return: the first in the iterable
"""
for item in items:
return item | 2ed7fa730b1b1c1588bc98e93ac8ef02a669ae98 | 29,346 |
from typing import List
import itertools
def mixup_arguments(*args) -> List:
"""mixups given arguments
[argument_1_1, argument_1_2], [argument_2_1] =>
[(argument_1_1, argument_2_1), (argument_1_2, argument_2_1)]
Returns:
List: [(arg1, arg2), ...]
"""
return list(itertools.product(*args)) | cf21e83b2ac07834220fab4bf000f98462c33a01 | 29,348 |
def cal_words_num(lines):
"""
Calculate number of words in lines
:param lines: lines to be calculate
:return: number of words
"""
return sum(map(len, lines)) | fc8f6022620687d21d0fa26bd51466a738eb0333 | 29,351 |
def add_delayed(df):
"""
Add col Delayed. 0 = punctual, 1 = delayed by more than 10 min
"""
_df = df.copy()
delayed = []
for index, row in _df.iterrows():
if row['Timedelta'] > 10:
delayed.append(1)
else:
delayed.append(0)
_df['Delayed'] = delayed
return _df | 06f187dc06b934a8f9384972c2f6bfe9461607b7 | 29,357 |
from typing import Collection
def key_map(data_: Collection) -> dict:
"""
Map all keys in a given data collection to their respective values.
e.g.
For the next data collection:
data = [
{
'name': 'foo',
'age': 31,
'country': 'UK'
},
{
'name': 'bar',
'age': 31,
'country': 'US'
},
{
'name': 'Mr. X',
'age': 29,
'country': 'UK'
}
]
mapped_data = key_mep(data)
mapped_data['age'][31]
will return:
[
{
'name': 'foo',
'age': 31,
'country': 'UK'
},
{
'name': 'bar',
'age': 31,
'country': 'US'
}
]
mapped_data['country']['UK']
will return:
[
{
'name': 'foo',
'age': 31,
'country': 'UK'
},
{
'name': 'Mr. X',
'age': 29,
'country': 'UK'
}
]
:param data_:
:return:
"""
mapped_data = {}
for item in data_:
for k, v in item.items():
if k not in mapped_data:
mapped_data[k] = {}
if v not in mapped_data[k]:
mapped_data[k][v] = []
mapped_data[k][v].append(item)
return mapped_data | f9939e79090831d140e41158e175bc61661cc740 | 29,359 |
def _parse_cpmd_atoms_block(lines, line_idx, parsed):
"""Add to ``parsed`` ``cpmd_atom_to_line_idx``.
``cpmd_atom_to_line_idx`` is a Dict[int, int] that associates a CPMD atom
index to the line number where its coordinates are stored.
Parameters
----------
lines : List[str]
The lines of the entire file as read by file.readlines().
line_idx : int
The index of the first line after '&ATOMS'.
parsed : Dict
A memo dictionary where the parsed info is saved.
Returns
-------
line_idx : int
The line index right after the '&END' directive of the '&MIMIC' block.
"""
parsed['cpmd_atom_to_line_idx'] = {}
current_atom_idx = 0
while line_idx < len(lines):
line = lines[line_idx].strip()
if line.startswith('*'):
# New atom type. First line is nonlocality, second is number of atoms.
n_atoms = int(lines[line_idx+2])
# Add the atoms to the map.
line_idx += 3
for element_atom_idx in range(n_atoms):
parsed['cpmd_atom_to_line_idx'][current_atom_idx] = line_idx+element_atom_idx
current_atom_idx += 1
line_idx += n_atoms
elif line.startswith('&END'):
break
else:
# Empty line.
line_idx += 1
return line_idx + 1 | 0dd693c4ca02af2b77288fd1c7a8ce2d2ab213bd | 29,363 |
def mndvi(b2, b4, b8):
"""
Modified Normalized Difference Vegetation Index \
(Main et al., 2011).
.. math:: MNDVI = (b8 - b4) / (b8 + b4 - 2 * b2)
:param b2: Blue.
:type b2: numpy.ndarray or float
:param b4: Red.
:type b4: numpy.ndarray or float
:param b8: NIR.
:type b8: numpy.ndarray or float
:returns MNDVI: Index value
.. Tip::
Main, R., Cho, M. A., Mathieu, R., O’kennedy, M. M., Ramoelo, A., \
Koch, S. 2011. An investigation into robust spectral indices for \
leaf chlorophyll estimation. ISPRS Journal of Photogrammetry and \
Remote Sensing 66, 751-761. doi:10.1016/j.isprsjprs.2011.08.001.
"""
MNDVI = (b8 - b4) / (b8 + b4 - 2 * b2)
return MNDVI | af90990cf706ec353b1b435dc3d48a3c9801be92 | 29,366 |
def get_heading_text_lines(heading_regions):
"""
Given a list of TextRegion objects ``heading_regions`` (of type heading) return all of their text lines as one big
list.
:param heading_regions: List of TextRegion objects of type heading.
:type heading_regions: List[TextRegion]
:return: List of all TextLine objects belonging to the heading regions.
"""
text_lines = []
for heading_region in heading_regions:
text_lines.extend(heading_region.text_lines)
return text_lines | 671d2de7ce90319307199d14805f9ac0f0bf76fd | 29,367 |
from typing import List
from typing import Dict
from typing import Any
def validate_cell_header(
headers: List[str], cell: Dict[str, Any]
) -> List[str]:
"""Check that header of a cell meets project specifications."""
content = [line.rstrip('\n') for line in cell['source']]
curr_header = content[0]
msg = f"Cell header must be h2 (i.e. start with ##), found: {curr_header}"
if not curr_header.startswith('## '):
raise ValueError(msg)
msg = f"Each header must appear only once, '{curr_header}' is duplicated"
if curr_header in headers:
raise ValueError(msg)
headers.append(curr_header)
return headers | c18c385792a0f04661ca3961e31d7bb7ce8e5801 | 29,372 |
def zaction(op, inv):
"""
Return a function
f: (G, Z) -> G
g, n |-> g op g op ... (n-1 times) ... op g
If n is zero, it returns identity element. If n is negative, it
returns |n|-1 times op on the inverse of g.
"""
def f(g, n):
result = op(g, inv(g)) # identity
if n < 0:
g, n = inv(g), -n
for i in range(n):
result = op(result, g)
return result
return f | a75f061221ce28b03f3bcc4ddbbc6985f20339b2 | 29,376 |
def percentage_to_int(value):
"""
Scale values from 0-100 to 0-255
"""
return round((255.0 / 100.0) * float(value)) | b7bbc35da0fc704db0f454692b52286123cbb942 | 29,380 |
import torch
def select_seeds(dist1: torch.Tensor, R1: float, scores1: torch.Tensor, fnn12: torch.Tensor, mnn: torch.Tensor):
"""
Select seed correspondences among the set of available matches.
dist1: Precomputed distance matrix between keypoints in image I_1
R1: Base radius of neighborhoods in image I_1
scores1: Confidence scores on the putative_matches. Usually holds Lowe's ratio scores.
fnn12: Matches between keypoints of I_1 and I_2.
The i-th entry of fnn12 is j if and only if keypoint k_i in image I_1 is matched to keypoint k_j in image I_2
mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on 'force_seed_mnn' in the DEFAULT_CONFIG.
If None, it disables the mutual nearest neighbor filtering on seed point selection.
Expected a bool tensor with shape (num_keypoints_in_source_image,)
Returns:
Indices of seed points.
im1seeds: Keypoint index of chosen seeds in image I_1
im2seeds: Keypoint index of chosen seeds in image I_2
"""
im1neighmap = dist1 < R1**2 # (n1, n1)
# find out who scores higher than whom
im1scorescomp = scores1.unsqueeze(1) > scores1.unsqueeze(0) # (n1, n1)
# find out who scores higher than all of its neighbors: seed points
if mnn is not None:
im1bs = (~torch.any(im1neighmap & im1scorescomp & mnn.unsqueeze(0),
dim=1)) & mnn & (scores1 < 0.8**2) # (n1,)
else:
im1bs = (~torch.any(im1neighmap & im1scorescomp, dim=1)) & (scores1 <
0.8**2)
# collect all seeds in both images and the 1NN of the seeds of the other image
im1seeds = torch.where(im1bs)[0] # (n1bs) index format
im2seeds = fnn12[im1bs] # (n1bs) index format
return im1seeds, im2seeds | 36ac7c9e9f6ccef31e487d350acfa2b4e496a7d4 | 29,381 |
def getarg(args, index):
"""
Helper to retrieve value from command line args
"""
return args[index] if index < len(args) else None | 256de43dda23c9f613c61a8dca456a3d507ca332 | 29,384 |
def resize_to(img_obj, new_height, new_width):
"""
Resize an image to the specified dimensions
"""
assert isinstance(new_height, int)
assert isinstance(new_width, int)
assert new_height > 0
assert new_width > 0
return img_obj.resize((new_width, new_height)) | 38303694e840ca29f01d6cb5b80e54d6f1c29008 | 29,387 |
def label(dt):
""" Setting the label for the integration timestep """
return 'dt = {} s'.format(dt) | 5cf5bce8079b2a0685eab0d54f16c4e61028b279 | 29,393 |
def try_to_convert(value):
"""Tries to convert [value] to an int, returns the original string on fail"""
try:
return int(value)
except:
return value | a4358e0827691262469ca776af6c207e5e09f8a2 | 29,395 |
def sf_mag(a: tuple) -> int:
"""
Calculates the magnitude of a snailfish number
:param a: a snailfish number
:return: the magnitude as int
>>> sf_mag((9, 1))
29
>>> sf_mag((1, 9))
21
>>> sf_mag(((9, 1),(1, 9)))
129
>>> sf_mag(((1,2),((3,4),5)))
143
>>> sf_mag(((((0,7),4),((7,8),(6,0))),(8,1)))
1384
>>> sf_mag(((((1,1),(2,2)),(3,3)),(4,4)))
445
>>> sf_mag(((((3,0),(5,3)),(4,4)),(5,5)))
791
>>> sf_mag(((((5,0),(7,4)),(5,5)),(6,6)))
1137
>>> sf_mag(((((8,7),(7,7)),((8,6),(7,7))),(((0,7),(6,6)),(8,7))))
3488
>>> sf_mag(((((6,6),(7,6)),((7,7),(7,0))),(((7,7),(7,7)),((7,8),(9,9)))))
4140
"""
if type(a[0]) is int:
left = a[0]
else:
left = sf_mag(a[0])
if type(a[1]) is int:
right = a[1]
else:
right = sf_mag(a[1])
return left * 3 + right * 2 | 8292494f9e8ef4fe63dbaa7aef1c0973576aba64 | 29,399 |
import time
def create_datasplit(train_set, validation_set, test_set, name=None):
"""Create a datasplit dict from user-defined data sets
Args:
train_set (set): set of audio file paths
valid_set (set): set of audio file paths
test_set (set): set of audio file paths
name (str): name of the datasplit (set to unix timestamp if not
specified)
Returns:
a dict with train_set, validation_set and test_set, as sets of
audio file paths
"""
if not name:
name = int(time.time())
return {"id": "{}".format(name),
"sets": {"train": train_set,
"validation": validation_set,
"test": test_set}
} | a6d35205dc8c5d31662301a471e291cd578f77ee | 29,408 |
def ndmi(b8, b11):
"""
Normalized Difference Moisture Index \
(Gerard et al., 2003).
.. math:: NDMI = (b8 - b11) / (b8 + b11)
:param b8: NIR.
:type b8: numpy.ndarray or float
:param b11: SWIR 1.
:type b11: numpy.ndarray or float
:returns NDMI: Index value
.. Tip::
Gerard, F., Plummer, S., Wadsworth, R., Sanfeliu, \
A. F., Iliffe, L., Balzter, H., & Wyatt, B. 2003. \
Forest fire scar detection in the boreal forest with \
multitemporal SPOT-VEGETATION data. IEEE Transactions \
on Geoscience and Remote Sensing 41(11), 2575-2585. \
doi:10.1109/tgrs.2003.819190.
"""
NDMI = (b8 - b11) / (b8 + b11)
return NDMI | ed60cd5bae20167a747d3df1e9a5e9aa386ce385 | 29,411 |
def chunker(df, size):
"""
Split dataframe *df* into chunks of size *size*
"""
return [df[pos:pos + size] for pos in range(0, len(df), size)] | ea96315f9963551f4870d6732570d0ae375bd3c3 | 29,418 |
def clean_advance_reservation(text):
""" The advance reservation field identifies whether or not advance
reservations are required to use these facilities (day use areas). If there
is not recorded answer (blank) we default to 'no reservation required'.
Returns 'True' if reservation required, False otherwise. """
text = text.lower()
if text in ['yes']:
return True
if 'registration required' in text:
return True
if 'tour request form' in text:
return True
if 'call ahead' in text:
return True
return False | 8f707074f62ff605935737e3a6fa4cf2dc492de2 | 29,428 |
def _get_question_features(conv_id, QUESTIONS):
"""
Given conversation id and a dictionary QUESTIONS
Returns an one-hot vector of length 8, the Xth entry being 1 iff the conversation contains question type X.
"""
ret = {}
for ind in range(8):
ret['question_type%d'%(ind)] = 0
if conv_id in QUESTIONS:
for pair in QUESTIONS[conv_id]:
ret['question_type%d'%(pair['question_type'])] = 1
return ret | 7e81b6aed3f7fdd4aae1cd9e8cafdb43ebea2586 | 29,433 |
def validate_csv(row0, required_fields):
"""
:param row0:
:param required_fields:
:return: a tuple, True if all requirements are met and a dictionary with the index for all the fields
"""
for field in required_fields:
if field not in row0:
return False, {}
field_pos = {}
for idx, field in enumerate(row0):
field_pos[field] = idx
return True, field_pos | 6a126f22a86fbcfa4192ec4f9104faab7efd6b3f | 29,439 |
from typing import Sequence
from typing import Callable
from typing import Any
def batch_by_property(
items: Sequence, property_func: Callable
) -> list[tuple[list, Any]]:
"""Takes in a Sequence, and returns a list of tuples, (batch, prop)
such that all items in a batch have the same output when
put into the Callable property_func, and such that chaining all these
batches together would give the original Sequence (i.e. order is
preserved).
Examples
--------
Normal usage::
batch_by_property([(1, 2), (3, 4), (5, 6, 7), (8, 9)], len)
# returns [([(1, 2), (3, 4)], 2), ([(5, 6, 7)], 3), ([(8, 9)], 2)]
"""
batch_prop_pairs = []
curr_batch = []
curr_prop = None
for item in items:
prop = property_func(item)
if prop != curr_prop:
# Add current batch
if len(curr_batch) > 0:
batch_prop_pairs.append((curr_batch, curr_prop))
# Redefine curr
curr_prop = prop
curr_batch = [item]
else:
curr_batch.append(item)
if len(curr_batch) > 0:
batch_prop_pairs.append((curr_batch, curr_prop))
return batch_prop_pairs | 733dae3d31219dafbe115f12263a3da735409c30 | 29,440 |
def transpose_func(classes, table):
"""
Transpose table.
:param classes: confusion matrix classes
:type classes: list
:param table: input confusion matrix
:type table: dict
:return: transposed table as dict
"""
transposed_table = {k: table[k].copy() for k in classes}
for i, item1 in enumerate(classes):
for j, item2 in enumerate(classes):
if i > j:
temp = transposed_table[item1][item2]
transposed_table[item1][item2] = transposed_table[item2][item1]
transposed_table[item2][item1] = temp
return transposed_table | 6c59feef2b735076c5768e086ef2e91331b78a73 | 29,450 |
from functools import reduce
def traverse_dict_children(data, *keys, fallback=None):
"""attempts to retrieve the config value under the given nested keys"""
value = reduce(lambda d, l: d.get(l, None) or {}, keys, data)
return value or fallback | 2c6f28259136bd8248306b7e759540fc3877d46f | 29,451 |
def get_idxs_in_correct_order(idx1, idx2):
"""First idx must be smaller than second when using upper-triangular arrays (matches, keypoints)"""
if idx1 < idx2: return idx1, idx2
else: return idx2, idx1 | 05963c4f4b692b362980fde3cf6bb1de1b8a21e0 | 29,453 |
from typing import Dict
from typing import Any
def source_startswith(cell: Dict[str, Any], key: str) -> bool:
"""Return True if cell source start with the key."""
source = cell.get("source", [])
return len(source) > 0 and source[0].startswith(key) | a3dab1e72488a5075832432f36c6fc10d9808a7f | 29,455 |
def _sabr_implied_vol_hagan_A4(
underlying, strike, maturity, alpha, beta, rho, nu):
"""_sabr_implied_vol_hagan_A4
One of factor in hagan formua.
See :py:func:`sabr_implied_vol_hagan`.
A_{4}(K, S; T)
& := &
1
+
\left(
\\frac{(1 - \\beta)^{2}}{24}
\\frac{\alpha^{2}}{(SK)^{1-\\beta}}
+ \\frac{1}{4}
\\frac{\\rho\\beta\nu\alpha}{(SK)^{(1-\\beta)/2}}
+ \\frac{2 - 3\\rho^{2}}{24}\nu^{2}
\\right) T
:param float underlying:
:param float strike:
:param float maturity:
:param float alpha:
:param float beta:
:param float rho:
:param float nu:
:return: value of factor.
:rtype: float.
"""
one_minus_beta = 1.0 - beta
one_minus_beta_half = one_minus_beta / 2.0
one_minus_beta2 = one_minus_beta ** 2
numerator1 = one_minus_beta2 * alpha * alpha
denominator1 = 24.0 * ((underlying * strike) ** one_minus_beta)
term1 = numerator1 / denominator1
numerator2 = rho * beta * nu * alpha
denominator2 = 4.0 * ((underlying * strike) ** one_minus_beta_half)
term2 = numerator2 / denominator2
term3 = (2.0 - 3.0 * rho * rho) * nu * nu / 24.0
return 1.0 + (term1 + term2 + term3) * maturity | 704f4db60570cc18ad16b17d9b6ba93747d373d4 | 29,466 |
import glob
def get_sorted_files(files):
"""Given a Unix-style pathname pattern, returns a sorted list of files matching that pattern"""
files = glob.glob(files)
files.sort()
return files | 9bed6be4c57846c39290d4b72dba1577f9d76396 | 29,474 |
from typing import Dict
from typing import Any
def modify_namelist_template(
namelist_template: str,
placeholder_dict: Dict[str, Any]
):
"""
Placeholders in the form of %PLACEHOLDER_NAME% are replaced within the
given namelist template.
Parameters
----------
namelist_template : str
Placeholders within this template are replaced by the given value.
placeholder_dict : Dict[str, Any]
This is the directory with the placeholder values. A placeholder is
skipped if it is not found within given namelist template. The values
have to be castable to string type.
Returns
-------
namelist_template : str
The namelist where the placeholders are replaced with given values.
"""
for placeholder, value in placeholder_dict.items():
namelist_template = namelist_template.replace(placeholder, str(value))
return namelist_template | 2a872b20caf871ff6406e04a91d69ee2f33ba66c | 29,479 |
import pickle
def load_results(path, filename):
"""
load result from pickle files.
args:
path: path to directory in which file is located
filename: name of the file (without pickle extention)
"""
with open(path+filename+'.pickle', 'rb') as handle:
return pickle.load(handle) | 6f76914cdbb25c4c5f81bc2bd61b61da5b34777a | 29,481 |
from pathlib import Path
def create_target_absolute_file_path(file_path, source_absolute_root, target_path_root, target_suffix):
"""
Create an absolute path to a file.
Create an absolute path to a file replacing the source_absolute_root part of the path with the target_path_root path
if file_path is on the source_absolute_root path and replace the extension with target_suffix.
If file_path is not on source_absolute_root return file_path with the target_suffix
Parameters
----------
file_path : str or Path
Path to a file
source_absolute_root : str or Path
a path that may be the start of file_path
target_path_root : str or Path
A path that will become the start of the path to the returned target path
target_suffix : str
The suffix to use on the returned target path
Returns
-------
Path
The new absolute path to the file that was on file_path
"""
if Path(file_path).is_relative_to(source_absolute_root):
target_relative_path_to_source_root = Path(file_path).relative_to(source_absolute_root)
# target_relative_path_to_source_root is the relative path that will be added onto the export folder path
return Path(target_path_root, target_relative_path_to_source_root).with_suffix(target_suffix)
if not Path(file_path).is_absolute():
# path is relative add target path_root and new suffix
return Path(target_path_root, file_path).with_suffix(target_suffix)
# file is not in the source path return the file path with the new suffix
return Path(file_path).with_suffix(target_suffix) | 0d24f8544752967815bd8ddceea15b371076c500 | 29,485 |
def query_prefix_transform(query_term):
"""str -> (str, bool)
return (query-term, is-prefix) tuple
"""
is_prefix = query_term.endswith('*')
query_term = query_term[:-1] if is_prefix else query_term
return (query_term, is_prefix) | d33dd4222f53cba471be349b61e969838f6188d5 | 29,486 |
def consolidate_conversion(x):
"""
Collapses the conversion status to Yes or No.
"""
xl = x.str.lower()
if any(xl.str.startswith('purchase')) or any(xl.str.startswith('converted')) or \
any(xl.str.startswith('y')) or any(xl.str.startswith('processed')) or \
any(xl.str.startswith('payment_completed')) or any(xl.str.startswith('initiated')) \
or any(xl.str.startswith('pdf_error')) or any(xl.str.startswith('toprocess')) \
or any(xl.str.startswith('delivered')):
return 'Y'
else:
return 'N' | fa9e8c93705d9d1941c12aeae293dc32750853d2 | 29,489 |
def fix_msg(msg, name):
"""Return msg with name inserted in square brackets"""
b1 = msg.index('[')+1
b2 = msg.index(']')
return msg[:b1] + name + msg[b2:] | 66544f811a9cead0a40b6685f60a7de8f219e254 | 29,491 |
def reshape_as_vectors(tensor):
"""Reshape from (b, c, h, w) to (b, h*w, c)."""
b, c = tensor.shape[:2]
return tensor.reshape(b, c, -1).permute(0, 2, 1) | 79044cc2061d0a4368922c3dc6c1324eb5fe315b | 29,493 |
def get_common_items(list1, list2):
"""
Compares two lists and returns the common items in a new list. Used internally.
Example
-------
>>> list1 = [1, 2, 3, 4]
>>> list2 = [2, 3, 4, 5]
>>> common = get_common_items(list1, list2)
list1: list
list2: list
returns: list
"""
common = [value for value in list1 if value in list2]
return common | 4978429d7d255270b4e4e52e44159e934cbd5ba5 | 29,497 |
def Powerlaw(x, amp, index, xp):
"""
Differential spectrum of simple Powerlaw normlized at xp
:param x: Energies where to calculate differential spectrum
:param amp: Amplitude of pl
:param index: Index of pl
:param xp: Normalization energy
:return: differential spectrum of a Powerlaw at energies x
"""
return amp*(x/xp)**index | 6e31d7a85998f762ff27305a38535487db6592fb | 29,501 |
def get_by_tag_name(element, tag):
"""
Get elements by tag name.
:param element: element
:param tag: tag string
:return: list of elements that matches tag
"""
results = []
for child in element.findall('.//'):
if tag in child.tag:
results.append(child)
return results | d1e2d196cae5c3a0de00c624f5df28c988eaa088 | 29,504 |
def clamp(value, min=0, max=255):
"""
Clamps a value to be within the specified range
Since led shop uses bytes for most data, the defaults are 0-255
"""
if value > max:
return max
elif value < min:
return min
else:
return value | 2d6e01daddc3603527021e4dbab261f82b3f8862 | 29,505 |
def clamp_value(value, minimum, maximum):
"""Clamp a value to fit within a range.
* If `value` is less than `minimum`, return `minimum`.
* If `value` is greater than `maximum`, return `maximum`
* Otherwise, return `value`
Args:
value (number or Unit): The value to clamp
minimum (number or Unit): The lower bound
maximum (number or Unit): The upper bound
Returns:
int or float: The clamped value
Example:
>>> clamp_value(-1, 2, 10)
2
>>> clamp_value(4.0, 2, 10)
4.0
>>> clamp_value(12, 2, 10)
10
"""
if value < minimum:
return minimum
elif value > maximum:
return maximum
else:
return value | 1224b7ed098781d66721dceef5c837470f1195a6 | 29,507 |
def make_signatures_with_minhash(family, seqs):
"""Construct a signature using MinHash for each sequence.
Args:
family: lsh.MinHashFamily object
seqs: dict mapping sequence header to sequences
Returns:
dict mapping sequence header to signature
"""
# Construct a single hash function; use the same for all sequences
h = family.make_h()
signatures = {}
for name, seq in seqs.items():
signatures[name] = h(seq)
return signatures | c6366811536f1e32c29e3a00c91267bde85969fa | 29,510 |
import socket
def resolve_fqdn_ip(fqdn):
"""Attempt to retrieve the IPv4 or IPv6 address to a given hostname."""
try:
return socket.inet_ntop(socket.AF_INET, socket.inet_pton(socket.AF_INET, socket.gethostbyname(fqdn)))
except Exception:
# Probably using ipv6
pass
try:
return socket.inet_ntop(socket.AF_INET6, socket.inet_pton(socket.AF_INET6, socket.getaddrinfo(fqdn, None, socket.AF_INET6)[0][4][0]))
except Exception:
return '' | 2e7680fe3a4ea174f3f7b22e4991a3a65e5e4995 | 29,516 |
from pathlib import Path
def field_name_from_path(path):
"""Extract field name from file path."""
parts = Path(path).stem.split('.')
field_name = parts[-1]
if len(parts) > 1:
if parts[-1] in ('bam', 'sam', 'cram'):
field_name = parts[-2]
return field_name | 9d21b760bccb6557f5450921482d76917ba13981 | 29,519 |
def binaryStringDigitDiff(binstr1, binstr2):
"""
Count the number of digits that differ between two
same-length binary strings
Parameters
----------
binstr1 : string
A binary (base-2) numeric string.
binstr2 : string
A binary (base-2) numeric string.
Returns
-------
An integer, the number of digits that differ between
the two strings.
"""
digitDiff = 0
if not len(binstr1) == len(binstr2):
raise Exception("binaryStringDigitDiff requires arguments to have same length")
for n in range(0, len(binstr1)):
if binstr1[n] != binstr2[n]:
digitDiff += 1
return digitDiff | be39c7dbc30f6e49263a880254a021ff6873d240 | 29,521 |
from datetime import datetime
def timestamp_to_datetime(timestamp):
"""Generate datetime string formatted for the ontology timeseries
Args:
timestamp (float, timemstamp): Timestamp value as float
Returns:
str: Returns the timestamp with the format necessary to insert in the Ontology
"""
return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%dT%H:%M:%SZ") | b894c3610842bf62387cbed77047fe4cc4d577a5 | 29,524 |
def setdiag(G, val):
"""
Sets the diagonal elements of a matrix to a specified value.
Parameters
----------
G: A 2D matrix or array.
The matrix to modify.
val: Int or float
The value to which the diagonal of 'G' will be set.
"""
n = G.shape[0]
for i in range(0,n):
G[i,i] = val
return G | 74a1e2899a8575f04692f74ad01e122b3639d2b1 | 29,526 |
def get_operation_full_job_id(op):
"""Returns the job-id or job-id.task-id for the operation."""
job_id = op.get_field('job-id')
task_id = op.get_field('task-id')
if task_id:
return '%s.%s' % (job_id, task_id)
else:
return job_id | 6c0258d5c2053a5320d78340979fe60c8ea88980 | 29,530 |
def get_conditions(worksheet):
"""
Get the conditions displayed on a worksheet.
args:
worksheet (seeq.spy.workbooks._worksheet.AnalysisWorksheet): Worksheet
returns:
conditions (pandas.DataFrame): Displayed Conditions
"""
display_items = worksheet.display_items
if len(display_items) == 0:
raise ValueError('No items (signals, conditions, etc) are displayed in this worksheet.')
return display_items.query("Type == 'Condition'") | f3fe0bd58f9a0344f047e3ae6eef6bdefa325c21 | 29,534 |
def TailFile(fname, lines=20):
"""Return the last lines from a file.
@note: this function will only read and parse the last 4KB of
the file; if the lines are very long, it could be that less
than the requested number of lines are returned
@param fname: the file name
@type lines: int
@param lines: the (maximum) number of lines to return
"""
fd = open(fname, "r")
try:
fd.seek(0, 2)
pos = fd.tell()
pos = max(0, pos - 4096)
fd.seek(pos, 0)
raw_data = fd.read()
finally:
fd.close()
rows = raw_data.splitlines()
return rows[-lines:] | 39f2f07421f150df16061219790e49f222f284e7 | 29,535 |
def get_df_subset(df, column_one, value_one, column_two, value_two):
"""
Takes a dataframe and filters it based on two columns and their matching values
"""
return df.loc[(df[column_one] == value_one) & (df[column_two] == value_two), :] | 4971af24f33b12d00a2385b7c5ee295630f385de | 29,538 |
def zoom_to_roi(zoom, resolution):
"""Gets region of interest coordinates from x,y,w,h zoom parameters"""
x1 = int(zoom[0] * resolution[0])
x2 = int((zoom[0]+zoom[2]) * resolution[0])
y1 = int(zoom[1] * resolution[1])
y2 = int((zoom[1]+zoom[3]) * resolution[1])
return ((x1,y1),(x2,y2)) | cd77da9a67713ed7f76f4d41a7b7bee7e2f54a78 | 29,540 |
def get_ext(path):
"""Get file extension.
Finds a file's extension and returns it.
Parameters
----------
path : str
The path to a file.
Returns
-------
str
The file extension including leading "."
"""
return path[path.rfind(".") :] | 80ba4fb8686b2a7454240a56aa0c3a7d41636f27 | 29,541 |
def _engprop(l): # {{{1
"""Print the engineering properties as a HTML table."""
lines = [
"</tbody>",
"<tbody>",
'<tr><td colspan="6" align="center"><strong>Engineering properties</strong></td></tr>',
'<tr><td colspan="3" align="center"><strong>In-plane</strong></td>',
'<td colspan="3" align="center"><strong>3D stiffness tensor</strong></td></tr>',
"<tr>",
f'<td>E<sub>x</sub></td><td>{l.Ex:.0f}</td><td align="left">MPa</td>',
f'<td>E<sub>x</sub></td><td>{l.tEx:.0f}</td><td align="left">MPa</td>',
"</tr>",
"<tr>",
f'<td>E<sub>y</sub></td><td>{l.Ey:.0f}</td><td align="left">MPa</td>',
f'<td>E<sub>y</sub></td><td>{l.tEy:.0f}</td><td align="left">MPa</td>',
"</tr>",
"<tr>",
f'<td>E<sub>z</sub></td><td>{l.Ez:.0f}</td><td align="left">MPa</td>',
f'<td>E<sub>z</sub></td><td>{l.tEz:.0f}</td><td align="left">MPa</td>',
"</tr>",
"<tr>",
f'<td>G<sub>xy</sub></td><td>{l.Gxy:.0f}</td><td align="left">MPa</td>',
f'<td>G<sub>xy</sub></td><td>{l.tGxy:.0f}</td><td align="left">MPa</td>',
"</tr>",
"<tr>",
f'<td>G<sub>xz</sub></td><td>{l.Gxz:.0f}</td><td align="left">MPa</td>',
f'<td>G<sub>xz</sub></td><td>{l.tGxz:.0f}</td><td align="left">MPa</td>',
"</tr>",
"<tr>",
f'<td>G<sub>yz</sub></td><td>{l.Gyz:.0f}</td><td align="left">MPa</td>',
f'<td>G<sub>yz</sub></td><td>{l.tGyz:.0f}</td><td align="left">MPa</td>',
"</tr>",
"<tr>",
f'<td>ν<sub>xy</sub></td><td>{l.νxy:.3f}</td><td align="left">-</td>',
f'<td>ν<sub>xy</sub></td><td>{l.tνxy:.3f}</td><td align="left">-</td>',
"</tr>",
"<tr>",
f'<td>ν<sub>yx</sub></td><td>{l.νyx:.3f}</td><td align="left">-</td>',
f'<td>ν<sub>xz</sub></td><td>{l.tνxz:.3f}</td><td align="left">-</td>',
"</tr>",
"<tr>",
f'<td>α<sub>x</sub></td><td>{l.αx:.3f}</td><td align="left">K<sup>-1</sup></td>',
f'<td>ν<sub>yz</sub></td><td>{l.tνyz:.3f}</td><td align="left">-</td>',
"</tr>",
"<tr>",
f'<td>α<sub>y</sub></td><td>{l.αy:.3f}</td><td align="left">K<sup>-1</sup></td>',
"</tr>",
]
return lines | e6bbaa4a39265b2703aa623a99a73f5b4e471023 | 29,544 |
import typing
import hashlib
def create_sf_instance(entity_name: str, property_label: str) -> typing.Tuple[str, str]:
"""Creates a slot filling instance by combining a name and a relation.
Arguments:
entity_name: ``str`` The name of the AmbER set to fill into the template.
property_label: ``str`` The property name of the AmbER set tuple.
Returns:
query: ``str`` The template with the name slotted in.
query_hashlib: ``str`` A MD5 hash of the query.
"""
sf_input = entity_name + " [SEP] " + property_label
sf_hashlib = hashlib.md5(sf_input.encode("utf-8")).hexdigest()
return sf_input, sf_hashlib | 02e69115261b148c7fdb270864095c63bbdb2278 | 29,549 |
def ensure_keys(dict_obj, *keys):
"""
Ensure ``dict_obj`` has the hierarchy ``{keys[0]: {keys[1]: {...}}}``
The innermost key will have ``{}`` has value if didn't exist already.
"""
if len(keys) == 0:
return dict_obj
else:
first, rest = keys[0], keys[1:]
if first not in dict_obj:
dict_obj[first] = {}
dict_obj[first] = ensure_keys(dict_obj[first], *rest)
return dict_obj | e8d87444ed8961d8d650b49c8670dca1496623b1 | 29,550 |
import re
def middle_coord(text):
"""Get the middle coordinate from a coordinate range.
The input is in the form <start> to <end> with both extents being in
degrees and minutes as N/S/W/E. S and W thus need to be negated as we only
care about N/E.
"""
def numbers_from_string(s):
"""Find all numbers in a string."""
return [float(n) for n in re.findall(r'[\d.]*\d[\d.]*', s)]
def tuple_to_float(numbers):
divisor = 1
result = 0
for num in numbers:
result += float(num) / divisor
divisor = divisor * 60
return result
if text is None:
return None
pieces = text.split(' to ', 1)
start, end = map(numbers_from_string, pieces)
start = tuple_to_float(start)
end = tuple_to_float(end)
if pieces[0][-1] in ('S', 'W'):
start = -start
if pieces[1][-1] in ('S', 'W'):
end = -end
return (start + end) / 2 | 4e8148102ff04969279690922ddce5bd767fed55 | 29,554 |
def convert_webaccess_datestamp(entry):
"""Set date and time attributes based on an iso date stamp"""
attrlist = entry['date_stamp'].split('/')
timelist = attrlist[-1].split(':')
entry['year'] = timelist[0]
months = {'Jan': '01', 'Feb': '02', 'Mar': '03',
'Apr': '04', 'May': '05', 'Jun': '06',
'Jul': '07', 'Aug': '08', 'Sep': '09',
'Oct': '10', 'Nov': '11', 'Dec': '12'}
entry['month'] = months[attrlist[1]]
entry['day'] = attrlist[0]
entry['tstamp'] = ''.join(timelist[1:])
entry['numeric_date_stamp'] = entry['year'] + entry['month'] + \
entry['day'] + entry['tstamp']
return entry | 795c889f93f6d87cced5f9aa9293e6491f6b2678 | 29,561 |
def multipart_content_type(boundary, subtype='mixed'):
"""Creates a MIME multipart header with the given configuration.
Returns a dict containing a MIME multipart header with the given
boundary.
.. code-block:: python
>>> multipart_content_type('8K5rNKlLQVyreRNncxOTeg')
{'Content-Type': 'multipart/mixed; boundary="8K5rNKlLQVyreRNncxOTeg"'}
>>> multipart_content_type('8K5rNKlLQVyreRNncxOTeg', 'alt')
{'Content-Type': 'multipart/alt; boundary="8K5rNKlLQVyreRNncxOTeg"'}
Parameters
----------
boundry : str
The content delimiter to put into the header
subtype : str
The subtype in :mimetype:`multipart/*`-domain to put into the header
"""
ctype = 'multipart/%s; boundary="%s"' % (
subtype,
boundary
)
return {'Content-Type': ctype} | a19cb6fcf43f2b3c2abecf3af960f57987967c0e | 29,563 |
import re
def pattern_count(pattern, text):
"""Counts apperances of a Regex pattern in a string."""
return len(re.findall(pattern, text)) | b12c8bc2132a9fd9afba7468befceac7edfb636f | 29,564 |
from typing import List
from typing import Any
from typing import Dict
from typing import Counter
def get_common_items(list_to_count: List[Any], top_n: int) -> Dict[Any, int]:
"""Get the n most common items in descending order in a list of items.
Args:
text (List[Any]): List of items to be counted.
top_n (int): This sets the limit for how many of the common items to return.
Returns:
Dict[str, int]: Dictionary with keys given by the item, and the value being count of the item in the list.
"""
counts = Counter(list_to_count)
return {item: count for item, count in Counter(counts).most_common(top_n)} | 928a243ab48cce35ead2c821b1891f88ce20123e | 29,568 |
def trycast(value):
"""
Try to cast a string attribute from an XML tag to an integer, then to a
float. If both fails, return the original string.
"""
for cast in (int, float):
try:
return cast(value)
except ValueError:
continue
return value | 3faaaa52a2d50e20a925db96de884709c052e7e3 | 29,571 |
def _fix_bed_coltype(bed):
"""Fix bed chrom and name columns to be string
This is necessary since the chromosome numbers are often interpreted as int
"""
bed["chrom"] = bed["chrom"].astype(str)
bed["name"] = bed["name"].astype(str)
return bed | 471410f31675d0de2f35883679e760c515ff0880 | 29,573 |
def get_time_slot(hour, minute):
"""
Computes time_slot id for given hour and minute. Time slot is corresponding to 15 minutes time
slots in reservation table on Sutka pool web page (https://www.sutka.eu/en/obsazenost-bazenu).
time_slot = 0 is time from 6:00 to 6:15, time_slot = 59 is time from 20:45 to 21:00.
:param hour: hour of the day in 24 hour format
:param minute: minute of the hour
:return: time slot for line usage
"""
slot_id = (hour - 6)*4 + int(minute/15)
return slot_id | dbfc510755a0b0a9612c0aa7d94922199c3f7f7d | 29,576 |
from datetime import datetime
def int_to_date_str(i_time):
"""unix epoc time in seconds to YYYY-MM-DD hh:mm:ss"""
return str(datetime.fromtimestamp(i_time)) | 27f0773a78202e57ae498c1d40faabb29877b573 | 29,581 |
def get_waist_to_height_ratio(df):
"""Waist-to-height ratio
A measure of the distribution of body fat.
WHR= waist/height
Ref.: https://en.wikipedia.org/wiki/Waist-to-height_ratio
"""
df["WHR"] = df["ac"] / df["height"]
return df | 0720dcda80bd5bccb3e121ca9859ea2da3b75144 | 29,586 |
def evaluate_acc(predictions, outputs):
"""Compute accuracy score by comparing two lists
of same length element-wise
Arguments:
predictions {series} -- first list to be compared with the second one
outputs {series} -- same length as predictions
"""
assert len(predictions) == len(outputs), "Lists have different size"
return (predictions == outputs).sum()/len(predictions) | 299086ba456799241505ab9df6c64e3cf54ea13a | 29,590 |
def has_tool_tag(invocation):
"""
Checks if invocation has a tool_tag in workspace info
Args:
invocation (Invocation)
Returns:
True if tool_tag exists else false
"""
if (hasattr(invocation, 'workspace_info')
and hasattr(invocation.workspace_info, 'tool_tag')
and invocation.workspace_info.tool_tag != ''):
return True
return False | 7ea992c62d6d3f9ec5e3d26d5e1c3ab850d6fe04 | 29,591 |
from typing import List
def get_param_with_name(parameters: List[dict], name: str) -> dict:
"""Get the parameter that has the given name."""
matched_params = (p for p in parameters if p["name"] == name)
return next(matched_params) | ea1f527bc03cb41a77e3b9743ee372246dc12f54 | 29,594 |
def extract_layout_switch(dic, default=None, do_pop=True):
"""
Extract the layout and/or view_id value
from the given dict; if both are present but different,
a ValueError is raised.
Futhermore, the "layout" might be got (.getLayout) or set
(.selectViewTemplate);
thus, a 3-tuple ('layout_id', do_set, do_get) is returned.
"""
if do_pop:
get = dic.pop
else:
get = dic.get
layout = None
layout_given = False
set_given = 'set_layout' in dic
set_layout = get('set_layout', None)
get_given = 'get_layout' in dic
get_layout = get('get_layout', None)
keys = []
for key in (
'layout', 'view_id',
):
val = get(key, None)
if val is not None:
if layout is None:
layout = val
elif val != layout:
earlier = keys[1:] and tuple(keys) or keys[0]
raise ValueError('%(key)r: %(val)r conflicts '
'%(earlier)r value %(layout)r!'
% locals())
keys.append(key)
layout_given = True
if layout is None:
layout = default
if set_layout is None:
set_layout = bool(layout)
return (layout, set_layout, get_layout) | 41a7a11e72ed70dee1456334a93a5cfe0651ec37 | 29,600 |
from bs4 import BeautifulSoup
def get_targets(html):
"""
Return bolded targeting parameters
"""
if html:
doc = BeautifulSoup(html, "html.parser")
return " ".join([b.get_text(" ") for b in doc.find_all("b")])
return "" | 04248637d3f77d4ed5b5365e60298e7bfb0c6933 | 29,601 |
def diff_possible(numbers, k):
"""
Given a list of sorted integers and a non negative
integer k, find if there exists 2 indicies i and j
such that A[i] - A[j] = k, i != j
"""
if k < 0:
raise ValueError('k can not be non negative')
# Find k since as long as i is not larger than k
# we do not even need to compare
if numbers[-1] < k:
return False
start_i = 0
while start_i < len(numbers):
if numbers[start_i] >= k:
break
else:
start_i += 1
for i in range(start_i, len(numbers)):
needed_num = numbers[i] - k
for j in reversed(range(0, i)):
if numbers[j] == needed_num:
return True
elif numbers[j] < needed_num:
# All hope is lost, we can never reach k again
break
return False | 54c45f24644c478dc48679c11c5217c0318af2b4 | 29,604 |
import tarfile
def smart_is_tarfile(filepath):
"""
:func:`tarfile.is_tarfile` plus error handling.
:param filepath: Filename.
:type filepath: str
"""
try:
istar = tarfile.is_tarfile(filepath)
except (OSError, IOError):
return False
else:
return istar | 4fb203685100204ea4a28d7854634628599801ce | 29,605 |
def to_cmd_string(unquoted_str: str) -> str:
"""
Add quotes around the string in order to make the command understand it's a string
(useful with tricky symbols like & or white spaces):
.. code-block:: python
>>> # This str wont work in the terminal without quotes (because of the &)
>>> pb_str = r"D:\Minab_4-DA&VHR\Minab_4-DA&VHR.shp"
>>> to_cmd_string(pb_str)
"\"D:\Minab_4-DA&VHR\Minab_4-DA&VHR.shp\""
Args:
unquoted_str (str): String to update
Returns:
str: Quoted string
"""
if not isinstance(unquoted_str, str):
unquoted_str = str(unquoted_str)
cmd_str = unquoted_str
if not unquoted_str.startswith('"'):
cmd_str = '"' + cmd_str
if not unquoted_str.endswith('"'):
cmd_str = cmd_str + '"'
return cmd_str | bdba5138daa580c34d49618da511ff0e20f192d4 | 29,607 |
from typing import Optional
from typing import Dict
from typing import Any
def define_by_run_func(trial) -> Optional[Dict[str, Any]]:
"""Define-by-run function to create the search space.
Ensure no actual computation takes place here. That should go into
the trainable passed to ``tune.run`` (in this example, that's
``easy_objective``).
For more information, see https://optuna.readthedocs.io/en/stable\
/tutorial/10_key_features/002_configurations.html
This function should either return None or a dict with constant values.
"""
# This param is not used in the objective function.
activation = trial.suggest_categorical("activation", ["relu", "tanh"])
trial.suggest_float("width", 0, 20)
trial.suggest_float("height", -100, 100)
# Define-by-run allows for conditional search spaces.
if activation == "relu":
trial.suggest_float("mult", 1, 2)
# Return all constants in a dictionary.
return {"steps": 100} | f8237b135e3a6467bdefd397f1da0ebaec0f4380 | 29,608 |
def rectangle_to_square(rectangle, width, height):
"""
Converts a rectangle in the image, to a valid square. Keeps the original
rectangle centered whenever possible, but when that requires going outside
the original picture, it moves the square so it stays inside.
Assumes the square is able to fit inside the original picture.
"""
from_x, from_y, to_x, to_y = rectangle
rectangle_width = to_x - from_x
rectangle_height = to_y - from_y
size = max(rectangle_width, rectangle_height)
x_center = from_x + rectangle_width // 2
y_center = from_y + rectangle_height // 2
from_x = x_center - size // 2
to_x = x_center + size // 2
from_y = y_center - size // 2
to_y = y_center + size // 2
# ensure fitting horizontally
if from_x < 0:
to_x = to_x - from_x
from_x = 0
elif to_x > width:
from_x = from_x - (to_x - width)
to_x = width
# ensure fitting vertically
if from_y < 0:
to_y = to_y - from_y
from_y = 0
elif to_y > height:
from_y = from_y - (to_y - height)
to_y = height
return from_x, from_y, to_x, to_y | e879cf81c1448f72d1d5326b0a8f964e47173f07 | 29,613 |
def check_treedepth(samples, max_treedepth=10, quiet=False, return_diagnostics=False):
"""Check transitions that ended prematurely due to maximum tree depth limit.
Parameters
----------
samples : ArviZ InferenceData instance
Contains samples to be checked. Must contain both `posterior`
and `samples_stats`.
max_treedepth: int, default 10
Maximum tree depth used in the calculation.
quiet : bool, default False
If True, do not print diagnostic result to the screen.
return_diagnostics : bool, default False
If True, return both a Boolean about whether the diagnostic
passed and the number of samples where the tree depth was too
deep. Otherwise, only return Boolean if the test passed.
Returns
-------
passed : bool
Return True if tree depth test passed. Return False otherwise.
n_too_deep : int, optional
Number of samplers wherein the tree depth was greater than
`max_treedepth`.
"""
n_too_deep = (samples.sample_stats.treedepth.values >= max_treedepth).sum()
n_total = samples.sample_stats.dims["chain"] * samples.sample_stats.dims["draw"]
if not quiet:
msg = "{} of {} ({}%) iterations saturated".format(
n_too_deep, n_total, 100 * n_too_deep / n_total
)
msg += " the maximum tree depth of {}.".format(max_treedepth)
print(msg)
pass_check = n_too_deep == 0
if not pass_check and not quiet:
print(
" Try running again with max_treedepth set to a larger value"
+ " to avoid saturation."
)
if return_diagnostics:
return pass_check, n_too_deep
return pass_check | ed949405b408841d4d716151187c65d2638b1b4e | 29,617 |
def inchesToMeters(inches):
"""Convert inches to meters."""
return inches * 0.0254 | b9f87ddc885474964ff59618bd560fb20ac9d7ff | 29,640 |
import bs4
def get_navigable_string_type(obj):
"""Get navigable string type."""
return bs4.NavigableString | 79d47783e0441a17fc3016218683dc19c7dc78f2 | 29,650 |
def convert_parentheses_back(text: str):
"""Replaces ( and ) tokens with -LRB- and -RRB-"""
return text.replace("(", "-LRB-").replace(")", "-RRB-") | 7bf23c858ade23d61c3d12b39cb3a76b840aefc0 | 29,651 |
def is_asc_sorted(lst: list) -> bool:
"""
Utility that tells whether a given list is already ascendentally sorted
with every item in the list greater than the previous.
:param lst: list to check
:return: true if and only if the given list is ascendentally sorted
"""
return all(lst[i+1] > lst[i] for i in range(0, len(lst) - 2)) | 9c1fcd2354196ca33c3f61fc91c17fa5cf6907a8 | 29,654 |
def identifyFileType(suffix):
"""Identify the file type and return correct syntax.
:suffix: file suffix
:returns: [inline comment syntax, multiple line comment syntax]
"""
if suffix == "py":
return "#", "\"\"\"", "\"\"\""
elif suffix == "c" or suffix == "h" or suffix == "cpp" or suffix == "hpp":
return "//", "/*", "*/"
elif suffix == "java":
return "//", "/*", "*/"
else:
return "not defined" | b4a6de0039fc7ca1459fffb56b0e95b884a10704 | 29,655 |
def parse_walltime(wt_arg):
""" Converts walltimes to format dd:hh:mm:ss.
"""
# Clean the wt
parts = wt_arg.split(":")
wt_clean = ["{0:02d}".format(int(value)) for value in parts]
# Pad with 00
wt_clean = ["00"] * (4 - len(wt_clean)) + wt_clean
# Join and return
return ":".join(wt_clean) | 85327866ccf738f4212324f258e7400318b6a2d1 | 29,659 |
def read_list(fn):
"""Reads a list from a file without using readline.
Uses standard line endings ("\n") to delimit list items.
"""
f = open(fn, "r")
s = f.read()
# If the last character in the file is a newline, delete it
if s[-1] == "\n":
s = s[:-1]
l = s.split("\n")
return l | 0b73082074914b824e93cceb18ea773a916db5bc | 29,660 |
def difference(f1_d, f2_d, out_f1_head, out_f2_head):
"""
Figures out the difference between two dictionaries
and reports the difference
Parameters
----------
f1_d : dict
Dictionary for first fasta, chromosome names as values
f2_d : dict
Dictionary for second fasta, chromosome names as values
out_f1_head : list
Dictionary of filtered out chromosomes from first fasta
out_f2_head : list
List of filtered out chromosomes from second fasta
Returns
-------
The dictionaries of chromosome names found in one fasta and not the other
nor in the filtered out chromosome names
"""
f1_not_f2 = [
f1_d[i]
for i in set(list(f1_d.keys())).difference(list(f2_d.keys()))
]
f1_not_f2_not_out = list(set(f1_not_f2) - set(list(out_f1_head)))
f1_not_f2_not_out.sort()
f2_not_f1 = [
f2_d[i]
for i in set(list(f2_d.keys())).difference(list(f1_d.keys()))
]
f2_not_f1_not_out = list(set(f2_not_f1) - set(list(out_f2_head)))
f2_not_f1_not_out.sort()
return(f1_not_f2_not_out, f2_not_f1_not_out) | 4f25fc4595fbc59f02121a772123413a9e2a61a6 | 29,663 |
def add_error_total_and_proportion_cols(
total_errs, total_rows, date,
errs_by_table, total_by_table,
aggregate_df_total, aggregate_df_error,
aggregate_df_proportion):
"""
Function adds a new column to the growing dataframes. This
column contains information depending on the dataframe in
question. The column may contain information about
a. the total number of rows
b. the total number of 'poorly defined' rows
c. the relative contribution of a particular table
to the number of 'poorly defined' rows
The column represents a particular date. Each row
represents a particular table type. The final row
is an 'aggregate' metric that is a sum of the
rows immediately above it.
:param
total_errs (int): total number of errors across all sites
for a particular date; across all tables
total_rows (int): total number of rows across all sites
for a particular date; across all tables
date (string): date used to index into the dictionaries above
errs_by_table (list): list of the total number of
poorly defined row counts across all sites.
sequence of the list parallels the alphabetical
order of the tables. has 'total' metric at the end.
total_by_table (list): list of the total number of row counts
across all sites. sequence of the list parallels the
alphabetical order of the tables. has 'total'
metric at the end.
aggregate_df_total (dataframe): dataframe that contains the
total number of rows across all sites. each column
is a date. each row is a table type. last row
is the total number of rows for a particular
date.
aggregate_df_error (dataframe): dataframe that contains
the total number of poorly defined rows across
all sites. each column is a date. each row is a table
type. last row is the total number of poorly defined
rows for a particular date.
aggregate_df_proportion (dataframe): dataframe that
shows the 'contribution' of each table to the
total number of poorly defined rows. for instance,
if a table has half of all of the 'poorly defined
rows' for a particular date, it will have a value of
0.5. each column is a date. each row is a table
type.
:return:
aggregate_df_total (dataframe): same as the df that
entered except now with an additional column
to represent the date in question
aggregate_df_error (dataframe): same as the df that
entered except now with an additional column
to represent the date in question
aggregate_df_proportion (dataframe): same as the df
that entered except now with an additional
column to represent the date in question
"""
# adding to the growing column
# total number of 'poorly defined' rows for a date
if total_errs > 0:
errs_by_table.append(total_errs)
else:
errs_by_table.append(float('NaN'))
# total number of rows for a table for the date
if total_rows > 0:
total_by_table.append(total_rows)
else:
total_by_table.append(float('NaN'))
# column for the 'total' rows; column for one date
aggregate_df_total[date] = total_by_table
# column for 'error' rows; column for one date
aggregate_df_error[date] = errs_by_table
# column for the contribution of each error type
succ_rate_by_table = []
for errors, total in zip(errs_by_table, total_by_table):
error_rate = round(errors / total * 100, 2)
success_rate = 100 - error_rate
succ_rate_by_table.append(success_rate)
aggregate_df_proportion[date] = succ_rate_by_table
return aggregate_df_error, aggregate_df_total, \
aggregate_df_proportion | 3f1e6b7aa675d0184cde7d7712e41b89d689a536 | 29,664 |
import yaml
def parse_str(source: str, model_content: str) -> dict[str, dict]:
"""Parse a string containing one or more yaml model definitions.
Args:
source: The file the content came from (to help with better logging)
model_content: The yaml to parse
Returns:
A dictionary of the parsed model(s). The key is the type name from the model and the
value is the parsed model root.
"""
parsed_models = {}
roots = yaml.load_all(model_content, Loader=yaml.FullLoader)
for root in roots:
if "import" in root:
del root["import"]
root_name = list(root.keys())[0]
parsed_models[root[root_name]["name"]] = root
return parsed_models | acbca7fb764b09c8ccb2b5d7e28748bbb74ad870 | 29,665 |
def int_scale(val, val_range, out_range):
"""
Scale val in the range [0, val_range-1] to an integer in the range
[0, out_range-1]. This implementation uses the "round-half-up" rounding
method.
>>> "%x" % int_scale(0x7, 0x10, 0x10000)
'7777'
>>> "%x" % int_scale(0x5f, 0x100, 0x10)
'6'
>>> int_scale(2, 6, 101)
40
>>> int_scale(1, 3, 4)
2
"""
num = int(val * (out_range-1) * 2 + (val_range-1))
dem = ((val_range-1) * 2)
# if num % dem == 0 then we are exactly half-way and have rounded up.
return num // dem | a58bd33dd0712444bbfbd91e4f988a44780de323 | 29,667 |
def dict_search(data: dict, key: str, depth: int = 3):
"""Search a key value in a dict, return None if not found.
Warn: This method can be slow due to the amount of depth
"""
data_keys = data.keys()
for keys in data_keys:
if keys == key:
return data[key]
if depth > 0:
for keys in data_keys:
if isinstance(data[keys], dict):
result = dict_search(data[keys], key, depth - 1)
if result:
return result | 94bf3753b8b37afb313983ff8a0d99a14b2e9b98 | 29,668 |
import importlib
def load_plugin(plugin):
"""Get the plugin module
"""
return importlib.import_module(plugin) | 5a59ee8f41e7a0e3d96e0582937a7f9eb7fa4be8 | 29,669 |
def bisection_search2(L, e):
"""
Implementation 2 for the divide-and-conquer algorithm
Complexity: O(log n)
:param L: List-object
:param e: Element to look for
:return: Boolean value if element has been found
"""
def helper(L, e, low, high):
if high == low:
return L[low] == e
mid = (low + high) // 2
if L[mid] == e:
return True
elif L[mid] > e:
if low == mid:
return False
else:
return helper(L, e, low, mid - 1)
else:
return helper(L, e, mid + 1, high)
if len(L) == 0:
return False
else:
return helper(L, e, 0, len(L) - 1) | d3bda3698b5a321ac6307fe2a068c4ec61d6c57b | 29,670 |
from importlib import import_module
def try_import_for_setup(module_name):
"""
Returns the imported module named :samp:`{module_name}`.
Attempts to import the module named :samp:`{module_name}` and
translates any raised :obj:`ImportError` into a :obj:`NotImplementedError`.
This is useful in benchmark :samp:`setup`, so that a failed import results in
the benchmark getting *skipped*.
:type module_name: :obj:`str`
:param module_name: Attempt to import this module.
:rtype: :obj:`module`
:returns: The imported module named :samp:`{module_name}`.
:raises NotImplementedError: if there is an :obj:`ImportError`.
"""
try:
module = import_module(module_name)
except ImportError as e:
raise NotImplementedError("Error during '%s' module import: %s." % (module_name, str(e)))
return module | 9dc45df6372276258f6b0b9aab2a151e9b4b75af | 29,671 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.