content
stringlengths 22
815k
| id
int64 0
4.91M
|
---|---|
def track_progress(
iterable: Iterable,
name: Optional[str] = None,
total: Optional[int] = None,
update_label: bool = False,
label_func: Optional[Callable] = lambda x: x,
clear: Optional[bool] = True,
):
"""
simple tracking loop using rich progress
"""
if name is None:
name = ""
if total is None:
total = len(iterable)
console.clear_live()
with Progress(console=console, transient=clear) as progress:
task = progress.add_task(name, total=total)
for i in iterable:
yield i
if update_label:
description = f"{name}: {label_func(i)}"
else:
description = name
progress.update(task, advance=1, description=description)
| 7,900 |
def trainAndEvaluateKNN():
"""
auxiliary function to call train_KNearestNeighbour() on full dataset
takes no parameters and evaluates the currently loaded test set
"""
print('***Begin training KNN***')
knn = train_KNearestNeighbour(x_train, y_train)
print('***Begin evaluating KNN***')
modelResults(knn, x_test)
print("END PROGRAM\n\n")
| 7,901 |
def attach_common_event_handlers(
parser, result, errors, is_response
):
"""Attach common event handlers to a HTTPParser.
The ``result`` parameter must be ``dict`` that contains the
results of parsing.
The ``errors`` parameter must be a ``list`` of exceptions that happened.
"""
def on_error(ex):
errors.append(ex)
def on_method(method):
result['req_method'] = method
def on_uri(uri):
result['req_uri'] = uri
def on_version(ver):
result['http_version'] = ver
def on_reason(msg):
result['reason'] = msg
def on_status_code(code):
result['status_code'] = code
def on_header_name(field):
result['raw_headers'].append(field)
def on_header_value(value):
result['raw_headers'].append(value)
def on_data(chk):
result['body'].append(chk)
parser.on('header_name', on_header_name)
parser.on('header_value', on_header_value)
parser.on('data', on_data)
parser.on('error', on_error)
if is_response:
# It's a response.
parser.on('reason', on_reason)
parser.on('status_code', on_status_code)
parser.on('version', on_version)
else:
parser.on('req_method', on_method)
parser.on('req_uri', on_uri)
parser.on('version', on_version)
| 7,902 |
def _get_parse_pauli_sums():
"""Helper function to obtain the generator of the sampled list of the pauli
sum coefficients after parsing pauli sums."""
# TODO(jaeyoo) : this will be c++ op
def _parse_pauli_sums(pauli_sums, n_programs, n_ops):
"""Helper function to parse given pauli sums to collect observable
coefficients.
Currently `cirq.PauliSum` is not subscriptable, which means it is not
possible to construct a uniform-shape tensor whose elements are
consistently matched to `cirq.PauliString` inside of given `PauliSum`
because the order of `PauliString`'s can be different whenever accessed.
So, the current version of _parse_pauli_sums only consider a `PauliSum`
to be sampled, not a `PauliString`. The observable coefficients are then
sum of the absolute value of coefficients of `PauliString`'s in the
`PauliSum`.
Args:
pauli_sums : `tf.Tensor` of strings with shape [n_programs, n_ops]
representing output observables for each program.
n_programs: `tf.Tensor` of the number of programs.
n_ops: `tf.Tensor` of the number of pauli sums.
Returns:
observable_coeff_: `tf.Tensor` of real numbers. This involves the
coefficients of Pauli sum terms of the first PauliString.
It is directly used to calculate probabilities.
[n_programs, n_ops]
"""
pauli_sums = util.from_tensor(pauli_sums)
def get_pauli_sum_coeff(i):
def get_i_pauli_sum_coeff(j):
# Because PauliSum object is not subscriptable, use for-loop.
# pauli_sums[i][j] : j-th `PauliSum` of i-th program.
return tf.reduce_sum(
tf.abs([
pstring.coefficient.real for pstring in pauli_sums[i][j]
]))
return tf.map_fn(get_i_pauli_sum_coeff,
tf.range(n_ops),
dtype=tf.float32)
observable_coeff = tf.map_fn(get_pauli_sum_coeff,
tf.range(n_programs),
dtype=tf.float32)
return observable_coeff
def parse_pauli_sums_generator(pauli_sums, n_programs, n_ops):
"""tf.py_function wrapper generator of _parse_programs()."""
# observable_coeff has the shape of [n_programs, n_ops]
observable_coeff = tf.py_function(func=_parse_pauli_sums,
inp=[
tf.stop_gradient(pauli_sums),
tf.stop_gradient(n_programs),
tf.stop_gradient(n_ops),
],
Tout=tf.float32)
return observable_coeff
return parse_pauli_sums_generator
| 7,903 |
def is_fully_defined(x):
"""Returns True iff `x` is fully defined in every dimension.
For more details, see `help(tf.TensorShape.is_fully_defined)`.
Args:
x: object representing a shape; convertible to `tf.TensorShape`.
Returns:
is_fully_defined: `bool` indicating that the shape is fully known.
"""
return tf.TensorShape(x).is_fully_defined()
| 7,904 |
def make_shell_context():
"""
Creates a python REPL with several default imports
in the context of the current_app
:return:
"""
return dict(current_app=current_app)
| 7,905 |
def recommend_hybrid_user(
df, model, interactions, user_id, user_dict,
item_dict, topn, new_only=True, threshold=3,
show=True):
"""Function to produce user recommendations. Hybrid version of
recommend_known_user
Args:
model: trained matrix factorization model
interactions: dataset used for training the model
user_id: user ID for which we need to generate recommendation
user_dict: Dictionary type input containing user_id as key and
interaction_index as value
item_dict: Dictionary type input containing item_id as key and
item_name as value
threshold: value above which the rating is favorable in interaction
matrix
topn: Number of output recommendation needed
new_only: whether to only recommend items that users have not visited
show: whether to show the result of function
Returns:
Prints list of items the given user has already visited
Prints list of N recommended items which user hopefully will be
interested in
"""
print('Recommending items for user {}...'.format(user_id))
n_users, n_items = interactions.shape
user_features, item_features, user_x, _ = feature_matrix(
df, user_id=user_id)
scores = pd.Series(model.predict(
user_x, interactions.values[user_x, :], user_features=user_features,
item_features=item_features))
scores.index = interactions.columns
scores = list(pd.Series(scores.sort_values(ascending=False).index))
known_items = list(pd.Series(
interactions.loc[user_id, :]
[interactions.loc[user_id, :] > threshold].index).sort_values(
ascending=False))
if new_only:
scores = [x for x in scores if x not in known_items]
item_list = scores[:topn]
known_items = list(pd.Series(known_items).apply(lambda x: item_dict[x]))
recommended_items = list(pd.Series(item_list).apply(
lambda x: item_dict[x]))
if show is True:
print("Known Likes:")
counter = 1
for i in known_items:
print(str(counter) + '- ' + i)
counter += 1
print("Recommended Items:")
counter = 1
for i in recommended_items:
print(str(counter) + '- ' + i)
counter += 1
return item_list
| 7,906 |
def addTopic(self, id, title='', REQUEST=None):
""" Create an empty topic.
"""
topic = Topic(id)
topic.id = id
topic.title = title
self._setObject(id, topic, suppress_events=True)
if REQUEST is not None:
REQUEST['RESPONSE'].redirect('manage_main')
| 7,907 |
def test_est_params_default_method():
"""Assert that custom parameters overwrite the default ones."""
trainer = DirectClassifier("RF", est_params={"n_jobs": 3}, random_state=1)
trainer.run(bin_train, bin_test)
assert trainer.rf.estimator.get_params()["n_jobs"] == 3
assert trainer.rf.estimator.get_params()["random_state"] == 1
| 7,908 |
def i(mu_i, mu_ij, N) :
"""Calcule le tableau I[i, j]"""
return [[I_ij(i, j, mu_i, mu_ij, N) for j in range(0, N)] for i in range(0, N)]
| 7,909 |
def format_datetime(this, date, date_format=None):
"""Convert datetime to a required format."""
date = dateutil.parser.isoparse(date)
if date_format is None:
date_format = "%d-%m-%Y"
return date.strftime(date_format)
| 7,910 |
def _estimate_melting_levels(latitudes_deg, valid_time_unix_sec):
"""Estimates melting level at each point.
This estimate is based on linear regression with respect to latitude. There
is one set of regression coefficients for each month.
:param latitudes_deg: numpy array of latitudes (deg N).
:param valid_time_unix_sec: Valid time.
:return: melting_levels_m_asl: numpy array of melting levels (metres above
sea level), with same shape as `latitudes_deg`.
"""
month_index = int(
time_conversion.unix_sec_to_string(valid_time_unix_sec, '%m')
)
return (
MELT_LEVEL_INTERCEPT_BY_MONTH_M_ASL[month_index - 1] +
MELT_LEVEL_SLOPE_BY_MONTH_M_DEG01[month_index - 1] *
numpy.absolute(latitudes_deg)
)
| 7,911 |
def train_word2vec(infile, outfile, skipgram, loss, size, epochs):
"""
train_word2vec(args**) -> Takes the input file, the output file and the model hyperparameters as arguments and trains the model accordingly.
The model is saved at the output location.
Arguments
---------
infile : Input pre-processed wiki dump
outfile : Output directory to save the model.
skipgram : Layers of the model (0 - CBOW, 1 - Skipgram)
loss : Loss Function (0 - Negative Sampling, 1 - Heirarichal Loss)
size : Embedding size (100 ~ 300)
epochs : Number of epochs
"""
sentence = LineSentence(infile)
model = Word2Vec(sentence, sg=skipgram, hs=loss, size=size, alpha=0.05, window=5,
min_count=5, workers=3, iter=epochs)
model.save(outfile)
| 7,912 |
def test_child_events():
"""Test that evented lists bubble child events."""
# create a random object that emits events
class E:
test = Signal(str)
e_obj = E()
root: EventedList[E] = EventedList(child_events=True)
mock = Mock()
root.events.connect(mock)
root.append(e_obj)
assert len(e_obj.test) == 1
assert root == [e_obj]
e_obj.test.emit("hi")
assert mock.call_count == 3
expected = [
call(EmissionInfo(root.events.inserting, (0,))),
call(EmissionInfo(root.events.inserted, (0, e_obj))),
call(EmissionInfo(root.events.child_event, (0, e_obj, e_obj.test, ("hi",)))),
]
mock.assert_has_calls(expected)
del root[0]
assert len(e_obj.test) == 0
| 7,913 |
def do_sharedstoragepool_list(cs, args):
"""Output a list of sharedstoragepool."""
# sharedstoragepools = cs.sharedstoragepool.list(args.cluster)
sharedstoragepools = cs.sharedstoragepool.list()
_print_sharedstoragepool_list(sharedstoragepools)
| 7,914 |
def edit_municipality(self, request, form):
""" Edit a municipality. """
layout = EditMunicipalityLayout(self, request)
if form.submitted(request):
form.update_model(self)
request.message(_("Municipality modified."), 'success')
return redirect(layout.success_url)
if not form.errors:
form.apply_model(self)
return {
'layout': layout,
'form': form,
'button_text': _("Save"),
'cancel': layout.cancel_url,
}
| 7,915 |
def plot_period_transactions(
model,
max_frequency=7,
title="Frequency of Repeat Transactions",
xlabel="Number of Calibration Period Transactions",
ylabel="Customers",
**kwargs
):
"""
Plot a figure with period actual and predicted transactions.
Parameters
----------
model: lifetimes model
A fitted lifetimes model.
max_frequency: int, optional
The maximum frequency to plot.
title: str, optional
Figure title
xlabel: str, optional
Figure xlabel
ylabel: str, optional
Figure ylabel
kwargs
Passed into the matplotlib.pyplot.plot command.
Returns
-------
axes: matplotlib.AxesSubplot
"""
from matplotlib import pyplot as plt
labels = kwargs.pop("label", ["Actual", "Model"])
n = model.data.shape[0]
simulated_data = model.generate_new_data(size=n)
model_counts = pd.DataFrame(model.data["frequency"].value_counts().sort_index().iloc[:max_frequency])
simulated_counts = pd.DataFrame(simulated_data["frequency"].value_counts().sort_index().iloc[:max_frequency])
combined_counts = model_counts.merge(simulated_counts, how="outer", left_index=True, right_index=True).fillna(0)
combined_counts.columns = labels
ax = combined_counts.plot(kind="bar", **kwargs)
plt.legend()
plt.title(title)
plt.ylabel(ylabel)
plt.xlabel(xlabel)
return ax
| 7,916 |
def operate_monitor(params):
""" different apps has different required params"""
ret_obj = copy.deepcopy(RET_OBJ)
group_id = params.get("group_id", type=int, default=None)
app_name = params.get("app_name")
operate = "update" if key_exist(group_id, app_name) else "insert"
valid_key = "_".join([app_name, operate])
if valid_key not in param_valids:
raise CustomException("operate_monitor Not found corresponding valid function for %s" % app_name, 1005)
params = param_valids[valid_key](params)
api_create(params) if operate == "insert" else api_update(params)
ret_obj['msg'] = operate + " monitor successfully."
return ret_obj
| 7,917 |
def run_task(*_):
"""
Wrap DDPG training task in the run_task function.
:param _:
:return:
"""
env = TfEnv(gym.make('FetchReach-v1'))
action_noise = OUStrategy(env.spec, sigma=0.2)
policy = ContinuousMLPPolicy(
env_spec=env.spec,
name="Policy",
hidden_sizes=[256, 256, 256],
hidden_nonlinearity=tf.nn.relu,
output_nonlinearity=tf.nn.tanh,
input_include_goal=True,
)
qf = ContinuousMLPQFunction(
env_spec=env.spec,
name="QFunction",
hidden_sizes=[256, 256, 256],
hidden_nonlinearity=tf.nn.relu,
input_include_goal=True,
)
replay_buffer = HerReplayBuffer(
env_spec=env.spec,
size_in_transitions=int(1e6),
time_horizon=100,
replay_k=0.4,
reward_fun=env.compute_reward)
ddpg = DDPG(
env,
policy=policy,
policy_lr=1e-3,
qf_lr=1e-3,
qf=qf,
replay_buffer=replay_buffer,
plot=False,
target_update_tau=0.05,
n_epochs=50,
n_epoch_cycles=20,
max_path_length=100,
n_train_steps=40,
discount=0.9,
exploration_strategy=action_noise,
policy_optimizer=tf.train.AdamOptimizer,
qf_optimizer=tf.train.AdamOptimizer,
buffer_batch_size=256,
input_include_goal=True,
)
ddpg.train()
| 7,918 |
def construct_rgba_vector(img, n_alpha=0):
"""
Construct RGBA vector to be used to color faces of pcolormesh
This funciton was taken from Flamingo.
----------
Args:
img [Mandatory (np.ndarray)]: NxMx3 RGB image matrix
n_alpha [Mandatory (float)]: Number of border pixels
to use to increase alpha
----------
Returns:
rgba [Mandatory (np.ndarray)]: (N*M)x4 RGBA image vector
"""
alpha = np.ones(img.shape[:2])
if n_alpha > 0:
for i, a in enumerate(np.linspace(0, 1, n_alpha)):
alpha[:, [i, -2-i]] = a
rgb = img[:, :-1, :].reshape((-1, 3)) # we have 1 less faces than grid
rgba = np.concatenate((rgb, alpha[:, :-1].reshape((-1, 1))), axis=1)
if np.any(img > 1):
rgba[:, :3] /= 255.0
return rgba
| 7,919 |
def nice(val):
"""Make sure this value is nice"""
if pd.isna(val):
return None
return val
| 7,920 |
def retrieve_tree(issue_id):
"""Retrieve a tree of issues from Redmine, starting at `issue_id`."""
logging.info(f" Retrieving issue #{issue_id} ...")
params = {
'issue_id': issue_id
}
response = requests.get(ISSUES_ENDPOINT, params=params, headers=HEADERS)
data = json.loads(response.text)
issue = data['issues'][0]
issue['children'] = retrieve_children(issue_id)
return issue
| 7,921 |
def cmdline_args(argv: Sequence[str], options: Sequence[Option], *, process: callable = None,
error: callable = None, results: dict = None) -> (Dict, Sequence[str]):
"""
Take an array of command line args, process them
:param argv: argument array
:param options: sequence of options to parse
:param process: process function
:param error: error function
:param results: optional dict to contain results (alternative to process callable)
:return: parsed results, remaining unprocessed arguments
"""
def select_option(short_opt, long_opt):
selected_option = None
for current_opt in options:
if short_opt is not None and short_opt == current_opt.short:
selected_option = current_opt
break
elif long_opt is not None and current_opt.long is not None:
if current_opt.long.startswith(long_opt) or long_opt.startswith(current_opt.long):
selected_option = current_opt
break
else:
if error is not None:
if short_opt:
error(f"unknown short option '-{short_opt}'")
else:
error(f"unknown long option '--{long_opt}'")
return selected_option
def dispatch_option(_option: Option, _opt: str, _args):
if _option.fn is not None:
return _option.fn(_option, _opt, _args) if callable(_option.fn) else _option.fn
if process:
tmp = process(_option, _opt, _args)
if tmp is not None:
return tmp
return _args if _option.has_arg else True
if results is None:
results = dict()
index = skip_count = 0
saved_args = []
for index, arg in enumerate(argv):
if skip_count:
skip_count -= 1
elif arg.startswith('--'): # long arg
skip_count = 0
longopt = arg[2:]
option = select_option(None, longopt)
if option is None:
saved_args.append(f"--{longopt}")
else:
args = None
if option.has_arg:
if '=' in longopt:
longopt, args = longopt.split('=', maxsplit=1)
else:
skip_count += 1
args = argv[index + skip_count]
results[option.long] = dispatch_option(option, longopt, args)
elif arg.startswith('-'):
skip_count = 0
for opt in arg[1:]:
option = select_option(opt, None)
if option is None:
saved_args.append(f"-{opt}")
else:
if option.has_arg:
skip_count += 1
args = argv[index + skip_count] if option.has_arg else None
results[option.long] = dispatch_option(option, opt, args)
else:
break
return results, saved_args + [arg for arg in argv[index + skip_count:]]
| 7,922 |
def trailing_zeroes(value):
# type: (int) -> int
"""Count the number of trailing zeros in a given 8-bit integer"""
return CTZ_TABLE[value]
| 7,923 |
def test_text_tweet():
"""Ensure that text tweets are properly parsed."""
results = {
'tweets': 0,
'retweets': 0,
'media': []
}
parse_tweet(TEXT_TWEET, True, 'large', results)
assert results['tweets'] == 1
assert results['retweets'] == 0
assert len(results['media']) == 1
assert results['media'][0]['tweet_id'] == '123456'
assert results['media'][0]['original_tweet_id'] == '123456'
assert results['media'][0]['text'] == 'Hello world!'
| 7,924 |
def _calc_WaterCirculation(heat_load, CT_design, WBT, DBT, fixedCWT_ctrl, pump_ctrl, ignore_CT_eff, max_CT_eff=0.85):
"""Calculates the water circulation loop. Used by simulate_CT().
Parameters:
Returns:
All (time x CT) arrays as
HWT Hot water temp [pint, C]
CWT Cold water temp [pint, C]
waterflow Water mass flow rate [pint, kg/s]. This is the input water stream to the CTs.
Notes:
1) This routine determines the temperatures of the water circuit (HWT, CWT) and the water flow rate to
transfer the heat load to the CT.
2) The WBT serves as a lower limit to CWT.
(variables: WBT is an iterable (length nTime), whereas WBT2 is a 2d array (time x CT))
"""
nTime = len(WBT)
nCT = CT_design.shape[0]
# .......................................................... 1) Calc CWT (based on WBT) and approach
# i) CWT
if fixedCWT_ctrl:
raise NotImplementedError
# This ctrl is not as simple as setting CWT to rated, because what if ambient WBT + min approach is above this?
# CWT fixed at design value
# CWT = Q_(np.tile(CT_design['CWT [°C]'].values, (Nsimul, 1)), 'degC')
else:
# CWT from CT performance curves
perf_m = CT_design['CT perf slope'].values
perf_b = CT_design['CT perf y-int'].values
# time x CT
CWT = Q_(np.outer(WBT, perf_m) + np.tile(perf_b, (nTime, 1)), 'degC')
# ii) Approach
WBT2 = Q_(np.transpose(np.tile(WBT, (nCT, 1))), 'degC')
approach = CWT - WBT2
# .......................................................... 2) Calc water circulation loop
# (calc deltaT, waterflow, assuming loaded)
# Forms a time-invariant array with shape (time x CT) and as a Pint quantity
tile_and_pint = lambda arr, units: Q_(np.tile(arr, (nTime, 1)), units)
HWT_r = tile_and_pint(CT_design['HWT [°C]'].values, 'degC')
waterflow_r = tile_and_pint(CT_design['water flow [kg/s]'].values, 'kg/s')
if pump_ctrl == 'fixed HWT':
deltaT = HWT_r - CWT
waterflow = (heat_load / (cp_water * deltaT)).to_base_units()
elif pump_ctrl == 'range limit':
# Calc range as if HWT = HWT_r
deltaT = HWT_r - CWT
# i) Adjust deltaT
deltaT_min = np.tile(CT_design['Min Range [C°]'].values, (nTime, 1))
deltaT = Q_(np.clip((deltaT).magnitude, deltaT_min, None), 'delta_degC')
# ii) Calc water flow
waterflow = (heat_load / (cp_water * deltaT)).to_base_units()
elif pump_ctrl == 'c':
# Calc range & water flow as if HWT = HWT_r
deltaT = HWT_r - CWT
waterflow = (heat_load / (cp_water * deltaT)).to_base_units()
waterflow_units = waterflow.units
# i) Adjust water flow
# Clip violating values
waterflow_ub = np.tile((CT_design['Max per unit water flow'] * CT_design['water flow [kg/s]']).values,
(nTime, 1))
waterflow_lb = np.tile((CT_design['Min per unit water flow'] * CT_design['water flow [kg/s]']).values,
(nTime, 1))
_wf = np.clip(waterflow.magnitude, waterflow_lb, waterflow_ub)
# Back to pint
waterflow = Q_(_wf, waterflow_units)
# ii) Calc deltaT
deltaT = (heat_load / (cp_water * waterflow)).to('delta_degC')
else:
waterflow = waterflow_r
deltaT = (heat_load / (cp_water * waterflow)).to('delta_degC')
# .......................................................... 3) No-load fix
# This part is necessary for all conrtol modes because the operational limits applied
# in the step 2 assumed loaded operation. After this step, water flow and deltaT are final.
CT_load_mask = (heat_load != 0).astype('int') # 0 if no load, 1 otherwise
waterflow = waterflow * CT_load_mask
deltaT = deltaT * CT_load_mask
HWT = CWT + deltaT
# .......................................................... 4) HWT and CWT adjustment
# HWT cannot be less than DBT; in which case, HWT is limited to DBT and CWT rises.
# Vectorize DBT into (time x CT)
DBT = np.tile(DBT, (nCT, 1)).transpose()
HWT = Q_(np.maximum(HWT.magnitude, DBT), 'degC')
CWT = HWT - deltaT
# .......................................................... 5) Checks and return
assert waterflow.units == ureg.kg / ureg.s
assert deltaT.units == ureg.delta_degC, deltaT.units
# Check that CT efficiency is realistic. In practice, efficiency is 65-70% (normal operating conditions)
CT_eff = deltaT / (deltaT + approach)
assert ignore_CT_eff or np.all(CT_eff < max_CT_eff), \
"CT efficiency exceeded the limit: {}".format(CT_eff)
assert all(obj.shape == (nTime, nCT) for obj in (HWT, CWT, waterflow, deltaT, approach, CT_eff))
# Check energy balance
assert np.allclose(heat_load.magnitude, (cp_water * deltaT * waterflow).to(heat_load.units).magnitude)
res = {
'HWT': HWT,
'CWT': CWT,
'water flow': waterflow,
'range': deltaT,
'approach': approach,
'CT_eff': CT_eff,
}
return res
| 7,925 |
def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=None,
mode='w'
):
"""Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if installed
and found on the default search path). If neither tool is available,
raises DistutilsExecError. Returns the name of the output zip file.
"""
import zipfile
mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)
def visit(z, dirname, names):
for name in names:
path = os.path.normpath(os.path.join(dirname, name))
if os.path.isfile(path):
p = path[len(base_dir)+1:]
if not dry_run:
z.write(path, p)
log.debug("adding '%s'" % p)
if compress is None:
compress = (sys.version>="2.4") # avoid 2.3 zipimport bug when 64 bits
compression = [zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED][bool(compress)]
if not dry_run:
z = zipfile.ZipFile(zip_filename, mode, compression=compression)
os.path.walk(base_dir, visit, z)
z.close()
else:
os.path.walk(base_dir, visit, None)
return zip_filename
| 7,926 |
def read_dataset_from_csv(data_type, path):
"""Read dataset from csv
Args:
data_type (str): train/valid/test
Returns:
pd: data
"""
data = pd.read_csv(tf.io.gfile.glob(path + data_type + "*")[0])
return data
| 7,927 |
def _ReportMissing(missing):
"""Report missing utilities, then exit.
Args:
missing: List of missing utilities, as returned by
osutils.FindMissingBinaries. If non-empty, will not return.
"""
if missing:
raise SystemExit(
'The tool(s) %s were not found.\n'
'Please install the appropriate package in your host.\n'
'Example(ubuntu):\n'
' sudo apt-get install <packagename>' % ', '.join(missing))
| 7,928 |
def search_ignore_case(s, *keywords):
"""Convenience function to search a string for keywords. Case
insensitive version.
"""
acora = AcoraBuilder(keywords, ignore_case=True).build()
return acora.findall(s)
| 7,929 |
def print_caves():
""" Print out the current cave structure """
for number in cave_numbers:
print(number, ":", caves[number])
print('----------')
| 7,930 |
def _logger_setup(logger: logging.Logger,
header_label: str,
formatter: Formatter = None,
level: int = logging.INFO,
level_normalized: int = logging.INFO,
handler_delegate=Union[logging.StreamHandler,Iterable[logging.StreamHandler]],
**handler_kwargs) ->logging.Logger:
"""A convenience function for creating well named loggers with optional custom formatter.
This function will implement an already defined formatter for you if the formatter param is
None. For an example of a good general use logger see the example code at the bottom of this
file.
SPECIAL NOTE:
Although this function's signature allows the caller to pass virtually any logging.Handler
subclass into the handler_delegate parameter, I've only tested this functionality against
the logging.StreamHandler class. If you wish to use it for others you will likely encounter
bugs. But if you are up to the task it seems like it could potentially be a helpful tool for
allowing the instantiation of a wide array of utility loggers under a single interface.
:param header_label:
:param logger: an initialized logger object that needs to have its formatter and optinoal handlers set.
:param child_name: The auxiliary logger you wish to create to handle some specific task. The
logger which maps to this child will set its level, handlers, and formatters
according to your inputs, allowing you to specify many different loggers to
manage data output in a form that suites you.
:type child_name: A string
:param formatter: An optional parameter that specifies the manner in which you wish to format
the available logging-event-_data as well as how you wish to present the
message _data for your log events. The default formatter will take one of
two styles, based the given `level`.
For level==logging.INFO (20) and bellow:
log messages will be presented in two parts.
* First, a header line that's formatted to be bold, and underlined,
that gives the time-stamp for when the log was submitted, the
child_name, the model and function and line number from which the
log-message was originated
* Followed by an indented new-line where the log-message will be
be printed. The message
For level==logging.INFO+1 (21) and above:
log messages will be presented in two parts.
* First, a header line that's formatted to be bold, and underlined,
that gives the time-stamp for when the log was submitted, the
child_name, the model and function and line number from which the
log-message was originated
* Followed, on the same line as the header, the log-message. This
distinction, as opposed to the indented new-line in lower level
messaged, is done because it is often the case the when higher
level messages occur, there are very many of them. Forcing each
one to then be a multi-line message actually makes it much harder
to visually parse.
* Special note: In order to aid in automated parsing of these
log-messages, the header details and log message will be seperated
by the following character key:
`::>`
:type formatter: an instance of logging.Formatter
:param handler_delegate: An optional parameter that Specifies the type of handler you want to
associate to the logger instance that's mapped to the
root_name.child_name you've passed in. The handler will be set up
inside of this function, this parameter simply allows you to indicate
the way you wish to have your output handled.
(E.G. to std_out, std_err, or some file output stream)
:type handler_delegate: This should be a delegate function of your desired handler's
constructor, DEFAULT=logging.StreamHandler
:param level: Specifies the desired logging level of the resulting logger.
DEFAULT=logging.DEBUG
:type level: An int, must be in the range of [0,0xffffffff]
:type handler_kwargs: Any additional keywords that should be passed into the construction of the
handler. These are necessary for the instantiation of handlers that will
output to anything other than sys.std_out, and sys.std_err.
:return: a reference to the logger instance that's mapped to the input naming scheme of
<root_name>.<child_name >
:rtype: logging.Logger
"""
logger.propagate = False
level_normalized = level if level_normalized is None else level_normalized
try:
colr_id = log_id_map[level_normalized]
except KeyError:
# level_normalized isn't in our custom log_id_map
if level_normalized in logging._levelToName:
# but it has been registered with the logging library
LEVELS_STR2INT[logging._levelToName[level_normalized]] = level_normalized
for lvl,color_code in sorted(log_id_map.items(),key=lambda tpl:tpl[0]):
if lvl<=level_normalized:
colr_id = color_code
else:
break
else:
colr_id = log_id_map["NOTSET"]
log_id_map[level_normalized] = colr_id
if formatter is None:
formatter = _build_default_formatter(level,header_label,colr_id,formatter)
logger.addHandler(_ensured_configure_handler(formatter, level, handler_delegate, handler_kwargs))
return logger
| 7,931 |
def _prepare_directory(data_dir: Union[str, PathLike],
ignore_bad: bool = True,
confirm_uids: bool = True) -> List[str]:
"""
Reorganizes PPMI `data_dir` to a structure compatible with ``heudiconv``
PPMI data starts off with a sub-directory structure that is not conducive
to use with ``heudiconv``. By default, scans are grouped by scan type
rather than by session, and there are a number of redundant sub-directories
that we don't need. This script reorganizes the data, moving things around
so that the general hierarchy is {subject}/{session}/{scan}, which makes
for a much easier time converting the PPMI dataset into BIDS format.
An added complication is that a minority of the scans in the PPMI database
are "bad" to some degree. For most, it is likely that there was some issue
with exporting/uploading the DICOM files. For others, the conversion
process we intend to utilize (``heudiconv`` and ``dcm2niix``) fails to
appropriately convert the files due to some idiosyncratic reason that could
be fixed but we don't have the patience to fix at the current juncture.
Nonetheless, these scans need to be removed so that we can run the batch of
subjects through ``heudiconv`` without any abrupt failures. By default,
these scans are moved to a sub-directory of `data_dir`; setting
`ignore_bad` to False will retain these scans (but be warned!)
Parameters
----------
data_dir : str or pathlib.Path
Filepath to PPMI dataset, as downloaded from https://ppmi-info.org
ignore_bad : bool, optional
Whether to ignore "bad" scans (i.e., ones that are known to fail
conversion or reconstruction)
confirm_uids : bool, optional
Whether to check that DICOM study instance UIDs for provided subject
are all consistent for a given session. Only applicable if `pydicom`
is installed. Default: True
Returns
-------
subjects : list
List of subjects who are ready to be converted / reconstructed with
``heudiconv``
coerce : list
List of paths to data directories where subjects / sessions may have
had inconsistent study instance UIDs that should be coerced
"""
if isinstance(data_dir, str):
data_dir = pathlib.Path(data_dir).resolve()
# location where "bad" scans will be moved
if ignore_bad:
timeout = data_dir / 'bad'
timeout.mkdir(exist_ok=True)
else:
timeout = None
subjects, coerce = [], []
for subj_dir in sorted(data_dir.glob('*')):
if not subj_dir.is_dir() or subj_dir.name == 'bad':
continue
subj, force = _prepare_subject(subj_dir, timeout=timeout,
confirm_uids=confirm_uids)
subjects.append(subj)
coerce.extend(force)
return subjects, coerce
| 7,932 |
def find_log_for(tool_code, form_id, log_f):
"""Returns an array of lines from log for
given tool code (P1,N3,...) and form_id. The
form_id is taken from runner - thus we search for
formula number ``form_id+1``
"""
log = open(log_f,'r')
current_f = -1
formula = re.compile('.*ltl:(\d+): (.*)$')
tool = re.compile('.*\[([PN]\d+)\]: (.*)$')
gather = re.compile('Performing sanity checks and gathering statistics')
output = []
for line in log:
m_form = formula.match(line)
if m_form:
current_f = int(m_form.group(1))
curr_tool = ''
if current_f < form_id+1:
continue
if current_f > form_id+1:
break
m_tool = tool.match(line)
if m_tool:
curr_tool = m_tool.group(1)
if gather.match(line):
curr_tool = 'end'
if curr_tool == tool_code:
output.append(line.strip())
log.close()
return output
| 7,933 |
def test_decode_goto():
"""Create program with GOTO from program number"""
program_number = GOTO
# expected program
expected_program = read_program("test_goto.s")
# decode program
assert expected_program == decode_number_as_code(program_number)
| 7,934 |
def get_images(repository_name):
"""Call ecr to get available images"""
eprint("obtaining available images")
try:
out = json.loads( run_command([
"aws", "ecr", "describe-images",
"--repository-name", repository_name,
"--no-paginate"
]).stdout)
except subprocess.CalledProcessError as e:
err(f"failed to get availabe images from repository: {e}" )
return list(sorted(out["imageDetails"], key=lambda image: image["imagePushedAt"], reverse=True))
| 7,935 |
def lint_repo(*, fail_on_missing_sub_src, exclude_lint, warn_lint):
"""Lint all sites using checks defined in :mod:`pegleg.engine.errorcodes`.
"""
warns = pegleg_main.run_lint(
exclude_lint, fail_on_missing_sub_src, warn_lint)
if warns:
click.echo("Linting passed, but produced some warnings.")
for w in warns:
click.echo(w)
| 7,936 |
def exe_cmd_and_poll_output(cmd, encoding='UTF-8', is_capture_output=False):
"""
将命令输出实时打印到标准输出
:param is_capture_output:
:param cmd: 命令行
:param encoding: 字符编码
:return: 标准输出字符串列表
"""
import shlex
func_name = inspect.stack()[0][3]
hlog.enter_func(func_name)
hlog.trace("cmd=%s" % cmd)
output = list()
cmd = shlex.split(cmd)
with subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
while p.poll() is None:
line = p.stdout.readline()
line = str(line, encoding=encoding)
print(line, end='')
if is_capture_output:
output.append(line)
if p.returncode != 0:
hlog.error('Command execution failed')
hlog.exit_func(func_name)
return output
| 7,937 |
def throw(exception, *args, **kwargs): # pragma: no cover
""" Raises an exception (as an expression) """
raise exception(*args, **kwargs)
| 7,938 |
def create_patric_boolean_dict(genome_dict,all_ECs):
"""
Create new dict of dicts to store genome names
:param genome_dict: dict of key=genome_id, value=dict of genome's name, id, ec_numbers
:param all_ECs: set of all ECs found across all genomes
"""
## new format: key=genome, value={EC:0 or 1}
## This makes it easy to write to file with pandas
boolean_genome_dict = {}
for genome_id in genome_dict:
boolean_genome_dict[genome_id] = {}
boolean_genome_dict[genome_id]['genome_name'] = genome_dict[genome_id]['genome_name']
boolean_genome_dict[genome_id]['genome_name_with_id'] = genome_dict[genome_id]['genome_name_with_id']
boolean_genome_dict[genome_id]['duplicate'] = genome_dict[genome_id]['duplicate']
for EC in all_ECs:
if EC in genome_dict[genome_id]['ECs']:
boolean_genome_dict[genome_id][EC] = 1
else:
boolean_genome_dict[genome_id][EC] = 0
return boolean_genome_dict
| 7,939 |
def append_ast_if_req(field):
""" Adds a new filter to template tags that for use in templates. Used by writing {{ field | append_ast_if_req }}
@register registers the filter into the django template library so it can be used in template.
:param Form.field field:
a field of a form that you would like to return the label and potentially an asterisk for.
:returns:
The field label and, if it's a required field, an asterisk
:rtype: string
"""
if field.field.required:
return field.label + '*'
else:
return field.label
| 7,940 |
def getPileupMixingModules(process):
"""
Method returns two lists:
1) list of mixing modules ("MixingModule")
2) list of data mixing modules ("DataMixingModules")
The first gets added only pileup files of type "mc", the
second pileup files of type "data".
"""
mixModules, dataMixModules = [], []
prodsAndFilters = {}
prodsAndFilters.update(process.producers)
prodsAndFilters.update(process.filters)
for key, value in prodsAndFilters.items():
if value.type_() in ["MixingModule", "DataMixingModule", "PreMixingModule"]:
mixModules.append(value)
if value.type_() == "DataMixingModule":
dataMixModules.append(value)
return mixModules, dataMixModules
| 7,941 |
def GetFirstTypeArgImpl_(type_: Hashable, parentClass: Type[Any]) -> Type[Any]:
""" Returns the actual type, even if type_ is a string. """
if isinstance(type_, type):
return type_
if not isinstance(type_, str):
# It's not a type and it's not a str.
# We don't know what to do with it.
raise ValueError("Bad type argument: {}".format(type_))
forwardRef = ForwardRef(type_, is_argument=False)
# pylint: disable=protected-access
evaluated = forwardRef._evaluate(GetClassNamespace_(parentClass), None)
if evaluated is None:
raise RuntimeError("Unable to resolve type {}".format(type_))
if isinstance(evaluated, typing._GenericAlias): # type: ignore
if isinstance(
evaluated.__args__[0], typing._GenericAlias): # type: ignore
# Now use the origin to retrieve the default value type.
return evaluated.__args__[0].__origin__
return evaluated.__args__[0]
return evaluated
| 7,942 |
def tree_map_zipped(fn: Callable[..., Any], nests: Sequence[Any]):
"""Map a function over a list of identical nested structures.
Args:
fn: the function to map; must have arity equal to `len(list_of_nests)`.
nests: a list of identical nested structures.
Returns:
a nested structure whose leaves are outputs of applying `fn`.
"""
if not nests:
return nests
tree_def = tree_structure(nests[0])
if any([tree_structure(x) != tree_def for x in nests[1:]]):
raise ValueError('All elements must share the same tree structure.')
return jax.tree_unflatten(
tree_def, [fn(*d) for d in zip(*[jax.tree_leaves(x) for x in nests])])
| 7,943 |
def square_area(side):
"""Returns the area of a square"""
# You have to code here
# REMEMBER: Tests first!!!
return pow(side,2)
| 7,944 |
def match_collision_name_to_mesh_name(properties):
"""
This function matches the selected collison to the selected mesh.
:param object properties: The property group that contains variables that maintain the addon's correct state.
:return str: The changed collision name.
"""
collisions = get_from_collection(properties.collision_collection_name, 'MESH', properties)
meshes = get_from_collection(properties.mesh_collection_name, 'MESH', properties)
if collisions and meshes:
selected_mesh = [mesh for mesh in meshes if mesh.select_get()][0]
selected_collision = [collision for collision in collisions if collision.select_get()][0]
name = f'{selected_collision.name.split("_")[0]}_{selected_mesh.name}'
selected_collision.name = name
return name
return ''
| 7,945 |
def prepare_ms_tree_certificates(ms_tree):
"""
filter and process the uploaded device pem certificates
"""
pem_certificates = ms_tree.pop("pem_certificates", [])
certificates = []
for pem_certificate in pem_certificates:
certificate = x509.load_pem_x509_certificate(pem_certificate.encode("utf-8"))
# filter out CA certificates
if is_ca(certificate):
continue
# build the cert tree
cert_tree = build_cert_tree(certificate)
if cert_tree not in certificates:
certificates.append(cert_tree)
# update the ms tree
if certificates:
ms_tree["certificates"] = certificates
| 7,946 |
def main(args=None):
"""Perform the validation."""
# Read the CLI args
if args:
schema = args.schema
data = args.data
# Validate
validator = Validator(schema, data)
validator.validate()
| 7,947 |
def _handle_event_colors(color_dict, unique_events, event_id):
"""Create event-integer-to-color mapping, assigning defaults as needed."""
default_colors = dict(zip(sorted(unique_events), cycle(_get_color_list())))
# warn if not enough colors
if color_dict is None:
if len(unique_events) > len(_get_color_list()):
warn('More events than default colors available. You should pass '
'a list of unique colors.')
else:
custom_colors = dict()
for key, color in color_dict.items():
if key in unique_events: # key was a valid event integer
custom_colors[key] = color
elif key in event_id: # key was an event label
custom_colors[event_id[key]] = color
else: # key not a valid event, warn and ignore
warn('Event ID %s is in the color dict but is not '
'present in events or event_id.' % str(key))
# warn if color_dict is missing any entries
unassigned = sorted(set(unique_events) - set(custom_colors))
if len(unassigned):
unassigned_str = ', '.join(str(e) for e in unassigned)
warn('Color was not assigned for event%s %s. Default colors will '
'be used.' % (_pl(unassigned), unassigned_str))
default_colors.update(custom_colors)
return default_colors
| 7,948 |
def redirect_logs_and_warnings_to_lists(
used_logs: list[logging.LogRecord], used_warnings: list
) -> RedirectedLogsAndWarnings:
"""For example if using many processes with multiprocessing, it may be beneficial to log from one place.
It's possible to log to variables (logs as well as warnings), pass it to the main process and then log it
with workings filter etc.
To log stored logs and warnings, use
Args:
used_logs (list): List where logs will be stored
used_warnings (list): List where warnings will be stored
Returns:
RedirectedLogsAndWarnings: Object, where you can reset redirect. Logs and warnings you already have
from inserted parameters.
"""
showwarning_backup = warnings.showwarning
OUTPUT_backup = config.OUTPUT
STREAM_backup = config.STREAM
def custom_warn(message, category, filename, lineno, file=None, line=None):
used_warnings.append(
{
"message": message,
"category": category,
"filename": filename,
"lineno": lineno,
"file": file,
"line": line,
}
)
warnings.showwarning = custom_warn
config.OUTPUT = None
config.STREAM = None
config.TO_LIST = used_logs
return RedirectedLogsAndWarnings(
logs=used_logs,
warnings=used_warnings,
showwarning_backup=showwarning_backup,
OUTPUT_backup=OUTPUT_backup,
STREAM_backup=STREAM_backup,
)
| 7,949 |
def get_file_picker_settings():
"""Return all the data FileUploader needs to start the Google Drive Picker."""
google_settings = frappe.get_single("Google Settings")
if not (google_settings.enable and google_settings.google_drive_picker_enabled):
return {}
return {
"enabled": True,
"appId": google_settings.app_id,
"developerKey": google_settings.api_key,
"clientId": google_settings.client_id
}
| 7,950 |
def find_version(*file_paths):
"""
Args:
*file_paths:
Returns:
"""
here = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
"""
Args:
*parts:
Returns:
"""
with codecs.open(os.path.join(here, *parts), "r") as fp:
return fp.read()
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
| 7,951 |
def match_subset(pattern: oechem.OEMol, target:oechem.OEMol):
"""Check if target is a subset of pattern."""
# Atoms are equal if they have same atomic number (so explicit Hydrogens are needed as well for a match)
atomexpr = oechem.OEExprOpts_AtomicNumber
# single or double bonds are considered identical (resonance,chirality fix)
bondexpr = oechem.OEExprOpts_EqSingleDouble
ss = oechem.OESubSearch(pattern, atomexpr, bondexpr )
oechem.OEPrepareSearch(target, ss)
return ss.SingleMatch(target)
| 7,952 |
def get_quad_strike_vector(q):
"""
Compute the unit vector pointing in the direction of strike for a
quadrilateral in ECEF coordinates. Top edge assumed to be horizontal.
Args:
q (list): A quadrilateral; list of four points.
Returns:
Vector: The unit vector pointing in strike direction in ECEF coords.
"""
P0, P1, P2, P3 = q
p0 = Vector.fromPoint(P0) # fromPoint converts to ECEF
p1 = Vector.fromPoint(P1)
v1 = (p1 - p0).norm()
return v1
| 7,953 |
def CP_to_TT(
cp_cores,
max_rank,
eps=1e-8,
final_round=None,
rsvd_kwargs=None,
verbose=False,
):
"""
Approximate a CP tensor by a TT tensor.
All cores of the TT are rounded to have a TT-rank of most `max_rank`, and singular values of at
most `eps` times the largest singular value. For the first core and last core this rounding is
done using SVD, for all other cores a randomized SVD is employed. Uses
`sklearn.utils.extmath.randomized_svd¶` for randomized SVD. After forming the TT, it is
optionally rounded again with an accuracy of `final_round`.
Parameters
----------
cp_cores: list<np.ndarray>
List of CP cores
max_rank: int
eps: float (default: 1e-8)
rsvd_kwargs: dict (optional)
keyword arguments to pass to the randomized svd method.
verbose: bool (default: False)
"""
d = len(cp_cores)
tt_cores = [None] * d
prev_rank = 1
if rsvd_kwargs is None:
rsvd_kwargs = {}
for alpha in range(d):
core = cp_cores[alpha]
dim = core.shape[0]
if alpha == 0:
U, S, V = svd(cp_cores[0], full_matrices=False)
elif alpha < d - 1: # Use randomized SVD for middle cores
core = np.einsum("ik,jk->ijk", SV, core)
core_mat = core.reshape(
core.shape[0] * core.shape[1], core.shape[2]
)
U, S, V = randomized_svd(
core_mat, n_components=max_rank, **rsvd_kwargs
)
else: # alpha = d - 1
core = np.einsum("ik,jk->ij", SV, core)
U, S, V = svd(core)
r = 1
r = max(1, min(max_rank, np.sum(S > eps)))
U = U[:, :r]
S = S[:r]
V = V[:r, :]
SV = (S * V.T).T
if alpha == d - 1:
tt_cores[alpha - 1] = np.einsum(
"ijk,kl->ijl", tt_cores[alpha - 1], U
)
tt_cores[alpha] = SV.reshape(SV.shape + (1,))
else:
tt_cores[alpha] = U.reshape((prev_rank, dim, r))
if verbose:
print(
f"feature {alpha+1}/{d}, compressed TT core size is {tt_cores[alpha].shape}"
)
prev_rank = r
if verbose:
print("Orthogonalizing")
tt = TensorTrain(tt_cores, is_orth=True)
if final_round is not None:
if verbose:
print(f"Rounding to {final_round}...")
tt.round(eps=final_round)
if verbose:
print(f"Final TT rank: {tt.tt_rank}")
return tt
| 7,954 |
def _create_key_list(entries):
"""
Checks if entries are from FieldInfo objects and extracts keys
:param entries: to create key list from
:return: the list of keys
"""
if len(entries) == 0:
return []
if all(isinstance(entry, FieldInfo) for entry in entries):
return [entry.key for entry in entries]
# this should be a regular list of strings
return entries
| 7,955 |
def compose_rule_hierarchies(rule_hierarchy1, lhs_instances1, rhs_instances1,
rule_hierarchy2, lhs_instances2, rhs_instances2):
"""Compose two rule hierarchies."""
if len(rule_hierarchy1["rules"]) == 0:
return rule_hierarchy2, lhs_instances2, rhs_instances2
if len(rule_hierarchy2["rules"]) == 0:
return rule_hierarchy1, lhs_instances1, rhs_instances1
graphs = set(rule_hierarchy1["rules"].keys()).union(
rule_hierarchy2["rules"].keys())
homomorphisms = set(rule_hierarchy1["rule_homomorphisms"].keys()).union(
rule_hierarchy2["rule_homomorphisms"].keys())
new_rule_hierarchy = {
"rules": {},
"rule_homomorphisms": {}
}
new_lhs_instances = {}
new_rhs_instances = {}
composition_data = {}
# Compose rules
for graph in graphs:
if graph in rule_hierarchy1["rules"]:
rule1 = rule_hierarchy1["rules"][graph]
lhs_instance1 = lhs_instances1[graph]
rhs_instance1 = rhs_instances1[graph]
else:
rule1 = Rule.identity_rule()
lhs_instance1 = {}
rhs_instance1 = {}
if graph in rule_hierarchy2["rules"]:
rule2 = rule_hierarchy2["rules"][graph]
lhs_instance2 = lhs_instances2[graph]
rhs_instance2 = rhs_instances2[graph]
else:
rule2 = Rule.identity_rule()
lhs_instance2 = {}
rhs_instance2 = {}
new_rule, new_lhs_instance, new_rhs_instance, data = compose_rules(
rule1, lhs_instance1, rhs_instance1,
rule2, lhs_instance2, rhs_instance2, return_all=True)
new_rule_hierarchy["rules"][graph] = new_rule
new_lhs_instances[graph] = new_lhs_instance
new_rhs_instances[graph] = new_rhs_instance
composition_data[graph] = data
# Compute rule homomorphisms
for source, target in homomorphisms:
lhs_hom1, p_hom1, rhs_hom1 = rule_hierarchy1["rule_homomorphisms"][
(source, target)]
lhs_hom2, p_hom2, rhs_hom2 = rule_hierarchy2["rule_homomorphisms"][
(source, target)]
source_data = composition_data[source]
target_data = composition_data[target]
# H_G -> H_T
h_hom = get_unique_map_from_pushout(
source_data["h"].nodes(),
source_data["rhs1_h"],
source_data["lhs2_h"],
compose(rhs_hom1, target_data["rhs1_h"]),
compose(lhs_hom2, target_data["lhs2_h"])
)
# P*G_1 -> P*T_1
p1_p_hom = get_unique_map_to_pullback_complement(
target_data["p1_p1_p"], target_data["p1_p_h"],
p_hom1, source_data["p1_p1_p"],
compose(source_data["p1_p_h"], h_hom))
# P*G_2 -> P*T_2
p2_p_hom = get_unique_map_to_pullback_complement(
target_data["p2_p2_p"], target_data["p2_p_h"],
p_hom2, source_data["p2_p2_p"],
compose(source_data["p2_p_h"], h_hom))
# Pi_G -> Pi_T
pi_hom = get_unique_map_to_pullback(
new_rule_hierarchy["rules"][target].p.nodes(),
target_data["pi_p1_p"], target_data["pi_p2_p"],
compose(source_data["pi_p1_p"], p1_p_hom),
compose(source_data["pi_p2_p"], p2_p_hom))
# L_G -> L_T
lambda_hom = get_unique_map_from_pushout(
new_rule_hierarchy["rules"][source].lhs.nodes(),
source_data["lhs1_lambda"], source_data["p1_p_lambda"],
compose(lhs_hom1, target_data["lhs1_lambda"]),
compose(p1_p_hom, target_data["p1_p_lambda"]))
# R_G -> R_T
rho_hom = get_unique_map_from_pushout(
new_rule_hierarchy["rules"][source].rhs.nodes(),
source_data["p2_p_rho"], source_data["rhs2_rho"],
compose(p2_p_hom, target_data["p2_p_rho"]),
compose(rhs_hom2, target_data["rhs2_rho"]))
new_rule_hierarchy["rule_homomorphisms"][(source, target)] = (
lambda_hom, pi_hom, rho_hom
)
return new_rule_hierarchy, new_lhs_instances, new_rhs_instances
| 7,956 |
def write_drc_script(cell_name, gds_name, extract, final_verification, output_path, sp_name=None):
"""
Write a klayout script to perform DRC and optionally extraction.
"""
global OPTS
# DRC:
# klayout -b -r drc_FreePDK45.lydrc -rd input=sram_8_256_freepdk45.gds -rd topcell=sram_8_256_freepdk45 -rd output=drc_FreePDK45.lyrdb
# Copy .lydrc file into the output directory
full_drc_file = OPTS.openram_tech + "tech/{}.lydrc".format(OPTS.tech_name)
drc_file = os.path.basename(full_drc_file)
if os.path.exists(full_drc_file):
shutil.copy(full_drc_file, output_path)
else:
debug.warning("Could not locate file: {}".format(full_drc_file))
# Create an auxiliary script to run calibre with the runset
run_file = output_path + "run_drc.sh"
f = open(run_file, "w")
f.write("#!/bin/sh\n")
cmd = "{0} -b -r {1} -rd input={2} -rd topcell={3} -rd output={3}.drc.report".format(OPTS.drc_exe[1],
drc_file,
gds_name,
cell_name)
f.write(cmd)
f.write("\n")
f.close()
os.system("chmod u+x {}".format(run_file))
| 7,957 |
def expand_tile(value, size):
"""Add a new axis of given size."""
value = tf.convert_to_tensor(value=value, name='value')
ndims = value.shape.ndims
return tf.tile(tf.expand_dims(value, axis=0), [size] + [1]*ndims)
| 7,958 |
def before_request():
"""Set parameters in g before each request."""
g.user = None
if 'user_id' in session:
g.user = User.query.get(session['user_id'])
g.referer = get_referer(request) or url_for('index')
g.request_headers = request.headers
| 7,959 |
def fetch_exchange(zone_key1='DK-DK1', zone_key2='DK-DK2', session=None,
target_datetime=None, logger=logging.getLogger(__name__)):
"""
Fetches 5-minute frequency exchange data for Danish bidding zones
from api.energidataservice.dk
"""
r = session or requests.session()
sorted_keys = '->'.join(sorted([zone_key1, zone_key2]))
# pick the correct zone to search
if 'DK1' in sorted_keys and 'DK2' in sorted_keys:
zone = 'DK1'
elif 'DK1' in sorted_keys:
zone = 'DK1'
elif 'DK2' in sorted_keys:
zone = 'DK2'
elif 'DK-BHM' in sorted_keys:
zone = 'DK2'
else:
raise NotImplementedError(
'Only able to fetch exchanges for Danish bidding zones')
exch_map = {
'DE->DK-DK1': '"ExchangeGermany"',
'DE->DK-DK2': '"ExchangeGermany"',
'DK-DK1->DK-DK2': '"ExchangeGreatBelt"',
'DK-DK1->NO-NO2': '"ExchangeNorway"',
'DK-DK1->NL': '"ExchangeNetherlands"',
'DK-DK1->SE': '"ExchangeSweden"',
'DK-DK1->SE-SE3': '"ExchangeSweden"',
'DK-DK1->NL': '"ExchangeNetherlands"',
'DK-DK2->SE': '("ExchangeSweden" - "BornholmSE4")', # Exchange from Bornholm to Sweden is included in "ExchangeSweden"
'DK-DK2->SE-SE4': '("ExchangeSweden" - "BornholmSE4")', # but Bornholm island is reported separately from DK-DK2 in eMap
'DK-BHM->SE': '"BornholmSE4"',
}
if sorted_keys not in exch_map:
raise NotImplementedError(
'Exchange {} not implemented'.format(sorted_keys))
timestamp = arrow.get(target_datetime).strftime('%Y-%m-%d %H:%M')
# fetch real-time/5-min data
sqlstr = 'SELECT "Minutes5UTC" as timestamp, {0} as "netFlow" \
from "{1}" WHERE "PriceArea" = \'{2}\' AND \
"Minutes5UTC" >= (timestamp\'{3}\'-INTERVAL \'24 hours\') AND \
"Minutes5UTC" <= timestamp\'{3}\' \
ORDER BY "Minutes5UTC" ASC'.format(exch_map[sorted_keys],
ids['real_time'],
zone,
timestamp)
url = 'https://api.energidataservice.dk/datastore_search_sql?sql={}'.format(sqlstr)
response = r.get(url)
# raise errors for responses with an error or no data
retry_count = 0
while response.status_code in [429, 403, 500]:
retry_count += 1
if retry_count > 5:
raise Exception('Retried too many times..')
# Wait and retry
logger.warn('Retrying..')
time.sleep(5 ** retry_count)
response = r.get(url)
if response.status_code != 200:
j = response.json()
if 'error' in j and 'info' in j['error']:
error = j['error']['__type']
text = j['error']['info']['orig']
msg = '"{}" fetching exchange data for {}: {}'.format(
error, sorted_keys, text)
else:
msg = 'error while fetching exchange data for {}: {}'.format(
sorted_keys, json.dumps(j))
raise requests.exceptions.HTTPError(msg)
if not response.json()['result']['records']:
raise ParserException(
"DK.py", 'API returned no data', zone_key=sorted_keys)
df = pd.DataFrame(response.json()['result']['records'])
df = df.set_index('timestamp')
df.index = pd.DatetimeIndex(df.index)
# drop empty rows
df.dropna(how='all', inplace=True)
# all exchanges are reported as net import,
# where as eMap expects net export from
# the first zone in alphabetical order
if 'DE' not in sorted_keys:
df['netFlow'] = -1 * df['netFlow']
# Format output
output = []
for dt in df.index:
data = {
'sortedZoneKeys': sorted_keys,
'datetime': None,
'netFlow': None,
'source': 'api.energidataservice.dk'
}
data['datetime'] = dt.to_pydatetime()
data['datetime'] = data['datetime'].replace(tzinfo=pytz.utc)
data['netFlow'] = df.loc[dt, 'netFlow']
output.append(data)
return output
| 7,960 |
def snitch(func):
"""
This method is used to add test function to TestCase classes.
snitch method gets test function and returns a copy of this function
with 'test_' prefix at the beginning (to identify this function as
an executable test).
It provides a way to implement a storage (python module that
contains non-executable test functions) for tests and to include
different set of functions into different test cases.
"""
return FunctionType(func.func_code, func.func_globals,
'test_' + func.func_name, closure=func.func_closure)
| 7,961 |
async def test_sensor_entity_meter_model(
hass, mock_config_entry_data, mock_config_entry
):
"""Test entity loads meter model."""
api = get_mock_device()
api.data.available_datapoints = [
"meter_model",
]
api.data.meter_model = "Model X"
with patch(
"aiohwenergy.HomeWizardEnergy",
return_value=api,
):
entry = mock_config_entry
entry.data = mock_config_entry_data
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
entity_registry = er.async_get(hass)
state = hass.states.get("sensor.product_name_aabbccddeeff_smart_meter_model")
entry = entity_registry.async_get(
"sensor.product_name_aabbccddeeff_smart_meter_model"
)
assert entry
assert state
assert entry.unique_id == "aabbccddeeff_meter_model"
assert not entry.disabled
assert state.state == "Model X"
assert (
state.attributes.get(ATTR_FRIENDLY_NAME)
== "Product Name (aabbccddeeff) Smart Meter Model"
)
assert ATTR_STATE_CLASS not in state.attributes
assert ATTR_UNIT_OF_MEASUREMENT not in state.attributes
assert ATTR_DEVICE_CLASS not in state.attributes
assert state.attributes.get(ATTR_ICON) == "mdi:gauge"
| 7,962 |
def average_h5(path, path_dc):
"""Return averaged data from HDF5 DC measurements.
Subtracts dark current from the signal measurements.
Args:
- path, path_dc: paths to signal and dark measurement files.
Returns:
- 2D array containing averaged and DC-subtracted measurement.
"""
with h5.File(path, 'r') as f:
with h5.File(path_dc, 'r') as fdc:
arr = (f['data'][...].mean(axis=0) -
fdc['data'][...].mean(axis=0))
return arr
| 7,963 |
def test_profile_to_osco_execute_bogus_config(tmp_path):
"""Test execute call bogus config."""
section = None
tgt = profile_to_osco.ProfileToOsco(section)
retval = tgt.execute()
assert retval == TaskOutcome.FAILURE
| 7,964 |
def init(templates_path: str = None, modules: dict = None, log: logging = None) -> None:
"""Set templates_path, and modules to import in Jinja2.
:param templates_path: Path to templates
:param modules: List of modules to import in Jinja2
:param log: logging
:return: None"""
import sys
global _templates_path, _modules
if not templates_path:
templates_path = sys.path[0] + '/templates'
_templates_path = templates_path
if not modules:
modules = dict()
_modules = modules
log.debug('Compiler has been initialised.')
| 7,965 |
def edit_distance(hypothesis, truth, normalize=True, name="edit_distance"):
"""Computes the Levenshtein distance between sequences.
This operation takes variable-length sequences (`hypothesis` and `truth`),
each provided as a `SparseTensor`, and computes the Levenshtein distance.
You can normalize the edit distance by length of `truth` by setting
`normalize` to true.
For example, given the following input:
```python
# 'hypothesis' is a tensor of shape `[2, 1]` with variable-length values:
# (0,0) = ["a"]
# (1,0) = ["b"]
hypothesis = tf.SparseTensor(
[[0, 0, 0],
[1, 0, 0]],
["a", "b"],
(2, 1, 1))
# 'truth' is a tensor of shape `[2, 2]` with variable-length values:
# (0,0) = []
# (0,1) = ["a"]
# (1,0) = ["b", "c"]
# (1,1) = ["a"]
truth = tf.SparseTensor(
[[0, 1, 0],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0]],
["a", "b", "c", "a"],
(2, 2, 2))
normalize = True
```
This operation would return the following:
```python
# 'output' is a tensor of shape `[2, 2]` with edit distances normalized
# by 'truth' lengths.
output ==> [[inf, 1.0], # (0,0): no truth, (0,1): no hypothesis
[0.5, 1.0]] # (1,0): addition, (1,1): no hypothesis
```
Args:
hypothesis: A `SparseTensor` containing hypothesis sequences.
truth: A `SparseTensor` containing truth sequences.
normalize: A `bool`. If `True`, normalizes the Levenshtein distance by
length of `truth.`
name: A name for the operation (optional).
Returns:
A dense `Tensor` with rank `R - 1`, where R is the rank of the
`SparseTensor` inputs `hypothesis` and `truth`.
Raises:
TypeError: If either `hypothesis` or `truth` are not a `SparseTensor`.
"""
if not isinstance(
hypothesis,
(sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)):
raise TypeError("Hypothesis must be a SparseTensor.")
if not isinstance(
truth, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)):
raise TypeError("Truth must be a SparseTensor.")
return gen_array_ops.edit_distance(
hypothesis.indices,
hypothesis.values,
hypothesis.dense_shape,
truth.indices,
truth.values,
truth.dense_shape,
normalize=normalize,
name=name)
| 7,966 |
def file_timestamp(path):
"""
Returns a datetime.datetime() object representing the given path's "latest"
timestamp, which is calculated via the maximum (newest/youngest) value
between ctime and mtime. This accounts for platform variations in said
values. If the path doesn't exist, the earliest timestamp supported by the
system is returned -- typically the epoch.
"""
try:
st = os.stat(path)
timestamp = max(st.st_mtime, st.st_ctime)
except OSError:
timestamp = 0
return datetime.datetime.fromtimestamp(timestamp)
| 7,967 |
def kl_bernoulli(p: np.ndarray, q: np.ndarray) -> np.ndarray:
"""
Compute KL-divergence between 2 probabilities `p` and `q`. `len(p)` divergences are calculated
simultaneously.
Parameters
----------
p
Probability.
q
Probability.
Returns
-------
Array with the KL-divergence between `p` and `q`.
"""
m = np.clip(p, 0.0000001, 0.9999999999999999).astype(float)
n = np.clip(q, 0.0000001, 0.9999999999999999).astype(float)
return m * np.log(m / n) + (1. - m) * np.log((1. - m) / (1. - n))
| 7,968 |
def _incremental_mean_and_var(X, last_mean, last_variance, last_sample_count):
"""Calculate mean update and a Youngs and Cramer variance update.
last_mean and last_variance are statistics computed at the last step by the
function. Both must be initialized to 0.0. In case no scaling is required
last_variance can be None. The mean is always required and returned because
necessary for the calculation of the variance. last_n_samples_seen is the
number of samples encountered until now.
From the paper "Algorithms for computing the sample variance: analysis and
recommendations", by Chan, Golub, and LeVeque.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Data to use for variance update
last_mean : array-like, shape: (n_features,)
last_variance : array-like, shape: (n_features,)
last_sample_count : array-like, shape (n_features,)
Returns
-------
updated_mean : array, shape (n_features,)
updated_variance : array, shape (n_features,)
If None, only mean is computed
updated_sample_count : array, shape (n_features,)
Notes
-----
NaNs are ignored during the algorithm.
References
----------
T. Chan, G. Golub, R. LeVeque. Algorithms for computing the sample
variance: recommendations, The American Statistician, Vol. 37, No. 3,
pp. 242-247
Also, see the sparse implementation of this in
`utils.sparsefuncs.incr_mean_variance_axis` and
`utils.sparsefuncs_fast.incr_mean_variance_axis0`
"""
# old = stats until now
# new = the current increment
# updated = the aggregated stats
last_sum = last_mean * last_sample_count
new_sum = _safe_accumulator_op(np.nansum, X, axis=0)
new_sample_count = np.sum(~np.isnan(X), axis=0)
updated_sample_count = last_sample_count + new_sample_count
updated_mean = (last_sum + new_sum) / updated_sample_count
if last_variance is None:
updated_variance = None
else:
new_unnormalized_variance = (
_safe_accumulator_op(np.nanvar, X, axis=0) * new_sample_count)
last_unnormalized_variance = last_variance * last_sample_count
with cupyx.errstate(divide=None, invalid=None):
last_over_new_count = last_sample_count / new_sample_count
updated_unnormalized_variance = (
last_unnormalized_variance + new_unnormalized_variance +
last_over_new_count / updated_sample_count *
(last_sum / last_over_new_count - new_sum) ** 2)
zeros = last_sample_count == 0
updated_unnormalized_variance[zeros] = new_unnormalized_variance[zeros]
updated_variance = updated_unnormalized_variance / updated_sample_count
return updated_mean, updated_variance, updated_sample_count
| 7,969 |
def avg_pds_from_events(
times,
gti,
segment_size,
dt,
norm="frac",
use_common_mean=True,
silent=False,
fluxes=None,
errors=None,
):
"""Calculate the average periodogram from a list of event times or a light curve.
If the input is a light curve, the time array needs to be uniformly sampled
inside GTIs (it can have gaps outside), and the fluxes need to be passed
through the ``fluxes`` array.
Otherwise, times are interpeted as photon arrival times.
Parameters
----------
times : float `np.array`
Array of times
gti : [[gti00, gti01], [gti10, gti11], ...]
good time intervals
segment_size : float
length of segments
dt : float
Time resolution of the light curves used to produce periodograms
Other Parameters
----------------
norm : str, default "frac"
The normalization of the periodogram. "abs" is absolute rms, "frac" is
fractional rms, "leahy" is Leahy+83 normalization, and "none" is the
unnormalized periodogram
use_common_mean : bool, default True
The mean of the light curve can be estimated in each interval, or on
the full light curve. This gives different results (Alston+2013).
Here we assume the mean is calculated on the full light curve, but
the user can set ``use_common_mean`` to False to calculate it on a
per-segment basis.
silent : bool, default False
Silence the progress bars
fluxes : float `np.array`, default None
Array of counts per bin or fluxes
errors : float `np.array`, default None
Array of errors on the fluxes above
Returns
-------
freq : `np.array`
The periodogram frequencies
power : `np.array`
The normalized periodogram powers
n_bin : int
the number of bins in the light curves used in each segment
n_ave : int
the number of averaged periodograms
mean : float
the mean flux
"""
if segment_size is None:
segment_size = gti.max() - gti.min()
n_bin = np.rint(segment_size / dt).astype(int)
dt = segment_size / n_bin
flux_iterable = get_flux_iterable_from_segments(
times, gti, segment_size, n_bin, fluxes=fluxes, errors=errors
)
cross = avg_pds_from_iterable(
flux_iterable, dt, norm=norm, use_common_mean=use_common_mean, silent=silent
)
if cross is not None:
cross.meta["gti"] = gti
return cross
| 7,970 |
def check_random_state(seed):
"""
Turn seed into a random.Random instance
If seed is None, return the Random singleton used by random.
If seed is an int, return a new Random instance seeded with seed.
If seed is already a Random instance, return it.
Otherwise raise ValueError.
"""
# Code slightly adjusted from scikit-learn utils/validation.py
if seed is None or isinstance(seed, int):
rng = random.Random(seed)
elif isinstance(seed, random.Random):
rng = seed
else:
raise ValueError(
"### error: '{}' cannot be used to seed random.Random instance.".format(
seed
)
)
return rng
| 7,971 |
def chunk(seq, size, groupByList=True):
"""Returns list of lists/tuples broken up by size input"""
func = tuple
if groupByList:
func = list
return [func(seq[i:i + size]) for i in range(0, len(seq), size)]
| 7,972 |
def registerNamespace(namespace, prefix):
"""
Register a namespace in libxmp.exempi
@namespace : the namespace to register
@prefix : the prefix to use with this namespace
"""
try:
registered_prefix = libxmp.exempi.namespace_prefix(namespace)
# The namespace already exists, return actual prefix.
return registered_prefix
except libxmp.XMPError:
# This namespace does not exist, that's cool
pass
try:
libxmp.exempi.prefix_namespace_uri(prefix)
# Prefix is already used, but not by us.
raise NameError("Prefix is already used")
except libxmp.XMPError:
# This prefix is not used yet, that's cool
pass
return libxmp.exempi.register_namespace(namespace, prefix)[:-1]
| 7,973 |
def definition():
"""
Lists the parent-child relationships through the curriculum structure.
"""
sql = """
--Course to session
SELECT c.course_id as parent_id,
CASE WHEN cc.course_id IS NULL THEN 0 ELSE 1 END as linked,
cs.course_session_id as child_id, 'course' as parent,
cs.description + ' ' + cast(cs.session as char(1)) as description,
-1 as ratio,0 as changed
FROM c_course c
LEFT OUTER JOIN c_course_session cs on cs.curriculum_id = c.curriculum_id
LEFT OUTER JOIN c_course_config cc on c.course_id = cc.course_id
AND cc.course_session_id = cs.course_session_id
UNION ALL
--session to group
SELECT a.course_session_id as parent_id,
CASE WHEN c.course_session_id IS NULL THEN 0 ELSE 1 END as linked,
b.cgroup_id as child_id, 'course_session' as parent,
b.description,
-1 as ratio, 0 as changed
FROM c_course_session a
LEFT OUTER JOIN c_cgroup b ON a.curriculum_id = b.curriculum_id
LEFT OUTER JOIN c_course_session_config c on a.course_session_id = c.course_session_id
AND b.cgroup_id = c.cgroup_id
UNION ALL
--CGroup to component
SELECT a.cgroup_id as parent_id,
CASE WHEN c.component_id IS NULL THEN 0 ELSE 1 END as linked,
b.component_id as child_id, 'cgroup' as parent, b.description,
ISNULL(c.ratio, 1) as ratio, 0 as changed
FROM c_cgroup a
LEFT OUTER JOIN c_component b ON a.curriculum_id = b.curriculum_id
LEFT OUTER JOIN c_cgroup_config c on a.cgroup_id = c.cgroup_id
AND b.component_id = c.component_id
"""
return sql
| 7,974 |
def create_user(strategy, details, backend, user=None, *args, **kwargs):
"""Aggressively attempt to register and sign in new user"""
if user:
return None
request = strategy.request
settings = request.settings
email = details.get("email")
username = kwargs.get("clean_username")
if not email or not username:
return None
try:
validate_email(email)
validate_new_registration(request, {"email": email, "username": username})
except ValidationError:
return None
activation_kwargs = {}
if settings.account_activation == "admin":
activation_kwargs = {"requires_activation": User.ACTIVATION_ADMIN}
new_user = User.objects.create_user(
username, email, joined_from_ip=request.user_ip, **activation_kwargs
)
setup_new_user(settings, new_user)
send_welcome_email(request, new_user)
return {"user": new_user, "is_new": True}
| 7,975 |
def enumerate_benchmark_replay(folder, runtime='python', time_kwargs=None,
skip_long_test=True, time_kwargs_fact=None,
time_limit=4, verbose=1, fLOG=None):
"""
Replays a benchmark stored with function
:func:`enumerate_validated_operator_opsets
<mlprodict.onnxrt.validate.validate.enumerate_validated_operator_opsets>`
or command line :ref:`validate_runtime <l-cmd-validate_runtime>`.
Enumerates the results.
@param folder folder where to find pickled files, all files must have
*pkl* or *pickle* extension
@param runtime runtime or runtimes
@param time_kwargs to define a more precise way to measure a model
@param skip_long_test skips tests for high values of N if they seem too long
@param time_kwargs_fact see :func:`_multiply_time_kwargs <mlprodict.onnxrt.validate.validate_helper._multiply_time_kwargs>`
@param time_limit to skip the rest of the test after this limit (in second)
@param verbose if >= 1, uses :epkg:`tqdm`
@param fLOG logging function
@return iterator on results
"""
files = [_ for _ in os.listdir(folder) if _.endswith(
".pkl") or _.endswith("_.pickle")]
if len(files) == 0:
raise FileNotFoundError(
"Unable to find any file in folder '{}'.".format(folder))
if time_kwargs in (None, ''):
time_kwargs = default_time_kwargs()
if isinstance(runtime, str):
runtime = runtime.split(",")
loop = files
if verbose >= 1:
try:
from tqdm import tqdm
loop = tqdm(files)
except ImportError: # pragma: no cover
pass
for pkl in loop:
if "ERROR" in pkl:
# An error.
if verbose >= 2 and fLOG is not None: # pragma: no cover
fLOG( # pragma: no cover
"[enumerate_benchmark_replay] skip '{}'.".format(pkl))
continue # pragma: no cover
if verbose >= 2 and fLOG is not None:
fLOG("[enumerate_benchmark_replay] process '{}'.".format(pkl))
row = {}
with open(os.path.join(folder, pkl), 'rb') as f:
obj = pickle.load(f)
X_test = obj['X_test']
ort_test = obj['Xort_test']
onx = obj['onnx_bytes']
model = obj['skl_model']
tkw = _multiply_time_kwargs(time_kwargs, time_kwargs_fact, model)
row['folder'] = folder
row['filename'] = pkl
row['n_features'] = X_test.shape[1]
for key in ['assume_finite', 'conv_options',
'init_types', 'idtype', 'method_name', 'n_features',
'name', 'optim', 'opset', 'predict_kwargs',
'output_index', 'problem', 'scenario']:
row[key] = obj['obs_op'][key]
# 'bench-batch',
# 'bench-skl',
oinfs = {}
for rt in runtime:
if rt == 'onnxruntime':
try:
oinfs[rt] = SimplifiedOnnxInference(onx)
except (OrtFail, RuntimeError) as e: # pragma: no cover
row['ERROR'] = str(e)
oinfs[rt] = None
else:
try:
oinfs[rt] = OnnxInference(
onx, runtime=rt, runtime_options=dict(
log_severity_level=3))
except (OrtFail, RuntimeError) as e: # pragma: no cover
row['ERROR'] = str(e)
oinfs[rt] = None
for k, v in sorted(tkw.items()):
if verbose >= 3 and fLOG is not None:
fLOG( # pragma: no cover
"[enumerate_benchmark_replay] process n_rows={} - {}".format(k, v))
xt = make_n_rows(X_test, k)
number = v['number']
repeat = v['repeat']
meth = getattr(model, row['method_name'])
with sklearn.config_context(assume_finite=row['assume_finite']):
skl = measure_time(lambda x: meth(x), xt,
number=number, repeat=repeat,
div_by_number=True)
if verbose >= 4 and fLOG is not None:
fLOG( # pragma: no cover
"[enumerate_benchmark_replay] skl={}".format(skl))
row['%d-skl-details' % k] = skl
row['%d-skl' % k] = skl['average']
xto = make_n_rows(ort_test, k)
for rt in runtime:
oinf = oinfs[rt]
if oinf is None:
continue # pragma: no cover
if len(oinf.input_names) != 1:
raise NotImplementedError( # pragma: no cover
"This function only allows one input not {}".format(
len(oinf.input_names)))
name = oinf.input_names[0]
ort = measure_time(lambda x: oinf.run({name: x}), xto,
number=number, repeat=repeat,
div_by_number=True)
if verbose >= 4 and fLOG is not None:
fLOG( # pragma: no cover
"[enumerate_benchmark_replay] {}={}".format(rt, ort))
row['%d-%s-detail' % (k, rt)] = ort
row['%d-%s' % (k, rt)] = ort['average']
yield row
| 7,976 |
def add_regex_def(name: str, regex: str, priority: str, entity: str):
"""
Add additional regexes to the JSON file.
Parameters
----------
name : str
Regex name.
regex : str
Regex definition.
priority : str
Regex priority.
entity : str
Entity corresponding to the regex.
"""
with open("regexes.json") as json_file:
data = json.load(json_file)
y = {name: {"regex": regex, "priority": priority, "entity": entity}}
data.update(y)
with open("regexes.json", "w") as f:
json.dump(data, f)
| 7,977 |
def wiggles(data, wiggleInterval=10, overlap=5, posFill='black',
negFill=None, lineColor='black', rescale=True, extent=None, ax=None):
"""
2-D Wiggle Trace Variable Amplitude Plot
Parameters
----------
x: input data (2D numpy array)
wiggleInterval: (default, 10) Plot 'wiggles' every wiggleInterval traces
overlap: (default, 0.7) amount to overlap 'wiggles' by (1.0 = scaled
to wiggleInterval)
posFill: (default, black) color to fill positive wiggles with (string
or None)
negFill: (default, None) color to fill negative wiggles with (string
or None)
lineColor: (default, black) color of wiggle trace (string or None)
resampleRatio: (default, 10) factor to resample traces by before
plotting (1 = raw data) (float)
extent: (default, (0, nx, 0, ny)) The extent to use for the plot.
A 4-tuple of (xmin, xmax, ymin, ymax)
ax: (default, current axis) The matplotlib axis to plot onto.
Output:
a matplotlib plot on the current axes
"""
# Rescale so that the data ranges from -1 to 1
if rescale:
data = data.astype(np.float)
data -= data.min()
data /= data.ptp()
data *= 2
data -= 1
if extent is None:
xmin, ymin = 0, data.shape[0]
ymax, xmax = 0, data.shape[1]
else:
xmin, xmax, ymin, ymax = extent
if ax is None:
_, ax = plt.subplots()
ax.invert_yaxis()
ax.set(xlim=[xmin, xmax], ylim=[ymin, ymax]) # xrange should be larger!!!
ny, nx = data.shape
x_loc = np.linspace(xmin, xmax, nx)
for i in range(wiggleInterval//2, nx, wiggleInterval):
x = overlap * (wiggleInterval / 2.0) * (x_loc[1] - x_loc[0]) * data[:, i]
wiggle(x + x_loc[i], origin=x_loc[i], posFill=posFill, negFill=negFill,
lineColor=lineColor, zmin=ymin, zmax=ymax, ax=ax)
# decorations
ax.xaxis.set_ticks_position('both')
ax.yaxis.set_ticks_position('both')
ax.xaxis.set_tick_params(labeltop='on', labelbottom='off')
# # ticks_list = [(0.2, 0.2), (0.4, 0.4), (0.6, 0.6), (0.8, 0.8)]
# ticks_list = [(0.2,0.2),(1,1)]
# ax.set(
# yticks=[item[1] for item in ax.transAxes.transform(ticks_list)],
# xticks=[item[0] for item in ax.transAxes.transform(ticks_list)]
# )
| 7,978 |
def save_dumps(module_name, dumps, dump_root="."):
"""
Serialize dump files to the disk.
Parameters
----------
module_name : str
File name, referring to the module that generated
the dump contents
dumps : dict
The output contents to be saved into the files
dump_root : str, optional
Path in which dump files will be created
"""
for dump_format in dumps:
dump_name = module_name + "." + dump_format
with open(Path(dump_root, dump_name), "w") as f:
f.write(dumps[dump_format])
| 7,979 |
def prendreTresorPlateau(plateau,lig,col,numTresor):
"""
prend le tresor numTresor qui se trouve sur la carte en lin,col du plateau
retourne True si l'opération s'est bien passée (le trésor était vraiment sur
la carte
paramètres: plateau: le plateau considéré
lig: la ligne où se trouve la carte
col: la colonne où se trouve la carte
numTresor: le numéro du trésor à prendre sur la carte
resultat: un booléen indiquant si le trésor était bien sur la carte considérée
"""
if getTresor(getVal(plateau,lig,col))==numTresor:
prendreTresor(getVal(plateau,lig,col))
return True
else:
return False
| 7,980 |
def load_styles(style_yaml) -> dict:
""" Load point style dictionary """
default_style = {"icon_image": DEFAULT_ICON_IMAGE,
"icon_color": DEFAULT_ICON_COLOR,
"icon_scale": DEFAULT_ICON_SCALE,
"text_scale": DEFAULT_TEXT_SCALE,
}
styles = {'Default': default_style}
if style_yaml is None:
return styles
if not os.path.isfile(style_yaml):
logging.error('Invalid style file location %s', style_yaml)
return styles
with open(style_yaml, 'r') as stream:
new_styles = yaml.load(stream)
for style in new_styles:
if style in styles:
logging.warning('Style %s already exists', style)
continue
else:
styles[style] = dict() # Create new style
for attr in ['icon_image', 'icon_color', 'icon_scale', 'text_scale']:
if attr in new_styles[style]:
attr_val = new_styles[style][attr]
else:
attr_val = default_style[attr]
styles[style][attr] = attr_val
return styles
| 7,981 |
def everything_deployed(project, chain, web3, accounts, deploy_address) -> dict:
"""Deploy our token plan."""
yaml_filename = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..","crowdsales", "allocated-token-sale-acceptance-test.yml"))
deployment_name = "testrpc"
chain_data = load_crowdsale_definitions(yaml_filename, deployment_name)
runtime_data, statistics, contracts = _deploy_contracts(project, chain, web3, yaml_filename, chain_data, deploy_address)
return contracts
| 7,982 |
def task_get_all(context, filters=None, marker=None, limit=None,
sort_key='created_at', sort_dir='desc', admin_as_user=False):
"""
Get all tasks that match zero or more filters.
:param filters: dict of filter keys and values.
:param marker: task id after which to start page
:param limit: maximum number of tasks to return
:param sort_key: task attribute by which results should be sorted
:param sort_dir: direction in which results should be sorted (asc, desc)
:param admin_as_user: For backwards compatibility. If true, then return to
an admin the equivalent set of tasks which it would see
if it were a regular user
:returns: tasks set
"""
filters = filters or {}
session = get_session()
query = session.query(models.Task)
if not (context.is_admin or admin_as_user) and context.owner is not None:
query = query.filter(models.Task.owner == context.owner)
_task_soft_delete(context, session=session)
showing_deleted = False
if 'deleted' in filters:
deleted_filter = filters.pop('deleted')
query = query.filter_by(deleted=deleted_filter)
showing_deleted = deleted_filter
for (k, v) in filters.items():
if v is not None:
key = k
if hasattr(models.Task, key):
query = query.filter(getattr(models.Task, key) == v)
marker_task = None
if marker is not None:
marker_task = _task_get(context, marker,
force_show_deleted=showing_deleted)
sort_keys = ['created_at', 'id']
if sort_key not in sort_keys:
sort_keys.insert(0, sort_key)
query = _paginate_query(query, models.Task, limit,
sort_keys,
marker=marker_task,
sort_dir=sort_dir)
task_refs = query.all()
tasks = []
for task_ref in task_refs:
tasks.append(_task_format(task_ref, task_info_ref=None))
return tasks
| 7,983 |
def updateAppMonConf(AppID, requestModel):
"""Update an Application Monitoring Configuration for a given application
Args:
AppID (str): This is the application ID of the Web App you are interested in.
requestModel: This is the data you wish to update and you need to put it in this
format:
{
"enabled": true,
"scanUrl": "https://mywebapp.com/directory"
}
explanation:
{
enabled (boolean): Enable Application Monitoring ,
scanUrl (string): Scan Url
}
Returns:
dict: Dictionary with the following layout
{
"success": true,
"errors": [
"string"
]
}
In the case of a return code 204, the update will take place but you will not
get the above layout, instead you will get a custom layout like this:
{'Response_Text': u'', 'Status_code': 204}
"""
url = "https://api.ams.fortify.com/api/v3/applications/{applicationId}/application-monitoring/configuration".format(applicationId=AppID)
req = fodRequest()
r = req.put(url, params=requestModel)
return r
#*******************************************************Applications**************************************************************
| 7,984 |
def plot_morphology(morphology,
order=MORPHOLOGY_ORDER,
colors=MORPHOLOGY_COLORS,
metastases=None,
metastasis_color=METASTASIS_COLOR,
ax=None,
bg_color='#f6f6f6',
**kwargs):
"""Plots morphology matrix as 2D heatmap.
Plots a morphology matrix (typically obtained from the parse_morphology
function) as a 2D heatmap. Matrix is expected to correspond with the
three categories returned by parse_morphology (ILC, Spindle cell
and Squamous).
Parameters
----------
morphology : pd.DataFrame
Boolean matrix of samples-by-morphologies.
order :
colors :
metastases : pd.DataFrame
Optional dataframe (single column) indicating which samples have
a metastasis. Used to draw metastases as an extra row in the heatmap.
metastasis_color :
ax : matplotlib.Axis
Axis to use for plotting.
bg_color : str
**kwargs
Any kwargs are passed to seaborns heatmap function.
Returns
-------
matplotlib.Axis
Axis that was used for plotting.
"""
if ax is None:
_, ax = plt.subplots()
# Add metastasis data if given.
if metastases is not None:
morphology = pd.concat([morphology, metastases], axis=1)
order = list(order) + [metastases.columns[0]]
colors = list(colors) + [metastasis_color]
# Sort by rows/columns.
morphology = morphology[list(order)]
morphology = sort_matrix(morphology, sort_columns=False)
# Convert to numeric matrix (for heatmap).
num_matrix = pd.DataFrame(
{
col: morphology[col].astype(int) * (i + 1)
for i, col in enumerate(morphology)
},
columns=morphology.columns)
# Draw heatmap.
cmap = ListedColormap([bg_color] + list(colors))
sns.heatmap(
num_matrix.T,
ax=ax,
cbar=False,
cmap=cmap,
vmin=0,
vmax=len(colors),
**kwargs)
ax.set_xticks([])
ax.set_xlim(0, num_matrix.shape[0])
ax.set_title('Tumor morphology')
ax.set_xlabel('Samples ({})'.format(morphology.shape[0]))
# Add counts to labels.
ax.set_yticklabels(
['{} ({})'.format(k, v) for k, v in morphology.sum().items()][::-1],
rotation=0)
return ax
| 7,985 |
def get_btc(path, date1, date2, period="5-min", delay=3):
"""
period = '5-min', 'Hourly'
"""
url2_1 = (
r"https://bitcoincharts.com/charts/chart.json?m=krakenUSD&SubmitButton=Draw&r=5&i="
+ period
+ "&c=1&s="
)
url2_2 = r"&Prev=&Next=&t=S&b=&a1=&m1=10&a2=&m2=25&x=0&i1=&i2=&i3=&i4=&v=1&cv=0&ps=0&l=0&p=0&"
Path(path).mkdir(parents=True, exist_ok=True)
with ProgressBar() as pb:
# print(int((end - start).days))cl
for d in pb(dates(date1, date2), total=int((date2 - date1).days)):
date = d.strftime("%Y-%m-%d")
r = requests.get(url2_1 + date + "&e=" + date + url2_2)
assert r.status_code == 200, "Page returned invalid response"
data = ast.literal_eval(r.text)
assert len(data[0]) == 8, "Data was improperly parsed"
headers = [
"Timestamp",
"Open",
"High",
"Low",
"Close",
"Volume(BTC)",
"Volume(Currency)",
"WeightedPrice",
]
with open(
os.path.join(path, f"{date}.csv"), mode="w", newline=""
) as data_file:
writer = csv.writer(data_file)
writer.writerow(headers)
writer.writerows(data)
time.sleep(delay)
| 7,986 |
def test_section_trsp(get_test_ds,myfunc,tfld,xflds,yflds,factor,args,mask,error):
"""compute a volume transport,
within the lat/lon portion of the domain"""
ds = get_test_ds
grid = ecco_v4_py.get_llc_grid(ds)
ds['U'],ds['V'] = get_fake_vectors(ds['U'],ds['V'])
for fx,fy in zip(xflds,yflds):
ds[fx] = ds['U'].copy()
ds[fy] = ds['V'].copy()
myargs = args.copy()
if mask:
myargs['maskW'],myargs['maskS'] = ecco_v4_py.vector_calc.get_latitude_masks(30,ds['YC'],grid)
else:
myargs['maskW']=None
myargs['maskS']=None
if error is None:
trsp = myfunc(ds,grid=grid,**myargs)
maskW,maskS = ecco_v4_py.calc_section_trsp._parse_section_trsp_inputs(ds,
grid=grid,**myargs)
expx = (ds['drF']*ds['dyG']).copy() if tfld == 'vol_trsp_z' else 2.*xr.ones_like(ds['hFacW'])
expy = (ds['drF']*ds['dxG']).copy() if tfld == 'vol_trsp_z' else 2.*xr.ones_like(ds['hFacS'])
trspx = (expx*np.abs(maskW)).where(ds['maskW']).sum(dim=['i_g','j','tile'])
trspy = (expy*np.abs(maskS)).where(ds['maskS']).sum(dim=['i','j_g','tile'])
test = trsp[tfld].squeeze().reset_coords(drop=True)
expected = (factor*(trspx+trspy)).reset_coords(drop=True)
xr.testing.assert_equal(test,expected)
else:
with pytest.raises(error):
trsp = myfunc(ds,**myargs)
| 7,987 |
def scores_summary(CurDataDir, steps = 300, population_size = 40, regenerate=False):
"""Obsolete for the one above! better and more automatic"""
ScoreEvolveTable = np.full((steps, population_size,), np.NAN)
ImagefnTable = [[""] * population_size for i in range(steps)]
fncatalog = os.listdir(CurDataDir)
if "scores_summary_table.npz" in fncatalog and (not regenerate):
# if the summary table exist, just read from it!
with np.load(os.path.join(CurDataDir, "scores_summary_table.npz")) as data:
ScoreEvolveTable = data['ScoreEvolveTable']
ImagefnTable = data['ImagefnTable']
return ScoreEvolveTable, ImagefnTable
startnum = 0
for stepi in range(startnum, steps):
try:
with np.load(os.path.join(CurDataDir, "scores_end_block{0:03}.npz".format(stepi))) as data:
score_tmp = data['scores']
image_ids = data['image_ids']
ScoreEvolveTable[stepi, :len(score_tmp)] = score_tmp
if stepi==0:
image_fns = image_ids
else:
image_fns = []
for imgid in image_ids:
fn_tmp_list = [fn for fn in fncatalog if (imgid in fn) and ('.npy' in fn)]
assert len(fn_tmp_list) is 1, "Code file not found or wrong Code file number"
image_fns.append(fn_tmp_list[0])
ImagefnTable[stepi][0:len(score_tmp)] = image_fns
# FIXME: 1st generation natural stimuli is not in the directory! so it's not possible to get the file name there. Here just put the codeid
except FileNotFoundError:
if stepi == 0:
startnum += 1
steps += 1
continue
else:
print("maximum steps is %d." % stepi)
ScoreEvolveTable = ScoreEvolveTable[0:stepi, :]
ImagefnTable = ImagefnTable[0:stepi]
steps = stepi
break
ImagefnTable = np.asarray(ImagefnTable)
savez(os.path.join(CurDataDir, "scores_summary_table.npz"),
{"ScoreEvolveTable": ScoreEvolveTable, "ImagefnTable": ImagefnTable})
return ScoreEvolveTable, ImagefnTable
| 7,988 |
def post(name,url,message,params=None):
"""Wrap a post in some basic error reporting"""
start = dt.now()
s = requests.session()
if params is None:
response = s.post(url,json=message)
else:
response = s.post(url,json=message,params=params)
end = dt.now()
if not response.status_code == 200:
print(name, 'error:',response.status_code)
print(response.json())
return response.json()
print(f'{name} returned in {end-start}s')
m = response.json()
if 'message' in m:
if 'results' in m['message']:
print(f'Num Results: {len(m["message"]["results"])}')
print_errors(m)
return m
| 7,989 |
def get_lin_reg_results(est, true, zero_tol=0):
"""
Parameters
----------
est: an Estimator
A covariance estimator.
true: array-like, shape (n_features, n_features)
zero_tol: float
Output
------
out: dict with keys 'utri' and 'graph'
"""
est_coef = get_coef(est)[0]
est_adj = fill_hollow_sym(est_coef)
true_adj = fill_hollow_sym(est_coef)
coef_results = compare_vecs(est=est_coef, truth=true,
zero_tol=zero_tol)
graph_results = compare_adj_mats(est=est_adj, truth=true_adj,
zero_tol=zero_tol)
results = merge_dicts(coef_results, graph_results, allow_key_overlap=False)
return results
| 7,990 |
def download_file(requested_url: str) -> str:
"""Download a file from github repository"""
url = f"https://github.com/{requested_url.replace('blob', 'raw')}"
resp = requests.get(url)
logging.info(F"Requested URL: {requested_url}")
if resp.status_code != 200:
logging.info(f"Can not download {url}")
raise NotebookDownloadException("Can not download the file. Please, check the URL")
return resp.text
| 7,991 |
def readBody(response):
"""
Get the body of an L{IResponse} and return it as a byte string.
This is a helper function for clients that don't want to incrementally
receive the body of an HTTP response.
@param response: The HTTP response for which the body will be read.
@type response: L{IResponse} provider
@return: A L{Deferred} which will fire with the body of the response.
Cancelling it will close the connection to the server immediately.
"""
def cancel(deferred):
"""
Cancel a L{readBody} call, close the connection to the HTTP server
immediately, if it is still open.
@param deferred: The cancelled L{defer.Deferred}.
"""
abort = getAbort()
if abort is not None:
abort()
d = defer.Deferred(cancel)
protocol = _ReadBodyProtocol(response.code, response.phrase, d)
def getAbort():
return getattr(protocol.transport, 'abortConnection', None)
response.deliverBody(protocol)
if protocol.transport is not None and getAbort() is None:
warnings.warn(
'Using readBody with a transport that does not have an '
'abortConnection method',
category=DeprecationWarning,
stacklevel=2)
return d
| 7,992 |
def is_valid_mac(address):
"""Verify the format of a MAC address."""
class mac_dialect(netaddr.mac_eui48):
word_fmt = '%.02x'
word_sep = ':'
try:
na = netaddr.EUI(address, dialect=mac_dialect)
except Exception:
return False
return str(na) == address.lower()
| 7,993 |
def build_state_abstraction(similar_states, mdp, tol=0.1):
"""
"""
bools = similar_states + np.eye(similar_states.shape[0]) < tol # approximate abstraction
if bools.sum() == 0:
raise ValueError('No abstraction')
mapping, parts = partitions(bools)
idx = list(set(np.array([p[0] for p in parts]))) # pick a representative set of states. one from each partition
f = construct_abstraction_fn(mapping, idx, mdp.S, len(idx))
# print('Abstracting from {} states to {} states'.format(mdp.S, len(parts)))
# print('idx', idx)
# print('mapping', mapping)
# print('parts', parts)
# mapping, parts = fix_mapping(mapping)
# print(f)
# print(f.shape, abs_mdp.S)
abs_mdp = abstract_the_mdp(mdp, idx)
# want a way to do this stuff in numpy!?
# should calculate the error of the abstraction?! check it is related to tol!?
return idx, abs_mdp, f
| 7,994 |
def diagram(source, rstrip=True):
"""High level API to generate ASCII diagram.
This function is equivalent to:
.. code-block:: python
Diagram(source).renders()
:param source: The ADia source code.
:type source: str or file-like
:param rstrip: If ``True``, the trailing wihtespaces at the end of each
line will be removed.
:type rstrip: bool, optional, default: True
:return: ASCII diagram.
:rtype: str
"""
return Diagram(source).renders(rstrip)
| 7,995 |
def eng_to_kong(eng_word: str)-> list[str]:
"""
Translate given English word into Korean into matching pronounciation,
matching the English Loanword Orthography.
For example, "hello" will be translated into 헐로.
# Panics
When given a english word that it cannot translate, `eng_to_kong` will raise a KeyError.
Example
```python
import konglog
def main():
word = "shrimp"
print(konglog.eng_to_kong(word))
```
"""
# Parse word into phonemes string for passing to Prolog Query.
prolog_arg_aras = "]"
for phe in cmudict.dict()[eng_word.lower().strip()][0]:
if phe[-1] == '0' or phe[-1] == '1' or phe[-1] == '2':
phe = phe[:-1]
prolog_arg_aras = "," + phe.lower() + prolog_arg_aras
prolog_arg_aras = "[" + prolog_arg_aras[1:]
# Execute Prolog query
with PrologMQI() as mqi:
with mqi.create_thread() as prolog_thread:
assert(prolog_thread.query("consult(\"ipa.pl\")"))
prolog_res = prolog_thread.query(f"ipa_to_kr(X,{prolog_arg_aras})")
# Parse results
jamo_lists = []
try:
for jls in prolog_res:
temp = jls['X']
temp.reverse()
jamo_lists.append(temp)
except TypeError:
raise KeyError
jamo_all = []
for jamo_list in jamo_lists:
temp_jamo_all = [""]
for jamos in jamo_list:
if isinstance(jamos, str):
for i in range(len(temp_jamo_all)):
temp_jamo_all[i] += jamos
else:
temp = []
for jamo in jamos:
for s in temp_jamo_all:
temp.append(s + jamo)
temp_jamo_all = temp
jamo_all.extend(temp_jamo_all)
# Combine jamos into Konglish word
jamo_all.sort(key = lambda x : len(x))
for jamos in jamo_all:
try:
return join_jamos(jamos, False)
except ValueError:
continue
| 7,996 |
def test_ME109(applicability_code, amount):
"""
If the flag 'amount' on duty expression is 'mandatory' then an amount must
be specified.
If the flag is set to 'not permitted' then no amount may be entered.
"""
measure = factories.MeasureFactory.create()
condition = factories.MeasureConditionComponentFactory.create(
condition__dependent_measure=measure,
duty_expression__duty_amount_applicability_code=applicability_code,
duty_amount=amount,
)
with pytest.raises(BusinessRuleViolation):
business_rules.ME109(condition.transaction).validate(measure)
| 7,997 |
def write_csv(path, data):
"""TODO"""
with open(path, 'w', newline='', encoding='utf-8') as csv_file:
writer = csv.writer(csv_file)
writer.writerows(data)
| 7,998 |
def targets_to_moves(
initial: Coordinates[AxisKey, CoordinateValue], targets: List[MoveTarget[AxisKey]]
) -> Iterator[Move[AxisKey]]:
"""Transform a list of MoveTargets into a list of Moves."""
all_axes: Set[AxisKey] = set()
for target in targets:
all_axes.update(set(target.position.keys()))
initial_checked = {k: np.float64(initial.get(k, 0)) for k in all_axes}
for target in targets:
position = {k: np.float64(target.position.get(k, 0)) for k in all_axes}
unit_vector, distance = get_unit_vector(initial_checked, position)
third_distance = np.float64(distance / 3)
m = Move(
unit_vector=unit_vector,
distance=distance,
max_speed=target.max_speed,
blocks=(
Block(
distance=third_distance,
initial_speed=target.max_speed,
acceleration=np.float64(0),
),
Block(
distance=third_distance,
initial_speed=target.max_speed,
acceleration=np.float64(0),
),
Block(
distance=third_distance,
initial_speed=target.max_speed,
acceleration=np.float64(0),
),
),
)
log.debug(f"Built move from {initial} to {target} as {m}")
yield m
initial_checked = position
| 7,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.