content
stringlengths 22
815k
| id
int64 0
4.91M
|
---|---|
def search_by_pattern(pattern, limit=20):
"""Perform a search for pattern."""
pattern_ = normalize_pattern(pattern)
db = get_db()
results = db.execute(
"""
SELECT json FROM places
WHERE document MATCH ?
ORDER BY rank DESC
LIMIT ?;
""",
(fts_pattern(pattern_), limit)
).fetchall()
return "[{}]".format(','.join([doc['json'] for doc in results]))
| 5,345,200 |
def gcd(a, b):
"""Greatest common divisor"""
return _gcd_internal(abs(a), abs(b))
| 5,345,201 |
def exp_create_database(db_name, demo, lang, user_password='admin', login='admin', country_code=None, phone=None):
""" Similar to exp_create but blocking."""
_logger.info('Create database `%s`.', db_name)
_create_empty_database(db_name)
_initialize_db(id, db_name, demo, lang, user_password, login, country_code, phone)
return True
| 5,345,202 |
def fix_cr(data):
"""Cosmic ray fixing function.
Args:
data (:class:`numpy.ndarray`): Input image data.
Returns:
:class:`numpy.dtype`: Fixed image data.
"""
m = data.mean(dtype=np.float64)
s = data.std(dtype=np.float64)
_mask = data > m + 3.*s
if _mask.sum()>0:
x = np.arange(data.size)
f = InterpolatedUnivariateSpline(x[~_mask], data[~_mask], k=3)
return f(x)
else:
return data
| 5,345,203 |
def update_user_edit_config_file(new_config_items):
"""
Update the settings to the user editable config file
"""
config = configparser.RawConfigParser()
# start with the current config settings
config_items = read_user_edit_config_file()
# update with the new config items
for section in new_config_items:
for name,value in new_config_items[section].items():
if section in config_items:
if name in config_items[section]:
config_items[section][name]=value
else:
sys.exit("ERROR: Unable to add new name ( " + name +
" ) to existing section ( " + section + " ) to " +
" config file: " + full_path_user_edit_config_file)
else:
sys.exit("ERROR: Unable to add new section ( " + section +
" ) to config file: " + full_path_user_edit_config_file)
for section in config_items:
config.add_section(section)
for name,value in config_items[section].items():
value=str(value)
if "file" in section or "folder" in section:
# convert to absolute path if needed
if not os.path.isabs(value):
value=os.path.abspath(value)
config.set(section,name,value)
try:
file_handle=open(full_path_user_edit_config_file,"wt")
config.write(file_handle)
file_handle.close()
except EnvironmentError:
sys.exit("Unable to write to the HUMAnN2 config file.")
| 5,345,204 |
def iou(box1, box2, iouType='segm'):
"""Compute the Intersection-Over-Union of two given boxes.
or the Intersection-Over box2.
Args:
box1: array of 4 elements [cx, cy, width, height].
box2: same as above
iouType: The kind of intersection it will compute.
'keypoints' is for intersection over box2 area.
Returns:
iou: a float number in range [0, 1]. iou of the two boxes.
"""
lr = min(box1[0]+0.5*box1[2], box2[0]+0.5*box2[2]) - \
max(box1[0]-0.5*box1[2], box2[0]-0.5*box2[2])
if lr > 0:
tb = min(box1[1]+0.5*box1[3], box2[1]+0.5*box2[3]) - \
max(box1[1]-0.5*box1[3], box2[1]-0.5*box2[3])
if tb > 0:
intersection = tb*lr
else:
intersection = 0
if(iouType == 'keypoints'):
box2_area = box2[2] * box2[3]
return intersection/box2_area
else:
union = box1[2]*box1[3]+box2[2]*box2[3]-intersection
return intersection/union
return 0
| 5,345,205 |
def transform_color(color1, color2, skipR=1, skipG=1, skipB=1):
"""
transform_color(color1, color2, skipR=1, skipG=1, skipB=1)
This function takes 2 color1 and color2 RGB color arguments, and then returns a
list of colors in-between the color1 and color2
eg- tj.transform_color([0,0,0],[10,10,20]) returns a list:-
[[0, 0, 0], [1, 1, 1], [2, 2, 2] ... [9, 9, 9], [10, 10, 10], [10, 10, 11] ... [10, 10, 20]]
This function is very useful for creating color fade or color transition effects in pygame.
There are 3 optional arguments, which are skip arguments set to 1 by default.
"""
L = []
if (color1[0] < color2[0]):
i = list(range(color1[0],
color2[0] + 1,
skipR))
else:
i = list(range(color2[0], color1[0] + 1, skipR))[::-1]
if i == []:
i = [color1[0]]
if (color1[1] < color2[1]):
j = list(range(color1[1],
color2[1] + 1,
skipG))
else:
j = list(range(color2[1], color1[1] + 1, skipG))[::-1]
if j == []:
j = [color1[1]]
if (color1[2] < color2[2]):
k = list(range(color1[2],
color2[2] + 1,
skipB))
else:
k = list(range(color2[2], color1[2] + 1, skipB))[::-1]
if k == []:
k = [color1[2]]
x = max(len(i), len(j), len(k))
for m in range(len(i), x):
i += [i[-1]]
for m in range(len(j), x):
j += [j[-1]]
for m in range(len(k), x):
k += [k[-1]]
for m in range(x):
l = [i[m], j[m], k[m]]
L += [l]
return L
| 5,345,206 |
def sandwich(func):
"""Write a decorator that prints UPPER_SLICE and
LOWE_SLICE before and after calling the function (func)
that is passed in (@wraps is to preserve the original
func's docstring)
"""
@wraps(func)
def wrapped(*args, **kwargs):
print(UPPER_SLICE)
func(*args, **kwargs)
print(LOWE_SLICE)
return wrapped
| 5,345,207 |
def as_dict(bdb_path, compact=True):
"""Get the state of a minter BerkeleyDB as a dict. Only the fields used by EZID are
included.
"""
with nog.bdb_wrapper.BdbWrapper(bdb_path, dry_run=False) as w:
return w.as_dict(compact)
| 5,345,208 |
def _ecg_findpeaks_ssf(signal, sampling_rate=1000, threshold=20, before=0.03, after=0.01):
"""From https://github.com/PIA-
Group/BioSPPy/blob/e65da30f6379852ecb98f8e2e0c9b4b5175416c3/biosppy/signals/ecg.py#L448.
- W. Zong, T. Heldt, G.B. Moody, and R.G. Mark. An open-source algorithm to detect onset of arterial
blood pressure pulses. In Computers in Cardiology, 2003, pages 259–262, 2003.
"""
# TODO: Doesn't really seems to work
# convert to samples
winB = int(before * sampling_rate)
winA = int(after * sampling_rate)
Rset = set()
length = len(signal)
# diff
dx = np.diff(signal)
dx[dx >= 0] = 0
dx = dx ** 2
# detection
(idx,) = np.nonzero(dx > threshold)
idx0 = np.hstack(([0], idx))
didx = np.diff(idx0)
# search
sidx = idx[didx > 1]
for item in sidx:
a = item - winB
if a < 0:
a = 0
b = item + winA
if b > length:
continue
r = np.argmax(signal[a:b]) + a
Rset.add(r)
# output
rpeaks = list(Rset)
rpeaks.sort()
rpeaks = np.array(rpeaks, dtype="int")
return rpeaks
| 5,345,209 |
def main() -> int:
"""
Builds/updates aircraft.json codes
"""
craft = {}
for line in AIRCRAFT_PATH.open().readlines():
code, _, name = line.strip().split("\t")
if code not in craft:
craft[code] = name
json.dump(craft, OUTPUT_PATH.open("w"))
return 0
| 5,345,210 |
def reflect_static_member(structured_cls, name):
"""Provide the type of 'name' which is a member of 'structured_cls'.
Arguments:
associative_cls: The type of the structured object (like a dict).
name: The name to be reflected. Must be a member of 'structured_cls'.
Returns:
The type of 'name' or None. Invalid names should return None,
whereas valid names with unknown type should return AnyType.
"""
raise NotImplementedError()
| 5,345,211 |
def bootstrap_mean(x, alpha=0.05, b=1000):
"""
Calculate bootstrap 1-alpha percentile CI of the mean from a sample x
Parameters
----------
x : 1d array
alpha : float
Confidence interval is defined as the
b : int
The number of bootstrap samples
Returns
-------
lb, ub : the lower and upper bounds of the confidence interval
"""
means = np.empty(b)
for ii in xrange(b):
idx = np.random.randint(0, len(x), len(x))
means[ii] = np.mean(x[idx])
sort_means = np.sort(means)
lb_idx = int(b * alpha/2)
ub_idx = int(b * (1-(alpha/2)))
return sort_means[lb_idx], sort_means[ub_idx]
| 5,345,212 |
def greet_users(names): # names is used as a python parameter
"""Greet a list of users"""
for name in names:
greeting = "Hello, " + name.title() + "!"
print(greeting)
| 5,345,213 |
def test_marginal_covs(with_tf_random_seed, ssm_setup):
""" Test that we generate the correct marginal means and covariances. """
ssm, array_dict = ssm_setup
transitions = ssm.num_transitions
marginal_covs = ssm.marginal_covariances
covs = [array_dict["P_0"]]
for i in range(transitions):
A_t = array_dict["A_s"][..., i, :, :]
Q_t = array_dict["Q_s"][..., i, :, :]
covs.append(np.einsum("...ij,...jk,...lk->...il", A_t, covs[-1], A_t) + Q_t)
np.testing.assert_allclose(marginal_covs, np.stack(covs, axis=-3))
| 5,345,214 |
def _penalize_token(log_probs, token_id, penalty=-1e7):
"""Penalize token probabilities."""
depth = log_probs.shape[-1]
penalty = tf.one_hot([token_id], depth, on_value=tf.cast(penalty, log_probs.dtype))
return log_probs + penalty
| 5,345,215 |
def get_data_home(data_home=None):
"""
Returns
-------
path: str
`data_home` if it is not None, otherwise a path to a directory into the
user HOME path.
"""
if data_home is None:
user_home = os.path.expanduser('~')
if user_home is None:
raise RuntimeError(
'You should specify at least your home directory with HOME env variable.')
return f'{os.path.join(user_home, BILLYS_WORKSPACE_NAME)}'
return data_home
| 5,345,216 |
def load_win32com(finder, module):
"""the win32com package manipulates its search path at runtime to include
the sibling directory called win32comext; simulate that by changing the
search path in a similar fashion here."""
baseDir = os.path.dirname(os.path.dirname(module.file))
module.path.append(os.path.join(baseDir, "win32comext"))
| 5,345,217 |
def _clear_mpi_env_vars():
"""
from mpi4py import MPI will call MPI_Init by default. If we spawn a child process that also calls MPI_Init and
has MPI environment variables defined, MPI will think that the child process is an MPI process just like the
parent and do bad things such as hang or crash.
This context manager is a hacky way to clear those environment variables temporarily such as when we are starting
multiprocessing Processes.
"""
with _clear_lock:
removed_environment = {}
for k, v in list(os.environ.items()):
for prefix in ["OMPI_", "PMI_"]:
if k.startswith(prefix):
removed_environment[k] = v
del os.environ[k]
try:
yield
finally:
os.environ.update(removed_environment)
| 5,345,218 |
def AddSourceArg(parser):
"""Adds argument for specifying source for the workflow."""
parser.add_argument(
'--source',
help='Location of a workflow source code to deploy. Required on first '
'deployment. Location needs to be defined as a path to a local file '
'with the source code.')
| 5,345,219 |
def plot_donut(df):
"""Generates a donut plot with the counts of 3 categories.
Parameters
----------
df : pandas.DataFrame
The DataFrame to be plotted.
"""
# We will only need 3 categories and 3 values.
labels = ["Positivo", "Negativo", "Neutro"]
positive = len(df[df["score"] > 0])
negative = len(df[df["score"] < 0])
neutral = len(df[df["score"] == 0])
values = [positive, negative, neutral]
colors = ["green", "orange", "yellow"]
explode = (0, 0, 0) # Explode a slice if required
plt.rcParams["font.size"] = 18
plt.rcParams["legend.fontsize"] = 20
plt.pie(values, explode=explode, labels=None,
colors=colors, autopct='%1.1f%%', shadow=False)
# We draw a circle in the Pie chart to make it a donut chart.
centre_circle = plt.Circle(
(0, 0), 0.75, color="#5C0E10", fc="#5C0E10", linewidth=0)
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
plt.axis("equal")
plt.legend(labels)
plt.savefig("donut.png", facecolor="#5C0E10")
| 5,345,220 |
def test_write_state(traj_path, dyn_path, discretizer, num_states):
"""Testing the writing function of the MDanalysis script
Args:
traj_path ([type]): [description]
dyn_path ([type]): [description]
discretizer ([type]): [description]
num_states ([type]): [description]
"""
topology = os.path.join(dirname, "Trajectories/ZIKV/startframe.pdb")
coordinates = os.path.join(dirname, "Trajectories/ZIKV/test.dcd")
base = os.path.join(dirname, "Trajectories/ZIKV/")
prefix = "ligand_view_"
traj_path = os.path.join(dirname, traj_path)
dyn_path = os.path.join(dirname, dyn_path)
time_ser, num_obs = load_parsed_dyno(traj_path=traj_path)
save_path = get_dir(traj_path)
proj = discretizer(time_ser=time_ser, num_states=num_states, save_path=save_path)
labels = smooth_projection_k_means(proj, num_states)
write_state(
labels=labels[:100], topology=topology, coordinates=coordinates, base=base
)
| 5,345,221 |
def minimize(function,
vs,
explicit=True,
num_correction_pairs=10,
tolerance=1e-05,
x_tolerance=0,
f_relative_tolerance=1e7,
initial_inverse_hessian_estimate=None,
max_iterations=1000,
parallel_iterations=1,
optimizer="l-bfgs",
trace=False,
logger=print):
"""
Takes a function whose arguments are subclasses of boa.core.AbstractVariable,
and performs some form of BFGS on it.
:param function:
:param vs: Structure of NTFO variables
:param explicit: If True, `function` must have the signature `function(*vs)`.
If False, `function` must have the signature `function()`
:param num_correction_pairs:
:param tolerance:
:param x_tolerance:
:param f_relative_tolerance:
:param initial_inverse_hessian_estimate:
:param max_iterations:
:param parallel_iterations:
:param logger:
:param trace:
:param optimizer:
:return:
"""
if optimizer not in AVAILABLE_OPTIMIZERS:
raise OptimizationError(f"Specified optimizer ({optimizer}) must be one of {AVAILABLE_OPTIMIZERS}!")
if not isinstance(vs, Iterable):
raise OptimizationError(f"Variables passed must be in an iterable structure!")
optimizer = AVAILABLE_OPTIMIZERS[optimizer]
float64_machine_eps = finfo(float64).eps
# Check if the function and the passed arguments are compatible
num_function_params = len(signature(function).parameters)
num_args = len(vs)
if explicit and num_function_params != num_args:
raise OptimizationError(f"Optimization target takes {num_function_params} argument(s) " \
f"but {num_args} were given!")
# These are chosen to match the parameters of
# scipy.optimizer.fmin_l_bfgs_b
optimizer_args = {"num_correction_pairs": num_correction_pairs,
"tolerance": tolerance, # This is pgtol in scipy
"x_tolerance": x_tolerance,
# This is eps * factr in scipy
"f_relative_tolerance": float64_machine_eps * f_relative_tolerance,
"initial_inverse_hessian_estimate": initial_inverse_hessian_estimate,
"max_iterations": max_iterations,
"parallel_iterations": parallel_iterations}
# Get the reparameterization of the
reparameterizations = get_reparametrizations(vs)
initial_position, bounds, shapes = recursive_flatten(reparameterizations)
def unflatten(xs):
return _recursive_unflatten(xs, bounds, shapes)
# Pull-back of the function to the unconstrained domain:
# Reparameterize the function such that instead of taking its original bounded
# arguments, it takes the unconstrained ones, and they get forward transformed.
def reparameterized_function(*args):
new_args = recursive_forward_transform(args, vs)
return function(*new_args)
def fn_with_grads(x, first_run=False):
if explicit:
# Get back the original arguments
args = unflatten(x)
with tf.GradientTape(watch_accessed_variables=False) as tape:
tape.watch(args)
value = reparameterized_function(*args)
gradients = tape.gradient(value, args)
else:
# If we're performing implicit optimization, we assign the parameter
# values to the watched variables at the start
values = unflatten(x)
recursive_assign(reparameterizations, values)
with tf.GradientTape(watch_accessed_variables=False) as tape:
tape.watch(reparameterizations)
value = function()
gradients = tape.gradient(value, reparameterizations)
if first_run:
for grad in gradients:
if grad is None:
raise OptimizationError("Given function does not depend on some of the given variables!")
# We must concatenate the gradients because lbfgs_minimize expects a single vector
gradients, _, _ = recursive_flatten(gradients)
return value, gradients
# Dry run to check if the optimization can be performed
fn_with_grads(initial_position, first_run=True)
optimizer_results = optimizer(fn_with_grads,
initial_position=initial_position,
**optimizer_args)
if trace:
logger(f"Optimizer evaluated the objective {optimizer_results.num_objective_evaluations.numpy()} times!")
logger(f"Optimizer terminated after "
f"{optimizer_results.num_iterations.numpy()}/{max_iterations} iterations!")
logger(f"Optimizer converged: {optimizer_results.converged.numpy()}")
logger(f"Optimizer diverged: {optimizer_results.failed.numpy()}")
optimum = unflatten(optimizer_results.position)
# Assign the results to the variables
recursive_assign(reparameterizations, optimum)
# Return the loss
return optimizer_results.objective_value, optimizer_results.converged, optimizer_results.failed
| 5,345,222 |
def variation_reliability(flow, gamma=1):
""" Calculates the flow variation reliability
Parameters
----------
flow: numpy array
flow values
gamma: float, optional
soft threshold
Returns
-------
variation reliability map (0 less reliable, 1 reliable)
"""
#compute central differences
gradx = np.gradient(flow[:, :, 0])
grady = np.gradient(flow[:, :, 1])
norm_grad = (gradx[0] ** 2 + gradx[1] ** 2 +
grady[0] ** 2 + grady[1] ** 2) / (0.01 * np.sum(flow ** 2, axis=2) + 0.002)
norm_grad[norm_grad > 1e2] = 0
return np.exp(-norm_grad / gamma)
| 5,345,223 |
def create_experiment_dirs(exp_dir):
"""
Create Directories of a regular tensorflow experiment directory
:param exp_dir:
:return summary_dir, checkpoint_dir:
"""
experiment_dir = os.path.realpath(os.path.join(os.path.dirname(__file__))) + "/experiments/" + exp_dir + "/"
summary_dir = experiment_dir + 'summaries/'
checkpoint_dir = experiment_dir + 'checkpoints/'
output_dir = experiment_dir + 'output/'
test_dir = experiment_dir + 'test/'
dirs = [summary_dir, checkpoint_dir, output_dir, test_dir]
try:
for dir_ in dirs:
if not os.path.exists(dir_):
os.makedirs(dir_)
print("Experiment directories created")
return experiment_dir, summary_dir, checkpoint_dir, output_dir, test_dir
except Exception as err:
print("Creating directories error: {0}".format(err))
exit(-1)
| 5,345,224 |
def sutherland_hodgman_polygon_clipping(subject_polygon, clip_polygon):
"""Sutherland-Hodgman polygon clipping.
.. note
This algorithm works in regular Cartesian plane, not in inverted y-axis image plane,
so make sure that polygons sent in are ordered clockwise in regular Cartesian sense!
Method reference:
`Sutherland-Hodgman <http://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm>`_
Reference code found at `Rosettacode
<http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python>`_
:param subject_polygon: A [n x 2] array of points representing the non-closed polygon to reduce.
:type subject_polygon: :py:class:`numpy.ndarray`
:param clip_polygon: A [m x 2] array of points representing the non-closed polygon to clip with.
:type clip_polygon: :py:class:`numpy.ndarray`
:return: A [r x 2] array of points representing the intersection polygon or :py:class:`None`
if no intersection is present.
:rtype: :py:class:`numpy.ndarray` or :py:class:`None`
"""
TOLERANCE = 1e-14
def inside(p):
# This ``inside`` function assumes y-axis pointing upwards. If one would
# like to rewrite this function to work with clockwise ordered coordinates
# in the image style, then reverse the comparison from ``>`` to ``<``.
return (cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])
def compute_intersection():
dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]]
dp = [s[0] - e[0], s[1] - e[1]]
n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
n2 = s[0] * e[1] - s[1] * e[0]
denominator = (dc[0] * dp[1] - dc[1] * dp[0])
if np.abs(denominator) < TOLERANCE:
# Lines were parallel.
return None
n3 = 1.0 / denominator
return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]
output_list = list(subject_polygon)
cp1 = clip_polygon[-1]
for clip_vertex in clip_polygon:
cp2 = clip_vertex
input_list = output_list
if not input_list:
return None
output_list = []
s = input_list[-1]
for subject_vertex in input_list:
e = subject_vertex
if inside(e):
if not inside(s):
intersection = compute_intersection()
if intersection is not None:
output_list.append(intersection)
output_list.append(e)
elif inside(s):
intersection = compute_intersection()
if intersection is not None:
output_list.append(intersection)
s = e
cp1 = cp2
# TODO: Verify that points are clockwise sorted here.
pnts_out = []
while len(output_list):
pnt = output_list.pop(0)
if not any([np.all(np.equal(pnt, unique_pnt)) for unique_pnt in pnts_out]):
pnts_out.append(pnt)
return np.array(pnts_out)
| 5,345,225 |
def main() -> None:
"""数当てゲームのメイン
"""
args = get_parser()
min_ans = int(args.min_ans)
max_ans = int(args.max_ans)
max_stage = int(args.max_stage)
mode = args.mode
if args.ans is not None:
ans = int(args.ans)
runner = number_guess3.NumberGuess(
min_ans=min_ans, max_ans=max_ans, max_stage=max_stage, ans=ans)
else:
runner = number_guess3.NumberGuess(
min_ans=min_ans, max_ans=max_ans, max_stage=max_stage)
stage, history = runner.run(mode=mode)
"""ここで、ansを決める"""
| 5,345,226 |
def countHitscore(evt, hitscore, hitscoreThreshold=200, outkey="predef: "):
"""A simple hitfinder that performs a limit test against an already defined hitscore
and adds the result to ``evt["analysis"][outkey + "isHit"]``, and
the hitscore to ``evt["analysis"][outkey + "hitscore"]``.
Args:
:evt: The event variable
:hitscore: A pre-defined hitscore
Kwargs:
:hitscoreThreshold(int): Events with hitscore above this threshold are hits, default=200
:outkey(str): Prefix of data key of resulting :func:`~backend.Record` object, default is "predef: "
:Authors:
Carl Nettelblad ([email protected]),
Benedikt J. Daurer
"""
hit = hitscore > hitscoreThreshold
v = evt["analysis"]
add_record(v, "analysis", outkey + "isHit", hit)
add_record(v, "analysis", outkey + "hitscore", hitscore)
| 5,345,227 |
def get_means(df: pd.DataFrame, *, matching_sides: bool,
matching_roots: bool) -> pd.Series:
"""
Calculates mean conditional probabilities from a given co-occurrence table
with filters restricting for matching sides and roots.
Args:
df: The co-occurrences.
matching_sides: Whether to consider pairs of sites with matching sides.
matching_roots: Whether to consider pairs of sites with matching roots.
Returns:
The mean conditional probabilities.
"""
return df.query('is_matching_sides == {} and '
'(reference_joint_type {} co_occurring_joint_type)'.format(
matching_sides, '=='
if matching_roots else '!=')).groupby([
'reference_joint_type', 'co_occurring_joint_type'
])['conditional_probability'].mean()
| 5,345,228 |
def main(
pathname: str,
sheetname: str='Sheet1',
min_row: int=None,
max_row: int=None,
min_col: int=None,
max_col: int=None,
openpyxl_kwargs: Dict=None
):
"""
main is the main function. It accepts details about a excel sheet and returns an HTML table matching it.
Arguments:
pathname: A path to the excel sheet
sheetname: The name of the sheet to convert
min_row: The minimum row to parse in the excel (1-based)
max_row: The maximum row to parse in the excel (1-based)
min_col: The minimum column to parse in the excel (1-based)
max_col: The maximum column to parse in the excel (1-based)
openpyxl_kwargs: A dicionary of arguments to pass to openpyxl.load_workbook
"""
def out_of_range(bounds):
'''bounds are of the form (left_col, top_row, right_col, bottom_row)'''
return (bounds[0] < (min_col or 0)) or (bounds[1] < (min_row or 0))
openpyxl_kwargs = openpyxl_kwargs or {} # just in case people are mutating openpyxl_kwargs between calls.
wb = openpyxl.load_workbook(pathname, **openpyxl_kwargs)
ws = wb[sheetname]
ws_meta = {
'themes': color_utilities.get_theme_colors(wb),
'merged_cell_ranges': ws.merged_cells.ranges,
'column_widths': {(openpyxl.utils.cell.column_index_from_string(i) - 1): math.ceil(x.width * 7) for i, x in ws.column_dimensions.items()}, # converting excel units to pixels
'default_col_width': ws.sheet_format.defaultColWidth or 64,
'row_heights': {(i - 1): x.height * (4 / 3) for i, x in ws.row_dimensions.items()}, # converting excel units to pixels
'default_row_height': ws.sheet_format.defaultRowHeight or 20,
'min_row': min_row or 1,
'min_col': min_col or 1,
'max_row': min(max_row or ws.max_row, ws.max_row),
'max_col': min(max_col or ws.max_column, ws.max_column),
}
parsed_sheet = []
candidate_merge_ranges = [x for x in ws.merged_cells.ranges if out_of_range(x.bounds)]
for i, row in enumerate(ws.iter_rows(min_row=min_row, max_row=max_row, min_col=min_col, max_col=max_col)):
parsed_row = []
for j, cell in enumerate(row):
if isinstance(cell, openpyxl.cell.cell.Cell):
parsed_row.append(ParsedCell(cell, ws_meta, i, j))
else:
for i, candidate_range in enumerate(candidate_merge_ranges):
if cell.coordinate in candidate_range:
parent_cell = ws.cell(row=candidate_range.bounds[1], column=candidate_range.bounds[0])
parsed_row.append(ParsedCell(parent_cell, ws_meta, i, j))
candidate_merge_ranges.pop(i)
break
parsed_sheet.append(parsed_row)
# it's important to first run background_color and then fix_borders, so that
# the border can be deleted on the cell in fix_background_color. Then you
# need to run fix_borders so their neighbors can also have their borders
# deleted. That's part of the reason we make default_border = False when
# running delete_side
fix_background_color(parsed_sheet)
fix_borders(parsed_sheet, ws_meta)
body = to_html(parsed_sheet)
return body
| 5,345,229 |
def get_go_module_path(package):
"""assumption: package name starts with <host>/org/repo"""
return "/".join(package.split("/")[3:])
| 5,345,230 |
def labelbooklets(
labels,
pagecount,
booklets="booklets.pdf",
output="labeled_booklets.pdf",
colfname="fname",
collname="lname",
colid="netID",
):
"""
Outputs a PDF containing labeled exams given a data frame of labels,
a PDF of unlabeled booklets, and the number of pages in each exam.
"""
# Extract pages from booklet pdf
pages = PdfReader(booklets, decompress=False).pages
pagex = [pagexobj(i) for i in pages]
# Set output path
c = canvas.Canvas(output, pagesize=letter)
# Select columns (order is important)
labels = labels[[colfname, collname, colid]]
# Truncate any string longer than 17 chars
labels = labels.applymap(func="{:.17}".format)
# Loop over all students to apply labels
for (i, fname, lname, netid) in labels.itertuples():
# Set font to fixed-wdith and set font size
c.setFont("Courier", 32)
# Extract the first page of this student's exam
c.doForm(makerl(c, pagex[i * pagecount]))
c.drawString(76, 481, fname.upper(), charSpace=7.8)
c.drawString(76, 418, lname.upper(), charSpace=7.8)
c.drawString(76, 355, netid.upper(), charSpace=7.8)
c.showPage()
# Loop over the rest of the pages in this student's exam
for page in pagex[i * pagecount + 1 : (i + 1) * pagecount]:
c.doForm(makerl(c, page))
c.showPage()
# Save the PDF file after processing all students
c.save()
print("Attempting to save output to " + output)
| 5,345,231 |
def test_adjust_axial_sz_px():
"""Test adjust_axial_sz_px."""
assert adjust_axial_sz_px(1, 16) == 16
assert adjust_axial_sz_px(2, 16) == 16
assert adjust_axial_sz_px(16, 16) == 16
assert adjust_axial_sz_px(17, 16) == 32
assert adjust_axial_sz_px(32, 16) == 32
| 5,345,232 |
def get_hports(obj, *args, **kwargs):
"""
get_hports(obj, ...)
Get hierarchical references to ports *within* an object.
Parameters
----------
obj : object, Iterable - required
The object or objects associated with this query. Queries return a collection of objects associated with the
provided object or objects that match the query criteria. For example, `sdn.get_instances(netlist, ...)` would
return all of the instances *within* the provided definition that match the additional criteria.
patterns : str, Iterable - optional, positional or named, default: wildcard
The search patterns. Patterns can be a single string or an Iterable collection of strings. Patterns can be
absolute or they can contain wildcards or regular expressions. If `patterns` is not provided, then it defaults
to a wildcard.
recursive : bool - optional, default: False
Specify if search should be recursive or not meaning that sub hierarchical pins within an instance are
included or not.
is_case : bool - optional, named, default: True
Specify if patterns should be treated as case sensitive. Only applies to patterns. Does not alter fast lookup
behavior (if namespace policy uses case insensitive indexing, this parameter will not prevent a fast lookup
from returning a matching object even if the case is not an exact match).
is_re: bool - optional, named, default: False
Specify if patterns are regular expressions. If `False`, a pattern can still contain `*` and `?` wildcards. A
`*` matches zero or more characters. A `?` matches upto a single character.
filter : function
This is a single input function that can be used to filter out unwanted virtual instances. If not specifed, all
matching virtual instances are returned. Otherwise, virtual instances that cause the filter function to evaluate
to true are the only items returned.
Returns
-------
href_ports : generator
The hierarchical references to ports associated with a particular object or collection of objects.
"""
# Check argument list
if len(args) == 1 and 'patterns' in kwargs:
raise TypeError("get_hports() got multiple values for argument 'patterns'")
if len(args) > 1 or any(x not in {'patterns', 'recursive', 'filter', 'is_case', 'is_re'} for x in
kwargs):
raise TypeError("Unknown usage. Please see help for more information.")
# Default values
filter_func = kwargs.get('filter', lambda x: True)
recursive = kwargs.get('recursive', False)
is_case = kwargs.get('is_case', True)
is_re = kwargs.get('is_re', False)
patterns = args[0] if len(args) == 1 else kwargs.get('patterns', ".*" if is_re else "*")
if isinstance(obj, (FirstClassElement, InnerPin, OuterPin, Wire)) is False:
try:
object_collection = list(iter(obj))
except TypeError:
object_collection = [obj]
else:
object_collection = [obj]
if all(isinstance(x, (HRef, FirstClassElement, InnerPin, OuterPin, Wire)) for x in object_collection) is False:
raise TypeError("get_hports() supports all netlist related objects and hierarchical references or a "
"collection of theses as the object searched, unsupported object provided")
if isinstance(patterns, str):
patterns = (patterns,)
assert isinstance(patterns, (FirstClassElement, InnerPin, OuterPin, Wire)) is False
return _get_hports(object_collection, patterns, recursive, is_case, is_re, filter_func)
| 5,345,233 |
def _command_from_cli() -> Command:
"""
Parse CLI arguments as a command.
:return: parsed command.
"""
parser = argparse.ArgumentParser(prog="curl")
parser.add_argument("url", help="Gemini URL to fetch")
parser.add_argument(
"-v", "--verbosity", action="count", default=0, help="Increase output verbosity"
)
parser.add_argument(
"-L", "--location", action="store_const", const=True, help="Follow redirects"
)
args = parser.parse_args()
if args.verbosity == 0:
# Default verbosity.
logging_level = logging.ERROR
elif args.verbosity == 1:
logging_level = logging.WARNING
elif args.verbosity == 2:
logging_level = logging.INFO
else: # >= 3
logging_level = logging.DEBUG
return Command(
url=args.url, logging_level=logging_level, follow_redirects=bool(args.location)
)
| 5,345,234 |
def binary_cross_entropy(preds, targets, name=None):
"""Computes binary cross entropy given `preds`.
For brevity, let `x = `, `z = targets`. The logistic loss is
loss(x, z) = - sum_i (x[i] * log(z[i]) + (1 - x[i]) * log(1 - z[i]))
Args:
preds: A `Tensor` of type `float32` or `float64`.
targets: A `Tensor` of the same type and shape as `preds`.
"""
eps = 1e-12
with ops.op_scope([preds, targets], name, "bce_loss") as name:
preds = ops.convert_to_tensor(preds, name="preds")
targets = ops.convert_to_tensor(targets, name="targets")
return tf.reduce_mean(-(targets * tf.log(preds + eps) +
(1. - targets) * tf.log(1. - preds + eps)))
| 5,345,235 |
def setup(app: Sphinx):
"""
:param app:
Passed by Sphinx.
"""
app.add_html_theme(
"piccolo_theme", os.path.abspath(os.path.dirname(__file__))
)
| 5,345,236 |
def get_organization(name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetOrganizationResult:
"""
Use this data source to retrieve basic information about a GitHub Organization.
## Example Usage
```python
import pulumi
import pulumi_github as github
test = github.get_organization(name="github")
```
:param str name: The name of the organization account
"""
__args__ = dict()
__args__['name'] = name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('github:index/getOrganization:getOrganization', __args__, opts=opts, typ=GetOrganizationResult).value
return AwaitableGetOrganizationResult(
description=__ret__.description,
id=__ret__.id,
login=__ret__.login,
members=__ret__.members,
name=__ret__.name,
node_id=__ret__.node_id,
plan=__ret__.plan,
repositories=__ret__.repositories)
| 5,345,237 |
def numerator_LGG(mfld_dim: int,
ambient_dim: array,
vol: array,
epsilon: array,
prob: float) -> array: # our theory
"""
Theoretical M * epsilon^2 / K, our formula
Parameters
----------
mfld_dim
K, dimensionality of manifold
ambient_dim
N, dimensionality of ambient space
vol
V, volume of manifold
epsilon
allowed distortion
prob
allowed failure probability
"""
onev = np.ones_like(epsilon)
Me_K = (np.log(vol / prob) / mfld_dim + 0.5 * np.log(27. / mfld_dim)
+ np.log(ambient_dim / 4.) + 1.5 * onev)
return 16 * Me_K
| 5,345,238 |
def group_nodes(node_list, tree_height):
"""
Groups a list of nodes.
"""
dict = OrderedDict()
for node in node_list:
nodelist = _make_node_list(GroupNode(node), tree_height)
if nodelist.get_name() not in dict:
dict[nodelist.get_name()] = nodelist
else:
dict[nodelist.get_name()].merge(nodelist)
return list(dict.values())
| 5,345,239 |
def power_over_line_rule_pos_rule(m, i, j, t):
"""
If decision variable m.var_x[i, j, t] is set to TRUE, the positive power over the line var_power_over_line is
limited by power_line_limit
:param m: complete pyomo model
:type m: pyomo model
:param i: startnode index of set_edge
:type i: int
:param j: endnode index of set_edge
:type j: int
:param t: type index of set_linetypes
:type t: int
:returns:
- **pyomo equality function**: pyomo rule
:rtype: function
"""
power_line_limit = m.var_x[i, j, t] \
* (m.dict_line_tech[t]['I_max_A'] * V_BASE * 10 ** 3) \
/ (S_BASE * 10 ** 6)
return m.var_power_over_line[i, j, t] <= power_line_limit
| 5,345,240 |
def join_tiles(tiles):
"""Reconstructs the image from tiles."""
return np.concatenate(np.concatenate(tiles, 1), 1)
| 5,345,241 |
def parallel_imap(func, args, pool: Union[Pool, DumbPool]) -> List[T]:
"""@TODO: Docs. Contribution is welcome."""
result = list(pool.imap_unordered(func, args))
return result
| 5,345,242 |
async def test_setup_component(hass):
"""Test setup component."""
config = {tts.DOMAIN: {"platform": "yandextts", "api_key": "1234567xx"}}
with assert_setup_component(1, tts.DOMAIN):
await async_setup_component(hass, tts.DOMAIN, config)
await hass.async_block_till_done()
| 5,345,243 |
def solve2(lines, max_total):
"""Solve the problem for Part 2."""
points = parse_points(lines)
xmin = min([p[0] for p in points])
xmax = max([p[0] for p in points])
ymin = min([p[1] for p in points])
ymax = max([p[1] for p in points])
size = 0
for x in range(xmin, xmax+1):
for y in range(ymin, ymax+1):
total = sum([dist((x, y), p) for p in points])
if total < max_total:
size += 1
return size
| 5,345,244 |
def main():
"""
関数の実行を行う関数。
Return:
"""
import random
def shuffle_dict(d):
"""
辞書(のキー)の順番をランダムにする
Args:
d: 順番をランダムにしたい辞書。
Return:
dの順番をランダムにしたもの
"""
keys = list(d.keys())
random.shuffle(keys)
return dict([(key, d[key]) for key in keys])
"""
input_node_dict: 全ノードについての情報を辞書にまとめたもの。dict()
key: ノードの名前。
value: リスト
第1要素: keyのノードが指すノードの集合。set()
第2要素: keyのノードのリンク先URL。str()
"""
input_node_dict = {"a": [set(), "example.html"],
"b": [{"a"}, "example.html"],
"c": [{"b", "e"}, "example.html"],
"d": [{"c", "a"}, "example.html"],
"e": [{"a"}, "example.html"],
"f": [{"e", "b", "a"}, "example.html"],
"g": [{"e"}, "example.html"],
"h": [{"g", "f"}, "example.html"],
"i": [{"a"}, "example.html"],
"j": [{"i"}, "example.html"],
"k": [{"j", "m"}, "example.html"],
"l": [{"i", "a"}, "example.html"],
"m": [{"i"}, "example.html"],
"n": [{"j", "m"}, "example.html"],
"o": [{"m", "l"}, "example.html"],
"p": [{"n", "k"}, "example.html"],
"q": [{"k", "o", "i"}, "example.html"],
}
node_list = create_node_list(shuffle_dict(input_node_dict))
remove_redundant_dependency(node_list)
assign_top_node(node_list)
assign_x_sequentially(node_list)
cut_edges_higher_than_1(node_list)
assign_x_sequentially(node_list)
sort_nodes_by_xcenter(node_list, downward=True)
sort_nodes_by_xcenter(node_list, downward=False)
node_attributes = node_list2node_dict(node_list)
# 有向グラフGraphの作成
graph = nx.DiGraph()
create_dependency_graph(node_list, graph)
# nodes_attrsを用いて各ノードの属性値を設定
nx.set_node_attributes(graph, node_attributes)
# グラフの描画
nx.draw_networkx(graph)
# cytoscape.jsの記述形式(JSON)でグラフを記述
graph_json = nx.cytoscape_data(graph, attrs=None)
with open('demo_sample.json', 'w') as f:
f.write(json.dumps(graph_json))
| 5,345,245 |
def register(cli, email, password, name, hint):
"""register a new account on server."""
log.debug("registering as:%s", email)
cli.client.register(email, password, name, hint)
del password
| 5,345,246 |
def test_keyword_exception(options, topology):
"""Tests if exceptions are thrown when keywords are missing"""
with pytest.raises(KeyError):
GeneralOptimizerPSO(5, 2, options, topology)
| 5,345,247 |
def scheme_load(*args):
"""Load a Scheme source file. ARGS should be of the form (SYM, ENV) or (SYM,
QUIET, ENV). The file named SYM is loaded in environment ENV, with verbosity
determined by QUIET (default true)."""
if not (2 <= len(args) <= 3):
expressions = args[:-1]
raise SchemeError('"load" given incorrect number of arguments: '
'{0}'.format(len(expressions)))
sym = args[0]
quiet = args[1] if len(args) > 2 else True
env = args[-1]
if (scheme_stringp(sym)):
sym = eval(sym)
check_type(sym, scheme_symbolp, 0, "load")
with scheme_open(sym) as infile:
lines = infile.readlines()
args = (lines, None) if quiet else (lines,)
def next_line():
return buffer_lines(*args)
read_eval_print_loop(next_line, env, quiet=quiet)
return okay
| 5,345,248 |
def drawVertexList_textured(vertex_list, tvertex_list):
"""Dibuja una lista de puntos point2/point3 con una lista Point2 de aristas
para modelos texturados"""
if len(vertex_list) >= 1:
if vertex_list[0].get_type() == POINT_2:
for vertex in range(len(vertex_list)):
glTexCoord2fv(tvertex_list[vertex].export_to_list())
glVertex2fv(vertex_list[vertex].export_to_list())
elif vertex_list[0].get_type() == POINT_3:
for vertex in range(len(vertex_list)):
glTexCoord2fv(tvertex_list[vertex].export_to_list())
glVertex3fv(vertex_list[vertex].export_to_list())
else:
raise Exception("el tipo de vertex_list debe ser POINT2 o POINT3")
else:
raise Exception("lista vacia")
| 5,345,249 |
def test_contrast():
"""
Feature: Test image contrast.
Description: Adjust image contrast.
Expectation: success.
"""
context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
image = np.random.random((32, 32, 3))
trans = Contrast(alpha=0.3, beta=0)
dst = trans(image)
print(dst)
| 5,345,250 |
def mask2idx(
mask: torch.Tensor,
max_length: Optional[int] = None,
padding_value: int = 0,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
E.g. input a tensor [[T T F F], [T T T F], [F F F T]] with padding value -1,
return [[0, 1, -1], [0, 1, 2], [3, -1, -1]]
:param mask: Mask tensor. Boolean. Not necessarily to be 2D.
:param max_length: If provided, will truncate.
:param padding_value: Padding value. Default to 0.
:return: Index tensor.
"""
shape_prefix, mask_length = mask.shape[:-1], mask.shape[-1]
flat_mask = mask.flatten(0, -2)
index_list = [torch.arange(mask_length, device=mask.device)[one_mask] for one_mask in flat_mask.unbind(0)]
index_tensor = pad_sequence(index_list, batch_first=True, padding_value=padding_value)
if max_length is not None:
index_tensor = index_tensor[:, :max_length]
index_tensor = index_tensor.reshape(*shape_prefix, -1)
return index_tensor, mask.sum(-1)
| 5,345,251 |
def generate_paths(data, path=''):
"""Iterate the json schema file and generate a list of all of the
XPath-like expression for each primitive value. An asterisk * represents
an array of items."""
paths = []
if isinstance(data, dict):
if len(data) == 0:
paths.append(f'{path}')
else:
for key, val in data.items():
if key == 'type':
if isinstance(val, list):
types = set(val)
else:
types = {val}
if types.isdisjoint({'object', 'array'}):
paths.append(f'{path}')
elif key == 'properties':
paths.extend(generate_paths(val, path))
else:
if key == 'items':
key = '*'
paths.extend(generate_paths(val, f'{path}/{key}'))
return paths
| 5,345,252 |
def parseCommandArgs(argv):
"""
Parse command line arguments
argv argument list from command line
Returns a pair consisting of options specified as returned by
OptionParser, and any remaining unparsed arguments.
"""
# create a parser for the command line options
parser = argparse.ArgumentParser(
description="EMPlaces data converter",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=command_summary_help
)
parser.add_argument('--version', action='version', version='%(prog)s '+EMP_VERSION)
parser.add_argument("--debug",
action="store_true",
dest="debug",
default=False,
help="Run with full debug output enabled. "+
"Also creates log file 'convert_emplaces_data.log' in the working directory"
)
parser.add_argument("command", metavar="COMMAND",
nargs=None,
help="sub-command, one of the options listed below."
)
parser.add_argument("args", metavar="ARGS",
nargs="*",
help="Additional arguments, depending on the command used."
)
# parse command line now
options = parser.parse_args(argv)
if options:
if options and options.command:
return options
print("No valid usage option given.", file=sys.stderr)
parser.print_usage()
return None
| 5,345,253 |
def run_hybrid_endpoint_overlap(topology_proposal, current_positions, new_positions):
"""
Test that the variance of the perturbation from lambda={0,1} to the corresponding nonalchemical endpoint is not
too large.
Parameters
----------
topology_proposal : perses.rjmc.TopologyProposal
TopologyProposal object describing the transformation
current_positions : np.array, unit-bearing
Positions of the initial system
new_positions : np.array, unit-bearing
Positions of the new system
Returns
-------
hybrid_endpoint_results : list
list of [df, ddf, N_eff] for 1 and 0
"""
# Create the hybrid system:
#hybrid_factory = HybridTopologyFactory(topology_proposal, current_positions, new_positions, use_dispersion_correction=True)
hybrid_factory = HybridTopologyFactory(topology_proposal, current_positions, new_positions, use_dispersion_correction=False) # DEBUG
# Get the relevant thermodynamic states:
nonalchemical_zero_thermodynamic_state, nonalchemical_one_thermodynamic_state, lambda_zero_thermodynamic_state, lambda_one_thermodynamic_state = utils.generate_endpoint_thermodynamic_states(
hybrid_factory.hybrid_system, topology_proposal)
nonalchemical_thermodynamic_states = [nonalchemical_zero_thermodynamic_state, nonalchemical_one_thermodynamic_state]
alchemical_thermodynamic_states = [lambda_zero_thermodynamic_state, lambda_one_thermodynamic_state]
# Create an MCMCMove, BAOAB with default parameters (but don't restart if we encounter a NaN)
mc_move = mcmc.LangevinDynamicsMove(n_restart_attempts=0, n_steps=100)
initial_sampler_state = SamplerState(hybrid_factory.hybrid_positions, box_vectors=hybrid_factory.hybrid_system.getDefaultPeriodicBoxVectors())
hybrid_endpoint_results = []
all_results = []
for lambda_state in (0, 1):
result, non, hybrid = run_endpoint_perturbation(alchemical_thermodynamic_states[lambda_state],
nonalchemical_thermodynamic_states[lambda_state], initial_sampler_state,
mc_move, 100, hybrid_factory, lambda_index=lambda_state)
all_results.append(non)
all_results.append(hybrid)
print('lambda {} : {}'.format(lambda_state,result))
hybrid_endpoint_results.append(result)
calculate_cross_variance(all_results)
return hybrid_endpoint_results
| 5,345,254 |
def _node_list(rawtext, text, inliner):
"""
Return a singleton node list or an empty list if source is unknown.
"""
source = inliner.document.attributes['source'].replace(os.path.sep, '/')
relsource = source.split('/docs/', 1)
if len(relsource) == 1:
return []
if text in rcParams:
refuri = 'https://matplotlib.org/stable/tutorials/introductory/customizing.html'
refuri = f'{refuri}?highlight={text}#the-matplotlibrc-file'
else:
path = '../' * relsource[1].count('/') + 'en/stable'
refuri = f'{path}/configuration.html?highlight={text}#table-of-settings'
node = nodes.Text(f'rc[{text!r}]' if '.' in text else f'rc.{text}')
ref = nodes.reference(rawtext, node, refuri=refuri)
return [nodes.literal('', '', ref)]
| 5,345,255 |
def enable_heater_shaker_python_api() -> bool:
"""Get whether to use the Heater-Shaker python API."""
return advs.get_setting_with_env_overload("enableHeaterShakerPAPI")
| 5,345,256 |
def main(args):
"""
This script will change some items TensorFlow Object Detection API training config file base on adaptive learning
config.ini
"""
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
with tf.gfile.GFile(args.pipeline, "r") as f:
proto_str = f.read()
text_format.Merge(proto_str, pipeline_config)
config = ConfigEngine(args.config)
pipeline_config.train_config.batch_size = int(config.get_section_dict('Student')['BatchSize'])
data_dir = Path(config.get_section_dict('Teacher')['ImagePath']).parent
pipeline_config.train_input_reader.tf_record_input_reader.input_path[:] = [os.path.join(str(data_dir),
"tfrecords",
"train.record")]
pipeline_config.eval_input_reader[:][0].tf_record_input_reader.input_path[:] = [os.path.join(str(data_dir),
"tfrecords",
"val.record")]
config_text = text_format.MessageToString(pipeline_config)
with tf.gfile.Open(args.pipeline, "wb") as f:
f.write(config_text)
logging.info("The config pipeline has been changes")
| 5,345,257 |
def solidityKeccak(abi_types, values):
"""
Executes keccak256 exactly as Solidity does.
Takes list of abi_types as inputs -- `[uint24, int8[], bool]`
and list of corresponding values -- `[20, [-1, 5, 0], True]`
"""
if len(abi_types) != len(values):
raise ValueError(
"Length mismatch between provided abi types and values. Got "
"{0} types and {1} values.".format(len(abi_types), len(values))
)
normalized_values = map_abi_data([abi_ens_resolver], abi_types, values)
hex_string = add_0x_prefix(''.join(
remove_0x_prefix(hex_encode_abi_type(abi_type, value))
for abi_type, value
in zip(abi_types, normalized_values)
))
return keccak(hexstr=hex_string)
| 5,345,258 |
def extract_frames(path_out, frame_rate=1, time_limit=10):
"""
Parameters
----------
path_out: str,
path to save the frames
time_limit: float, optional
time to record in seconds, default 10
frame_rate: int or float, optional
Extract the frame every "frame_rate" seconds, default 1
Returns
-------
"""
count = 0
vc = cv2.VideoCapture(0)
success, image = vc.read()
success = True
end_time = chrono() + time_limit
while success and chrono() < end_time:
vc.set(cv2.CAP_PROP_POS_MSEC, (count * 1000))
success, image = vc.read()
cv2.imwrite(path_out + "/frame%d.jpg" % count, image)
count += frame_rate
| 5,345,259 |
def check_segment_end(segment, duration):
"""
not all segments have an end set...
helper to check for that without concern
duration should be passed in to handle no segment end
"""
end = duration
#TODO: What about no end on segment?
# get end of content (total length)
if segment.end:
end = segment.end.total_seconds()
return end
| 5,345,260 |
def set_status(new_status: str):
"""
Sets the status for the bot
:param new_status: String to use for the status
"""
global status, raw_settings
status = raw_settings["status"] = new_status
save_json(os.path.join("config", "settings.json"), raw_settings)
| 5,345,261 |
def run_fib_recursive_mathy_cached(n):
"""Return Fibonacci sequence with length "n" using "fib_recursive_mathy_cached".
Args:
n: The length of the sequence to return.
Returns:
A list containing the Fibonacci sequence.
"""
return [fib_recursive_mathy_cached(i + 1) for i in range(n)]
| 5,345,262 |
async def test_metakg_500(client):
"""Test that when a KP gives a bad response to /meta_knowledge_graph,
we add a message to the log but continue running.
"""
QGRAPH = query_graph_from_string(
"""
n0(( ids[] CHEBI:6801 ))
n0(( categories[] biolink:ChemicalSubstance ))
n1(( categories[] biolink:Disease ))
n2(( categories[] biolink:PhenotypicFeature ))
n0-- biolink:treats -->n1
n1-- biolink:has_phenotype -->n2
"""
)
# Create query
q = {
"message": {"query_graph": QGRAPH},
"log_level": "WARNING",
}
# Run
response = await client.post("/query", json=q)
output = response.json()
# Check that we stored the error
assert "/meta_knowledge_graph for KP mychem" in output["logs"][0]["message"]
| 5,345,263 |
def test_ngram_regex_field_resolve(dataset_num_files_1, reader_factory):
"""Tests ngram.resolve_regex_field_names function
"""
fields = {
-1: ["^id.*", "sensor_name", TestSchema.partition_key],
0: ["^id.*", "sensor_name", TestSchema.partition_key],
1: ["^id.*", "sensor_name", TestSchema.partition_key]
}
ts_field = '^id$'
ngram = NGram(fields=fields, delta_threshold=10, timestamp_field=ts_field)
expected_fields = {TestSchema.id, TestSchema.id2, TestSchema.id_float, TestSchema.id_odd,
TestSchema.sensor_name, TestSchema.partition_key}
ngram.resolve_regex_field_names(TestSchema)
ngram_fields = ngram.fields
# Can't do direct set equality between expected fields and ngram.fields b/c of issue
# with `Collections.UnischemaField` (see unischema.py for more information). __hash__
# and __eq__ is implemented correctly for UnischemaField. However, a collections.UnischemaField
# object will not use the __hash__ definied in `petastorm.unischema.py`
for k in ngram_fields.keys():
assert len(expected_fields) == len(ngram_fields[k])
for curr_field in expected_fields:
assert curr_field in ngram_fields[k]
assert TestSchema.id == ngram._timestamp_field
| 5,345,264 |
def binning(LLRs_per_window,info,num_of_bins):
""" Genomic windows are distributed into bins. The LLRs in a genomic windows
are regarded as samples of a random variable. Within each bin, we calculate
the mean and population standard deviation of the mean of random variables.
The boundaries of the bins as well as the mean LLR and the standard-error
per bin are returned. """
#K,M,V = tuple(LLR_stat.keys()), *zip(*LLR_stat.values())
list_of_windows = [*LLRs_per_window.keys()]
bins = bin_genomic_windows(list_of_windows, info['chr_id'], num_of_bins)
X = [*bins]
LLR_matrix = [*LLRs_per_window.values()]
Y, E = [], []
for C in bins.values():
if C:
mean, std = mean_and_std_of_mean_of_rnd_var(LLR_matrix[C[0]:C[1]])
else:
mean, std = None, None
Y.append(mean)
E.append(std)
return X,Y,E
| 5,345,265 |
def conj(node: BaseNode,
name: Optional[Text] = None,
axis_names: Optional[List[Text]] = None) -> BaseNode:
"""Conjugate a `node`.
Args:
node: A `BaseNode`.
name: Optional name to give the new node.
axis_names: Optional list of names for the axis.
Returns:
A new node. The complex conjugate of `node`.
Raises:
AttributeError: If `node` has no `backend` attribute.
"""
if not hasattr(node, 'backend'):
raise AttributeError('Node {} of type {} has no `backend`'.format(
node, type(node)))
backend = node.backend
if not axis_names:
axis_names = node.axis_names
return Node(
backend.conj(node.tensor),
name=name,
axis_names=axis_names,
backend=backend)
| 5,345,266 |
def f1(
predictions: Union[list, np.array, torch.Tensor],
labels: Union[list, np.array, torch.Tensor],
):
"""Calculate F1 score for binary classification."""
return f1_score(y_true=labels, y_pred=predictions)
| 5,345,267 |
def length(v, squared=False, out=None, dtype=None):
"""Get the length of a vector.
Parameters
----------
v : array_like
Vector to normalize, can be Nx2, Nx3, or Nx4. If a 2D array is
specified, rows are treated as separate vectors.
squared : bool, optional
If ``True`` the squared length is returned. The default is ``False``.
out : ndarray, optional
Optional output array. Must be same `shape` and `dtype` as the expected
output if `out` was not specified.
dtype : dtype or str, optional
Data type for computations can either be 'float32' or 'float64'. If
`out` is specified, the data type of `out` is used and this argument is
ignored. If `out` is not provided, 'float64' is used by default.
Returns
-------
float or ndarray
Length of vector `v`.
"""
if out is None:
dtype = np.float64 if dtype is None else np.dtype(dtype).type
else:
dtype = np.dtype(out.dtype).type
v = np.asarray(v, dtype=dtype)
if v.ndim == 2:
assert v.shape[1] <= 4
toReturn = np.zeros((v.shape[0],), dtype=dtype) if out is None else out
v2d, vr = np.atleast_2d(v, toReturn) # 2d view of array
if squared:
vr[:, :] = np.sum(np.square(v2d), axis=1)
else:
vr[:, :] = np.sqrt(np.sum(np.square(v2d), axis=1))
elif v.ndim == 1:
assert v.shape[0] <= 4
if squared:
toReturn = np.sum(np.square(v))
else:
toReturn = np.sqrt(np.sum(np.square(v)))
else:
raise ValueError("Input arguments have invalid dimensions.")
return toReturn
| 5,345,268 |
def generateUniqueId():
"""
Generates a unique ID each time it is invoked.
Returns
-------
string
uniqueId
Examples
--------
>>> from arch.api import session
>>> session.generateUniqueId()
"""
return RuntimeInstance.SESSION.generateUniqueId()
| 5,345,269 |
def order_rep(dumper, data):
""" YAML Dumper to represent OrderedDict """
return dumper.represent_mapping(u'tag:yaml.org,2002:map', data.items(),
flow_style=False)
| 5,345,270 |
def match_format(
format_this: spec.BinaryInteger,
like_this: spec.BinaryInteger,
match_pad: bool = False,
) -> spec.BinaryInteger:
"""
will only match left pads, because pad size cannot be reliably determined
"""
output_format = get_binary_format(like_this)
output = convert(data=format_this, output_format=output_format)
if match_pad:
padded_size = get_binary_n_bytes(like_this)
output = add_binary_pad(output, padded_size=padded_size)
return output
| 5,345,271 |
def parse_nonterm_6_elems(expr_list, idx):
"""
Try to parse a non-terminal node from six elements of {expr_list}, starting
from {idx}.
Return the new expression list on success, None on error.
"""
(it_a, it_b, it_c, it_d, it_e, it_f) = expr_list[idx : idx + 6]
# Match against and_n.
if (
isinstance(it_a, Node)
and it_a.p.has_all("Bdu")
and it_b == OP_NOTIF
and isinstance(it_c, Node)
and it_c.t == NodeType.JUST_0
and it_d == OP_ELSE
and isinstance(it_e, Node)
and it_e.p.has_any("BKV")
and it_f == OP_ENDIF
):
node = Node().construct_and_n(it_a, it_e)
expr_list[idx : idx + 6] = [node]
return expr_list
# Match against andor.
if (
isinstance(it_a, Node)
and it_a.p.has_all("Bdu")
and it_b == OP_NOTIF
and isinstance(it_c, Node)
and it_c.p.has_any("BKV")
and it_d == OP_ELSE
and isinstance(it_e, Node)
and it_e.p.has_any("BKV")
and it_f == OP_ENDIF
):
node = Node().construct_andor(it_a, it_e, it_c)
expr_list[idx : idx + 6] = [node]
return expr_list
| 5,345,272 |
def make1d(u, v, num_cols=224):
"""Make a 2D image index linear.
"""
return (u * num_cols + v).astype("int")
| 5,345,273 |
def xkcd(scale=1, length=100, randomness=2):
"""
Turn on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode. This will
only have effect on things drawn after this function is called.
For best results, the "Humor Sans" font should be installed: it is
not included with Matplotlib.
Parameters
----------
scale : float, optional
The amplitude of the wiggle perpendicular to the source line.
length : float, optional
The length of the wiggle along the line.
randomness : float, optional
The scale factor by which the length is shrunken or expanded.
Notes
-----
This function works by a number of rcParams, so it will probably
override others you have set before.
If you want the effects of this function to be temporary, it can
be used as a context manager, for example::
with plt.xkcd():
# This figure will be in XKCD-style
fig1 = plt.figure()
# ...
# This figure will be in regular style
fig2 = plt.figure()
"""
return _xkcd(scale, length, randomness)
| 5,345,274 |
def team_size(data):
"""
Computes team size of each paper by taking the number of authors in 'authors'
Input:
- df: dataframe (dataset); or just the 'authors' column [pandas dataframe]
Output:
- team: vector of team_size for each paper of the given dataset [pandas series]
with team_size [int]
"""
team = pd.Series([len(i) for i in data['authors']]) # teamsize
return team
| 5,345,275 |
def header_to_date(header):
""" return the initial date based on the header of an ascii file"""
try:
starttime = datetime.strptime(header[2], '%Y%m%d_%H%M')
except ValueError:
try:
starttime = datetime.strptime(
header[2] + '_' + header[3], '%Y%m%d_%H'
)
except ValueError:
print("Warning: could not retrieve starttime from header,\
setting to default value ")
starttime = datetime(1970, 1, 1)
return starttime
| 5,345,276 |
def PhenylAlanineCenterNormal(residue):
""" Phenylalanine """
PHE_ATOMS = ["CG", "CD1", "CD2", "CE1", "CE2", "CZ"]
return RingCenterNormal(residue, PHE_ATOMS)
| 5,345,277 |
def test_is_character_at_index_not_with_character_at_end():
"""
Make sure that a string with one of the characters at the index is handled properly.
"""
# Arrange
input_string = "this is a test!"
start_index = len(input_string) - 1
valid_character = "!"
expected_output = False
# Act
actual_output = ParserHelper.is_character_at_index_not(
input_string, start_index, valid_character
)
# Assert
assert expected_output == actual_output
| 5,345,278 |
def _check_source(src, paths, vshape):
"""Checks (non exaustive) on the validity of a stochasticity source."""
# check compliance with the source protocol
if callable(src) and hasattr(src, 'paths') and hasattr(src, 'vshape'):
# check paths and vshape
paths_ok = (src.paths == paths)
try:
vshape_ok = True
np.broadcast_to(np.empty(src.vshape), vshape)
except ValueError:
vshape_ok = False
if not paths_ok or not vshape_ok:
raise ValueError(
'invalid stochasticity source: '
'expecting soruce paths={} and vshape broadcastable to {}, '
'but paths={}, vshape={} were found'
.format(paths, vshape, src.paths, src.vshape))
return
else:
raise ValueError(
"stochasticity source of type '{}', not compliant with the "
'source protocol (should be callable with properly '
'defined paths and vshape attributes)'
.format(type(src).__name__))
| 5,345,279 |
def test_emnist_exception():
"""
Test error cases for EMnistDataset
"""
logger.info("Test error cases for EMnistDataset")
error_msg_1 = "sampler and shuffle cannot be specified at the same time"
with pytest.raises(RuntimeError, match=error_msg_1):
ds.EMnistDataset(DATA_DIR, "byclass", "train", shuffle=False, sampler=ds.PKSampler(3))
ds.EMnistDataset(DATA_DIR, "mnist", "test", shuffle=False, sampler=ds.PKSampler(3))
error_msg_2 = "sampler and sharding cannot be specified at the same time"
with pytest.raises(RuntimeError, match=error_msg_2):
ds.EMnistDataset(DATA_DIR, "mnist", "train", sampler=ds.PKSampler(3), num_shards=2, shard_id=0)
ds.EMnistDataset(DATA_DIR, "mnist", "test", sampler=ds.PKSampler(3), num_shards=2, shard_id=0)
error_msg_3 = "num_shards is specified and currently requires shard_id as well"
with pytest.raises(RuntimeError, match=error_msg_3):
ds.EMnistDataset(DATA_DIR, "byclass", "train", num_shards=10)
ds.EMnistDataset(DATA_DIR, "mnist", "test", num_shards=10)
error_msg_4 = "shard_id is specified but num_shards is not"
with pytest.raises(RuntimeError, match=error_msg_4):
ds.EMnistDataset(DATA_DIR, "mnist", "train", shard_id=0)
ds.EMnistDataset(DATA_DIR, "mnist", "test", shard_id=0)
error_msg_5 = "Input shard_id is not within the required interval"
with pytest.raises(ValueError, match=error_msg_5):
ds.EMnistDataset(DATA_DIR, "byclass", "train", num_shards=5, shard_id=-1)
ds.EMnistDataset(DATA_DIR, "mnist", "test", num_shards=5, shard_id=-1)
with pytest.raises(ValueError, match=error_msg_5):
ds.EMnistDataset(DATA_DIR, "mnist", "train", num_shards=5, shard_id=5)
ds.EMnistDataset(DATA_DIR, "mnist", "test", num_shards=5, shard_id=5)
with pytest.raises(ValueError, match=error_msg_5):
ds.EMnistDataset(DATA_DIR, "byclass", "train", num_shards=2, shard_id=5)
ds.EMnistDataset(DATA_DIR, "mnist", "test", num_shards=2, shard_id=5)
error_msg_6 = "num_parallel_workers exceeds"
with pytest.raises(ValueError, match=error_msg_6):
ds.EMnistDataset(DATA_DIR, "mnist", "train", shuffle=False, num_parallel_workers=0)
ds.EMnistDataset(DATA_DIR, "mnist", "test", shuffle=False, num_parallel_workers=0)
with pytest.raises(ValueError, match=error_msg_6):
ds.EMnistDataset(DATA_DIR, "byclass", "train", shuffle=False, num_parallel_workers=256)
ds.EMnistDataset(DATA_DIR, "mnist", "test", shuffle=False, num_parallel_workers=256)
with pytest.raises(ValueError, match=error_msg_6):
ds.EMnistDataset(DATA_DIR, "mnist", "train", shuffle=False, num_parallel_workers=-2)
ds.EMnistDataset(DATA_DIR, "mnist", "test", shuffle=False, num_parallel_workers=-2)
error_msg_7 = "Argument shard_id"
with pytest.raises(TypeError, match=error_msg_7):
ds.EMnistDataset(DATA_DIR, "mnist", "train", num_shards=2, shard_id="0")
ds.EMnistDataset(DATA_DIR, "mnist", "test", num_shards=2, shard_id="0")
def exception_func(item):
raise Exception("Error occur!")
error_msg_8 = "The corresponding data files"
with pytest.raises(RuntimeError, match=error_msg_8):
data = ds.EMnistDataset(DATA_DIR, "mnist", "train")
data = data.map(operations=exception_func, input_columns=["image"], num_parallel_workers=1)
for _ in data.__iter__():
pass
with pytest.raises(RuntimeError, match=error_msg_8):
data = ds.EMnistDataset(DATA_DIR, "mnist", "train")
data = data.map(operations=vision.Decode(), input_columns=["image"], num_parallel_workers=1)
for _ in data.__iter__():
pass
with pytest.raises(RuntimeError, match=error_msg_8):
data = ds.EMnistDataset(DATA_DIR, "mnist", "train")
data = data.map(operations=exception_func, input_columns=["label"], num_parallel_workers=1)
for _ in data.__iter__():
pass
| 5,345,280 |
def get_labels(input_dir):
"""Get a list of labels from preprocessed output dir."""
data_dir = _get_latest_data_dir(input_dir)
labels_file = os.path.join(data_dir, 'labels')
with file_io.FileIO(labels_file, 'r') as f:
labels = f.read().rstrip().split('\n')
return labels
| 5,345,281 |
def documents_concordance(response: Response,
request: Request=Query(None, title=opasConfig.TITLE_REQUEST, description=opasConfig.DESCRIPTION_REQUEST),
paralangid: str=Query(None, title=opasConfig.TITLE_DOCUMENT_CONCORDANCE_ID, description=opasConfig.DESCRIPTION_DOCUMENT_CONCORDANCE_ID), # return controls
paralangrx: str=Query(None, title=opasConfig.TITLE_DOCUMENT_CONCORDANCE_RX, description=opasConfig.DESCRIPTION_DOCUMENT_CONCORDANCE_RX), # return controls
return_format: str=Query("HTML", title=opasConfig.TITLE_RETURNFORMATS, description=opasConfig.DESCRIPTION_RETURNFORMATS),
search: str=Query(None, title=opasConfig.TITLE_SEARCHPARAM, description=opasConfig.DESCRIPTION_SEARCHPARAM),
client_id:int=Depends(get_client_id),
client_session:str= Depends(get_client_session)
):
"""
## Function
<b>Returns the translation paragraph identified by the unique para ID(s) .</b>
## Return Type
models.Documents
## Status
This endpoint is working.
## Sample Call
http://localhost:9100/v2/Documents/Document/IJP.077.0217A/
## Notes
N/A
## Potential Errors
THE USER NEEDS TO BE AUTHENTICATED to return a para.
"""
caller_name = "[v2/Documents/Concordance]"
if opasConfig.DEBUG_TRACE:
print(f"{datetime.now().time().isoformat()}: {caller_name} {client_session}: ")
ret_val = None
item_of_interest = f"{paralangid}/{paralangrx}"
opasDocPermissions.verify_header(request, caller_name) # for debugging client call
log_endpoint(request, client_id=client_id, session_id=client_session, level="debug")
ocd, session_info = opasDocPermissions.get_session_info(request, response, session_id=client_session, client_id=client_id, caller_name=caller_name)
try:
ret_val = opasAPISupportLib.documents_get_concordance_paras( para_lang_id=paralangid,
para_lang_rx=paralangrx,
ret_format=return_format,
req_url=request.url._url,
session_info=session_info,
request=request
)
except Exception as e:
response.status_code=httpCodes.HTTP_400_BAD_REQUEST
status_message = f"ConcordanceError: Para Fetch: {e}"
logger.error(status_message)
ret_val = None
#ocd.record_session_endpoint(api_endpoint_id=opasCentralDBLib.API_DOCUMENTS_CONCORDANCE,
#session_info=session_info,
#params=request.url._url,
#item_of_interest=item_of_interest,
#return_status_code = response.status_code,
#status_message=status_message
#)
raise HTTPException(
status_code=response.status_code,
detail=status_message
)
else:
if ret_val != {}:
response.status_code = httpCodes.HTTP_200_OK
status_message = opasCentralDBLib.API_STATUS_SUCCESS
else:
# make sure we specify an error in the session log
# not sure this is the best return code, but for now...
status_message = "Not Found"
response.status_code = httpCodes.HTTP_404_NOT_FOUND
ocd.record_session_endpoint(api_endpoint_id=opasCentralDBLib.API_DOCUMENTS_CONCORDANCE,
session_info=session_info,
params=request.url._url,
item_of_interest=item_of_interest,
return_status_code = response.status_code,
status_message=status_message
)
if ret_val == {}:
raise HTTPException(
status_code=response.status_code,
detail=status_message
)
return ret_val
| 5,345,282 |
def query_yes_no(question, default=True):
"""Ask a yes/no question via intput() and return their answer.
"question" is a string that is presented to the user.
"default" is the default return value True or False
The "answer" return value is True for "yes" or False for "no".
https://stackoverflow.com/questions/3041986/apt-command-line-interface-like-yes-no-input
"""
valid = {"yes": True, "y": True, "ye": True, "yeet": True, "yerp": True, "Y": True, "N": False,
"no": False, "n": False}
if default is True:
prompt = " [Y/n]: "
else:
prompt = " [y/N]: "
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return default
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
| 5,345,283 |
def diamBiasK(diam, B, Kexcess, RshellRstar=2.5):
"""
diameter bias (>1) due to the presence of a shell
only works for scalar diam, B and Kexcess
validity: Kexcess>0 and Kexcess<0.1 and B*diam <~ 500
return 1 if Kexcess <= 0
"""
global __biasData, KLUDGE
d = np.abs(__biasData['Rshell/Rstar']-RshellRstar)
j0 = np.argsort(d)[0]
j1 = np.argsort(d)[1]
if Kexcess>0 and diam*B/2.2<__biasData['Bdw'][-1]:
tmp = [np.interp(diam*B/2.2, __biasData['Bdw'],
__biasData['bias'][j0,k,:])
for k in range(__biasData['bias'].shape[1]) ]
r0 = np.interp(np.log10(KLUDGE*Kexcess), np.log10(__biasData['fr'][j0,:]), tmp)
tmp = [np.interp(diam*B/2.2, __biasData['Bdw'],
__biasData['bias'][j1,k,:])
for k in range(__biasData['bias'].shape[1]) ]
r1 = np.interp(np.log10(KLUDGE*Kexcess), np.log10(__biasData['fr'][j0,:]), tmp)
return r0 + (r1-r0)*(RshellRstar-__biasData['Rshell/Rstar'][j0])/\
(__biasData['Rshell/Rstar'][j1]-__biasData['Rshell/Rstar'][j0])
else:
return 1
| 5,345,284 |
def interpolate_poses_from_samples(time_stamped_poses, samples):
"""
Interpolate time stamped poses at the time stamps provided in samples.
The poses are expected in the following format:
[timestamp [s], x [m], y [m], z [m], qx, qy, qz, qw]
We apply linear interpolation to the position and use SLERP for
the quaternion interpolation.
"""
# Extract the quaternions from the poses.
quaternions = []
for pose in time_stamped_poses[:, 1:]:
quaternions.append(Quaternion(q=pose[3:]))
# interpolate the quaternions.
quaternions_interp = resample_quaternions_from_samples(
time_stamped_poses[:, 0], quaternions, samples)
# Interpolate the position and assemble the full aligned pose vector.
num_poses = samples.shape[0]
aligned_poses = np.zeros((num_poses, time_stamped_poses.shape[1]))
aligned_poses[:, 0] = samples[:]
for i in [1, 2, 3]:
aligned_poses[:, i] = np.interp(
samples,
np.asarray(time_stamped_poses[:, 0]).ravel(),
np.asarray(time_stamped_poses[:, i]).ravel())
for i in range(0, num_poses):
aligned_poses[i, 4:8] = quaternions_interp[i].q
return aligned_poses.copy()
| 5,345,285 |
def test_add_client(case, client_name, client=None, client_id=None, duplicate_client=None, check_errors=False,
log_checker=None):
"""
UC MEMBER_47 main test method. Tries to add a new client to a security server and check logs if
ssh_host is set.
:param case: MainController object
:param client_name: str - existing client name
:param client: dict|None - existing client and new subsystem data; this or client_id is required
:param client_id: str|None - existing client and new subsystem data as string; this or client is required
:param duplicate_client: dict|None - if set, existing client subsystem data (used for checking error messages)
:param check_errors: bool - True to check for error scenarios, False otherwise
:param unregistered_member: dict|None - if set, used for checking for correct messages when the member is unregistered
:param ssh_host: str|None - if set, Central Server SSH host for checking the audit.log; if None, no log check
:param ssh_user: str|None - CS SSH username, needed if cs_ssh_host is set
:param ssh_pass: str|None - CS SSH password, needed if cs_ssh_host is set
:param client_unregistered: bool|None - if True, client will always be confirmed (skip a few tests)
:return:
"""
self = case
def create_registration_request():
# UC MEMBER_47 1 - select to add a security server client
self.log('MEMBER_47 1 - select to add a security server client')
current_log_lines = None
self.logdata = []
if client is None:
client_data = xroad.split_xroad_subsystem(client_id)
else:
client_data = client
client_data['name'] = client_name
if log_checker:
current_log_lines = log_checker.get_line_count()
check_values = []
# Create a list of erroneous and/or testing values to be entered as client
check_value_errors = [
[['', client_data['class'], ''], 'Missing parameter: {0}', False],
[['', client_data['class'], client_data['subsystem']], 'Missing parameter: {0}', False],
# [[client_data['code'], client_data['class'], ''], 'Missing parameter: {2}', False],
[[256 * 'A', client_data['class'], client_data['subsystem']],
"Parameter '{0}' input exceeds 255 characters", False],
[[client_data['code'], client_data['class'], 256 * 'A'], "Parameter '{2}' input exceeds 255 characters",
False],
[[256 * 'A', client_data['class'], 256 * 'A'], "Parameter '{0}' input exceeds 255 characters", False],
[[' {0} '.format(client_data['code']), client_data['class'],
' {0} '.format(client_data['subsystem'])], CLIENT_ALREADY_EXISTS_ERROR, True]
]
# UC MEMBER_47 2, 3 - insert the X-Road identifier of the client and parse the user input
self.log('MEMBER_47 2, 3, 4 - insert the X-Road identifier of the client and parse the user input')
if check_errors:
# UC MEMBER_47 3a - check for erroneous inputs / parse user input
check_values += check_value_errors
self.log('MEMBER_47 3a - check for erroneous inputs')
if duplicate_client:
# UC MEMBER_47 4 - verify that a client does not already exist
self.log('MEMBER_47 4a - verify that the client does not already exist')
check_values += [[['{0}'.format(duplicate_client['code']), duplicate_client['class'],
'{0}'.format(duplicate_client['subsystem'])], 'Client already exists', False]]
# Try adding the client with different parameters (delete all added clients)
add_clients(self, check_values, instance=client_data['instance'], delete=False)
if current_log_lines:
# UC MEMBER_47 3a, 4a, 7 - Check logs for entries
self.log('MEMBER_47 3a, 4a, 7 - checking logs for: {0}'.format(self.logdata))
logs_found = log_checker.check_log(self.logdata, from_line=current_log_lines + 1)
self.is_true(logs_found,
msg='Some log entries were missing. Expected: "{0}", found: "{1}"'.format(self.logdata,
log_checker.log_output))
return create_registration_request
| 5,345,286 |
def get_data_unit_labels(data_unit: DataUnit) -> List[Attributes]:
"""
Extract important information from data_unit. That is, get only bounding_boxes and
associated classifications.
Args:
data_unit: The data unit to extract information from.
Returns: list of pairs of objects and associated answers for the particular data
unit.
"""
res = []
for obj in data_unit.objects:
# Classifications (are both on the object_answer.classifications and on the object.
# Store all nested classification info.
obj_answer = obj.object_answer
classes = [
ClassificationInfo(
ontology_id=obj.ontology_object.id, value=obj.value, name=obj.name
)
]
queue = obj_answer.classifications
while len(queue) > 0:
c = queue.pop(0)
# Skip text for now.
if (
not hasattr(c.ontology_object, "type")
or c.ontology_object.type == "text"
):
continue
classes.append(
ClassificationInfo(
ontology_id=c.ontology_object.id, value=c.value, name=c.name
)
)
if (
c.answers is not None
and isinstance(c.answers, list)
and len(c.answers) > 0
):
queue.extend(c.answers)
elif c.answers is not None:
raise ValueError(
f"I didn't expect to see this. What to do in this situation?\n{c.answers}"
)
# Bounding box and polygon
bbox = obj.bounding_box if hasattr(obj, "bounding_box") else None
polygon = obj.polygon if hasattr(obj, "polygon") else None
res.append(Attributes(bbox=bbox, polygon=polygon, classes=classes, du=obj))
return res
| 5,345,287 |
def mock_folder_contributions():
"""Mock all action functions and ensure they raise an error if they are called."""
with mock.patch(
"forester.folder_contributions.print_folder_contributions"
) as mock_contrib, mock.patch("forester.tree_info.print_tree_info") as mock_info:
mock_info.side_effect = RuntimeError(
"print_tree_info was unexpectedly called!"
)
yield mock_contrib
| 5,345,288 |
def calc_4points_bezier_path(svec, syaw, spitch, evec, eyaw, epitch, offset, n_points=100):
"""
Compute control points and path given start and end position.
:param sx: (float) x-coordinate of the starting point
:param sy: (float) y-coordinate of the starting point
:param syaw: (float) yaw angle at start
:param ex: (float) x-coordinate of the ending point
:param ey: (float) y-coordinate of the ending point
:param eyaw: (float) yaw angle at the end
:param offset: (float)
:return: (numpy array, numpy array)
"""
#dist = np.linalg.norm(svec - evec) / offset
dist = offset
control_points = np.array(
(svec,
svec + dist*np.array([np.cos(syaw)*np.cos(spitch), np.sin(syaw)*np.cos(spitch), np.sin(spitch)]),
evec - dist*np.array([np.cos(eyaw)*np.cos(epitch), np.sin(eyaw)*np.cos(epitch), np.sin(epitch)]),
evec))
path = calc_bezier_path(control_points, n_points=100)
return path, control_points
| 5,345,289 |
def permutationwithparity(n):
"""Returns a list of all permutation of n integers, with its first element being the parity"""
if (n == 1):
result = [[1,1]]
return result
else:
result = permutationwithparity(n-1)
newresult = []
for shorterpermutation in result:
for position in range(1,n+1):
parity = shorterpermutation[0]
for swaps in range(n-position):
parity = - parity
newpermutation = copy.deepcopy(shorterpermutation)
newpermutation.insert(position,n)
newpermutation[0] = parity
newresult.append(newpermutation)
return newresult
| 5,345,290 |
def _train_model(model: BertForValueExtraction, optimizer, scheduler, train_data_loader, val_data_loader) -> List[int]:
"""
Main method to train & evaluate model.
:param model: BertForValueExtraction object
:param optimizer: optimizer
:param scheduler: scheduler
:param train_data_loader: training DataLoader object
:param val_data_loader: validation DataLoader object
:return: List[int] - validation predictions
"""
val_predictions = []
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
logging.info(f"Using device: {device}")
for epoch_number in trange(EPOCHS, desc="Epoch"):
# put the model into training mode.
model.train()
# reset the total loss for this epoch.
total_loss = 0
# training loop
train_true_labels, train_predictions = [], []
for step, batch in enumerate(train_data_loader):
# add batch to gpu if available
batch = tuple(t.to(device) for t in batch)
b_input_ids, b_token_type_ids, b_labels = batch
# always clear any previously calculated gradients before performing a backward pass
model.zero_grad()
# forward pass
# This will return the loss (together with the model output) because we have provided the `labels`
outputs = model(b_input_ids, token_type_ids=b_token_type_ids, labels=b_labels)
# get the loss
loss = outputs[0]
# move logits and labels to CPU
logits = outputs[1].detach().cpu().numpy()
b_labels = b_labels.to("cpu").numpy()
train_predictions.extend(logits.argmax(1))
train_true_labels.extend(b_labels)
# perform a backward pass to calculate the gradients
loss.backward()
# track train loss
total_loss += loss.item()
# clip the norm of the gradient
# this is to help prevent the "exploding gradients" problem
torch.nn.utils.clip_grad_norm_(parameters=model.parameters(), max_norm=MAX_GRAD_NORM)
# update parameters
optimizer.step()
# Update the learning rate
scheduler.step()
# calculate the average loss over the training data.
avg_train_loss = total_loss / len(train_data_loader)
logging.info(f"Average train loss on epoch {epoch_number}: {avg_train_loss}")
accuracy = accuracy_score(train_predictions, train_true_labels)[0]
logging.info(f"Train Accuracy on epoch {epoch_number + 1}: {accuracy}")
# Put the model into evaluation mode
model.eval()
# reset the validation loss for this epoch
eval_loss, eval_accuracy = 0, 0
val_predictions, true_labels = [], []
for batch in val_data_loader:
batch = tuple(t.to(device) for t in batch)
b_input_ids, b_token_type_ids, b_labels = batch
# telling the model not to compute or store gradients, saving memory and speeding up validation
with torch.no_grad():
# forward pass, calculate logit predictions
# this will return the logits rather than the loss because we have not provided labels
outputs = model(b_input_ids, token_type_ids=b_token_type_ids, labels=b_labels)
# move logits and labels to CPU
logits = outputs[1].detach().cpu().numpy()
b_labels = b_labels.to("cpu").numpy()
# calculate the accuracy for this batch of test sentences
eval_loss += outputs[0].mean().item()
val_predictions.extend(logits.argmax(1))
true_labels.extend(b_labels)
eval_loss = eval_loss / len(val_data_loader)
logging.info(f"Validation loss on epoch {epoch_number + 1}: {eval_loss}")
accuracy = accuracy_score(val_predictions, true_labels)[0]
logging.info(f"Validation Accuracy on epoch {epoch_number + 1}: {accuracy}")
logging.info("\n")
return [val_prediction.tolist()[0] for val_prediction in val_predictions]
| 5,345,291 |
def mass_at_two_by_counting_mod_power(self, k):
"""
Computes the local mass at `p=2` assuming that it's stable `(mod 2^k)`.
Note: This is **way** too slow to be useful, even when k=1!!!
TO DO: Remove this routine, or try to compile it!
INPUT:
k -- an integer >= 1
OUTPUT:
a rational number
EXAMPLE::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1,1])
sage: Q.mass_at_two_by_counting_mod_power(1)
4
"""
R = IntegerModRing(2**k)
Q1 = self.base_change_to(R)
n = self.dim()
MS = MatrixSpace(R, n)
ct = sum([1 for x in mrange([2**k] * (n**2)) if Q1(MS(x)) == Q1]) ## Count the solutions mod 2^k
two_mass = ZZ(1)/2 * (ZZ(ct) / ZZ(2)**(k*n*(n-1)/2))
return two_mass
| 5,345,292 |
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up Hive thermostat based on a config entry."""
hive = hass.data[DOMAIN][entry.entry_id]
devices = hive.session.deviceList.get("sensor")
entities = []
if devices:
for description in SENSOR_TYPES:
for dev in devices:
if dev["hiveType"] == description.key:
entities.append(HiveSensorEntity(hive, dev, description))
async_add_entities(entities, True)
| 5,345,293 |
def get_paginiation_data(first_pagination_url, family, cazy_home, args, session):
"""Parse the first paginiation page and retrieve URLs to all pagination page for the Family.
:param first_pagination_url: str, URL to the fist page of the family
:param family: Family class instance, represents a unique CAZy family
:param cazy_home: str, URL to CAZy home page
:param args: cmd-line args parser
:param session: open SQL database session
Return dict of error messages if errors arise OR list of URLs to paginiation pages, and the
total number of proteins in the family.
"""
logger = logging.getLogger(__name__)
# retrieve a list of all page urls of protein tables for the CAZy family
first_pagination_page, error_message = get_page(
first_pagination_url, args, max_tries=args.retries,
)
if first_pagination_page is None:
logger.warning(
f"Could not connect to {first_pagination_url} after {args.retries} attempts\n"
f"The following error was raised:\n{error_message}\nTherefore, could not "
"retrieve all pagination pages URLs, therefore, cannot scrape proteins from "
f"{family.name}"
)
return(
{
"url": (
f"{first_pagination_url}\t{family.cazy_class}\t"
f"Failed to connect to first pagination page for {family.name}, therefore "
f"could not retrieve URLs to all paginiation pages\t{error_message}"
),
"format": None,
},
None,
)
# Get the URLS to all pages of proteins and the total number of proteins in the (sub)family
protein_page_urls, total_proteins = get_paginiation_page_urls(
first_pagination_url, first_pagination_page, cazy_home, family.name,
)
if total_proteins == 'Deleted family!':
# add family to the database
logger.warning(
f'{family.name} listed as "Deleted family" in CAZy.\nAdding family name to the database'
)
sql_interface.add_deleted_cazy_family(family.name, session)
return(
{
"url": None,
"format": (
f"{first_pagination_url}\t{family.cazy_class}\t{family.name} listed as "
"'Deleted family' in CAZy.\tAdded family name to the database"
),
},
None
)
elif total_proteins == 'Empty family':
# add family to the database
logger.warning(
f'{family.name} is an empty family, but not listed "Deleted family" in CAZy.\n'
'Adding family name to the database'
)
sql_interface.add_deleted_cazy_family(family.name, session)
return(
{
"url": None,
"format": (
f"{first_pagination_url}\t{family.cazy_class}\t{family.name} is empty in CAZy, "
"but not listed as Deleted fam.\tAdded family name to the database"
),
},
None
)
elif total_proteins == 'Failed Retrieval':
# add family to the database
logger.warning(
f"Could not retrieve total protiens count for {family.name}, appears to be empty\n"
"but not listed 'Deleted family' in CAZy.\nAdding family name to the database"
)
sql_interface.add_deleted_cazy_family(family.name, session)
return(
{
"url": None,
"format": (
f"{first_pagination_url}\t{family.cazy_class}\t{family.name} Could not "
"retrieve total protiens count\tAdded family name to the database"
),
},
None
)
elif len(protein_page_urls) == 0:
logger.warning(f"No protein page URLs found for {family.name}: {first_pagination_url}")
return(
{
"url": None,
"format": (
f"{first_pagination_url}\t{family.cazy_class}\tFailed to retrieve URLs to "
f"protein table pages for {family.name}\tNo specific error message availble."
),
},
None
)
else:
return protein_page_urls, total_proteins
| 5,345,294 |
def task(ctx, config):
"""
Loop a sequential group of tasks
example:
- loop:
count: 10
body:
- tasktest:
- tasktest:
:param ctx: Context
:param config: Configuration
"""
for i in range(config.get('count', 1)):
stack = []
try:
for entry in config.get('body', []):
if not isinstance(entry, dict):
entry = ctx.config.get(entry, {})
((taskname, confg),) = entry.iteritems()
log.info('In sequential, running task %s...' % taskname)
mgr = run_tasks.run_one_task(taskname, ctx=ctx, config=confg)
if hasattr(mgr, '__enter__'):
mgr.__enter__()
stack.append(mgr)
finally:
try:
exc_info = sys.exc_info()
while stack:
mgr = stack.pop()
mgr.__exit__(*exc_info)
finally:
del exc_info
| 5,345,295 |
def gravitationalPotentialEnergy(mass, gravity, y):
"""1 J = 1 N*m = 1 Kg*m**2/s**2
Variables: m=mass g=gravity constant y=height
Usage: Energy stored by springs"""
U = mass*gravity*y
return U
| 5,345,296 |
def subset_by_supported(input_file, get_coords, calls_by_name, work_dir, data,
headers=("#",)):
"""Limit CNVkit input to calls with support from another caller.
get_coords is a function that return chrom, start, end from a line of the
input_file, allowing handling of multiple input file types.
"""
support_files = [(c, tz.get_in([c, "vrn_file"], calls_by_name))
for c in convert.SUBSET_BY_SUPPORT["cnvkit"]]
support_files = [(c, f) for (c, f) in support_files if f and vcfutils.vcf_has_variants(f)]
if len(support_files) == 0:
return input_file
else:
out_file = os.path.join(work_dir, "%s-havesupport%s" %
utils.splitext_plus(os.path.basename(input_file)))
if not utils.file_uptodate(out_file, input_file):
input_bed = _input_to_bed(input_file, work_dir, get_coords, headers)
pass_coords = set([])
with file_transaction(data, out_file) as tx_out_file:
support_beds = " ".join([_sv_vcf_to_bed(f, c, out_file) for c, f in support_files])
tmp_cmp_bed = "%s-intersectwith.bed" % utils.splitext_plus(tx_out_file)[0]
cmd = "bedtools intersect -wa -f 0.5 -r -a {input_bed} -b {support_beds} > {tmp_cmp_bed}"
do.run(cmd.format(**locals()), "Intersect CNVs with support files")
for r in pybedtools.BedTool(tmp_cmp_bed):
pass_coords.add((str(r.chrom), str(r.start), str(r.stop)))
with open(input_file) as in_handle:
with open(tx_out_file, "w") as out_handle:
for line in in_handle:
passes = True
if not line.startswith(headers):
passes = get_coords(line) in pass_coords
if passes:
out_handle.write(line)
return out_file
| 5,345,297 |
def to_list(obj):
"""List Converter
Takes any object and converts it to a `list`.
If the object is already a `list` it is just returned,
If the object is None an empty `list` is returned,
Else a `list` is created with the object as it's first element.
Args:
obj (any object): the object to be converted
Returns:
A list containing the given object
"""
if isinstance(obj, list):
return obj
elif isinstance(obj, tuple):
return list(obj)
elif obj is None:
return []
else:
return [obj, ]
| 5,345,298 |
def remove(molecular_system, selection=None, frame_indices=None, to_form=None, syntaxis='MolSysMT'):
"""remove(item, selection=None, frame_indices=None, syntaxis='MolSysMT')
Remove atoms or frames from the molecular model.
Paragraph with detailed explanation.
Parameters
----------
item: molecular model
Molecular model in any of the supported forms by MolSysMT. (See: XXX)
selection: str, list, tuple or np.ndarray, default=None
Atoms selection over which this method applies. The selection can be given by a
list, tuple or numpy array of integers (0-based), or by means of a string following any of
the selection syntaxis parsable by MolSysMT (see: :func:`molsysmt.select`).
frame_indices: str, list, tuple or np.ndarray, default=None
XXX
syntaxis: str, default='MolSysMT'
Syntaxis used in the argument `selection` (in case it is a string). The
current options supported by MolSysMt can be found in section XXX (see: :func:`molsysmt.select`).
Returns
-------
item: molecular model
The result is a new molecular model with the same form as the input item.
Examples
--------
Remove chains 0 and 1 from the pdb: 1B3T.
>>> import molsysmt as m3t
>>> system = m3t.load('pdb:1B3T')
Check the number of chains
>>> m3t.get(system, n_chains=True)
8
Remove chains 0 and 1
>>> new_system = m3t.remove(system, 'chainid 0 1')
Check the number of chains of the new molecular model
>>> m3t.get(new_system, n_chains=True)
6
See Also
--------
:func:`molsysmt.select`
Notes
-----
There is a specific method to remove solvent atoms: molsysmt.remove_solvent and another one to
remove hydrogens: molsysmt.remove_hydrogens.
"""
from molsysmt.basic import select, extract
molecular_system = digest_molecular_system(molecular_system)
frame_indices = digest_frame_indices(frame_indices)
atom_indices_to_be_kept = 'all'
frame_indices_to_be_kept = 'all'
if selection is not None:
atom_indices_to_be_removed = select(molecular_system, selection=selection, syntaxis=syntaxis)
atom_indices_to_be_kept = complementary_atom_indices(molecular_system, atom_indices_to_be_removed)
if frame_indices is not None:
frame_indices_to_be_kept = complementary_frame_indices(molecular_system, frame_indices)
tmp_item = extract(molecular_system, selection=atom_indices_to_be_kept, frame_indices=frame_indices_to_be_kept, to_form=to_form)
tmp_item = digest_output(tmp_item)
return tmp_item
| 5,345,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.