hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f72ef9eff5cffb76416d59a9c3337dac4842e086 | 2,066 | py | Python | flaskblog/posts/routes.py | amiinegal/Blog | b88b29603832048a1322cfd79b2cef0684282f4b | [
"Unlicense",
"MIT"
] | null | null | null | flaskblog/posts/routes.py | amiinegal/Blog | b88b29603832048a1322cfd79b2cef0684282f4b | [
"Unlicense",
"MIT"
] | null | null | null | flaskblog/posts/routes.py | amiinegal/Blog | b88b29603832048a1322cfd79b2cef0684282f4b | [
"Unlicense",
"MIT"
] | null | null | null | from flask import (render_template, url_for, flash,
redirect, request, abort, Blueprint)
from flask_login import current_user, login_required
from flaskblog import db
from flaskblog.models import Post
from flaskblog.posts.forms import PostForm
posts = Blueprint('posts', __name__)
@posts.route("/post/new", methods=['GET', 'POST'])
@login_required
def new_post():
form = PostForm()
if form.validate_on_submit():
post = Post(title=form.title.data, content=form.content.data, author=current_user)
db.session.add(post)
db.session.commit()
flash('Your post has been created!', 'success')
return redirect(url_for('main.home_page'))
return render_template('create_post.html', title='New Post',
form=form, legend='New Post')
@posts.route("/post/<int:post_id>")
def post(post_id):
post = Post.query.get_or_404(post_id)
return render_template('post.html', title=post.title, post=post)
@posts.route("/post/<int:post_id>/update", methods=['GET', 'POST'])
@login_required
def update_post(post_id):
post = Post.query.get_or_404(post_id)
if post.author != current_user:
abort(403)
form = PostForm()
if form.validate_on_submit():
post.title = form.title.data
post.content = form.content.data
db.session.commit()
flash('Your post has been updated!', 'success')
return redirect(url_for('posts.post', post_id=post.id))
elif request.method == 'GET':
form.title.data = post.title
form.content.data = post.content
return render_template('create_post.html', title='Update Post',
form=form, legend='Update Post')
@posts.route("/post/<int:post_id>/delete", methods=['POST'])
@login_required
def delete_post(post_id):
post = Post.query.get_or_404(post_id)
if post.author != current_user:
abort(403)
db.session.delete(post)
db.session.commit()
flash('Your post has been deleted!', 'success')
return redirect(url_for('main.home'))
| 33.868852 | 90 | 0.664085 | from flask import (render_template, url_for, flash,
redirect, request, abort, Blueprint)
from flask_login import current_user, login_required
from flaskblog import db
from flaskblog.models import Post
from flaskblog.posts.forms import PostForm
posts = Blueprint('posts', __name__)
@posts.route("/post/new", methods=['GET', 'POST'])
@login_required
def new_post():
form = PostForm()
if form.validate_on_submit():
post = Post(title=form.title.data, content=form.content.data, author=current_user)
db.session.add(post)
db.session.commit()
flash('Your post has been created!', 'success')
return redirect(url_for('main.home_page'))
return render_template('create_post.html', title='New Post',
form=form, legend='New Post')
@posts.route("/post/<int:post_id>")
def post(post_id):
post = Post.query.get_or_404(post_id)
return render_template('post.html', title=post.title, post=post)
@posts.route("/post/<int:post_id>/update", methods=['GET', 'POST'])
@login_required
def update_post(post_id):
post = Post.query.get_or_404(post_id)
if post.author != current_user:
abort(403)
form = PostForm()
if form.validate_on_submit():
post.title = form.title.data
post.content = form.content.data
db.session.commit()
flash('Your post has been updated!', 'success')
return redirect(url_for('posts.post', post_id=post.id))
elif request.method == 'GET':
form.title.data = post.title
form.content.data = post.content
return render_template('create_post.html', title='Update Post',
form=form, legend='Update Post')
@posts.route("/post/<int:post_id>/delete", methods=['POST'])
@login_required
def delete_post(post_id):
post = Post.query.get_or_404(post_id)
if post.author != current_user:
abort(403)
db.session.delete(post)
db.session.commit()
flash('Your post has been deleted!', 'success')
return redirect(url_for('main.home'))
| true | true |
f72ef9fd42c6c5d66574a205a52aee8fc64d8a20 | 690 | py | Python | backend/migrations/versions/ae566f24d973_.py | sartography/star-drive | c0f33378d42913c3e677e07f74eb46d7b2b82a0a | [
"MIT"
] | null | null | null | backend/migrations/versions/ae566f24d973_.py | sartography/star-drive | c0f33378d42913c3e677e07f74eb46d7b2b82a0a | [
"MIT"
] | 368 | 2018-12-18T14:43:20.000Z | 2022-03-02T02:54:18.000Z | backend/migrations/versions/ae566f24d973_.py | sartography/star-drive | c0f33378d42913c3e677e07f74eb46d7b2b82a0a | [
"MIT"
] | 2 | 2019-10-02T03:06:06.000Z | 2020-10-05T16:53:48.000Z | """empty message
Revision ID: ae566f24d973
Revises: 838f47fa598e
Create Date: 2020-02-18 17:02:08.574872
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ae566f24d973'
down_revision = '838f47fa598e'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('stardrive_user', sa.Column('last_login', sa.DateTime(timezone=True), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('stardrive_user', 'last_login')
# ### end Alembic commands ###
| 23.793103 | 103 | 0.705797 | from alembic import op
import sqlalchemy as sa
revision = 'ae566f24d973'
down_revision = '838f47fa598e'
branch_labels = None
depends_on = None
def upgrade():
| true | true |
f72efb136a1aa339fcf07bfbcbdf071f1369ec8a | 883 | py | Python | dynadb/migrations/0075_auto_20170124_1439.py | GPCRmd/GPCRmd | 7dc75359ace4a00c1597bdb7a86ebee17d51f09c | [
"Apache-2.0"
] | 3 | 2019-03-06T13:35:38.000Z | 2020-08-05T15:31:29.000Z | dynadb/migrations/0075_auto_20170124_1439.py | GPCRmd/GPCRmd | 7dc75359ace4a00c1597bdb7a86ebee17d51f09c | [
"Apache-2.0"
] | null | null | null | dynadb/migrations/0075_auto_20170124_1439.py | GPCRmd/GPCRmd | 7dc75359ace4a00c1597bdb7a86ebee17d51f09c | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-01-24 13:39
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dynadb', '0074_auto_20170123_1212'),
]
operations = [
migrations.AlterField(
model_name='dyndbefficacy',
name='reference_id_compound',
field=models.ForeignKey(db_column='reference_id_compound', null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dynadb.DyndbCompound'),
),
migrations.AlterField(
model_name='dyndbefficacy',
name='type',
field=models.SmallIntegerField(choices=[(0, 'Full Agonist'), (1, 'Partial Agonist'), (2, 'Antagonist'), (3, 'Inverse Agonist'), (4, 'Other')], default=0),
),
]
| 32.703704 | 166 | 0.642129 |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dynadb', '0074_auto_20170123_1212'),
]
operations = [
migrations.AlterField(
model_name='dyndbefficacy',
name='reference_id_compound',
field=models.ForeignKey(db_column='reference_id_compound', null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='dynadb.DyndbCompound'),
),
migrations.AlterField(
model_name='dyndbefficacy',
name='type',
field=models.SmallIntegerField(choices=[(0, 'Full Agonist'), (1, 'Partial Agonist'), (2, 'Antagonist'), (3, 'Inverse Agonist'), (4, 'Other')], default=0),
),
]
| true | true |
f72efbf64861c201c9fde808e528c73dae484dc4 | 1,157 | py | Python | genomepy/plugins/minimap2.py | tilschaef/genomepy | 4c10e69b6886cf52381caf6498395391834a675b | [
"MIT"
] | 146 | 2019-11-19T16:07:46.000Z | 2022-03-15T16:10:31.000Z | genomepy/plugins/minimap2.py | tilschaef/genomepy | 4c10e69b6886cf52381caf6498395391834a675b | [
"MIT"
] | 125 | 2019-11-19T18:08:23.000Z | 2022-03-30T09:16:46.000Z | genomepy/plugins/minimap2.py | tilschaef/genomepy | 4c10e69b6886cf52381caf6498395391834a675b | [
"MIT"
] | 18 | 2019-12-02T15:54:34.000Z | 2022-03-04T19:16:31.000Z | import os
from genomepy.plugins import Plugin
from genomepy.utils import cmd_ok, mkdir_p, rm_rf, run_index_cmd
class Minimap2Plugin(Plugin):
def after_genome_download(self, genome, threads=1, force=False):
if not cmd_ok("minimap2"):
return
# Create index dir
index_dir = genome.plugin["minimap2"]["index_dir"]
index_name = genome.plugin["minimap2"]["index_name"]
if force:
# Start from scratch
rm_rf(index_dir)
mkdir_p(index_dir)
if not any(fname.endswith(".mmi") for fname in os.listdir(index_dir)):
# Create index
cmd = f"minimap2 -t {threads} -d {index_name} {genome.filename}"
run_index_cmd("minimap2", cmd)
def get_properties(self, genome):
props = {
"index_dir": os.path.join(
os.path.dirname(genome.filename), "index", "minimap2"
),
"index_name": os.path.join(
os.path.dirname(genome.filename),
"index",
"minimap2",
f"{genome.name}.mmi",
),
}
return props
| 30.447368 | 78 | 0.560069 | import os
from genomepy.plugins import Plugin
from genomepy.utils import cmd_ok, mkdir_p, rm_rf, run_index_cmd
class Minimap2Plugin(Plugin):
def after_genome_download(self, genome, threads=1, force=False):
if not cmd_ok("minimap2"):
return
index_dir = genome.plugin["minimap2"]["index_dir"]
index_name = genome.plugin["minimap2"]["index_name"]
if force:
rm_rf(index_dir)
mkdir_p(index_dir)
if not any(fname.endswith(".mmi") for fname in os.listdir(index_dir)):
cmd = f"minimap2 -t {threads} -d {index_name} {genome.filename}"
run_index_cmd("minimap2", cmd)
def get_properties(self, genome):
props = {
"index_dir": os.path.join(
os.path.dirname(genome.filename), "index", "minimap2"
),
"index_name": os.path.join(
os.path.dirname(genome.filename),
"index",
"minimap2",
f"{genome.name}.mmi",
),
}
return props
| true | true |
f72efca428a828d722447e9aced971774beef150 | 4,183 | py | Python | python/nano/src/bigdl/nano/automl/tf/objective.py | Forest216/BigDL | 840da9a2eaf395978dd83730b02aa5e5dfbd7989 | [
"Apache-2.0"
] | null | null | null | python/nano/src/bigdl/nano/automl/tf/objective.py | Forest216/BigDL | 840da9a2eaf395978dd83730b02aa5e5dfbd7989 | [
"Apache-2.0"
] | null | null | null | python/nano/src/bigdl/nano/automl/tf/objective.py | Forest216/BigDL | 840da9a2eaf395978dd83730b02aa5e5dfbd7989 | [
"Apache-2.0"
] | null | null | null | #
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from selectors import EpollSelector
from tensorflow.keras.backend import clear_session
from tensorflow.keras.models import clone_model
import tensorflow as tf
import inspect
import copy
from bigdl.nano.automl.hpo.backend import create_tfkeras_pruning_callback
from bigdl.nano.utils.log4Error import invalidInputError
def _is_creator(model):
return inspect.ismethod(model) or inspect.isfunction(model)
class Objective(object):
"""The Tuning objective for HPO."""
def __init__(self,
model=None,
target_metric=None,
pruning=False,
backend=None,
**kwargs
):
"""
Init the objective.
:param: model: a model instance or a creator function.
Defaults to None.
:param: target_metric: str(optional): target metric to optimize.
Defaults to None.
:param: pruning: bool (optional): whether to enable pruning.
Defaults to False.
throw: ValueError: _description_
"""
if not _is_creator(model) and not isinstance(model, tf.keras.Model):
invalidInputError(False,
"You should either pass a Tensorflo Keras model, or "
"a model_creator to the Tuning objective.")
self.model_ = model
self.target_metric_ = target_metric
self.pruning = pruning
self.backend = backend
self.kwargs = kwargs
@property
def target_metric(self):
"""Get the target metric."""
return self.target_metric_
@target_metric.setter
def target_metric(self, value):
"""Set the target metric."""
# TODO add more validity check here
self.target_metric_ = value
def _prepare_fit_args(self, trial):
# only do shallow copy and process/duplicate
# specific args TODO: may need to handle more cases
new_kwargs = copy.copy(self.kwargs)
new_kwargs['verbose'] = 2
# process batch size
new_kwargs = self.backend.instantiate_param(trial, new_kwargs, 'batch_size')
# process callbacks
callbacks = new_kwargs.get('callbacks', None)
callbacks = callbacks() if inspect.isfunction(callbacks) else callbacks
if self.pruning:
callbacks = callbacks or []
prune_callback = create_tfkeras_pruning_callback(trial, self.target_metric)
callbacks.append(prune_callback)
new_kwargs['callbacks'] = callbacks
return new_kwargs
def __call__(self, trial):
"""
Execute Training and return target metric in each trial.
:param: trial: the trial object which provides the hyperparameter combinition.
:return: the target metric value.
"""
# Clear clutter from previous Keras session graphs.
clear_session()
# TODO may add data creator here, e.g. refresh data, reset generators, etc.
# create model
if _is_creator(self.model_):
model = self.model_(trial)
else:
# copy model so that the original model is not changed
# Need tests to check this path
model = clone_model(self.model_)
# fit
new_kwargs = self._prepare_fit_args(trial)
hist = model.fit(**new_kwargs)
score = hist.history.get(self.target_metric, None)
if score is not None:
if isinstance(score, list):
# score = score[-1]
score = max(score)
return score
| 33.464 | 87 | 0.638059 |
from selectors import EpollSelector
from tensorflow.keras.backend import clear_session
from tensorflow.keras.models import clone_model
import tensorflow as tf
import inspect
import copy
from bigdl.nano.automl.hpo.backend import create_tfkeras_pruning_callback
from bigdl.nano.utils.log4Error import invalidInputError
def _is_creator(model):
return inspect.ismethod(model) or inspect.isfunction(model)
class Objective(object):
def __init__(self,
model=None,
target_metric=None,
pruning=False,
backend=None,
**kwargs
):
if not _is_creator(model) and not isinstance(model, tf.keras.Model):
invalidInputError(False,
"You should either pass a Tensorflo Keras model, or "
"a model_creator to the Tuning objective.")
self.model_ = model
self.target_metric_ = target_metric
self.pruning = pruning
self.backend = backend
self.kwargs = kwargs
@property
def target_metric(self):
return self.target_metric_
@target_metric.setter
def target_metric(self, value):
self.target_metric_ = value
def _prepare_fit_args(self, trial):
new_kwargs = copy.copy(self.kwargs)
new_kwargs['verbose'] = 2
new_kwargs = self.backend.instantiate_param(trial, new_kwargs, 'batch_size')
callbacks = new_kwargs.get('callbacks', None)
callbacks = callbacks() if inspect.isfunction(callbacks) else callbacks
if self.pruning:
callbacks = callbacks or []
prune_callback = create_tfkeras_pruning_callback(trial, self.target_metric)
callbacks.append(prune_callback)
new_kwargs['callbacks'] = callbacks
return new_kwargs
def __call__(self, trial):
clear_session()
if _is_creator(self.model_):
model = self.model_(trial)
else:
model = clone_model(self.model_)
new_kwargs = self._prepare_fit_args(trial)
hist = model.fit(**new_kwargs)
score = hist.history.get(self.target_metric, None)
if score is not None:
if isinstance(score, list):
score = max(score)
return score
| true | true |
f72efd44eb8409c927c2b099abb4c95c6681f60d | 2,428 | py | Python | examples/python/onnx/mnist_mlp.py | jiazhihao/FlexFlow-1 | b9bf0b615d8cf6d22bc38de4755b76ee3f8c4c22 | [
"Apache-2.0"
] | 1 | 2021-03-09T05:43:58.000Z | 2021-03-09T05:43:58.000Z | examples/python/onnx/mnist_mlp.py | jiazhihao/FlexFlow-1 | b9bf0b615d8cf6d22bc38de4755b76ee3f8c4c22 | [
"Apache-2.0"
] | null | null | null | examples/python/onnx/mnist_mlp.py | jiazhihao/FlexFlow-1 | b9bf0b615d8cf6d22bc38de4755b76ee3f8c4c22 | [
"Apache-2.0"
] | null | null | null | from flexflow.core import *
import numpy as np
from flexflow.keras.datasets import mnist
from flexflow.onnx.model import ONNXModel
from accuracy import ModelAccuracy
def top_level_task():
ffconfig = FFConfig()
ffconfig.parse_args()
print("Python API batchSize(%d) workersPerNodes(%d) numNodes(%d)" %(ffconfig.get_batch_size(), ffconfig.get_workers_per_node(), ffconfig.get_num_nodes()))
ffmodel = FFModel(ffconfig)
dims1 = [ffconfig.get_batch_size(), 784]
input1 = ffmodel.create_tensor(dims1, DataType.DT_FLOAT);
num_samples = 60000
onnx_model = ONNXModel("mnist_mlp.onnx")
t = onnx_model.apply(ffmodel, {"input.1": input1})
ffoptimizer = SGDOptimizer(ffmodel, 0.01)
ffmodel.set_sgd_optimizer(ffoptimizer)
ffmodel.compile(loss_type=LossType.LOSS_SPARSE_CATEGORICAL_CROSSENTROPY, metrics=[MetricsType.METRICS_ACCURACY, MetricsType.METRICS_SPARSE_CATEGORICAL_CROSSENTROPY])
label = ffmodel.get_label_tensor()
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 784)
x_train = x_train.astype('float32')
x_train /= 255
y_train = y_train.astype('int32')
y_train = np.reshape(y_train, (len(y_train), 1))
dims_full_input = [num_samples, 784]
full_input = ffmodel.create_tensor(dims_full_input, DataType.DT_FLOAT)
dims_full_label = [num_samples, 1]
full_label = ffmodel.create_tensor(dims_full_label, DataType.DT_INT32)
full_input.attach_numpy_array(ffconfig, x_train)
full_label.attach_numpy_array(ffconfig, y_train)
dataloader_input = SingleDataLoader(ffmodel, input1, full_input, num_samples, DataType.DT_FLOAT)
dataloader_label = SingleDataLoader(ffmodel, label, full_label, num_samples, DataType.DT_INT32)
full_input.detach_numpy_array(ffconfig)
full_label.detach_numpy_array(ffconfig)
ffmodel.init_layers()
epochs = ffconfig.get_epochs()
ts_start = ffconfig.get_current_time()
ffmodel.fit(x=dataloader_input, y=dataloader_label, epochs=epochs)
ts_end = ffconfig.get_current_time()
run_time = 1e-6 * (ts_end - ts_start);
print("epochs %d, ELAPSED TIME = %.4fs, THROUGHPUT = %.2f samples/s\n" %(epochs, run_time, num_samples * epochs / run_time));
perf_metrics = ffmodel.get_perf_metrics()
accuracy = perf_metrics.get_accuracy()
if accuracy < ModelAccuracy.MNIST_MLP.value:
assert 0, 'Check Accuracy'
if __name__ == "__main__":
print("mnist mlp onnx")
top_level_task()
| 34.685714 | 167 | 0.76112 | from flexflow.core import *
import numpy as np
from flexflow.keras.datasets import mnist
from flexflow.onnx.model import ONNXModel
from accuracy import ModelAccuracy
def top_level_task():
ffconfig = FFConfig()
ffconfig.parse_args()
print("Python API batchSize(%d) workersPerNodes(%d) numNodes(%d)" %(ffconfig.get_batch_size(), ffconfig.get_workers_per_node(), ffconfig.get_num_nodes()))
ffmodel = FFModel(ffconfig)
dims1 = [ffconfig.get_batch_size(), 784]
input1 = ffmodel.create_tensor(dims1, DataType.DT_FLOAT);
num_samples = 60000
onnx_model = ONNXModel("mnist_mlp.onnx")
t = onnx_model.apply(ffmodel, {"input.1": input1})
ffoptimizer = SGDOptimizer(ffmodel, 0.01)
ffmodel.set_sgd_optimizer(ffoptimizer)
ffmodel.compile(loss_type=LossType.LOSS_SPARSE_CATEGORICAL_CROSSENTROPY, metrics=[MetricsType.METRICS_ACCURACY, MetricsType.METRICS_SPARSE_CATEGORICAL_CROSSENTROPY])
label = ffmodel.get_label_tensor()
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 784)
x_train = x_train.astype('float32')
x_train /= 255
y_train = y_train.astype('int32')
y_train = np.reshape(y_train, (len(y_train), 1))
dims_full_input = [num_samples, 784]
full_input = ffmodel.create_tensor(dims_full_input, DataType.DT_FLOAT)
dims_full_label = [num_samples, 1]
full_label = ffmodel.create_tensor(dims_full_label, DataType.DT_INT32)
full_input.attach_numpy_array(ffconfig, x_train)
full_label.attach_numpy_array(ffconfig, y_train)
dataloader_input = SingleDataLoader(ffmodel, input1, full_input, num_samples, DataType.DT_FLOAT)
dataloader_label = SingleDataLoader(ffmodel, label, full_label, num_samples, DataType.DT_INT32)
full_input.detach_numpy_array(ffconfig)
full_label.detach_numpy_array(ffconfig)
ffmodel.init_layers()
epochs = ffconfig.get_epochs()
ts_start = ffconfig.get_current_time()
ffmodel.fit(x=dataloader_input, y=dataloader_label, epochs=epochs)
ts_end = ffconfig.get_current_time()
run_time = 1e-6 * (ts_end - ts_start);
print("epochs %d, ELAPSED TIME = %.4fs, THROUGHPUT = %.2f samples/s\n" %(epochs, run_time, num_samples * epochs / run_time));
perf_metrics = ffmodel.get_perf_metrics()
accuracy = perf_metrics.get_accuracy()
if accuracy < ModelAccuracy.MNIST_MLP.value:
assert 0, 'Check Accuracy'
if __name__ == "__main__":
print("mnist mlp onnx")
top_level_task()
| true | true |
f72efd6fc94e91466ebd1578b756f630faaefffc | 1,461 | py | Python | spiral.py | vimithamanohar/practice | 3e5372aeb29b9db3467c97ef8c4f879fff1ac7b7 | [
"MIT"
] | null | null | null | spiral.py | vimithamanohar/practice | 3e5372aeb29b9db3467c97ef8c4f879fff1ac7b7 | [
"MIT"
] | null | null | null | spiral.py | vimithamanohar/practice | 3e5372aeb29b9db3467c97ef8c4f879fff1ac7b7 | [
"MIT"
] | null | null | null | import math
import unittest
def get_line(arr, x, y, ln, dx, dy):
ret = []
for i in range(ln):
ret.append(arr[x][y])
x = x + dx
y = y + dy
return ret
def get_square(arr, x, y, ln):
if ln == 0:
return []
if ln == 1:
return [arr[x][y]]
ret = []
ret.extend(get_line(arr, x, y, ln - 1, 0, 1))
ret.extend(get_line(arr, x, y + ln - 1, ln - 1, 1, 0))
ret.extend(get_line(arr, x + ln - 1, y + ln - 1, ln - 1, 0, -1))
ret.extend(get_line(arr, x + ln - 1, y, ln - 1, -1, 0))
return ret
def get_spiral(arr):
arr_len = len(arr)
if arr_len == 0:
return []
ret = []
for i in range(math.ceil(arr_len / 2)):
ret.extend(get_square(arr, i, i, arr_len - i * 2))
return ret
class TestSpiral(unittest.TestCase):
def test_len_3(self):
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
self.assertEqual(get_spiral(a), [1, 2, 3, 6, 9, 8, 7, 4, 5])
def test_len_4(self):
a = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
self.assertEqual(get_spiral(a), [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10])
def test_len_1(self):
a = [[1]]
self.assertEqual(get_spiral(a), [1])
def test_len_0(self):
a = []
self.assertEqual(get_spiral(a), [])
if __name__ == '__main__':
unittest.main()
| 22.476923 | 96 | 0.473648 | import math
import unittest
def get_line(arr, x, y, ln, dx, dy):
ret = []
for i in range(ln):
ret.append(arr[x][y])
x = x + dx
y = y + dy
return ret
def get_square(arr, x, y, ln):
if ln == 0:
return []
if ln == 1:
return [arr[x][y]]
ret = []
ret.extend(get_line(arr, x, y, ln - 1, 0, 1))
ret.extend(get_line(arr, x, y + ln - 1, ln - 1, 1, 0))
ret.extend(get_line(arr, x + ln - 1, y + ln - 1, ln - 1, 0, -1))
ret.extend(get_line(arr, x + ln - 1, y, ln - 1, -1, 0))
return ret
def get_spiral(arr):
arr_len = len(arr)
if arr_len == 0:
return []
ret = []
for i in range(math.ceil(arr_len / 2)):
ret.extend(get_square(arr, i, i, arr_len - i * 2))
return ret
class TestSpiral(unittest.TestCase):
def test_len_3(self):
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
self.assertEqual(get_spiral(a), [1, 2, 3, 6, 9, 8, 7, 4, 5])
def test_len_4(self):
a = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
self.assertEqual(get_spiral(a), [1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10])
def test_len_1(self):
a = [[1]]
self.assertEqual(get_spiral(a), [1])
def test_len_0(self):
a = []
self.assertEqual(get_spiral(a), [])
if __name__ == '__main__':
unittest.main()
| true | true |
f72efd91fc83e7a45d20c311f82e965626069a2c | 13,324 | py | Python | i3pystatus/network.py | MaicoTimmerman/i3pystatus | dbfc94575b287420159434df2bb00fedeebeb2ed | [
"MIT"
] | null | null | null | i3pystatus/network.py | MaicoTimmerman/i3pystatus | dbfc94575b287420159434df2bb00fedeebeb2ed | [
"MIT"
] | null | null | null | i3pystatus/network.py | MaicoTimmerman/i3pystatus | dbfc94575b287420159434df2bb00fedeebeb2ed | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import netifaces
from i3pystatus import IntervalModule
from i3pystatus.core.color import ColorRangeModule
from i3pystatus.core.util import make_graph, round_dict, make_bar
def count_bits(integer):
bits = 0
while (integer):
integer &= integer - 1
bits += 1
return bits
def v6_to_int(v6):
return int(v6.replace(":", ""), 16)
def prefix6(mask):
return count_bits(v6_to_int(mask))
def cidr6(addr, mask):
return "{addr}/{bits}".format(addr=addr, bits=prefix6(mask))
def v4_to_int(v4):
sum = 0
mul = 1
for part in reversed(v4.split(".")):
sum += int(part) * mul
mul *= 2 ** 8
return sum
def prefix4(mask):
return count_bits(v4_to_int(mask))
def cidr4(addr, mask):
return "{addr}/{bits}".format(addr=addr, bits=prefix4(mask))
def get_bonded_slaves():
try:
with open("/sys/class/net/bonding_masters") as f:
masters = f.read().split()
except FileNotFoundError:
return {}
slaves = {}
for master in masters:
with open("/sys/class/net/{}/bonding/slaves".format(master)) as f:
for slave in f.read().split():
slaves[slave] = master
return slaves
def sysfs_interface_up(interface, unknown_up=False):
try:
with open("/sys/class/net/{}/operstate".format(interface)) as f:
status = f.read().strip()
except FileNotFoundError:
# Interface doesn't exist
return False
return status == "up" or unknown_up and status == "unknown"
class NetworkInfo():
"""
Retrieve network information.
"""
def __init__(self, interface, ignore_interfaces, detached_down, unknown_up, get_wifi_info=False):
if interface not in netifaces.interfaces() and not detached_down:
raise RuntimeError(
"Unknown interface {iface}!".format(iface=interface))
self.ignore_interfaces = ignore_interfaces
self.detached_down = detached_down
self.unknown_up = unknown_up
self.get_wifi_info = get_wifi_info
def get_info(self, interface):
format_dict = dict(v4="", v4mask="", v4cidr="", v6="", v6mask="", v6cidr="")
iface_up = sysfs_interface_up(interface, self.unknown_up)
if not iface_up:
return format_dict
network_info = netifaces.ifaddresses(interface)
slaves = get_bonded_slaves()
try:
master = slaves[interface]
except KeyError:
pass
else:
if sysfs_interface_up(interface, self.unknown_up):
master_info = netifaces.ifaddresses(master)
for af in (netifaces.AF_INET, netifaces.AF_INET6):
try:
network_info[af] = master_info[af]
except KeyError:
pass
try:
mac = network_info[netifaces.AF_PACKET][0]["addr"]
except KeyError:
mac = "NONE"
format_dict['mac'] = mac
if iface_up:
format_dict.update(self.extract_network_info(network_info))
format_dict.update(self.extract_wireless_info(interface))
return format_dict
@staticmethod
def extract_network_info(network_info):
info = dict()
if netifaces.AF_INET in network_info:
v4 = network_info[netifaces.AF_INET][0]
info["v4"] = v4["addr"]
info["v4mask"] = v4["netmask"]
info["v4cidr"] = cidr4(v4["addr"], v4["netmask"])
if netifaces.AF_INET6 in network_info:
for v6 in network_info[netifaces.AF_INET6]:
info["v6"] = v6["addr"]
info["v6mask"] = v6["netmask"]
info["v6cidr"] = cidr6(v6["addr"], v6["netmask"])
if not v6["addr"].startswith("fe80::"): # prefer non link-local addresses
break
return info
def extract_wireless_info(self, interface):
info = dict(essid="", freq="", quality=0.0, quality_bar="")
# Just return empty values if we're not using any Wifi functionality
if not self.get_wifi_info:
return info
import basiciw
try:
iwi = basiciw.iwinfo(interface)
except Exception:
# Not a wireless interface
return info
info["essid"] = iwi["essid"]
info["freq"] = iwi["freq"]
quality = iwi["quality"]
if quality["quality_max"] > 0:
info["quality"] = quality["quality"] / quality["quality_max"]
else:
info["quality"] = quality["quality"]
info["quality"] *= 100
info["quality_bar"] = make_bar(info["quality"])
info["quality"] = round(info["quality"])
return info
class NetworkTraffic():
"""
Retrieve network traffic information
"""
pnic = None
pnic_before = None
def __init__(self, unknown_up, divisor, round_size):
self.unknown_up = unknown_up
self.divisor = divisor
self.round_size = round_size
def update_counters(self, interface):
import psutil
self.pnic_before = self.pnic
counters = psutil.net_io_counters(pernic=True)
self.pnic = counters[interface] if interface in counters else None
def clear_counters(self):
self.pnic_before = None
self.pnic = None
def get_bytes_sent(self):
return (self.pnic.bytes_sent - self.pnic_before.bytes_sent) / self.divisor
def get_bytes_received(self):
return (self.pnic.bytes_recv - self.pnic_before.bytes_recv) / self.divisor
def get_packets_sent(self):
return self.pnic.packets_sent - self.pnic_before.packets_sent
def get_packets_received(self):
return self.pnic.packets_recv - self.pnic_before.packets_recv
def get_usage(self, interface):
self.update_counters(interface)
usage = dict(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0)
if not sysfs_interface_up(interface, self.unknown_up) or not self.pnic_before:
return usage
else:
usage["bytes_sent"] = self.get_bytes_sent()
usage["bytes_recv"] = self.get_bytes_received()
usage["packets_sent"] = self.get_packets_sent()
usage["packets_recv"] = self.get_packets_received()
round_dict(usage, self.round_size)
return usage
class Network(IntervalModule, ColorRangeModule):
"""
Displays network information for an interface.
Requires the PyPI packages `psutil`, `colour`, `netifaces` and `basiciw`
.. rubric:: Available formatters
Network Traffic Formatters:
* `{interface}` — the configured network interface
* `{kbs}` – Float representing kb\s
* `{network_graph}` – Unicode graph representing network usage
* `{bytes_sent}` — bytes sent per second (divided by divisor)
* `{bytes_recv}` — bytes received per second (divided by divisor)
* `{packets_sent}` — bytes sent per second (divided by divisor)
* `{packets_recv}` — bytes received per second (divided by divisor)
Network Information Formatters:
* `{interface}` — same as setting
* `{v4}` — IPv4 address
* `{v4mask}` — subnet mask
* `{v4cidr}` — IPv4 address in cidr notation (i.e. 192.168.2.204/24)
* `{v6}` — IPv6 address
* `{v6mask}` — subnet mask
* `{v6cidr}` — IPv6 address in cidr notation
* `{mac}` — MAC of interface
Wireless Information Formatters:
* `{essid}` — ESSID of currently connected wifi
* `{freq}` — Current frequency
* `{quality}` — Link quality in percent
* `{quality_bar}` —Bar graphically representing link quality
"""
settings = (
("format_up", "format string"),
("format_down", "format string"),
"color_up",
"color_down",
("interface", "Interface to watch, eg 'eth0'"),
("dynamic_color", "Set color dynamically based on network traffic. Note: this overrides color_up"),
("start_color", "Hex or English name for start of color range, eg '#00FF00' or 'green'"),
("end_color", "Hex or English name for end of color range, eg '#FF0000' or 'red'"),
("graph_width", "Width of the network traffic graph"),
("graph_style", "Graph style ('blocks', 'braille-fill', 'braille-peak', or 'braille-snake')"),
("upper_limit",
"Expected max kb/s. This value controls how the network traffic graph is drawn and in what color"),
("graph_type", "Whether to draw the network traffic graph for input or output. "
"Allowed values 'input' or 'output'"),
("divisor", "divide all byte values by this value"),
("ignore_interfaces", "Array of interfaces to ignore when cycling through "
"on click, eg, ['lo']"),
("round_size", "defines number of digits in round"),
("detached_down", "If the interface doesn't exist, display it as if it were down"),
("unknown_up", "If the interface is in unknown state, display it as if it were up"),
)
interval = 1
interface = 'eth0'
format_up = "{interface} {network_graph}{kbs}KB/s"
format_down = "{interface}: DOWN"
color_up = "#00FF00"
color_down = "#FF0000"
dynamic_color = True
graph_type = 'input'
graph_width = 15
graph_style = 'blocks'
upper_limit = 150.0
# Network traffic settings
divisor = 1024
round_size = None
# Network info settings
detached_down = True
unknown_up = False
ignore_interfaces = ["lo"]
on_leftclick = "nm-connection-editor"
on_rightclick = "cycle_interface"
on_upscroll = ['cycle_interface', 1]
on_downscroll = ['cycle_interface', -1]
def init(self):
# Don't require importing basiciw unless using the functionality it offers.
if any(s in self.format_up or s in self.format_up for s in
['essid', 'freq', 'quality', 'quality_bar']):
get_wifi_info = True
else:
get_wifi_info = False
self.network_info = NetworkInfo(self.interface, self.ignore_interfaces, self.detached_down, self.unknown_up,
get_wifi_info)
# Don't require importing psutil unless using the functionality it offers.
if any(s in self.format_up or s in self.format_down for s in
['bytes_sent', 'bytes_recv', 'packets_sent', 'packets_recv', 'network_graph', 'kbs']):
self.network_traffic = NetworkTraffic(self.unknown_up, self.divisor, self.round_size)
else:
self.network_traffic = None
if not self.dynamic_color:
self.end_color = self.start_color
self.colors = self.get_hex_color_range(self.start_color, self.end_color, int(self.upper_limit))
self.kbs_arr = [0.0] * self.graph_width
def cycle_interface(self, increment=1):
interfaces = [i for i in netifaces.interfaces() if i not in self.ignore_interfaces]
if self.interface in interfaces:
next_index = (interfaces.index(self.interface) + increment) % len(interfaces)
self.interface = interfaces[next_index]
elif len(interfaces) > 0:
self.interface = interfaces[0]
if self.network_traffic:
self.network_traffic.clear_counters()
self.kbs_arr = [0.0] * self.graph_width
def get_network_graph(self, kbs):
# Cycle array by inserting at the start and chopping off the last element
self.kbs_arr.insert(0, kbs)
self.kbs_arr = self.kbs_arr[:self.graph_width]
return make_graph(self.kbs_arr, 0.0, self.upper_limit, self.graph_style)
def run(self):
format_values = dict(kbs="", network_graph="", bytes_sent="", bytes_recv="", packets_sent="", packets_recv="",
interface="", v4="", v4mask="", v4cidr="", v6="", v6mask="", v6cidr="", mac="",
essid="", freq="", quality="", quality_bar="")
if self.network_traffic:
network_usage = self.network_traffic.get_usage(self.interface)
format_values.update(network_usage)
if self.graph_type == 'input':
kbs = network_usage['bytes_recv']
elif self.graph_type == 'output':
kbs = network_usage['bytes_sent']
else:
raise Exception("graph_type must be either 'input' or 'output'!")
format_values['network_graph'] = self.get_network_graph(kbs)
format_values['kbs'] = "{0:.1f}".format(round(kbs, 2)).rjust(6)
color = self.get_gradient(kbs, self.colors, self.upper_limit)
else:
color = None
if sysfs_interface_up(self.interface, self.unknown_up):
if not color:
color = self.color_up
format_str = self.format_up
else:
color = self.color_down
format_str = self.format_down
network_info = self.network_info.get_info(self.interface)
format_values.update(network_info)
format_values['interface'] = self.interface
self.output = {
"full_text": format_str.format(**format_values),
'color': color,
}
| 35.248677 | 118 | 0.611828 |
import netifaces
from i3pystatus import IntervalModule
from i3pystatus.core.color import ColorRangeModule
from i3pystatus.core.util import make_graph, round_dict, make_bar
def count_bits(integer):
bits = 0
while (integer):
integer &= integer - 1
bits += 1
return bits
def v6_to_int(v6):
return int(v6.replace(":", ""), 16)
def prefix6(mask):
return count_bits(v6_to_int(mask))
def cidr6(addr, mask):
return "{addr}/{bits}".format(addr=addr, bits=prefix6(mask))
def v4_to_int(v4):
sum = 0
mul = 1
for part in reversed(v4.split(".")):
sum += int(part) * mul
mul *= 2 ** 8
return sum
def prefix4(mask):
return count_bits(v4_to_int(mask))
def cidr4(addr, mask):
return "{addr}/{bits}".format(addr=addr, bits=prefix4(mask))
def get_bonded_slaves():
try:
with open("/sys/class/net/bonding_masters") as f:
masters = f.read().split()
except FileNotFoundError:
return {}
slaves = {}
for master in masters:
with open("/sys/class/net/{}/bonding/slaves".format(master)) as f:
for slave in f.read().split():
slaves[slave] = master
return slaves
def sysfs_interface_up(interface, unknown_up=False):
try:
with open("/sys/class/net/{}/operstate".format(interface)) as f:
status = f.read().strip()
except FileNotFoundError:
return False
return status == "up" or unknown_up and status == "unknown"
class NetworkInfo():
def __init__(self, interface, ignore_interfaces, detached_down, unknown_up, get_wifi_info=False):
if interface not in netifaces.interfaces() and not detached_down:
raise RuntimeError(
"Unknown interface {iface}!".format(iface=interface))
self.ignore_interfaces = ignore_interfaces
self.detached_down = detached_down
self.unknown_up = unknown_up
self.get_wifi_info = get_wifi_info
def get_info(self, interface):
format_dict = dict(v4="", v4mask="", v4cidr="", v6="", v6mask="", v6cidr="")
iface_up = sysfs_interface_up(interface, self.unknown_up)
if not iface_up:
return format_dict
network_info = netifaces.ifaddresses(interface)
slaves = get_bonded_slaves()
try:
master = slaves[interface]
except KeyError:
pass
else:
if sysfs_interface_up(interface, self.unknown_up):
master_info = netifaces.ifaddresses(master)
for af in (netifaces.AF_INET, netifaces.AF_INET6):
try:
network_info[af] = master_info[af]
except KeyError:
pass
try:
mac = network_info[netifaces.AF_PACKET][0]["addr"]
except KeyError:
mac = "NONE"
format_dict['mac'] = mac
if iface_up:
format_dict.update(self.extract_network_info(network_info))
format_dict.update(self.extract_wireless_info(interface))
return format_dict
@staticmethod
def extract_network_info(network_info):
info = dict()
if netifaces.AF_INET in network_info:
v4 = network_info[netifaces.AF_INET][0]
info["v4"] = v4["addr"]
info["v4mask"] = v4["netmask"]
info["v4cidr"] = cidr4(v4["addr"], v4["netmask"])
if netifaces.AF_INET6 in network_info:
for v6 in network_info[netifaces.AF_INET6]:
info["v6"] = v6["addr"]
info["v6mask"] = v6["netmask"]
info["v6cidr"] = cidr6(v6["addr"], v6["netmask"])
if not v6["addr"].startswith("fe80::"): # prefer non link-local addresses
break
return info
def extract_wireless_info(self, interface):
info = dict(essid="", freq="", quality=0.0, quality_bar="")
# Just return empty values if we're not using any Wifi functionality
if not self.get_wifi_info:
return info
import basiciw
try:
iwi = basiciw.iwinfo(interface)
except Exception:
return info
info["essid"] = iwi["essid"]
info["freq"] = iwi["freq"]
quality = iwi["quality"]
if quality["quality_max"] > 0:
info["quality"] = quality["quality"] / quality["quality_max"]
else:
info["quality"] = quality["quality"]
info["quality"] *= 100
info["quality_bar"] = make_bar(info["quality"])
info["quality"] = round(info["quality"])
return info
class NetworkTraffic():
pnic = None
pnic_before = None
def __init__(self, unknown_up, divisor, round_size):
self.unknown_up = unknown_up
self.divisor = divisor
self.round_size = round_size
def update_counters(self, interface):
import psutil
self.pnic_before = self.pnic
counters = psutil.net_io_counters(pernic=True)
self.pnic = counters[interface] if interface in counters else None
def clear_counters(self):
self.pnic_before = None
self.pnic = None
def get_bytes_sent(self):
return (self.pnic.bytes_sent - self.pnic_before.bytes_sent) / self.divisor
def get_bytes_received(self):
return (self.pnic.bytes_recv - self.pnic_before.bytes_recv) / self.divisor
def get_packets_sent(self):
return self.pnic.packets_sent - self.pnic_before.packets_sent
def get_packets_received(self):
return self.pnic.packets_recv - self.pnic_before.packets_recv
def get_usage(self, interface):
self.update_counters(interface)
usage = dict(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0)
if not sysfs_interface_up(interface, self.unknown_up) or not self.pnic_before:
return usage
else:
usage["bytes_sent"] = self.get_bytes_sent()
usage["bytes_recv"] = self.get_bytes_received()
usage["packets_sent"] = self.get_packets_sent()
usage["packets_recv"] = self.get_packets_received()
round_dict(usage, self.round_size)
return usage
class Network(IntervalModule, ColorRangeModule):
settings = (
("format_up", "format string"),
("format_down", "format string"),
"color_up",
"color_down",
("interface", "Interface to watch, eg 'eth0'"),
("dynamic_color", "Set color dynamically based on network traffic. Note: this overrides color_up"),
("start_color", "Hex or English name for start of color range, eg '#00FF00' or 'green'"),
("end_color", "Hex or English name for end of color range, eg '#FF0000' or 'red'"),
("graph_width", "Width of the network traffic graph"),
("graph_style", "Graph style ('blocks', 'braille-fill', 'braille-peak', or 'braille-snake')"),
("upper_limit",
"Expected max kb/s. This value controls how the network traffic graph is drawn and in what color"),
("graph_type", "Whether to draw the network traffic graph for input or output. "
"Allowed values 'input' or 'output'"),
("divisor", "divide all byte values by this value"),
("ignore_interfaces", "Array of interfaces to ignore when cycling through "
"on click, eg, ['lo']"),
("round_size", "defines number of digits in round"),
("detached_down", "If the interface doesn't exist, display it as if it were down"),
("unknown_up", "If the interface is in unknown state, display it as if it were up"),
)
interval = 1
interface = 'eth0'
format_up = "{interface} {network_graph}{kbs}KB/s"
format_down = "{interface}: DOWN"
color_up = "#00FF00"
color_down = "#FF0000"
dynamic_color = True
graph_type = 'input'
graph_width = 15
graph_style = 'blocks'
upper_limit = 150.0
# Network traffic settings
divisor = 1024
round_size = None
# Network info settings
detached_down = True
unknown_up = False
ignore_interfaces = ["lo"]
on_leftclick = "nm-connection-editor"
on_rightclick = "cycle_interface"
on_upscroll = ['cycle_interface', 1]
on_downscroll = ['cycle_interface', -1]
def init(self):
# Don't require importing basiciw unless using the functionality it offers.
if any(s in self.format_up or s in self.format_up for s in
['essid', 'freq', 'quality', 'quality_bar']):
get_wifi_info = True
else:
get_wifi_info = False
self.network_info = NetworkInfo(self.interface, self.ignore_interfaces, self.detached_down, self.unknown_up,
get_wifi_info)
if any(s in self.format_up or s in self.format_down for s in
['bytes_sent', 'bytes_recv', 'packets_sent', 'packets_recv', 'network_graph', 'kbs']):
self.network_traffic = NetworkTraffic(self.unknown_up, self.divisor, self.round_size)
else:
self.network_traffic = None
if not self.dynamic_color:
self.end_color = self.start_color
self.colors = self.get_hex_color_range(self.start_color, self.end_color, int(self.upper_limit))
self.kbs_arr = [0.0] * self.graph_width
def cycle_interface(self, increment=1):
interfaces = [i for i in netifaces.interfaces() if i not in self.ignore_interfaces]
if self.interface in interfaces:
next_index = (interfaces.index(self.interface) + increment) % len(interfaces)
self.interface = interfaces[next_index]
elif len(interfaces) > 0:
self.interface = interfaces[0]
if self.network_traffic:
self.network_traffic.clear_counters()
self.kbs_arr = [0.0] * self.graph_width
def get_network_graph(self, kbs):
# Cycle array by inserting at the start and chopping off the last element
self.kbs_arr.insert(0, kbs)
self.kbs_arr = self.kbs_arr[:self.graph_width]
return make_graph(self.kbs_arr, 0.0, self.upper_limit, self.graph_style)
def run(self):
format_values = dict(kbs="", network_graph="", bytes_sent="", bytes_recv="", packets_sent="", packets_recv="",
interface="", v4="", v4mask="", v4cidr="", v6="", v6mask="", v6cidr="", mac="",
essid="", freq="", quality="", quality_bar="")
if self.network_traffic:
network_usage = self.network_traffic.get_usage(self.interface)
format_values.update(network_usage)
if self.graph_type == 'input':
kbs = network_usage['bytes_recv']
elif self.graph_type == 'output':
kbs = network_usage['bytes_sent']
else:
raise Exception("graph_type must be either 'input' or 'output'!")
format_values['network_graph'] = self.get_network_graph(kbs)
format_values['kbs'] = "{0:.1f}".format(round(kbs, 2)).rjust(6)
color = self.get_gradient(kbs, self.colors, self.upper_limit)
else:
color = None
if sysfs_interface_up(self.interface, self.unknown_up):
if not color:
color = self.color_up
format_str = self.format_up
else:
color = self.color_down
format_str = self.format_down
network_info = self.network_info.get_info(self.interface)
format_values.update(network_info)
format_values['interface'] = self.interface
self.output = {
"full_text": format_str.format(**format_values),
'color': color,
}
| true | true |
f72efe28d7c827765fc230987e47746d83b1714e | 1,500 | py | Python | 00Python/day11/basic02.py | HaoZhang95/PythonAndMachineLearning | b897224b8a0e6a5734f408df8c24846a98c553bf | [
"MIT"
] | 937 | 2019-05-08T08:46:25.000Z | 2022-03-31T12:56:07.000Z | 00Python/day11/basic02.py | Sakura-gh/Python24 | b97e18867264a0647d5645c7d757a0040e755577 | [
"MIT"
] | 47 | 2019-09-17T10:06:02.000Z | 2022-03-11T23:46:52.000Z | 00Python/day11/basic02.py | Sakura-gh/Python24 | b97e18867264a0647d5645c7d757a0040e755577 | [
"MIT"
] | 354 | 2019-05-10T02:15:26.000Z | 2022-03-30T05:52:57.000Z | """
__new__()方法, 对象创建的过程,
1- new方法返回一个对象 2- init利用new返回的对象进行属性的添加
"""
class Person(object):
# 监听创建一个实例对象的过程,需要返回一个对象赋值给xiaoming
# new中不return的话,那么久不会执行init方法
def __new__(cls, *args, **kwargs):
print("new")
print((object.__new__(cls)))
return object.__new__(cls)
# 构造方法,当执行init方法的时候对象**已经创建成功**,剩下的是将属性添加到对象中
def __init__(self, name):
print("init")
self.name = name
# 类的toString方法
# def __str__(self):
# return "我的名字是: %s" % self.name
# 监听引用计数为0的时候,python会执行del方法
def __del__(self):
print("再见")
# xioaming的地址和new中return的obj的地址一样,说明new中返回的obj就是xiaoming
xiaoming = Person("小明")
print(xiaoming)
print("=" * 28)
"""
python的单例模式,需要使用到new关键方法
1- 保证返回的对象是同一个,在new中修改
2- 保证对象的属性只能赋值一次,在init方法中修改
3- 一般单例模式中的包含静态方法, 类似于Tools.XX, 不需要创建多个对象来调用同一个静态方法
"""
class Student(object):
# 定义一个类属型保存实例对象
__instance = None
# 类属型保证实例属性只能被赋值一次
__is_first = True
# s1,s2要保证使用一份内存, 需要new的时候返回同一个对象
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
def __init__(self, name, age):
if self.__is_first:
self.name = name
self.age = age
self.__is_first = False
# 静态方法
@staticmethod
def add_num(a, b):
return a + b
s1 = Student("小明", 25)
s2 = Student("小红", 28)
print(s1)
print(s2)
print(s1.name)
print(s2.name)
| 20.547945 | 56 | 0.626 |
class Person(object):
def __new__(cls, *args, **kwargs):
print("new")
print((object.__new__(cls)))
return object.__new__(cls)
def __init__(self, name):
print("init")
self.name = name
def __del__(self):
print("再见")
xiaoming = Person("小明")
print(xiaoming)
print("=" * 28)
class Student(object):
__instance = None
__is_first = True
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
def __init__(self, name, age):
if self.__is_first:
self.name = name
self.age = age
self.__is_first = False
@staticmethod
def add_num(a, b):
return a + b
s1 = Student("小明", 25)
s2 = Student("小红", 28)
print(s1)
print(s2)
print(s1.name)
print(s2.name)
| true | true |
f72efe3d12d989d9d5fbd596ed2881377aad1ab5 | 3,542 | py | Python | test/functional/wallet_encryption.py | Hary2511/xaya | 312ffe32f0bc58d0936f96770c59b57d9862ac35 | [
"MIT"
] | 2 | 2018-08-07T17:27:05.000Z | 2018-08-07T17:28:18.000Z | test/functional/wallet_encryption.py | Hary2511/xaya | 312ffe32f0bc58d0936f96770c59b57d9862ac35 | [
"MIT"
] | null | null | null | test/functional/wallet_encryption.py | Hary2511/xaya | 312ffe32f0bc58d0936f96770c59b57d9862ac35 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2016-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test Wallet encryption"""
import time
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
assert_greater_than,
assert_greater_than_or_equal,
)
class WalletEncryptionTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
passphrase = "WalletPassphrase"
passphrase2 = "SecondWalletPassphrase"
# Make sure the wallet isn't encrypted first
address = self.nodes[0].getnewaddress()
privkey = self.nodes[0].dumpprivkey(address)
assert_equal(privkey[:1], "b")
assert_equal(len(privkey), 52)
# Encrypt the wallet
self.nodes[0].node_encrypt_wallet(passphrase)
self.start_node(0)
# Test that the wallet is encrypted
assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].dumpprivkey, address)
# Check that walletpassphrase works
self.nodes[0].walletpassphrase(passphrase, 2)
assert_equal(privkey, self.nodes[0].dumpprivkey(address))
# Check that the timeout is right
time.sleep(2)
assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].dumpprivkey, address)
# Test wrong passphrase
assert_raises_rpc_error(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase + "wrong", 10)
# Test walletlock
self.nodes[0].walletpassphrase(passphrase, 84600)
assert_equal(privkey, self.nodes[0].dumpprivkey(address))
self.nodes[0].walletlock()
assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].dumpprivkey, address)
# Test passphrase changes
self.nodes[0].walletpassphrasechange(passphrase, passphrase2)
assert_raises_rpc_error(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase, 10)
self.nodes[0].walletpassphrase(passphrase2, 10)
assert_equal(privkey, self.nodes[0].dumpprivkey(address))
self.nodes[0].walletlock()
# Test timeout bounds
assert_raises_rpc_error(-8, "Timeout cannot be negative.", self.nodes[0].walletpassphrase, passphrase2, -10)
# Check the timeout
# Check a time less than the limit
MAX_VALUE = 100000000
expected_time = int(time.time()) + MAX_VALUE - 600
self.nodes[0].walletpassphrase(passphrase2, MAX_VALUE - 600)
actual_time = self.nodes[0].getwalletinfo()['unlocked_until']
assert_greater_than_or_equal(actual_time, expected_time)
assert_greater_than(expected_time + 5, actual_time) # 5 second buffer
# Check a time greater than the limit
expected_time = int(time.time()) + MAX_VALUE - 1
self.nodes[0].walletpassphrase(passphrase2, MAX_VALUE + 1000)
actual_time = self.nodes[0].getwalletinfo()['unlocked_until']
assert_greater_than_or_equal(actual_time, expected_time)
assert_greater_than(expected_time + 5, actual_time) # 5 second buffer
if __name__ == '__main__':
WalletEncryptionTest().main()
| 43.195122 | 138 | 0.705816 |
import time
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
assert_greater_than,
assert_greater_than_or_equal,
)
class WalletEncryptionTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
def run_test(self):
passphrase = "WalletPassphrase"
passphrase2 = "SecondWalletPassphrase"
address = self.nodes[0].getnewaddress()
privkey = self.nodes[0].dumpprivkey(address)
assert_equal(privkey[:1], "b")
assert_equal(len(privkey), 52)
# Encrypt the wallet
self.nodes[0].node_encrypt_wallet(passphrase)
self.start_node(0)
# Test that the wallet is encrypted
assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].dumpprivkey, address)
# Check that walletpassphrase works
self.nodes[0].walletpassphrase(passphrase, 2)
assert_equal(privkey, self.nodes[0].dumpprivkey(address))
# Check that the timeout is right
time.sleep(2)
assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].dumpprivkey, address)
# Test wrong passphrase
assert_raises_rpc_error(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase + "wrong", 10)
# Test walletlock
self.nodes[0].walletpassphrase(passphrase, 84600)
assert_equal(privkey, self.nodes[0].dumpprivkey(address))
self.nodes[0].walletlock()
assert_raises_rpc_error(-13, "Please enter the wallet passphrase with walletpassphrase first", self.nodes[0].dumpprivkey, address)
# Test passphrase changes
self.nodes[0].walletpassphrasechange(passphrase, passphrase2)
assert_raises_rpc_error(-14, "wallet passphrase entered was incorrect", self.nodes[0].walletpassphrase, passphrase, 10)
self.nodes[0].walletpassphrase(passphrase2, 10)
assert_equal(privkey, self.nodes[0].dumpprivkey(address))
self.nodes[0].walletlock()
# Test timeout bounds
assert_raises_rpc_error(-8, "Timeout cannot be negative.", self.nodes[0].walletpassphrase, passphrase2, -10)
# Check the timeout
# Check a time less than the limit
MAX_VALUE = 100000000
expected_time = int(time.time()) + MAX_VALUE - 600
self.nodes[0].walletpassphrase(passphrase2, MAX_VALUE - 600)
actual_time = self.nodes[0].getwalletinfo()['unlocked_until']
assert_greater_than_or_equal(actual_time, expected_time)
assert_greater_than(expected_time + 5, actual_time) # 5 second buffer
# Check a time greater than the limit
expected_time = int(time.time()) + MAX_VALUE - 1
self.nodes[0].walletpassphrase(passphrase2, MAX_VALUE + 1000)
actual_time = self.nodes[0].getwalletinfo()['unlocked_until']
assert_greater_than_or_equal(actual_time, expected_time)
assert_greater_than(expected_time + 5, actual_time) # 5 second buffer
if __name__ == '__main__':
WalletEncryptionTest().main()
| true | true |
f72efe4f9f448f396364ed1b99e237c63630816c | 2,612 | py | Python | tests/providers/amazon/aws/hooks/test_aws_dynamodb_hook.py | wileeam/airflow | f46be8152a4d89c57db4ca46f5b3339e4876b723 | [
"Apache-2.0"
] | 1 | 2020-02-17T17:40:14.000Z | 2020-02-17T17:40:14.000Z | tests/providers/amazon/aws/hooks/test_aws_dynamodb_hook.py | devlocalca/airflow | 58c3542ed25061320ce61dbe0adf451a44c738dd | [
"Apache-2.0"
] | 2 | 2021-05-12T12:41:51.000Z | 2021-09-29T17:47:43.000Z | tests/providers/amazon/aws/hooks/test_aws_dynamodb_hook.py | devlocalca/airflow | 58c3542ed25061320ce61dbe0adf451a44c738dd | [
"Apache-2.0"
] | null | null | null | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
import unittest
import uuid
from airflow.providers.amazon.aws.hooks.aws_dynamodb_hook import AwsDynamoDBHook
try:
from moto import mock_dynamodb2
except ImportError:
mock_dynamodb2 = None
class TestDynamoDBHook(unittest.TestCase):
@unittest.skipIf(mock_dynamodb2 is None, 'mock_dynamodb2 package not present')
@mock_dynamodb2
def test_get_conn_returns_a_boto3_connection(self):
hook = AwsDynamoDBHook(aws_conn_id='aws_default')
self.assertIsNotNone(hook.get_conn())
@unittest.skipIf(mock_dynamodb2 is None, 'mock_dynamodb2 package not present')
@mock_dynamodb2
def test_insert_batch_items_dynamodb_table(self):
hook = AwsDynamoDBHook(aws_conn_id='aws_default',
table_name='test_airflow', table_keys=['id'], region_name='us-east-1')
# this table needs to be created in production
table = hook.get_conn().create_table(
TableName='test_airflow',
KeySchema=[
{
'AttributeName': 'id',
'KeyType': 'HASH'
},
],
AttributeDefinitions=[
{
'AttributeName': 'id',
'AttributeType': 'S'
}
],
ProvisionedThroughput={
'ReadCapacityUnits': 10,
'WriteCapacityUnits': 10
}
)
table = hook.get_conn().Table('test_airflow')
items = [{'id': str(uuid.uuid4()), 'name': 'airflow'}
for _ in range(10)]
hook.write_batch_data(items)
table.meta.client.get_waiter(
'table_exists').wait(TableName='test_airflow')
self.assertEqual(table.item_count, 10)
if __name__ == '__main__':
unittest.main()
| 32.246914 | 101 | 0.64242 |
import unittest
import uuid
from airflow.providers.amazon.aws.hooks.aws_dynamodb_hook import AwsDynamoDBHook
try:
from moto import mock_dynamodb2
except ImportError:
mock_dynamodb2 = None
class TestDynamoDBHook(unittest.TestCase):
@unittest.skipIf(mock_dynamodb2 is None, 'mock_dynamodb2 package not present')
@mock_dynamodb2
def test_get_conn_returns_a_boto3_connection(self):
hook = AwsDynamoDBHook(aws_conn_id='aws_default')
self.assertIsNotNone(hook.get_conn())
@unittest.skipIf(mock_dynamodb2 is None, 'mock_dynamodb2 package not present')
@mock_dynamodb2
def test_insert_batch_items_dynamodb_table(self):
hook = AwsDynamoDBHook(aws_conn_id='aws_default',
table_name='test_airflow', table_keys=['id'], region_name='us-east-1')
table = hook.get_conn().create_table(
TableName='test_airflow',
KeySchema=[
{
'AttributeName': 'id',
'KeyType': 'HASH'
},
],
AttributeDefinitions=[
{
'AttributeName': 'id',
'AttributeType': 'S'
}
],
ProvisionedThroughput={
'ReadCapacityUnits': 10,
'WriteCapacityUnits': 10
}
)
table = hook.get_conn().Table('test_airflow')
items = [{'id': str(uuid.uuid4()), 'name': 'airflow'}
for _ in range(10)]
hook.write_batch_data(items)
table.meta.client.get_waiter(
'table_exists').wait(TableName='test_airflow')
self.assertEqual(table.item_count, 10)
if __name__ == '__main__':
unittest.main()
| true | true |
f72efe56b3a6ea76c20c2859404736eb8275a81d | 12,811 | py | Python | install.py | ArgusHomeSecurity/argus_management | d2a6fb0004f23963f1cbc9cd07f40596abaf8b7b | [
"MIT"
] | null | null | null | install.py | ArgusHomeSecurity/argus_management | d2a6fb0004f23963f1cbc9cd07f40596abaf8b7b | [
"MIT"
] | 1 | 2021-02-24T12:04:11.000Z | 2021-02-24T12:04:11.000Z | install.py | ArPIHomeSecurity/arpi_management | d2a6fb0004f23963f1cbc9cd07f40596abaf8b7b | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# encoding: utf-8
"""
Script for installing the components of the ArPI home security system to a running Raspberry PI Zero Wifi host.
It uses the configuration file install.yaml!
---
@author: Gábor Kovács
@copyright: 2017 arpi-security.info. All rights reserved.
@contact: gkovacs81@gmail.com
"""
import json
import logging
import subprocess
import sys
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from os import system
from os.path import join, exists
from socket import gaierror
from time import sleep
import paramiko
import yaml
from paramiko.ssh_exception import AuthenticationException, NoValidConnectionsError
from scp import SCPClient
from utils import (
deep_copy,
execute_remote,
generate_SSH_key,
list_copy,
print_lines,
show_progress
)
CONFIG = {}
logging.basicConfig(format="%(message)s")
logger = logging.getLogger()
logging.getLogger("paramiko").setLevel(logging.CRITICAL)
__all__ = []
__version__ = 0.1
__date__ = "2017-08-21"
__updated__ = "2019-08-21"
program_shortdesc = __import__("__main__").__doc__.split("---")[0]
program_license = """%s
Created by gkovacs81@gmail.com on %s.
Copyright 2019 arpi-security.info. All rights reserved.
USAGE
""" % (
program_shortdesc,
str(__date__),
)
def get_connection():
try:
logger.info(
"Connecting with private key in '%s' %s@%s",
CONFIG["arpi_key_name"],
CONFIG["arpi_username"],
CONFIG["arpi_hostname"],
)
private_key = None
if exists(CONFIG["arpi_key_name"]):
private_key = paramiko.RSAKey.from_private_key_file(
CONFIG["arpi_key_name"], CONFIG["arpi_password"]
)
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(
CONFIG["arpi_hostname"],
username=CONFIG["arpi_username"],
password=CONFIG["arpi_password"],
pkey=private_key,
)
logger.info("Connected")
except (AuthenticationException, NoValidConnectionsError, gaierror):
try:
logger.info("Connecting %s@%s", CONFIG["default_username"], CONFIG["default_hostname"])
ssh.connect(
CONFIG["default_hostname"],
username=CONFIG["default_username"],
password=CONFIG["default_password"],
)
logger.info("Connected")
except (NoValidConnectionsError, gaierror):
raise Exception("Can't connect to the host!")
return ssh
def install_environment():
"""
Install prerequisites to an empty Raspberry PI.
"""
if not exists(CONFIG["arpi_key_name"]) and \
not exists(CONFIG["arpi_key_name"] + ".pub"):
generate_SSH_key(CONFIG["arpi_key_name"], CONFIG["arpi_password"])
dhparam_file = "arpi_dhparam.pem"
if not exists(dhparam_file):
logger.info("dhparam (%s) generating", dhparam_file)
system(f"openssl dhparam -out {dhparam_file} {CONFIG['dhparam_size']}")
else:
logger.info("dhparam (%s) already exists", dhparam_file)
system(f"openssl dhparam -in {dhparam_file} -text | head -3")
# create the env variables string because paramiko update_evironment ignores them
arguments = {
"ARPI_PASSWORD": CONFIG["arpi_password"],
"ARGUS_DB_SCHEMA": CONFIG["argus_db_schema"],
"ARGUS_DB_USERNAME": CONFIG["argus_db_username"],
"ARGUS_DB_PASSWORD": CONFIG["argus_db_password"],
"ARPI_HOSTNAME": CONFIG["arpi_hostname"],
"DHPARAM_FILE": join("/tmp", dhparam_file),
# progress
"QUIET": "" if CONFIG["progress"] else "-q",
"PROGRESS": "on" if CONFIG["progress"] else "off"
}
# adding package versions
arguments.update({p.upper(): f"{v}" for p, v in CONFIG["packages"].items() if v})
arguments = [f"export {key}={value}" for key, value in arguments.items()]
arguments = "; ".join(arguments)
ssh = get_connection()
scp = SCPClient(ssh.get_transport(), progress=show_progress if CONFIG["progress"] else None)
scp.put("scripts/install_environment.sh", remote_path=".")
deep_copy(ssh, join(CONFIG["server_path"], "etc"), "/tmp/etc", "**/*", CONFIG["progress"])
list_copy(
ssh,
((dhparam_file, "/tmp"),),
CONFIG["progress"]
)
channel = ssh.get_transport().open_session()
channel.get_pty()
channel.set_combine_stderr(True)
output = channel.makefile("r", -1)
logger.info("Starting install script...")
channel.exec_command(f"{arguments}; ./install_environment.sh")
print_lines(output)
ssh.close()
# waiting for user
# 1. deploy key can timeout
# 2. ssh accept password only from terminal
input("Waiting before deploying public key!")
command = f"ssh-copy-id -i {CONFIG['arpi_key_name']} {CONFIG['arpi_username']}@{CONFIG['default_hostname']}"
logger.info("Deploy public key: %s", command)
while subprocess.call(command, shell=True) != 0:
# retry after 2 seconds
sleep(2)
ssh = get_connection()
execute_remote(
message="Enabling key based ssh authentication",
ssh=ssh,
command="sudo sed -i -E -e 's/.*PasswordAuthentication (yes|no)/PasswordAuthentication no/g' /etc/ssh/sshd_config",
)
execute_remote(message="Restarting the host", ssh=ssh, command="sudo reboot")
def install_component(component, update=False, restart=False):
"""
Install the monitor component to a Raspberry PI.
"""
ssh = get_connection()
execute_remote(
message="Creating server directories...",
ssh=ssh,
command="mkdir -p server/etc server/scripts server/src server/webapplication",
)
logger.info("Copy common files...")
list_copy(
ssh,
(
(join(CONFIG["server_path"], "Pipfile"), "server"),
(join(CONFIG["server_path"], "Pipfile.lock"), "server"),
(join(CONFIG["server_path"], f".env_{CONFIG['environment']}"), "server/.env"),
(join(CONFIG["server_path"], "src", "data.py"), join("server", "src", "data.py")),
(join(CONFIG["server_path"], "src", "hash.py"), join("server", "src", "hash.py")),
(join(CONFIG["server_path"], "src", "models.py"), join("server", "src", "models.py")),
), CONFIG["progress"]
)
deep_copy(
ssh, join(CONFIG["server_path"], "src", "tools"), join("server", "src", "tools"), "**/*.py", CONFIG["progress"]
)
logger.info("Copy component '%s'...", component)
deep_copy(
ssh,
join(CONFIG["server_path"], "src", component),
join("server", "src", component),
"**/*.py",
CONFIG["progress"]
)
if update:
execute_remote(
message="Start installing python packages on sytem...",
ssh=ssh,
command="cd server; sudo PIPENV_TIMEOUT=9999 pipenv install --system",
)
execute_remote(
message="Create virtual environment with python3 for argus...",
ssh=ssh,
command="cd server; PIPENV_TIMEOUT=9999 CI=1 pipenv install --skip-lock --site-packages",
)
execute_remote(
message="Create virtual environment with python3 for root...",
ssh=ssh,
command="cd server; sudo PIPENV_TIMEOUT=9999 CI=1 pipenv install --skip-lock --site-packages",
)
if restart:
execute_remote(
message="Restarting the service...",
ssh=ssh,
command="sudo systemctl restart argus_monitor.service argus_server.service",
)
ssh.close()
def install_server(update=False, restart=False):
"""
Install the server component to a Raspberry PI.
"""
install_component("server", update=update, restart=restart)
def install_monitoring(update=False, restart=False):
"""
Install the monitor component to a Raspberry PI.
"""
install_component("monitoring", update=update, restart=restart)
def install_database():
"""
Install the database component to a Raspberry PI.
"""
ssh = get_connection()
execute_remote(
message="Initialize database...",
ssh=ssh,
command="cd server; pipenv run flask db init",
)
execute_remote(
message="Migrate database...",
ssh=ssh,
command="cd server; pipenv run flask db migrate",
)
execute_remote(
message="Upgrade database...",
ssh=ssh,
command="cd server; pipenv run flask db upgrade",
)
execute_remote(
message="Updating database content...",
ssh=ssh,
command=f"cd server; pipenv run src/data.py -d -c {CONFIG['argus_db_content']}",
)
ssh.close()
def install_webapplication(restart=False):
"""
Install the web application component to a Raspberry PI.
"""
ssh = get_connection()
execute_remote(
message="Delete old webapplication on remote site...",
ssh=ssh,
command="rm -R server/webapplication || true",
)
target = join("server", "webapplication")
logger.info("Copy web application: %s => %s", CONFIG["webapplication_path"], target)
deep_copy(ssh, CONFIG["webapplication_path"], target, "**/*", CONFIG["progress"])
if restart:
execute_remote(
message="Restarting the service...",
ssh=ssh,
command="sudo systemctl restart argus_server.service",
)
def main(argv=None): # IGNORE:C0111
"""Command line options."""
if argv is None:
argv = sys.argv
else:
sys.argv.extend(argv)
try:
# Setup argument parser
parser = ArgumentParser(
description=program_license, formatter_class=RawDescriptionHelpFormatter
)
parser.add_argument(
"-v",
"--verbose",
dest="verbose",
action="count",
help="set verbosity level [default: %(default)s]",
)
parser.add_argument(
"component",
choices=["environment", "server", "monitoring", "webapplication", "database"],
)
parser.add_argument(
"-e",
"--env",
dest="environment",
default="",
help="Select a different config (install.{environment}.yaml)",
)
parser.add_argument(
"-r",
"--restart",
action="store_true",
help="Restart depending service(s) after deployment",
)
parser.add_argument(
"-u",
"--update",
action="store_true",
help="Update the python environment for the depending service(s) after deployment",
)
parser.add_argument(
"-p",
"--progress",
action="store_true",
help="Show progress bars",
)
# Process arguments
args = parser.parse_args()
if args.verbose:
logger.setLevel(logging.DEBUG)
logger.info("Verbose mode on")
else:
logger.setLevel(logging.INFO)
config_filename = __file__.replace(".py", ".yaml")
if args.environment:
config_filename = config_filename.replace(".yaml", "." + args.environment + ".yaml")
logger.info("Working with %s", args)
logger.info("Working from %s", config_filename)
with open(config_filename, "r") as stream:
global CONFIG
CONFIG = yaml.load(stream, Loader=yaml.FullLoader)
CONFIG["progress"] = args.progress
logger.info("Working with configuration: \n%s", json.dumps(CONFIG, indent=4, sort_keys=True))
input("Waiting before starting the installation to verify the configuration!")
if args.component == "environment":
install_environment()
elif args.component == "server":
install_server(args.update, args.restart)
elif args.component == "monitoring":
install_monitoring(args.update, args.restart)
elif args.component == "webapplication":
install_webapplication(args.restart)
elif args.component == "database":
install_database()
else:
logger.error("Unknown component: %s", args.component)
logger.info("Finished successfully!")
return 0
except KeyboardInterrupt:
# handle keyboard interrupt ###
logger.info("\n\nCancelled!\n")
return 0
except Exception:
logger.exception("Failed to execute!")
return 2
if __name__ == "__main__":
sys.exit(main())
| 31.246341 | 123 | 0.609788 |
import json
import logging
import subprocess
import sys
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from os import system
from os.path import join, exists
from socket import gaierror
from time import sleep
import paramiko
import yaml
from paramiko.ssh_exception import AuthenticationException, NoValidConnectionsError
from scp import SCPClient
from utils import (
deep_copy,
execute_remote,
generate_SSH_key,
list_copy,
print_lines,
show_progress
)
CONFIG = {}
logging.basicConfig(format="%(message)s")
logger = logging.getLogger()
logging.getLogger("paramiko").setLevel(logging.CRITICAL)
__all__ = []
__version__ = 0.1
__date__ = "2017-08-21"
__updated__ = "2019-08-21"
program_shortdesc = __import__("__main__").__doc__.split("---")[0]
program_license = """%s
Created by gkovacs81@gmail.com on %s.
Copyright 2019 arpi-security.info. All rights reserved.
USAGE
""" % (
program_shortdesc,
str(__date__),
)
def get_connection():
try:
logger.info(
"Connecting with private key in '%s' %s@%s",
CONFIG["arpi_key_name"],
CONFIG["arpi_username"],
CONFIG["arpi_hostname"],
)
private_key = None
if exists(CONFIG["arpi_key_name"]):
private_key = paramiko.RSAKey.from_private_key_file(
CONFIG["arpi_key_name"], CONFIG["arpi_password"]
)
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(
CONFIG["arpi_hostname"],
username=CONFIG["arpi_username"],
password=CONFIG["arpi_password"],
pkey=private_key,
)
logger.info("Connected")
except (AuthenticationException, NoValidConnectionsError, gaierror):
try:
logger.info("Connecting %s@%s", CONFIG["default_username"], CONFIG["default_hostname"])
ssh.connect(
CONFIG["default_hostname"],
username=CONFIG["default_username"],
password=CONFIG["default_password"],
)
logger.info("Connected")
except (NoValidConnectionsError, gaierror):
raise Exception("Can't connect to the host!")
return ssh
def install_environment():
if not exists(CONFIG["arpi_key_name"]) and \
not exists(CONFIG["arpi_key_name"] + ".pub"):
generate_SSH_key(CONFIG["arpi_key_name"], CONFIG["arpi_password"])
dhparam_file = "arpi_dhparam.pem"
if not exists(dhparam_file):
logger.info("dhparam (%s) generating", dhparam_file)
system(f"openssl dhparam -out {dhparam_file} {CONFIG['dhparam_size']}")
else:
logger.info("dhparam (%s) already exists", dhparam_file)
system(f"openssl dhparam -in {dhparam_file} -text | head -3")
# create the env variables string because paramiko update_evironment ignores them
arguments = {
"ARPI_PASSWORD": CONFIG["arpi_password"],
"ARGUS_DB_SCHEMA": CONFIG["argus_db_schema"],
"ARGUS_DB_USERNAME": CONFIG["argus_db_username"],
"ARGUS_DB_PASSWORD": CONFIG["argus_db_password"],
"ARPI_HOSTNAME": CONFIG["arpi_hostname"],
"DHPARAM_FILE": join("/tmp", dhparam_file),
# progress
"QUIET": "" if CONFIG["progress"] else "-q",
"PROGRESS": "on" if CONFIG["progress"] else "off"
}
# adding package versions
arguments.update({p.upper(): f"{v}" for p, v in CONFIG["packages"].items() if v})
arguments = [f"export {key}={value}" for key, value in arguments.items()]
arguments = "; ".join(arguments)
ssh = get_connection()
scp = SCPClient(ssh.get_transport(), progress=show_progress if CONFIG["progress"] else None)
scp.put("scripts/install_environment.sh", remote_path=".")
deep_copy(ssh, join(CONFIG["server_path"], "etc"), "/tmp/etc", "**/*", CONFIG["progress"])
list_copy(
ssh,
((dhparam_file, "/tmp"),),
CONFIG["progress"]
)
channel = ssh.get_transport().open_session()
channel.get_pty()
channel.set_combine_stderr(True)
output = channel.makefile("r", -1)
logger.info("Starting install script...")
channel.exec_command(f"{arguments}; ./install_environment.sh")
print_lines(output)
ssh.close()
# waiting for user
# 1. deploy key can timeout
# 2. ssh accept password only from terminal
input("Waiting before deploying public key!")
command = f"ssh-copy-id -i {CONFIG['arpi_key_name']} {CONFIG['arpi_username']}@{CONFIG['default_hostname']}"
logger.info("Deploy public key: %s", command)
while subprocess.call(command, shell=True) != 0:
# retry after 2 seconds
sleep(2)
ssh = get_connection()
execute_remote(
message="Enabling key based ssh authentication",
ssh=ssh,
command="sudo sed -i -E -e 's/.*PasswordAuthentication (yes|no)/PasswordAuthentication no/g' /etc/ssh/sshd_config",
)
execute_remote(message="Restarting the host", ssh=ssh, command="sudo reboot")
def install_component(component, update=False, restart=False):
ssh = get_connection()
execute_remote(
message="Creating server directories...",
ssh=ssh,
command="mkdir -p server/etc server/scripts server/src server/webapplication",
)
logger.info("Copy common files...")
list_copy(
ssh,
(
(join(CONFIG["server_path"], "Pipfile"), "server"),
(join(CONFIG["server_path"], "Pipfile.lock"), "server"),
(join(CONFIG["server_path"], f".env_{CONFIG['environment']}"), "server/.env"),
(join(CONFIG["server_path"], "src", "data.py"), join("server", "src", "data.py")),
(join(CONFIG["server_path"], "src", "hash.py"), join("server", "src", "hash.py")),
(join(CONFIG["server_path"], "src", "models.py"), join("server", "src", "models.py")),
), CONFIG["progress"]
)
deep_copy(
ssh, join(CONFIG["server_path"], "src", "tools"), join("server", "src", "tools"), "**/*.py", CONFIG["progress"]
)
logger.info("Copy component '%s'...", component)
deep_copy(
ssh,
join(CONFIG["server_path"], "src", component),
join("server", "src", component),
"**/*.py",
CONFIG["progress"]
)
if update:
execute_remote(
message="Start installing python packages on sytem...",
ssh=ssh,
command="cd server; sudo PIPENV_TIMEOUT=9999 pipenv install --system",
)
execute_remote(
message="Create virtual environment with python3 for argus...",
ssh=ssh,
command="cd server; PIPENV_TIMEOUT=9999 CI=1 pipenv install --skip-lock --site-packages",
)
execute_remote(
message="Create virtual environment with python3 for root...",
ssh=ssh,
command="cd server; sudo PIPENV_TIMEOUT=9999 CI=1 pipenv install --skip-lock --site-packages",
)
if restart:
execute_remote(
message="Restarting the service...",
ssh=ssh,
command="sudo systemctl restart argus_monitor.service argus_server.service",
)
ssh.close()
def install_server(update=False, restart=False):
install_component("server", update=update, restart=restart)
def install_monitoring(update=False, restart=False):
install_component("monitoring", update=update, restart=restart)
def install_database():
ssh = get_connection()
execute_remote(
message="Initialize database...",
ssh=ssh,
command="cd server; pipenv run flask db init",
)
execute_remote(
message="Migrate database...",
ssh=ssh,
command="cd server; pipenv run flask db migrate",
)
execute_remote(
message="Upgrade database...",
ssh=ssh,
command="cd server; pipenv run flask db upgrade",
)
execute_remote(
message="Updating database content...",
ssh=ssh,
command=f"cd server; pipenv run src/data.py -d -c {CONFIG['argus_db_content']}",
)
ssh.close()
def install_webapplication(restart=False):
ssh = get_connection()
execute_remote(
message="Delete old webapplication on remote site...",
ssh=ssh,
command="rm -R server/webapplication || true",
)
target = join("server", "webapplication")
logger.info("Copy web application: %s => %s", CONFIG["webapplication_path"], target)
deep_copy(ssh, CONFIG["webapplication_path"], target, "**/*", CONFIG["progress"])
if restart:
execute_remote(
message="Restarting the service...",
ssh=ssh,
command="sudo systemctl restart argus_server.service",
)
def main(argv=None): # IGNORE:C0111
if argv is None:
argv = sys.argv
else:
sys.argv.extend(argv)
try:
# Setup argument parser
parser = ArgumentParser(
description=program_license, formatter_class=RawDescriptionHelpFormatter
)
parser.add_argument(
"-v",
"--verbose",
dest="verbose",
action="count",
help="set verbosity level [default: %(default)s]",
)
parser.add_argument(
"component",
choices=["environment", "server", "monitoring", "webapplication", "database"],
)
parser.add_argument(
"-e",
"--env",
dest="environment",
default="",
help="Select a different config (install.{environment}.yaml)",
)
parser.add_argument(
"-r",
"--restart",
action="store_true",
help="Restart depending service(s) after deployment",
)
parser.add_argument(
"-u",
"--update",
action="store_true",
help="Update the python environment for the depending service(s) after deployment",
)
parser.add_argument(
"-p",
"--progress",
action="store_true",
help="Show progress bars",
)
# Process arguments
args = parser.parse_args()
if args.verbose:
logger.setLevel(logging.DEBUG)
logger.info("Verbose mode on")
else:
logger.setLevel(logging.INFO)
config_filename = __file__.replace(".py", ".yaml")
if args.environment:
config_filename = config_filename.replace(".yaml", "." + args.environment + ".yaml")
logger.info("Working with %s", args)
logger.info("Working from %s", config_filename)
with open(config_filename, "r") as stream:
global CONFIG
CONFIG = yaml.load(stream, Loader=yaml.FullLoader)
CONFIG["progress"] = args.progress
logger.info("Working with configuration: \n%s", json.dumps(CONFIG, indent=4, sort_keys=True))
input("Waiting before starting the installation to verify the configuration!")
if args.component == "environment":
install_environment()
elif args.component == "server":
install_server(args.update, args.restart)
elif args.component == "monitoring":
install_monitoring(args.update, args.restart)
elif args.component == "webapplication":
install_webapplication(args.restart)
elif args.component == "database":
install_database()
else:
logger.error("Unknown component: %s", args.component)
logger.info("Finished successfully!")
return 0
except KeyboardInterrupt:
# handle keyboard interrupt ###
logger.info("\n\nCancelled!\n")
return 0
except Exception:
logger.exception("Failed to execute!")
return 2
if __name__ == "__main__":
sys.exit(main())
| true | true |
f72efec7f239fcde6bd467031c71d0a0a0d48054 | 3,661 | py | Python | DNCNN/common.py | Khanhnn00/blind_sr_denoise | 3153f90d20fd884ab69b47c30c685e0175276055 | [
"Apache-2.0"
] | null | null | null | DNCNN/common.py | Khanhnn00/blind_sr_denoise | 3153f90d20fd884ab69b47c30c685e0175276055 | [
"Apache-2.0"
] | null | null | null | DNCNN/common.py | Khanhnn00/blind_sr_denoise | 3153f90d20fd884ab69b47c30c685e0175276055 | [
"Apache-2.0"
] | null | null | null | import os
import random
import numpy as np
import scipy.misc as misc
import imageio
from tqdm import tqdm
import cv2
from PIL import Image
import torch
import torch.nn.functional as F
IMG_EXTENSIONS = ['.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP']
BINARY_EXTENSIONS = ['.npy']
BENCHMARK = ['Set5', 'Set14', 'B100', 'Urban100', 'Manga109', 'DIV2K', 'DF2K']
####################
# Files & IO
####################
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
def is_binary_file(filename):
return any(filename.endswith(extension) for extension in BINARY_EXTENSIONS)
def _get_paths_from_images(path):
assert os.path.isdir(path), '[Error] [%s] is not a valid directory' % path
images = []
for dirpath, _, fnames in sorted(os.walk(path)):
for fname in sorted(fnames):
if is_image_file(fname):
img_path = os.path.join(dirpath, fname)
images.append(img_path)
assert images, '[%s] has no valid image file' % path
return images
def _get_paths_from_binary(path):
assert os.path.isdir(path), '[Error] [%s] is not a valid directory' % path
files = []
for dirpath, _, fnames in sorted(os.walk(path)):
for fname in sorted(fnames):
if is_binary_file(fname):
binary_path = os.path.join(dirpath, fname)
files.append(binary_path)
assert files, '[%s] has no valid binary file' % path
return files
def find_benchmark(dataroot):
bm_list = [dataroot.find(bm)>=0 for bm in BENCHMARK]
if not sum(bm_list) == 0:
bm_idx = bm_list.index(True)
bm_name = BENCHMARK[bm_idx]
else:
bm_name = 'MyImage'
return bm_name
def read_img(path):
# read image by misc or from .npy
# return: Numpy float32, HWC, RGB, [0,255]
img = imageio.imread(path, pilmode='RGB')
if img.ndim == 2:
img = np.expand_dims(img, axis=2)
return img
# image processing
# process on numpy image
####################
def im2tensor01(im_np):
"""Convert numpy to tensor to the gpu"""
im_np = im_np / 255.0 if im_np.dtype == 'uint8' else im_np
im_np = np.ascontiguousarray(im_np)
return torch.FloatTensor(np.transpose(im_np, (2, 0, 1)))
def tensor2im(im_t):
"""Copy the tensor to the cpu & convert to range [0,255]"""
im_np = np.clip(np.round((np.transpose(im_t.squeeze(0).detach().cpu().float().numpy(), (1, 2, 0)) + 1) / 2.0 * 255.0), 0, 255)
return im_np.astype(np.uint8)
def get_patch(img_tar, patch_size):
oh, ow = img_tar.shape[:2]
ip = patch_size
tp = ip
ix = random.randrange(0, ow - ip + 1)
iy = random.randrange(0, oh - ip + 1)
tx, ty = ix, iy
img_tar = img_tar[ty:ty + tp, tx:tx + tp, :]
return img_tar
def augment(img_list, hflip=True, rot=True):
# horizontal flip OR rotate
hflip = hflip and random.random() < 0.5
vflip = rot and random.random() < 0.5
rot90 = rot and random.random() < 0.5
def _augment(img):
if hflip: img = img[:, ::-1, :]
if vflip: img = img[::-1, :, :]
if rot90: img = img.transpose(1, 0, 2)
return img
return [_augment(img) for img in img_list]
def modcrop(img_in, scale):
img = np.copy(img_in)
if img.ndim == 2:
H, W = img.shape
H_r, W_r = H % scale, W % scale
img = img[:H - H_r, :W - W_r]
elif img.ndim == 3:
H, W, C = img.shape
H_r, W_r = H % scale, W % scale
img = img[:H - H_r, :W - W_r, :]
else:
raise ValueError('Wrong img ndim: [%d].' % img.ndim)
return img
| 29.055556 | 130 | 0.600656 | import os
import random
import numpy as np
import scipy.misc as misc
import imageio
from tqdm import tqdm
import cv2
from PIL import Image
import torch
import torch.nn.functional as F
IMG_EXTENSIONS = ['.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP']
BINARY_EXTENSIONS = ['.npy']
BENCHMARK = ['Set5', 'Set14', 'B100', 'Urban100', 'Manga109', 'DIV2K', 'DF2K']
n sorted(os.walk(path)):
for fname in sorted(fnames):
if is_image_file(fname):
img_path = os.path.join(dirpath, fname)
images.append(img_path)
assert images, '[%s] has no valid image file' % path
return images
def _get_paths_from_binary(path):
assert os.path.isdir(path), '[Error] [%s] is not a valid directory' % path
files = []
for dirpath, _, fnames in sorted(os.walk(path)):
for fname in sorted(fnames):
if is_binary_file(fname):
binary_path = os.path.join(dirpath, fname)
files.append(binary_path)
assert files, '[%s] has no valid binary file' % path
return files
def find_benchmark(dataroot):
bm_list = [dataroot.find(bm)>=0 for bm in BENCHMARK]
if not sum(bm_list) == 0:
bm_idx = bm_list.index(True)
bm_name = BENCHMARK[bm_idx]
else:
bm_name = 'MyImage'
return bm_name
def read_img(path):
img = imageio.imread(path, pilmode='RGB')
if img.ndim == 2:
img = np.expand_dims(img, axis=2)
return img
def tensor2im(im_t):
im_np = np.clip(np.round((np.transpose(im_t.squeeze(0).detach().cpu().float().numpy(), (1, 2, 0)) + 1) / 2.0 * 255.0), 0, 255)
return im_np.astype(np.uint8)
def get_patch(img_tar, patch_size):
oh, ow = img_tar.shape[:2]
ip = patch_size
tp = ip
ix = random.randrange(0, ow - ip + 1)
iy = random.randrange(0, oh - ip + 1)
tx, ty = ix, iy
img_tar = img_tar[ty:ty + tp, tx:tx + tp, :]
return img_tar
def augment(img_list, hflip=True, rot=True):
hflip = hflip and random.random() < 0.5
vflip = rot and random.random() < 0.5
rot90 = rot and random.random() < 0.5
def _augment(img):
if hflip: img = img[:, ::-1, :]
if vflip: img = img[::-1, :, :]
if rot90: img = img.transpose(1, 0, 2)
return img
return [_augment(img) for img in img_list]
def modcrop(img_in, scale):
img = np.copy(img_in)
if img.ndim == 2:
H, W = img.shape
H_r, W_r = H % scale, W % scale
img = img[:H - H_r, :W - W_r]
elif img.ndim == 3:
H, W, C = img.shape
H_r, W_r = H % scale, W % scale
img = img[:H - H_r, :W - W_r, :]
else:
raise ValueError('Wrong img ndim: [%d].' % img.ndim)
return img
| true | true |
f72efed312141d7d38b208a997d8ee5a183db48d | 1,290 | py | Python | app/core/tests/test_models.py | slauzinho/recipe-app-api | c05f2d007dc19bab5792742a1e7959b5cf8e95a4 | [
"MIT"
] | null | null | null | app/core/tests/test_models.py | slauzinho/recipe-app-api | c05f2d007dc19bab5792742a1e7959b5cf8e95a4 | [
"MIT"
] | null | null | null | app/core/tests/test_models.py | slauzinho/recipe-app-api | c05f2d007dc19bab5792742a1e7959b5cf8e95a4 | [
"MIT"
] | null | null | null | from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTests(TestCase):
def test_create_user_with_email_successful(self):
""" Test creating a new user with an email is successful"""
email = 'test@example.com'
password = 'testpass123'
user = get_user_model().objects.create_user(
email=email,
password=password
)
self.assertEqual(user.email, email)
self.assertTrue(user.check_password(password))
def test_new_user_email_normalized(self):
""" Test the email for a new user is normalized """
email = 'test@EXAMPLE.COM'
user = get_user_model().objects.create_user(email, 'test123')
self.assertEqual(user.email, email.lower())
def test_new_user_invalid_email(self):
""" Test creating user is no email raises error"""
with self.assertRaises(ValueError):
get_user_model().objects.create_user(None, 'test123')
def test_create_new_superuser(self):
""" Test creating a new super user"""
user = get_user_model().objects.create_superuser(
'test@example.com',
'test123'
)
self.assertTrue(user.is_superuser)
self.assertTrue(user.is_staff)
| 32.25 | 69 | 0.651163 | from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTests(TestCase):
def test_create_user_with_email_successful(self):
email = 'test@example.com'
password = 'testpass123'
user = get_user_model().objects.create_user(
email=email,
password=password
)
self.assertEqual(user.email, email)
self.assertTrue(user.check_password(password))
def test_new_user_email_normalized(self):
email = 'test@EXAMPLE.COM'
user = get_user_model().objects.create_user(email, 'test123')
self.assertEqual(user.email, email.lower())
def test_new_user_invalid_email(self):
with self.assertRaises(ValueError):
get_user_model().objects.create_user(None, 'test123')
def test_create_new_superuser(self):
user = get_user_model().objects.create_superuser(
'test@example.com',
'test123'
)
self.assertTrue(user.is_superuser)
self.assertTrue(user.is_staff)
| true | true |
f72efee2c58c739a39aee6ac1603f9a379173f68 | 960 | py | Python | pics/views.py | NinahMo/Pictogram | d7b1ad7af253e6b3a34c2495b370328bbc051059 | [
"Unlicense"
] | null | null | null | pics/views.py | NinahMo/Pictogram | d7b1ad7af253e6b3a34c2495b370328bbc051059 | [
"Unlicense"
] | null | null | null | pics/views.py | NinahMo/Pictogram | d7b1ad7af253e6b3a34c2495b370328bbc051059 | [
"Unlicense"
] | null | null | null | from django.shortcuts import render,redirect
from django.http import HttpResponse,Http404
from .models import Pics,categories
# Create your views here.
def welcome(request):
return render(request, 'welcome.html')
def pictogram(request):
images = Pics.objects.all()
return render(request, 'pictogram.html', {'images':images})
def show(request, image_id):
image = Pics.objects.get(id=image_id)
return render(request, 'show.html', {'image':image})
def search_results(request):
if 'categories' in request.GET and request.GET["categories"]:
search_term = request.GET.get("categories")
searched_categories = categories.search_by_categories(search_term)
message = f"{search_term}"
return render(request, 'search.html',{"message":message,"categories":searched_categories})
else:
message = "You haven't searched for any term"
return render(request, 'search.html',{"message":message}) | 34.285714 | 98 | 0.710417 | from django.shortcuts import render,redirect
from django.http import HttpResponse,Http404
from .models import Pics,categories
def welcome(request):
return render(request, 'welcome.html')
def pictogram(request):
images = Pics.objects.all()
return render(request, 'pictogram.html', {'images':images})
def show(request, image_id):
image = Pics.objects.get(id=image_id)
return render(request, 'show.html', {'image':image})
def search_results(request):
if 'categories' in request.GET and request.GET["categories"]:
search_term = request.GET.get("categories")
searched_categories = categories.search_by_categories(search_term)
message = f"{search_term}"
return render(request, 'search.html',{"message":message,"categories":searched_categories})
else:
message = "You haven't searched for any term"
return render(request, 'search.html',{"message":message}) | true | true |
f72effa674b9c81ff3e1f7f6616cfc19ae50580c | 3,781 | py | Python | fast_pixel_cnn_pp/test_end_to_end.py | tinyrobots/Generalized-PixelVAE | 8d8c6033e14bf2ce37749bd2604e4a90459ff3d4 | [
"MIT"
] | 510 | 2017-02-21T17:18:51.000Z | 2022-02-02T17:12:46.000Z | fast_pixel_cnn_pp/test_end_to_end.py | jinxu06/fast-pixel-cnn | ee99634be08c726c3da7e8ba2675c8d1448e15af | [
"MIT"
] | 4 | 2017-08-24T18:20:11.000Z | 2021-07-05T06:00:56.000Z | fast_pixel_cnn_pp/test_end_to_end.py | jinxu06/fast-pixel-cnn | ee99634be08c726c3da7e8ba2675c8d1448e15af | [
"MIT"
] | 82 | 2017-02-21T23:16:28.000Z | 2021-09-18T13:04:59.000Z | from . import model
from . import fast_nn
import tensorflow as tf
import numpy as np
import os
import unittest
class FastPixelCNNPPEndToEndTest(tf.test.TestCase):
def test_end_to_end(self):
with self.test_session() as sess:
print('Creating model')
image_size = (10, 32, 32, 4)
batch_size, image_height, image_width, image_channels = image_size
# Create placeholders.
row_input = tf.placeholder(
tf.float32, [batch_size, 1, image_width, image_channels],
name='row_input')
pixel_input = tf.placeholder(
tf.float32, [batch_size, 1, 1, image_channels],
name='pixel_input')
row_id = tf.placeholder(tf.int32, [], name='row_id')
col_id = tf.placeholder(tf.int32, [], name='col_id')
ema = tf.train.ExponentialMovingAverage(0.9995)
# Create the model.
model_spec = tf.make_template('model', model.model_spec)
sample, fast_nn_out, v_stack = model_spec(
row_input, pixel_input, row_id, col_id, image_size)
# Initialize the caches.
cache_variables = [
v for v in tf.global_variables() if 'cache' in v.name
]
sess.run(tf.variables_initializer(cache_variables))
# Load the pretrained model
print('Restoring variables')
vars_to_restore = {
k: v
for k, v in ema.variables_to_restore().items()
if 'cache' not in k
}
saver = tf.train.Saver(vars_to_restore)
ckpt_path = None
assert ckpt_path, 'Provide a path to the checkpoint in this file'
saver.restore(sess, ckpt_path)
# Create the fixed random input.
np.random.seed(2702)
x = np.random.randint(0, 256, size=(10, 32, 32, 3))
x = np.cast[np.float32]((x - 127.5) / 127.5)
x_pad = np.concatenate(
(x, np.ones((batch_size, 32, 32, 1))), axis=3)
x_downshift = fast_nn.down_shift(x_pad)
x_rightshift = fast_nn.right_shift(x_pad)
# Holds the output.
num_output_features = 10 * 10
output_features = np.zeros(
(batch_size, 32, 32, num_output_features))
# Compute all features.
print('Computing features')
sess.run(fast_nn.reset_cache_op())
for row in range(image_height):
x_row_input = x_downshift[:, row:(row + 1), :, :]
sess.run(v_stack, {row_input: x_row_input, row_id: row})
for col in range(image_width):
x_pixel_input = x_rightshift[:, row:(row + 1),
col:(col + 1), :]
feed_dict = {
row_id: row,
col_id: col,
pixel_input: x_pixel_input
}
pixel_features = sess.run(fast_nn_out, feed_dict)
output_features[:, row:(row + 1), col:(
col + 1), :] = pixel_features
ground_truth_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'ground_truth_output.npy')
ground_truth_features = np.load(ground_truth_file)
total_features = np.prod(output_features[0].shape)
for i in range(batch_size):
self.assertTrue(
np.allclose(
output_features[i, :, :, :],
ground_truth_features[i, :, :, :],
atol=1e-4))
| 39.8 | 89 | 0.519968 | from . import model
from . import fast_nn
import tensorflow as tf
import numpy as np
import os
import unittest
class FastPixelCNNPPEndToEndTest(tf.test.TestCase):
def test_end_to_end(self):
with self.test_session() as sess:
print('Creating model')
image_size = (10, 32, 32, 4)
batch_size, image_height, image_width, image_channels = image_size
row_input = tf.placeholder(
tf.float32, [batch_size, 1, image_width, image_channels],
name='row_input')
pixel_input = tf.placeholder(
tf.float32, [batch_size, 1, 1, image_channels],
name='pixel_input')
row_id = tf.placeholder(tf.int32, [], name='row_id')
col_id = tf.placeholder(tf.int32, [], name='col_id')
ema = tf.train.ExponentialMovingAverage(0.9995)
model_spec = tf.make_template('model', model.model_spec)
sample, fast_nn_out, v_stack = model_spec(
row_input, pixel_input, row_id, col_id, image_size)
cache_variables = [
v for v in tf.global_variables() if 'cache' in v.name
]
sess.run(tf.variables_initializer(cache_variables))
print('Restoring variables')
vars_to_restore = {
k: v
for k, v in ema.variables_to_restore().items()
if 'cache' not in k
}
saver = tf.train.Saver(vars_to_restore)
ckpt_path = None
assert ckpt_path, 'Provide a path to the checkpoint in this file'
saver.restore(sess, ckpt_path)
np.random.seed(2702)
x = np.random.randint(0, 256, size=(10, 32, 32, 3))
x = np.cast[np.float32]((x - 127.5) / 127.5)
x_pad = np.concatenate(
(x, np.ones((batch_size, 32, 32, 1))), axis=3)
x_downshift = fast_nn.down_shift(x_pad)
x_rightshift = fast_nn.right_shift(x_pad)
num_output_features = 10 * 10
output_features = np.zeros(
(batch_size, 32, 32, num_output_features))
print('Computing features')
sess.run(fast_nn.reset_cache_op())
for row in range(image_height):
x_row_input = x_downshift[:, row:(row + 1), :, :]
sess.run(v_stack, {row_input: x_row_input, row_id: row})
for col in range(image_width):
x_pixel_input = x_rightshift[:, row:(row + 1),
col:(col + 1), :]
feed_dict = {
row_id: row,
col_id: col,
pixel_input: x_pixel_input
}
pixel_features = sess.run(fast_nn_out, feed_dict)
output_features[:, row:(row + 1), col:(
col + 1), :] = pixel_features
ground_truth_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'ground_truth_output.npy')
ground_truth_features = np.load(ground_truth_file)
total_features = np.prod(output_features[0].shape)
for i in range(batch_size):
self.assertTrue(
np.allclose(
output_features[i, :, :, :],
ground_truth_features[i, :, :, :],
atol=1e-4))
| true | true |
f72f0248d59c0576c9f63814fa86650afed6d006 | 9,579 | py | Python | dowhy/do_why.py | mrklees/dowhy | a9e950fd0cf180dc4cbbca13332638aab9d00c65 | [
"MIT"
] | 3 | 2019-12-21T05:46:21.000Z | 2020-05-19T15:35:02.000Z | dowhy/do_why.py | mrklees/dowhy | a9e950fd0cf180dc4cbbca13332638aab9d00c65 | [
"MIT"
] | null | null | null | dowhy/do_why.py | mrklees/dowhy | a9e950fd0cf180dc4cbbca13332638aab9d00c65 | [
"MIT"
] | 3 | 2019-09-05T10:59:58.000Z | 2021-02-04T02:53:59.000Z | """ Module containing the main model class for the dowhy package.
"""
import logging
from sympy import init_printing
import dowhy.causal_estimators as causal_estimators
import dowhy.causal_refuters as causal_refuters
import dowhy.utils.cli_helpers as cli
from dowhy.causal_estimator import CausalEstimate
from dowhy.causal_graph import CausalGraph
from dowhy.causal_identifier import CausalIdentifier
init_printing() # To display symbolic math symbols
class CausalModel:
"""Main class for storing the causal model state.
"""
def __init__(self, data, treatment, outcome, graph=None,
common_causes=None, instruments=None, estimand_type="ate",
proceed_when_unidentifiable=False,
**kwargs):
"""Initialize data and create a causal graph instance.
Assigns treatment and outcome variables.
Also checks and finds the common causes and instruments for treatment
and outcome.
At least one of graph, common_causes or instruments must be provided.
:param data: a pandas dataframe containing treatment, outcome and other
variables.
:param treatment: name of the treatment variable
:param outcome: name of the outcome variable
:param graph: path to DOT file containing a DAG or a string containing
a DAG specification in DOT format
:param common_causes: names of common causes of treatment and _outcome
:param instruments: names of instrumental variables for the effect of
treatment on outcome
:returns: an instance of CausalModel class
"""
self._data = data
self._treatment = treatment
self._outcome = outcome
self._estimand_type = estimand_type
self._proceed_when_unidentifiable = proceed_when_unidentifiable
if 'logging_level' in kwargs:
logging.basicConfig(level=kwargs['logging_level'])
else:
logging.basicConfig(level=logging.INFO)
# TODO: move the logging level argument to a json file. Tue 20 Feb 2018 06:56:27 PM DST
self.logger = logging.getLogger(__name__)
if graph is None:
self.logger.warning("Causal Graph not provided. DoWhy will construct a graph based on data inputs.")
self._common_causes = common_causes
self._instruments = instruments
if common_causes is not None and instruments is not None:
self._graph = CausalGraph(
self._treatment,
self._outcome,
common_cause_names=self._common_causes,
instrument_names=self._instruments,
observed_node_names=self._data.columns.tolist()
)
elif common_causes is not None:
self._graph = CausalGraph(
self._treatment,
self._outcome,
common_cause_names=self._common_causes,
observed_node_names=self._data.columns.tolist()
)
elif instruments is not None:
self._graph = CausalGraph(
self._treatment,
self._outcome,
instrument_names=self._instruments,
observed_node_names=self._data.columns.tolist()
)
else:
cli.query_yes_no(
"WARN: Are you sure that there are no common causes of treatment and outcome?",
default=None
)
else:
self._graph = CausalGraph(
self._treatment,
self._outcome,
graph,
observed_node_names=self._data.columns.tolist()
)
self._common_causes = self._graph.get_common_causes(self._treatment, self._outcome)
self._instruments = self._graph.get_instruments(self._treatment,
self._outcome)
self._other_variables = kwargs
self.summary()
def identify_effect(self):
"""Identify the causal effect to be estimated, using properties of the causal graph.
:returns: a probability expression for the causal effect if identified, else NULL
"""
self.identifier = CausalIdentifier(self._graph,
self._estimand_type,
proceed_when_unidentifiable=self._proceed_when_unidentifiable)
identified_estimand = self.identifier.identify_effect()
return identified_estimand
def estimate_effect(self, identified_estimand, method_name=None,
test_significance=None, method_params=None):
"""Estimate the identified causal effect.
If method_name is provided, uses the provided method. Else, finds a
suitable method to be used.
:param identified_estimand: a probability expression
that represents the effect to be estimated. Output of
CausalModel.identify_effect method
:param method_name: (optional) name of the estimation method to be used.
:returns: an instance of the CausalEstimate class, containing the causal effect estimate
and other method-dependent information
"""
if method_name is None:
pass
else:
str_arr = method_name.split(".")
identifier_name = str_arr[0]
estimator_name = str_arr[1]
identified_estimand.set_identifier_method(identifier_name)
causal_estimator_class = causal_estimators.get_class_object(estimator_name + "_estimator")
# Check if estimator's target estimand is identified
if identified_estimand.estimands[identifier_name] is None:
self.logger.warning("No valid identified estimand for using instrumental variables method")
estimate = CausalEstimate(None, None, None)
else:
causal_estimator = causal_estimator_class(
self._data,
identified_estimand,
self._treatment, self._outcome,
test_significance=test_significance,
params=method_params
)
estimate = causal_estimator.estimate_effect()
estimate.add_params(
estimand_type=identified_estimand.estimand_type,
estimator_class=causal_estimator_class
)
return estimate
def do(self, x, identified_estimand, method_name=None, method_params=None):
"""Estimate the identified causal effect.
If method_name is provided, uses the provided method. Else, finds a
suitable method to be used.
:param identified_estimand: a probability expression
that represents the effect to be estimated. Output of
CausalModel.identify_effect method
:param method_name: (optional) name of the estimation method to be used.
:returns: an instance of the CausalEstimate class, containing the causal effect estimate
and other method-dependent information
"""
if method_name is None:
pass
else:
str_arr = method_name.split(".")
identifier_name = str_arr[0]
estimator_name = str_arr[1]
identified_estimand.set_identifier_method(identifier_name)
causal_estimator_class = causal_estimators.get_class_object(estimator_name + "_estimator")
# Check if estimator's target estimand is identified
if identified_estimand.estimands[identifier_name] is None:
self.logger.warning("No valid identified estimand for using instrumental variables method")
estimate = CausalEstimate(None, None, None)
else:
causal_estimator = causal_estimator_class(
self._data,
identified_estimand,
self._treatment, self._outcome,
test_significance=False,
params=method_params
)
try:
estimate = causal_estimator.do(x)
except NotImplementedError:
self.logger.error('Do Operation not implemented or not supported for this estimator.')
raise NotImplementedError
return estimate
def refute_estimate(self, estimand, estimate, method_name=None, **kwargs):
"""Refute an estimated causal effect.
If method_name is provided, uses the provided method. Else, finds a
suitable method to use.
:param estimate: an instance of the CausalEstimate class.
:returns: an instance of the RefuteResult class
"""
if method_name is None:
pass
else:
refuter_class = causal_refuters.get_class_object(method_name)
refuter = refuter_class(
self._data,
identified_estimand=estimand,
estimate=estimate,
**kwargs
)
res = refuter.refute_estimate()
return res
def view_model(self, layout="dot"):
"""View the causal DAG.
:returns: a visualization of the graph
"""
self._graph.view_graph(layout)
def summary(self):
"""Print a text summary of the model.
:returns: None
"""
self.logger.info("Model to find the causal effect of treatment {0} on outcome {1}".format(self._treatment, self._outcome))
| 38.939024 | 130 | 0.624178 |
import logging
from sympy import init_printing
import dowhy.causal_estimators as causal_estimators
import dowhy.causal_refuters as causal_refuters
import dowhy.utils.cli_helpers as cli
from dowhy.causal_estimator import CausalEstimate
from dowhy.causal_graph import CausalGraph
from dowhy.causal_identifier import CausalIdentifier
init_printing()
class CausalModel:
def __init__(self, data, treatment, outcome, graph=None,
common_causes=None, instruments=None, estimand_type="ate",
proceed_when_unidentifiable=False,
**kwargs):
self._data = data
self._treatment = treatment
self._outcome = outcome
self._estimand_type = estimand_type
self._proceed_when_unidentifiable = proceed_when_unidentifiable
if 'logging_level' in kwargs:
logging.basicConfig(level=kwargs['logging_level'])
else:
logging.basicConfig(level=logging.INFO)
self.logger = logging.getLogger(__name__)
if graph is None:
self.logger.warning("Causal Graph not provided. DoWhy will construct a graph based on data inputs.")
self._common_causes = common_causes
self._instruments = instruments
if common_causes is not None and instruments is not None:
self._graph = CausalGraph(
self._treatment,
self._outcome,
common_cause_names=self._common_causes,
instrument_names=self._instruments,
observed_node_names=self._data.columns.tolist()
)
elif common_causes is not None:
self._graph = CausalGraph(
self._treatment,
self._outcome,
common_cause_names=self._common_causes,
observed_node_names=self._data.columns.tolist()
)
elif instruments is not None:
self._graph = CausalGraph(
self._treatment,
self._outcome,
instrument_names=self._instruments,
observed_node_names=self._data.columns.tolist()
)
else:
cli.query_yes_no(
"WARN: Are you sure that there are no common causes of treatment and outcome?",
default=None
)
else:
self._graph = CausalGraph(
self._treatment,
self._outcome,
graph,
observed_node_names=self._data.columns.tolist()
)
self._common_causes = self._graph.get_common_causes(self._treatment, self._outcome)
self._instruments = self._graph.get_instruments(self._treatment,
self._outcome)
self._other_variables = kwargs
self.summary()
def identify_effect(self):
self.identifier = CausalIdentifier(self._graph,
self._estimand_type,
proceed_when_unidentifiable=self._proceed_when_unidentifiable)
identified_estimand = self.identifier.identify_effect()
return identified_estimand
def estimate_effect(self, identified_estimand, method_name=None,
test_significance=None, method_params=None):
if method_name is None:
pass
else:
str_arr = method_name.split(".")
identifier_name = str_arr[0]
estimator_name = str_arr[1]
identified_estimand.set_identifier_method(identifier_name)
causal_estimator_class = causal_estimators.get_class_object(estimator_name + "_estimator")
if identified_estimand.estimands[identifier_name] is None:
self.logger.warning("No valid identified estimand for using instrumental variables method")
estimate = CausalEstimate(None, None, None)
else:
causal_estimator = causal_estimator_class(
self._data,
identified_estimand,
self._treatment, self._outcome,
test_significance=test_significance,
params=method_params
)
estimate = causal_estimator.estimate_effect()
estimate.add_params(
estimand_type=identified_estimand.estimand_type,
estimator_class=causal_estimator_class
)
return estimate
def do(self, x, identified_estimand, method_name=None, method_params=None):
if method_name is None:
pass
else:
str_arr = method_name.split(".")
identifier_name = str_arr[0]
estimator_name = str_arr[1]
identified_estimand.set_identifier_method(identifier_name)
causal_estimator_class = causal_estimators.get_class_object(estimator_name + "_estimator")
# Check if estimator's target estimand is identified
if identified_estimand.estimands[identifier_name] is None:
self.logger.warning("No valid identified estimand for using instrumental variables method")
estimate = CausalEstimate(None, None, None)
else:
causal_estimator = causal_estimator_class(
self._data,
identified_estimand,
self._treatment, self._outcome,
test_significance=False,
params=method_params
)
try:
estimate = causal_estimator.do(x)
except NotImplementedError:
self.logger.error('Do Operation not implemented or not supported for this estimator.')
raise NotImplementedError
return estimate
def refute_estimate(self, estimand, estimate, method_name=None, **kwargs):
if method_name is None:
pass
else:
refuter_class = causal_refuters.get_class_object(method_name)
refuter = refuter_class(
self._data,
identified_estimand=estimand,
estimate=estimate,
**kwargs
)
res = refuter.refute_estimate()
return res
def view_model(self, layout="dot"):
self._graph.view_graph(layout)
def summary(self):
self.logger.info("Model to find the causal effect of treatment {0} on outcome {1}".format(self._treatment, self._outcome))
| true | true |
f72f03ee4306e4479f46e2f00d5347764d7ca9b6 | 6,514 | py | Python | lib/flows/cron/compactors_test.py | nahidupa/grr | 100a9d85ef2abb234e12e3ac2623caffb4116be7 | [
"Apache-2.0"
] | 3 | 2016-02-20T13:06:31.000Z | 2017-12-15T12:09:01.000Z | lib/flows/cron/compactors_test.py | nahidupa/grr | 100a9d85ef2abb234e12e3ac2623caffb4116be7 | [
"Apache-2.0"
] | 3 | 2020-09-11T12:54:50.000Z | 2020-09-11T12:55:01.000Z | lib/flows/cron/compactors_test.py | nahidupa/grr | 100a9d85ef2abb234e12e3ac2623caffb4116be7 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
"""Tests for grr.lib.flows.cron.compactors."""
# pylint: disable=unused-import, g-bad-import-order
from grr.lib import server_plugins
# pylint: enable=unused-import, g-bad-import-order
from grr.lib import aff4
from grr.lib import flags
from grr.lib import flow
from grr.lib import rdfvalue
from grr.lib import test_lib
from grr.lib import utils
class PackedVersionedCollectionCompactorTest(test_lib.FlowTestsBaseclass):
"""Test for PackedVersionedCollectionCompactor."""
def testCompactsSingleCollection(self):
with aff4.FACTORY.Create("aff4:/tmp/coll", "PackedVersionedCollection",
mode="w", token=self.token) as fd:
fd.Add(rdfvalue.GrrMessage(request_id=1))
# Collection is not compacted, so recorded size is 0.
fd = aff4.FACTORY.Open("aff4:/tmp/coll", token=self.token)
self.assertEqual(fd.Get(fd.Schema.SIZE), 0)
# Run the compactor.
for _ in test_lib.TestFlowHelper("PackedVersionedCollectionCompactor",
token=self.token):
pass
# Collection is compacted now, so recorded size is 1.
fd = aff4.FACTORY.Open("aff4:/tmp/coll", token=self.token)
self.assertEqual(fd.Get(fd.Schema.SIZE), 1)
def testNotificationIsRemovedAfterCompaction(self):
with aff4.FACTORY.Create("aff4:/tmp/coll", "PackedVersionedCollection",
mode="w", token=self.token) as fd:
fd.Add(rdfvalue.GrrMessage(request_id=1))
# Check that there's 1 compaction notification for our collection.
notifications = aff4.PackedVersionedCollection.QueryNotifications(
token=self.token)
notifications = [n for n in notifications
if n == "aff4:/tmp/coll"]
self.assertEqual(len(list(notifications)), 1)
# Run the compactor.
for _ in test_lib.TestFlowHelper("PackedVersionedCollectionCompactor",
token=self.token):
pass
# Check that notification for our collection is deleted after compaction.
notifications = aff4.PackedVersionedCollection.QueryNotifications(
token=self.token)
notifications = [n for n in notifications
if n == "aff4:/tmp/coll"]
self.assertEqual(len(list(notifications)), 0)
def testNewNotificationsAreNotRemovedAfterCompaction(self):
def AddNewElementToCollection(*unused_args, **unused_kwargs):
with aff4.FACTORY.Create("aff4:/tmp/coll", "PackedVersionedCollection",
mode="w", token=self.token) as fd:
fd.Add(rdfvalue.GrrMessage(request_id=1))
AddNewElementToCollection()
# Check that there's 1 compaction notification for our collection.
notifications = aff4.PackedVersionedCollection.QueryNotifications(
token=self.token)
notifications = [n for n in notifications
if n == "aff4:/tmp/coll"]
self.assertEqual(len(list(notifications)), 1)
# When Compact() is called on collection, we add additional element to
# the collection and notification gets written to the data store.
# This notification shouldn't be deleted after compaction, because
# it was written during the compaction, and therefore there are
# probably some uncompacted elements that should be compacted during
# then next compaction round.
with utils.Stubber(aff4.PackedVersionedCollection, "Compact",
AddNewElementToCollection):
# Run the compactor.
for _ in test_lib.TestFlowHelper("PackedVersionedCollectionCompactor",
token=self.token):
pass
# Check that notification for our collection is deleted after compaction.
notifications = aff4.PackedVersionedCollection.QueryNotifications(
token=self.token)
notifications = [n for n in notifications
if n == "aff4:/tmp/coll"]
self.assertEqual(len(list(notifications)), 1)
def testCompactsTwoCollections(self):
with aff4.FACTORY.Create("aff4:/tmp/coll1", "PackedVersionedCollection",
mode="w", token=self.token) as fd:
fd.Add(rdfvalue.GrrMessage(request_id=1))
with aff4.FACTORY.Create("aff4:/tmp/coll2", "PackedVersionedCollection",
mode="w", token=self.token) as fd:
fd.Add(rdfvalue.GrrMessage(request_id=1))
# Collection is not compacted, so recorded size is 0 for both collections.
fd = aff4.FACTORY.Open("aff4:/tmp/coll1", token=self.token)
self.assertEqual(fd.Get(fd.Schema.SIZE), 0)
fd = aff4.FACTORY.Open("aff4:/tmp/coll2", token=self.token)
self.assertEqual(fd.Get(fd.Schema.SIZE), 0)
# Run the compactor.
for _ in test_lib.TestFlowHelper("PackedVersionedCollectionCompactor",
token=self.token):
pass
# Collection is not compacted, so recorded size is 1 for both collections.
fd = aff4.FACTORY.Open("aff4:/tmp/coll1", token=self.token)
self.assertEqual(fd.Get(fd.Schema.SIZE), 1)
fd = aff4.FACTORY.Open("aff4:/tmp/coll2", token=self.token)
self.assertEqual(fd.Get(fd.Schema.SIZE), 1)
def testSecondConsecutiveRunDoesNothing(self):
with aff4.FACTORY.Create("aff4:/tmp/coll", "PackedVersionedCollection",
mode="w", token=self.token) as fd:
fd.Add(rdfvalue.GrrMessage(request_id=1))
# Collection is not compacted, so recorded size is 0.
fd = aff4.FACTORY.Open("aff4:/tmp/coll", token=self.token)
self.assertEqual(fd.Get(fd.Schema.SIZE), 0)
# Run the compactor and check that it reports that our collection
# got compacted.
flow_urn = flow.GRRFlow.StartFlow(
flow_name="PackedVersionedCollectionCompactor", sync=True,
token=self.token)
flow_fd = aff4.FACTORY.Open(flow_urn, token=self.token)
self.assertTrue(list(l.log_message for l in flow_fd.GetLog()
if "aff4:/tmp/coll" in l.log_message))
# Run the compactor again and check that our collection isn't
# mentioned.
flow_urn = flow.GRRFlow.StartFlow(
flow_name="PackedVersionedCollectionCompactor", sync=True,
token=self.token)
flow_fd = aff4.FACTORY.Open(flow_urn, token=self.token)
self.assertFalse(list(l.log_message for l in flow_fd.GetLog()
if "aff4:/tmp/coll" in l.log_message))
def main(argv):
# Run the full test suite
test_lib.GrrTestProgram(argv=argv)
if __name__ == "__main__":
flags.StartMain(main)
| 40.7125 | 78 | 0.675161 |
from grr.lib import server_plugins
from grr.lib import aff4
from grr.lib import flags
from grr.lib import flow
from grr.lib import rdfvalue
from grr.lib import test_lib
from grr.lib import utils
class PackedVersionedCollectionCompactorTest(test_lib.FlowTestsBaseclass):
def testCompactsSingleCollection(self):
with aff4.FACTORY.Create("aff4:/tmp/coll", "PackedVersionedCollection",
mode="w", token=self.token) as fd:
fd.Add(rdfvalue.GrrMessage(request_id=1))
fd = aff4.FACTORY.Open("aff4:/tmp/coll", token=self.token)
self.assertEqual(fd.Get(fd.Schema.SIZE), 0)
for _ in test_lib.TestFlowHelper("PackedVersionedCollectionCompactor",
token=self.token):
pass
fd = aff4.FACTORY.Open("aff4:/tmp/coll", token=self.token)
self.assertEqual(fd.Get(fd.Schema.SIZE), 1)
def testNotificationIsRemovedAfterCompaction(self):
with aff4.FACTORY.Create("aff4:/tmp/coll", "PackedVersionedCollection",
mode="w", token=self.token) as fd:
fd.Add(rdfvalue.GrrMessage(request_id=1))
notifications = aff4.PackedVersionedCollection.QueryNotifications(
token=self.token)
notifications = [n for n in notifications
if n == "aff4:/tmp/coll"]
self.assertEqual(len(list(notifications)), 1)
# Run the compactor.
for _ in test_lib.TestFlowHelper("PackedVersionedCollectionCompactor",
token=self.token):
pass
# Check that notification for our collection is deleted after compaction.
notifications = aff4.PackedVersionedCollection.QueryNotifications(
token=self.token)
notifications = [n for n in notifications
if n == "aff4:/tmp/coll"]
self.assertEqual(len(list(notifications)), 0)
def testNewNotificationsAreNotRemovedAfterCompaction(self):
def AddNewElementToCollection(*unused_args, **unused_kwargs):
with aff4.FACTORY.Create("aff4:/tmp/coll", "PackedVersionedCollection",
mode="w", token=self.token) as fd:
fd.Add(rdfvalue.GrrMessage(request_id=1))
AddNewElementToCollection()
# Check that there's 1 compaction notification for our collection.
notifications = aff4.PackedVersionedCollection.QueryNotifications(
token=self.token)
notifications = [n for n in notifications
if n == "aff4:/tmp/coll"]
self.assertEqual(len(list(notifications)), 1)
# it was written during the compaction, and therefore there are
# probably some uncompacted elements that should be compacted during
# then next compaction round.
with utils.Stubber(aff4.PackedVersionedCollection, "Compact",
AddNewElementToCollection):
# Run the compactor.
for _ in test_lib.TestFlowHelper("PackedVersionedCollectionCompactor",
token=self.token):
pass
# Check that notification for our collection is deleted after compaction.
notifications = aff4.PackedVersionedCollection.QueryNotifications(
token=self.token)
notifications = [n for n in notifications
if n == "aff4:/tmp/coll"]
self.assertEqual(len(list(notifications)), 1)
def testCompactsTwoCollections(self):
with aff4.FACTORY.Create("aff4:/tmp/coll1", "PackedVersionedCollection",
mode="w", token=self.token) as fd:
fd.Add(rdfvalue.GrrMessage(request_id=1))
with aff4.FACTORY.Create("aff4:/tmp/coll2", "PackedVersionedCollection",
mode="w", token=self.token) as fd:
fd.Add(rdfvalue.GrrMessage(request_id=1))
# Collection is not compacted, so recorded size is 0 for both collections.
fd = aff4.FACTORY.Open("aff4:/tmp/coll1", token=self.token)
self.assertEqual(fd.Get(fd.Schema.SIZE), 0)
fd = aff4.FACTORY.Open("aff4:/tmp/coll2", token=self.token)
self.assertEqual(fd.Get(fd.Schema.SIZE), 0)
# Run the compactor.
for _ in test_lib.TestFlowHelper("PackedVersionedCollectionCompactor",
token=self.token):
pass
# Collection is not compacted, so recorded size is 1 for both collections.
fd = aff4.FACTORY.Open("aff4:/tmp/coll1", token=self.token)
self.assertEqual(fd.Get(fd.Schema.SIZE), 1)
fd = aff4.FACTORY.Open("aff4:/tmp/coll2", token=self.token)
self.assertEqual(fd.Get(fd.Schema.SIZE), 1)
def testSecondConsecutiveRunDoesNothing(self):
with aff4.FACTORY.Create("aff4:/tmp/coll", "PackedVersionedCollection",
mode="w", token=self.token) as fd:
fd.Add(rdfvalue.GrrMessage(request_id=1))
# Collection is not compacted, so recorded size is 0.
fd = aff4.FACTORY.Open("aff4:/tmp/coll", token=self.token)
self.assertEqual(fd.Get(fd.Schema.SIZE), 0)
# Run the compactor and check that it reports that our collection
# got compacted.
flow_urn = flow.GRRFlow.StartFlow(
flow_name="PackedVersionedCollectionCompactor", sync=True,
token=self.token)
flow_fd = aff4.FACTORY.Open(flow_urn, token=self.token)
self.assertTrue(list(l.log_message for l in flow_fd.GetLog()
if "aff4:/tmp/coll" in l.log_message))
# Run the compactor again and check that our collection isn't
flow_urn = flow.GRRFlow.StartFlow(
flow_name="PackedVersionedCollectionCompactor", sync=True,
token=self.token)
flow_fd = aff4.FACTORY.Open(flow_urn, token=self.token)
self.assertFalse(list(l.log_message for l in flow_fd.GetLog()
if "aff4:/tmp/coll" in l.log_message))
def main(argv):
test_lib.GrrTestProgram(argv=argv)
if __name__ == "__main__":
flags.StartMain(main)
| true | true |
f72f0480cd1832c1a453482d9f0e8bb0cd69f5f7 | 6,838 | py | Python | carla-data-export/dataexport.py | zhangyanyu0722/EC523_Project | 72673713bb798023e82ccc257e8c05459c34a4b9 | [
"MIT"
] | 3 | 2020-10-06T19:32:02.000Z | 2020-10-21T04:16:04.000Z | carla-data-export/dataexport.py | zhangyanyu0722/EC523_Project | 72673713bb798023e82ccc257e8c05459c34a4b9 | [
"MIT"
] | null | null | null | carla-data-export/dataexport.py | zhangyanyu0722/EC523_Project | 72673713bb798023e82ccc257e8c05459c34a4b9 | [
"MIT"
] | null | null | null | """
This file contains all the methods responsible for saving the generated data in the correct output format.
"""
import cv2
import numpy as np
import os
import logging
from utils import degrees_to_radians
import json
def save_groundplanes(planes_fname, player_measurements, lidar_height):
from math import cos, sin
""" Saves the groundplane vector of the current frame.
The format of the ground plane file is first three lines describing the file (number of parameters).
The next line is the three parameters of the normal vector, and the last is the height of the normal vector,
which is the same as the distance to the camera in meters.
"""
rotation = player_measurements.transform.rotation
pitch, roll = rotation.pitch, rotation.roll
# Since measurements are in degrees, convert to radians
pitch = degrees_to_radians(pitch)
roll = degrees_to_radians(roll)
# Rotate normal vector (y) wrt. pitch and yaw
normal_vector = [cos(pitch)*sin(roll),
-cos(pitch)*cos(roll),
sin(pitch)
]
normal_vector = map(str, normal_vector)
with open(planes_fname, 'w') as f:
f.write("# Plane\n")
f.write("Width 4\n")
f.write("Height 1\n")
f.write("{} {}\n".format(" ".join(normal_vector), lidar_height))
logging.info("Wrote plane data to %s", planes_fname)
def save_ref_files(OUTPUT_FOLDER, TIME_ON_NEW_EPISODE, PHASE, id):
""" Appends the id of the given record to the files """
# for name in ['train.txt', 'val.txt', 'trainval.txt']:
# path = os.path.join(OUTPUT_FOLDER, name)
# with open(path, 'a') as f:
# f.write("{0:06}".format(id) + '\n')
# logging.info("Wrote reference files to %s", path)
prefix = os.path.join("\".", "data", "carla", PHASE, "label", TIME_ON_NEW_EPISODE)
name = "{0:06}.json\"".format(id)
path = os.path.join(OUTPUT_FOLDER, "label", "{}.json".format(TIME_ON_NEW_EPISODE))
with open(path, "a") as f:
filePath = os.path.join(prefix, name)
f.write(filePath + "\n")
logging.info("Wrote reference files to %s", path)
def save_image_data(filename, image):
logging.info("Wrote image data to %s", filename)
# Convert to correct color format
color_fmt = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
cv2.imwrite(filename, color_fmt)
def save_lidar_data(filename, point_cloud, LIDAR_HEIGHT, format="bin"):
""" Saves lidar data to given filename, according to the lidar data format.
bin is used for KITTI-data format, while .ply is the regular point cloud format
In Unreal, the coordinate system of the engine is defined as, which is the same as the lidar points
z
^ ^ x
| /
| /
|/____> y
This is a left-handed coordinate system, with x being forward, y to the right and z up
See also https://github.com/carla-simulator/carla/issues/498
However, the lidar coordinate system from KITTI is defined as
z
^ ^ x
| /
| /
y<____|/
Which is a right handed coordinate sylstem
Therefore, we need to flip the y axis of the lidar in order to get the correct lidar format for kitti.
This corresponds to the following changes from Carla to Kitti
Carla: X Y Z
KITTI: X -Y Z
NOTE: We do not flip the coordinate system when saving to .ply.
"""
logging.info("Wrote lidar data to %s", filename)
if format == "bin":
lidar_array = [[point[0], -point[1], point[2], 1.0]
for point in point_cloud]
lidar_array = np.array(lidar_array).astype(np.float32)
logging.debug("Lidar min/max of x: {} {}".format(
lidar_array[:, 0].min(), lidar_array[:, 0].max()))
logging.debug("Lidar min/max of y: {} {}".format(
lidar_array[:, 1].min(), lidar_array[:, 0].max()))
logging.debug("Lidar min/max of z: {} {}".format(
lidar_array[:, 2].min(), lidar_array[:, 0].max()))
lidar_array.tofile(filename)
else:
lidar_measurement.point_cloud.save_to_disk(filename)
def save_kitti_data(filename, datapoints):
with open(filename, 'w') as f:
# out_str = "\n".join([str(point) for point in datapoints if point])
# f.write(out_str)
json.dump(datapoints, f)
logging.info("Wrote kitti data to %s", filename)
def save_calibration_matrices(filename, intrinsic_mat, extrinsic_mat):
""" Saves the calibration matrices to a file.
AVOD (and KITTI) refers to P as P=K*[R;t], so we will just store P.
The resulting file will contain:
3x4 p0-p3 Camera P matrix. Contains extrinsic
and intrinsic parameters. (P=K*[R;t])
3x3 r0_rect Rectification matrix, required to transform points
from velodyne to camera coordinate frame.
3x4 tr_velodyne_to_cam Used to transform from velodyne to cam
coordinate frame according to:
Point_Camera = P_cam * R0_rect *
Tr_velo_to_cam *
Point_Velodyne.
3x4 tr_imu_to_velo Used to transform from imu to velodyne coordinate frame. This is not needed since we do not export
imu data.
"""
# KITTI format demands that we flatten in row-major order
ravel_mode = 'C'
P0 = intrinsic_mat
P0 = np.column_stack((P0, np.array([0, 0, 0])))
P0 = np.ravel(P0, order=ravel_mode)
R0 = np.identity(3)
TR_velodyne = np.array([[0, -1, 0],
[0, 0, -1],
[1, 0, 0]])
# Add translation vector from velo to camera. This is 0 because the position of camera and lidar is equal in our configuration.
TR_velodyne = np.column_stack((TR_velodyne, np.array([0, 0, 0])))
TR_imu_to_velo = np.identity(3)
TR_imu_to_velo = np.column_stack((TR_imu_to_velo, np.array([0, 0, 0])))
def write_flat(f, name, arr):
f.write("{}: {}\n".format(name, ' '.join(
map(str, arr.flatten(ravel_mode).squeeze()))))
# All matrices are written on a line with spacing
with open(filename, 'w') as f:
for i in range(4): # Avod expects all 4 P-matrices even though we only use the first
write_flat(f, "P" + str(i), P0)
write_flat(f, "R0_rect", R0)
write_flat(f, "Tr_velo_to_cam", TR_velodyne)
write_flat(f, "TR_imu_to_velo", TR_imu_to_velo)
logging.info("Wrote all calibration matrices to %s", filename)
| 43.278481 | 135 | 0.603832 | import cv2
import numpy as np
import os
import logging
from utils import degrees_to_radians
import json
def save_groundplanes(planes_fname, player_measurements, lidar_height):
from math import cos, sin
rotation = player_measurements.transform.rotation
pitch, roll = rotation.pitch, rotation.roll
pitch = degrees_to_radians(pitch)
roll = degrees_to_radians(roll)
normal_vector = [cos(pitch)*sin(roll),
-cos(pitch)*cos(roll),
sin(pitch)
]
normal_vector = map(str, normal_vector)
with open(planes_fname, 'w') as f:
f.write("# Plane\n")
f.write("Width 4\n")
f.write("Height 1\n")
f.write("{} {}\n".format(" ".join(normal_vector), lidar_height))
logging.info("Wrote plane data to %s", planes_fname)
def save_ref_files(OUTPUT_FOLDER, TIME_ON_NEW_EPISODE, PHASE, id):
prefix = os.path.join("\".", "data", "carla", PHASE, "label", TIME_ON_NEW_EPISODE)
name = "{0:06}.json\"".format(id)
path = os.path.join(OUTPUT_FOLDER, "label", "{}.json".format(TIME_ON_NEW_EPISODE))
with open(path, "a") as f:
filePath = os.path.join(prefix, name)
f.write(filePath + "\n")
logging.info("Wrote reference files to %s", path)
def save_image_data(filename, image):
logging.info("Wrote image data to %s", filename)
color_fmt = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
cv2.imwrite(filename, color_fmt)
def save_lidar_data(filename, point_cloud, LIDAR_HEIGHT, format="bin"):
logging.info("Wrote lidar data to %s", filename)
if format == "bin":
lidar_array = [[point[0], -point[1], point[2], 1.0]
for point in point_cloud]
lidar_array = np.array(lidar_array).astype(np.float32)
logging.debug("Lidar min/max of x: {} {}".format(
lidar_array[:, 0].min(), lidar_array[:, 0].max()))
logging.debug("Lidar min/max of y: {} {}".format(
lidar_array[:, 1].min(), lidar_array[:, 0].max()))
logging.debug("Lidar min/max of z: {} {}".format(
lidar_array[:, 2].min(), lidar_array[:, 0].max()))
lidar_array.tofile(filename)
else:
lidar_measurement.point_cloud.save_to_disk(filename)
def save_kitti_data(filename, datapoints):
with open(filename, 'w') as f:
json.dump(datapoints, f)
logging.info("Wrote kitti data to %s", filename)
def save_calibration_matrices(filename, intrinsic_mat, extrinsic_mat):
ravel_mode = 'C'
P0 = intrinsic_mat
P0 = np.column_stack((P0, np.array([0, 0, 0])))
P0 = np.ravel(P0, order=ravel_mode)
R0 = np.identity(3)
TR_velodyne = np.array([[0, -1, 0],
[0, 0, -1],
[1, 0, 0]])
TR_velodyne = np.column_stack((TR_velodyne, np.array([0, 0, 0])))
TR_imu_to_velo = np.identity(3)
TR_imu_to_velo = np.column_stack((TR_imu_to_velo, np.array([0, 0, 0])))
def write_flat(f, name, arr):
f.write("{}: {}\n".format(name, ' '.join(
map(str, arr.flatten(ravel_mode).squeeze()))))
with open(filename, 'w') as f:
for i in range(4):
write_flat(f, "P" + str(i), P0)
write_flat(f, "R0_rect", R0)
write_flat(f, "Tr_velo_to_cam", TR_velodyne)
write_flat(f, "TR_imu_to_velo", TR_imu_to_velo)
logging.info("Wrote all calibration matrices to %s", filename)
| true | true |
f72f0708d59dc5469fe994c4b30668cfc4355f4a | 22 | py | Python | __init__.py | cosanlab/facesync | bd5922de5729e4e76a6eaae84b45d965660f1545 | [
"MIT"
] | 9 | 2018-07-13T14:06:07.000Z | 2021-12-24T01:53:20.000Z | __init__.py | cosanlab/facesync | bd5922de5729e4e76a6eaae84b45d965660f1545 | [
"MIT"
] | null | null | null | __init__.py | cosanlab/facesync | bd5922de5729e4e76a6eaae84b45d965660f1545 | [
"MIT"
] | 2 | 2019-11-24T00:43:39.000Z | 2020-10-08T05:06:52.000Z | __all__ = ["facesync"] | 22 | 22 | 0.681818 | __all__ = ["facesync"] | true | true |
f72f071336b0f843d1521175037b68c86bc72fb7 | 467 | py | Python | complex/complex/logger.py | jasonamyers/pynash-click | 512e9712dc1de80e76a6815e0df04dd46af45641 | [
"MIT"
] | null | null | null | complex/complex/logger.py | jasonamyers/pynash-click | 512e9712dc1de80e76a6815e0df04dd46af45641 | [
"MIT"
] | null | null | null | complex/complex/logger.py | jasonamyers/pynash-click | 512e9712dc1de80e76a6815e0df04dd46af45641 | [
"MIT"
] | null | null | null | import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
file_log_handler = logging.FileHandler('combinator-cli.log')
logger.addHandler(file_log_handler)
stderr_log_handler = logging.StreamHandler()
logger.addHandler(stderr_log_handler)
format_string = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
formatter = logging.Formatter(format_string)
file_log_handler.setFormatter(formatter)
stderr_log_handler.setFormatter(formatter)
| 29.1875 | 70 | 0.815846 | import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
file_log_handler = logging.FileHandler('combinator-cli.log')
logger.addHandler(file_log_handler)
stderr_log_handler = logging.StreamHandler()
logger.addHandler(stderr_log_handler)
format_string = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
formatter = logging.Formatter(format_string)
file_log_handler.setFormatter(formatter)
stderr_log_handler.setFormatter(formatter)
| true | true |
f72f07649189725423a37d1b780363c21568ce47 | 1,124 | py | Python | model-optimizer/extensions/front/mxnet/rnn_param_concat.py | calvinfeng/openvino | 11f591c16852637506b1b40d083b450e56d0c8ac | [
"Apache-2.0"
] | null | null | null | model-optimizer/extensions/front/mxnet/rnn_param_concat.py | calvinfeng/openvino | 11f591c16852637506b1b40d083b450e56d0c8ac | [
"Apache-2.0"
] | 19 | 2021-03-26T08:11:00.000Z | 2022-02-21T13:06:26.000Z | model-optimizer/extensions/front/mxnet/rnn_param_concat.py | calvinfeng/openvino | 11f591c16852637506b1b40d083b450e56d0c8ac | [
"Apache-2.0"
] | 1 | 2021-07-28T17:30:46.000Z | 2021-07-28T17:30:46.000Z | """
Copyright (C) 2018-2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from mo.front.extractor import FrontExtractorOp
from mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs
from mo.ops.concat import Concat
class RNNParamConcatFrontExtractor(FrontExtractorOp):
op = '_rnn_param_concat'
enabled = True
@classmethod
def extract(cls, node):
attrs = get_mxnet_layer_attrs(node.symbol_dict)
data = {
'axis': attrs.int("dim", 1),
}
# update the attributes of the node
Concat.update_node_stat(node, data)
return cls.enabled
| 31.222222 | 73 | 0.728648 |
from mo.front.extractor import FrontExtractorOp
from mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs
from mo.ops.concat import Concat
class RNNParamConcatFrontExtractor(FrontExtractorOp):
op = '_rnn_param_concat'
enabled = True
@classmethod
def extract(cls, node):
attrs = get_mxnet_layer_attrs(node.symbol_dict)
data = {
'axis': attrs.int("dim", 1),
}
Concat.update_node_stat(node, data)
return cls.enabled
| true | true |
f72f0880bd5a9c11966123d872540d2c0220fd79 | 2,536 | py | Python | scanapi/evaluators/string_evaluator.py | dubirajara/scanapi | b0c7b40a48a4d60871c0b3cf9c959d0155985180 | [
"MIT"
] | 1 | 2020-06-02T18:08:08.000Z | 2020-06-02T18:08:08.000Z | scanapi/evaluators/string_evaluator.py | dubirajara/scanapi | b0c7b40a48a4d60871c0b3cf9c959d0155985180 | [
"MIT"
] | null | null | null | scanapi/evaluators/string_evaluator.py | dubirajara/scanapi | b0c7b40a48a4d60871c0b3cf9c959d0155985180 | [
"MIT"
] | null | null | null | import logging
import os
import re
import sys
from scanapi.errors import BadConfigurationError, InvalidPythonCodeError
from scanapi.evaluators.code_evaluator import CodeEvaluator
logger = logging.getLogger(__name__)
variable_pattern = re.compile(
r"(?P<something_before>\w*)(?P<start>\${)(?P<variable>\w*)(?P<end>})(?P<something_after>\w*)"
) # ${<variable>}
class StringEvaluator:
def __init__(self, spec_evaluator):
self.spec_evaluator = spec_evaluator
self.api_tree = spec_evaluator.api_tree
self.code_evaluator = CodeEvaluator(self)
def evaluate(self, sequence):
try:
sequence = self.evaluate_env_var(sequence)
except BadConfigurationError as e:
logger.error(e)
sys.exit()
sequence = self.evaluate_custom_var(sequence)
if not self.api_tree.responses:
return sequence
try:
return self.code_evaluator.evaluate(sequence)
except InvalidPythonCodeError as e:
logger.error(e)
sys.exit()
def evaluate_env_var(self, sequence):
matches = variable_pattern.finditer(sequence)
if not matches:
return sequence
for match in matches:
variable_name = match.group("variable")
if any(letter.islower() for letter in variable_name):
continue
try:
variable_value = os.environ[variable_name]
except KeyError as e:
raise BadConfigurationError(e)
sequence = self.replace_var_with_value(
sequence, match.group(), variable_value
)
return sequence
def evaluate_custom_var(self, sequence):
matches = variable_pattern.finditer(sequence)
if not matches:
return sequence
for match in matches:
variable_name = match.group("variable")
if variable_name.isupper():
continue
if not self.api_tree.custom_vars.get(variable_name):
continue
variable_value = self.spec_evaluator.evaluate(
self.api_tree.custom_vars[variable_name]
)
sequence = self.replace_var_with_value(
sequence, match.group(), variable_value
)
return sequence
def replace_var_with_value(self, sequence, variable, variable_value):
variable = re.escape(variable)
return re.sub(variable, variable_value, sequence)
| 28.494382 | 97 | 0.621451 | import logging
import os
import re
import sys
from scanapi.errors import BadConfigurationError, InvalidPythonCodeError
from scanapi.evaluators.code_evaluator import CodeEvaluator
logger = logging.getLogger(__name__)
variable_pattern = re.compile(
r"(?P<something_before>\w*)(?P<start>\${)(?P<variable>\w*)(?P<end>})(?P<something_after>\w*)"
)
class StringEvaluator:
def __init__(self, spec_evaluator):
self.spec_evaluator = spec_evaluator
self.api_tree = spec_evaluator.api_tree
self.code_evaluator = CodeEvaluator(self)
def evaluate(self, sequence):
try:
sequence = self.evaluate_env_var(sequence)
except BadConfigurationError as e:
logger.error(e)
sys.exit()
sequence = self.evaluate_custom_var(sequence)
if not self.api_tree.responses:
return sequence
try:
return self.code_evaluator.evaluate(sequence)
except InvalidPythonCodeError as e:
logger.error(e)
sys.exit()
def evaluate_env_var(self, sequence):
matches = variable_pattern.finditer(sequence)
if not matches:
return sequence
for match in matches:
variable_name = match.group("variable")
if any(letter.islower() for letter in variable_name):
continue
try:
variable_value = os.environ[variable_name]
except KeyError as e:
raise BadConfigurationError(e)
sequence = self.replace_var_with_value(
sequence, match.group(), variable_value
)
return sequence
def evaluate_custom_var(self, sequence):
matches = variable_pattern.finditer(sequence)
if not matches:
return sequence
for match in matches:
variable_name = match.group("variable")
if variable_name.isupper():
continue
if not self.api_tree.custom_vars.get(variable_name):
continue
variable_value = self.spec_evaluator.evaluate(
self.api_tree.custom_vars[variable_name]
)
sequence = self.replace_var_with_value(
sequence, match.group(), variable_value
)
return sequence
def replace_var_with_value(self, sequence, variable, variable_value):
variable = re.escape(variable)
return re.sub(variable, variable_value, sequence)
| true | true |
f72f0a5368a77bd168688ea65e43ba66486e53c4 | 902 | py | Python | church/migrations/0017_linkedchurch.py | khanhpn/florida | 5e83d0561b9f41ff79383a6a2f0a84d6c8459ef0 | [
"Apache-2.0"
] | 1 | 2021-01-22T02:52:33.000Z | 2021-01-22T02:52:33.000Z | church/migrations/0017_linkedchurch.py | khanhpn/florida | 5e83d0561b9f41ff79383a6a2f0a84d6c8459ef0 | [
"Apache-2.0"
] | null | null | null | church/migrations/0017_linkedchurch.py | khanhpn/florida | 5e83d0561b9f41ff79383a6a2f0a84d6c8459ef0 | [
"Apache-2.0"
] | null | null | null | # Generated by Django 3.2.5 on 2021-08-01 06:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('church', '0016_masstime'),
]
operations = [
migrations.CreateModel(
name='LinkedChurch',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.TextField(max_length=900000, null=True)),
('logo', models.FileField(upload_to='uploads/%Y/%m/%d/')),
('church_url', models.TextField(max_length=90000, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
options={
'db_table': 'linked_church',
},
),
]
| 32.214286 | 114 | 0.559867 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('church', '0016_masstime'),
]
operations = [
migrations.CreateModel(
name='LinkedChurch',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.TextField(max_length=900000, null=True)),
('logo', models.FileField(upload_to='uploads/%Y/%m/%d/')),
('church_url', models.TextField(max_length=90000, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
options={
'db_table': 'linked_church',
},
),
]
| true | true |
f72f0bebfae6ba10ce11191ee930be3d4ec64296 | 4,692 | py | Python | app/model/SimpleSimulator.py | OuissalTAIM/jenkins | 7ea5bcdeb6c0bb3cc14c2826a68e4f521de163c1 | [
"BSD-1-Clause"
] | null | null | null | app/model/SimpleSimulator.py | OuissalTAIM/jenkins | 7ea5bcdeb6c0bb3cc14c2826a68e4f521de163c1 | [
"BSD-1-Clause"
] | 6 | 2021-02-02T22:52:41.000Z | 2022-03-12T00:37:30.000Z | app/model/SimpleSimulator.py | OuissalTAIM/jenkins | 7ea5bcdeb6c0bb3cc14c2826a68e4f521de163c1 | [
"BSD-1-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
from app.graph.Graph import *
from app.data.Client import Driver
from app.config.env import MONIKER_SEPARATOR
from app.entity.Transport import Transport
from app.samples.graph_sample import SimpleEntity
class SimpleSimulator:
def __init__(self, graph):
"""
Constructor
:param graph: input graph
"""
self.graph = graph
def build_graph(self):
"""
Get data from data service and build graph
:return: None
"""
# get locations
locations = Driver.get_data("simplelocation")
unit_locations = {}
for location in locations:
for key in location:
if key not in unit_locations:
unit_locations[key] = []
unit_locations[key].append(location[key])
# get infrastructure
infrastructure = Driver.get_data("infrastructure")
# get connections
connections = Driver.get_data("connection")
upstream_to_downstream_connection = {}
for connection in connections:
#TODO: could the headers "From" and "To" be dynamic?
# at least the unit in "Distance[km]" should be
upstream_to_downstream_connection[(connection["From"],connection["To"])] = connection["Distance[km]"]
# build graph
nodes = {}
for unit_location in unit_locations:
if unit_location == "_id":
continue
for location in unit_locations[unit_location]:
if location is None:
continue
key = unit_location + MONIKER_SEPARATOR + location
entity = SimpleEntity(key, 1, 1, 1)
node = Node(entity)
nodes[key] = node
# upstream to downstream
network = Network("CenterAxe")
for node_key in nodes:
node = nodes[node_key]
has_downstream = False
for up_down in upstream_to_downstream_connection:
if node_key != up_down[0]:
continue
from_to = up_down[1].split(MONIKER_SEPARATOR)
if from_to[1] not in unit_locations[from_to[0]]:
continue
distance = upstream_to_downstream_connection[up_down]
for infra in infrastructure:
transport = Transport(infra, distance)
node.add_downstream(transport, up_down[1])
network.add_node(nodes[up_down[1]])
has_downstream = True
if has_downstream:
network.add_node(node)
self.graph = Graph(network)
def build_all_scenarios(self, start, end):
"""
Brute force simulation
:param start: list of starting points
:param end: list of ending points
:return: list
"""
paths = []
for s in start:
for e in end:
se_paths = self.graph.paths(s, e)
if len(se_paths) > 0:
paths.extend(se_paths)
len_paths = len(paths)
masks = ['{{0:0{0}b}}'.format(len_paths).format(n) for n in range(0, 2 ** len_paths)]
scenarios = []
for mask in masks:
scenario = []
scenario_names = []
for i in range(0, len_paths):
if mask[i] == '1':
scenario.append(paths[i])
print(scenario)
scenarios.append(scenario)
return scenarios
def compute(self):
"""
TODO: iterate over all scenarios and compute cost-pv
and other metrics
:return: dictionary
"""
scenarios = self.build_all_scenarios()
for scenario in scenarios:
self.compute(scenario)
return {}
def simulate(self, scenario, plot=False, function="cost_pv"):
"""
Apply function on scenario
:param scenario: list[[string]]
:param plot: boolean, choose to plot the graph or not
:return: Result object
"""
scenario_result = []
for path in scenario:
result = []
next_node = None
path.reverse()
path_to_nodes = [self.graph.get_node(name) for name in path]
for node in path_to_nodes:
result.append(getattr(node, function)(next_node))
next_node = node
path.reverse()
result.reverse()
print("%s | %s" % (path, result))
scenario_result.append(result)
if plot:
self.graph.plot()
return scenario_result
| 34 | 113 | 0.547528 |
from app.graph.Graph import *
from app.data.Client import Driver
from app.config.env import MONIKER_SEPARATOR
from app.entity.Transport import Transport
from app.samples.graph_sample import SimpleEntity
class SimpleSimulator:
def __init__(self, graph):
self.graph = graph
def build_graph(self):
locations = Driver.get_data("simplelocation")
unit_locations = {}
for location in locations:
for key in location:
if key not in unit_locations:
unit_locations[key] = []
unit_locations[key].append(location[key])
infrastructure = Driver.get_data("infrastructure")
connections = Driver.get_data("connection")
upstream_to_downstream_connection = {}
for connection in connections:
upstream_to_downstream_connection[(connection["From"],connection["To"])] = connection["Distance[km]"]
nodes = {}
for unit_location in unit_locations:
if unit_location == "_id":
continue
for location in unit_locations[unit_location]:
if location is None:
continue
key = unit_location + MONIKER_SEPARATOR + location
entity = SimpleEntity(key, 1, 1, 1)
node = Node(entity)
nodes[key] = node
network = Network("CenterAxe")
for node_key in nodes:
node = nodes[node_key]
has_downstream = False
for up_down in upstream_to_downstream_connection:
if node_key != up_down[0]:
continue
from_to = up_down[1].split(MONIKER_SEPARATOR)
if from_to[1] not in unit_locations[from_to[0]]:
continue
distance = upstream_to_downstream_connection[up_down]
for infra in infrastructure:
transport = Transport(infra, distance)
node.add_downstream(transport, up_down[1])
network.add_node(nodes[up_down[1]])
has_downstream = True
if has_downstream:
network.add_node(node)
self.graph = Graph(network)
def build_all_scenarios(self, start, end):
paths = []
for s in start:
for e in end:
se_paths = self.graph.paths(s, e)
if len(se_paths) > 0:
paths.extend(se_paths)
len_paths = len(paths)
masks = ['{{0:0{0}b}}'.format(len_paths).format(n) for n in range(0, 2 ** len_paths)]
scenarios = []
for mask in masks:
scenario = []
scenario_names = []
for i in range(0, len_paths):
if mask[i] == '1':
scenario.append(paths[i])
print(scenario)
scenarios.append(scenario)
return scenarios
def compute(self):
scenarios = self.build_all_scenarios()
for scenario in scenarios:
self.compute(scenario)
return {}
def simulate(self, scenario, plot=False, function="cost_pv"):
scenario_result = []
for path in scenario:
result = []
next_node = None
path.reverse()
path_to_nodes = [self.graph.get_node(name) for name in path]
for node in path_to_nodes:
result.append(getattr(node, function)(next_node))
next_node = node
path.reverse()
result.reverse()
print("%s | %s" % (path, result))
scenario_result.append(result)
if plot:
self.graph.plot()
return scenario_result
| true | true |
f72f0bee0a0d6143e7a6c4be603b00b01323a74d | 1,459 | py | Python | models/vgg16.py | lizhipengTouch/CSA-inpainting | 50602607ddc9153af5bfe627e355b0466fc4944f | [
"CC-BY-4.0"
] | null | null | null | models/vgg16.py | lizhipengTouch/CSA-inpainting | 50602607ddc9153af5bfe627e355b0466fc4944f | [
"CC-BY-4.0"
] | null | null | null | models/vgg16.py | lizhipengTouch/CSA-inpainting | 50602607ddc9153af5bfe627e355b0466fc4944f | [
"CC-BY-4.0"
] | null | null | null | import torch
import torchvision
from torchvision import models
from collections import namedtuple
class Vgg16(torch.nn.Module):
def __init__(self, requires_grad=False):
super(Vgg16, self).__init__()
vgg_pretrained_features = models.vgg16(pretrained=True).features # 获取预训练vgg网络层
self.slice1 = torch.nn.Sequential()
self.slice2 = torch.nn.Sequential()
self.slice3 = torch.nn.Sequential()
self.slice4 = torch.nn.Sequential()
for x in range(5):
self.slice1.add_module(str(x), vgg_pretrained_features[x])
for x in range(5, 10):
self.slice2.add_module(str(x), vgg_pretrained_features[x])
for x in range(10, 17):
self.slice3.add_module(str(x), vgg_pretrained_features[x])
for x in range(17, 23):
self.slice4.add_module(str(x), vgg_pretrained_features[x])
if not requires_grad:
for param in self.parameters():
param.requires_grad = False
def forward(self, X):
h = self.slice1(X)
h_relu1_2 = h
h = self.slice2(h)
h_relu2_2 = h
h = self.slice3(h)
h_relu3_3 = h
h = self.slice4(h)
h_relu4_3 = h
vgg_outputs = namedtuple("VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3'])
# 定义一个namedtuple类型数据,并包含列表中的属性。
out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3)
return out # 得到经过不同层的特征值 | 38.394737 | 92 | 0.6244 | import torch
import torchvision
from torchvision import models
from collections import namedtuple
class Vgg16(torch.nn.Module):
def __init__(self, requires_grad=False):
super(Vgg16, self).__init__()
vgg_pretrained_features = models.vgg16(pretrained=True).features
self.slice1 = torch.nn.Sequential()
self.slice2 = torch.nn.Sequential()
self.slice3 = torch.nn.Sequential()
self.slice4 = torch.nn.Sequential()
for x in range(5):
self.slice1.add_module(str(x), vgg_pretrained_features[x])
for x in range(5, 10):
self.slice2.add_module(str(x), vgg_pretrained_features[x])
for x in range(10, 17):
self.slice3.add_module(str(x), vgg_pretrained_features[x])
for x in range(17, 23):
self.slice4.add_module(str(x), vgg_pretrained_features[x])
if not requires_grad:
for param in self.parameters():
param.requires_grad = False
def forward(self, X):
h = self.slice1(X)
h_relu1_2 = h
h = self.slice2(h)
h_relu2_2 = h
h = self.slice3(h)
h_relu3_3 = h
h = self.slice4(h)
h_relu4_3 = h
vgg_outputs = namedtuple("VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3'])
out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3)
return out | true | true |
f72f0df111c27c3d72be292658ad3543f741792e | 6,525 | py | Python | sdk/python/kulado_azure/network/express_route_circuit_peering.py | kulado/kulado-azure | f3a408fa0405fe6ae93e0049b2ae0f0e266f1cf6 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/kulado_azure/network/express_route_circuit_peering.py | kulado/kulado-azure | f3a408fa0405fe6ae93e0049b2ae0f0e266f1cf6 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/kulado_azure/network/express_route_circuit_peering.py | kulado/kulado-azure | f3a408fa0405fe6ae93e0049b2ae0f0e266f1cf6 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Kulado Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import kulado
import kulado.runtime
from .. import utilities, tables
class ExpressRouteCircuitPeering(kulado.CustomResource):
azure_asn: kulado.Output[float]
"""
The ASN used by Azure.
"""
express_route_circuit_name: kulado.Output[str]
"""
The name of the ExpressRoute Circuit in which to create the Peering.
"""
microsoft_peering_config: kulado.Output[dict]
"""
A `microsoft_peering_config` block as defined below. Required when `peering_type` is set to `MicrosoftPeering`.
"""
peer_asn: kulado.Output[float]
"""
The Either a 16-bit or a 32-bit ASN. Can either be public or private..
"""
peering_type: kulado.Output[str]
"""
The type of the ExpressRoute Circuit Peering. Acceptable values include `AzurePrivatePeering`, `AzurePublicPeering` and `MicrosoftPeering`. Changing this forces a new resource to be created.
"""
primary_azure_port: kulado.Output[str]
"""
The Primary Port used by Azure for this Peering.
"""
primary_peer_address_prefix: kulado.Output[str]
"""
A `/30` subnet for the primary link.
"""
resource_group_name: kulado.Output[str]
"""
The name of the resource group in which to
create the Express Route Circuit Peering. Changing this forces a new resource to be created.
"""
secondary_azure_port: kulado.Output[str]
"""
The Secondary Port used by Azure for this Peering.
"""
secondary_peer_address_prefix: kulado.Output[str]
"""
A `/30` subnet for the secondary link.
"""
shared_key: kulado.Output[str]
"""
The shared key. Can be a maximum of 25 characters.
"""
vlan_id: kulado.Output[float]
"""
A valid VLAN ID to establish this peering on.
"""
def __init__(__self__, resource_name, opts=None, express_route_circuit_name=None, microsoft_peering_config=None, peer_asn=None, peering_type=None, primary_peer_address_prefix=None, resource_group_name=None, secondary_peer_address_prefix=None, shared_key=None, vlan_id=None, __name__=None, __opts__=None):
"""
Manages an ExpressRoute Circuit Peering.
:param str resource_name: The name of the resource.
:param kulado.ResourceOptions opts: Options for the resource.
:param kulado.Input[str] express_route_circuit_name: The name of the ExpressRoute Circuit in which to create the Peering.
:param kulado.Input[dict] microsoft_peering_config: A `microsoft_peering_config` block as defined below. Required when `peering_type` is set to `MicrosoftPeering`.
:param kulado.Input[float] peer_asn: The Either a 16-bit or a 32-bit ASN. Can either be public or private..
:param kulado.Input[str] peering_type: The type of the ExpressRoute Circuit Peering. Acceptable values include `AzurePrivatePeering`, `AzurePublicPeering` and `MicrosoftPeering`. Changing this forces a new resource to be created.
:param kulado.Input[str] primary_peer_address_prefix: A `/30` subnet for the primary link.
:param kulado.Input[str] resource_group_name: The name of the resource group in which to
create the Express Route Circuit Peering. Changing this forces a new resource to be created.
:param kulado.Input[str] secondary_peer_address_prefix: A `/30` subnet for the secondary link.
:param kulado.Input[str] shared_key: The shared key. Can be a maximum of 25 characters.
:param kulado.Input[float] vlan_id: A valid VLAN ID to establish this peering on.
> This content is derived from https://github.com/terraform-providers/terraform-provider-azurerm/blob/master/website/docs/r/express_route_circuit_peering.html.markdown.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if not resource_name:
raise TypeError('Missing resource name argument (for URN creation)')
if not isinstance(resource_name, str):
raise TypeError('Expected resource name to be a string')
if opts and not isinstance(opts, kulado.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
__props__ = dict()
if express_route_circuit_name is None:
raise TypeError("Missing required property 'express_route_circuit_name'")
__props__['express_route_circuit_name'] = express_route_circuit_name
__props__['microsoft_peering_config'] = microsoft_peering_config
__props__['peer_asn'] = peer_asn
if peering_type is None:
raise TypeError("Missing required property 'peering_type'")
__props__['peering_type'] = peering_type
if primary_peer_address_prefix is None:
raise TypeError("Missing required property 'primary_peer_address_prefix'")
__props__['primary_peer_address_prefix'] = primary_peer_address_prefix
if resource_group_name is None:
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
if secondary_peer_address_prefix is None:
raise TypeError("Missing required property 'secondary_peer_address_prefix'")
__props__['secondary_peer_address_prefix'] = secondary_peer_address_prefix
__props__['shared_key'] = shared_key
if vlan_id is None:
raise TypeError("Missing required property 'vlan_id'")
__props__['vlan_id'] = vlan_id
__props__['azure_asn'] = None
__props__['primary_azure_port'] = None
__props__['secondary_azure_port'] = None
super(ExpressRouteCircuitPeering, __self__).__init__(
'azure:network/expressRouteCircuitPeering:ExpressRouteCircuitPeering',
resource_name,
__props__,
opts)
def translate_output_property(self, prop):
return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| 45.950704 | 308 | 0.70636 |
import json
import warnings
import kulado
import kulado.runtime
from .. import utilities, tables
class ExpressRouteCircuitPeering(kulado.CustomResource):
azure_asn: kulado.Output[float]
express_route_circuit_name: kulado.Output[str]
microsoft_peering_config: kulado.Output[dict]
peer_asn: kulado.Output[float]
peering_type: kulado.Output[str]
primary_azure_port: kulado.Output[str]
primary_peer_address_prefix: kulado.Output[str]
resource_group_name: kulado.Output[str]
secondary_azure_port: kulado.Output[str]
secondary_peer_address_prefix: kulado.Output[str]
shared_key: kulado.Output[str]
vlan_id: kulado.Output[float]
def __init__(__self__, resource_name, opts=None, express_route_circuit_name=None, microsoft_peering_config=None, peer_asn=None, peering_type=None, primary_peer_address_prefix=None, resource_group_name=None, secondary_peer_address_prefix=None, shared_key=None, vlan_id=None, __name__=None, __opts__=None):
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if not resource_name:
raise TypeError('Missing resource name argument (for URN creation)')
if not isinstance(resource_name, str):
raise TypeError('Expected resource name to be a string')
if opts and not isinstance(opts, kulado.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
__props__ = dict()
if express_route_circuit_name is None:
raise TypeError("Missing required property 'express_route_circuit_name'")
__props__['express_route_circuit_name'] = express_route_circuit_name
__props__['microsoft_peering_config'] = microsoft_peering_config
__props__['peer_asn'] = peer_asn
if peering_type is None:
raise TypeError("Missing required property 'peering_type'")
__props__['peering_type'] = peering_type
if primary_peer_address_prefix is None:
raise TypeError("Missing required property 'primary_peer_address_prefix'")
__props__['primary_peer_address_prefix'] = primary_peer_address_prefix
if resource_group_name is None:
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
if secondary_peer_address_prefix is None:
raise TypeError("Missing required property 'secondary_peer_address_prefix'")
__props__['secondary_peer_address_prefix'] = secondary_peer_address_prefix
__props__['shared_key'] = shared_key
if vlan_id is None:
raise TypeError("Missing required property 'vlan_id'")
__props__['vlan_id'] = vlan_id
__props__['azure_asn'] = None
__props__['primary_azure_port'] = None
__props__['secondary_azure_port'] = None
super(ExpressRouteCircuitPeering, __self__).__init__(
'azure:network/expressRouteCircuitPeering:ExpressRouteCircuitPeering',
resource_name,
__props__,
opts)
def translate_output_property(self, prop):
return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| true | true |
f72f0e3e3ffbf41a6e99a86e70f0c5f90ed14feb | 2,479 | py | Python | attachment_large_object/ir_attachment.py | ShaheenHossain/itpp-labs-misc-addons13 | bf62dc5bc1abdc18d78e9560a286babbe1d0e082 | [
"MIT"
] | null | null | null | attachment_large_object/ir_attachment.py | ShaheenHossain/itpp-labs-misc-addons13 | bf62dc5bc1abdc18d78e9560a286babbe1d0e082 | [
"MIT"
] | null | null | null | attachment_large_object/ir_attachment.py | ShaheenHossain/itpp-labs-misc-addons13 | bf62dc5bc1abdc18d78e9560a286babbe1d0e082 | [
"MIT"
] | 3 | 2020-08-25T01:57:59.000Z | 2021-09-11T15:38:02.000Z | # -*- coding: utf-8 -*-
import logging
import psycopg2
from odoo import api, models
logger = logging.getLogger(__name__)
LARGE_OBJECT_LOCATION = "postgresql:lobject"
class IrAttachment(models.Model):
"""Provide storage as PostgreSQL large objects of attachements with filestore location ``postgresql:lobject``.
Works by overriding the storage handling methods of ``ir.attachment``, as intended by the
default implementation. The overrides call :funct:`super`, so that this is transparent
for other locations.
"""
_name = "ir.attachment"
_inherit = "ir.attachment"
@api.model
def lobject(self, cr, *args):
return cr._cnx.lobject(*args)
@api.model
def _file_write(self, value, checksum):
"""Write the content in a newly created large object.
:param value: base64 encoded payload
:returns str: object id (will be considered the file storage name)
"""
location = self._storage()
if location != LARGE_OBJECT_LOCATION:
return super(IrAttachment, self)._file_write(value, checksum)
lobj = self.lobject(self.env.cr, 0, "wb") # oid=0 means creation
lobj.write(value.decode("base64"))
oid = lobj.oid
return str(oid)
def _file_delete(self, fname):
filestore = False
try:
oid = long(fname)
except Exception:
filestore = True
if not filestore:
try:
return self.lobject(self.env.cr, oid, "rb").unlink()
except (psycopg2.OperationalError, ValueError):
filestore = True
return super(IrAttachment, self)._file_delete(fname)
def _lobject_read(self, fname, bin_size):
"""Read the large object, base64 encoded.
:param fname: file storage name, must be the oid as a string.
"""
lobj = self.lobject(self.env.cr, long(fname), "rb")
if bin_size:
return lobj.seek(0, 2)
return lobj.read().encode(
"base64"
) # GR TODO it must be possible to read-encode in chunks
@api.depends("store_fname", "db_datas")
def _compute_datas(self):
bin_size = self._context.get("bin_size")
for attach in self:
try:
attach.datas = self._lobject_read(attach.store_fname, bin_size)
except (psycopg2.OperationalError, ValueError):
super(IrAttachment, attach)._compute_datas()
| 31.379747 | 114 | 0.624445 |
import logging
import psycopg2
from odoo import api, models
logger = logging.getLogger(__name__)
LARGE_OBJECT_LOCATION = "postgresql:lobject"
class IrAttachment(models.Model):
_name = "ir.attachment"
_inherit = "ir.attachment"
@api.model
def lobject(self, cr, *args):
return cr._cnx.lobject(*args)
@api.model
def _file_write(self, value, checksum):
location = self._storage()
if location != LARGE_OBJECT_LOCATION:
return super(IrAttachment, self)._file_write(value, checksum)
lobj = self.lobject(self.env.cr, 0, "wb")
lobj.write(value.decode("base64"))
oid = lobj.oid
return str(oid)
def _file_delete(self, fname):
filestore = False
try:
oid = long(fname)
except Exception:
filestore = True
if not filestore:
try:
return self.lobject(self.env.cr, oid, "rb").unlink()
except (psycopg2.OperationalError, ValueError):
filestore = True
return super(IrAttachment, self)._file_delete(fname)
def _lobject_read(self, fname, bin_size):
lobj = self.lobject(self.env.cr, long(fname), "rb")
if bin_size:
return lobj.seek(0, 2)
return lobj.read().encode(
"base64"
)
@api.depends("store_fname", "db_datas")
def _compute_datas(self):
bin_size = self._context.get("bin_size")
for attach in self:
try:
attach.datas = self._lobject_read(attach.store_fname, bin_size)
except (psycopg2.OperationalError, ValueError):
super(IrAttachment, attach)._compute_datas()
| true | true |
f72f1077a32379129769997eb35ec1972c898c1c | 102 | py | Python | dircolors/pyls/__init__.py | mic-e/pydircolors | 62096e73ed065d015adde3f9e55c38e10a49dc3c | [
"Apache-2.0"
] | 3 | 2020-02-17T20:02:03.000Z | 2020-09-05T02:17:47.000Z | dircolors/pyls/__init__.py | mic-e/pydircolors | 62096e73ed065d015adde3f9e55c38e10a49dc3c | [
"Apache-2.0"
] | null | null | null | dircolors/pyls/__init__.py | mic-e/pydircolors | 62096e73ed065d015adde3f9e55c38e10a49dc3c | [
"Apache-2.0"
] | 2 | 2020-02-18T01:11:20.000Z | 2020-09-05T02:17:51.000Z | # dircolors.pyls package
""" pyls - a simple implementation of `ls` used to test python-dircolors """
| 34 | 76 | 0.72549 | true | true | |
f72f11d65f3800ed3177636dba116a8e2edb427c | 2,402 | py | Python | test/test_tcti.py | fer9898/tpm2-pytss | a2bd7292411511a9c6da3c2553c7af01470e63ef | [
"BSD-2-Clause"
] | null | null | null | test/test_tcti.py | fer9898/tpm2-pytss | a2bd7292411511a9c6da3c2553c7af01470e63ef | [
"BSD-2-Clause"
] | null | null | null | test/test_tcti.py | fer9898/tpm2-pytss | a2bd7292411511a9c6da3c2553c7af01470e63ef | [
"BSD-2-Clause"
] | null | null | null | #!/usr/bin/python3 -u
# SPDX-License-Identifier: BSD-2
import unittest
from tpm2_pytss import *
from .TSS2_BaseTest import TSS2_EsapiTest
class TestTCTI(TSS2_EsapiTest):
def test_init(self):
self.assertEqual(self.tcti.version, 2)
self.assertGreater(self.tcti.magic, 0)
v1ctx = ffi.cast("TSS2_TCTI_CONTEXT_COMMON_V1 *", self.tcti._ctx)
v1ctx.version = 1
tcti = TCTI(self.tcti._ctx)
self.assertEqual(tcti.version, 1)
self.assertEqual(tcti._v2, None)
def test_transmit_receive(self):
startup = b"\x80\x01\x00\x00\x00\x0C\x00\x00\x01\x44\x00\x00"
self.tcti.transmit(startup)
resp = self.tcti.receive()
self.assertEqual(resp, b"\x80\x01\x00\x00\x00\n\x00\x00\x01\x00")
def test_finalize(self):
tcti = TCTI(self.tcti._ctx)
tcti.finalize()
def test_cancel(self):
if getattr(self.tcti, "name", "") == "swtpm":
self.skipTest("cancel supported by swtpm")
startup = b"\x80\x01\x00\x00\x00\x0C\x00\x00\x01\x44\x00\x00"
self.tcti.transmit(startup)
self.tcti.cancel()
def test_get_poll_handles(self):
tcti_name = getattr(self.tcti, "name", "")
try:
handles = self.tcti.get_poll_handles()
except TSS2_Exception as e:
if e.rc != lib.TSS2_TCTI_RC_NOT_IMPLEMENTED:
raise e
else:
self.skipTest(f"get_poll_handles not supported by {tcti_name}")
def test_set_locality(self):
self.tcti.set_locality(TPMA_LOCALITY.TWO)
def test_make_sticky(self):
tcti_name = getattr(self.tcti, "name", "")
if tcti_name in ("swtpm", "mssim"):
self.skipTest(f"make_sticky not supported by {tcti_name}")
raise Exception(self.tcti.name)
self.tcti.make_sticky(0, 0)
tcti._v2 = None
with self.assertRaises(RuntimeError) as e:
self.tcti.make_sticky(0, 0)
self.assertEqual(str(e.exception), "unsupported by TCTI API version")
def test_tctildr(self):
self.assertIsInstance(self.tcti.name, str)
self.assertIsInstance(self.tcti.conf, str)
with self.assertRaises(TypeError):
TCTILdr(name=None, conf=1234)
with self.assertRaises(TypeError):
TCTILdr(name=1234, conf=None)
if __name__ == "__main__":
unittest.main()
| 30.405063 | 79 | 0.628226 |
import unittest
from tpm2_pytss import *
from .TSS2_BaseTest import TSS2_EsapiTest
class TestTCTI(TSS2_EsapiTest):
def test_init(self):
self.assertEqual(self.tcti.version, 2)
self.assertGreater(self.tcti.magic, 0)
v1ctx = ffi.cast("TSS2_TCTI_CONTEXT_COMMON_V1 *", self.tcti._ctx)
v1ctx.version = 1
tcti = TCTI(self.tcti._ctx)
self.assertEqual(tcti.version, 1)
self.assertEqual(tcti._v2, None)
def test_transmit_receive(self):
startup = b"\x80\x01\x00\x00\x00\x0C\x00\x00\x01\x44\x00\x00"
self.tcti.transmit(startup)
resp = self.tcti.receive()
self.assertEqual(resp, b"\x80\x01\x00\x00\x00\n\x00\x00\x01\x00")
def test_finalize(self):
tcti = TCTI(self.tcti._ctx)
tcti.finalize()
def test_cancel(self):
if getattr(self.tcti, "name", "") == "swtpm":
self.skipTest("cancel supported by swtpm")
startup = b"\x80\x01\x00\x00\x00\x0C\x00\x00\x01\x44\x00\x00"
self.tcti.transmit(startup)
self.tcti.cancel()
def test_get_poll_handles(self):
tcti_name = getattr(self.tcti, "name", "")
try:
handles = self.tcti.get_poll_handles()
except TSS2_Exception as e:
if e.rc != lib.TSS2_TCTI_RC_NOT_IMPLEMENTED:
raise e
else:
self.skipTest(f"get_poll_handles not supported by {tcti_name}")
def test_set_locality(self):
self.tcti.set_locality(TPMA_LOCALITY.TWO)
def test_make_sticky(self):
tcti_name = getattr(self.tcti, "name", "")
if tcti_name in ("swtpm", "mssim"):
self.skipTest(f"make_sticky not supported by {tcti_name}")
raise Exception(self.tcti.name)
self.tcti.make_sticky(0, 0)
tcti._v2 = None
with self.assertRaises(RuntimeError) as e:
self.tcti.make_sticky(0, 0)
self.assertEqual(str(e.exception), "unsupported by TCTI API version")
def test_tctildr(self):
self.assertIsInstance(self.tcti.name, str)
self.assertIsInstance(self.tcti.conf, str)
with self.assertRaises(TypeError):
TCTILdr(name=None, conf=1234)
with self.assertRaises(TypeError):
TCTILdr(name=1234, conf=None)
if __name__ == "__main__":
unittest.main()
| true | true |
f72f13692aafad6149b0efd13c89c38ea0616f87 | 6,325 | py | Python | backend/users/api/views.py | tyrozz/django-next-backend | 1e06d8daa079548d0d4c79474f035041d44d5ead | [
"MIT"
] | 1 | 2022-02-24T17:55:35.000Z | 2022-02-24T17:55:35.000Z | backend/users/api/views.py | tyrozz/django-next-backend | 1e06d8daa079548d0d4c79474f035041d44d5ead | [
"MIT"
] | null | null | null | backend/users/api/views.py | tyrozz/django-next-backend | 1e06d8daa079548d0d4c79474f035041d44d5ead | [
"MIT"
] | null | null | null | from allauth.account import app_settings as allauth_settings
from allauth.account.models import EmailAddress
from allauth.account.utils import complete_signup
from allauth.account.views import ConfirmEmailView
from django.contrib.auth import get_user_model
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.debug import sensitive_post_parameters
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.exceptions import MethodNotAllowed, ValidationError
from rest_framework.generics import CreateAPIView, GenericAPIView
from rest_framework.mixins import (
CreateModelMixin,
ListModelMixin,
RetrieveModelMixin,
UpdateModelMixin,
)
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from .serializers import (
CreateUserSerializer,
PasswordChangeSerializer,
PasswordResetConfirmSerializer,
RegisterSerializer,
ResendEmailVerificationSerializer,
UserPasswordResetSerializer,
UserSerializer,
VerifyEmailSerializer,
)
User = get_user_model()
sensitive_post_parameters_m = method_decorator(
sensitive_post_parameters(
"password",
"old_password",
"new_password1",
"new_password2",
),
)
class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
lookup_field = "username"
def get_queryset(self, *args, **kwargs):
return self.queryset.filter(id=self.request.user.id)
@action(detail=False, methods=["GET"])
def me(self, request):
serializer = UserSerializer(request.user, context={"request": request})
user_data = {"user": serializer.data}
return Response(status=status.HTTP_200_OK, data=user_data)
class UserCreateViewSet(CreateModelMixin, GenericViewSet):
queryset = User.objects.all()
serializer_class = CreateUserSerializer
permission_classes = [
AllowAny,
]
class PasswordResetView(GenericAPIView):
serializer_class = UserPasswordResetSerializer
permission_classes = (AllowAny,)
def post(self, request, *args, **kwargs):
# Create a serializer with request.data
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
# Return the success message with OK HTTP status
return Response(
{"detail": _("Password reset e-mail has been sent.")},
status=status.HTTP_200_OK,
)
class PasswordResetConfirmView(GenericAPIView):
serializer_class = PasswordResetConfirmSerializer
permission_classes = (AllowAny,)
@sensitive_post_parameters_m
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response({"detail": _("Password has been reset with the new password")})
class PasswordChangeView(GenericAPIView):
serializer_class = PasswordChangeSerializer
permission_classes = (IsAuthenticated,)
@sensitive_post_parameters_m
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response({"detail": _("New password has been saved")})
class VerifyEmailView(APIView, ConfirmEmailView):
permission_classes = (AllowAny,)
allowed_methods = ("POST", "OPTIONS", "HEAD")
def get_serializer(self, *args, **kwargs):
return VerifyEmailSerializer(*args, **kwargs)
def get(self, *args, **kwargs):
raise MethodNotAllowed("GET")
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.kwargs["key"] = serializer.validated_data["key"]
confirmation = self.get_object()
confirmation.confirm(self.request)
return Response({"detail": _("ok")}, status=status.HTTP_200_OK)
class ResendEmailVerificationView(CreateAPIView):
permission_classes = (AllowAny,)
serializer_class = ResendEmailVerificationSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
email = EmailAddress.objects.get(**serializer.validated_data)
if not email:
raise ValidationError("Account does not exist")
if email.verified:
raise ValidationError("Account is already verified")
email.send_confirmation()
return Response({"detail": _("ok")}, status=status.HTTP_200_OK)
class RegisterView(CreateAPIView):
serializer_class = RegisterSerializer
permission_classes = (AllowAny,)
@sensitive_post_parameters_m
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def get_response_data(self, user):
if (
allauth_settings.EMAIL_VERIFICATION
== allauth_settings.EmailVerificationMethod.MANDATORY
):
return {"detail": _("Verification e-mail sent.")}
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(
self.get_response_data(user),
status=status.HTTP_201_CREATED,
headers=headers,
)
def perform_create(self, serializer):
user = serializer.save(self.request)
complete_signup(
self.request._request,
user,
allauth_settings.EMAIL_VERIFICATION,
None,
)
return user
| 33.115183 | 88 | 0.707826 | from allauth.account import app_settings as allauth_settings
from allauth.account.models import EmailAddress
from allauth.account.utils import complete_signup
from allauth.account.views import ConfirmEmailView
from django.contrib.auth import get_user_model
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.debug import sensitive_post_parameters
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.exceptions import MethodNotAllowed, ValidationError
from rest_framework.generics import CreateAPIView, GenericAPIView
from rest_framework.mixins import (
CreateModelMixin,
ListModelMixin,
RetrieveModelMixin,
UpdateModelMixin,
)
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from .serializers import (
CreateUserSerializer,
PasswordChangeSerializer,
PasswordResetConfirmSerializer,
RegisterSerializer,
ResendEmailVerificationSerializer,
UserPasswordResetSerializer,
UserSerializer,
VerifyEmailSerializer,
)
User = get_user_model()
sensitive_post_parameters_m = method_decorator(
sensitive_post_parameters(
"password",
"old_password",
"new_password1",
"new_password2",
),
)
class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
lookup_field = "username"
def get_queryset(self, *args, **kwargs):
return self.queryset.filter(id=self.request.user.id)
@action(detail=False, methods=["GET"])
def me(self, request):
serializer = UserSerializer(request.user, context={"request": request})
user_data = {"user": serializer.data}
return Response(status=status.HTTP_200_OK, data=user_data)
class UserCreateViewSet(CreateModelMixin, GenericViewSet):
queryset = User.objects.all()
serializer_class = CreateUserSerializer
permission_classes = [
AllowAny,
]
class PasswordResetView(GenericAPIView):
serializer_class = UserPasswordResetSerializer
permission_classes = (AllowAny,)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(
{"detail": _("Password reset e-mail has been sent.")},
status=status.HTTP_200_OK,
)
class PasswordResetConfirmView(GenericAPIView):
serializer_class = PasswordResetConfirmSerializer
permission_classes = (AllowAny,)
@sensitive_post_parameters_m
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response({"detail": _("Password has been reset with the new password")})
class PasswordChangeView(GenericAPIView):
serializer_class = PasswordChangeSerializer
permission_classes = (IsAuthenticated,)
@sensitive_post_parameters_m
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response({"detail": _("New password has been saved")})
class VerifyEmailView(APIView, ConfirmEmailView):
permission_classes = (AllowAny,)
allowed_methods = ("POST", "OPTIONS", "HEAD")
def get_serializer(self, *args, **kwargs):
return VerifyEmailSerializer(*args, **kwargs)
def get(self, *args, **kwargs):
raise MethodNotAllowed("GET")
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.kwargs["key"] = serializer.validated_data["key"]
confirmation = self.get_object()
confirmation.confirm(self.request)
return Response({"detail": _("ok")}, status=status.HTTP_200_OK)
class ResendEmailVerificationView(CreateAPIView):
permission_classes = (AllowAny,)
serializer_class = ResendEmailVerificationSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
email = EmailAddress.objects.get(**serializer.validated_data)
if not email:
raise ValidationError("Account does not exist")
if email.verified:
raise ValidationError("Account is already verified")
email.send_confirmation()
return Response({"detail": _("ok")}, status=status.HTTP_200_OK)
class RegisterView(CreateAPIView):
serializer_class = RegisterSerializer
permission_classes = (AllowAny,)
@sensitive_post_parameters_m
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def get_response_data(self, user):
if (
allauth_settings.EMAIL_VERIFICATION
== allauth_settings.EmailVerificationMethod.MANDATORY
):
return {"detail": _("Verification e-mail sent.")}
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(
self.get_response_data(user),
status=status.HTTP_201_CREATED,
headers=headers,
)
def perform_create(self, serializer):
user = serializer.save(self.request)
complete_signup(
self.request._request,
user,
allauth_settings.EMAIL_VERIFICATION,
None,
)
return user
| true | true |
f72f13d49d6c7a860c5b0fe7664a87a652eb88a8 | 641 | py | Python | tests/test_data/test_datasets/test_xml_dataset.py | Brym-Gyimah/mmdetection | d5d749afe57c77e2ec4500395faed3566fdfedae | [
"Apache-2.0"
] | 20,190 | 2018-09-10T01:11:53.000Z | 2022-03-31T22:31:33.000Z | tests/test_data/test_datasets/test_xml_dataset.py | Joker-co/mmdet_pro | 96abfd90cf0e38c5ce398795f949e9328eb85c1b | [
"Apache-2.0"
] | 6,736 | 2018-09-17T09:45:51.000Z | 2022-03-31T22:54:10.000Z | tests/test_data/test_datasets/test_xml_dataset.py | Joker-co/mmdet_pro | 96abfd90cf0e38c5ce398795f949e9328eb85c1b | [
"Apache-2.0"
] | 7,837 | 2018-09-11T02:58:23.000Z | 2022-03-31T22:31:38.000Z | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
from mmdet.datasets import DATASETS
def test_xml_dataset():
dataconfig = {
'ann_file': 'data/VOCdevkit/VOC2007/ImageSets/Main/test.txt',
'img_prefix': 'data/VOCdevkit/VOC2007/',
'pipeline': [{
'type': 'LoadImageFromFile'
}]
}
XMLDataset = DATASETS.get('XMLDataset')
class XMLDatasetSubClass(XMLDataset):
CLASSES = None
# get_ann_info and _filter_imgs of XMLDataset
# would use self.CLASSES, we added CLASSES not NONE
with pytest.raises(AssertionError):
XMLDatasetSubClass(**dataconfig)
| 26.708333 | 69 | 0.666147 |
import pytest
from mmdet.datasets import DATASETS
def test_xml_dataset():
dataconfig = {
'ann_file': 'data/VOCdevkit/VOC2007/ImageSets/Main/test.txt',
'img_prefix': 'data/VOCdevkit/VOC2007/',
'pipeline': [{
'type': 'LoadImageFromFile'
}]
}
XMLDataset = DATASETS.get('XMLDataset')
class XMLDatasetSubClass(XMLDataset):
CLASSES = None
with pytest.raises(AssertionError):
XMLDatasetSubClass(**dataconfig)
| true | true |
f72f1410ab89a22b8401c8e0baede753bd6f5c48 | 10,693 | py | Python | src/python/pants/base/specs.py | rcuza/pants | 0429258b181986eed856ae45af93b776727774a0 | [
"Apache-2.0"
] | 1 | 2021-02-22T18:11:26.000Z | 2021-02-22T18:11:26.000Z | src/python/pants/base/specs.py | rcuza/pants | 0429258b181986eed856ae45af93b776727774a0 | [
"Apache-2.0"
] | null | null | null | src/python/pants/base/specs.py | rcuza/pants | 0429258b181986eed856ae45af93b776727774a0 | [
"Apache-2.0"
] | 2 | 2021-05-11T07:51:26.000Z | 2021-05-19T10:14:46.000Z | # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import itertools
import os
from abc import ABC, ABCMeta, abstractmethod
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterable, Mapping, Sequence, Tuple
from pants.base.exceptions import ResolveError
from pants.build_graph.address import Address
from pants.engine.fs import GlobExpansionConjunction, GlobMatchErrorBehavior, PathGlobs
from pants.engine.internals.target_adaptor import TargetAdaptor
from pants.util.dirutil import fast_relpath_optional, recursive_dirname
from pants.util.meta import frozen_after_init
if TYPE_CHECKING:
from pants.engine.internals.mapper import AddressFamily
class Spec(ABC):
"""A specification for what Pants should operate on."""
@abstractmethod
def __str__(self) -> str:
"""The normalized string representation of this spec."""
class AddressSpec(Spec, metaclass=ABCMeta):
"""Represents address selectors as passed from the command line."""
@dataclass(frozen=True)
class AddressLiteralSpec(AddressSpec):
"""An AddressSpec for a single address.
This may be a traditional address, like `a/b/c:c`, or a file address using disambiguation
syntax, e.g. `a/b/c.txt:tgt`.
"""
path_component: str
target_component: str
def __str__(self) -> str:
return f"{self.path_component}:{self.target_component}"
class AddressGlobSpec(AddressSpec, metaclass=ABCMeta):
@abstractmethod
def to_globs(self, build_patterns: Iterable[str]) -> Tuple[str, ...]:
"""Generate glob patterns matching exactly all the BUILD files this address spec covers."""
@abstractmethod
def matching_address_families(
self, address_families_dict: Mapping[str, "AddressFamily"]
) -> Tuple["AddressFamily", ...]:
"""Given a dict of (namespace path) -> AddressFamily, return the values matching this
address spec.
:raises: :class:`ResolveError` if no address families matched this spec and this spec type
expects a match.
"""
def matching_addresses(
self, address_families: Sequence["AddressFamily"]
) -> Sequence[Tuple[Address, TargetAdaptor]]:
"""Given a list of AddressFamily, return (Address, TargetAdaptor) pairs matching this
address spec.
:raises: :class:`ResolveError` if no addresses could be matched and this spec type expects
a match.
"""
return tuple(
itertools.chain.from_iterable(
af.addresses_to_target_adaptors.items() for af in address_families
)
)
@dataclass(frozen=True)
class SiblingAddresses(AddressGlobSpec):
"""An AddressSpec representing all addresses located directly within the given directory."""
directory: str
def __str__(self) -> str:
return f"{self.directory}:"
def to_globs(self, build_patterns: Iterable[str]) -> Tuple[str, ...]:
return tuple(os.path.join(self.directory, pat) for pat in build_patterns)
def matching_address_families(
self, address_families_dict: Mapping[str, "AddressFamily"]
) -> Tuple["AddressFamily", ...]:
maybe_af = address_families_dict.get(self.directory)
if maybe_af is None:
raise ResolveError(
f"Path '{self.directory}' does not contain any BUILD files, but '{self}' expected "
"matching targets there."
)
return (maybe_af,)
@dataclass(frozen=True)
class MaybeEmptyDescendantAddresses(AddressGlobSpec):
"""An AddressSpec representing all addresses located recursively under the given directory.
It is not an error if there are no such addresses.
"""
directory: str
def __str__(self) -> str:
return f"{self.directory}::"
def to_globs(self, build_patterns: Iterable[str]) -> Tuple[str, ...]:
return tuple(os.path.join(self.directory, "**", pat) for pat in build_patterns)
def matching_address_families(
self, address_families_dict: Mapping[str, "AddressFamily"]
) -> Tuple["AddressFamily", ...]:
return tuple(
af
for ns, af in address_families_dict.items()
if fast_relpath_optional(ns, self.directory) is not None
)
class DescendantAddresses(MaybeEmptyDescendantAddresses):
"""An AddressSpec representing all addresses located recursively under the given directory.
At least one such address must exist.
"""
def matching_addresses(
self, address_families: Sequence["AddressFamily"]
) -> Sequence[Tuple[Address, TargetAdaptor]]:
matching = super().matching_addresses(address_families)
if len(matching) == 0:
raise ResolveError(f"Address spec '{self}' does not match any targets.")
return matching
@dataclass(frozen=True)
class AscendantAddresses(AddressGlobSpec):
"""An AddressSpec representing all addresses located recursively _above_ the given directory."""
directory: str
def __str__(self) -> str:
return f"{self.directory}^"
def to_globs(self, build_patterns: Iterable[str]) -> Tuple[str, ...]:
return tuple(
os.path.join(f, pattern)
for pattern in build_patterns
for f in recursive_dirname(self.directory)
)
def matching_address_families(
self, address_families_dict: Mapping[str, "AddressFamily"]
) -> Tuple["AddressFamily", ...]:
return tuple(
af
for ns, af in address_families_dict.items()
if fast_relpath_optional(self.directory, ns) is not None
)
@frozen_after_init
@dataclass(unsafe_hash=True)
class AddressSpecs:
literals: Tuple[AddressLiteralSpec, ...]
globs: Tuple[AddressGlobSpec, ...]
filter_by_global_options: bool
def __init__(
self, specs: Iterable[AddressSpec], *, filter_by_global_options: bool = False
) -> None:
"""Create the specs for what addresses Pants should run on.
If `filter_by_global_options` is set to True, then the resulting Addresses will be filtered
by the global options `--tag` and `--exclude-target-regexp`.
"""
literals = []
globs = []
for spec in specs:
if isinstance(spec, AddressLiteralSpec):
literals.append(spec)
elif isinstance(spec, AddressGlobSpec):
globs.append(spec)
else:
raise ValueError(f"Unexpected type of AddressSpec: {repr(self)}")
self.literals = tuple(literals)
self.globs = tuple(globs)
self.filter_by_global_options = filter_by_global_options
@property
def specs(self) -> Tuple[AddressSpec, ...]:
return (*self.literals, *self.globs)
def to_path_globs(
self, *, build_patterns: Iterable[str], build_ignore_patterns: Iterable[str]
) -> PathGlobs:
includes = set(
itertools.chain.from_iterable(spec.to_globs(build_patterns) for spec in self.globs)
)
ignores = (f"!{p}" for p in build_ignore_patterns)
return PathGlobs(globs=(*includes, *ignores))
def __bool__(self) -> bool:
return bool(self.specs)
class FilesystemSpec(Spec, metaclass=ABCMeta):
pass
@dataclass(frozen=True)
class FilesystemLiteralSpec(FilesystemSpec):
"""A literal file name, e.g. `foo.py`."""
file: str
def __str__(self) -> str:
return self.file
@dataclass(frozen=True)
class FilesystemGlobSpec(FilesystemSpec):
"""A spec with a glob or globs, e.g. `*.py` and `**/*.java`."""
glob: str
def __str__(self) -> str:
return self.glob
@dataclass(frozen=True)
class FilesystemIgnoreSpec(FilesystemSpec):
"""A spec to ignore certain files or globs."""
glob: str
def __post_init__(self) -> None:
if self.glob.startswith("!"):
raise ValueError(f"The `glob` for {self} should not start with `!`.")
def __str__(self) -> str:
return f"!{self.glob}"
@frozen_after_init
@dataclass(unsafe_hash=True)
class FilesystemSpecs:
includes: tuple[FilesystemLiteralSpec | FilesystemGlobSpec, ...]
ignores: tuple[FilesystemIgnoreSpec, ...]
def __init__(self, specs: Iterable[FilesystemSpec]) -> None:
includes = []
ignores = []
for spec in specs:
if isinstance(spec, (FilesystemLiteralSpec, FilesystemGlobSpec)):
includes.append(spec)
elif isinstance(spec, FilesystemIgnoreSpec):
ignores.append(spec)
else:
raise ValueError(f"Unexpected type of FilesystemSpec: {repr(self)}")
self.includes = tuple(includes)
self.ignores = tuple(ignores)
@property
def specs(self) -> Tuple[FilesystemSpec, ...]:
return (*self.includes, *self.ignores)
@staticmethod
def _generate_path_globs(
specs: Iterable[FilesystemSpec], glob_match_error_behavior: GlobMatchErrorBehavior
) -> PathGlobs:
return PathGlobs(
globs=(str(s) for s in specs),
glob_match_error_behavior=glob_match_error_behavior,
# We validate that _every_ glob is valid.
conjunction=GlobExpansionConjunction.all_match,
description_of_origin=(
None
if glob_match_error_behavior == GlobMatchErrorBehavior.ignore
else "file arguments"
),
)
def path_globs_for_spec(
self,
spec: FilesystemLiteralSpec | FilesystemGlobSpec,
glob_match_error_behavior: GlobMatchErrorBehavior,
) -> PathGlobs:
"""Generate PathGlobs for the specific spec, automatically including the instance's
FilesystemIgnoreSpecs."""
return self._generate_path_globs((spec, *self.ignores), glob_match_error_behavior)
def to_path_globs(self, glob_match_error_behavior: GlobMatchErrorBehavior) -> PathGlobs:
"""Generate a single PathGlobs for the instance."""
return self._generate_path_globs((*self.includes, *self.ignores), glob_match_error_behavior)
def __bool__(self) -> bool:
return bool(self.specs)
@dataclass(frozen=True)
class Specs:
address_specs: AddressSpecs
filesystem_specs: FilesystemSpecs
@property
def provided(self) -> bool:
"""Did the user provide specs?"""
return bool(self.address_specs) or bool(self.filesystem_specs)
@classmethod
def empty(cls) -> Specs:
return Specs(AddressSpecs([], filter_by_global_options=True), FilesystemSpecs([]))
| 32.901538 | 100 | 0.666511 |
from __future__ import annotations
import itertools
import os
from abc import ABC, ABCMeta, abstractmethod
from dataclasses import dataclass
from typing import TYPE_CHECKING, Iterable, Mapping, Sequence, Tuple
from pants.base.exceptions import ResolveError
from pants.build_graph.address import Address
from pants.engine.fs import GlobExpansionConjunction, GlobMatchErrorBehavior, PathGlobs
from pants.engine.internals.target_adaptor import TargetAdaptor
from pants.util.dirutil import fast_relpath_optional, recursive_dirname
from pants.util.meta import frozen_after_init
if TYPE_CHECKING:
from pants.engine.internals.mapper import AddressFamily
class Spec(ABC):
@abstractmethod
def __str__(self) -> str:
class AddressSpec(Spec, metaclass=ABCMeta):
@dataclass(frozen=True)
class AddressLiteralSpec(AddressSpec):
path_component: str
target_component: str
def __str__(self) -> str:
return f"{self.path_component}:{self.target_component}"
class AddressGlobSpec(AddressSpec, metaclass=ABCMeta):
@abstractmethod
def to_globs(self, build_patterns: Iterable[str]) -> Tuple[str, ...]:
@abstractmethod
def matching_address_families(
self, address_families_dict: Mapping[str, "AddressFamily"]
) -> Tuple["AddressFamily", ...]:
def matching_addresses(
self, address_families: Sequence["AddressFamily"]
) -> Sequence[Tuple[Address, TargetAdaptor]]:
return tuple(
itertools.chain.from_iterable(
af.addresses_to_target_adaptors.items() for af in address_families
)
)
@dataclass(frozen=True)
class SiblingAddresses(AddressGlobSpec):
directory: str
def __str__(self) -> str:
return f"{self.directory}:"
def to_globs(self, build_patterns: Iterable[str]) -> Tuple[str, ...]:
return tuple(os.path.join(self.directory, pat) for pat in build_patterns)
def matching_address_families(
self, address_families_dict: Mapping[str, "AddressFamily"]
) -> Tuple["AddressFamily", ...]:
maybe_af = address_families_dict.get(self.directory)
if maybe_af is None:
raise ResolveError(
f"Path '{self.directory}' does not contain any BUILD files, but '{self}' expected "
"matching targets there."
)
return (maybe_af,)
@dataclass(frozen=True)
class MaybeEmptyDescendantAddresses(AddressGlobSpec):
directory: str
def __str__(self) -> str:
return f"{self.directory}::"
def to_globs(self, build_patterns: Iterable[str]) -> Tuple[str, ...]:
return tuple(os.path.join(self.directory, "**", pat) for pat in build_patterns)
def matching_address_families(
self, address_families_dict: Mapping[str, "AddressFamily"]
) -> Tuple["AddressFamily", ...]:
return tuple(
af
for ns, af in address_families_dict.items()
if fast_relpath_optional(ns, self.directory) is not None
)
class DescendantAddresses(MaybeEmptyDescendantAddresses):
def matching_addresses(
self, address_families: Sequence["AddressFamily"]
) -> Sequence[Tuple[Address, TargetAdaptor]]:
matching = super().matching_addresses(address_families)
if len(matching) == 0:
raise ResolveError(f"Address spec '{self}' does not match any targets.")
return matching
@dataclass(frozen=True)
class AscendantAddresses(AddressGlobSpec):
directory: str
def __str__(self) -> str:
return f"{self.directory}^"
def to_globs(self, build_patterns: Iterable[str]) -> Tuple[str, ...]:
return tuple(
os.path.join(f, pattern)
for pattern in build_patterns
for f in recursive_dirname(self.directory)
)
def matching_address_families(
self, address_families_dict: Mapping[str, "AddressFamily"]
) -> Tuple["AddressFamily", ...]:
return tuple(
af
for ns, af in address_families_dict.items()
if fast_relpath_optional(self.directory, ns) is not None
)
@frozen_after_init
@dataclass(unsafe_hash=True)
class AddressSpecs:
literals: Tuple[AddressLiteralSpec, ...]
globs: Tuple[AddressGlobSpec, ...]
filter_by_global_options: bool
def __init__(
self, specs: Iterable[AddressSpec], *, filter_by_global_options: bool = False
) -> None:
literals = []
globs = []
for spec in specs:
if isinstance(spec, AddressLiteralSpec):
literals.append(spec)
elif isinstance(spec, AddressGlobSpec):
globs.append(spec)
else:
raise ValueError(f"Unexpected type of AddressSpec: {repr(self)}")
self.literals = tuple(literals)
self.globs = tuple(globs)
self.filter_by_global_options = filter_by_global_options
@property
def specs(self) -> Tuple[AddressSpec, ...]:
return (*self.literals, *self.globs)
def to_path_globs(
self, *, build_patterns: Iterable[str], build_ignore_patterns: Iterable[str]
) -> PathGlobs:
includes = set(
itertools.chain.from_iterable(spec.to_globs(build_patterns) for spec in self.globs)
)
ignores = (f"!{p}" for p in build_ignore_patterns)
return PathGlobs(globs=(*includes, *ignores))
def __bool__(self) -> bool:
return bool(self.specs)
class FilesystemSpec(Spec, metaclass=ABCMeta):
pass
@dataclass(frozen=True)
class FilesystemLiteralSpec(FilesystemSpec):
file: str
def __str__(self) -> str:
return self.file
@dataclass(frozen=True)
class FilesystemGlobSpec(FilesystemSpec):
glob: str
def __str__(self) -> str:
return self.glob
@dataclass(frozen=True)
class FilesystemIgnoreSpec(FilesystemSpec):
glob: str
def __post_init__(self) -> None:
if self.glob.startswith("!"):
raise ValueError(f"The `glob` for {self} should not start with `!`.")
def __str__(self) -> str:
return f"!{self.glob}"
@frozen_after_init
@dataclass(unsafe_hash=True)
class FilesystemSpecs:
includes: tuple[FilesystemLiteralSpec | FilesystemGlobSpec, ...]
ignores: tuple[FilesystemIgnoreSpec, ...]
def __init__(self, specs: Iterable[FilesystemSpec]) -> None:
includes = []
ignores = []
for spec in specs:
if isinstance(spec, (FilesystemLiteralSpec, FilesystemGlobSpec)):
includes.append(spec)
elif isinstance(spec, FilesystemIgnoreSpec):
ignores.append(spec)
else:
raise ValueError(f"Unexpected type of FilesystemSpec: {repr(self)}")
self.includes = tuple(includes)
self.ignores = tuple(ignores)
@property
def specs(self) -> Tuple[FilesystemSpec, ...]:
return (*self.includes, *self.ignores)
@staticmethod
def _generate_path_globs(
specs: Iterable[FilesystemSpec], glob_match_error_behavior: GlobMatchErrorBehavior
) -> PathGlobs:
return PathGlobs(
globs=(str(s) for s in specs),
glob_match_error_behavior=glob_match_error_behavior,
conjunction=GlobExpansionConjunction.all_match,
description_of_origin=(
None
if glob_match_error_behavior == GlobMatchErrorBehavior.ignore
else "file arguments"
),
)
def path_globs_for_spec(
self,
spec: FilesystemLiteralSpec | FilesystemGlobSpec,
glob_match_error_behavior: GlobMatchErrorBehavior,
) -> PathGlobs:
return self._generate_path_globs((spec, *self.ignores), glob_match_error_behavior)
def to_path_globs(self, glob_match_error_behavior: GlobMatchErrorBehavior) -> PathGlobs:
return self._generate_path_globs((*self.includes, *self.ignores), glob_match_error_behavior)
def __bool__(self) -> bool:
return bool(self.specs)
@dataclass(frozen=True)
class Specs:
address_specs: AddressSpecs
filesystem_specs: FilesystemSpecs
@property
def provided(self) -> bool:
return bool(self.address_specs) or bool(self.filesystem_specs)
@classmethod
def empty(cls) -> Specs:
return Specs(AddressSpecs([], filter_by_global_options=True), FilesystemSpecs([]))
| true | true |
f72f15c5de015caaeac2371e1ce51f83332786d4 | 1,144 | py | Python | lib/datasets/synthetic_example.py | liulu112601/AutoDL-Projects | 59d07b63420837f56ea45b678784e299612477c3 | [
"MIT"
] | null | null | null | lib/datasets/synthetic_example.py | liulu112601/AutoDL-Projects | 59d07b63420837f56ea45b678784e299612477c3 | [
"MIT"
] | null | null | null | lib/datasets/synthetic_example.py | liulu112601/AutoDL-Projects | 59d07b63420837f56ea45b678784e299612477c3 | [
"MIT"
] | null | null | null | #####################################################
# Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2021.04 #
#####################################################
import copy
from .math_dynamic_funcs import DynamicQuadraticFunc
from .math_adv_funcs import ConstantFunc, ComposedSinFunc
from .synthetic_env import SyntheticDEnv
def create_example_v1(
timestamp_config=None,
num_per_task=5000,
):
mean_generator = ComposedSinFunc()
std_generator = ComposedSinFunc(min_amplitude=0.5, max_amplitude=0.5)
dynamic_env = SyntheticDEnv(
[mean_generator],
[[std_generator]],
num_per_task=num_per_task,
timestamp_config=timestamp_config,
)
function = DynamicQuadraticFunc()
function_param = dict()
function_param[0] = ComposedSinFunc(
num_sin_phase=4, phase_shift=1.0, max_amplitude=1.0
)
function_param[1] = ConstantFunc(constant=0.9)
function_param[2] = ComposedSinFunc(
num_sin_phase=5, phase_shift=0.4, max_amplitude=0.9
)
function.set(function_param)
dynamic_env.set_oracle_map(copy.deepcopy(function))
return dynamic_env, function
| 30.105263 | 73 | 0.657343 | true | true | |
f72f163111d0ad06a68b563a14a17a629ddccdab | 756 | py | Python | milarun/lib/monitor.py | laceyg/milabench | a314094a406c2e98a932f6d4f3a9588a991148d3 | [
"MIT"
] | 7 | 2020-07-09T18:55:00.000Z | 2022-03-31T19:51:29.000Z | milarun/lib/monitor.py | laceyg/milabench | a314094a406c2e98a932f6d4f3a9588a991148d3 | [
"MIT"
] | 6 | 2020-07-02T08:58:39.000Z | 2021-02-01T20:31:28.000Z | milarun/lib/monitor.py | laceyg/milabench | a314094a406c2e98a932f6d4f3a9588a991148d3 | [
"MIT"
] | 8 | 2020-06-19T17:16:19.000Z | 2022-03-31T19:34:49.000Z | import GPUtil
from threading import Thread
import time
class GPUMonitor(Thread):
def __init__(self, delay):
super().__init__()
self.stopped = False
self.delay = delay
self.data = {
g.id: dict(
load=[],
memory=[],
temperature=[]
)
for g in GPUtil.getGPUs()
}
def run(self):
while not self.stopped:
for g in GPUtil.getGPUs():
data = self.data[g.id]
data["load"].append(g.load)
data["memory"].append(g.memoryUsed)
data["temperature"].append(g.temperature)
time.sleep(self.delay)
def stop(self):
self.stopped = True
| 24.387097 | 57 | 0.492063 | import GPUtil
from threading import Thread
import time
class GPUMonitor(Thread):
def __init__(self, delay):
super().__init__()
self.stopped = False
self.delay = delay
self.data = {
g.id: dict(
load=[],
memory=[],
temperature=[]
)
for g in GPUtil.getGPUs()
}
def run(self):
while not self.stopped:
for g in GPUtil.getGPUs():
data = self.data[g.id]
data["load"].append(g.load)
data["memory"].append(g.memoryUsed)
data["temperature"].append(g.temperature)
time.sleep(self.delay)
def stop(self):
self.stopped = True
| true | true |
f72f168e38670fee460a5423e951a0f83d8cd4f5 | 702 | py | Python | matplotlib/matplotlib_test/plot_lib_test.py | alphaciel/Balancing-Robot-Raspberry-Pi-DIY | 8a61acf688ea0915017c40eaff3841a9b219f9b7 | [
"MIT"
] | null | null | null | matplotlib/matplotlib_test/plot_lib_test.py | alphaciel/Balancing-Robot-Raspberry-Pi-DIY | 8a61acf688ea0915017c40eaff3841a9b219f9b7 | [
"MIT"
] | null | null | null | matplotlib/matplotlib_test/plot_lib_test.py | alphaciel/Balancing-Robot-Raspberry-Pi-DIY | 8a61acf688ea0915017c40eaff3841a9b219f9b7 | [
"MIT"
] | null | null | null | import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider, Button, RadioButtons
fig = plt.figure()
ax = fig.add_subplot(111)
fig.subplots_adjust(left=0.25, bottom=0.25)
min0 = 0
max0 = 25000
im = max0 * np.random.random((10,10))
im1 = ax.imshow(im)
fig.colorbar(im1)
axcolor = 'lightgoldenrodyellow'
axmin = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
axmax = fig.add_axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
smin = Slider(axmin, 'Min', 0, 30000, valinit=min0)
smax = Slider(axmax, 'Max', 0, 30000, valinit=max0)
def update(val):
im1.set_clim([smin.val,smax.val])
fig.canvas.draw()
smin.on_changed(update)
smax.on_changed(update)
plt.show() | 25.071429 | 63 | 0.709402 | import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider, Button, RadioButtons
fig = plt.figure()
ax = fig.add_subplot(111)
fig.subplots_adjust(left=0.25, bottom=0.25)
min0 = 0
max0 = 25000
im = max0 * np.random.random((10,10))
im1 = ax.imshow(im)
fig.colorbar(im1)
axcolor = 'lightgoldenrodyellow'
axmin = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
axmax = fig.add_axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
smin = Slider(axmin, 'Min', 0, 30000, valinit=min0)
smax = Slider(axmax, 'Max', 0, 30000, valinit=max0)
def update(val):
im1.set_clim([smin.val,smax.val])
fig.canvas.draw()
smin.on_changed(update)
smax.on_changed(update)
plt.show() | true | true |
f72f16a11c68a6687ece2fc6cae8e47c19ce6f15 | 613 | py | Python | src/rakali/transforms.py | sthysel/rakali | d641b8f75e7bbbd4ab973060658f5b30d24e99ff | [
"MIT"
] | 6 | 2019-02-17T01:23:39.000Z | 2021-01-13T23:01:16.000Z | src/rakali/transforms.py | sthysel/rakali | d641b8f75e7bbbd4ab973060658f5b30d24e99ff | [
"MIT"
] | 1 | 2020-09-09T19:52:17.000Z | 2021-09-13T08:25:44.000Z | src/rakali/transforms.py | sthysel/rakali | d641b8f75e7bbbd4ab973060658f5b30d24e99ff | [
"MIT"
] | 3 | 2021-07-21T14:09:43.000Z | 2021-08-22T15:03:48.000Z | import cv2 as cv
def scale(img, scale):
"""scale preserving aspect ratio"""
return resize(img, x_scale=scale, y_scale=scale)
def resize(img, x_scale, y_scale, optimize=True):
"""resize image by scaling using provided factors"""
interpolation = cv.INTER_LINEAR
# pick an optimized scaler if asked to
if optimize:
if x_scale > 1 and y_scale > 1:
interpolation = cv.INTER_CUBIC
else:
interpolation = cv.INTER_AREA
return cv.resize(
img,
None,
fx=x_scale,
fy=y_scale,
interpolation=interpolation,
)
| 22.703704 | 56 | 0.619902 | import cv2 as cv
def scale(img, scale):
return resize(img, x_scale=scale, y_scale=scale)
def resize(img, x_scale, y_scale, optimize=True):
interpolation = cv.INTER_LINEAR
if optimize:
if x_scale > 1 and y_scale > 1:
interpolation = cv.INTER_CUBIC
else:
interpolation = cv.INTER_AREA
return cv.resize(
img,
None,
fx=x_scale,
fy=y_scale,
interpolation=interpolation,
)
| true | true |
f72f17683039c31b552fe4aaaab293ebc4b067b4 | 1,380 | py | Python | load_isbi.py | lone17/deform-conv | 3502cedbeae61c961d7e988382c55b9d45fd1873 | [
"MIT"
] | null | null | null | load_isbi.py | lone17/deform-conv | 3502cedbeae61c961d7e988382c55b9d45fd1873 | [
"MIT"
] | null | null | null | load_isbi.py | lone17/deform-conv | 3502cedbeae61c961d7e988382c55b9d45fd1873 | [
"MIT"
] | null | null | null | from keras.preprocessing.image import ImageDataGenerator
data_gen_args = dict(rescale=1./255,
rotation_range=0.2,
shear_range=0.2,
zoom_range=0.2,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=True,
fill_mode='nearest')
seed = 17
train_image_gen = \
ImageDataGenerator(**data_gen_args)\
.flow_from_directory('ISBI/train', classes=['image'], target_size=(512, 512),
color_mode='grayscale', class_mode=None, batch_size=1,
shuffle=True, seed=seed)
train_mask_gen = \
ImageDataGenerator(**data_gen_args)\
.flow_from_directory('ISBI/train', classes=['label'], target_size=(512, 512),
color_mode='grayscale', class_mode=None, batch_size=1,
shuffle=True, seed=seed)
val_image_gen = \
ImageDataGenerator(rescale=1./255)\
.flow_from_directory('ISBI/val', classes=['image'], target_size=(512, 512),
color_mode='grayscale', class_mode=None, batch_size=1)
val_mask_gen = \
ImageDataGenerator(rescale=1./255)\
.flow_from_directory('ISBI/val', classes=['label'], target_size=(512, 512),
color_mode='grayscale', class_mode=None, batch_size=1)
| 41.818182 | 81 | 0.588406 | from keras.preprocessing.image import ImageDataGenerator
data_gen_args = dict(rescale=1./255,
rotation_range=0.2,
shear_range=0.2,
zoom_range=0.2,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=True,
fill_mode='nearest')
seed = 17
train_image_gen = \
ImageDataGenerator(**data_gen_args)\
.flow_from_directory('ISBI/train', classes=['image'], target_size=(512, 512),
color_mode='grayscale', class_mode=None, batch_size=1,
shuffle=True, seed=seed)
train_mask_gen = \
ImageDataGenerator(**data_gen_args)\
.flow_from_directory('ISBI/train', classes=['label'], target_size=(512, 512),
color_mode='grayscale', class_mode=None, batch_size=1,
shuffle=True, seed=seed)
val_image_gen = \
ImageDataGenerator(rescale=1./255)\
.flow_from_directory('ISBI/val', classes=['image'], target_size=(512, 512),
color_mode='grayscale', class_mode=None, batch_size=1)
val_mask_gen = \
ImageDataGenerator(rescale=1./255)\
.flow_from_directory('ISBI/val', classes=['label'], target_size=(512, 512),
color_mode='grayscale', class_mode=None, batch_size=1)
| true | true |
f72f183dad87e98bbd6b38f75d1d545a70ce6384 | 2,519 | py | Python | parser/fase2/team10/sql/Instrucciones/Sql_alter/AlterTableAlterColumn.py | Gabriel-15/tytus | fb00718bf3fcc5211a3604fba1a551f44bdc6deb | [
"MIT"
] | 35 | 2020-12-07T03:11:43.000Z | 2021-04-15T17:38:16.000Z | parser/fase2/team10/sql/Instrucciones/Sql_alter/AlterTableAlterColumn.py | Gabriel-15/tytus | fb00718bf3fcc5211a3604fba1a551f44bdc6deb | [
"MIT"
] | 47 | 2020-12-09T01:29:09.000Z | 2021-01-13T05:37:50.000Z | parser/fase2/team10/sql/Instrucciones/Sql_alter/AlterTableAlterColumn.py | Gabriel-15/tytus | fb00718bf3fcc5211a3604fba1a551f44bdc6deb | [
"MIT"
] | 556 | 2020-12-07T03:13:31.000Z | 2021-06-17T17:41:10.000Z | from sql.Instrucciones.TablaSimbolos.Instruccion import Instruccion
from sql.Instrucciones.Sql_create.Tipo_Constraint import Tipo_Constraint, Tipo_Dato_Constraint
from sql.Instrucciones.Excepcion import Excepcion
class AlterTableAlterColumn(Instruccion):
def __init__(self, tabla, col, strGram, linea, columna):
Instruccion.__init__(self,None,linea,columna,strGram)
self.tabla = tabla
self.col = col
def ejecutar(self, tabla, arbol):
super().ejecutar(tabla,arbol)
if arbol.bdUsar != None:
objetoTabla = arbol.devolviendoTablaDeBase(self.tabla)
if objetoTabla != 0:
existe = None
for columnas in objetoTabla.lista_de_campos:
if columnas.nombre == self.col:
existe = columnas
if existe != None:
#print(len(listaUnique),self.tabla, self.id)
#Insertar llaves Unique
if existe.constraint != None:
existe.constraint.append(Tipo_Constraint(None, Tipo_Dato_Constraint.NOT_NULL, None))
#print("MÁS DE UNA-----------------",existe.nombre, existe.tipo.toString(),len(existe.constraint))
else:
existe.constraint = []
existe.constraint.append(Tipo_Constraint(None, Tipo_Dato_Constraint.NOT_NULL, None))
#print("SOLO UNA-------------",existe.nombre, existe.tipo.toString(),len(existe.constraint))
arbol.consola.append("Consulta devuelta correctamente.")
else:
#print(listaNombres,self.lista_col)
#print(lista)
error = Excepcion('42P01',"Semántico","No existe la columna «"+self.col+"» en la llave",self.linea,self.columna)
arbol.excepciones.append(error)
arbol.consola.append(error.toString())
return error
else:
error = Excepcion('42P01',"Semántico","No existe la relación "+self.tabla,self.linea,self.columna)
arbol.excepciones.append(error)
arbol.consola.append(error.toString())
return error
else:
error = Excepcion("100","Semantico","No ha seleccionado ninguna Base de Datos.",self.linea,self.columna)
arbol.excepciones.append(error)
arbol.consola.append(error.toString())
| 51.408163 | 132 | 0.579595 | from sql.Instrucciones.TablaSimbolos.Instruccion import Instruccion
from sql.Instrucciones.Sql_create.Tipo_Constraint import Tipo_Constraint, Tipo_Dato_Constraint
from sql.Instrucciones.Excepcion import Excepcion
class AlterTableAlterColumn(Instruccion):
def __init__(self, tabla, col, strGram, linea, columna):
Instruccion.__init__(self,None,linea,columna,strGram)
self.tabla = tabla
self.col = col
def ejecutar(self, tabla, arbol):
super().ejecutar(tabla,arbol)
if arbol.bdUsar != None:
objetoTabla = arbol.devolviendoTablaDeBase(self.tabla)
if objetoTabla != 0:
existe = None
for columnas in objetoTabla.lista_de_campos:
if columnas.nombre == self.col:
existe = columnas
if existe != None:
if existe.constraint != None:
existe.constraint.append(Tipo_Constraint(None, Tipo_Dato_Constraint.NOT_NULL, None))
else:
existe.constraint = []
existe.constraint.append(Tipo_Constraint(None, Tipo_Dato_Constraint.NOT_NULL, None))
arbol.consola.append("Consulta devuelta correctamente.")
else:
error = Excepcion('42P01',"Semántico","No existe la columna «"+self.col+"» en la llave",self.linea,self.columna)
arbol.excepciones.append(error)
arbol.consola.append(error.toString())
return error
else:
error = Excepcion('42P01',"Semántico","No existe la relación "+self.tabla,self.linea,self.columna)
arbol.excepciones.append(error)
arbol.consola.append(error.toString())
return error
else:
error = Excepcion("100","Semantico","No ha seleccionado ninguna Base de Datos.",self.linea,self.columna)
arbol.excepciones.append(error)
arbol.consola.append(error.toString())
| true | true |
f72f18abb7dcfee0f3b682427c6f42194a6ada0f | 6,676 | py | Python | KaboomImages.py | Toinas/IntelligentSuit | f3d33b327406d899d18ecf5fd6a100b0c786fdce | [
"MIT"
] | null | null | null | KaboomImages.py | Toinas/IntelligentSuit | f3d33b327406d899d18ecf5fd6a100b0c786fdce | [
"MIT"
] | null | null | null | KaboomImages.py | Toinas/IntelligentSuit | f3d33b327406d899d18ecf5fd6a100b0c786fdce | [
"MIT"
] | null | null | null | Kaboom_0=[
0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,
0,0,0,2,2,2,2,2,2,0,0,0,0,0,0,0,
0,0,2,2,2,2,2,2,2,2,0,0,0,0,0,0,
0,0,2,2,2,2,2,2,2,2,0,0,0,0,0,0,
0,0,2,2,2,2,2,2,2,2,0,0,0,0,0,0,
0,0,2,1,1,1,1,1,1,2,0,0,0,0,2,2,
0,0,2,1,1,1,1,1,1,2,0,0,0,0,2,2,
0,0,2,1,2,1,1,2,1,2,0,0,0,0,0,0,
0,0,2,1,1,1,1,1,1,2,0,0,0,0,0,3,
0,0,0,2,2,1,1,2,2,0,0,0,0,0,4,3,
0,0,2,2,2,2,2,2,2,2,2,4,4,4,0,0,
0,0,2,2,2,2,2,2,2,0,0,0,0,0,0,0,
0,0,2,2,2,2,2,2,2,0,0,0,0,0,0,0,
0,0,0,0,2,2,2,2,2,0,0,0,0,0,0,0,
0,0,0,0,2,2,0,2,2,0,0,0,0,0,0,0,
0,0,0,0,2,2,0,2,2,0,0,0,0,0,0,0]
kaboom_1=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,2,2,2,2,2,2,2,2,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
kaboom_2=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,
2,2,2,2,2,2,2,3,3,3,0,0,0,0,0,0,
0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
kaboom_3=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,3,0,0,0,3,0,0,0,0,0,
0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,
2,2,2,2,2,2,2,3,3,3,0,0,0,0,0,0,
0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,
0,0,0,0,0,0,3,0,0,0,3,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
kaboom_4=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,
0,0,0,0,0,3,0,0,3,0,0,3,0,0,0,0,
0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,
0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,
2,2,2,2,2,3,3,3,3,3,3,3,0,0,0,0,
0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,
0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,
0,0,0,0,0,3,0,0,3,0,0,3,0,0,0,0,
0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
kaboom_5=[0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,0,
0,0,0,3,0,0,0,0,3,0,0,0,0,3,0,0,
0,0,0,0,3,0,3,0,3,0,3,0,3,0,0,0,
0,0,0,0,0,3,3,3,3,3,3,3,0,0,0,0,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
0,0,0,0,0,3,3,3,3,3,3,3,0,0,0,0,
2,2,2,3,3,3,3,3,3,3,3,3,3,3,0,0,
0,0,0,0,0,3,3,3,3,3,3,3,0,0,0,0,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
0,0,0,0,0,3,3,3,3,3,3,3,0,0,0,0,
0,0,0,0,3,0,3,0,3,0,3,0,3,0,0,0,
0,0,0,3,0,0,0,0,3,0,0,0,0,3,0,0,
0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
kaboom_6=[0,0,3,0,0,3,0,0,3,0,0,3,0,0,3,0,
0,0,0,3,0,3,0,0,3,0,0,3,0,3,0,0,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
0,0,0,3,0,3,0,0,3,0,0,3,0,3,0,0,
0,0,3,0,0,3,0,0,3,0,0,3,0,0,3,0,
0,3,0,0,0,0,0,0,3,0,0,0,0,0,0,3,
3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
kaboom_7=[0,0,3,0,0,3,0,0,3,0,0,3,0,0,3,0,
0,0,0,3,3,3,3,3,3,3,3,3,3,3,0,0,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
0,0,0,3,3,3,3,3,3,3,3,3,3,3,0,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,0,3,3,3,3,3,3,3,3,3,3,3,0,0,
2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,0,3,3,3,3,3,3,3,3,3,3,3,0,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,0,3,3,3,3,3,3,3,3,3,3,3,0,0,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
0,0,0,3,3,3,3,3,3,3,3,3,3,3,0,0,
0,0,3,0,0,3,0,0,3,0,0,3,0,0,3,0,
0,3,0,0,0,3,0,0,3,0,0,3,0,0,0,3,
3,0,0,0,0,3,0,0,3,0,0,3,0,0,0,0,
0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0]
kaboom_8=[0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
0,3,0,3,0,3,0,0,3,0,0,3,0,3,0,3,
3,0,0,0,0,3,0,0,3,0,0,3,0,0,0,0,
0,0,0,0,0,3,0,0,3,0,0,3,0,0,0,0]
kaboom_9=[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,0,3,0,0,3,0,0,3,0,0,3,0,3,0,3,
0,0,3,0,0,3,0,0,3,0,0,3,0,3,0,0]
kaboom_10=[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,0,3,0,0,3,0,0,3,0,0,3,0,3,0,3]
kaboom_11=[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3] | 32.407767 | 44 | 0.474835 | Kaboom_0=[
0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,
0,0,0,2,2,2,2,2,2,0,0,0,0,0,0,0,
0,0,2,2,2,2,2,2,2,2,0,0,0,0,0,0,
0,0,2,2,2,2,2,2,2,2,0,0,0,0,0,0,
0,0,2,2,2,2,2,2,2,2,0,0,0,0,0,0,
0,0,2,1,1,1,1,1,1,2,0,0,0,0,2,2,
0,0,2,1,1,1,1,1,1,2,0,0,0,0,2,2,
0,0,2,1,2,1,1,2,1,2,0,0,0,0,0,0,
0,0,2,1,1,1,1,1,1,2,0,0,0,0,0,3,
0,0,0,2,2,1,1,2,2,0,0,0,0,0,4,3,
0,0,2,2,2,2,2,2,2,2,2,4,4,4,0,0,
0,0,2,2,2,2,2,2,2,0,0,0,0,0,0,0,
0,0,2,2,2,2,2,2,2,0,0,0,0,0,0,0,
0,0,0,0,2,2,2,2,2,0,0,0,0,0,0,0,
0,0,0,0,2,2,0,2,2,0,0,0,0,0,0,0,
0,0,0,0,2,2,0,2,2,0,0,0,0,0,0,0]
kaboom_1=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,2,2,2,2,2,2,2,2,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
kaboom_2=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,
2,2,2,2,2,2,2,3,3,3,0,0,0,0,0,0,
0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
kaboom_3=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,3,0,0,0,3,0,0,0,0,0,
0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,
2,2,2,2,2,2,2,3,3,3,0,0,0,0,0,0,
0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,
0,0,0,0,0,0,3,0,0,0,3,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
kaboom_4=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,
0,0,0,0,0,3,0,0,3,0,0,3,0,0,0,0,
0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,
0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,
2,2,2,2,2,3,3,3,3,3,3,3,0,0,0,0,
0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,
0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,
0,0,0,0,0,3,0,0,3,0,0,3,0,0,0,0,
0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
kaboom_5=[0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,0,
0,0,0,3,0,0,0,0,3,0,0,0,0,3,0,0,
0,0,0,0,3,0,3,0,3,0,3,0,3,0,0,0,
0,0,0,0,0,3,3,3,3,3,3,3,0,0,0,0,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
0,0,0,0,0,3,3,3,3,3,3,3,0,0,0,0,
2,2,2,3,3,3,3,3,3,3,3,3,3,3,0,0,
0,0,0,0,0,3,3,3,3,3,3,3,0,0,0,0,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
0,0,0,0,0,3,3,3,3,3,3,3,0,0,0,0,
0,0,0,0,3,0,3,0,3,0,3,0,3,0,0,0,
0,0,0,3,0,0,0,0,3,0,0,0,0,3,0,0,
0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
kaboom_6=[0,0,3,0,0,3,0,0,3,0,0,3,0,0,3,0,
0,0,0,3,0,3,0,0,3,0,0,3,0,3,0,0,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
0,0,0,0,3,3,3,3,3,3,3,3,3,0,0,0,
0,0,0,3,0,3,0,0,3,0,0,3,0,3,0,0,
0,0,3,0,0,3,0,0,3,0,0,3,0,0,3,0,
0,3,0,0,0,0,0,0,3,0,0,0,0,0,0,3,
3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
kaboom_7=[0,0,3,0,0,3,0,0,3,0,0,3,0,0,3,0,
0,0,0,3,3,3,3,3,3,3,3,3,3,3,0,0,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
0,0,0,3,3,3,3,3,3,3,3,3,3,3,0,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,0,3,3,3,3,3,3,3,3,3,3,3,0,0,
2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,0,3,3,3,3,3,3,3,3,3,3,3,0,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,0,3,3,3,3,3,3,3,3,3,3,3,0,0,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
0,0,0,3,3,3,3,3,3,3,3,3,3,3,0,0,
0,0,3,0,0,3,0,0,3,0,0,3,0,0,3,0,
0,3,0,0,0,3,0,0,3,0,0,3,0,0,0,3,
3,0,0,0,0,3,0,0,3,0,0,3,0,0,0,0,
0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0]
kaboom_8=[0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
0,0,3,3,3,3,3,3,3,3,3,3,3,3,3,0,
0,3,0,3,0,3,0,0,3,0,0,3,0,3,0,3,
3,0,0,0,0,3,0,0,3,0,0,3,0,0,0,0,
0,0,0,0,0,3,0,0,3,0,0,3,0,0,0,0]
kaboom_9=[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,0,3,0,0,3,0,0,3,0,0,3,0,3,0,3,
0,0,3,0,0,3,0,0,3,0,0,3,0,3,0,0]
kaboom_10=[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,0,3,0,0,3,0,0,3,0,0,3,0,3,0,3]
kaboom_11=[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3] | true | true |
f72f190a17b6b82a72841a82dddb9b59a381bfe5 | 197 | py | Python | worldclock/views.py | arminfriedl/netclock | f83f0faa1f2c8f06dc04d2d6de315a7b35f1c361 | [
"MIT"
] | null | null | null | worldclock/views.py | arminfriedl/netclock | f83f0faa1f2c8f06dc04d2d6de315a7b35f1c361 | [
"MIT"
] | null | null | null | worldclock/views.py | arminfriedl/netclock | f83f0faa1f2c8f06dc04d2d6de315a7b35f1c361 | [
"MIT"
] | null | null | null | from flask import render_template, request, flash, redirect, url_for, session
from . import app
@app.route('', methods=['GET'])
def create():
return render_template("worldclock/create.html")
| 24.625 | 77 | 0.736041 | from flask import render_template, request, flash, redirect, url_for, session
from . import app
@app.route('', methods=['GET'])
def create():
return render_template("worldclock/create.html")
| true | true |
f72f1912a1ea4ca3114f0a355e5ee07788eceb1f | 1,182 | py | Python | pyairwatch/system/users.py | jprichards/PyVMwareAirWatch | ac25185d1f6a001c9670d57d11a3047553f743a1 | [
"MIT"
] | 17 | 2018-03-19T05:52:37.000Z | 2022-03-09T16:41:03.000Z | pyairwatch/system/users.py | marshall-brown/PyVMwareAirWatch | ac25185d1f6a001c9670d57d11a3047553f743a1 | [
"MIT"
] | 2 | 2018-12-06T17:12:54.000Z | 2019-08-27T09:57:13.000Z | pyairwatch/system/users.py | marshall-brown/PyVMwareAirWatch | ac25185d1f6a001c9670d57d11a3047553f743a1 | [
"MIT"
] | 9 | 2018-04-02T18:42:51.000Z | 2020-06-10T02:11:05.000Z | class Users(object):
def __init__(self, client):
self.client = client
#UNTESTED
def search(self, **kwargs):
"""
Returns the Enrollment User's details matching the search parameters
/api/system/users/search?{params}
PARAMS:
username={username}
firstname={firstname}
lastname={lastname}
email={email}
organizationgroupid={locationgroupid}
role={role}
"""
response = self._get(path='/users/search', params=kwargs)
return response
def _get(self, module='system', path=None, version=None, params=None, header=None):
"""GET requests for the /System/Users module."""
response = self.client.get(module=module, path=path, version=version, params=params, header=header)
return response
def _post(self, module='system', path=None, version=None, params=None, data=None, json=None, header=None):
"""POST requests for the /System/Users module."""
response = self.client.post(module=module, path=path, version=version, params=params, data=data, json=json, header=header)
return response
| 35.818182 | 130 | 0.628596 | class Users(object):
def __init__(self, client):
self.client = client
def search(self, **kwargs):
response = self._get(path='/users/search', params=kwargs)
return response
def _get(self, module='system', path=None, version=None, params=None, header=None):
response = self.client.get(module=module, path=path, version=version, params=params, header=header)
return response
def _post(self, module='system', path=None, version=None, params=None, data=None, json=None, header=None):
response = self.client.post(module=module, path=path, version=version, params=params, data=data, json=json, header=header)
return response
| true | true |
f72f1930dfc31b7280f1354dfad37771fff132eb | 14,948 | py | Python | veroviz/getTimeDist3D.py | optimatorlab/veroviz | 4b4b7da07abbc764169223cc4cac41e19ff7031d | [
"MIT"
] | 16 | 2019-11-05T06:33:21.000Z | 2022-02-09T04:37:03.000Z | veroviz/getTimeDist3D.py | optimatorlab/veroviz | 4b4b7da07abbc764169223cc4cac41e19ff7031d | [
"MIT"
] | 6 | 2019-11-22T09:38:01.000Z | 2021-06-18T02:08:43.000Z | veroviz/getTimeDist3D.py | optimatorlab/veroviz | 4b4b7da07abbc764169223cc4cac41e19ff7031d | [
"MIT"
] | 4 | 2020-09-25T07:48:56.000Z | 2022-02-09T04:39:54.000Z | from veroviz._common import *
from veroviz._validation import *
from veroviz._buildFlightProfile import buildNoLoiteringFlight
from veroviz._buildFlightProfile import getTimeDistFromFlight
from veroviz._utilities import privConvertDistance
from veroviz._utilities import privConvertTime
def getTimeDist3D(nodes=None, matrixType='all2all', fromNodeID=None, toNodeID=None, takeoffSpeedMPS=None, cruiseSpeedMPS=None, landSpeedMPS=None, cruiseAltMetersAGL=None,
routeType='square', climbRateMPS=None, descentRateMPS=None, outputDistUnits='meters', outputTimeUnits='seconds'):
"""
This function calculates travel time and distance for vehicles that travel in 3-dimensional space (e.g., drones). The function returns three dictionaries; one for time, one for ground distance, and one for overall (3D) travel distance.
Parameters
----------
nodes: :ref:`Nodes`, Required, default as None
This :ref:`Nodes` dataframe contains the locations between which the travel time and distance will be calculated.
matrixType: string, Optional, default as 'all2all'
Specifies the structure of the travel matrices. Valid options include 'all2all', 'many2one', and 'one2many'. The default 'all2all' option will return square matrices (one for time, one for distance) describing the directed travel time and travel distance between all pairs of nodes. The 'one2many' option will return vectors describing the directed travel from one node to all other nodes. Similarly, the 'many2one' option will return vectors describing the directed travel from all nodes to a given node. See the table in the note below for details.
fromNodeID: int, Optional, default as None
Specifies the node ID (from the `id` column of the input `nodes` dataframe) of the origin node. This parameter is required for the 'one2many' matrix type; it is ignored by all other matrix types. See the table in the note below for details.
toNodeID: int, Optional, default as None
Specifies the node ID (from the `id` column of the input `nodes` dataframe) of the destination node. This parameter is required for the 'many2one' matrix type; it is ignored for all other matrix types. See the table in the note below for details.
takeoffSpeedMPS: float, Conditional, default as None
The speed of the aircraft, in meters per second, during the "takeoff" phase. This will apply only to 'square' and 'trapezoidal' route types. The takeoff phase is the first component of these route types, and is associated with an increase in altitude. The takeoff speed is assumed to be constant, and ignores acceleration. See :ref:`Flight Profile and Flight Path` for additional information.
cruiseSpeedMPS: float, Conditional, default as None
The speed of the aircraft, in meters per second, during the "cruising" phase. This will apply to all of the route options. Typically, the cruising phase occurs at a constant altitude, as specified by `cruiseAltMetersAGL`. However, for the 'triangular' route type, cruiseSpeedMPS specifies the constant travel speed during both the ascent to, and immediate descent from, the cruise altitude. In the 'triangle' route type, the aircraft has no horizontal travel at the cruise altitude. In all cases, the cruise speed is assumed to be constant, and ignores acceleration. See :ref:`Flight Profile and Flight Path` for additional information.
landSpeedMPS: float, Conditional, default as None
The speed of the aircraft, in meters per second, during the "landing" phase. This will apply to only the 'square' and 'trapezoidal' route types. The landing phase is the last component of these route types, and is associated with a decrease in altitude. The landing speed is assumed to be constant, and ignore deceleration. See :ref:`Flight Profile and Flight Path` for additional information.
cruiseAltMetersAGL: float, Conditional, default as None
The altitude, in meters above ground level, at which the aircraft is in the "cruise" phase. This phase is typically associated with horizontal movement at a fixed altitude. The exception is for the 'triangular' route type, in which case the aircraft instantaneously transitions from ascent to descent at the cruise altitude (i.e., there is no horizontal travel at this altitude). All but the 'straight' route type require/use the cruise altitude. See :ref:`Flight Profile and Flight Path` for additional details.
routeType: string, Optional, default as 'square'
Specifies the basic shape of the flight profile. Valid options include 'square', 'triangular', 'trapezoidal', and 'straight'. The square profile involves a vertical takeoff to a cruising altitude, horizontal travel at the cruising altitude, and a vertical landing. The trapezoidal profile describes a takeoff phase in which the aircraft increases altitude and travels horizontally towards the destination until reaching the cruising altitude, horizontal travel at the cruising altitude, and a landing phase in which the aircraft decreases altitude and travels horizontally until reaching the destination. For the trapezoidal profile, the horizontal movement during the takeoff and landing phases is a function of the `climbRateMPS` and `descentRateMPS`, respectively. The triangular profile describes an ascent to the cruising altitude followed immediately by a descent to the destination. Finally, the straight profile describes straight-line flight directly from the starting location to the ending location; the altitudes of these two locations may differ. See :ref:`Flight Profile and Flight Path` for a description of these flight profiles.
climbRateMPS: float, Conditional, default as None
This parameter is used only for the 'trapezoidal' route type, and is in units of meters per second. It describes the rate at which the aircraft increases its altitude, relative to the value of `takeoffSpeedMPS`. If `climbRateMPS == takeoffSpeedMPS`, then the takeoff phase will be purely vertical. If `climbRateMPS` is close to zero, then the takeoff phase will be characterized by a slow increase in altitude (and longer horizontal flight). The aircraft's actual travel speed during the climb will be `takeoffSpeedMPS`. See :ref:`Flight Profile and Flight Path` for additional details.
descentRateMPS: float, Conditional, default as None
This parameter is used only for the 'trapezoidal' route type, and is in units of meters per second. It describes the rate at which the aircraft decreases its altitude, relative to the value of `landSpeedMPS`. If `descentRateMPS == landSpeedMPS`, then the landing phase will be purely vertical. If `descentRateMPS` is close to zero, then the landing phase will be characterized by a slow decrease in altitude (and longer horizontal flight). The aircraft's actual travel speed during the descent will be `landSpeedMPS`. See :ref:`Flight Profile and Flight Path` for additional details.
outputDistUnits: string, Optional, default as 'meters'
Specifies the desired distance units for the function's output. Valid values are 'meters', 'm', 'kilometers', 'km', 'miles', 'mi', 'feet', 'ft', 'nm', and 'nmi' (nautical miles). See :ref:`Units` for options and abbreviations.
outputTimeUnits: string, Optional, default as 'seconds'
Specifies the desired time units for the function's output. Valid values are 'seconds', 'hours', and 'minutes'. See :ref:`Units` for options and abbreviations.
Returns
-------
totalTime: dictionary
A Python dictionary containing travel times. Time units are defined by `outputTimeUnits`. The format of key values is: `(fromID, toID)`. The travel time from ID 1 to ID 2 is provided by `time[1, 2]`.
totalGroundDistance: dictionary
A Python dictionary containing ground travel distances (i.e., ignoring any vertical distances). Distance units are defined by `outputDistUnits`. The format of key values is: `(fromID, toID)`. The horizontal-only travel distance from ID 1 to ID 2 is provided by `totalGroundDistance[1, 2]`.
totalFlightDistance: dictionary
A Python dictionary containing total travel distances (i.e., including both the horizontal and vertical components of flight). Distance units are defined by `outputDistUnits`. The format of key values is: `(fromID, toID)`. The total travel distance from ID 1 to ID 2 is provided by `totalFlightDistance[1, 2]`.
Note
----
For `matrixType`, the options are 'all2all', 'one2many', and 'many2one'.
+----------------------+--------------+------------+------------------+
| `matrixType` options | `fromNodeID` | `toNodeID` | Return type |
+======================+==============+============+==================+
| 'all2all' | ignored | ignored | Square matrices |
+----------------------+--------------+------------+------------------+
| 'one2many' | required | ignored | Row vectors |
+----------------------+--------------+------------+------------------+
| 'many2one' | ignored | required | Column vectors |
+----------------------+--------------+------------+------------------+
In 'all2all', square matrices will be generated for all node pairs in the
provided `nodes` dataframe.
In 'one2many', a node `id` will be assigned in the `fromNodeID` field, which
comes from the `id` column in the provided `nodes` dataframe.
Row vectors will be returned for the time and distance from that node
to all the nodes in the provided `nodes` dataframe.
In 'many2one', column vectors will be returned for the time and distance
from all nodes in the provided `nodes` dataframe to the node indicated
by `toNodeID`.
Examples
--------
Import veroviz and check if the version is up-to-date
>>> import veroviz as vrv
>>> vrv.checkVersion()
Generate a :ref:`Nodes` dataframe from a list of coordinates. See :meth:`~veroviz.generateNodes.generateNodes` for other methods to generate "nodes" dataframes.
>>> locs = [
... [42.1538, -78.4253],
... [42.3465, -78.6234],
... [42.6343, -78.1146]]
>>> exampleNodes = vrv.createNodesFromLocs(locs=locs)
Example 1 - Calculate 'all2all' travel matrices for a drone with a 'square' flight profile. There are 3 nodes, so the matrices will be 3x3.
>>> [totalTime, totalGroundDistance, totalFlightDistance] = vrv.getTimeDist3D(
... nodes = exampleNodes,
... routeType = 'square',
... cruiseAltMetersAGL = 120,
... takeoffSpeedMPS = 5,
... cruiseSpeedMPS = 12,
... landSpeedMPS = 2,
... outputDistUnits = 'meters',
... outputTimeUnits = 'seconds')
>>> print("Travel time from node 2 to node 3 is %.2f seconds" % (totalTime[2, 3]))
>>> print("Ground distance from node 2 to node 3 is %.2f meters" % (totalGroundDistance[2, 3]))
>>> print("Total flight distance from node 2 to node 3 is %.2f meters" % (totalFlightDistance[2, 3]))
Example 2 - Calculate 'one2many' travel matrices for a drone with a 'trapezoidal' flight profile, starting from node 2. All functional arguments are included in this example.
>>> [timeSec, groundDist, totalDist] = vrv.getTimeDist3D(
... nodes = exampleNodes,
... matrixType = 'one2many',
... fromNodeID = 2,
... toNodeID = None,
... takeoffSpeedMPS = 5,
... cruiseSpeedMPS = 12,
... landSpeedMPS = 5,
... cruiseAltMetersAGL = 120,
... routeType = 'trapezoidal',
... climbRateMPS = 1,
... descentRateMPS = 1,
... outputDistUnits = 'meters',
... outputTimeUnits = 'seconds')
>>> print("Travel time from node 2 to node 3 is %.2f seconds" % (timeSec[2, 3]))
>>> print("Ground distance from node 2 to node 3 is %.2f meters" % (groundDist[2, 3]))
>>> print("Total flight distance from node 2 to node 3 is %.2f meters" % (totalDist[2, 3]))
"""
# validation
[valFlag, errorMsg, warningMsg] = valGetTimeDist3D(nodes, matrixType, fromNodeID, toNodeID, outputDistUnits, outputTimeUnits, routeType, takeoffSpeedMPS, climbRateMPS, cruiseSpeedMPS, cruiseAltMetersAGL, landSpeedMPS, descentRateMPS)
if (not valFlag):
print (errorMsg)
return [None, None, None]
elif (config['VRV_SETTING_SHOWWARNINGMESSAGE'] and warningMsg != ""):
print (warningMsg)
try:
matrixType = matrixType.lower()
except:
pass
# Specify the list of rows and columns of output dataframes
fromIDs = []
toIDs = []
if (matrixType == "all2all"):
fromIDs = nodes['id'].tolist()
toIDs = nodes['id'].tolist()
elif (matrixType == "one2many"):
fromIDs = [fromNodeID]
toIDs = nodes['id'].tolist()
elif (matrixType == "many2one"):
fromIDs = nodes['id'].tolist()
toIDs = [toNodeID]
else:
return
# Specify the list of coordinations, for each coordinate, it is in [lat, lon, alt] format
fromLocs = []
toLocs = []
for i in range(0, len(fromIDs)):
fromLocs.append([
float(nodes.loc[nodes['id'] == fromIDs[i], 'lat']),
float(nodes.loc[nodes['id'] == fromIDs[i], 'lon']),
float(nodes.loc[nodes['id'] == fromIDs[i], 'altMeters'])])
for i in range(0, len(toIDs)):
toLocs.append([
float(nodes.loc[nodes['id'] == toIDs[i], 'lat']),
float(nodes.loc[nodes['id'] == toIDs[i], 'lon']),
float(nodes.loc[nodes['id'] == toIDs[i], 'altMeters'])])
# Do queries to find DICTIONARIES of distance and time matrices
totalTimeSec = {}
totalGroundDistMeters = {}
totalFlightDistMeters = {}
for i in range(len(fromLocs)):
for j in range(i, len(toLocs)):
# Prepare for fields to generate flight
startLoc = fromLocs[i]
endLoc = toLocs[j]
if (i != j):
# The flight has no loitering
flight = buildNoLoiteringFlight(routeType, startLoc, cruiseAltMetersAGL, endLoc, takeoffSpeedMPS, climbRateMPS, cruiseSpeedMPS, landSpeedMPS, descentRateMPS)
# Time and ground/flight distance, notice the matrix is symmetric
[time, groundDistance, flightDistance] = getTimeDistFromFlight(flight.copy())
totalTimeSec[i, j] = time
totalTimeSec[j, i] = time
totalGroundDistMeters[i, j] = groundDistance
totalGroundDistMeters[j, i] = groundDistance
totalFlightDistMeters[i, j] = flightDistance
totalFlightDistMeters[j, i] = flightDistance
else:
totalTimeSec[i, j] = 0
totalGroundDistMeters[i, j] = 0
totalFlightDistMeters[i, j] = 0
# Rename the keyvalues by fromRows and toCols and reset output units
totalTime = {}
totalGroundDistance = {}
totalFlightDistance = {}
for i in range(len(fromIDs)):
for j in range(len(toIDs)):
totalTime[fromIDs[i], toIDs[j]] = totalTimeSec[i, j] * privConvertTime(1.0, 's', outputTimeUnits)
totalGroundDistance[fromIDs[i], toIDs[j]] = totalGroundDistMeters[i, j] * privConvertDistance(1.0, 'm', outputDistUnits)
totalFlightDistance[fromIDs[i], toIDs[j]] = totalFlightDistMeters[i, j] * privConvertDistance(1.0, 'm', outputDistUnits)
return [totalTime, totalGroundDistance, totalFlightDistance]
| 71.865385 | 1,154 | 0.711466 | from veroviz._common import *
from veroviz._validation import *
from veroviz._buildFlightProfile import buildNoLoiteringFlight
from veroviz._buildFlightProfile import getTimeDistFromFlight
from veroviz._utilities import privConvertDistance
from veroviz._utilities import privConvertTime
def getTimeDist3D(nodes=None, matrixType='all2all', fromNodeID=None, toNodeID=None, takeoffSpeedMPS=None, cruiseSpeedMPS=None, landSpeedMPS=None, cruiseAltMetersAGL=None,
routeType='square', climbRateMPS=None, descentRateMPS=None, outputDistUnits='meters', outputTimeUnits='seconds'):
[valFlag, errorMsg, warningMsg] = valGetTimeDist3D(nodes, matrixType, fromNodeID, toNodeID, outputDistUnits, outputTimeUnits, routeType, takeoffSpeedMPS, climbRateMPS, cruiseSpeedMPS, cruiseAltMetersAGL, landSpeedMPS, descentRateMPS)
if (not valFlag):
print (errorMsg)
return [None, None, None]
elif (config['VRV_SETTING_SHOWWARNINGMESSAGE'] and warningMsg != ""):
print (warningMsg)
try:
matrixType = matrixType.lower()
except:
pass
fromIDs = []
toIDs = []
if (matrixType == "all2all"):
fromIDs = nodes['id'].tolist()
toIDs = nodes['id'].tolist()
elif (matrixType == "one2many"):
fromIDs = [fromNodeID]
toIDs = nodes['id'].tolist()
elif (matrixType == "many2one"):
fromIDs = nodes['id'].tolist()
toIDs = [toNodeID]
else:
return
fromLocs = []
toLocs = []
for i in range(0, len(fromIDs)):
fromLocs.append([
float(nodes.loc[nodes['id'] == fromIDs[i], 'lat']),
float(nodes.loc[nodes['id'] == fromIDs[i], 'lon']),
float(nodes.loc[nodes['id'] == fromIDs[i], 'altMeters'])])
for i in range(0, len(toIDs)):
toLocs.append([
float(nodes.loc[nodes['id'] == toIDs[i], 'lat']),
float(nodes.loc[nodes['id'] == toIDs[i], 'lon']),
float(nodes.loc[nodes['id'] == toIDs[i], 'altMeters'])])
totalTimeSec = {}
totalGroundDistMeters = {}
totalFlightDistMeters = {}
for i in range(len(fromLocs)):
for j in range(i, len(toLocs)):
startLoc = fromLocs[i]
endLoc = toLocs[j]
if (i != j):
flight = buildNoLoiteringFlight(routeType, startLoc, cruiseAltMetersAGL, endLoc, takeoffSpeedMPS, climbRateMPS, cruiseSpeedMPS, landSpeedMPS, descentRateMPS)
[time, groundDistance, flightDistance] = getTimeDistFromFlight(flight.copy())
totalTimeSec[i, j] = time
totalTimeSec[j, i] = time
totalGroundDistMeters[i, j] = groundDistance
totalGroundDistMeters[j, i] = groundDistance
totalFlightDistMeters[i, j] = flightDistance
totalFlightDistMeters[j, i] = flightDistance
else:
totalTimeSec[i, j] = 0
totalGroundDistMeters[i, j] = 0
totalFlightDistMeters[i, j] = 0
totalTime = {}
totalGroundDistance = {}
totalFlightDistance = {}
for i in range(len(fromIDs)):
for j in range(len(toIDs)):
totalTime[fromIDs[i], toIDs[j]] = totalTimeSec[i, j] * privConvertTime(1.0, 's', outputTimeUnits)
totalGroundDistance[fromIDs[i], toIDs[j]] = totalGroundDistMeters[i, j] * privConvertDistance(1.0, 'm', outputDistUnits)
totalFlightDistance[fromIDs[i], toIDs[j]] = totalFlightDistMeters[i, j] * privConvertDistance(1.0, 'm', outputDistUnits)
return [totalTime, totalGroundDistance, totalFlightDistance]
| true | true |
f72f19389baf6383e97fcdeeb7e0ff036c8208a5 | 1,325 | py | Python | youtuatools/extractor/unity.py | Pagasis/YouTua | edb44b2065a7224f8b26aaf76166bf7287901567 | [
"MIT"
] | 47 | 2021-01-02T07:44:50.000Z | 2022-02-28T22:02:13.000Z | nextdl/extractor/unity.py | devenu85/nextdl | 0b458f556e2e0be80cb94bd9a9b1405ad2e9182d | [
"MIT"
] | 4 | 2021-02-07T03:35:13.000Z | 2021-10-31T19:23:53.000Z | nextdl/extractor/unity.py | devenu85/nextdl | 0b458f556e2e0be80cb94bd9a9b1405ad2e9182d | [
"MIT"
] | 8 | 2021-01-03T05:44:39.000Z | 2021-11-01T05:46:32.000Z | from __future__ import unicode_literals
from .common import InfoExtractor
from .youtube import YoutubeIE
class UnityIE(InfoExtractor):
_VALID_URL = (
r"https?://(?:www\.)?unity3d\.com/learn/tutorials/(?:[^/]+/)*(?P<id>[^/?#&]+)"
)
_TESTS = [
{
"url": "https://unity3d.com/learn/tutorials/topics/animation/animate-anything-mecanim",
"info_dict": {
"id": "jWuNtik0C8E",
"ext": "mp4",
"title": "Live Training 22nd September 2014 - Animate Anything",
"description": "md5:e54913114bd45a554c56cdde7669636e",
"duration": 2893,
"uploader": "Unity",
"uploader_id": "Unity3D",
"upload_date": "20140926",
},
},
{
"url": "https://unity3d.com/learn/tutorials/projects/2d-ufo-tutorial/following-player-camera?playlist=25844",
"only_matching": True,
},
]
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
youtube_id = self._search_regex(
r'data-video-id="([_0-9a-zA-Z-]+)"', webpage, "youtube ID"
)
return self.url_result(youtube_id, ie=YoutubeIE.ie_key(), video_id=video_id)
| 34.868421 | 121 | 0.556226 | from __future__ import unicode_literals
from .common import InfoExtractor
from .youtube import YoutubeIE
class UnityIE(InfoExtractor):
_VALID_URL = (
r"https?://(?:www\.)?unity3d\.com/learn/tutorials/(?:[^/]+/)*(?P<id>[^/?#&]+)"
)
_TESTS = [
{
"url": "https://unity3d.com/learn/tutorials/topics/animation/animate-anything-mecanim",
"info_dict": {
"id": "jWuNtik0C8E",
"ext": "mp4",
"title": "Live Training 22nd September 2014 - Animate Anything",
"description": "md5:e54913114bd45a554c56cdde7669636e",
"duration": 2893,
"uploader": "Unity",
"uploader_id": "Unity3D",
"upload_date": "20140926",
},
},
{
"url": "https://unity3d.com/learn/tutorials/projects/2d-ufo-tutorial/following-player-camera?playlist=25844",
"only_matching": True,
},
]
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
youtube_id = self._search_regex(
r'data-video-id="([_0-9a-zA-Z-]+)"', webpage, "youtube ID"
)
return self.url_result(youtube_id, ie=YoutubeIE.ie_key(), video_id=video_id)
| true | true |
f72f19778b0b87aa95ac05b779fa868ad2422b2a | 256 | py | Python | pybat/__init__.py | mbercx/pybat | e0cf610fd06a97979f5ec70757406de1f9a788ef | [
"MIT"
] | 3 | 2019-04-08T13:10:15.000Z | 2021-07-04T07:23:49.000Z | pybat/__init__.py | mbercx/pybat | e0cf610fd06a97979f5ec70757406de1f9a788ef | [
"MIT"
] | 1 | 2019-02-28T12:51:57.000Z | 2019-02-28T12:51:57.000Z | pybat/__init__.py | mbercx/pybat | e0cf610fd06a97979f5ec70757406de1f9a788ef | [
"MIT"
] | 4 | 2018-07-30T12:58:35.000Z | 2020-03-05T20:09:46.000Z | # These import commands make importing core classes easier, e.g. you can just import
# Cathode using:
#
# from pybat import Cathode
#
# Instead of:
#
# from pybat.core import Cathode
#
from pybat.core import Cathode, LiRichCathode, Dimer, DimerNEBAnalysis
| 23.272727 | 84 | 0.765625 |
from pybat.core import Cathode, LiRichCathode, Dimer, DimerNEBAnalysis
| true | true |
f72f19dca994b161669b0dcdd2b3c6e2c7ce4f8d | 308 | py | Python | src/scripts/chmTools/module.py | Matej-Chmel/approximate-knn | 4d29dc285f50fcdce1c3052472959f789c46cc70 | [
"MIT"
] | null | null | null | src/scripts/chmTools/module.py | Matej-Chmel/approximate-knn | 4d29dc285f50fcdce1c3052472959f789c46cc70 | [
"MIT"
] | null | null | null | src/scripts/chmTools/module.py | Matej-Chmel/approximate-knn | 4d29dc285f50fcdce1c3052472959f789c46cc70 | [
"MIT"
] | null | null | null | from .runner import AppError, checkInsideVenv, insideVenv, wrapMain
checkInsideVenv()
from .configParam import getConfigPath
from .Dataset import Dataset
from .export import getExportedData
from .jsonTypeCheck import configStr, getDictValue, getRoot
from .RecallTable import RecallTable, RecallTableConfig
| 30.8 | 67 | 0.847403 | from .runner import AppError, checkInsideVenv, insideVenv, wrapMain
checkInsideVenv()
from .configParam import getConfigPath
from .Dataset import Dataset
from .export import getExportedData
from .jsonTypeCheck import configStr, getDictValue, getRoot
from .RecallTable import RecallTable, RecallTableConfig
| true | true |
f72f1ae9e9ef3f419c5a8e7fe69af1c394dd4b59 | 285 | py | Python | exercicios/ex020.py | MaikolSantos/curso-em-video-python3 | 3a1ab2761b8a0f98e128083a7b0e50b19a75b7bf | [
"MIT"
] | null | null | null | exercicios/ex020.py | MaikolSantos/curso-em-video-python3 | 3a1ab2761b8a0f98e128083a7b0e50b19a75b7bf | [
"MIT"
] | null | null | null | exercicios/ex020.py | MaikolSantos/curso-em-video-python3 | 3a1ab2761b8a0f98e128083a7b0e50b19a75b7bf | [
"MIT"
] | null | null | null | from random import shuffle
a1 = input('Digite o nome do Aluno 1: ')
a2 = input('Digite o nome do Aluno 2: ')
a3 = input('Digite o nome do Aluno 3: ')
a4 = input('Digite o nome do Aluno 4: ')
deck = [a1, a2, a3, a4]
shuffle(deck)
print('A ordem de apresentação será: {}'.format(deck))
| 28.5 | 54 | 0.663158 | from random import shuffle
a1 = input('Digite o nome do Aluno 1: ')
a2 = input('Digite o nome do Aluno 2: ')
a3 = input('Digite o nome do Aluno 3: ')
a4 = input('Digite o nome do Aluno 4: ')
deck = [a1, a2, a3, a4]
shuffle(deck)
print('A ordem de apresentação será: {}'.format(deck))
| true | true |
f72f1bae0e6194d644c89e50750e438c176f29ce | 1,867 | py | Python | service/es_utils.py | LandRegistry/digital-register-elasticsearch-updater | 2e7b95d8d5eac70e9bba6612bed09bf58376e781 | [
"MIT"
] | null | null | null | service/es_utils.py | LandRegistry/digital-register-elasticsearch-updater | 2e7b95d8d5eac70e9bba6612bed09bf58376e781 | [
"MIT"
] | 12 | 2015-06-05T15:10:25.000Z | 2016-04-21T15:17:19.000Z | service/es_utils.py | LandRegistry/digital-register-elasticsearch-updater | 2e7b95d8d5eac70e9bba6612bed09bf58376e781 | [
"MIT"
] | 1 | 2021-04-11T06:03:41.000Z | 2021-04-11T06:03:41.000Z | from elasticsearch import Elasticsearch # type: ignore
from elasticsearch.client import IndicesClient # type: ignore
from elasticsearch.helpers import bulk # type: ignore
import logging
from config import CONFIG_DICT
LOGGER = logging.getLogger(__name__)
ELASTICSEARCH_NODES = [CONFIG_DICT['ELASTICSEARCH_URI']]
elasticsearch_client = Elasticsearch(ELASTICSEARCH_NODES)
indices_client = IndicesClient(elasticsearch_client)
def ensure_mapping_exists(index_name, doc_type, mapping):
if index_name not in elasticsearch_client.indices.status()['indices']:
LOGGER.info(
"Index '{}' not found in elasticsearch. Creating...".format(index_name)
)
elasticsearch_client.index(index=index_name, doc_type=doc_type, body={})
else:
LOGGER.info("Index '{}' with doc type '{}' already exists".format(index_name, doc_type))
LOGGER.info("Ensuring mapping exists for index '{}', doc type '{}'".format(
index_name, doc_type
))
indices_client.put_mapping(
index=index_name, doc_type=doc_type, body=mapping,
)
def execute_elasticsearch_actions(actions):
return bulk(elasticsearch_client, actions)
def search(query_dict, index_name, doc_type):
result = elasticsearch_client.search(
index=index_name, doc_type=doc_type, body=query_dict
)
return result['hits']['hits']
def get_upsert_action(index_name, doc_type, document, id):
return {
'doc_as_upsert': True,
'_op_type': 'update',
'_index': index_name,
'_type': doc_type,
'_id': id,
'doc': document,
}
def get_delete_action(index_name, doc_type, id):
return {
'_op_type': 'delete',
'_index': index_name,
'_type': doc_type,
'_id': id,
}
def get_cluster_info():
return elasticsearch_client.info()
| 26.671429 | 96 | 0.681843 | from elasticsearch import Elasticsearch
from elasticsearch.client import IndicesClient
from elasticsearch.helpers import bulk
import logging
from config import CONFIG_DICT
LOGGER = logging.getLogger(__name__)
ELASTICSEARCH_NODES = [CONFIG_DICT['ELASTICSEARCH_URI']]
elasticsearch_client = Elasticsearch(ELASTICSEARCH_NODES)
indices_client = IndicesClient(elasticsearch_client)
def ensure_mapping_exists(index_name, doc_type, mapping):
if index_name not in elasticsearch_client.indices.status()['indices']:
LOGGER.info(
"Index '{}' not found in elasticsearch. Creating...".format(index_name)
)
elasticsearch_client.index(index=index_name, doc_type=doc_type, body={})
else:
LOGGER.info("Index '{}' with doc type '{}' already exists".format(index_name, doc_type))
LOGGER.info("Ensuring mapping exists for index '{}', doc type '{}'".format(
index_name, doc_type
))
indices_client.put_mapping(
index=index_name, doc_type=doc_type, body=mapping,
)
def execute_elasticsearch_actions(actions):
return bulk(elasticsearch_client, actions)
def search(query_dict, index_name, doc_type):
result = elasticsearch_client.search(
index=index_name, doc_type=doc_type, body=query_dict
)
return result['hits']['hits']
def get_upsert_action(index_name, doc_type, document, id):
return {
'doc_as_upsert': True,
'_op_type': 'update',
'_index': index_name,
'_type': doc_type,
'_id': id,
'doc': document,
}
def get_delete_action(index_name, doc_type, id):
return {
'_op_type': 'delete',
'_index': index_name,
'_type': doc_type,
'_id': id,
}
def get_cluster_info():
return elasticsearch_client.info()
| true | true |
f72f1bee9e17f5e0644db620d7e3407dcb35a5dc | 716 | py | Python | src/pre_R1956001.py | atrettel/sheardata | db09d70ba464e24bdb2fb7729b6f3e905af68d72 | [
"MIT"
] | 2 | 2020-04-27T19:56:07.000Z | 2022-02-27T22:16:19.000Z | src/pre_R1956001.py | atrettel/sheardata | db09d70ba464e24bdb2fb7729b6f3e905af68d72 | [
"MIT"
] | null | null | null | src/pre_R1956001.py | atrettel/sheardata | db09d70ba464e24bdb2fb7729b6f3e905af68d72 | [
"MIT"
] | 1 | 2021-11-05T18:39:35.000Z | 2021-11-05T18:39:35.000Z | #!/usr/bin/env python3
# Copyright (C) 2020-2021 Andrew Trettel
#
# SPDX-License-Identifier: MIT
import csv
import math
import sqlite3
import sheardata as sd
import sys
conn = sqlite3.connect( sys.argv[1] )
cursor = conn.cursor()
cursor.execute( "PRAGMA foreign_keys = ON;" )
flow_class = sd.FC_BOUNDARY_DRIVEN_FLOW
year = 1956
study_number = 1
study_id = sd.add_study(
cursor,
flow_class_id=flow_class,
year=year,
study_number=study_number,
study_type_id=sd.ST_EXPERIMENT,
)
sd.add_study_source( cursor, study_id, "ReichardtH+1956+deu+JOUR", sd.PRIMARY_SOURCE )
sd.add_study_source( cursor, study_id, "ReichardtH+1959+deu+RPRT", sd.PRIMARY_SOURCE )
conn.commit()
conn.close()
| 21.058824 | 86 | 0.736034 |
import csv
import math
import sqlite3
import sheardata as sd
import sys
conn = sqlite3.connect( sys.argv[1] )
cursor = conn.cursor()
cursor.execute( "PRAGMA foreign_keys = ON;" )
flow_class = sd.FC_BOUNDARY_DRIVEN_FLOW
year = 1956
study_number = 1
study_id = sd.add_study(
cursor,
flow_class_id=flow_class,
year=year,
study_number=study_number,
study_type_id=sd.ST_EXPERIMENT,
)
sd.add_study_source( cursor, study_id, "ReichardtH+1956+deu+JOUR", sd.PRIMARY_SOURCE )
sd.add_study_source( cursor, study_id, "ReichardtH+1959+deu+RPRT", sd.PRIMARY_SOURCE )
conn.commit()
conn.close()
| true | true |
f72f1c4792e80f4b2c6d910802fa3060425bf488 | 8,356 | py | Python | pythonExamples/fileIngestModule.py | trac3me/autopsy | ff70cdd19bfad1b4966c5e25933035daba132535 | [
"Apache-2.0"
] | 1 | 2015-01-31T19:20:43.000Z | 2015-01-31T19:20:43.000Z | pythonExamples/fileIngestModule.py | trac3me/autopsy | ff70cdd19bfad1b4966c5e25933035daba132535 | [
"Apache-2.0"
] | null | null | null | pythonExamples/fileIngestModule.py | trac3me/autopsy | ff70cdd19bfad1b4966c5e25933035daba132535 | [
"Apache-2.0"
] | null | null | null | # Sample module in the public domain. Feel free to use this as a template
# for your modules (and you can remove this header and take complete credit
# and liability)
#
# Contact: Brian Carrier [carrier <at> sleuthkit [dot] org]
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
# Simple file-level ingest module for Autopsy.
# Search for TODO for the things that you need to change
# See http://sleuthkit.org/autopsy/docs/api-docs/latest/index.html for documentation
import jarray
import inspect
from java.lang import System
from java.util.logging import Level
from org.sleuthkit.datamodel import Score
from org.sleuthkit.datamodel import SleuthkitCase
from org.sleuthkit.datamodel import AbstractFile
from org.sleuthkit.datamodel import ReadContentInputStream
from org.sleuthkit.datamodel import BlackboardArtifact
from org.sleuthkit.datamodel import BlackboardAttribute
from org.sleuthkit.datamodel import TskData
from org.sleuthkit.autopsy.ingest import IngestModule
from org.sleuthkit.autopsy.ingest.IngestModule import IngestModuleException
from org.sleuthkit.autopsy.ingest import DataSourceIngestModule
from org.sleuthkit.autopsy.ingest import FileIngestModule
from org.sleuthkit.autopsy.ingest import IngestModuleFactoryAdapter
from org.sleuthkit.autopsy.ingest import IngestMessage
from org.sleuthkit.autopsy.ingest import IngestServices
from org.sleuthkit.autopsy.ingest import ModuleDataEvent
from org.sleuthkit.autopsy.coreutils import Logger
from org.sleuthkit.autopsy.casemodule import Case
from org.sleuthkit.autopsy.casemodule.services import Services
from org.sleuthkit.autopsy.casemodule.services import FileManager
from org.sleuthkit.autopsy.casemodule.services import Blackboard
from java.util import Arrays
# Factory that defines the name and details of the module and allows Autopsy
# to create instances of the modules that will do the anlaysis.
# TODO: Rename this to something more specific. Search and replace for it because it is used a few times
class SampleJythonFileIngestModuleFactory(IngestModuleFactoryAdapter):
# TODO: give it a unique name. Will be shown in module list, logs, etc.
moduleName = "Sample file ingest Module"
def getModuleDisplayName(self):
return self.moduleName
# TODO: Give it a description
def getModuleDescription(self):
return "Sample module that does X, Y, and Z."
def getModuleVersionNumber(self):
return "1.0"
# Return true if module wants to get called for each file
def isFileIngestModuleFactory(self):
return True
# can return null if isFileIngestModuleFactory returns false
def createFileIngestModule(self, ingestOptions):
return SampleJythonFileIngestModule()
# File-level ingest module. One gets created per thread.
# TODO: Rename this to something more specific. Could just remove "Factory" from above name.
# Looks at the attributes of the passed in file.
class SampleJythonFileIngestModule(FileIngestModule):
_logger = Logger.getLogger(SampleJythonFileIngestModuleFactory.moduleName)
def log(self, level, msg):
self._logger.logp(level, self.__class__.__name__, inspect.stack()[1][3], msg)
# Where any setup and configuration is done
# 'context' is an instance of org.sleuthkit.autopsy.ingest.IngestJobContext.
# See: http://sleuthkit.org/autopsy/docs/api-docs/latest/classorg_1_1sleuthkit_1_1autopsy_1_1ingest_1_1_ingest_job_context.html
# TODO: Add any setup code that you need here.
def startUp(self, context):
self.filesFound = 0
# Throw an IngestModule.IngestModuleException exception if there was a problem setting up
# raise IngestModuleException("Oh No!")
pass
# Where the analysis is done. Each file will be passed into here.
# The 'file' object being passed in is of type org.sleuthkit.datamodel.AbstractFile.
# See: http://www.sleuthkit.org/sleuthkit/docs/jni-docs/latest/classorg_1_1sleuthkit_1_1datamodel_1_1_abstract_file.html
# TODO: Add your analysis code in here.
def process(self, file):
# Skip non-files
if ((file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNALLOC_BLOCKS) or
(file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNUSED_BLOCKS) or
(file.isFile() == False)):
return IngestModule.ProcessResult.OK
# Use blackboard class to index blackboard artifacts for keyword search
blackboard = Case.getCurrentCase().getSleuthkitCase().getBlackboard()
# For an example, we will flag files with .txt in the name and make a blackboard artifact.
if file.getName().lower().endswith(".txt"):
self.log(Level.INFO, "Found a text file: " + file.getName())
self.filesFound+=1
# Make an artifact on the blackboard. TSK_INTERESTING_FILE_HIT is a generic type of
# artifact. Refer to the developer docs for other examples.
attrs = Arrays.asList(BlackboardAttribute(BlackboardAttribute.Type.TSK_SET_NAME,
SampleJythonFileIngestModuleFactory.moduleName, "Text Files"))
art = file.newAnalysisResult(BlackboardArtifact.Type.TSK_INTERESTING_FILE_HIT, Score.SCORE_LIKELY_NOTABLE,
None, "Text Files", None, attrs).getAnalysisResult()
try:
# post the artifact for listeners of artifact events
blackboard.postArtifact(art, SampleJythonFileIngestModuleFactory.moduleName)
except Blackboard.BlackboardException as e:
self.log(Level.SEVERE, "Error indexing artifact " + art.getDisplayName())
# For the example (this wouldn't be needed normally), we'll query the blackboard for data that was added
# by other modules. We then iterate over its attributes. We'll just print them, but you would probably
# want to do something with them.
artifactList = file.getArtifacts(BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_FILE_HIT)
for artifact in artifactList:
attributeList = artifact.getAttributes()
for attrib in attributeList:
self.log(Level.INFO, attrib.toString())
# To further the example, this code will read the contents of the file and count the number of bytes
inputStream = ReadContentInputStream(file)
buffer = jarray.zeros(1024, "b")
totLen = 0
len = inputStream.read(buffer)
while (len != -1):
totLen = totLen + len
len = inputStream.read(buffer)
return IngestModule.ProcessResult.OK
# Where any shutdown code is run and resources are freed.
# TODO: Add any shutdown code that you need here.
def shutDown(self):
# As a final part of this example, we'll send a message to the ingest inbox with the number of files found (in this thread)
message = IngestMessage.createMessage(
IngestMessage.MessageType.DATA, SampleJythonFileIngestModuleFactory.moduleName,
str(self.filesFound) + " files found")
ingestServices = IngestServices.getInstance().postMessage(message) | 49.443787 | 131 | 0.732049 |
import jarray
import inspect
from java.lang import System
from java.util.logging import Level
from org.sleuthkit.datamodel import Score
from org.sleuthkit.datamodel import SleuthkitCase
from org.sleuthkit.datamodel import AbstractFile
from org.sleuthkit.datamodel import ReadContentInputStream
from org.sleuthkit.datamodel import BlackboardArtifact
from org.sleuthkit.datamodel import BlackboardAttribute
from org.sleuthkit.datamodel import TskData
from org.sleuthkit.autopsy.ingest import IngestModule
from org.sleuthkit.autopsy.ingest.IngestModule import IngestModuleException
from org.sleuthkit.autopsy.ingest import DataSourceIngestModule
from org.sleuthkit.autopsy.ingest import FileIngestModule
from org.sleuthkit.autopsy.ingest import IngestModuleFactoryAdapter
from org.sleuthkit.autopsy.ingest import IngestMessage
from org.sleuthkit.autopsy.ingest import IngestServices
from org.sleuthkit.autopsy.ingest import ModuleDataEvent
from org.sleuthkit.autopsy.coreutils import Logger
from org.sleuthkit.autopsy.casemodule import Case
from org.sleuthkit.autopsy.casemodule.services import Services
from org.sleuthkit.autopsy.casemodule.services import FileManager
from org.sleuthkit.autopsy.casemodule.services import Blackboard
from java.util import Arrays
class SampleJythonFileIngestModuleFactory(IngestModuleFactoryAdapter):
moduleName = "Sample file ingest Module"
def getModuleDisplayName(self):
return self.moduleName
def getModuleDescription(self):
return "Sample module that does X, Y, and Z."
def getModuleVersionNumber(self):
return "1.0"
def isFileIngestModuleFactory(self):
return True
def createFileIngestModule(self, ingestOptions):
return SampleJythonFileIngestModule()
class SampleJythonFileIngestModule(FileIngestModule):
_logger = Logger.getLogger(SampleJythonFileIngestModuleFactory.moduleName)
def log(self, level, msg):
self._logger.logp(level, self.__class__.__name__, inspect.stack()[1][3], msg)
def startUp(self, context):
self.filesFound = 0
pass
def process(self, file):
if ((file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNALLOC_BLOCKS) or
(file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNUSED_BLOCKS) or
(file.isFile() == False)):
return IngestModule.ProcessResult.OK
blackboard = Case.getCurrentCase().getSleuthkitCase().getBlackboard()
if file.getName().lower().endswith(".txt"):
self.log(Level.INFO, "Found a text file: " + file.getName())
self.filesFound+=1
attrs = Arrays.asList(BlackboardAttribute(BlackboardAttribute.Type.TSK_SET_NAME,
SampleJythonFileIngestModuleFactory.moduleName, "Text Files"))
art = file.newAnalysisResult(BlackboardArtifact.Type.TSK_INTERESTING_FILE_HIT, Score.SCORE_LIKELY_NOTABLE,
None, "Text Files", None, attrs).getAnalysisResult()
try:
blackboard.postArtifact(art, SampleJythonFileIngestModuleFactory.moduleName)
except Blackboard.BlackboardException as e:
self.log(Level.SEVERE, "Error indexing artifact " + art.getDisplayName())
# want to do something with them.
artifactList = file.getArtifacts(BlackboardArtifact.ARTIFACT_TYPE.TSK_INTERESTING_FILE_HIT)
for artifact in artifactList:
attributeList = artifact.getAttributes()
for attrib in attributeList:
self.log(Level.INFO, attrib.toString())
# To further the example, this code will read the contents of the file and count the number of bytes
inputStream = ReadContentInputStream(file)
buffer = jarray.zeros(1024, "b")
totLen = 0
len = inputStream.read(buffer)
while (len != -1):
totLen = totLen + len
len = inputStream.read(buffer)
return IngestModule.ProcessResult.OK
# Where any shutdown code is run and resources are freed.
# TODO: Add any shutdown code that you need here.
def shutDown(self):
# As a final part of this example, we'll send a message to the ingest inbox with the number of files found (in this thread)
message = IngestMessage.createMessage(
IngestMessage.MessageType.DATA, SampleJythonFileIngestModuleFactory.moduleName,
str(self.filesFound) + " files found")
ingestServices = IngestServices.getInstance().postMessage(message) | true | true |
f72f1c9c7960ef51f7a686696065cb2abe68dd75 | 144 | py | Python | django_async_redis/__init__.py | adamchainz/django-async-redis | e9a54ba885fa76e504ff18726f333264585da34a | [
"Apache-2.0"
] | 14 | 2020-10-06T18:29:07.000Z | 2021-10-02T05:11:14.000Z | django_async_redis/__init__.py | adamchainz/django-async-redis | e9a54ba885fa76e504ff18726f333264585da34a | [
"Apache-2.0"
] | 4 | 2020-10-06T18:38:09.000Z | 2021-08-24T20:38:54.000Z | django_async_redis/__init__.py | adamchainz/django-async-redis | e9a54ba885fa76e504ff18726f333264585da34a | [
"Apache-2.0"
] | 4 | 2020-10-07T07:13:21.000Z | 2022-01-27T21:28:30.000Z | """Top-level package for Django Async Redis."""
__author__ = """Andrew Chen Wang"""
__email__ = "acwangpython@gmail.com"
__version__ = "0.1.0"
| 24 | 47 | 0.701389 |
__author__ = """Andrew Chen Wang"""
__email__ = "acwangpython@gmail.com"
__version__ = "0.1.0"
| true | true |
f72f1e8b1425ad70062469566557c13ef9b23423 | 16,879 | py | Python | models/transformer.py | Honghe/AnchorDETR | fc3d45441241cd689b28878d3aa4b0bffb33a8b8 | [
"Apache-2.0"
] | null | null | null | models/transformer.py | Honghe/AnchorDETR | fc3d45441241cd689b28878d3aa4b0bffb33a8b8 | [
"Apache-2.0"
] | null | null | null | models/transformer.py | Honghe/AnchorDETR | fc3d45441241cd689b28878d3aa4b0bffb33a8b8 | [
"Apache-2.0"
] | null | null | null | # ------------------------------------------------------------------------
# Copyright (c) 2021 megvii-model. All Rights Reserved.
# ------------------------------------------------------------------------
# Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR)
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# ------------------------------------------------------------------------
# Modified from DETR (https://github.com/facebookresearch/detr)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# ------------------------------------------------------------------------
import copy
from typing import Optional, List
import math
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from util.misc import inverse_sigmoid
from models.row_column_decoupled_attention import MultiheadRCDA
class Transformer(nn.Module):
def __init__(self, d_model=256, nhead=8,
num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=1024, dropout=0.,
activation="relu", num_feature_levels=3,num_query_position = 300,num_query_pattern=3,
spatial_prior="learned",attention_type="RCDA"):
super().__init__()
self.d_model = d_model
self.nhead = nhead
self.attention_type = attention_type
encoder_layer = TransformerEncoderLayerSpatial(d_model, dim_feedforward,
dropout, activation, nhead , attention_type)
encoder_layer_level = TransformerEncoderLayerLevel(d_model, dim_feedforward,
dropout, activation, nhead)
decoder_layer = TransformerDecoderLayer(d_model, dim_feedforward,
dropout, activation, nhead,
num_feature_levels, attention_type)
if num_feature_levels == 1:
self.num_encoder_layers_level = 0
else:
self.num_encoder_layers_level = num_encoder_layers // 2
self.num_encoder_layers_spatial = num_encoder_layers - self.num_encoder_layers_level
self.encoder_layers = _get_clones(encoder_layer, self.num_encoder_layers_spatial)
self.encoder_layers_level = _get_clones(encoder_layer_level, self.num_encoder_layers_level)
self.decoder_layers = _get_clones(decoder_layer, num_decoder_layers)
self.spatial_prior=spatial_prior
if num_feature_levels>1:
self.level_embed = nn.Embedding(num_feature_levels, d_model)
self.num_pattern = num_query_pattern
self.pattern = nn.Embedding(self.num_pattern, d_model)
self.num_position = num_query_position
if self.spatial_prior == "learned":
self.position = nn.Embedding(self.num_position, 2)
self.adapt_pos2d = nn.Sequential(
nn.Linear(d_model, d_model),
nn.ReLU(),
nn.Linear(d_model, d_model),
)
self.adapt_pos1d = nn.Sequential(
nn.Linear(d_model, d_model),
nn.ReLU(),
nn.Linear(d_model, d_model),
)
self.num_layers = num_decoder_layers
num_classes = 91
self.class_embed = nn.Linear(d_model, num_classes)
self.bbox_embed = MLP(d_model, d_model, 4, 3)
self._reset_parameters()
def _reset_parameters(self):
num_pred = self.num_layers
num_classes = 91
prior_prob = 0.01
bias_value = -math.log((1 - prior_prob) / prior_prob)
self.class_embed.bias.data = torch.ones(num_classes) * bias_value
nn.init.constant_(self.bbox_embed.layers[-1].weight.data, 0)
nn.init.constant_(self.bbox_embed.layers[-1].bias.data, 0)
if self.spatial_prior == "learned":
nn.init.uniform_(self.position.weight.data, 0, 1)
nn.init.constant_(self.bbox_embed.layers[-1].bias.data[2:], -2.0)
self.class_embed = nn.ModuleList([self.class_embed for _ in range(num_pred)])
self.bbox_embed = nn.ModuleList([self.bbox_embed for _ in range(num_pred)])
def forward(self, srcs, masks):
# prepare input for decoder
bs, l, c, h, w = srcs.shape
if self.spatial_prior == "learned":
reference_points = self.position.weight.unsqueeze(0).repeat(bs, self.num_pattern, 1)
elif self.spatial_prior == "grid":
nx=ny=round(math.sqrt(self.num_position))
self.num_position=nx*ny
x = (torch.arange(nx) + 0.5) / nx
y = (torch.arange(ny) + 0.5) / ny
xy=torch.meshgrid(x,y)
reference_points=torch.cat([xy[0].reshape(-1)[...,None],xy[1].reshape(-1)[...,None]],-1).cuda()
reference_points = reference_points.unsqueeze(0).repeat(bs, self.num_pattern, 1)
else:
raise ValueError(f'unknown {self.spatial_prior} spatial prior')
tgt = self.pattern.weight.reshape(1, self.num_pattern, 1, c).repeat(bs, 1, self.num_position, 1).reshape(
bs, self.num_pattern * self.num_position, c)
mask = masks[-1].unsqueeze(1).repeat(1,l,1,1).reshape(bs*l,h,w)
pos_col, pos_row = mask2pos(mask)
if self.attention_type=="RCDA":
posemb_row = self.adapt_pos1d(pos2posemb1d(pos_row))
posemb_col = self.adapt_pos1d(pos2posemb1d(pos_col))
posemb_2d = None
else:
pos_2d = torch.cat([pos_row.unsqueeze(1).repeat(1, h, 1).unsqueeze(-1), pos_col.unsqueeze(2).repeat(1, 1, w).unsqueeze(-1)],dim=-1)
posemb_2d = self.adapt_pos2d(pos2posemb2d(pos_2d))
posemb_row = posemb_col = None
outputs = srcs.reshape(bs * l, c, h, w)
for idx in range(len(self.encoder_layers)):
outputs = self.encoder_layers[idx](outputs, mask, posemb_row, posemb_col,posemb_2d)
if idx < self.num_encoder_layers_level:
outputs = self.encoder_layers_level[idx](outputs, level_emb=self.level_embed.weight.unsqueeze(1).unsqueeze(0).repeat(bs,1,1,1).reshape(bs*l,1,c))
srcs = outputs.reshape(bs, l, c, h, w)
output = tgt
outputs_classes = []
outputs_coords = []
for lid, layer in enumerate(self.decoder_layers):
output = layer(output, reference_points, srcs, mask, adapt_pos2d=self.adapt_pos2d,
adapt_pos1d=self.adapt_pos1d, posemb_row=posemb_row, posemb_col=posemb_col,posemb_2d=posemb_2d)
reference = inverse_sigmoid(reference_points)
outputs_class = self.class_embed[lid](output)
tmp = self.bbox_embed[lid](output)
if reference.shape[-1] == 4:
tmp += reference
else:
assert reference.shape[-1] == 2
tmp[..., :2] += reference
outputs_coord = tmp.sigmoid()
outputs_classes.append(outputs_class[None,])
outputs_coords.append(outputs_coord[None,])
output = torch.cat(outputs_classes, dim=0), torch.cat(outputs_coords, dim=0)
return output
class TransformerEncoderLayerSpatial(nn.Module):
def __init__(self,
d_model=256, d_ffn=1024,
dropout=0., activation="relu",
n_heads=8, attention_type="RCDA"):
super().__init__()
self.attention_type = attention_type
if attention_type=="RCDA":
attention_module=MultiheadRCDA
elif attention_type == "nn.MultiheadAttention":
attention_module=nn.MultiheadAttention
else:
raise ValueError(f'unknown {attention_type} attention_type')
# self attention
self.self_attn = attention_module(d_model, n_heads, dropout=dropout)
self.dropout1 = nn.Dropout(dropout)
self.norm1 = nn.LayerNorm(d_model)
# ffn
self.ffn = FFN(d_model, d_ffn, dropout, activation)
@staticmethod
def with_pos_embed(tensor, pos):
return tensor if pos is None else tensor + pos
def forward(self, src, padding_mask=None, posemb_row=None, posemb_col=None,posemb_2d=None):
# self attention
bz, c, h, w = src.shape
src = src.permute(0, 2, 3, 1)
if self.attention_type=="RCDA":
posemb_row = posemb_row.unsqueeze(1).repeat(1, h, 1, 1)
posemb_col = posemb_col.unsqueeze(2).repeat(1, 1, w, 1)
src2 = self.self_attn((src + posemb_row).reshape(bz, h * w, c), (src + posemb_col).reshape(bz, h * w, c),
src + posemb_row, src + posemb_col,
src, key_padding_mask=padding_mask)[0].transpose(0, 1).reshape(bz, h, w, c)
else:
src2 = self.self_attn((src + posemb_2d).reshape(bz, h * w, c).transpose(0, 1),
(src + posemb_2d).reshape(bz, h * w, c).transpose(0, 1),
src.reshape(bz, h * w, c).transpose(0, 1))[0].transpose(0, 1).reshape(bz, h, w, c)
src = src + self.dropout1(src2)
src = self.norm1(src)
# ffn
src = self.ffn(src)
src = src.permute(0, 3, 1, 2)
return src
class TransformerEncoderLayerLevel(nn.Module):
def __init__(self,
d_model=256, d_ffn=1024,
dropout=0., activation="relu",
n_heads=8):
super().__init__()
# self attention
self.self_attn_level = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
self.dropout1 = nn.Dropout(dropout)
self.norm1 = nn.LayerNorm(d_model)
# ffn
self.ffn = FFN(d_model, d_ffn, dropout, activation)
@staticmethod
def with_pos_embed(tensor, pos):
return tensor if pos is None else tensor + pos
def forward(self, src, level_emb=0):
# self attention
bz, c, h, w = src.shape
src = src.permute(0, 2, 3, 1)
src2 = self.self_attn_level(src.reshape(bz, h * w, c) + level_emb, src.reshape(bz, h * w, c) + level_emb,
src.reshape(bz, h * w, c))[0].reshape(bz, h, w, c)
src = src + self.dropout1(src2)
src = self.norm1(src)
# ffn
src = self.ffn(src)
src = src.permute(0, 3, 1, 2)
return src
class TransformerDecoderLayer(nn.Module):
def __init__(self, d_model=256, d_ffn=1024,
dropout=0., activation="relu", n_heads=8,
n_levels=3, attention_type="RCDA"):
super().__init__()
self.attention_type = attention_type
self.attention_type = attention_type
if attention_type=="RCDA":
attention_module=MultiheadRCDA
elif attention_type == "nn.MultiheadAttention":
attention_module=nn.MultiheadAttention
else:
raise ValueError(f'unknown {attention_type} attention_type')
# cross attention
self.cross_attn = attention_module(d_model, n_heads, dropout=dropout)
self.dropout1 = nn.Dropout(dropout)
self.norm1 = nn.LayerNorm(d_model)
# self attention
self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
self.dropout2 = nn.Dropout(dropout)
self.norm2 = nn.LayerNorm(d_model)
# level combination
if n_levels>1:
self.level_fc = nn.Linear(d_model * n_levels, d_model)
# ffn
self.ffn = FFN(d_model, d_ffn, dropout, activation)
@staticmethod
def with_pos_embed(tensor, pos):
return tensor if pos is None else tensor + pos
def forward(self, tgt, reference_points, srcs, src_padding_masks=None, adapt_pos2d=None,
adapt_pos1d=None, posemb_row=None, posemb_col=None, posemb_2d=None):
tgt_len = tgt.shape[1]
query_pos = pos2posemb2d(reference_points.squeeze(2))
query_pos = adapt_pos2d(query_pos)
# self attention
q = k = self.with_pos_embed(tgt, query_pos)
tgt2 = self.self_attn(q.transpose(0, 1), k.transpose(0, 1), tgt.transpose(0, 1))[0].transpose(0, 1)
tgt = tgt + self.dropout2(tgt2)
tgt = self.norm2(tgt)
bz, l, c, h, w = srcs.shape
srcs = srcs.reshape(bz * l, c, h, w).permute(0, 2, 3, 1)
if self.attention_type == "RCDA":
query_pos_x = adapt_pos1d(pos2posemb1d(reference_points[..., 0]))
query_pos_y = adapt_pos1d(pos2posemb1d(reference_points[..., 1]))
posemb_row = posemb_row.unsqueeze(1).repeat(1, h, 1, 1)
posemb_col = posemb_col.unsqueeze(2).repeat(1, 1, w, 1)
src_row = src_col = srcs
k_row = src_row + posemb_row
k_col = src_col + posemb_col
tgt2 = self.cross_attn((tgt + query_pos_x).repeat(l, 1, 1), (tgt + query_pos_y).repeat(l, 1, 1), k_row, k_col,
srcs, key_padding_mask=src_padding_masks)[0].transpose(0, 1)
else:
tgt2 = self.cross_attn((tgt + query_pos).repeat(l, 1, 1).transpose(0, 1),
(srcs + posemb_2d).reshape(bz * l, h * w, c).transpose(0,1),
srcs.reshape(bz * l, h * w, c).transpose(0, 1))[0].transpose(0,1)
if l > 1:
tgt2 = self.level_fc(tgt2.reshape(bz, l, tgt_len, c).permute(0, 2, 3, 1).reshape(bz, tgt_len, c * l))
tgt = tgt + self.dropout1(tgt2)
tgt = self.norm1(tgt)
# ffn
tgt = self.ffn(tgt)
return tgt
class FFN(nn.Module):
def __init__(self, d_model=256, d_ffn=1024, dropout=0., activation='relu'):
super().__init__()
self.linear1 = nn.Linear(d_model, d_ffn)
self.activation = _get_activation_fn(activation)
self.dropout2 = nn.Dropout(dropout)
self.linear2 = nn.Linear(d_ffn, d_model)
self.dropout3 = nn.Dropout(dropout)
self.norm2 = nn.LayerNorm(d_model)
def forward(self, src):
src2 = self.linear2(self.dropout2(self.activation(self.linear1(src))))
src = src + self.dropout3(src2)
src = self.norm2(src)
return src
class MLP(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
super().__init__()
self.num_layers = num_layers
h = [hidden_dim] * (num_layers - 1)
self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
def forward(self, x):
for i, layer in enumerate(self.layers):
x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
return x
def _get_clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
def _get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == "relu":
return F.relu
if activation == "gelu":
return F.gelu
if activation == "glu":
return F.glu
raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
def build_transformer(args):
return Transformer(
d_model=args.hidden_dim,
nhead=args.nheads,
num_encoder_layers=args.enc_layers,
num_decoder_layers=args.dec_layers,
dim_feedforward=args.dim_feedforward,
dropout=args.dropout,
activation="relu",
num_feature_levels=args.num_feature_levels,
num_query_position=args.num_query_position,
num_query_pattern=args.num_query_pattern,
spatial_prior=args.spatial_prior,
attention_type=args.attention_type,
)
def pos2posemb2d(pos, num_pos_feats=128, temperature=10000):
scale = 2 * math.pi
pos = pos * scale
dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=pos.device)
dim_t = temperature ** (2 * (dim_t // 2) / num_pos_feats)
pos_x = pos[..., 0, None] / dim_t
pos_y = pos[..., 1, None] / dim_t
pos_x = torch.stack((pos_x[..., 0::2].sin(), pos_x[..., 1::2].cos()), dim=-1).flatten(-2)
pos_y = torch.stack((pos_y[..., 0::2].sin(), pos_y[..., 1::2].cos()), dim=-1).flatten(-2)
posemb = torch.cat((pos_y, pos_x), dim=-1)
return posemb
def pos2posemb1d(pos, num_pos_feats=256, temperature=10000):
scale = 2 * math.pi
pos = pos * scale
dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=pos.device)
dim_t = temperature ** (2 * (dim_t // 2) / num_pos_feats)
pos_x = pos[..., None] / dim_t
posemb = torch.stack((pos_x[..., 0::2].sin(), pos_x[..., 1::2].cos()), dim=-1).flatten(-2)
return posemb
def mask2pos(mask):
not_mask = ~mask
y_embed = not_mask[:, :, 0].cumsum(1, dtype=torch.float32)
x_embed = not_mask[:, 0, :].cumsum(1, dtype=torch.float32)
y_embed = (y_embed - 0.5) / y_embed[:, -1:]
x_embed = (x_embed - 0.5) / x_embed[:, -1:]
return y_embed, x_embed
| 39.071759 | 161 | 0.598377 |
import copy
from typing import Optional, List
import math
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from util.misc import inverse_sigmoid
from models.row_column_decoupled_attention import MultiheadRCDA
class Transformer(nn.Module):
def __init__(self, d_model=256, nhead=8,
num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=1024, dropout=0.,
activation="relu", num_feature_levels=3,num_query_position = 300,num_query_pattern=3,
spatial_prior="learned",attention_type="RCDA"):
super().__init__()
self.d_model = d_model
self.nhead = nhead
self.attention_type = attention_type
encoder_layer = TransformerEncoderLayerSpatial(d_model, dim_feedforward,
dropout, activation, nhead , attention_type)
encoder_layer_level = TransformerEncoderLayerLevel(d_model, dim_feedforward,
dropout, activation, nhead)
decoder_layer = TransformerDecoderLayer(d_model, dim_feedforward,
dropout, activation, nhead,
num_feature_levels, attention_type)
if num_feature_levels == 1:
self.num_encoder_layers_level = 0
else:
self.num_encoder_layers_level = num_encoder_layers // 2
self.num_encoder_layers_spatial = num_encoder_layers - self.num_encoder_layers_level
self.encoder_layers = _get_clones(encoder_layer, self.num_encoder_layers_spatial)
self.encoder_layers_level = _get_clones(encoder_layer_level, self.num_encoder_layers_level)
self.decoder_layers = _get_clones(decoder_layer, num_decoder_layers)
self.spatial_prior=spatial_prior
if num_feature_levels>1:
self.level_embed = nn.Embedding(num_feature_levels, d_model)
self.num_pattern = num_query_pattern
self.pattern = nn.Embedding(self.num_pattern, d_model)
self.num_position = num_query_position
if self.spatial_prior == "learned":
self.position = nn.Embedding(self.num_position, 2)
self.adapt_pos2d = nn.Sequential(
nn.Linear(d_model, d_model),
nn.ReLU(),
nn.Linear(d_model, d_model),
)
self.adapt_pos1d = nn.Sequential(
nn.Linear(d_model, d_model),
nn.ReLU(),
nn.Linear(d_model, d_model),
)
self.num_layers = num_decoder_layers
num_classes = 91
self.class_embed = nn.Linear(d_model, num_classes)
self.bbox_embed = MLP(d_model, d_model, 4, 3)
self._reset_parameters()
def _reset_parameters(self):
num_pred = self.num_layers
num_classes = 91
prior_prob = 0.01
bias_value = -math.log((1 - prior_prob) / prior_prob)
self.class_embed.bias.data = torch.ones(num_classes) * bias_value
nn.init.constant_(self.bbox_embed.layers[-1].weight.data, 0)
nn.init.constant_(self.bbox_embed.layers[-1].bias.data, 0)
if self.spatial_prior == "learned":
nn.init.uniform_(self.position.weight.data, 0, 1)
nn.init.constant_(self.bbox_embed.layers[-1].bias.data[2:], -2.0)
self.class_embed = nn.ModuleList([self.class_embed for _ in range(num_pred)])
self.bbox_embed = nn.ModuleList([self.bbox_embed for _ in range(num_pred)])
def forward(self, srcs, masks):
bs, l, c, h, w = srcs.shape
if self.spatial_prior == "learned":
reference_points = self.position.weight.unsqueeze(0).repeat(bs, self.num_pattern, 1)
elif self.spatial_prior == "grid":
nx=ny=round(math.sqrt(self.num_position))
self.num_position=nx*ny
x = (torch.arange(nx) + 0.5) / nx
y = (torch.arange(ny) + 0.5) / ny
xy=torch.meshgrid(x,y)
reference_points=torch.cat([xy[0].reshape(-1)[...,None],xy[1].reshape(-1)[...,None]],-1).cuda()
reference_points = reference_points.unsqueeze(0).repeat(bs, self.num_pattern, 1)
else:
raise ValueError(f'unknown {self.spatial_prior} spatial prior')
tgt = self.pattern.weight.reshape(1, self.num_pattern, 1, c).repeat(bs, 1, self.num_position, 1).reshape(
bs, self.num_pattern * self.num_position, c)
mask = masks[-1].unsqueeze(1).repeat(1,l,1,1).reshape(bs*l,h,w)
pos_col, pos_row = mask2pos(mask)
if self.attention_type=="RCDA":
posemb_row = self.adapt_pos1d(pos2posemb1d(pos_row))
posemb_col = self.adapt_pos1d(pos2posemb1d(pos_col))
posemb_2d = None
else:
pos_2d = torch.cat([pos_row.unsqueeze(1).repeat(1, h, 1).unsqueeze(-1), pos_col.unsqueeze(2).repeat(1, 1, w).unsqueeze(-1)],dim=-1)
posemb_2d = self.adapt_pos2d(pos2posemb2d(pos_2d))
posemb_row = posemb_col = None
outputs = srcs.reshape(bs * l, c, h, w)
for idx in range(len(self.encoder_layers)):
outputs = self.encoder_layers[idx](outputs, mask, posemb_row, posemb_col,posemb_2d)
if idx < self.num_encoder_layers_level:
outputs = self.encoder_layers_level[idx](outputs, level_emb=self.level_embed.weight.unsqueeze(1).unsqueeze(0).repeat(bs,1,1,1).reshape(bs*l,1,c))
srcs = outputs.reshape(bs, l, c, h, w)
output = tgt
outputs_classes = []
outputs_coords = []
for lid, layer in enumerate(self.decoder_layers):
output = layer(output, reference_points, srcs, mask, adapt_pos2d=self.adapt_pos2d,
adapt_pos1d=self.adapt_pos1d, posemb_row=posemb_row, posemb_col=posemb_col,posemb_2d=posemb_2d)
reference = inverse_sigmoid(reference_points)
outputs_class = self.class_embed[lid](output)
tmp = self.bbox_embed[lid](output)
if reference.shape[-1] == 4:
tmp += reference
else:
assert reference.shape[-1] == 2
tmp[..., :2] += reference
outputs_coord = tmp.sigmoid()
outputs_classes.append(outputs_class[None,])
outputs_coords.append(outputs_coord[None,])
output = torch.cat(outputs_classes, dim=0), torch.cat(outputs_coords, dim=0)
return output
class TransformerEncoderLayerSpatial(nn.Module):
def __init__(self,
d_model=256, d_ffn=1024,
dropout=0., activation="relu",
n_heads=8, attention_type="RCDA"):
super().__init__()
self.attention_type = attention_type
if attention_type=="RCDA":
attention_module=MultiheadRCDA
elif attention_type == "nn.MultiheadAttention":
attention_module=nn.MultiheadAttention
else:
raise ValueError(f'unknown {attention_type} attention_type')
self.self_attn = attention_module(d_model, n_heads, dropout=dropout)
self.dropout1 = nn.Dropout(dropout)
self.norm1 = nn.LayerNorm(d_model)
self.ffn = FFN(d_model, d_ffn, dropout, activation)
@staticmethod
def with_pos_embed(tensor, pos):
return tensor if pos is None else tensor + pos
def forward(self, src, padding_mask=None, posemb_row=None, posemb_col=None,posemb_2d=None):
bz, c, h, w = src.shape
src = src.permute(0, 2, 3, 1)
if self.attention_type=="RCDA":
posemb_row = posemb_row.unsqueeze(1).repeat(1, h, 1, 1)
posemb_col = posemb_col.unsqueeze(2).repeat(1, 1, w, 1)
src2 = self.self_attn((src + posemb_row).reshape(bz, h * w, c), (src + posemb_col).reshape(bz, h * w, c),
src + posemb_row, src + posemb_col,
src, key_padding_mask=padding_mask)[0].transpose(0, 1).reshape(bz, h, w, c)
else:
src2 = self.self_attn((src + posemb_2d).reshape(bz, h * w, c).transpose(0, 1),
(src + posemb_2d).reshape(bz, h * w, c).transpose(0, 1),
src.reshape(bz, h * w, c).transpose(0, 1))[0].transpose(0, 1).reshape(bz, h, w, c)
src = src + self.dropout1(src2)
src = self.norm1(src)
src = self.ffn(src)
src = src.permute(0, 3, 1, 2)
return src
class TransformerEncoderLayerLevel(nn.Module):
def __init__(self,
d_model=256, d_ffn=1024,
dropout=0., activation="relu",
n_heads=8):
super().__init__()
self.self_attn_level = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
self.dropout1 = nn.Dropout(dropout)
self.norm1 = nn.LayerNorm(d_model)
self.ffn = FFN(d_model, d_ffn, dropout, activation)
@staticmethod
def with_pos_embed(tensor, pos):
return tensor if pos is None else tensor + pos
def forward(self, src, level_emb=0):
bz, c, h, w = src.shape
src = src.permute(0, 2, 3, 1)
src2 = self.self_attn_level(src.reshape(bz, h * w, c) + level_emb, src.reshape(bz, h * w, c) + level_emb,
src.reshape(bz, h * w, c))[0].reshape(bz, h, w, c)
src = src + self.dropout1(src2)
src = self.norm1(src)
src = self.ffn(src)
src = src.permute(0, 3, 1, 2)
return src
class TransformerDecoderLayer(nn.Module):
def __init__(self, d_model=256, d_ffn=1024,
dropout=0., activation="relu", n_heads=8,
n_levels=3, attention_type="RCDA"):
super().__init__()
self.attention_type = attention_type
self.attention_type = attention_type
if attention_type=="RCDA":
attention_module=MultiheadRCDA
elif attention_type == "nn.MultiheadAttention":
attention_module=nn.MultiheadAttention
else:
raise ValueError(f'unknown {attention_type} attention_type')
self.cross_attn = attention_module(d_model, n_heads, dropout=dropout)
self.dropout1 = nn.Dropout(dropout)
self.norm1 = nn.LayerNorm(d_model)
self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
self.dropout2 = nn.Dropout(dropout)
self.norm2 = nn.LayerNorm(d_model)
if n_levels>1:
self.level_fc = nn.Linear(d_model * n_levels, d_model)
self.ffn = FFN(d_model, d_ffn, dropout, activation)
@staticmethod
def with_pos_embed(tensor, pos):
return tensor if pos is None else tensor + pos
def forward(self, tgt, reference_points, srcs, src_padding_masks=None, adapt_pos2d=None,
adapt_pos1d=None, posemb_row=None, posemb_col=None, posemb_2d=None):
tgt_len = tgt.shape[1]
query_pos = pos2posemb2d(reference_points.squeeze(2))
query_pos = adapt_pos2d(query_pos)
q = k = self.with_pos_embed(tgt, query_pos)
tgt2 = self.self_attn(q.transpose(0, 1), k.transpose(0, 1), tgt.transpose(0, 1))[0].transpose(0, 1)
tgt = tgt + self.dropout2(tgt2)
tgt = self.norm2(tgt)
bz, l, c, h, w = srcs.shape
srcs = srcs.reshape(bz * l, c, h, w).permute(0, 2, 3, 1)
if self.attention_type == "RCDA":
query_pos_x = adapt_pos1d(pos2posemb1d(reference_points[..., 0]))
query_pos_y = adapt_pos1d(pos2posemb1d(reference_points[..., 1]))
posemb_row = posemb_row.unsqueeze(1).repeat(1, h, 1, 1)
posemb_col = posemb_col.unsqueeze(2).repeat(1, 1, w, 1)
src_row = src_col = srcs
k_row = src_row + posemb_row
k_col = src_col + posemb_col
tgt2 = self.cross_attn((tgt + query_pos_x).repeat(l, 1, 1), (tgt + query_pos_y).repeat(l, 1, 1), k_row, k_col,
srcs, key_padding_mask=src_padding_masks)[0].transpose(0, 1)
else:
tgt2 = self.cross_attn((tgt + query_pos).repeat(l, 1, 1).transpose(0, 1),
(srcs + posemb_2d).reshape(bz * l, h * w, c).transpose(0,1),
srcs.reshape(bz * l, h * w, c).transpose(0, 1))[0].transpose(0,1)
if l > 1:
tgt2 = self.level_fc(tgt2.reshape(bz, l, tgt_len, c).permute(0, 2, 3, 1).reshape(bz, tgt_len, c * l))
tgt = tgt + self.dropout1(tgt2)
tgt = self.norm1(tgt)
tgt = self.ffn(tgt)
return tgt
class FFN(nn.Module):
def __init__(self, d_model=256, d_ffn=1024, dropout=0., activation='relu'):
super().__init__()
self.linear1 = nn.Linear(d_model, d_ffn)
self.activation = _get_activation_fn(activation)
self.dropout2 = nn.Dropout(dropout)
self.linear2 = nn.Linear(d_ffn, d_model)
self.dropout3 = nn.Dropout(dropout)
self.norm2 = nn.LayerNorm(d_model)
def forward(self, src):
src2 = self.linear2(self.dropout2(self.activation(self.linear1(src))))
src = src + self.dropout3(src2)
src = self.norm2(src)
return src
class MLP(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
super().__init__()
self.num_layers = num_layers
h = [hidden_dim] * (num_layers - 1)
self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
def forward(self, x):
for i, layer in enumerate(self.layers):
x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
return x
def _get_clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
def _get_activation_fn(activation):
if activation == "relu":
return F.relu
if activation == "gelu":
return F.gelu
if activation == "glu":
return F.glu
raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
def build_transformer(args):
return Transformer(
d_model=args.hidden_dim,
nhead=args.nheads,
num_encoder_layers=args.enc_layers,
num_decoder_layers=args.dec_layers,
dim_feedforward=args.dim_feedforward,
dropout=args.dropout,
activation="relu",
num_feature_levels=args.num_feature_levels,
num_query_position=args.num_query_position,
num_query_pattern=args.num_query_pattern,
spatial_prior=args.spatial_prior,
attention_type=args.attention_type,
)
def pos2posemb2d(pos, num_pos_feats=128, temperature=10000):
scale = 2 * math.pi
pos = pos * scale
dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=pos.device)
dim_t = temperature ** (2 * (dim_t // 2) / num_pos_feats)
pos_x = pos[..., 0, None] / dim_t
pos_y = pos[..., 1, None] / dim_t
pos_x = torch.stack((pos_x[..., 0::2].sin(), pos_x[..., 1::2].cos()), dim=-1).flatten(-2)
pos_y = torch.stack((pos_y[..., 0::2].sin(), pos_y[..., 1::2].cos()), dim=-1).flatten(-2)
posemb = torch.cat((pos_y, pos_x), dim=-1)
return posemb
def pos2posemb1d(pos, num_pos_feats=256, temperature=10000):
scale = 2 * math.pi
pos = pos * scale
dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=pos.device)
dim_t = temperature ** (2 * (dim_t // 2) / num_pos_feats)
pos_x = pos[..., None] / dim_t
posemb = torch.stack((pos_x[..., 0::2].sin(), pos_x[..., 1::2].cos()), dim=-1).flatten(-2)
return posemb
def mask2pos(mask):
not_mask = ~mask
y_embed = not_mask[:, :, 0].cumsum(1, dtype=torch.float32)
x_embed = not_mask[:, 0, :].cumsum(1, dtype=torch.float32)
y_embed = (y_embed - 0.5) / y_embed[:, -1:]
x_embed = (x_embed - 0.5) / x_embed[:, -1:]
return y_embed, x_embed
| true | true |
f72f1e928139d4f1f8e92e1e0291db259b10cc61 | 8,261 | py | Python | src/problem3.py | mcgeeml/06-Exam1Practice | 721f95eda65e0f5bd2ae541bc028e1d5dc9e6b47 | [
"MIT"
] | null | null | null | src/problem3.py | mcgeeml/06-Exam1Practice | 721f95eda65e0f5bd2ae541bc028e1d5dc9e6b47 | [
"MIT"
] | null | null | null | src/problem3.py | mcgeeml/06-Exam1Practice | 721f95eda65e0f5bd2ae541bc028e1d5dc9e6b47 | [
"MIT"
] | null | null | null | """
PRACTICE Exam 1, problem 3.
Authors: David Mutchler, Vibha Alangar, Valerie Galluzzi, Mark Hays,
Amanda Stouder, their colleagues and Myon McGee.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
import rosegraphics as rg
########################################################################
# Students:
#
# These problems have DIFFICULTY and TIME ratings:
# DIFFICULTY rating: 1 to 10, where:
# 1 is very easy
# 3 is an "easy" Test 1 question.
# 5 is a "typical" Test 1 question.
# 7 is a "hard" Test 1 question.
# 10 is an EXTREMELY hard problem (too hard for a Test 1 question)
#
# TIME ratings: A ROUGH estimate of the number of minutes that we
# would expect a well-prepared student to take on the problem.
#
# IMPORTANT: For ALL the problems in this module,
# if you reach the time estimate and are NOT close to a solution,
# STOP working on that problem and ASK YOUR INSTRUCTOR FOR HELP
# on it, in class or via Piazza.
########################################################################
def main():
""" Calls the TEST functions in this module. """
run_test_problem3a()
run_test_problem3b()
def run_test_problem3a():
""" Tests the problem3a function. """
# ------------------------------------------------------------------
# TODO: 2. Implement this TEST function.
# It TESTS the problem1a function defined below.
# Include at least ** 5 ** tests (we wrote four for you).
# ------------------------------------------------------------------
# ------------------------------------------------------------------
# DIFFICULTY AND TIME RATINGS (see top of this file for explanation)
# DIFFICULTY: 4
# TIME ESTIMATE: 10 to 15 minutes.
# ------------------------------------------------------------------
# Window 1:
title = 'Problem 3a. Test 1: Start at (30, 30), 6 lines'
window1 = rg.RoseWindow(350, 200, title)
# Test 1 (it is on window 1):
point = rg.Point(30, 30)
expected = 36
answer = problem3a(window1, point, 6)
print()
print('Test 1 expected:', expected)
print(' actual: ', answer)
window1.close_on_mouse_click()
# Window 2:
title = 'Problem 3a. Test 2: Start at (80, 10), 9 lines.'
title += ' Test 3: Start at (30, 50), 3 lines.'
window2 = rg.RoseWindow(550, 200, title)
# Test 2 (it is on window 2):
point = rg.Point(80, 10)
expected = 75
answer = problem3a(window2, point, 9)
print()
print('Test 2 expected:', expected)
print(' actual: ', answer)
# Test 3 (it is also on window 2):
point = rg.Point(30, 50)
expected = 9
answer = problem3a(window2, point, 3)
print()
print('Test 3 expected:', expected)
print(' actual: ', answer)
window2.close_on_mouse_click()
# Window 3:
title = 'Problem 3a. Test 4: Start at (30, 30), 20 lines'
window3 = rg.RoseWindow(450, 300, title)
# Test 4 (it is on window 3):
point = rg.Point(30, 30)
expected = 218
answer = problem3a(window3, point, 20)
print()
print('Test 4 expected:', expected)
print(' actual: ', answer)
window3.close_on_mouse_click()
# ------------------------------------------------------------------
# TO DO: 2 (continued).
# Below this comment (or integrated with one of the above tests,
# your choice), add 1 more test case of your own choosing.
# ------------------------------------------------------------------
def problem3a(window, point, n):
"""
See problem3a_picture.pdf in this project for pictures
that may help you better understand the following specification:
What comes in:
-- An rg.RoseWindow.
-- An rg.Point.
-- A nonnegative integer n.
What goes out:
-- Returns the sum of the thicknesses of the rg.Lines
that are drawn as described in the Side effects (below).
Side effects:
Draws n rg.Lines on the given rg.RoseWindow,
as follows:
-- There are the given number (n) of rg.Lines.
-- Each rg.Line is vertical and has length 50.
(All units are pixels.)
-- The top of the first (leftmost) rg.Line
is at the given rg.Point.
-- Each successive rg.Line is 20 pixels to the right
and 10 pixels down from the previous rg.Line.
-- The first rg.Line has thickness 1.
-- Each successive rg.Line has thickness 2 greater than
the rg.Line to its left, but no greater than 13.
(So once a rg.Line has thickness 13,
it and all the rg.Lines to its right have thickness 13.)
Type hints:
:type window: rg.RoseWindow
:type point: rg.Point
:type n: int
"""
# ------------------------------------------------------------------
# TODO: 3. Implement and test this function.
# Note that you should write its TEST function first (above).
# ------------------------------------------------------------------
# ------------------------------------------------------------------
# DIFFICULTY AND TIME RATINGS (see top of this file for explanation)
# DIFFICULTY: 7 or 8
# TIME ESTIMATE: 20 to 35 minutes.
# ------------------------------------------------------------------
def run_test_problem3b():
""" Tests the problem3b function. """
# Test 1 is ALREADY DONE (here).
expected = 158
answer = problem3b(4, rg.Point(100, 50))
print()
print('Test 1 expected:', expected)
print(' actual: ', answer)
# Test 2 is ALREADY DONE (here).
expected = 539
answer = problem3b(7, rg.Point(30, 30))
print()
print('Test 2 expected:', expected)
print(' actual: ', answer)
def problem3b(m, point1):
"""
See problem3b_picture.pdf in this project for pictures
that may help you better understand the following specification:
What comes in:
-- A positive integer m.
-- An rg.Point.
What goes out:
-- Returns the sum of the thicknesses of ALL of the lines drawn
(over all m sets of lines).
Side effects:
-- Constructs and displays an rg.RoseWindow
that is 400 wide by 650 tall.
-- Draws, on the rg.RoseWindow, m SETS of lines, where:
-- Each SET of lines is drawn
*** by a call to ** problem3a **. ***
-- The first set has 3 lines that start at point1
(the given point).
-- The second set has 5 lines that start 60 pixels
directly below point1.
-- The third set has 7 lines that start 120 pixels
directly below point1.
-- The fourth set has 9 lines that start 180 pixels
directly below point1.
-- etc until m SETS of lines are drawn (where m is given).
-- Each set of lines should have widths (thicknesses)
per problem3a.
-- Waits for the user to click the mouse (and displays an
appropriate message prompting the user to do so),
then closes the window.
Type hints:
:type m: int
:type point1: rg.Point
"""
# ------------------------------------------------------------------
# TODO: 4. Implement and test this function.
# Tests have been written for you (above).
#
####################################################################
# IMPORTANT:
# ** For full credit you must appropriately use (call)
# ** the problem3a function that you implemented above.
####################################################################
# ------------------------------------------------------------------
# DIFFICULTY AND TIME RATINGS (see top of this file for explanation)
# DIFFICULTY: 8 or 9
# TIME ESTIMATE: 20 to 30 minutes.
# ------------------------------------------------------------------
# ----------------------------------------------------------------------
# Calls main to start the ball rolling.
# ----------------------------------------------------------------------
main()
| 37.211712 | 72 | 0.507808 |
import rosegraphics as rg
| true | true |
f72f1fb175ba5701b831b4c399b500717379e533 | 1,591 | py | Python | examples/01_plotting/plot_colormaps.py | SIMEXP/nilearn | 4f51aea58f38689ca32c2edd748528d521e6cfb0 | [
"BSD-2-Clause"
] | 827 | 2015-01-30T23:11:42.000Z | 2022-03-29T21:21:05.000Z | examples/01_plotting/plot_colormaps.py | SIMEXP/nilearn | 4f51aea58f38689ca32c2edd748528d521e6cfb0 | [
"BSD-2-Clause"
] | 2,845 | 2015-01-04T22:14:41.000Z | 2022-03-31T20:28:09.000Z | examples/01_plotting/plot_colormaps.py | SIMEXP/nilearn | 4f51aea58f38689ca32c2edd748528d521e6cfb0 | [
"BSD-2-Clause"
] | 484 | 2015-02-03T10:58:19.000Z | 2022-03-29T21:57:16.000Z | """
Matplotlib colormaps in Nilearn
================================
Visualize HCP connectome workbench color maps shipped with Nilearn
which can be used for plotting brain images on surface.
See :ref:`surface-plotting` for surface plotting details.
"""
import numpy as np
import matplotlib.pyplot as plt
from nilearn.plotting.cm import _cmap_d as nilearn_cmaps
from nilearn.plotting import show
###########################################################################
# Plot color maps
# ----------------
nmaps = len(nilearn_cmaps)
a = np.outer(np.arange(0, 1, 0.01), np.ones(10))
# Initialize the figure
plt.figure(figsize=(10, 4.2))
plt.subplots_adjust(top=0.4, bottom=0.05, left=0.01, right=0.99)
for index, cmap in enumerate(nilearn_cmaps):
plt.subplot(1, nmaps + 1, index + 1)
plt.imshow(a, cmap=nilearn_cmaps[cmap])
plt.axis('off')
plt.title(cmap, fontsize=10, va='bottom', rotation=90)
###########################################################################
# Plot matplotlib color maps
# --------------------------
plt.figure(figsize=(10, 5))
plt.subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99)
deprecated_cmaps = ['Vega10', 'Vega20', 'Vega20b', 'Vega20c', 'spectral']
m_cmaps = []
for m in plt.cm.datad:
if not m.endswith("_r") and m not in deprecated_cmaps:
m_cmaps.append(m)
m_cmaps.sort()
for index, cmap in enumerate(m_cmaps):
plt.subplot(1, len(m_cmaps) + 1, index + 1)
plt.imshow(a, cmap=plt.get_cmap(cmap), aspect='auto')
plt.axis('off')
plt.title(cmap, fontsize=10, va='bottom', rotation=90)
show()
| 30.596154 | 75 | 0.606537 | import numpy as np
import matplotlib.pyplot as plt
from nilearn.plotting.cm import _cmap_d as nilearn_cmaps
from nilearn.plotting import show
| true | true |
f72f2071f1e1301bd9f2a6ccbf675cb274979e21 | 684 | py | Python | setup.py | pmartin23/metapub | 7dc3f2321720191d461056deeaedf69cd1479157 | [
"Apache-2.0"
] | null | null | null | setup.py | pmartin23/metapub | 7dc3f2321720191d461056deeaedf69cd1479157 | [
"Apache-2.0"
] | 3 | 2019-11-14T23:36:14.000Z | 2020-11-05T20:42:50.000Z | setup.py | pmartin23/metapub | 7dc3f2321720191d461056deeaedf69cd1479157 | [
"Apache-2.0"
] | 1 | 2018-02-08T12:25:12.000Z | 2018-02-08T12:25:12.000Z | import glob, os
from setuptools import setup, find_packages
setup(
name = 'metapub',
version = '0.4.3.5',
description = 'Pubmed / NCBI / eutils interaction library, handling the metadata of pubmed papers.',
url = 'https://bitbucket.org/metapub/metapub',
author = 'Naomi Most',
maintainer = 'Naomi Most',
author_email = 'naomi@nthmost.com',
maintainer_email = 'naomi@nthmost.com',
license = 'Apache 2.0',
packages = find_packages(),
install_requires = [
'setuptools',
'lxml',
'requests',
'eutils',
'tabulate',
'cssselect',
'unidecode',
'six',
'tox',
],
)
| 24.428571 | 104 | 0.574561 | import glob, os
from setuptools import setup, find_packages
setup(
name = 'metapub',
version = '0.4.3.5',
description = 'Pubmed / NCBI / eutils interaction library, handling the metadata of pubmed papers.',
url = 'https://bitbucket.org/metapub/metapub',
author = 'Naomi Most',
maintainer = 'Naomi Most',
author_email = 'naomi@nthmost.com',
maintainer_email = 'naomi@nthmost.com',
license = 'Apache 2.0',
packages = find_packages(),
install_requires = [
'setuptools',
'lxml',
'requests',
'eutils',
'tabulate',
'cssselect',
'unidecode',
'six',
'tox',
],
)
| true | true |
f72f20b73a9f992e3e7d7b8d15bee88e20b845b2 | 13,740 | py | Python | rltoolkit/rl.py | raznem/sac_ppo | c18e9bd32a70fcc4bc413565c6b885d7560b8b5a | [
"MIT"
] | null | null | null | rltoolkit/rl.py | raznem/sac_ppo | c18e9bd32a70fcc4bc413565c6b885d7560b8b5a | [
"MIT"
] | null | null | null | rltoolkit/rl.py | raznem/sac_ppo | c18e9bd32a70fcc4bc413565c6b885d7560b8b5a | [
"MIT"
] | null | null | null | import logging
from pathlib import Path
from typing import Any, Optional, Tuple, Union
import gym
import torch
import pickle as pkl
from rltoolkit import config, utils
from rltoolkit.buffer import Memory
from rltoolkit.stats_logger import StatsLogger
from rltoolkit.tensorboard_logger import TensorboardWriter
logger = logging.getLogger(__name__)
class MetaLearner:
def __init__(
self,
env_name: str,
use_gpu: bool,
debug_mode: bool = config.DEBUG_MODE,
tensorboard_dir: Union[str, None] = config.TENSORBOARD_DIR,
tensorboard_comment: str = config.TENSORBOARD_COMMENT,
):
f"""Class with parameters common for RL and other interactions with environment
Args:
env_name (str): Name of the gym environment.
use_gpu (bool): Use CUDA.
debug_mode (bool, optional): Log additional info.
Defaults to { config.DEBUG_MODE }
tensorboard_dir (Union[str, None], optional): Path to tensorboard logs.
Defaults to { config.TENSORBOARD_DIR }.
tensorboard_comment (str, optional): Comment for tensorboard files.
Defaults to { config.TENSORBOARD_COMMENT }.
"""
self.env_name = env_name
if use_gpu and torch.cuda.is_available():
self.device = torch.device("cuda")
else:
self.device = torch.device("cpu")
self.env = gym.make(self.env_name)
self.discrete = isinstance(self.env.action_space, gym.spaces.Discrete)
self.ob_dim = self.env.observation_space.shape[0]
if self.discrete:
self.ac_dim = self.env.action_space.n
self.ac_lim = None
else:
self.ac_dim = self.env.action_space.shape[0]
self.ac_lim = torch.tensor(self.env.action_space.high, device=self.device)
self.obs_mean = torch.zeros(self.ob_dim, device=self.device)
self.obs_std = torch.ones(self.ob_dim, device=self.device)
self.iteration = 0 # used in tensorboard
self.opt = torch.optim.Adam
self.loss = {}
self.debug_mode = debug_mode
self.tensorboard_writer = None
self.tensorboard_comment = (
"_" + tensorboard_comment if tensorboard_comment else ""
)
self.tensorboard_dir = tensorboard_dir
def run_tensorboard_if_needed(self):
if self.tensorboard_writer is None and (self.tensorboard_dir is not None):
self.tensorboard_writer = TensorboardWriter(
env_name=self.env_name,
log_dir=self.tensorboard_dir,
filename=self.filename,
render=self.render,
)
def log_obs_mean_std_tensorboard(self):
"""
Log mean and std of observations in the tensorboard.
"""
self.run_tensorboard_if_needed()
self.tensorboard_writer.log_obs_mean_std(
self.iteration, self.obs_mean, self.obs_std
)
def update_obs_mean_std(self, buffer: Memory) -> Memory:
"""
Update running average of mean and stds based on the buffer.
Args:
buffer (Memory)
Returns:
Memory
"""
buffer.update_obs_mean_std()
self.obs_mean = buffer.obs_mean
self.obs_std = buffer.obs_std
if self.debug_mode and self.tensorboard_dir is not None:
self.log_obs_mean_std_tensorboard()
return buffer
class RL(MetaLearner):
def __init__(
self,
env_name: str = config.ENV_NAME,
gamma: float = config.GAMMA,
stats_freq: int = config.STATS_FREQ,
test_episodes: int = config.TEST_EPISODES,
batch_size: int = config.BATCH_SIZE,
iterations: int = config.ITERATIONS,
max_frames: int = None,
return_done: Union[int, None] = config.RETURN_DONE,
log_dir: str = config.LOG_DIR,
use_gpu: bool = config.USE_GPU,
verbose: int = config.VERBOSE,
render: bool = config.RENDER,
*args,
**kwargs,
):
f"""Basic parent class for reinforcement learning algorithms.
Args:
env_name (str, optional): Name of the gym environment.
Defaults to { config.ENV_NAME }.
gamma (float, optional): Discount factor. Defaults to { config.GAMMA }.
stats_freq (int, optional): Frequency of logging the progress.
Defaults to { config.STATS_FREQ }.
batch_size (int, optional): Number of frames used for one algorithm step
(could be higher because batch collection stops when rollout ends).
Defaults to { config.BATCH_SIZE }.
iterations (int, optional): Number of algorithms iterations.
Defaults to { config.ITERATIONS }.
max_frames (int, optional): Limit of frames for training. Defaults to
{ None }.
return_done (Union[int, None], optional): target return, which will stop
training if reached. Defaults to { config.RETURN_DONE }.
log_dir (str, optional): Path for basic logs which includes final model.
Defaults to { config.LOG_DIR }.
use_gpu (bool, optional): Use CUDA. Defaults to { config.USE_GPU }.
verbose (int, optional): Verbose level. Defaults to { config.VERBOSE }.
render (bool, optional): Render rollouts to tensorboard.
Defaults to { config.RENDER }.
debug_mode (bool, optional): Log additional info.
Defaults to { config.DEBUG_MODE }
tensorboard_dir (Union[str, None], optional): Path to tensorboard logs.
Defaults to { config.TENSORBOARD_DIR }.
tensorboard_comment (str, optional): Comment for tensorboard files.
Defaults to { config.TENSORBOARD_COMMENT }.
"""
super().__init__(env_name, use_gpu, *args, **kwargs)
assert iterations > 0, f"Iteration has to be positive not {iterations}"
if max_frames is not None:
assert (
max_frames <= iterations * batch_size
), "max_frames should be smaller or equal than iterations * batch_size"
self.max_frames = max_frames
self.gamma = gamma
self.stats_freq = stats_freq
self.test_episodes = test_episodes
self.batch_size = batch_size
self.iterations = iterations
self.return_done = return_done
if log_dir is not None:
self.log_dir = Path(log_dir)
self.log_dir.mkdir(parents=True, exist_ok=True)
else:
self.log_dir = log_dir
self.verbose = verbose
self.render = render
self.max_ep_len = self.env._max_episode_steps
self.start_time = utils.get_time()
self.hparams = {
"hparams/gamma": self.gamma,
"hparams/batch_size": self.batch_size,
"hparams/type": utils.get_pretty_type_name(self),
}
self.shortnames = config.SHORTNAMES
self.stats_logger = StatsLogger()
def train(self, iterations=None):
f""" Train RL model
Args:
iterations ([type], optional): Number of additional training iterations.
If None performs number of iterations defined in self.iterations.
Otherwise increase global counter by this value to run additional steps.
Defaults to { None }.
"""
self.run_tensorboard_if_needed()
if iterations:
self.iterations += iterations
while self.iteration < self.iterations:
buffer, time_diff = self.perform_iteration()
self.stats_logger.time_list.append(time_diff)
running_return = self.stats_logger.calc_running_return(buffer)
if self.return_done is not None and running_return >= self.return_done:
break
if self.iteration % self.stats_freq == 0:
self.logs_after_iteration(buffer)
if self.log_dir is not None:
self.stats_logger.dump_stats(self.log_path)
self.iteration += 1 # used also for logs
if (
self.max_frames is not None
and self.max_frames < self.stats_logger.frames
):
logger.info(f"Reached max_frames at {self.iteration} iteration") # INFO
break
self.logs_after_iteration(buffer, done=True)
if self.log_dir is not None:
self.save()
def test(self, episodes=None):
f"""Test policy
Args:
episodes (int): Number of episodes. Defaults to { None }.
Returns:
float: mean episode reward
"""
mean_reward = None
return mean_reward
@utils.measure_time
def perform_iteration(self):
raise NotImplementedError
def save_model(self):
raise NotImplementedError
def check_path(self, path):
if self.filename is None and path is None:
raise AttributeError
elif path is None:
path = str(self.log_path) + ".pkl"
return path
def collect_params_dict(self):
params_dict = {}
params_dict["actor"] = self.actor.state_dict()
params_dict["critic"] = self.critic.state_dict()
params_dict["obs_mean"] = self.obs_mean
params_dict["obs_std"] = self.obs_std
return params_dict
def apply_params_dict(self, params_dict):
self.actor.load_state_dict(params_dict["actor"])
self.critic.load_state_dict(params_dict["critic"])
self.obs_mean = params_dict["obs_mean"]
self.obs_std = params_dict["obs_std"]
def save(self, path: str = None):
f"""Save RL object
Args:
path (str): Path to save
"""
path = self.check_path(path)
with open(path, "wb") as f:
params_dict = self.collect_params_dict()
pkl.dump(params_dict, f)
def load(self, path: str):
"""Load RL object
Args:
path (str): Path to saved RL object
"""
path = self.check_path(path)
with open(path, "rb") as f:
params_dict = pkl.load(f)
self.apply_params_dict(params_dict)
@property
def log_iteration(self):
return self.iteration // self.stats_freq
@property
def filename(self):
suffix = self.get_tensorboard_hparams_suffix()
suffix += self.tensorboard_comment
filename = self.start_time + suffix
return filename
@property
def log_path(self):
log_path = Path(self.log_dir)
log_path = log_path / self.filename
return log_path
def logs_after_iteration(self, buffer: Memory, done: bool = False):
f"""Logs writer
Args:
buffer (Memory): Buffer used for tensorboard
done (bool, optional): Finalize tensorboard logging due to last iteration.
Defaults to { False }.
"""
if self.test_episodes is not None:
self.stats_logger.test_return = self.test()
running_return = self.stats_logger.running_return
if self.verbose:
if done:
self.stats_logger.task_done(self.iteration)
else:
self.stats_logger.log_stats(self.iteration)
self.stats_logger.stats.append([self.iteration, running_return])
self.stats_logger.reset_time_list()
if self.tensorboard_writer is not None:
self.add_tensorboard_logs(buffer, done)
def add_tensorboard_logs(self, buffer: Memory, done: bool):
self.tensorboard_writer.log_running_return(
self.iteration,
self.stats_logger.frames,
self.stats_logger.rollouts,
self.stats_logger.running_return,
)
if self.test_episodes:
self.tensorboard_writer.log_test_return(
self.iteration,
self.stats_logger.frames,
self.stats_logger.rollouts,
self.stats_logger.test_return,
)
if (self.log_iteration % 5) == 0 or done:
_, rendering_time = self.tensorboard_writer.record_episode(
self, self.iteration, done
)
self.tensorboard_writer.log_returns(self.iteration, buffer)
self.tensorboard_writer.log_actions(self.iteration, buffer)
self.tensorboard_writer.log_observations(self.iteration, buffer)
self.tensorboard_writer.log_loss(self.iteration, self.loss)
def get_tensorboard_hparams_suffix(self):
suffix = ""
for key, val in self.hparams.items():
if key in self.shortnames.keys():
key = self.shortnames[key]
else:
key = key.split("/")[1]
if isinstance(val, float):
val = f"{val:.2}"
else:
val = str(val)
suffix += f"-{key}{val}"
return suffix
def _get_initial_obs_mean_std(
self, obs_norm: Any
) -> Tuple[Optional[torch.tensor], Optional[torch.tensor]]:
f"""
Check if observations are normalized and if so return initial mean and std,
None otherwise.
Returns:
Tuple[Optional[torch.tensor], Optional[torch.tensor]]: obs mean and std
"""
if obs_norm:
obs_mean = torch.zeros(self.ob_dim, device=self.device)
obs_std = torch.ones(self.ob_dim, device=self.device)
else:
obs_mean = None
obs_std = None
return obs_mean, obs_std
| 35.412371 | 88 | 0.605968 | import logging
from pathlib import Path
from typing import Any, Optional, Tuple, Union
import gym
import torch
import pickle as pkl
from rltoolkit import config, utils
from rltoolkit.buffer import Memory
from rltoolkit.stats_logger import StatsLogger
from rltoolkit.tensorboard_logger import TensorboardWriter
logger = logging.getLogger(__name__)
class MetaLearner:
def __init__(
self,
env_name: str,
use_gpu: bool,
debug_mode: bool = config.DEBUG_MODE,
tensorboard_dir: Union[str, None] = config.TENSORBOARD_DIR,
tensorboard_comment: str = config.TENSORBOARD_COMMENT,
):
f"""Class with parameters common for RL and other interactions with environment
Args:
env_name (str): Name of the gym environment.
use_gpu (bool): Use CUDA.
debug_mode (bool, optional): Log additional info.
Defaults to { config.DEBUG_MODE }
tensorboard_dir (Union[str, None], optional): Path to tensorboard logs.
Defaults to { config.TENSORBOARD_DIR }.
tensorboard_comment (str, optional): Comment for tensorboard files.
Defaults to { config.TENSORBOARD_COMMENT }.
"""
self.env_name = env_name
if use_gpu and torch.cuda.is_available():
self.device = torch.device("cuda")
else:
self.device = torch.device("cpu")
self.env = gym.make(self.env_name)
self.discrete = isinstance(self.env.action_space, gym.spaces.Discrete)
self.ob_dim = self.env.observation_space.shape[0]
if self.discrete:
self.ac_dim = self.env.action_space.n
self.ac_lim = None
else:
self.ac_dim = self.env.action_space.shape[0]
self.ac_lim = torch.tensor(self.env.action_space.high, device=self.device)
self.obs_mean = torch.zeros(self.ob_dim, device=self.device)
self.obs_std = torch.ones(self.ob_dim, device=self.device)
self.iteration = 0
self.opt = torch.optim.Adam
self.loss = {}
self.debug_mode = debug_mode
self.tensorboard_writer = None
self.tensorboard_comment = (
"_" + tensorboard_comment if tensorboard_comment else ""
)
self.tensorboard_dir = tensorboard_dir
def run_tensorboard_if_needed(self):
if self.tensorboard_writer is None and (self.tensorboard_dir is not None):
self.tensorboard_writer = TensorboardWriter(
env_name=self.env_name,
log_dir=self.tensorboard_dir,
filename=self.filename,
render=self.render,
)
def log_obs_mean_std_tensorboard(self):
self.run_tensorboard_if_needed()
self.tensorboard_writer.log_obs_mean_std(
self.iteration, self.obs_mean, self.obs_std
)
def update_obs_mean_std(self, buffer: Memory) -> Memory:
buffer.update_obs_mean_std()
self.obs_mean = buffer.obs_mean
self.obs_std = buffer.obs_std
if self.debug_mode and self.tensorboard_dir is not None:
self.log_obs_mean_std_tensorboard()
return buffer
class RL(MetaLearner):
def __init__(
self,
env_name: str = config.ENV_NAME,
gamma: float = config.GAMMA,
stats_freq: int = config.STATS_FREQ,
test_episodes: int = config.TEST_EPISODES,
batch_size: int = config.BATCH_SIZE,
iterations: int = config.ITERATIONS,
max_frames: int = None,
return_done: Union[int, None] = config.RETURN_DONE,
log_dir: str = config.LOG_DIR,
use_gpu: bool = config.USE_GPU,
verbose: int = config.VERBOSE,
render: bool = config.RENDER,
*args,
**kwargs,
):
f"""Basic parent class for reinforcement learning algorithms.
Args:
env_name (str, optional): Name of the gym environment.
Defaults to { config.ENV_NAME }.
gamma (float, optional): Discount factor. Defaults to { config.GAMMA }.
stats_freq (int, optional): Frequency of logging the progress.
Defaults to { config.STATS_FREQ }.
batch_size (int, optional): Number of frames used for one algorithm step
(could be higher because batch collection stops when rollout ends).
Defaults to { config.BATCH_SIZE }.
iterations (int, optional): Number of algorithms iterations.
Defaults to { config.ITERATIONS }.
max_frames (int, optional): Limit of frames for training. Defaults to
{ None }.
return_done (Union[int, None], optional): target return, which will stop
training if reached. Defaults to { config.RETURN_DONE }.
log_dir (str, optional): Path for basic logs which includes final model.
Defaults to { config.LOG_DIR }.
use_gpu (bool, optional): Use CUDA. Defaults to { config.USE_GPU }.
verbose (int, optional): Verbose level. Defaults to { config.VERBOSE }.
render (bool, optional): Render rollouts to tensorboard.
Defaults to { config.RENDER }.
debug_mode (bool, optional): Log additional info.
Defaults to { config.DEBUG_MODE }
tensorboard_dir (Union[str, None], optional): Path to tensorboard logs.
Defaults to { config.TENSORBOARD_DIR }.
tensorboard_comment (str, optional): Comment for tensorboard files.
Defaults to { config.TENSORBOARD_COMMENT }.
"""
super().__init__(env_name, use_gpu, *args, **kwargs)
assert iterations > 0, f"Iteration has to be positive not {iterations}"
if max_frames is not None:
assert (
max_frames <= iterations * batch_size
), "max_frames should be smaller or equal than iterations * batch_size"
self.max_frames = max_frames
self.gamma = gamma
self.stats_freq = stats_freq
self.test_episodes = test_episodes
self.batch_size = batch_size
self.iterations = iterations
self.return_done = return_done
if log_dir is not None:
self.log_dir = Path(log_dir)
self.log_dir.mkdir(parents=True, exist_ok=True)
else:
self.log_dir = log_dir
self.verbose = verbose
self.render = render
self.max_ep_len = self.env._max_episode_steps
self.start_time = utils.get_time()
self.hparams = {
"hparams/gamma": self.gamma,
"hparams/batch_size": self.batch_size,
"hparams/type": utils.get_pretty_type_name(self),
}
self.shortnames = config.SHORTNAMES
self.stats_logger = StatsLogger()
def train(self, iterations=None):
f""" Train RL model
Args:
iterations ([type], optional): Number of additional training iterations.
If None performs number of iterations defined in self.iterations.
Otherwise increase global counter by this value to run additional steps.
Defaults to { None }.
"""
self.run_tensorboard_if_needed()
if iterations:
self.iterations += iterations
while self.iteration < self.iterations:
buffer, time_diff = self.perform_iteration()
self.stats_logger.time_list.append(time_diff)
running_return = self.stats_logger.calc_running_return(buffer)
if self.return_done is not None and running_return >= self.return_done:
break
if self.iteration % self.stats_freq == 0:
self.logs_after_iteration(buffer)
if self.log_dir is not None:
self.stats_logger.dump_stats(self.log_path)
self.iteration += 1
if (
self.max_frames is not None
and self.max_frames < self.stats_logger.frames
):
logger.info(f"Reached max_frames at {self.iteration} iteration")
break
self.logs_after_iteration(buffer, done=True)
if self.log_dir is not None:
self.save()
def test(self, episodes=None):
f"""Test policy
Args:
episodes (int): Number of episodes. Defaults to { None }.
Returns:
float: mean episode reward
"""
mean_reward = None
return mean_reward
@utils.measure_time
def perform_iteration(self):
raise NotImplementedError
def save_model(self):
raise NotImplementedError
def check_path(self, path):
if self.filename is None and path is None:
raise AttributeError
elif path is None:
path = str(self.log_path) + ".pkl"
return path
def collect_params_dict(self):
params_dict = {}
params_dict["actor"] = self.actor.state_dict()
params_dict["critic"] = self.critic.state_dict()
params_dict["obs_mean"] = self.obs_mean
params_dict["obs_std"] = self.obs_std
return params_dict
def apply_params_dict(self, params_dict):
self.actor.load_state_dict(params_dict["actor"])
self.critic.load_state_dict(params_dict["critic"])
self.obs_mean = params_dict["obs_mean"]
self.obs_std = params_dict["obs_std"]
def save(self, path: str = None):
f"""Save RL object
Args:
path (str): Path to save
"""
path = self.check_path(path)
with open(path, "wb") as f:
params_dict = self.collect_params_dict()
pkl.dump(params_dict, f)
def load(self, path: str):
path = self.check_path(path)
with open(path, "rb") as f:
params_dict = pkl.load(f)
self.apply_params_dict(params_dict)
@property
def log_iteration(self):
return self.iteration // self.stats_freq
@property
def filename(self):
suffix = self.get_tensorboard_hparams_suffix()
suffix += self.tensorboard_comment
filename = self.start_time + suffix
return filename
@property
def log_path(self):
log_path = Path(self.log_dir)
log_path = log_path / self.filename
return log_path
def logs_after_iteration(self, buffer: Memory, done: bool = False):
f"""Logs writer
Args:
buffer (Memory): Buffer used for tensorboard
done (bool, optional): Finalize tensorboard logging due to last iteration.
Defaults to { False }.
"""
if self.test_episodes is not None:
self.stats_logger.test_return = self.test()
running_return = self.stats_logger.running_return
if self.verbose:
if done:
self.stats_logger.task_done(self.iteration)
else:
self.stats_logger.log_stats(self.iteration)
self.stats_logger.stats.append([self.iteration, running_return])
self.stats_logger.reset_time_list()
if self.tensorboard_writer is not None:
self.add_tensorboard_logs(buffer, done)
def add_tensorboard_logs(self, buffer: Memory, done: bool):
self.tensorboard_writer.log_running_return(
self.iteration,
self.stats_logger.frames,
self.stats_logger.rollouts,
self.stats_logger.running_return,
)
if self.test_episodes:
self.tensorboard_writer.log_test_return(
self.iteration,
self.stats_logger.frames,
self.stats_logger.rollouts,
self.stats_logger.test_return,
)
if (self.log_iteration % 5) == 0 or done:
_, rendering_time = self.tensorboard_writer.record_episode(
self, self.iteration, done
)
self.tensorboard_writer.log_returns(self.iteration, buffer)
self.tensorboard_writer.log_actions(self.iteration, buffer)
self.tensorboard_writer.log_observations(self.iteration, buffer)
self.tensorboard_writer.log_loss(self.iteration, self.loss)
def get_tensorboard_hparams_suffix(self):
suffix = ""
for key, val in self.hparams.items():
if key in self.shortnames.keys():
key = self.shortnames[key]
else:
key = key.split("/")[1]
if isinstance(val, float):
val = f"{val:.2}"
else:
val = str(val)
suffix += f"-{key}{val}"
return suffix
def _get_initial_obs_mean_std(
self, obs_norm: Any
) -> Tuple[Optional[torch.tensor], Optional[torch.tensor]]:
f"""
Check if observations are normalized and if so return initial mean and std,
None otherwise.
Returns:
Tuple[Optional[torch.tensor], Optional[torch.tensor]]: obs mean and std
"""
if obs_norm:
obs_mean = torch.zeros(self.ob_dim, device=self.device)
obs_std = torch.ones(self.ob_dim, device=self.device)
else:
obs_mean = None
obs_std = None
return obs_mean, obs_std
| true | true |
f72f22453b31c307baa4b3ff658060219127ff43 | 2,989 | py | Python | main_window.py | isu-enterprise/dacha | 5f8444e156fbed102fd7e25f9f3766538434659e | [
"Apache-2.0"
] | null | null | null | main_window.py | isu-enterprise/dacha | 5f8444e156fbed102fd7e25f9f3766538434659e | [
"Apache-2.0"
] | null | null | null | main_window.py | isu-enterprise/dacha | 5f8444e156fbed102fd7e25f9f3766538434659e | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/main-window.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(673, 558)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 673, 22))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
self.menuDocuments = QtWidgets.QMenu(self.menubar)
self.menuDocuments.setObjectName("menuDocuments")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.toolBar = QtWidgets.QToolBar(MainWindow)
self.toolBar.setObjectName("toolBar")
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
self.actionSomething = QtWidgets.QAction(MainWindow)
self.actionSomething.setEnabled(False)
self.actionSomething.setObjectName("actionSomething")
self.actionQuit = QtWidgets.QAction(MainWindow)
self.actionQuit.setCheckable(False)
self.actionQuit.setObjectName("actionQuit")
self.actionMoney = QtWidgets.QAction(MainWindow)
self.actionMoney.setObjectName("actionMoney")
self.menuFile.addAction(self.actionSomething)
self.menuFile.addSeparator()
self.menuFile.addAction(self.actionQuit)
self.menuDocuments.addAction(self.actionMoney)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuDocuments.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.menuDocuments.setTitle(_translate("MainWindow", "Documents"))
self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
self.actionSomething.setText(_translate("MainWindow", "Something"))
self.actionQuit.setText(_translate("MainWindow", "Quit"))
self.actionMoney.setText(_translate("MainWindow", "Money"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
| 42.7 | 75 | 0.71094 |
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(673, 558)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 673, 22))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
self.menuDocuments = QtWidgets.QMenu(self.menubar)
self.menuDocuments.setObjectName("menuDocuments")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.toolBar = QtWidgets.QToolBar(MainWindow)
self.toolBar.setObjectName("toolBar")
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
self.actionSomething = QtWidgets.QAction(MainWindow)
self.actionSomething.setEnabled(False)
self.actionSomething.setObjectName("actionSomething")
self.actionQuit = QtWidgets.QAction(MainWindow)
self.actionQuit.setCheckable(False)
self.actionQuit.setObjectName("actionQuit")
self.actionMoney = QtWidgets.QAction(MainWindow)
self.actionMoney.setObjectName("actionMoney")
self.menuFile.addAction(self.actionSomething)
self.menuFile.addSeparator()
self.menuFile.addAction(self.actionQuit)
self.menuDocuments.addAction(self.actionMoney)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuDocuments.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.menuDocuments.setTitle(_translate("MainWindow", "Documents"))
self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
self.actionSomething.setText(_translate("MainWindow", "Something"))
self.actionQuit.setText(_translate("MainWindow", "Quit"))
self.actionMoney.setText(_translate("MainWindow", "Money"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
| true | true |
f72f226a2107b3a3b8e9d4e622c36bce5ef81935 | 13,892 | py | Python | rfcs/0010-eaglesong/eaglesong.py | malinoisls01/npx-create-react-app-react-i18n-app-cd-react-i18n-app | ab7d16b9afae8cd9523f0f3afb46dbca83cd42e5 | [
"MIT"
] | 256 | 2018-11-28T04:00:20.000Z | 2022-03-14T13:46:51.000Z | rfcs/0010-eaglesong/eaglesong.py | malinoisls01/npx-create-react-app-react-i18n-app-cd-react-i18n-app | ab7d16b9afae8cd9523f0f3afb46dbca83cd42e5 | [
"MIT"
] | 122 | 2018-11-28T05:20:37.000Z | 2022-03-18T02:31:50.000Z | rfcs/0010-eaglesong/eaglesong.py | malinoisls01/npx-create-react-app-react-i18n-app-cd-react-i18n-app | ab7d16b9afae8cd9523f0f3afb46dbca83cd42e5 | [
"MIT"
] | 155 | 2018-11-28T04:52:13.000Z | 2022-03-28T23:21:12.000Z | def PrintState( state ):
s = ""
for i in range(0, 16):
s += "0x%08x" % state[i]
s += " "
print(s)
def EaglesongPermutation( state ):
N = 43
#PrintState(state)
for i in range(0, N):
state = EaglesongRound(state, i)
return state
def EaglesongRound( state, index ):
# constants
bitmatrix = [[1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1],
[0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1],
[0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1],
[0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0],
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1],
[1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0],
[1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1],
[0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1],
[0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1],
[0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1],
[1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0],
[1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1]]
coefficients = [[0, 2, 4], [0, 13, 22], [0, 4, 19], [0, 3, 14], [0, 27, 31], [0, 3, 8], [0, 17, 26], [0, 3, 12], [0, 18, 22], [0, 12, 18], [0, 4, 7], [0, 4, 31], [0, 12, 27], [0, 7, 17], [0, 7, 8], [0, 1, 13]]
injection_constants = [ 0x6e9e40ae , 0x71927c02 , 0x9a13d3b1 , 0xdaec32ad , 0x3d8951cf , 0xe1c9fe9a , 0xb806b54c , 0xacbbf417 ,
0xd3622b3b , 0xa082762a , 0x9edcf1c0 , 0xa9bada77 , 0x7f91e46c , 0xcb0f6e4f , 0x265d9241 , 0xb7bdeab0 ,
0x6260c9e6 , 0xff50dd2a , 0x9036aa71 , 0xce161879 , 0xd1307cdf , 0x89e456df , 0xf83133e2 , 0x65f55c3d ,
0x94871b01 , 0xb5d204cd , 0x583a3264 , 0x5e165957 , 0x4cbda964 , 0x675fca47 , 0xf4a3033e , 0x2a417322 ,
0x3b61432f , 0x7f5532f2 , 0xb609973b , 0x1a795239 , 0x31b477c9 , 0xd2949d28 , 0x78969712 , 0x0eb87b6e ,
0x7e11d22d , 0xccee88bd , 0xeed07eb8 , 0xe5563a81 , 0xe7cb6bcf , 0x25de953e , 0x4d05653a , 0x0b831557 ,
0x94b9cd77 , 0x13f01579 , 0x794b4a4a , 0x67e7c7dc , 0xc456d8d4 , 0x59689c9b , 0x668456d7 , 0x22d2a2e1 ,
0x38b3a828 , 0x0315ac3c , 0x438d681e , 0xab7109c5 , 0x97ee19a8 , 0xde062b2e , 0x2c76c47b , 0x0084456f ,
0x908f0fd3 , 0xa646551f , 0x3e826725 , 0xd521788e , 0x9f01c2b0 , 0x93180cdc , 0x92ea1df8 , 0x431a9aae ,
0x7c2ea356 , 0xda33ad03 , 0x46926893 , 0x66bde7d7 , 0xb501cc75 , 0x1f6e8a41 , 0x685250f4 , 0x3bb1f318 ,
0xaf238c04 , 0x974ed2ec , 0x5b159e49 , 0xd526f8bf , 0x12085626 , 0x3e2432a9 , 0x6bd20c48 , 0x1f1d59da ,
0x18ab1068 , 0x80f83cf8 , 0x2c8c11c0 , 0x7d548035 , 0x0ff675c3 , 0xfed160bf , 0x74bbbb24 , 0xd98e006b ,
0xdeaa47eb , 0x05f2179e , 0x437b0b71 , 0xa7c95f8f , 0x00a99d3b , 0x3fc3c444 , 0x72686f8e , 0x00fd01a9 ,
0xdedc0787 , 0xc6af7626 , 0x7012fe76 , 0xf2a5f7ce , 0x9a7b2eda , 0x5e57fcf2 , 0x4da0d4ad , 0x5c63b155 ,
0x34117375 , 0xd4134c11 , 0x2ea77435 , 0x5278b6de , 0xab522c4c , 0xbc8fc702 , 0xc94a09e4 , 0xebb93a9e ,
0x91ecb65e , 0x4c52ecc6 , 0x8703bb52 , 0xcb2d60aa , 0x30a0538a , 0x1514f10b , 0x157f6329 , 0x3429dc3d ,
0x5db73eb2 , 0xa7a1a969 , 0x7286bd24 , 0x0df6881e , 0x3785ba5f , 0xcd04623a , 0x02758170 , 0xd827f556 ,
0x99d95191 , 0x84457eb1 , 0x58a7fb22 , 0xd2967c5f , 0x4f0c33f6 , 0x4a02099a , 0xe0904821 , 0x94124036 ,
0x496a031b , 0x780b69c4 , 0xcf1a4927 , 0x87a119b8 , 0xcdfaf4f8 , 0x4cf9cd0f , 0x27c96a84 , 0x6d11117e ,
0x7f8cf847 , 0x74ceede5 , 0xc88905e6 , 0x60215841 , 0x7172875a , 0x736e993a , 0x010aa53c , 0x43d53c2b ,
0xf0d91a93 , 0x0d983b56 , 0xf816663c , 0xe5d13363 , 0x0a61737c , 0x09d51150 , 0x83a5ac2f , 0x3e884905 ,
0x7b01aeb5 , 0x600a6ea7 , 0xb7678f7b , 0x72b38977 , 0x068018f2 , 0xce6ae45b , 0x29188aa8 , 0xe5a0b1e9 ,
0xc04c2b86 , 0x8bd14d75 , 0x648781f3 , 0xdbae1e0a , 0xddcdd8ae , 0xab4d81a3 , 0x446baaba , 0x1cc0c19d ,
0x17be4f90 , 0x82c0e65d , 0x676f9c95 , 0x5c708db2 , 0x6fd4c867 , 0xa5106ef0 , 0x19dde49d , 0x78182f95 ,
0xd089cd81 , 0xa32e98fe , 0xbe306c82 , 0x6cd83d8c , 0x037f1bde , 0x0b15722d , 0xeddc1e22 , 0x93c76559 ,
0x8a2f571b , 0x92cc81b4 , 0x021b7477 , 0x67523904 , 0xc95dbccc , 0xac17ee9d , 0x944e46bc , 0x0781867e ,
0xc854dd9d , 0x26e2c30c , 0x858c0416 , 0x6d397708 , 0xebe29c58 , 0xc80ced86 , 0xd496b4ab , 0xbe45e6f5 ,
0x10d24706 , 0xacf8187a , 0x96f523cb , 0x2227e143 , 0x78c36564 , 0x4643adc2 , 0x4729d97a , 0xcff93e0d ,
0x25484bbd , 0x91c6798e , 0x95f773f4 , 0x44204675 , 0x2eda57ba , 0x06d313ef , 0xeeaa4466 , 0x2dfa7530 ,
0xa8af0c9b , 0x39f1535e , 0x0cc2b7bd , 0x38a76c0e , 0x4f41071d , 0xcdaf2475 , 0x49a6eff8 , 0x01621748 ,
0x36ebacab , 0xbd6d9a29 , 0x44d1cd65 , 0x40815dfd , 0x55fa5a1a , 0x87cce9e9 , 0xae559b45 , 0xd76b4c26 ,
0x637d60ad , 0xde29f5f9 , 0x97491cbb , 0xfb350040 , 0xffe7f997 , 0x201c9dcd , 0xe61320e9 , 0xa90987a3 ,
0xe24afa83 , 0x61c1e6fc , 0xcc87ff62 , 0xf1c9d8fa , 0x4fd04546 , 0x90ecc76e , 0x46e456b9 , 0x305dceb8 ,
0xf627e68c , 0x2d286815 , 0xc705bbfd , 0x101b6df3 , 0x892dae62 , 0xd5b7fb44 , 0xea1d5c94 , 0x5332e3cb ,
0xf856f88a , 0xb341b0e9 , 0x28408d9d , 0x5421bc17 , 0xeb9af9bc , 0x602371c5 , 0x67985a91 , 0xd774907f ,
0x7c4d697d , 0x9370b0b8 , 0x6ff5cebb , 0x7d465744 , 0x674ceac0 , 0xea9102fc , 0x0de94784 , 0xc793de69 ,
0xfe599bb1 , 0xc6ad952f , 0x6d6ca9c3 , 0x928c3f91 , 0xf9022f05 , 0x24a164dc , 0xe5e98cd3 , 0x7649efdb ,
0x6df3bcdb , 0x5d1e9ff1 , 0x17f5d010 , 0xe2686ea1 , 0x6eac77fe , 0x7bb5c585 , 0x88d90cbb , 0x18689163 ,
0x67c9efa5 , 0xc0b76d9b , 0x960efbab , 0xbd872807 , 0x70f4c474 , 0x56c29d20 , 0xd1541d15 , 0x88137033 ,
0xe3f02b3e , 0xb6d9b28d , 0x53a077ba , 0xeedcd29e , 0xa50a6c1d , 0x12c2801e , 0x52ba335b , 0x35984614 ,
0xe2599aa8 , 0xaf94ed1d , 0xd90d4767 , 0x202c7d07 , 0x77bec4f4 , 0xfa71bc80 , 0xfc5c8b76 , 0x8d0fbbfc ,
0xda366dc6 , 0x8b32a0c7 , 0x1b36f7fc , 0x6642dcbc , 0x6fe7e724 , 0x8b5fa782 , 0xc4227404 , 0x3a7d1da7 ,
0x517ed658 , 0x8a18df6d , 0x3e5c9b23 , 0x1fbd51ef , 0x1470601d , 0x3400389c , 0x676b065d , 0x8864ad80 ,
0xea6f1a9c , 0x2db484e1 , 0x608785f0 , 0x8dd384af , 0x69d26699 , 0x409c4e16 , 0x77f9986a , 0x7f491266 ,
0x883ea6cf , 0xeaa06072 , 0xfa2e5db5 , 0x352594b4 , 0x9156bb89 , 0xa2fbbbfb , 0xac3989c7 , 0x6e2422b1 ,
0x581f3560 , 0x1009a9b5 , 0x7e5ad9cd , 0xa9fc0a6e , 0x43e5998e , 0x7f8778f9 , 0xf038f8e1 , 0x5415c2e8 ,
0x6499b731 , 0xb82389ae , 0x05d4d819 , 0x0f06440e , 0xf1735aa0 , 0x986430ee , 0x47ec952c , 0xbf149cc5 ,
0xb3cb2cb6 , 0x3f41e8c2 , 0x271ac51b , 0x48ac5ded , 0xf76a0469 , 0x717bba4d , 0x4f5c90d6 , 0x3b74f756 ,
0x1824110a , 0xa4fd43e3 , 0x1eb0507c , 0xa9375c08 , 0x157c59a7 , 0x0cad8f51 , 0xd66031a0 , 0xabb5343f ,
0xe533fa43 , 0x1996e2bb , 0xd7953a71 , 0xd2529b94 , 0x58f0fa07 , 0x4c9b1877 , 0x057e990d , 0x8bfe19c4 ,
0xa8e2c0c9 , 0x99fcaada , 0x69d2aaca , 0xdc1c4642 , 0xf4d22307 , 0x7fe27e8c , 0x1366aa07 , 0x1594e637 ,
0xce1066bf , 0xdb922552 , 0x9930b52a , 0xaeaa9a3e , 0x31ff7eb4 , 0x5e1f945a , 0x150ac49c , 0x0ccdac2d ,
0xd8a8a217 , 0xb82ea6e5 , 0xd6a74659 , 0x67b7e3e6 , 0x836eef4a , 0xb6f90074 , 0x7fa3ea4b , 0xcb038123 ,
0xbf069f55 , 0x1fa83fc4 , 0xd6ebdb23 , 0x16f0a137 , 0x19a7110d , 0x5ff3b55f , 0xfb633868 , 0xb466f845 ,
0xbce0c198 , 0x88404296 , 0xddbdd88b , 0x7fc52546 , 0x63a553f8 , 0xa728405a , 0x378a2bce , 0x6862e570 ,
0xefb77e7d , 0xc611625e , 0x32515c15 , 0x6984b765 , 0xe8405976 , 0x9ba386fd , 0xd4eed4d9 , 0xf8fe0309 ,
0x0ce54601 , 0xbaf879c2 , 0xd8524057 , 0x1d8c1d7a , 0x72c0a3a9 , 0x5a1ffbde , 0x82f33a45 , 0x5143f446 ,
0x29c7e182 , 0xe536c32f , 0x5a6f245b , 0x44272adb , 0xcb701d9c , 0xf76137ec , 0x0841f145 , 0xe7042ecc ,
0xf1277dd7 , 0x745cf92c , 0xa8fe65fe , 0xd3e2d7cf , 0x54c513ef , 0x6079bc2d , 0xb66336b0 , 0x101e383b ,
0xbcd75753 , 0x25be238a , 0x56a6f0be , 0xeeffcc17 , 0x5ea31f3d , 0x0ae772f5 , 0xf76de3de , 0x1bbecdad ,
0xc9107d43 , 0xf7e38dce , 0x618358cd , 0x5c833f04 , 0xf6975906 , 0xde4177e5 , 0x67d314dc , 0xb4760f3e ,
0x56ce5888 , 0x0e8345a8 , 0xbff6b1bf , 0x78dfb112 , 0xf1709c1e , 0x7bb8ed8b , 0x902402b9 , 0xdaa64ae0 ,
0x46b71d89 , 0x7eee035f , 0xbe376509 , 0x99648f3a , 0x0863ea1f , 0x49ad8887 , 0x79bdecc5 , 0x3c10b568 ,
0x5f2e4bae , 0x04ef20ab , 0x72f8ce7b , 0x521e1ebe , 0x14525535 , 0x2e8af95b , 0x9094ccfd , 0xbcf36713 ,
0xc73953ef , 0xd4b91474 , 0x6554ec2d , 0xe3885c96 , 0x03dc73b7 , 0x931688a9 , 0xcbbef182 , 0x2b77cfc9 ,
0x632a32bd , 0xd2115dcc , 0x1ae5533d , 0x32684e13 , 0x4cc5a004 , 0x13321bde , 0x62cbd38d , 0x78383a3b ,
0xd00686f1 , 0x9f601ee7 , 0x7eaf23de , 0x3110c492 , 0x9c351209 , 0x7eb89d52 , 0x6d566eac , 0xc2efd226 ,
0x32e9fac5 , 0x52227274 , 0x09f84725 , 0xb8d0b605 , 0x72291f02 , 0x71b5c34b , 0x3dbfcbb8 , 0x04a02263 ,
0x55ba597f , 0xd4e4037d , 0xc813e1be , 0xffddeefa , 0xc3c058f3 , 0x87010f2e , 0x1dfcf55f , 0xc694eeeb ,
0xa9c01a74 , 0x98c2fc6b , 0xe57e1428 , 0xdd265a71 , 0x836b956d , 0x7e46ab1a , 0x5835d541 , 0x50b32505 ,
0xe640913c , 0xbb486079 , 0xfe496263 , 0x113c5b69 , 0x93cd6620 , 0x5efe823b , 0x2d657b40 , 0xb46dfc6c ,
0x57710c69 , 0xfe9fadeb , 0xb5f8728a , 0xe3224170 , 0xca28b751 , 0xfdabae56 , 0x5ab12c3c , 0xa697c457 ,
0xd28fa2b7 , 0x056579f2 , 0x9fd9d810 , 0xe3557478 , 0xd88d89ab , 0xa72a9422 , 0x6d47abd0 , 0x405bcbd9 ,
0x6f83ebaf , 0x13caec76 , 0xfceb9ee2 , 0x2e922df7 , 0xce9856df , 0xc05e9322 , 0x2772c854 , 0xb67f2a32 ,
0x6d1af28d , 0x3a78cf77 , 0xdff411e4 , 0x61c74ca9 , 0xed8b842e , 0x72880845 , 0x6e857085 , 0xc6404932 ,
0xee37f6bc , 0x27116f48 , 0x5e9ec45a , 0x8ea2a51f , 0xa5573db7 , 0xa746d036 , 0x486b4768 , 0x5b438f3b ,
0x18c54a5c , 0x64fcf08e , 0xe993cdc1 , 0x35c1ead3 , 0x9de07de7 , 0x321b841c , 0x87423c5e , 0x071aa0f6 ,
0x962eb75b , 0xbb06bdd2 , 0xdcdb5363 , 0x389752f2 , 0x83d9cc88 , 0xd014adc6 , 0xc71121bb , 0x2372f938 ,
0xcaff2650 , 0x62be8951 , 0x56dccaff , 0xac4084c0 , 0x09712e95 , 0x1d3c288f , 0x1b085744 , 0xe1d3cfef ,
0x5c9a812e , 0x6611fd59 , 0x85e46044 , 0x1981d885 , 0x5a4c903f , 0x43f30d4b , 0x7d1d601b , 0xdd3c3391 ,
0x030ec65e , 0xc12878cd , 0x72e795fe , 0xd0c76abd , 0x1ec085db , 0x7cbb61fa , 0x93e8dd1e , 0x8582eb06 ,
0x73563144 , 0x049d4e7e , 0x5fd5aefe , 0x7b842a00 , 0x75ced665 , 0xbb32d458 , 0x4e83bba7 , 0x8f15151f ,
0x7795a125 , 0xf0842455 , 0x499af99d , 0x565cc7fa , 0xa3b1278d , 0x3f27ce74 , 0x96ca058e , 0x8a497443 ,
0xa6fb8cae , 0xc115aa21 , 0x17504923 , 0xe4932402 , 0xaea886c2 , 0x8eb79af5 , 0xebd5ea6b , 0xc7980d3b ,
0x71369315 , 0x796e6a66 , 0x3a7ec708 , 0xb05175c8 , 0xe02b74e7 , 0xeb377ad3 , 0x6c8c1f54 , 0xb980c374 ,
0x59aee281 , 0x449cb799 , 0xe01f5605 , 0xed0e085e , 0xc9a1a3b4 , 0xaac481b1 , 0xc935c39c , 0xb7d8ce7f ]
# bit matrix
new = [0 for i in range(0,16)]
for j in range(0, 16):
for k in range(0, 16):
new[j] = new[j] ^ (state[k] * bitmatrix[k][j])
new[j] = new[j] & 0xffffffff # truncate to 32 bits, if necessary
state = new
# circulant multiplication
for i in range(0, 16):
acc = 0
for j in range(0, 3):
acc = acc ^ (state[i] << coefficients[i][j]) ^ (state[i] >> (32-coefficients[i][j]))
state[i] = acc & 0xffffffff # truncate to 32 bits, if necessary
# constants injection
for i in range(0, 16):
state[i] = state[i] ^ injection_constants[index*16 + i]
# add / rotate / add
for i in range(0, 8):
state[2*i] = (state[2*i] + state[2*i+1]) & 0xffffffff # truncate to 32 bits, if necessary
state[2*i] = (state[2*i] >> 24) ^ ((state[2*i] << 8) & 0xffffffff) # shift bytes
state[2*i+1] = (state[2*i+1] >> 8) ^ ((state[2*i+1] << 24) & 0xffffffff) # shift bytes
state[2*i+1] = (state[2*i] + state[2*i+1]) & 0xffffffff # truncate to 32 bits, if necessary
return state
def EaglesongSponge( input_bytes, num_output_bytes, delimiter ):
# parameters
capacity = 256 # must be multiple of 32
rate = 256 # must be multiple of 32
state = [0 for i in range(0, 16)]
# absorbing
for i in range(0, ((len(input_bytes)+1)*8+rate-1) // rate):
for j in range(0, rate//32):
integer = 0
for k in range(0, 4):
if i*rate//8 + j*4 + k < len(input_bytes):
integer = (integer << 8) ^ input_bytes[i*rate//8 + j*4 + k]
elif i*rate//8 + j*4 + k == len(input_bytes):
integer = (integer << 8) ^ delimiter
state[j] = state[j] ^ integer
state = EaglesongPermutation(state)
# squeezing
output_bytes = [0] * num_output_bytes
for i in range(0, num_output_bytes//(rate//8)):
for j in range(0, rate//32):
for k in range(0, 4):
output_bytes[i*rate//8 + j*4 + k] = (state[j] >> (8*k)) & 0xff
state = EaglesongPermutation(state)
return output_bytes
def EaglesongHash( input_bytes ):
# just run the sponge (with delimiter 0x06 -- hashing mode) and truncate to 32 bytes == 256 bits
return EaglesongSponge(bytearray(input_bytes), 32, 0x06)
| 75.5 | 213 | 0.628707 | def PrintState( state ):
s = ""
for i in range(0, 16):
s += "0x%08x" % state[i]
s += " "
print(s)
def EaglesongPermutation( state ):
N = 43
for i in range(0, N):
state = EaglesongRound(state, i)
return state
def EaglesongRound( state, index ):
bitmatrix = [[1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1],
[0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1],
[0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1],
[0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0],
[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1],
[1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0],
[1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1],
[0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1],
[0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1],
[0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1],
[1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0],
[1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1]]
coefficients = [[0, 2, 4], [0, 13, 22], [0, 4, 19], [0, 3, 14], [0, 27, 31], [0, 3, 8], [0, 17, 26], [0, 3, 12], [0, 18, 22], [0, 12, 18], [0, 4, 7], [0, 4, 31], [0, 12, 27], [0, 7, 17], [0, 7, 8], [0, 1, 13]]
injection_constants = [ 0x6e9e40ae , 0x71927c02 , 0x9a13d3b1 , 0xdaec32ad , 0x3d8951cf , 0xe1c9fe9a , 0xb806b54c , 0xacbbf417 ,
0xd3622b3b , 0xa082762a , 0x9edcf1c0 , 0xa9bada77 , 0x7f91e46c , 0xcb0f6e4f , 0x265d9241 , 0xb7bdeab0 ,
0x6260c9e6 , 0xff50dd2a , 0x9036aa71 , 0xce161879 , 0xd1307cdf , 0x89e456df , 0xf83133e2 , 0x65f55c3d ,
0x94871b01 , 0xb5d204cd , 0x583a3264 , 0x5e165957 , 0x4cbda964 , 0x675fca47 , 0xf4a3033e , 0x2a417322 ,
0x3b61432f , 0x7f5532f2 , 0xb609973b , 0x1a795239 , 0x31b477c9 , 0xd2949d28 , 0x78969712 , 0x0eb87b6e ,
0x7e11d22d , 0xccee88bd , 0xeed07eb8 , 0xe5563a81 , 0xe7cb6bcf , 0x25de953e , 0x4d05653a , 0x0b831557 ,
0x94b9cd77 , 0x13f01579 , 0x794b4a4a , 0x67e7c7dc , 0xc456d8d4 , 0x59689c9b , 0x668456d7 , 0x22d2a2e1 ,
0x38b3a828 , 0x0315ac3c , 0x438d681e , 0xab7109c5 , 0x97ee19a8 , 0xde062b2e , 0x2c76c47b , 0x0084456f ,
0x908f0fd3 , 0xa646551f , 0x3e826725 , 0xd521788e , 0x9f01c2b0 , 0x93180cdc , 0x92ea1df8 , 0x431a9aae ,
0x7c2ea356 , 0xda33ad03 , 0x46926893 , 0x66bde7d7 , 0xb501cc75 , 0x1f6e8a41 , 0x685250f4 , 0x3bb1f318 ,
0xaf238c04 , 0x974ed2ec , 0x5b159e49 , 0xd526f8bf , 0x12085626 , 0x3e2432a9 , 0x6bd20c48 , 0x1f1d59da ,
0x18ab1068 , 0x80f83cf8 , 0x2c8c11c0 , 0x7d548035 , 0x0ff675c3 , 0xfed160bf , 0x74bbbb24 , 0xd98e006b ,
0xdeaa47eb , 0x05f2179e , 0x437b0b71 , 0xa7c95f8f , 0x00a99d3b , 0x3fc3c444 , 0x72686f8e , 0x00fd01a9 ,
0xdedc0787 , 0xc6af7626 , 0x7012fe76 , 0xf2a5f7ce , 0x9a7b2eda , 0x5e57fcf2 , 0x4da0d4ad , 0x5c63b155 ,
0x34117375 , 0xd4134c11 , 0x2ea77435 , 0x5278b6de , 0xab522c4c , 0xbc8fc702 , 0xc94a09e4 , 0xebb93a9e ,
0x91ecb65e , 0x4c52ecc6 , 0x8703bb52 , 0xcb2d60aa , 0x30a0538a , 0x1514f10b , 0x157f6329 , 0x3429dc3d ,
0x5db73eb2 , 0xa7a1a969 , 0x7286bd24 , 0x0df6881e , 0x3785ba5f , 0xcd04623a , 0x02758170 , 0xd827f556 ,
0x99d95191 , 0x84457eb1 , 0x58a7fb22 , 0xd2967c5f , 0x4f0c33f6 , 0x4a02099a , 0xe0904821 , 0x94124036 ,
0x496a031b , 0x780b69c4 , 0xcf1a4927 , 0x87a119b8 , 0xcdfaf4f8 , 0x4cf9cd0f , 0x27c96a84 , 0x6d11117e ,
0x7f8cf847 , 0x74ceede5 , 0xc88905e6 , 0x60215841 , 0x7172875a , 0x736e993a , 0x010aa53c , 0x43d53c2b ,
0xf0d91a93 , 0x0d983b56 , 0xf816663c , 0xe5d13363 , 0x0a61737c , 0x09d51150 , 0x83a5ac2f , 0x3e884905 ,
0x7b01aeb5 , 0x600a6ea7 , 0xb7678f7b , 0x72b38977 , 0x068018f2 , 0xce6ae45b , 0x29188aa8 , 0xe5a0b1e9 ,
0xc04c2b86 , 0x8bd14d75 , 0x648781f3 , 0xdbae1e0a , 0xddcdd8ae , 0xab4d81a3 , 0x446baaba , 0x1cc0c19d ,
0x17be4f90 , 0x82c0e65d , 0x676f9c95 , 0x5c708db2 , 0x6fd4c867 , 0xa5106ef0 , 0x19dde49d , 0x78182f95 ,
0xd089cd81 , 0xa32e98fe , 0xbe306c82 , 0x6cd83d8c , 0x037f1bde , 0x0b15722d , 0xeddc1e22 , 0x93c76559 ,
0x8a2f571b , 0x92cc81b4 , 0x021b7477 , 0x67523904 , 0xc95dbccc , 0xac17ee9d , 0x944e46bc , 0x0781867e ,
0xc854dd9d , 0x26e2c30c , 0x858c0416 , 0x6d397708 , 0xebe29c58 , 0xc80ced86 , 0xd496b4ab , 0xbe45e6f5 ,
0x10d24706 , 0xacf8187a , 0x96f523cb , 0x2227e143 , 0x78c36564 , 0x4643adc2 , 0x4729d97a , 0xcff93e0d ,
0x25484bbd , 0x91c6798e , 0x95f773f4 , 0x44204675 , 0x2eda57ba , 0x06d313ef , 0xeeaa4466 , 0x2dfa7530 ,
0xa8af0c9b , 0x39f1535e , 0x0cc2b7bd , 0x38a76c0e , 0x4f41071d , 0xcdaf2475 , 0x49a6eff8 , 0x01621748 ,
0x36ebacab , 0xbd6d9a29 , 0x44d1cd65 , 0x40815dfd , 0x55fa5a1a , 0x87cce9e9 , 0xae559b45 , 0xd76b4c26 ,
0x637d60ad , 0xde29f5f9 , 0x97491cbb , 0xfb350040 , 0xffe7f997 , 0x201c9dcd , 0xe61320e9 , 0xa90987a3 ,
0xe24afa83 , 0x61c1e6fc , 0xcc87ff62 , 0xf1c9d8fa , 0x4fd04546 , 0x90ecc76e , 0x46e456b9 , 0x305dceb8 ,
0xf627e68c , 0x2d286815 , 0xc705bbfd , 0x101b6df3 , 0x892dae62 , 0xd5b7fb44 , 0xea1d5c94 , 0x5332e3cb ,
0xf856f88a , 0xb341b0e9 , 0x28408d9d , 0x5421bc17 , 0xeb9af9bc , 0x602371c5 , 0x67985a91 , 0xd774907f ,
0x7c4d697d , 0x9370b0b8 , 0x6ff5cebb , 0x7d465744 , 0x674ceac0 , 0xea9102fc , 0x0de94784 , 0xc793de69 ,
0xfe599bb1 , 0xc6ad952f , 0x6d6ca9c3 , 0x928c3f91 , 0xf9022f05 , 0x24a164dc , 0xe5e98cd3 , 0x7649efdb ,
0x6df3bcdb , 0x5d1e9ff1 , 0x17f5d010 , 0xe2686ea1 , 0x6eac77fe , 0x7bb5c585 , 0x88d90cbb , 0x18689163 ,
0x67c9efa5 , 0xc0b76d9b , 0x960efbab , 0xbd872807 , 0x70f4c474 , 0x56c29d20 , 0xd1541d15 , 0x88137033 ,
0xe3f02b3e , 0xb6d9b28d , 0x53a077ba , 0xeedcd29e , 0xa50a6c1d , 0x12c2801e , 0x52ba335b , 0x35984614 ,
0xe2599aa8 , 0xaf94ed1d , 0xd90d4767 , 0x202c7d07 , 0x77bec4f4 , 0xfa71bc80 , 0xfc5c8b76 , 0x8d0fbbfc ,
0xda366dc6 , 0x8b32a0c7 , 0x1b36f7fc , 0x6642dcbc , 0x6fe7e724 , 0x8b5fa782 , 0xc4227404 , 0x3a7d1da7 ,
0x517ed658 , 0x8a18df6d , 0x3e5c9b23 , 0x1fbd51ef , 0x1470601d , 0x3400389c , 0x676b065d , 0x8864ad80 ,
0xea6f1a9c , 0x2db484e1 , 0x608785f0 , 0x8dd384af , 0x69d26699 , 0x409c4e16 , 0x77f9986a , 0x7f491266 ,
0x883ea6cf , 0xeaa06072 , 0xfa2e5db5 , 0x352594b4 , 0x9156bb89 , 0xa2fbbbfb , 0xac3989c7 , 0x6e2422b1 ,
0x581f3560 , 0x1009a9b5 , 0x7e5ad9cd , 0xa9fc0a6e , 0x43e5998e , 0x7f8778f9 , 0xf038f8e1 , 0x5415c2e8 ,
0x6499b731 , 0xb82389ae , 0x05d4d819 , 0x0f06440e , 0xf1735aa0 , 0x986430ee , 0x47ec952c , 0xbf149cc5 ,
0xb3cb2cb6 , 0x3f41e8c2 , 0x271ac51b , 0x48ac5ded , 0xf76a0469 , 0x717bba4d , 0x4f5c90d6 , 0x3b74f756 ,
0x1824110a , 0xa4fd43e3 , 0x1eb0507c , 0xa9375c08 , 0x157c59a7 , 0x0cad8f51 , 0xd66031a0 , 0xabb5343f ,
0xe533fa43 , 0x1996e2bb , 0xd7953a71 , 0xd2529b94 , 0x58f0fa07 , 0x4c9b1877 , 0x057e990d , 0x8bfe19c4 ,
0xa8e2c0c9 , 0x99fcaada , 0x69d2aaca , 0xdc1c4642 , 0xf4d22307 , 0x7fe27e8c , 0x1366aa07 , 0x1594e637 ,
0xce1066bf , 0xdb922552 , 0x9930b52a , 0xaeaa9a3e , 0x31ff7eb4 , 0x5e1f945a , 0x150ac49c , 0x0ccdac2d ,
0xd8a8a217 , 0xb82ea6e5 , 0xd6a74659 , 0x67b7e3e6 , 0x836eef4a , 0xb6f90074 , 0x7fa3ea4b , 0xcb038123 ,
0xbf069f55 , 0x1fa83fc4 , 0xd6ebdb23 , 0x16f0a137 , 0x19a7110d , 0x5ff3b55f , 0xfb633868 , 0xb466f845 ,
0xbce0c198 , 0x88404296 , 0xddbdd88b , 0x7fc52546 , 0x63a553f8 , 0xa728405a , 0x378a2bce , 0x6862e570 ,
0xefb77e7d , 0xc611625e , 0x32515c15 , 0x6984b765 , 0xe8405976 , 0x9ba386fd , 0xd4eed4d9 , 0xf8fe0309 ,
0x0ce54601 , 0xbaf879c2 , 0xd8524057 , 0x1d8c1d7a , 0x72c0a3a9 , 0x5a1ffbde , 0x82f33a45 , 0x5143f446 ,
0x29c7e182 , 0xe536c32f , 0x5a6f245b , 0x44272adb , 0xcb701d9c , 0xf76137ec , 0x0841f145 , 0xe7042ecc ,
0xf1277dd7 , 0x745cf92c , 0xa8fe65fe , 0xd3e2d7cf , 0x54c513ef , 0x6079bc2d , 0xb66336b0 , 0x101e383b ,
0xbcd75753 , 0x25be238a , 0x56a6f0be , 0xeeffcc17 , 0x5ea31f3d , 0x0ae772f5 , 0xf76de3de , 0x1bbecdad ,
0xc9107d43 , 0xf7e38dce , 0x618358cd , 0x5c833f04 , 0xf6975906 , 0xde4177e5 , 0x67d314dc , 0xb4760f3e ,
0x56ce5888 , 0x0e8345a8 , 0xbff6b1bf , 0x78dfb112 , 0xf1709c1e , 0x7bb8ed8b , 0x902402b9 , 0xdaa64ae0 ,
0x46b71d89 , 0x7eee035f , 0xbe376509 , 0x99648f3a , 0x0863ea1f , 0x49ad8887 , 0x79bdecc5 , 0x3c10b568 ,
0x5f2e4bae , 0x04ef20ab , 0x72f8ce7b , 0x521e1ebe , 0x14525535 , 0x2e8af95b , 0x9094ccfd , 0xbcf36713 ,
0xc73953ef , 0xd4b91474 , 0x6554ec2d , 0xe3885c96 , 0x03dc73b7 , 0x931688a9 , 0xcbbef182 , 0x2b77cfc9 ,
0x632a32bd , 0xd2115dcc , 0x1ae5533d , 0x32684e13 , 0x4cc5a004 , 0x13321bde , 0x62cbd38d , 0x78383a3b ,
0xd00686f1 , 0x9f601ee7 , 0x7eaf23de , 0x3110c492 , 0x9c351209 , 0x7eb89d52 , 0x6d566eac , 0xc2efd226 ,
0x32e9fac5 , 0x52227274 , 0x09f84725 , 0xb8d0b605 , 0x72291f02 , 0x71b5c34b , 0x3dbfcbb8 , 0x04a02263 ,
0x55ba597f , 0xd4e4037d , 0xc813e1be , 0xffddeefa , 0xc3c058f3 , 0x87010f2e , 0x1dfcf55f , 0xc694eeeb ,
0xa9c01a74 , 0x98c2fc6b , 0xe57e1428 , 0xdd265a71 , 0x836b956d , 0x7e46ab1a , 0x5835d541 , 0x50b32505 ,
0xe640913c , 0xbb486079 , 0xfe496263 , 0x113c5b69 , 0x93cd6620 , 0x5efe823b , 0x2d657b40 , 0xb46dfc6c ,
0x57710c69 , 0xfe9fadeb , 0xb5f8728a , 0xe3224170 , 0xca28b751 , 0xfdabae56 , 0x5ab12c3c , 0xa697c457 ,
0xd28fa2b7 , 0x056579f2 , 0x9fd9d810 , 0xe3557478 , 0xd88d89ab , 0xa72a9422 , 0x6d47abd0 , 0x405bcbd9 ,
0x6f83ebaf , 0x13caec76 , 0xfceb9ee2 , 0x2e922df7 , 0xce9856df , 0xc05e9322 , 0x2772c854 , 0xb67f2a32 ,
0x6d1af28d , 0x3a78cf77 , 0xdff411e4 , 0x61c74ca9 , 0xed8b842e , 0x72880845 , 0x6e857085 , 0xc6404932 ,
0xee37f6bc , 0x27116f48 , 0x5e9ec45a , 0x8ea2a51f , 0xa5573db7 , 0xa746d036 , 0x486b4768 , 0x5b438f3b ,
0x18c54a5c , 0x64fcf08e , 0xe993cdc1 , 0x35c1ead3 , 0x9de07de7 , 0x321b841c , 0x87423c5e , 0x071aa0f6 ,
0x962eb75b , 0xbb06bdd2 , 0xdcdb5363 , 0x389752f2 , 0x83d9cc88 , 0xd014adc6 , 0xc71121bb , 0x2372f938 ,
0xcaff2650 , 0x62be8951 , 0x56dccaff , 0xac4084c0 , 0x09712e95 , 0x1d3c288f , 0x1b085744 , 0xe1d3cfef ,
0x5c9a812e , 0x6611fd59 , 0x85e46044 , 0x1981d885 , 0x5a4c903f , 0x43f30d4b , 0x7d1d601b , 0xdd3c3391 ,
0x030ec65e , 0xc12878cd , 0x72e795fe , 0xd0c76abd , 0x1ec085db , 0x7cbb61fa , 0x93e8dd1e , 0x8582eb06 ,
0x73563144 , 0x049d4e7e , 0x5fd5aefe , 0x7b842a00 , 0x75ced665 , 0xbb32d458 , 0x4e83bba7 , 0x8f15151f ,
0x7795a125 , 0xf0842455 , 0x499af99d , 0x565cc7fa , 0xa3b1278d , 0x3f27ce74 , 0x96ca058e , 0x8a497443 ,
0xa6fb8cae , 0xc115aa21 , 0x17504923 , 0xe4932402 , 0xaea886c2 , 0x8eb79af5 , 0xebd5ea6b , 0xc7980d3b ,
0x71369315 , 0x796e6a66 , 0x3a7ec708 , 0xb05175c8 , 0xe02b74e7 , 0xeb377ad3 , 0x6c8c1f54 , 0xb980c374 ,
0x59aee281 , 0x449cb799 , 0xe01f5605 , 0xed0e085e , 0xc9a1a3b4 , 0xaac481b1 , 0xc935c39c , 0xb7d8ce7f ]
new = [0 for i in range(0,16)]
for j in range(0, 16):
for k in range(0, 16):
new[j] = new[j] ^ (state[k] * bitmatrix[k][j])
new[j] = new[j] & 0xffffffff
state = new
for i in range(0, 16):
acc = 0
for j in range(0, 3):
acc = acc ^ (state[i] << coefficients[i][j]) ^ (state[i] >> (32-coefficients[i][j]))
state[i] = acc & 0xffffffff
for i in range(0, 16):
state[i] = state[i] ^ injection_constants[index*16 + i]
for i in range(0, 8):
state[2*i] = (state[2*i] + state[2*i+1]) & 0xffffffff
state[2*i] = (state[2*i] >> 24) ^ ((state[2*i] << 8) & 0xffffffff)
state[2*i+1] = (state[2*i+1] >> 8) ^ ((state[2*i+1] << 24) & 0xffffffff)
state[2*i+1] = (state[2*i] + state[2*i+1]) & 0xffffffff
return state
def EaglesongSponge( input_bytes, num_output_bytes, delimiter ):
capacity = 256
rate = 256
state = [0 for i in range(0, 16)]
for i in range(0, ((len(input_bytes)+1)*8+rate-1) // rate):
for j in range(0, rate//32):
integer = 0
for k in range(0, 4):
if i*rate//8 + j*4 + k < len(input_bytes):
integer = (integer << 8) ^ input_bytes[i*rate//8 + j*4 + k]
elif i*rate//8 + j*4 + k == len(input_bytes):
integer = (integer << 8) ^ delimiter
state[j] = state[j] ^ integer
state = EaglesongPermutation(state)
output_bytes = [0] * num_output_bytes
for i in range(0, num_output_bytes//(rate//8)):
for j in range(0, rate//32):
for k in range(0, 4):
output_bytes[i*rate//8 + j*4 + k] = (state[j] >> (8*k)) & 0xff
state = EaglesongPermutation(state)
return output_bytes
def EaglesongHash( input_bytes ):
return EaglesongSponge(bytearray(input_bytes), 32, 0x06)
| true | true |
f72f22a0fe94fdce3a0eac34cb4c8736d4df683c | 19,363 | py | Python | pynndescent/utils.py | samggreenberg/pynndescent | f97bc2fe01e4e59c5dad20ed23b9cb47e8182b6c | [
"BSD-2-Clause"
] | null | null | null | pynndescent/utils.py | samggreenberg/pynndescent | f97bc2fe01e4e59c5dad20ed23b9cb47e8182b6c | [
"BSD-2-Clause"
] | null | null | null | pynndescent/utils.py | samggreenberg/pynndescent | f97bc2fe01e4e59c5dad20ed23b9cb47e8182b6c | [
"BSD-2-Clause"
] | null | null | null | # Author: Leland McInnes <leland.mcinnes@gmail.com>
#
# License: BSD 2 clause
import time
import numba
from numba.core import types
import numba.experimental.structref as structref
import numpy as np
@numba.njit("void(i8[:], i8)", cache=True)
def seed(rng_state, seed):
"""Seed the random number generator with a given seed."""
rng_state.fill(seed + 0xFFFF)
@numba.njit("i4(i8[:])", cache=True)
def tau_rand_int(state):
"""A fast (pseudo)-random number generator.
Parameters
----------
state: array of int64, shape (3,)
The internal state of the rng
Returns
-------
A (pseudo)-random int32 value
"""
state[0] = (((state[0] & 4294967294) << 12) & 0xFFFFFFFF) ^ (
(((state[0] << 13) & 0xFFFFFFFF) ^ state[0]) >> 19
)
state[1] = (((state[1] & 4294967288) << 4) & 0xFFFFFFFF) ^ (
(((state[1] << 2) & 0xFFFFFFFF) ^ state[1]) >> 25
)
state[2] = (((state[2] & 4294967280) << 17) & 0xFFFFFFFF) ^ (
(((state[2] << 3) & 0xFFFFFFFF) ^ state[2]) >> 11
)
return state[0] ^ state[1] ^ state[2]
@numba.njit("f4(i8[:])", cache=True)
def tau_rand(state):
"""A fast (pseudo)-random number generator for floats in the range [0,1]
Parameters
----------
state: array of int64, shape (3,)
The internal state of the rng
Returns
-------
A (pseudo)-random float32 in the interval [0, 1]
"""
integer = tau_rand_int(state)
return abs(float(integer) / 0x7FFFFFFF)
@numba.njit(
[
"f4(f4[::1])",
numba.types.float32(
numba.types.Array(numba.types.float32, 1, "C", readonly=True)
),
],
locals={
"dim": numba.types.intp,
"i": numba.types.uint32,
# "result": numba.types.float32, # This provides speed, but causes errors in corner cases
},
fastmath=True,
cache=True,
)
def norm(vec):
"""Compute the (standard l2) norm of a vector.
Parameters
----------
vec: array of shape (dim,)
Returns
-------
The l2 norm of vec.
"""
result = 0.0
dim = vec.shape[0]
for i in range(dim):
result += vec[i] * vec[i]
return np.sqrt(result)
@numba.njit(cache=True)
def rejection_sample(n_samples, pool_size, rng_state):
"""Generate n_samples many integers from 0 to pool_size such that no
integer is selected twice. The duplication constraint is achieved via
rejection sampling.
Parameters
----------
n_samples: int
The number of random samples to select from the pool
pool_size: int
The size of the total pool of candidates to sample from
rng_state: array of int64, shape (3,)
Internal state of the random number generator
Returns
-------
sample: array of shape(n_samples,)
The ``n_samples`` randomly selected elements from the pool.
"""
result = np.empty(n_samples, dtype=np.int64)
for i in range(n_samples):
reject_sample = True
j = 0
while reject_sample:
j = tau_rand_int(rng_state) % pool_size
for k in range(i):
if j == result[k]:
break
else:
reject_sample = False
result[i] = j
return result
@structref.register
class HeapType(types.StructRef):
pass
class Heap(structref.StructRefProxy):
@property
def indices(self):
return Heap_get_indices(self)
@property
def distances(self):
return Heap_get_distances(self)
@property
def flags(self):
return Heap_get_flags(self)
@numba.njit(cache=True)
def Heap_get_flags(self):
return self.flags
@numba.njit(cache=True)
def Heap_get_distances(self):
return self.distances
@numba.njit(cache=True)
def Heap_get_indices(self):
return self.indices
structref.define_proxy(Heap, HeapType, ["indices", "distances", "flags"])
# Heap = namedtuple("Heap", ("indices", "distances", "flags"))
@numba.njit(cache=True)
def make_heap(n_points, size):
"""Constructor for the numba enabled heap objects. The heaps are used
for approximate nearest neighbor search, maintaining a list of potential
neighbors sorted by their distance. We also flag if potential neighbors
are newly added to the list or not. Internally this is stored as
a single ndarray; the first axis determines whether we are looking at the
array of candidate graph_indices, the array of distances, or the flag array for
whether elements are new or not. Each of these arrays are of shape
(``n_points``, ``size``)
Parameters
----------
n_points: int
The number of graph_data points to track in the heap.
size: int
The number of items to keep on the heap for each graph_data point.
Returns
-------
heap: An ndarray suitable for passing to other numba enabled heap functions.
"""
indices = np.full((int(n_points), int(size)), -1, dtype=np.int32)
distances = np.full((int(n_points), int(size)), np.infty, dtype=np.float32)
flags = np.zeros((int(n_points), int(size)), dtype=np.uint8)
result = (indices, distances, flags)
return result
@numba.njit(cache=True)
def siftdown(heap1, heap2, elt):
"""Restore the heap property for a heap with an out of place element
at position ``elt``. This works with a heap pair where heap1 carries
the weights and heap2 holds the corresponding elements."""
while elt * 2 + 1 < heap1.shape[0]:
left_child = elt * 2 + 1
right_child = left_child + 1
swap = elt
if heap1[swap] < heap1[left_child]:
swap = left_child
if right_child < heap1.shape[0] and heap1[swap] < heap1[right_child]:
swap = right_child
if swap == elt:
break
else:
heap1[elt], heap1[swap] = heap1[swap], heap1[elt]
heap2[elt], heap2[swap] = heap2[swap], heap2[elt]
elt = swap
@numba.njit(parallel=True, cache=False)
def deheap_sort(indices, distances):
"""Given two arrays representing a heap (indices and distances), reorder the
arrays by increasing distance. This is effectively just the second half of
heap sort (the first half not being required since we already have the
graph_data in a heap).
Note that this is done in-place.
Parameters
----------
indices : array of shape (n_samples, n_neighbors)
The graph indices to sort by distance.
distances : array of shape (n_samples, n_neighbors)
The corresponding edge distance.
Returns
-------
indices, distances: arrays of shape (n_samples, n_neighbors)
The indices and distances sorted by increasing distance.
"""
for i in numba.prange(indices.shape[0]):
# starting from the end of the array and moving back
for j in range(indices.shape[1] - 1, 0, -1):
indices[i, 0], indices[i, j] = indices[i, j], indices[i, 0]
distances[i, 0], distances[i, j] = distances[i, j], distances[i, 0]
siftdown(distances[i, :j], indices[i, :j], 0)
return indices, distances
# @numba.njit()
# def smallest_flagged(heap, row):
# """Search the heap for the smallest element that is
# still flagged.
#
# Parameters
# ----------
# heap: array of shape (3, n_samples, n_neighbors)
# The heaps to search
#
# row: int
# Which of the heaps to search
#
# Returns
# -------
# index: int
# The index of the smallest flagged element
# of the ``row``th heap, or -1 if no flagged
# elements remain in the heap.
# """
# ind = heap[0][row]
# dist = heap[1][row]
# flag = heap[2][row]
#
# min_dist = np.inf
# result_index = -1
#
# for i in range(ind.shape[0]):
# if flag[i] == 1 and dist[i] < min_dist:
# min_dist = dist[i]
# result_index = i
#
# if result_index >= 0:
# flag[result_index] = 0.0
# return int(ind[result_index])
# else:
# return -1
@numba.njit(parallel=True, locals={"idx": numba.types.int64}, cache=False)
def new_build_candidates(current_graph, max_candidates, rng_state, n_threads):
"""Build a heap of candidate neighbors for nearest neighbor descent. For
each vertex the candidate neighbors are any current neighbors, and any
vertices that have the vertex as one of their nearest neighbors.
Parameters
----------
current_graph: heap
The current state of the graph for nearest neighbor descent.
max_candidates: int
The maximum number of new candidate neighbors.
rng_state: array of int64, shape (3,)
The internal state of the rng
Returns
-------
candidate_neighbors: A heap with an array of (randomly sorted) candidate
neighbors for each vertex in the graph.
"""
current_indices = current_graph[0]
current_flags = current_graph[2]
n_vertices = current_indices.shape[0]
n_neighbors = current_indices.shape[1]
new_candidate_indices = np.full((n_vertices, max_candidates), -1, dtype=np.int32)
new_candidate_priority = np.full(
(n_vertices, max_candidates), np.inf, dtype=np.float32
)
old_candidate_indices = np.full((n_vertices, max_candidates), -1, dtype=np.int32)
old_candidate_priority = np.full(
(n_vertices, max_candidates), np.inf, dtype=np.float32
)
for n in numba.prange(n_threads):
local_rng_state = rng_state + n
for i in range(n_vertices):
for j in range(n_neighbors):
idx = current_indices[i, j]
isn = current_flags[i, j]
if idx < 0:
continue
d = tau_rand(local_rng_state)
if isn:
if i % n_threads == n:
checked_heap_push(
new_candidate_priority[i], new_candidate_indices[i], d, idx
)
if idx % n_threads == n:
checked_heap_push(
new_candidate_priority[idx],
new_candidate_indices[idx],
d,
i,
)
else:
if i % n_threads == n:
checked_heap_push(
old_candidate_priority[i], old_candidate_indices[i], d, idx
)
if idx % n_threads == n:
checked_heap_push(
old_candidate_priority[idx],
old_candidate_indices[idx],
d,
i,
)
indices = current_graph[0]
flags = current_graph[2]
for i in numba.prange(n_vertices):
for j in range(n_neighbors):
idx = indices[i, j]
for k in range(max_candidates):
if new_candidate_indices[i, k] == idx:
flags[i, j] = 0
break
return new_candidate_indices, old_candidate_indices
@numba.njit("b1(u1[::1],i4)", cache=True)
def has_been_visited(table, candidate):
loc = candidate >> 3
mask = 1 << (candidate & 7)
return table[loc] & mask
@numba.njit("void(u1[::1],i4)", cache=True)
def mark_visited(table, candidate):
loc = candidate >> 3
mask = 1 << (candidate & 7)
table[loc] |= mask
return
@numba.njit(
"i4(f4[::1],i4[::1],f4,i4)",
fastmath=True,
locals={
"size": numba.types.intp,
"i": numba.types.uint16,
"ic1": numba.types.uint16,
"ic2": numba.types.uint16,
"i_swap": numba.types.uint16,
},
cache=True,
)
def simple_heap_push(priorities, indices, p, n):
if p >= priorities[0]:
return 0
size = priorities.shape[0]
# insert val at position zero
priorities[0] = p
indices[0] = n
# descend the heap, swapping values until the max heap criterion is met
i = 0
while True:
ic1 = 2 * i + 1
ic2 = ic1 + 1
if ic1 >= size:
break
elif ic2 >= size:
if priorities[ic1] > p:
i_swap = ic1
else:
break
elif priorities[ic1] >= priorities[ic2]:
if p < priorities[ic1]:
i_swap = ic1
else:
break
else:
if p < priorities[ic2]:
i_swap = ic2
else:
break
priorities[i] = priorities[i_swap]
indices[i] = indices[i_swap]
i = i_swap
priorities[i] = p
indices[i] = n
return 1
@numba.njit(
"i4(f4[::1],i4[::1],f4,i4)",
fastmath=True,
locals={
"size": numba.types.intp,
"i": numba.types.uint16,
"ic1": numba.types.uint16,
"ic2": numba.types.uint16,
"i_swap": numba.types.uint16,
},
cache=True,
)
def checked_heap_push(priorities, indices, p, n):
if p >= priorities[0]:
return 0
size = priorities.shape[0]
# break if we already have this element.
for i in range(size):
if n == indices[i]:
return 0
# insert val at position zero
priorities[0] = p
indices[0] = n
# descend the heap, swapping values until the max heap criterion is met
i = 0
while True:
ic1 = 2 * i + 1
ic2 = ic1 + 1
if ic1 >= size:
break
elif ic2 >= size:
if priorities[ic1] > p:
i_swap = ic1
else:
break
elif priorities[ic1] >= priorities[ic2]:
if p < priorities[ic1]:
i_swap = ic1
else:
break
else:
if p < priorities[ic2]:
i_swap = ic2
else:
break
priorities[i] = priorities[i_swap]
indices[i] = indices[i_swap]
i = i_swap
priorities[i] = p
indices[i] = n
return 1
@numba.njit(
"i4(f4[::1],i4[::1],u1[::1],f4,i4,u1)",
fastmath=True,
locals={
"size": numba.types.intp,
"i": numba.types.uint16,
"ic1": numba.types.uint16,
"ic2": numba.types.uint16,
"i_swap": numba.types.uint16,
},
cache=True,
)
def checked_flagged_heap_push(priorities, indices, flags, p, n, f):
if p >= priorities[0]:
return 0
size = priorities.shape[0]
# break if we already have this element.
for i in range(size):
if n == indices[i]:
return 0
# insert val at position zero
priorities[0] = p
indices[0] = n
flags[0] = f
# descend the heap, swapping values until the max heap criterion is met
i = 0
while True:
ic1 = 2 * i + 1
ic2 = ic1 + 1
if ic1 >= size:
break
elif ic2 >= size:
if priorities[ic1] > p:
i_swap = ic1
else:
break
elif priorities[ic1] >= priorities[ic2]:
if p < priorities[ic1]:
i_swap = ic1
else:
break
else:
if p < priorities[ic2]:
i_swap = ic2
else:
break
priorities[i] = priorities[i_swap]
indices[i] = indices[i_swap]
flags[i] = flags[i_swap]
i = i_swap
priorities[i] = p
indices[i] = n
flags[i] = f
return 1
@numba.njit(
parallel=True,
locals={
"p": numba.int32,
"q": numba.int32,
"d": numba.float32,
"added": numba.uint8,
"n": numba.uint32,
"i": numba.uint32,
"j": numba.uint32,
},
cache=False,
)
def apply_graph_updates_low_memory(current_graph, updates, n_threads):
n_changes = 0
priorities = current_graph[1]
indices = current_graph[0]
flags = current_graph[2]
# n_threads = numba.get_num_threads()
for n in numba.prange(n_threads):
for i in range(len(updates)):
for j in range(len(updates[i])):
p, q, d = updates[i][j]
if p == -1 or q == -1:
continue
if p % n_threads == n:
added = checked_flagged_heap_push(
priorities[p], indices[p], flags[p], d, q, 1
)
n_changes += added
if q % n_threads == n:
added = checked_flagged_heap_push(
priorities[q], indices[q], flags[q], d, p, 1
)
n_changes += added
return n_changes
@numba.njit(locals={"p": numba.types.int64, "q": numba.types.int64}, cache=True)
def apply_graph_updates_high_memory(current_graph, updates, in_graph):
n_changes = 0
for i in range(len(updates)):
for j in range(len(updates[i])):
p, q, d = updates[i][j]
if p == -1 or q == -1:
continue
if q in in_graph[p] and p in in_graph[q]:
continue
elif q in in_graph[p]:
pass
else:
added = checked_flagged_heap_push(
current_graph[1][p],
current_graph[0][p],
current_graph[2][p],
d,
q,
1,
)
if added > 0:
in_graph[p].add(q)
n_changes += added
if p == q or p in in_graph[q]:
pass
else:
added = checked_flagged_heap_push(
current_graph[1][p],
current_graph[0][p],
current_graph[2][p],
d,
q,
1,
)
if added > 0:
in_graph[q].add(p)
n_changes += added
return n_changes
@numba.njit(cache=True)
def initalize_heap_from_graph_indices(heap, graph_indices, data, metric):
for i in range(graph_indices.shape[0]):
for idx in range(graph_indices.shape[1]):
j = graph_indices[i, idx]
if j >= 0:
d = metric(data[i], data[j])
checked_flagged_heap_push(heap[1][i], heap[0][i], heap[2][i], d, j, 1)
return heap
@numba.njit(parallel=True, cache=False)
def sparse_initalize_heap_from_graph_indices(
heap, graph_indices, data_indptr, data_indices, data_vals, metric
):
for i in numba.prange(graph_indices.shape[0]):
for idx in range(graph_indices.shape[1]):
j = graph_indices[i, idx]
ind1 = data_indices[data_indptr[i] : data_indptr[i + 1]]
data1 = data_vals[data_indptr[i] : data_indptr[i + 1]]
ind2 = data_indices[data_indptr[j] : data_indptr[j + 1]]
data2 = data_vals[data_indptr[j] : data_indptr[j + 1]]
d = metric(ind1, data1, ind2, data2)
checked_flagged_heap_push(heap[1][i], heap[0][i], heap[2][i], d, j, 1)
return heap
# Generates a timestamp for use in logging messages when verbose=True
def ts():
return time.ctime(time.time())
| 27.157083 | 97 | 0.549553 |
import time
import numba
from numba.core import types
import numba.experimental.structref as structref
import numpy as np
@numba.njit("void(i8[:], i8)", cache=True)
def seed(rng_state, seed):
rng_state.fill(seed + 0xFFFF)
@numba.njit("i4(i8[:])", cache=True)
def tau_rand_int(state):
state[0] = (((state[0] & 4294967294) << 12) & 0xFFFFFFFF) ^ (
(((state[0] << 13) & 0xFFFFFFFF) ^ state[0]) >> 19
)
state[1] = (((state[1] & 4294967288) << 4) & 0xFFFFFFFF) ^ (
(((state[1] << 2) & 0xFFFFFFFF) ^ state[1]) >> 25
)
state[2] = (((state[2] & 4294967280) << 17) & 0xFFFFFFFF) ^ (
(((state[2] << 3) & 0xFFFFFFFF) ^ state[2]) >> 11
)
return state[0] ^ state[1] ^ state[2]
@numba.njit("f4(i8[:])", cache=True)
def tau_rand(state):
integer = tau_rand_int(state)
return abs(float(integer) / 0x7FFFFFFF)
@numba.njit(
[
"f4(f4[::1])",
numba.types.float32(
numba.types.Array(numba.types.float32, 1, "C", readonly=True)
),
],
locals={
"dim": numba.types.intp,
"i": numba.types.uint32,
c):
result = 0.0
dim = vec.shape[0]
for i in range(dim):
result += vec[i] * vec[i]
return np.sqrt(result)
@numba.njit(cache=True)
def rejection_sample(n_samples, pool_size, rng_state):
result = np.empty(n_samples, dtype=np.int64)
for i in range(n_samples):
reject_sample = True
j = 0
while reject_sample:
j = tau_rand_int(rng_state) % pool_size
for k in range(i):
if j == result[k]:
break
else:
reject_sample = False
result[i] = j
return result
@structref.register
class HeapType(types.StructRef):
pass
class Heap(structref.StructRefProxy):
@property
def indices(self):
return Heap_get_indices(self)
@property
def distances(self):
return Heap_get_distances(self)
@property
def flags(self):
return Heap_get_flags(self)
@numba.njit(cache=True)
def Heap_get_flags(self):
return self.flags
@numba.njit(cache=True)
def Heap_get_distances(self):
return self.distances
@numba.njit(cache=True)
def Heap_get_indices(self):
return self.indices
structref.define_proxy(Heap, HeapType, ["indices", "distances", "flags"])
@numba.njit(cache=True)
def make_heap(n_points, size):
indices = np.full((int(n_points), int(size)), -1, dtype=np.int32)
distances = np.full((int(n_points), int(size)), np.infty, dtype=np.float32)
flags = np.zeros((int(n_points), int(size)), dtype=np.uint8)
result = (indices, distances, flags)
return result
@numba.njit(cache=True)
def siftdown(heap1, heap2, elt):
while elt * 2 + 1 < heap1.shape[0]:
left_child = elt * 2 + 1
right_child = left_child + 1
swap = elt
if heap1[swap] < heap1[left_child]:
swap = left_child
if right_child < heap1.shape[0] and heap1[swap] < heap1[right_child]:
swap = right_child
if swap == elt:
break
else:
heap1[elt], heap1[swap] = heap1[swap], heap1[elt]
heap2[elt], heap2[swap] = heap2[swap], heap2[elt]
elt = swap
@numba.njit(parallel=True, cache=False)
def deheap_sort(indices, distances):
for i in numba.prange(indices.shape[0]):
for j in range(indices.shape[1] - 1, 0, -1):
indices[i, 0], indices[i, j] = indices[i, j], indices[i, 0]
distances[i, 0], distances[i, j] = distances[i, j], distances[i, 0]
siftdown(distances[i, :j], indices[i, :j], 0)
return indices, distances
# still flagged.
#
# Parameters
# ----------
# heap: array of shape (3, n_samples, n_neighbors)
# The heaps to search
#
# row: int
# Which of the heaps to search
#
# Returns
# -------
# index: int
# The index of the smallest flagged element
# of the ``row``th heap, or -1 if no flagged
# elements remain in the heap.
# """
@numba.njit(parallel=True, locals={"idx": numba.types.int64}, cache=False)
def new_build_candidates(current_graph, max_candidates, rng_state, n_threads):
current_indices = current_graph[0]
current_flags = current_graph[2]
n_vertices = current_indices.shape[0]
n_neighbors = current_indices.shape[1]
new_candidate_indices = np.full((n_vertices, max_candidates), -1, dtype=np.int32)
new_candidate_priority = np.full(
(n_vertices, max_candidates), np.inf, dtype=np.float32
)
old_candidate_indices = np.full((n_vertices, max_candidates), -1, dtype=np.int32)
old_candidate_priority = np.full(
(n_vertices, max_candidates), np.inf, dtype=np.float32
)
for n in numba.prange(n_threads):
local_rng_state = rng_state + n
for i in range(n_vertices):
for j in range(n_neighbors):
idx = current_indices[i, j]
isn = current_flags[i, j]
if idx < 0:
continue
d = tau_rand(local_rng_state)
if isn:
if i % n_threads == n:
checked_heap_push(
new_candidate_priority[i], new_candidate_indices[i], d, idx
)
if idx % n_threads == n:
checked_heap_push(
new_candidate_priority[idx],
new_candidate_indices[idx],
d,
i,
)
else:
if i % n_threads == n:
checked_heap_push(
old_candidate_priority[i], old_candidate_indices[i], d, idx
)
if idx % n_threads == n:
checked_heap_push(
old_candidate_priority[idx],
old_candidate_indices[idx],
d,
i,
)
indices = current_graph[0]
flags = current_graph[2]
for i in numba.prange(n_vertices):
for j in range(n_neighbors):
idx = indices[i, j]
for k in range(max_candidates):
if new_candidate_indices[i, k] == idx:
flags[i, j] = 0
break
return new_candidate_indices, old_candidate_indices
@numba.njit("b1(u1[::1],i4)", cache=True)
def has_been_visited(table, candidate):
loc = candidate >> 3
mask = 1 << (candidate & 7)
return table[loc] & mask
@numba.njit("void(u1[::1],i4)", cache=True)
def mark_visited(table, candidate):
loc = candidate >> 3
mask = 1 << (candidate & 7)
table[loc] |= mask
return
@numba.njit(
"i4(f4[::1],i4[::1],f4,i4)",
fastmath=True,
locals={
"size": numba.types.intp,
"i": numba.types.uint16,
"ic1": numba.types.uint16,
"ic2": numba.types.uint16,
"i_swap": numba.types.uint16,
},
cache=True,
)
def simple_heap_push(priorities, indices, p, n):
if p >= priorities[0]:
return 0
size = priorities.shape[0]
priorities[0] = p
indices[0] = n
i = 0
while True:
ic1 = 2 * i + 1
ic2 = ic1 + 1
if ic1 >= size:
break
elif ic2 >= size:
if priorities[ic1] > p:
i_swap = ic1
else:
break
elif priorities[ic1] >= priorities[ic2]:
if p < priorities[ic1]:
i_swap = ic1
else:
break
else:
if p < priorities[ic2]:
i_swap = ic2
else:
break
priorities[i] = priorities[i_swap]
indices[i] = indices[i_swap]
i = i_swap
priorities[i] = p
indices[i] = n
return 1
@numba.njit(
"i4(f4[::1],i4[::1],f4,i4)",
fastmath=True,
locals={
"size": numba.types.intp,
"i": numba.types.uint16,
"ic1": numba.types.uint16,
"ic2": numba.types.uint16,
"i_swap": numba.types.uint16,
},
cache=True,
)
def checked_heap_push(priorities, indices, p, n):
if p >= priorities[0]:
return 0
size = priorities.shape[0]
for i in range(size):
if n == indices[i]:
return 0
priorities[0] = p
indices[0] = n
i = 0
while True:
ic1 = 2 * i + 1
ic2 = ic1 + 1
if ic1 >= size:
break
elif ic2 >= size:
if priorities[ic1] > p:
i_swap = ic1
else:
break
elif priorities[ic1] >= priorities[ic2]:
if p < priorities[ic1]:
i_swap = ic1
else:
break
else:
if p < priorities[ic2]:
i_swap = ic2
else:
break
priorities[i] = priorities[i_swap]
indices[i] = indices[i_swap]
i = i_swap
priorities[i] = p
indices[i] = n
return 1
@numba.njit(
"i4(f4[::1],i4[::1],u1[::1],f4,i4,u1)",
fastmath=True,
locals={
"size": numba.types.intp,
"i": numba.types.uint16,
"ic1": numba.types.uint16,
"ic2": numba.types.uint16,
"i_swap": numba.types.uint16,
},
cache=True,
)
def checked_flagged_heap_push(priorities, indices, flags, p, n, f):
if p >= priorities[0]:
return 0
size = priorities.shape[0]
for i in range(size):
if n == indices[i]:
return 0
priorities[0] = p
indices[0] = n
flags[0] = f
i = 0
while True:
ic1 = 2 * i + 1
ic2 = ic1 + 1
if ic1 >= size:
break
elif ic2 >= size:
if priorities[ic1] > p:
i_swap = ic1
else:
break
elif priorities[ic1] >= priorities[ic2]:
if p < priorities[ic1]:
i_swap = ic1
else:
break
else:
if p < priorities[ic2]:
i_swap = ic2
else:
break
priorities[i] = priorities[i_swap]
indices[i] = indices[i_swap]
flags[i] = flags[i_swap]
i = i_swap
priorities[i] = p
indices[i] = n
flags[i] = f
return 1
@numba.njit(
parallel=True,
locals={
"p": numba.int32,
"q": numba.int32,
"d": numba.float32,
"added": numba.uint8,
"n": numba.uint32,
"i": numba.uint32,
"j": numba.uint32,
},
cache=False,
)
def apply_graph_updates_low_memory(current_graph, updates, n_threads):
n_changes = 0
priorities = current_graph[1]
indices = current_graph[0]
flags = current_graph[2]
for n in numba.prange(n_threads):
for i in range(len(updates)):
for j in range(len(updates[i])):
p, q, d = updates[i][j]
if p == -1 or q == -1:
continue
if p % n_threads == n:
added = checked_flagged_heap_push(
priorities[p], indices[p], flags[p], d, q, 1
)
n_changes += added
if q % n_threads == n:
added = checked_flagged_heap_push(
priorities[q], indices[q], flags[q], d, p, 1
)
n_changes += added
return n_changes
@numba.njit(locals={"p": numba.types.int64, "q": numba.types.int64}, cache=True)
def apply_graph_updates_high_memory(current_graph, updates, in_graph):
n_changes = 0
for i in range(len(updates)):
for j in range(len(updates[i])):
p, q, d = updates[i][j]
if p == -1 or q == -1:
continue
if q in in_graph[p] and p in in_graph[q]:
continue
elif q in in_graph[p]:
pass
else:
added = checked_flagged_heap_push(
current_graph[1][p],
current_graph[0][p],
current_graph[2][p],
d,
q,
1,
)
if added > 0:
in_graph[p].add(q)
n_changes += added
if p == q or p in in_graph[q]:
pass
else:
added = checked_flagged_heap_push(
current_graph[1][p],
current_graph[0][p],
current_graph[2][p],
d,
q,
1,
)
if added > 0:
in_graph[q].add(p)
n_changes += added
return n_changes
@numba.njit(cache=True)
def initalize_heap_from_graph_indices(heap, graph_indices, data, metric):
for i in range(graph_indices.shape[0]):
for idx in range(graph_indices.shape[1]):
j = graph_indices[i, idx]
if j >= 0:
d = metric(data[i], data[j])
checked_flagged_heap_push(heap[1][i], heap[0][i], heap[2][i], d, j, 1)
return heap
@numba.njit(parallel=True, cache=False)
def sparse_initalize_heap_from_graph_indices(
heap, graph_indices, data_indptr, data_indices, data_vals, metric
):
for i in numba.prange(graph_indices.shape[0]):
for idx in range(graph_indices.shape[1]):
j = graph_indices[i, idx]
ind1 = data_indices[data_indptr[i] : data_indptr[i + 1]]
data1 = data_vals[data_indptr[i] : data_indptr[i + 1]]
ind2 = data_indices[data_indptr[j] : data_indptr[j + 1]]
data2 = data_vals[data_indptr[j] : data_indptr[j + 1]]
d = metric(ind1, data1, ind2, data2)
checked_flagged_heap_push(heap[1][i], heap[0][i], heap[2][i], d, j, 1)
return heap
def ts():
return time.ctime(time.time())
| true | true |
f72f232db2207147d84c9324167fdd40d2261e65 | 548 | py | Python | backend/manage.py | Web-Multi-Media/HttpStreamingServer | c062840b1323f6a5b35a1d7d26542a0fd6e77b0e | [
"MIT"
] | 5 | 2019-12-25T16:28:26.000Z | 2022-03-22T11:05:16.000Z | backend/manage.py | Web-Multi-Media/HttpStreamingServer | c062840b1323f6a5b35a1d7d26542a0fd6e77b0e | [
"MIT"
] | 26 | 2019-11-14T16:03:26.000Z | 2022-02-10T11:56:04.000Z | backend/manage.py | Web-Multi-Media/HttpStreamingServer | c062840b1323f6a5b35a1d7d26542a0fd6e77b0e | [
"MIT"
] | 2 | 2020-09-01T09:25:14.000Z | 2020-10-09T12:06:35.000Z | #!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'StreamingServer.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
| 32.235294 | 79 | 0.689781 |
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'StreamingServer.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
| true | true |
f72f24046e5fa65b5ee35e45bd348bb5ccc79c50 | 861 | py | Python | ooobuild/dyn/chart/chart_axis_y_supplier.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | ooobuild/dyn/chart/chart_axis_y_supplier.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | ooobuild/dyn/chart/chart_axis_y_supplier.py | Amourspirit/ooo_uno_tmpl | 64e0c86fd68f24794acc22d63d8d32ae05dd12b8 | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http: // www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Service Class
# this is a auto generated file generated by Cheetah
# Libre Office Version: 7.3
# Namespace: com.sun.star.chart
from ...lo.chart.chart_axis_y_supplier import ChartAxisYSupplier as ChartAxisYSupplier
__all__ = ['ChartAxisYSupplier']
| 33.115385 | 86 | 0.763066 |
from ...lo.chart.chart_axis_y_supplier import ChartAxisYSupplier as ChartAxisYSupplier
__all__ = ['ChartAxisYSupplier']
| true | true |
f72f2566c3018af4ef5d78db70a1751fce0ba12b | 4,040 | py | Python | fugue_notebook/__init__.py | gityow/fugue | e975625b33766d8b9dc64c6954871569b59367ec | [
"Apache-2.0"
] | null | null | null | fugue_notebook/__init__.py | gityow/fugue | e975625b33766d8b9dc64c6954871569b59367ec | [
"Apache-2.0"
] | null | null | null | fugue_notebook/__init__.py | gityow/fugue | e975625b33766d8b9dc64c6954871569b59367ec | [
"Apache-2.0"
] | null | null | null | # flake8: noqa
from typing import Any
from fugue_version import __version__
from IPython import get_ipython
from IPython.display import Javascript
from fugue_notebook.env import NotebookSetup, _setup_fugue_notebook
_HIGHLIGHT_JS = r"""
require(["codemirror/lib/codemirror"]);
function set(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var fugue_keywords = "fill hash rand even presort persist broadcast params process output outtransform rowcount concurrency prepartition zip print title save append parquet csv json single checkpoint weak strong deterministic yield connect sample seed take sub callback dataframe file";
CodeMirror.defineMIME("text/x-fsql", {
name: "sql",
keywords: set(fugue_keywords + " add after all alter analyze and anti archive array as asc at between bucket buckets by cache cascade case cast change clear cluster clustered codegen collection column columns comment commit compact compactions compute concatenate cost create cross cube current current_date current_timestamp database databases data dbproperties defined delete delimited deny desc describe dfs directories distinct distribute drop else end escaped except exchange exists explain export extended external false fields fileformat first following for format formatted from full function functions global grant group grouping having if ignore import in index indexes inner inpath inputformat insert intersect interval into is items join keys last lateral lazy left like limit lines list load local location lock locks logical macro map minus msck natural no not null nulls of on optimize option options or order out outer outputformat over overwrite partition partitioned partitions percent preceding principals purge range recordreader recordwriter recover reduce refresh regexp rename repair replace reset restrict revoke right rlike role roles rollback rollup row rows schema schemas select semi separated serde serdeproperties set sets show skewed sort sorted start statistics stored stratify struct table tables tablesample tblproperties temp temporary terminated then to touch transaction transactions transform true truncate unarchive unbounded uncache union unlock unset use using values view when where window with"),
builtin: set("date datetime tinyint smallint int bigint boolean float double string binary timestamp decimal array map struct uniontype delimited serde sequencefile textfile rcfile inputformat outputformat"),
atoms: set("false true null"),
operatorChars: /^[*\/+\-%<>!=~&|^]/,
dateSQL: set("time"),
support: set("ODBCdotTable doubleQuote zerolessFloat")
});
CodeMirror.modeInfo.push( {
name: "Fugue SQL",
mime: "text/x-fsql",
mode: "sql"
} );
require(['notebook/js/codecell'], function(codecell) {
codecell.CodeCell.options_default.highlight_modes['magic_text/x-fsql'] = {'reg':[/%%fsql/]} ;
Jupyter.notebook.events.on('kernel_ready.Kernel', function(){
Jupyter.notebook.get_cells().map(function(cell){
if (cell.cell_type == 'code'){ cell.auto_highlight(); } }) ;
});
});
"""
def load_ipython_extension(ip: Any) -> None:
"""Entrypoint for IPython %load_ext"""
_setup_fugue_notebook(ip, None)
def _jupyter_nbextension_paths():
"""Entrypoint for Jupyter extension"""
return [
{
"section": "notebook",
"src": "nbextension",
"dest": "fugue_notebook",
"require": "fugue_notebook/main",
}
]
def setup(notebook_setup: Any = None, is_lab: bool = False) -> Any:
"""Setup the notebook environment inside notebook without
installing the jupyter extension or loading ipython extension
:param notebook_setup: ``None`` or an instance of
:class:`~.fugue_notebook.env.NotebookSetup`, defaults to None
"""
ip = get_ipython()
_setup_fugue_notebook(ip, notebook_setup)
if not is_lab:
return Javascript(_HIGHLIGHT_JS)
| 56.111111 | 1,543 | 0.746287 |
from typing import Any
from fugue_version import __version__
from IPython import get_ipython
from IPython.display import Javascript
from fugue_notebook.env import NotebookSetup, _setup_fugue_notebook
_HIGHLIGHT_JS = r"""
require(["codemirror/lib/codemirror"]);
function set(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var fugue_keywords = "fill hash rand even presort persist broadcast params process output outtransform rowcount concurrency prepartition zip print title save append parquet csv json single checkpoint weak strong deterministic yield connect sample seed take sub callback dataframe file";
CodeMirror.defineMIME("text/x-fsql", {
name: "sql",
keywords: set(fugue_keywords + " add after all alter analyze and anti archive array as asc at between bucket buckets by cache cascade case cast change clear cluster clustered codegen collection column columns comment commit compact compactions compute concatenate cost create cross cube current current_date current_timestamp database databases data dbproperties defined delete delimited deny desc describe dfs directories distinct distribute drop else end escaped except exchange exists explain export extended external false fields fileformat first following for format formatted from full function functions global grant group grouping having if ignore import in index indexes inner inpath inputformat insert intersect interval into is items join keys last lateral lazy left like limit lines list load local location lock locks logical macro map minus msck natural no not null nulls of on optimize option options or order out outer outputformat over overwrite partition partitioned partitions percent preceding principals purge range recordreader recordwriter recover reduce refresh regexp rename repair replace reset restrict revoke right rlike role roles rollback rollup row rows schema schemas select semi separated serde serdeproperties set sets show skewed sort sorted start statistics stored stratify struct table tables tablesample tblproperties temp temporary terminated then to touch transaction transactions transform true truncate unarchive unbounded uncache union unlock unset use using values view when where window with"),
builtin: set("date datetime tinyint smallint int bigint boolean float double string binary timestamp decimal array map struct uniontype delimited serde sequencefile textfile rcfile inputformat outputformat"),
atoms: set("false true null"),
operatorChars: /^[*\/+\-%<>!=~&|^]/,
dateSQL: set("time"),
support: set("ODBCdotTable doubleQuote zerolessFloat")
});
CodeMirror.modeInfo.push( {
name: "Fugue SQL",
mime: "text/x-fsql",
mode: "sql"
} );
require(['notebook/js/codecell'], function(codecell) {
codecell.CodeCell.options_default.highlight_modes['magic_text/x-fsql'] = {'reg':[/%%fsql/]} ;
Jupyter.notebook.events.on('kernel_ready.Kernel', function(){
Jupyter.notebook.get_cells().map(function(cell){
if (cell.cell_type == 'code'){ cell.auto_highlight(); } }) ;
});
});
"""
def load_ipython_extension(ip: Any) -> None:
_setup_fugue_notebook(ip, None)
def _jupyter_nbextension_paths():
return [
{
"section": "notebook",
"src": "nbextension",
"dest": "fugue_notebook",
"require": "fugue_notebook/main",
}
]
def setup(notebook_setup: Any = None, is_lab: bool = False) -> Any:
ip = get_ipython()
_setup_fugue_notebook(ip, notebook_setup)
if not is_lab:
return Javascript(_HIGHLIGHT_JS)
| true | true |
f72f25b50dcbfd6ed34ab185f0b12887078ac367 | 1,814 | py | Python | prnet/utils/render_app.py | RonnyLV/PRNet | 0c2ded7042ceee2b2f9bba02bc19d91d4c3993c5 | [
"MIT"
] | null | null | null | prnet/utils/render_app.py | RonnyLV/PRNet | 0c2ded7042ceee2b2f9bba02bc19d91d4c3993c5 | [
"MIT"
] | null | null | null | prnet/utils/render_app.py | RonnyLV/PRNet | 0c2ded7042ceee2b2f9bba02bc19d91d4c3993c5 | [
"MIT"
] | null | null | null | import numpy as np
from prnet.utils.render import vis_of_vertices, render_texture
from scipy import ndimage
def get_visibility(vertices, triangles, h, w):
triangles = triangles.T
vertices_vis = vis_of_vertices(vertices.T, triangles, h, w)
vertices_vis = vertices_vis.astype(bool)
for k in range(2):
tri_vis = vertices_vis[triangles[0,:]] | vertices_vis[triangles[1,:]] | vertices_vis[triangles[2,:]]
ind = triangles[:, tri_vis]
vertices_vis[ind] = True
# for k in range(2):
# tri_vis = vertices_vis[triangles[0,:]] & vertices_vis[triangles[1,:]] & vertices_vis[triangles[2,:]]
# ind = triangles[:, tri_vis]
# vertices_vis[ind] = True
vertices_vis = vertices_vis.astype(np.float32) #1 for visible and 0 for non-visible
return vertices_vis
def get_uv_mask(vertices_vis, triangles, uv_coords, h, w, resolution):
triangles = triangles.T
vertices_vis = vertices_vis.astype(np.float32)
uv_mask = render_texture(uv_coords.T, vertices_vis[np.newaxis, :], triangles, resolution, resolution, 1)
uv_mask = np.squeeze(uv_mask > 0)
uv_mask = ndimage.binary_closing(uv_mask)
uv_mask = ndimage.binary_erosion(uv_mask, structure = np.ones((4,4)))
uv_mask = ndimage.binary_closing(uv_mask)
uv_mask = ndimage.binary_erosion(uv_mask, structure = np.ones((4,4)))
uv_mask = ndimage.binary_erosion(uv_mask, structure = np.ones((4,4)))
uv_mask = ndimage.binary_erosion(uv_mask, structure = np.ones((4,4)))
uv_mask = uv_mask.astype(np.float32)
return np.squeeze(uv_mask)
def get_depth_image(vertices, triangles, h, w, isShow = False):
z = vertices[:, 2:]
if isShow:
z = z/max(z)
depth_image = render_texture(vertices.T, z.T, triangles.T, h, w, 1)
return np.squeeze(depth_image) | 45.35 | 110 | 0.691841 | import numpy as np
from prnet.utils.render import vis_of_vertices, render_texture
from scipy import ndimage
def get_visibility(vertices, triangles, h, w):
triangles = triangles.T
vertices_vis = vis_of_vertices(vertices.T, triangles, h, w)
vertices_vis = vertices_vis.astype(bool)
for k in range(2):
tri_vis = vertices_vis[triangles[0,:]] | vertices_vis[triangles[1,:]] | vertices_vis[triangles[2,:]]
ind = triangles[:, tri_vis]
vertices_vis[ind] = True
vertices_vis = vertices_vis.astype(np.float32)
return vertices_vis
def get_uv_mask(vertices_vis, triangles, uv_coords, h, w, resolution):
triangles = triangles.T
vertices_vis = vertices_vis.astype(np.float32)
uv_mask = render_texture(uv_coords.T, vertices_vis[np.newaxis, :], triangles, resolution, resolution, 1)
uv_mask = np.squeeze(uv_mask > 0)
uv_mask = ndimage.binary_closing(uv_mask)
uv_mask = ndimage.binary_erosion(uv_mask, structure = np.ones((4,4)))
uv_mask = ndimage.binary_closing(uv_mask)
uv_mask = ndimage.binary_erosion(uv_mask, structure = np.ones((4,4)))
uv_mask = ndimage.binary_erosion(uv_mask, structure = np.ones((4,4)))
uv_mask = ndimage.binary_erosion(uv_mask, structure = np.ones((4,4)))
uv_mask = uv_mask.astype(np.float32)
return np.squeeze(uv_mask)
def get_depth_image(vertices, triangles, h, w, isShow = False):
z = vertices[:, 2:]
if isShow:
z = z/max(z)
depth_image = render_texture(vertices.T, z.T, triangles.T, h, w, 1)
return np.squeeze(depth_image) | true | true |
f72f26220b3eace9e7640d67550958c5c1e52ae2 | 969 | py | Python | mysite/urls.py | taylorculver/Django_Project_Improvement | a03eb076eb170c0ec74d9edac515f826cf2ee30e | [
"Unlicense"
] | null | null | null | mysite/urls.py | taylorculver/Django_Project_Improvement | a03eb076eb170c0ec74d9edac515f826cf2ee30e | [
"Unlicense"
] | null | null | null | mysite/urls.py | taylorculver/Django_Project_Improvement | a03eb076eb170c0ec74d9edac515f826cf2ee30e | [
"Unlicense"
] | null | null | null | """mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'', include('menu.urls')),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
| 31.258065 | 77 | 0.69453 | from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'', include('menu.urls')),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
| true | true |
f72f28a8cc0117ce6a4927c59ca5ac49a7281a79 | 7,388 | py | Python | cyder/base/mixins.py | zeeman/cyder | 10d347e77554628e4c7af478d0f57b6c14a608ef | [
"BSD-3-Clause"
] | null | null | null | cyder/base/mixins.py | zeeman/cyder | 10d347e77554628e4c7af478d0f57b6c14a608ef | [
"BSD-3-Clause"
] | null | null | null | cyder/base/mixins.py | zeeman/cyder | 10d347e77554628e4c7af478d0f57b6c14a608ef | [
"BSD-3-Clause"
] | null | null | null | import os
import fcntl
from string import Template
from django.core.urlresolvers import NoReverseMatch, reverse
from django.db.models.loading import get_model
from django.forms import ModelChoiceField, HiddenInput
from django import forms
from cyder.base.utils import filter_by_ctnr
class DisplayMixin(object):
# Knobs
justs = {
'pk_just': 10,
'rhs_just': 1,
'ttl_just': 6,
'rdtype_just': 7,
'rdclass_just': 3,
'prio_just': 2,
'lhs_just': 61,
'extra_just': 1
}
def bind_render_record(self, pk=False, custom=None):
kwargs = vars(self)
if custom:
for key, value in custom.items():
kwargs[key] = value
template = Template(self.template).substitute(**self.justs)
bind_name = self.fqdn + "."
if not self.ttl:
self.ttl = 3600
return template.format(bind_name=bind_name, rdtype=self.rdtype,
rdclass='IN', **kwargs)
class ObjectUrlMixin(object):
"""
This is a mixin that adds important url methods to a model. This
class uses the ``_meta.db_table`` instance variable of an object to
calculate URLs. Because of this, you must use the app label of your
class when declaring urls in your urls.py.
"""
@classmethod
def get_list_url(cls):
"""
Return the 'list' url of an object. Class method since don't
need specific instance of object.
"""
return reverse(cls._meta.db_table)
@classmethod
def get_create_url(cls):
"""Return the create url of the type of object (to be posted to)."""
return cls.get_list_url()
def get_update_url(self):
"""Return the update url of an object."""
return reverse(self._meta.db_table + '-update', args=[self.pk])
def get_delete_url(self):
"""Return the delete url of an object."""
return reverse('delete')
def get_detail_url(self):
"""Return the detail url of an object."""
try:
return reverse(self._meta.db_table + '-detail', args=[self.pk])
except NoReverseMatch:
return ''
def get_table_update_url(self):
"""Return the editableGrid update url of an object."""
try:
return reverse(self._meta.db_table + '-table-update',
args=[self.pk])
except NoReverseMatch:
return ''
def details(self):
"""
Return base details with generic postback URL for editable tables.
"""
return {'url': self.get_table_update_url()}
class UsabilityFormMixin(object):
def append_required_all(self):
for fieldname, field in self.fields.items():
if self.fields[fieldname].required is True:
if self.fields[fieldname].label is None:
fname = fieldname.replace('_', ' ')
self.fields[fieldname].label = fname.capitalize() + '*'
else:
self.fields[fieldname].label += '*'
def alphabetize_all(self):
for fieldname, field in self.fields.items():
if hasattr(field, 'queryset'):
self.fields[fieldname].queryset = field.queryset.order_by(
*field.queryset.model.sort_fields)
def filter_by_ctnr_all(self, request):
from cyder.core.ctnr.models import Ctnr
from cyder.cydns.domain.models import Domain
ctnr = request.session['ctnr']
for fieldname, field in self.fields.items():
if not hasattr(field, 'queryset'):
continue
queryset = self.fields[fieldname].queryset
if queryset.model is Ctnr:
ctnrs = set(c.pk for c in request.session['ctnrs'])
for pk in [1, 2]:
if pk in ctnrs:
ctnrs.remove(pk)
if self.fields[fieldname].initial:
ctnrs.add(self.fields[fieldname].initial.pk)
queryset = queryset.filter(pk__in=ctnrs)
else:
queryset = filter_by_ctnr(ctnr=ctnr,
objects=field.queryset).distinct()
if queryset.count() == 1:
self.fields[fieldname].initial = queryset[0]
self.fields[fieldname].queryset = queryset
def autoselect_system(self):
System = get_model('cyder', 'system')
if 'system' in self.initial:
self.fields['system'] = ModelChoiceField(
widget=HiddenInput(),
empty_label='',
queryset=System.objects.filter(pk=int(self.initial['system'])))
elif 'system' in self.fields:
del(self.fields['system'])
def autoselect_ctnr(self, request):
if 'ctnr' not in self.fields:
return
ctnr = request.session['ctnr']
if ctnr.name != "global":
if 'ctnr' not in self.initial:
self.fields['ctnr'].initial = request.session['ctnr']
self.fields['ctnr'].widget = HiddenInput()
def make_usable(self, request):
self.autoselect_system()
self.autoselect_ctnr(request)
if 'ctnr' in request.session:
self.filter_by_ctnr_all(request)
self.alphabetize_all()
self.append_required_all()
class MutexMixin(object):
def __enter__(self):
self.lock()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.unlock()
def lock(self):
if not os.path.exists(os.path.dirname(self.lock_file)):
os.makedirs(os.path.dirname(self.lock_file))
self.log_debug("Attempting to lock {0}..."
.format(self.lock_file))
self.lock_fd = open(self.lock_file, 'w')
try:
fcntl.flock(self.lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError as exc_value:
self.lock_fd.close()
# IOError: [Errno 11] Resource temporarily unavailable
if exc_value[0] == 11:
with open(self.pid_file, 'r') as pid_fd:
self._lock_failure(pid_fd.read())
else:
raise
self.log_debug("Lock acquired")
try:
with open(self.pid_file, 'w') as pid_fd:
pid_fd.write(unicode(os.getpid()))
except IOError as exc_value:
# IOError: [Errno 2] No such file or directory
if exc_value[0] == 2:
self.error(
"Failed to acquire lock on {0}, but the process that has "
"it hasn't written the PID file ({1}) yet.".format(
self.lock_file, self.pid_file))
else:
raise
def unlock(self):
if not self.lock_fd:
return False
self.log_debug("Releasing lock ({0})...".format(self.lock_file))
fcntl.flock(self.lock_fd, fcntl.LOCK_UN)
self.lock_fd.close()
os.remove(self.pid_file)
os.remove(self.lock_file)
self.log_debug("Unlock complete")
return True
def _lock_failure(self, pid):
self.error('Failed to acquire lock on {0}. Process {1} currently '
'has it.'.format(self.lock_file, pid))
| 32.982143 | 79 | 0.569031 | import os
import fcntl
from string import Template
from django.core.urlresolvers import NoReverseMatch, reverse
from django.db.models.loading import get_model
from django.forms import ModelChoiceField, HiddenInput
from django import forms
from cyder.base.utils import filter_by_ctnr
class DisplayMixin(object):
justs = {
'pk_just': 10,
'rhs_just': 1,
'ttl_just': 6,
'rdtype_just': 7,
'rdclass_just': 3,
'prio_just': 2,
'lhs_just': 61,
'extra_just': 1
}
def bind_render_record(self, pk=False, custom=None):
kwargs = vars(self)
if custom:
for key, value in custom.items():
kwargs[key] = value
template = Template(self.template).substitute(**self.justs)
bind_name = self.fqdn + "."
if not self.ttl:
self.ttl = 3600
return template.format(bind_name=bind_name, rdtype=self.rdtype,
rdclass='IN', **kwargs)
class ObjectUrlMixin(object):
@classmethod
def get_list_url(cls):
return reverse(cls._meta.db_table)
@classmethod
def get_create_url(cls):
return cls.get_list_url()
def get_update_url(self):
return reverse(self._meta.db_table + '-update', args=[self.pk])
def get_delete_url(self):
return reverse('delete')
def get_detail_url(self):
try:
return reverse(self._meta.db_table + '-detail', args=[self.pk])
except NoReverseMatch:
return ''
def get_table_update_url(self):
try:
return reverse(self._meta.db_table + '-table-update',
args=[self.pk])
except NoReverseMatch:
return ''
def details(self):
return {'url': self.get_table_update_url()}
class UsabilityFormMixin(object):
def append_required_all(self):
for fieldname, field in self.fields.items():
if self.fields[fieldname].required is True:
if self.fields[fieldname].label is None:
fname = fieldname.replace('_', ' ')
self.fields[fieldname].label = fname.capitalize() + '*'
else:
self.fields[fieldname].label += '*'
def alphabetize_all(self):
for fieldname, field in self.fields.items():
if hasattr(field, 'queryset'):
self.fields[fieldname].queryset = field.queryset.order_by(
*field.queryset.model.sort_fields)
def filter_by_ctnr_all(self, request):
from cyder.core.ctnr.models import Ctnr
from cyder.cydns.domain.models import Domain
ctnr = request.session['ctnr']
for fieldname, field in self.fields.items():
if not hasattr(field, 'queryset'):
continue
queryset = self.fields[fieldname].queryset
if queryset.model is Ctnr:
ctnrs = set(c.pk for c in request.session['ctnrs'])
for pk in [1, 2]:
if pk in ctnrs:
ctnrs.remove(pk)
if self.fields[fieldname].initial:
ctnrs.add(self.fields[fieldname].initial.pk)
queryset = queryset.filter(pk__in=ctnrs)
else:
queryset = filter_by_ctnr(ctnr=ctnr,
objects=field.queryset).distinct()
if queryset.count() == 1:
self.fields[fieldname].initial = queryset[0]
self.fields[fieldname].queryset = queryset
def autoselect_system(self):
System = get_model('cyder', 'system')
if 'system' in self.initial:
self.fields['system'] = ModelChoiceField(
widget=HiddenInput(),
empty_label='',
queryset=System.objects.filter(pk=int(self.initial['system'])))
elif 'system' in self.fields:
del(self.fields['system'])
def autoselect_ctnr(self, request):
if 'ctnr' not in self.fields:
return
ctnr = request.session['ctnr']
if ctnr.name != "global":
if 'ctnr' not in self.initial:
self.fields['ctnr'].initial = request.session['ctnr']
self.fields['ctnr'].widget = HiddenInput()
def make_usable(self, request):
self.autoselect_system()
self.autoselect_ctnr(request)
if 'ctnr' in request.session:
self.filter_by_ctnr_all(request)
self.alphabetize_all()
self.append_required_all()
class MutexMixin(object):
def __enter__(self):
self.lock()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.unlock()
def lock(self):
if not os.path.exists(os.path.dirname(self.lock_file)):
os.makedirs(os.path.dirname(self.lock_file))
self.log_debug("Attempting to lock {0}..."
.format(self.lock_file))
self.lock_fd = open(self.lock_file, 'w')
try:
fcntl.flock(self.lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError as exc_value:
self.lock_fd.close()
if exc_value[0] == 11:
with open(self.pid_file, 'r') as pid_fd:
self._lock_failure(pid_fd.read())
else:
raise
self.log_debug("Lock acquired")
try:
with open(self.pid_file, 'w') as pid_fd:
pid_fd.write(unicode(os.getpid()))
except IOError as exc_value:
if exc_value[0] == 2:
self.error(
"Failed to acquire lock on {0}, but the process that has "
"it hasn't written the PID file ({1}) yet.".format(
self.lock_file, self.pid_file))
else:
raise
def unlock(self):
if not self.lock_fd:
return False
self.log_debug("Releasing lock ({0})...".format(self.lock_file))
fcntl.flock(self.lock_fd, fcntl.LOCK_UN)
self.lock_fd.close()
os.remove(self.pid_file)
os.remove(self.lock_file)
self.log_debug("Unlock complete")
return True
def _lock_failure(self, pid):
self.error('Failed to acquire lock on {0}. Process {1} currently '
'has it.'.format(self.lock_file, pid))
| true | true |
f72f2ae2da1a8824ea37a9d9fc536ef3fce7fc12 | 1,481 | py | Python | tests/test.py | icetana-james/python-onvif-zeep | 9947a3c203037857fbc04c9fafabc722e3436a13 | [
"MIT"
] | null | null | null | tests/test.py | icetana-james/python-onvif-zeep | 9947a3c203037857fbc04c9fafabc722e3436a13 | [
"MIT"
] | null | null | null | tests/test.py | icetana-james/python-onvif-zeep | 9947a3c203037857fbc04c9fafabc722e3436a13 | [
"MIT"
] | null | null | null | #!/usr/bin/python
# -*-coding=utf-8
from __future__ import print_function, division
import unittest
from onvif import ONVIFCamera, ONVIFError
CAM_HOST = '10.1.3.10'
CAM_PORT = 80
CAM_USER = 'root'
CAM_PASS = 'password'
DEBUG = False
def log(ret):
if DEBUG:
print(ret)
class TestDevice(unittest.TestCase):
# Class level cam. Run this test more efficiently..
cam = ONVIFCamera(CAM_HOST, CAM_PORT, CAM_USER, CAM_PASS)
# ***************** Test Capabilities ***************************
def test_GetWsdlUrl(self):
ret = self.cam.devicemgmt.GetWsdlUrl()
def test_GetHostname(self):
''' Get the hostname from a device '''
self.cam.devicemgmt.GetHostname()
def test_GetServiceCapabilities(self):
'''Returns the capabilities of the devce service.'''
ret = self.cam.devicemgmt.GetServiceCapabilities()
def test_GetDNS(self):
''' Gets the DNS setting from a device '''
ret = self.cam.devicemgmt.GetDNS()
self.assertTrue(hasattr(ret, 'FromDHCP'))
if not ret.FromDHCP and len(ret.DNSManual) > 0:
log(ret.DNSManual[0].Type)
log(ret.DNSManual[0].IPv4Address)
def test_GetNTP(self):
''' Get the NTP settings from a device '''
ret = self.cam.devicemgmt.GetNTP()
if ret.FromDHCP == False:
self.assertTrue(hasattr(ret, 'NTPManual'))
log(ret.NTPManual)
if __name__ == '__main__':
unittest.main()
| 26.927273 | 69 | 0.627279 |
from __future__ import print_function, division
import unittest
from onvif import ONVIFCamera, ONVIFError
CAM_HOST = '10.1.3.10'
CAM_PORT = 80
CAM_USER = 'root'
CAM_PASS = 'password'
DEBUG = False
def log(ret):
if DEBUG:
print(ret)
class TestDevice(unittest.TestCase):
cam = ONVIFCamera(CAM_HOST, CAM_PORT, CAM_USER, CAM_PASS)
def test_GetWsdlUrl(self):
ret = self.cam.devicemgmt.GetWsdlUrl()
def test_GetHostname(self):
self.cam.devicemgmt.GetHostname()
def test_GetServiceCapabilities(self):
ret = self.cam.devicemgmt.GetServiceCapabilities()
def test_GetDNS(self):
ret = self.cam.devicemgmt.GetDNS()
self.assertTrue(hasattr(ret, 'FromDHCP'))
if not ret.FromDHCP and len(ret.DNSManual) > 0:
log(ret.DNSManual[0].Type)
log(ret.DNSManual[0].IPv4Address)
def test_GetNTP(self):
ret = self.cam.devicemgmt.GetNTP()
if ret.FromDHCP == False:
self.assertTrue(hasattr(ret, 'NTPManual'))
log(ret.NTPManual)
if __name__ == '__main__':
unittest.main()
| true | true |
f72f2bb0605f13d7ce68cd600bd8a6628eb6c15d | 249 | py | Python | scripts/fundamentals/codewars_sum_range_of_numbers.py | duttashi/learnpy | c08b76b173b06d66187e51a6939d55d5dd12cb5a | [
"MIT"
] | null | null | null | scripts/fundamentals/codewars_sum_range_of_numbers.py | duttashi/learnpy | c08b76b173b06d66187e51a6939d55d5dd12cb5a | [
"MIT"
] | 77 | 2019-04-20T06:54:19.000Z | 2022-01-16T08:15:20.000Z | scripts/fundamentals/codewars_sum_range_of_numbers.py | duttashi/learnpy | c08b76b173b06d66187e51a6939d55d5dd12cb5a | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 8 16:31:07 2020
@author: Ashish
"""
def get_sum(a,b):
numsum=0
for i in range(a,b+1):
numsum+=i
return numsum
print(get_sum(0,1))
| 12.45 | 36 | 0.457831 |
def get_sum(a,b):
numsum=0
for i in range(a,b+1):
numsum+=i
return numsum
print(get_sum(0,1))
| true | true |
f72f2c05186f829fbd3b433c815fb25ffb7d09a0 | 231 | py | Python | core/templatetags/check_if_favorited_filter.py | jcquinlan/colophon | 96f3eec0a524cb1fe3d655f3cc850b125f4aaff4 | [
"MIT"
] | null | null | null | core/templatetags/check_if_favorited_filter.py | jcquinlan/colophon | 96f3eec0a524cb1fe3d655f3cc850b125f4aaff4 | [
"MIT"
] | null | null | null | core/templatetags/check_if_favorited_filter.py | jcquinlan/colophon | 96f3eec0a524cb1fe3d655f3cc850b125f4aaff4 | [
"MIT"
] | null | null | null | from django import template
register = template.Library()
@register.filter
def check_if_favorited(document, user):
"""Returns boolean of whether or not a user favorited this document"""
return document.is_favorited(user)
| 25.666667 | 74 | 0.770563 | from django import template
register = template.Library()
@register.filter
def check_if_favorited(document, user):
return document.is_favorited(user)
| true | true |
f72f2dd7cff77a014d7828254d487da410fcc65b | 2,757 | py | Python | implementations/guidi2020/benchmark/PyAligner/test/test_matrix_init.py | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/guidi2020/benchmark/PyAligner/test/test_matrix_init.py | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/guidi2020/benchmark/PyAligner/test/test_matrix_init.py | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | import unittest
from pyaligner import *
class TestMatrixInit ( unittest.TestCase ):
def test_matrix_init_global ( self ):
scorer = Scorer( 5, -1, -3, 7 )
seqh = Sequence( "ACTG" )
seqv = Sequence( "ACAAA" )
matrix = DPMatrix( seqh, seqv, scorer )
self.assertEqual( matrix.seqh.seq_string, seqh.seq_string )
self.assertEqual( matrix.seqv.seq_string, seqv.seq_string )
self.assertEqual( matrix.scorer.match, scorer.match )
self.assertEqual( matrix.scorer.mismatch, scorer.mismatch )
self.assertEqual( matrix.scorer.gap, scorer.gap )
self.assertEqual( matrix.scorer.xdrop, scorer.xdrop )
self.assertEqual( matrix.semiglobal, False )
self.assertEqual( matrix.dimh, 5 )
self.assertEqual( matrix.dimv, 6 )
self.assertEqual( matrix.max_score, 10 )
self.assertEqual( matrix.max_row, 2 )
self.assertEqual( matrix.max_col, 2 )
self.assertEqual( matrix.dp_matrix, [[ 0, -3, -6, -9, -12 ],
[ -3, 5, 2, "X", "X" ],
[ -6, 2, 10, 7, 4 ],
[ -9, -1, 7, 9, 6 ],
[-12, "X", 4, 6, 8 ],
[-15, "X", "X", "X", 5 ]])
def test_matrix_init_semiglobal ( self ):
scorer = Scorer( 5, -1, -3, 7 )
seqh = Sequence( "ACTG" )
seqv = Sequence( "ACAAA" )
matrix = DPMatrix( seqh, seqv, scorer, True )
self.assertEqual( matrix.seqh.seq_string, seqh.seq_string )
self.assertEqual( matrix.seqv.seq_string, seqv.seq_string )
self.assertEqual( matrix.scorer.match, scorer.match )
self.assertEqual( matrix.scorer.mismatch, scorer.mismatch )
self.assertEqual( matrix.scorer.gap, scorer.gap )
self.assertEqual( matrix.scorer.xdrop, scorer.xdrop )
self.assertEqual( matrix.semiglobal, True )
self.assertEqual( matrix.dimh, 5 )
self.assertEqual( matrix.dimv, 6 )
self.assertEqual( matrix.max_score, 10 )
self.assertEqual( matrix.max_row, 2 )
self.assertEqual( matrix.max_col, 2 )
self.assertEqual( matrix.dp_matrix, [[ 0, -3, -6, -9, -12 ],
[ -3, 5, 2, "X", "X" ],
[ -6, 2, 10, 7, 4 ],
[ -9, -1, 7, 9, 6 ],
[-12, "X", 4, 6, 8 ],
[-15, "X", "X", "X", 5 ]])
if __name__ == '__main__':
unittest.main()
| 45.196721 | 73 | 0.488575 | import unittest
from pyaligner import *
class TestMatrixInit ( unittest.TestCase ):
def test_matrix_init_global ( self ):
scorer = Scorer( 5, -1, -3, 7 )
seqh = Sequence( "ACTG" )
seqv = Sequence( "ACAAA" )
matrix = DPMatrix( seqh, seqv, scorer )
self.assertEqual( matrix.seqh.seq_string, seqh.seq_string )
self.assertEqual( matrix.seqv.seq_string, seqv.seq_string )
self.assertEqual( matrix.scorer.match, scorer.match )
self.assertEqual( matrix.scorer.mismatch, scorer.mismatch )
self.assertEqual( matrix.scorer.gap, scorer.gap )
self.assertEqual( matrix.scorer.xdrop, scorer.xdrop )
self.assertEqual( matrix.semiglobal, False )
self.assertEqual( matrix.dimh, 5 )
self.assertEqual( matrix.dimv, 6 )
self.assertEqual( matrix.max_score, 10 )
self.assertEqual( matrix.max_row, 2 )
self.assertEqual( matrix.max_col, 2 )
self.assertEqual( matrix.dp_matrix, [[ 0, -3, -6, -9, -12 ],
[ -3, 5, 2, "X", "X" ],
[ -6, 2, 10, 7, 4 ],
[ -9, -1, 7, 9, 6 ],
[-12, "X", 4, 6, 8 ],
[-15, "X", "X", "X", 5 ]])
def test_matrix_init_semiglobal ( self ):
scorer = Scorer( 5, -1, -3, 7 )
seqh = Sequence( "ACTG" )
seqv = Sequence( "ACAAA" )
matrix = DPMatrix( seqh, seqv, scorer, True )
self.assertEqual( matrix.seqh.seq_string, seqh.seq_string )
self.assertEqual( matrix.seqv.seq_string, seqv.seq_string )
self.assertEqual( matrix.scorer.match, scorer.match )
self.assertEqual( matrix.scorer.mismatch, scorer.mismatch )
self.assertEqual( matrix.scorer.gap, scorer.gap )
self.assertEqual( matrix.scorer.xdrop, scorer.xdrop )
self.assertEqual( matrix.semiglobal, True )
self.assertEqual( matrix.dimh, 5 )
self.assertEqual( matrix.dimv, 6 )
self.assertEqual( matrix.max_score, 10 )
self.assertEqual( matrix.max_row, 2 )
self.assertEqual( matrix.max_col, 2 )
self.assertEqual( matrix.dp_matrix, [[ 0, -3, -6, -9, -12 ],
[ -3, 5, 2, "X", "X" ],
[ -6, 2, 10, 7, 4 ],
[ -9, -1, 7, 9, 6 ],
[-12, "X", 4, 6, 8 ],
[-15, "X", "X", "X", 5 ]])
if __name__ == '__main__':
unittest.main()
| true | true |
f72f2e9ad66d303ddba9f56bb29c8a001bcf4f92 | 623 | py | Python | visualization/__init__.py | svarthafnyra/CNN_Visualizations | a17615932519e67c7b7ec4ebaf030047dfd6d1e2 | [
"MIT"
] | 17 | 2019-08-13T06:07:13.000Z | 2021-03-02T22:14:21.000Z | visualization/__init__.py | svarthafnyra/CAMP-Project | a17615932519e67c7b7ec4ebaf030047dfd6d1e2 | [
"MIT"
] | null | null | null | visualization/__init__.py | svarthafnyra/CAMP-Project | a17615932519e67c7b7ec4ebaf030047dfd6d1e2 | [
"MIT"
] | 3 | 2019-12-16T09:08:10.000Z | 2020-02-19T10:43:25.000Z | #from visualization.deep_dream import runDeepDream
from visualization.gradcam import runGradCam
from visualization.guided_backprop import runGBackProp
from visualization.guided_gradcam import runGGradCam
from visualization.smooth_grad import runsmoothGrad
#from visualization.inverted_representation import runInvRep
from visualization.vanilla_backprop import runVanillaBP
from visualization.explain import runExplain
from visualization.deepimgprior import runImgPrior
from visualization.gradcam2 import runGradCam2
from visualization.explain2 import runExplain2
from visualization.inverted_representation import runInvRep | 51.916667 | 60 | 0.900482 |
from visualization.gradcam import runGradCam
from visualization.guided_backprop import runGBackProp
from visualization.guided_gradcam import runGGradCam
from visualization.smooth_grad import runsmoothGrad
from visualization.vanilla_backprop import runVanillaBP
from visualization.explain import runExplain
from visualization.deepimgprior import runImgPrior
from visualization.gradcam2 import runGradCam2
from visualization.explain2 import runExplain2
from visualization.inverted_representation import runInvRep | true | true |
f72f30a07b60677628393833bb542a0b8f11afc0 | 22,124 | py | Python | src/buildstream/_artifact.py | samkenxstream/buildstream | 2164ac3ad2854eea30f85af6af2bc8a0b8754f3f | [
"Apache-2.0"
] | null | null | null | src/buildstream/_artifact.py | samkenxstream/buildstream | 2164ac3ad2854eea30f85af6af2bc8a0b8754f3f | [
"Apache-2.0"
] | null | null | null | src/buildstream/_artifact.py | samkenxstream/buildstream | 2164ac3ad2854eea30f85af6af2bc8a0b8754f3f | [
"Apache-2.0"
] | null | null | null | #
# Copyright (C) 2020 Codethink Limited
# Copyright (C) 2019 Bloomberg Finance LP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Authors:
# Tom Pollard <tom.pollard@codethink.co.uk>
# Tristan Van Berkom <tristan.vanberkom@codethink.co.uk>
"""
Artifact
=========
Implementation of the Artifact class which aims to 'abstract' direct
artifact composite interaction away from Element class
"""
import os
from typing import Dict, Tuple
from ._protos.buildstream.v2.artifact_pb2 import Artifact as ArtifactProto
from . import _yaml
from . import utils
from .node import Node
from .types import _Scope
from .storage._casbaseddirectory import CasBasedDirectory
from .sandbox._config import SandboxConfig
from ._variables import Variables
# An Artifact class to abstract artifact operations
# from the Element class
#
# Args:
# element (Element): The Element object
# context (Context): The BuildStream context
# strong_key (str): The elements strong cache key, dependent on context
# strict_key (str): The elements strict cache key
# weak_key (str): The elements weak cache key
#
class Artifact:
version = 1
def __init__(self, element, context, *, strong_key=None, strict_key=None, weak_key=None):
self._element = element
self._context = context
self._cache_key = strong_key
self._strict_key = strict_key
self._weak_cache_key = weak_key
self._artifactdir = context.artifactdir
self._cas = context.get_cascache()
self._tmpdir = context.tmpdir
self._proto = None
self._metadata_keys = None # Strong, strict and weak key tuple extracted from the artifact
self._metadata_dependencies = None # Dictionary of dependency strong keys from the artifact
self._metadata_workspaced = None # Boolean of whether it's a workspaced artifact
self._metadata_workspaced_dependencies = None # List of which dependencies are workspaced from the artifact
self._cached = None # Boolean of whether the artifact is cached
# strong_key():
#
# A property which evaluates to the strong key, regardless of whether
# it was the strong key that the Artifact object was initialized with
# or whether it was the strong key loaded from artifact metadata.
#
@property
def strong_key(self) -> str:
if self.cached():
key, _, _ = self.get_metadata_keys()
else:
key = self._cache_key
return key
# strict_key():
#
# A property which evaluates to the strict key, regardless of whether
# it was the strict key that the Artifact object was initialized with
# or whether it was the strict key loaded from artifact metadata.
#
@property
def strict_key(self) -> str:
if self.cached():
_, key, _ = self.get_metadata_keys()
else:
key = self._strict_key
return key
# weak_key():
#
# A property which evaluates to the weak key, regardless of whether
# it was the weak key that the Artifact object was initialized with
# or whether it was the weak key loaded from artifact metadata.
#
@property
def weak_key(self) -> str:
if self.cached():
_, _, key = self.get_metadata_keys()
else:
key = self._weak_cache_key
return key
# get_files():
#
# Get a virtual directory for the artifact files content
#
# Returns:
# (Directory): The virtual directory object
#
def get_files(self):
files_digest = self._get_field_digest("files")
return CasBasedDirectory(self._cas, digest=files_digest)
# get_buildtree():
#
# Get a virtual directory for the artifact buildtree content
#
# Returns:
# (Directory): The virtual directory object
#
def get_buildtree(self):
buildtree_digest = self._get_field_digest("buildtree")
return CasBasedDirectory(self._cas, digest=buildtree_digest)
# get_sources():
#
# Get a virtual directory for the artifact sources
#
# Returns:
# (Directory): The virtual directory object
#
def get_sources(self):
sources_digest = self._get_field_digest("sources")
return CasBasedDirectory(self._cas, digest=sources_digest)
# get_logs():
#
# Get the paths of the artifact's logs
#
# Returns:
# (list): A list of object paths
#
def get_logs(self):
artifact = self._get_proto()
logfile_paths = []
for logfile in artifact.logs:
logfile_paths.append(self._cas.objpath(logfile.digest))
return logfile_paths
# get_extract_key():
#
# Get the key used to extract the artifact
#
# Returns:
# (str): The key
#
def get_extract_key(self):
return self._cache_key or self._weak_cache_key
# cache():
#
# Create the artifact and commit to cache
#
# Args:
# sandbox_build_dir (Directory): Virtual Directory object for the sandbox build-root
# collectvdir (Directory): Virtual Directoy object from within the sandbox for collection
# sourcesvdir (Directory): Virtual Directoy object for the staged sources
# buildresult (tuple): bool, short desc and detailed desc of result
# publicdata (dict): dict of public data to commit to artifact metadata
# variables (Variables): The element's Variables
# environment (dict): dict of the element's environment variables
# sandboxconfig (SandboxConfig): The element's SandboxConfig
#
# Returns:
# (int): The size of the newly cached artifact
#
def cache(
self,
*,
sandbox_build_dir,
collectvdir,
sourcesvdir,
buildresult,
publicdata,
variables,
environment,
sandboxconfig,
):
context = self._context
element = self._element
size = 0
filesvdir = None
buildtreevdir = None
artifact = ArtifactProto()
artifact.version = self.version
# Store result
artifact.build_success = buildresult[0]
artifact.build_error = buildresult[1]
artifact.build_error_details = "" if not buildresult[2] else buildresult[2]
# Store keys
artifact.strong_key = self._cache_key
artifact.strict_key = self._strict_key
artifact.weak_key = self._weak_cache_key
artifact.was_workspaced = bool(element._get_workspace())
properties = ["mtime"] if artifact.was_workspaced else []
# Store files
if collectvdir is not None:
filesvdir = CasBasedDirectory(cas_cache=self._cas)
filesvdir._import_files_internal(collectvdir, properties=properties)
artifact.files.CopyFrom(filesvdir._get_digest())
size += filesvdir._get_size()
# Store public data
with utils._tempnamedfile_name(dir=self._tmpdir) as tmpname:
_yaml.roundtrip_dump(publicdata, tmpname)
public_data_digest = self._cas.add_object(path=tmpname)
artifact.public_data.CopyFrom(public_data_digest)
size += public_data_digest.size_bytes
# Store low diversity metadata, this metadata must have a high
# probability of deduplication, such as environment variables
# and SandboxConfig.
#
with utils._tempnamedfile_name(dir=self._tmpdir) as tmpname:
sandbox_dict = sandboxconfig.to_dict()
low_diversity_dict = {"environment": environment, "sandbox-config": sandbox_dict}
low_diversity_node = Node.from_dict(low_diversity_dict)
_yaml.roundtrip_dump(low_diversity_node, tmpname)
low_diversity_meta_digest = self._cas.add_object(path=tmpname)
artifact.low_diversity_meta.CopyFrom(low_diversity_meta_digest)
size += low_diversity_meta_digest.size_bytes
# Store high diversity metadata, this metadata is expected to diverge
# for every element and as such cannot be deduplicated.
#
with utils._tempnamedfile_name(dir=self._tmpdir) as tmpname:
# The Variables object supports being converted directly to a dictionary
variables_dict = dict(variables)
high_diversity_dict = {"variables": variables_dict}
high_diversity_node = Node.from_dict(high_diversity_dict)
_yaml.roundtrip_dump(high_diversity_node, tmpname)
high_diversity_meta_digest = self._cas.add_object(path=tmpname)
artifact.high_diversity_meta.CopyFrom(high_diversity_meta_digest)
size += high_diversity_meta_digest.size_bytes
# store build dependencies
for e in element._dependencies(_Scope.BUILD):
new_build = artifact.build_deps.add()
new_build.project_name = e.project_name
new_build.element_name = e.name
new_build.cache_key = e._get_cache_key()
new_build.was_workspaced = bool(e._get_workspace())
# Store log file
log_filename = context.messenger.get_log_filename()
if log_filename:
digest = self._cas.add_object(path=log_filename)
log = artifact.logs.add()
log.name = os.path.basename(log_filename)
log.digest.CopyFrom(digest)
size += log.digest.size_bytes
# Store build tree
if sandbox_build_dir is not None:
buildtreevdir = CasBasedDirectory(cas_cache=self._cas)
buildtreevdir._import_files_internal(sandbox_build_dir, properties=properties)
artifact.buildtree.CopyFrom(buildtreevdir._get_digest())
size += buildtreevdir._get_size()
# Store sources
if sourcesvdir is not None:
artifact.sources.CopyFrom(sourcesvdir._get_digest())
size += sourcesvdir._get_size()
os.makedirs(os.path.dirname(os.path.join(self._artifactdir, element.get_artifact_name())), exist_ok=True)
keys = utils._deduplicate([self._cache_key, self._weak_cache_key])
for key in keys:
path = os.path.join(self._artifactdir, element.get_artifact_name(key=key))
with utils.save_file_atomic(path, mode="wb") as f:
f.write(artifact.SerializeToString())
return size
# cached_buildtree()
#
# Check if artifact is cached with expected buildtree. A
# buildtree will not be present if the rest of the partial artifact
# is not cached.
#
# Returns:
# (bool): True if artifact cached with buildtree, False if
# missing expected buildtree. Note this only confirms
# if a buildtree is present, not its contents.
#
def cached_buildtree(self):
buildtree_digest = self._get_field_digest("buildtree")
if buildtree_digest:
return self._cas.contains_directory(buildtree_digest, with_files=True)
else:
return False
# buildtree_exists()
#
# Check if artifact was created with a buildtree. This does not check
# whether the buildtree is present in the local cache.
#
# Returns:
# (bool): True if artifact was created with buildtree
#
def buildtree_exists(self):
artifact = self._get_proto()
return bool(str(artifact.buildtree))
# cached_sources()
#
# Check if artifact is cached with sources.
#
# Returns:
# (bool): True if artifact is cached with sources, False if sources
# are not available.
#
def cached_sources(self):
sources_digest = self._get_field_digest("sources")
if sources_digest:
return self._cas.contains_directory(sources_digest, with_files=True)
else:
return False
# load_public_data():
#
# Loads the public data from the cached artifact
#
# Returns:
# (dict): The artifacts cached public data
#
def load_public_data(self):
# Load the public data from the artifact
artifact = self._get_proto()
with self._cas.open(artifact.public_data) as meta_file:
meta_str = meta_file.read()
data = _yaml.load_data(meta_str, file_name="public.yaml")
return data
# load_sandbox_config():
#
# Loads the sandbox configuration from the cached artifact
#
# Returns:
# The stored SandboxConfig object
#
def load_sandbox_config(self) -> SandboxConfig:
# Load the sandbox data from the artifact
artifact = self._get_proto()
meta_file = self._cas.objpath(artifact.low_diversity_meta)
data = _yaml.load(meta_file, shortname="low-diversity-meta.yaml")
# Extract the sandbox data
config = data.get_mapping("sandbox-config")
# Return a SandboxConfig
return SandboxConfig.new_from_node(config)
# load_environment():
#
# Loads the environment variables from the cached artifact
#
# Returns:
# The environment variables
#
def load_environment(self) -> Dict[str, str]:
# Load the sandbox data from the artifact
artifact = self._get_proto()
meta_file = self._cas.objpath(artifact.low_diversity_meta)
data = _yaml.load(meta_file, shortname="low-diversity-meta.yaml")
# Extract the environment
config = data.get_mapping("environment")
# Return the environment
return config.strip_node_info()
# load_variables():
#
# Loads the element variables from the cached artifact
#
# Returns:
# The element variables
#
def load_variables(self) -> Variables:
# Load the sandbox data from the artifact
artifact = self._get_proto()
meta_file = self._cas.objpath(artifact.high_diversity_meta)
data = _yaml.load(meta_file, shortname="high-diversity-meta.yaml")
# Extract the variables node and return the new Variables instance
variables_node = data.get_mapping("variables")
return Variables(variables_node)
# load_build_result():
#
# Load the build result from the cached artifact
#
# Returns:
# (bool): Whether the artifact of this element present in the artifact cache is of a success
# (str): Short description of the result
# (str): Detailed description of the result
#
def load_build_result(self):
artifact = self._get_proto()
build_result = (artifact.build_success, artifact.build_error, artifact.build_error_details)
return build_result
# get_metadata_keys():
#
# Retrieve the strong and weak keys from the given artifact.
#
# Returns:
# The strong key
# The strict key
# The weak key
#
def get_metadata_keys(self) -> Tuple[str, str, str]:
if self._metadata_keys is not None:
return self._metadata_keys
# Extract proto
artifact = self._get_proto()
strong_key = artifact.strong_key
strict_key = artifact.strict_key
weak_key = artifact.weak_key
self._metadata_keys = (strong_key, strict_key, weak_key)
return self._metadata_keys
# get_metadata_workspaced():
#
# Retrieve the hash of dependency from the given artifact.
#
# Returns:
# (bool): Whether the given artifact was workspaced
#
def get_metadata_workspaced(self):
if self._metadata_workspaced is not None:
return self._metadata_workspaced
# Extract proto
artifact = self._get_proto()
self._metadata_workspaced = artifact.was_workspaced
return self._metadata_workspaced
# get_metadata_workspaced_dependencies():
#
# Retrieve the hash of workspaced dependencies keys from the given artifact.
#
# Returns:
# (list): List of which dependencies are workspaced
#
def get_metadata_workspaced_dependencies(self):
if self._metadata_workspaced_dependencies is not None:
return self._metadata_workspaced_dependencies
# Extract proto
artifact = self._get_proto()
self._metadata_workspaced_dependencies = [
dep.element_name for dep in artifact.build_deps if dep.was_workspaced
]
return self._metadata_workspaced_dependencies
# get_dependency_artifact_names()
#
# Retrieve the artifact names of all of the dependencies in _Scope.BUILD
#
# Returns:
# (list [str]): A list of refs of all build dependencies in staging order.
#
def get_dependency_artifact_names(self):
# XXX: The pylint disable is necessary due to upstream issue:
# https://github.com/PyCQA/pylint/issues/850
from .element import _get_normal_name # pylint: disable=cyclic-import
artifact = self._get_proto()
try:
dependency_refs = [
os.path.join(dep.project_name, _get_normal_name(dep.element_name), dep.cache_key)
for dep in artifact.build_deps
]
except AttributeError:
# If the artifact has no dependencies, the build_deps attribute
# will be missing from the proto.
dependency_refs = []
return dependency_refs
# query_cache():
#
# Check whether the artifact corresponding to the stored cache key is
# available. This also checks whether all required parts of the artifact
# are available, which may depend on command and configuration. The cache
# key used for querying is dependent on the current context.
#
# Returns:
# (bool): Whether artifact is in local cache
#
def query_cache(self):
artifact = self._load_proto()
if not artifact:
self._cached = False
return False
# Check whether 'files' subdirectory is available, with or without file contents
if str(artifact.files) and not self._cas.contains_directory(artifact.files, with_files=True):
self._cached = False
return False
# Check whether public data and logs are available
logfile_digests = [logfile.digest for logfile in artifact.logs]
digests = [artifact.low_diversity_meta, artifact.high_diversity_meta, artifact.public_data] + logfile_digests
if not self._cas.contains_files(digests):
self._cached = False
return False
self._proto = artifact
self._cached = True
return True
# cached()
#
# Return whether the artifact is available in the local cache. This must
# be called after `query_cache()` or `set_cached()`.
#
# Returns:
# (bool): Whether artifact is in local cache
#
def cached(self, *, buildtree=False):
assert self._cached is not None
ret = self._cached
if buildtree:
ret = ret and (self.cached_buildtree() or not self.buildtree_exists())
return ret
# cached_logs()
#
# Check if the artifact is cached with log files.
#
# Returns:
# (bool): True if artifact is cached with logs, False if
# element not cached or missing logs.
#
def cached_logs(self):
# Log files are currently considered an essential part of an artifact.
# If the artifact is cached, its log files are available as well.
return self._element._cached()
# set_cached()
#
# Mark the artifact as cached without querying the filesystem.
# This is used as optimization when we know the artifact is available.
#
def set_cached(self):
self._proto = self._load_proto()
assert self._proto
self._cached = True
# pull()
#
# Pull artifact from remote artifact repository into local artifact cache.
#
# Args:
# pull_buildtrees (bool): Whether to pull buildtrees or not
#
# Returns: True if the artifact has been downloaded, False otherwise
#
def pull(self, *, pull_buildtrees):
artifacts = self._context.artifactcache
pull_key = self.get_extract_key()
if not artifacts.pull(self._element, pull_key, pull_buildtrees=pull_buildtrees):
return False
self.set_cached()
# Add reference for the other key (weak key when pulling with strong key,
# strong key when pulling with weak key)
for key in self.get_metadata_keys():
artifacts.link_key(self._element, pull_key, key)
return True
# load_proto()
#
# Returns:
# (Artifact): Artifact proto
#
def _load_proto(self):
key = self.get_extract_key()
proto_path = os.path.join(self._artifactdir, self._element.get_artifact_name(key=key))
artifact = ArtifactProto()
try:
with open(proto_path, mode="r+b") as f:
artifact.ParseFromString(f.read())
except FileNotFoundError:
return None
os.utime(proto_path)
return artifact
# _get_proto()
#
# Returns:
# (Artifact): Artifact proto
#
def _get_proto(self):
return self._proto
# _get_field_digest()
#
# Returns:
# (Digest): Digest of field specified
#
def _get_field_digest(self, field):
artifact_proto = self._get_proto()
digest = getattr(artifact_proto, field)
if not str(digest):
return None
return digest
| 32.631268 | 117 | 0.650741 |
import os
from typing import Dict, Tuple
from ._protos.buildstream.v2.artifact_pb2 import Artifact as ArtifactProto
from . import _yaml
from . import utils
from .node import Node
from .types import _Scope
from .storage._casbaseddirectory import CasBasedDirectory
from .sandbox._config import SandboxConfig
from ._variables import Variables
class Artifact:
version = 1
def __init__(self, element, context, *, strong_key=None, strict_key=None, weak_key=None):
self._element = element
self._context = context
self._cache_key = strong_key
self._strict_key = strict_key
self._weak_cache_key = weak_key
self._artifactdir = context.artifactdir
self._cas = context.get_cascache()
self._tmpdir = context.tmpdir
self._proto = None
self._metadata_keys = None
self._metadata_dependencies = None
self._metadata_workspaced = None
self._metadata_workspaced_dependencies = None # List of which dependencies are workspaced from the artifact
self._cached = None # Boolean of whether the artifact is cached
# strong_key():
#
# A property which evaluates to the strong key, regardless of whether
# it was the strong key that the Artifact object was initialized with
# or whether it was the strong key loaded from artifact metadata.
#
@property
def strong_key(self) -> str:
if self.cached():
key, _, _ = self.get_metadata_keys()
else:
key = self._cache_key
return key
# strict_key():
#
# A property which evaluates to the strict key, regardless of whether
# it was the strict key that the Artifact object was initialized with
# or whether it was the strict key loaded from artifact metadata.
#
@property
def strict_key(self) -> str:
if self.cached():
_, key, _ = self.get_metadata_keys()
else:
key = self._strict_key
return key
# weak_key():
#
# A property which evaluates to the weak key, regardless of whether
# it was the weak key that the Artifact object was initialized with
# or whether it was the weak key loaded from artifact metadata.
#
@property
def weak_key(self) -> str:
if self.cached():
_, _, key = self.get_metadata_keys()
else:
key = self._weak_cache_key
return key
# get_files():
#
# Get a virtual directory for the artifact files content
#
# Returns:
# (Directory): The virtual directory object
#
def get_files(self):
files_digest = self._get_field_digest("files")
return CasBasedDirectory(self._cas, digest=files_digest)
# get_buildtree():
#
# Get a virtual directory for the artifact buildtree content
#
# Returns:
# (Directory): The virtual directory object
#
def get_buildtree(self):
buildtree_digest = self._get_field_digest("buildtree")
return CasBasedDirectory(self._cas, digest=buildtree_digest)
# get_sources():
#
# Get a virtual directory for the artifact sources
#
# Returns:
# (Directory): The virtual directory object
#
def get_sources(self):
sources_digest = self._get_field_digest("sources")
return CasBasedDirectory(self._cas, digest=sources_digest)
# get_logs():
#
# Get the paths of the artifact's logs
def get_logs(self):
artifact = self._get_proto()
logfile_paths = []
for logfile in artifact.logs:
logfile_paths.append(self._cas.objpath(logfile.digest))
return logfile_paths
def get_extract_key(self):
return self._cache_key or self._weak_cache_key
# environment (dict): dict of the element's environment variables
#
# Returns:
# (int): The size of the newly cached artifact
#
def cache(
self,
*,
sandbox_build_dir,
collectvdir,
sourcesvdir,
buildresult,
publicdata,
variables,
environment,
sandboxconfig,
):
context = self._context
element = self._element
size = 0
filesvdir = None
buildtreevdir = None
artifact = ArtifactProto()
artifact.version = self.version
# Store result
artifact.build_success = buildresult[0]
artifact.build_error = buildresult[1]
artifact.build_error_details = "" if not buildresult[2] else buildresult[2]
# Store keys
artifact.strong_key = self._cache_key
artifact.strict_key = self._strict_key
artifact.weak_key = self._weak_cache_key
artifact.was_workspaced = bool(element._get_workspace())
properties = ["mtime"] if artifact.was_workspaced else []
# Store files
if collectvdir is not None:
filesvdir = CasBasedDirectory(cas_cache=self._cas)
filesvdir._import_files_internal(collectvdir, properties=properties)
artifact.files.CopyFrom(filesvdir._get_digest())
size += filesvdir._get_size()
# Store public data
with utils._tempnamedfile_name(dir=self._tmpdir) as tmpname:
_yaml.roundtrip_dump(publicdata, tmpname)
public_data_digest = self._cas.add_object(path=tmpname)
artifact.public_data.CopyFrom(public_data_digest)
size += public_data_digest.size_bytes
# Store low diversity metadata, this metadata must have a high
# probability of deduplication, such as environment variables
# and SandboxConfig.
#
with utils._tempnamedfile_name(dir=self._tmpdir) as tmpname:
sandbox_dict = sandboxconfig.to_dict()
low_diversity_dict = {"environment": environment, "sandbox-config": sandbox_dict}
low_diversity_node = Node.from_dict(low_diversity_dict)
_yaml.roundtrip_dump(low_diversity_node, tmpname)
low_diversity_meta_digest = self._cas.add_object(path=tmpname)
artifact.low_diversity_meta.CopyFrom(low_diversity_meta_digest)
size += low_diversity_meta_digest.size_bytes
# Store high diversity metadata, this metadata is expected to diverge
# for every element and as such cannot be deduplicated.
#
with utils._tempnamedfile_name(dir=self._tmpdir) as tmpname:
# The Variables object supports being converted directly to a dictionary
variables_dict = dict(variables)
high_diversity_dict = {"variables": variables_dict}
high_diversity_node = Node.from_dict(high_diversity_dict)
_yaml.roundtrip_dump(high_diversity_node, tmpname)
high_diversity_meta_digest = self._cas.add_object(path=tmpname)
artifact.high_diversity_meta.CopyFrom(high_diversity_meta_digest)
size += high_diversity_meta_digest.size_bytes
# store build dependencies
for e in element._dependencies(_Scope.BUILD):
new_build = artifact.build_deps.add()
new_build.project_name = e.project_name
new_build.element_name = e.name
new_build.cache_key = e._get_cache_key()
new_build.was_workspaced = bool(e._get_workspace())
# Store log file
log_filename = context.messenger.get_log_filename()
if log_filename:
digest = self._cas.add_object(path=log_filename)
log = artifact.logs.add()
log.name = os.path.basename(log_filename)
log.digest.CopyFrom(digest)
size += log.digest.size_bytes
# Store build tree
if sandbox_build_dir is not None:
buildtreevdir = CasBasedDirectory(cas_cache=self._cas)
buildtreevdir._import_files_internal(sandbox_build_dir, properties=properties)
artifact.buildtree.CopyFrom(buildtreevdir._get_digest())
size += buildtreevdir._get_size()
# Store sources
if sourcesvdir is not None:
artifact.sources.CopyFrom(sourcesvdir._get_digest())
size += sourcesvdir._get_size()
os.makedirs(os.path.dirname(os.path.join(self._artifactdir, element.get_artifact_name())), exist_ok=True)
keys = utils._deduplicate([self._cache_key, self._weak_cache_key])
for key in keys:
path = os.path.join(self._artifactdir, element.get_artifact_name(key=key))
with utils.save_file_atomic(path, mode="wb") as f:
f.write(artifact.SerializeToString())
return size
# cached_buildtree()
#
# Check if artifact is cached with expected buildtree. A
# buildtree will not be present if the rest of the partial artifact
# is not cached.
#
# Returns:
# (bool): True if artifact cached with buildtree, False if
# missing expected buildtree. Note this only confirms
# if a buildtree is present, not its contents.
#
def cached_buildtree(self):
buildtree_digest = self._get_field_digest("buildtree")
if buildtree_digest:
return self._cas.contains_directory(buildtree_digest, with_files=True)
else:
return False
# buildtree_exists()
#
# Check if artifact was created with a buildtree. This does not check
# whether the buildtree is present in the local cache.
#
# Returns:
# (bool): True if artifact was created with buildtree
#
def buildtree_exists(self):
artifact = self._get_proto()
return bool(str(artifact.buildtree))
# cached_sources()
#
# Check if artifact is cached with sources.
#
# Returns:
# (bool): True if artifact is cached with sources, False if sources
# are not available.
#
def cached_sources(self):
sources_digest = self._get_field_digest("sources")
if sources_digest:
return self._cas.contains_directory(sources_digest, with_files=True)
else:
return False
# load_public_data():
#
# Loads the public data from the cached artifact
#
# Returns:
# (dict): The artifacts cached public data
#
def load_public_data(self):
# Load the public data from the artifact
artifact = self._get_proto()
with self._cas.open(artifact.public_data) as meta_file:
meta_str = meta_file.read()
data = _yaml.load_data(meta_str, file_name="public.yaml")
return data
# load_sandbox_config():
#
# Loads the sandbox configuration from the cached artifact
#
# Returns:
# The stored SandboxConfig object
#
def load_sandbox_config(self) -> SandboxConfig:
# Load the sandbox data from the artifact
artifact = self._get_proto()
meta_file = self._cas.objpath(artifact.low_diversity_meta)
data = _yaml.load(meta_file, shortname="low-diversity-meta.yaml")
# Extract the sandbox data
config = data.get_mapping("sandbox-config")
# Return a SandboxConfig
return SandboxConfig.new_from_node(config)
# load_environment():
#
# Loads the environment variables from the cached artifact
#
# Returns:
# The environment variables
#
def load_environment(self) -> Dict[str, str]:
# Load the sandbox data from the artifact
artifact = self._get_proto()
meta_file = self._cas.objpath(artifact.low_diversity_meta)
data = _yaml.load(meta_file, shortname="low-diversity-meta.yaml")
# Extract the environment
config = data.get_mapping("environment")
# Return the environment
return config.strip_node_info()
# load_variables():
#
# Loads the element variables from the cached artifact
#
# Returns:
# The element variables
#
def load_variables(self) -> Variables:
# Load the sandbox data from the artifact
artifact = self._get_proto()
meta_file = self._cas.objpath(artifact.high_diversity_meta)
data = _yaml.load(meta_file, shortname="high-diversity-meta.yaml")
# Extract the variables node and return the new Variables instance
variables_node = data.get_mapping("variables")
return Variables(variables_node)
# load_build_result():
#
# Load the build result from the cached artifact
#
# Returns:
# (bool): Whether the artifact of this element present in the artifact cache is of a success
# (str): Short description of the result
# (str): Detailed description of the result
#
def load_build_result(self):
artifact = self._get_proto()
build_result = (artifact.build_success, artifact.build_error, artifact.build_error_details)
return build_result
# get_metadata_keys():
#
# Retrieve the strong and weak keys from the given artifact.
#
# Returns:
# The strong key
# The strict key
# The weak key
#
def get_metadata_keys(self) -> Tuple[str, str, str]:
if self._metadata_keys is not None:
return self._metadata_keys
# Extract proto
artifact = self._get_proto()
strong_key = artifact.strong_key
strict_key = artifact.strict_key
weak_key = artifact.weak_key
self._metadata_keys = (strong_key, strict_key, weak_key)
return self._metadata_keys
# get_metadata_workspaced():
#
# Retrieve the hash of dependency from the given artifact.
#
# Returns:
# (bool): Whether the given artifact was workspaced
#
def get_metadata_workspaced(self):
if self._metadata_workspaced is not None:
return self._metadata_workspaced
# Extract proto
artifact = self._get_proto()
self._metadata_workspaced = artifact.was_workspaced
return self._metadata_workspaced
# get_metadata_workspaced_dependencies():
#
# Retrieve the hash of workspaced dependencies keys from the given artifact.
#
# Returns:
# (list): List of which dependencies are workspaced
#
def get_metadata_workspaced_dependencies(self):
if self._metadata_workspaced_dependencies is not None:
return self._metadata_workspaced_dependencies
# Extract proto
artifact = self._get_proto()
self._metadata_workspaced_dependencies = [
dep.element_name for dep in artifact.build_deps if dep.was_workspaced
]
return self._metadata_workspaced_dependencies
# get_dependency_artifact_names()
#
# Retrieve the artifact names of all of the dependencies in _Scope.BUILD
#
# Returns:
# (list [str]): A list of refs of all build dependencies in staging order.
#
def get_dependency_artifact_names(self):
# XXX: The pylint disable is necessary due to upstream issue:
# https://github.com/PyCQA/pylint/issues/850
from .element import _get_normal_name # pylint: disable=cyclic-import
artifact = self._get_proto()
try:
dependency_refs = [
os.path.join(dep.project_name, _get_normal_name(dep.element_name), dep.cache_key)
for dep in artifact.build_deps
]
except AttributeError:
# If the artifact has no dependencies, the build_deps attribute
# will be missing from the proto.
dependency_refs = []
return dependency_refs
# query_cache():
#
# Check whether the artifact corresponding to the stored cache key is
# available. This also checks whether all required parts of the artifact
# are available, which may depend on command and configuration. The cache
# key used for querying is dependent on the current context.
#
# Returns:
# (bool): Whether artifact is in local cache
#
def query_cache(self):
artifact = self._load_proto()
if not artifact:
self._cached = False
return False
# Check whether 'files' subdirectory is available, with or without file contents
if str(artifact.files) and not self._cas.contains_directory(artifact.files, with_files=True):
self._cached = False
return False
# Check whether public data and logs are available
logfile_digests = [logfile.digest for logfile in artifact.logs]
digests = [artifact.low_diversity_meta, artifact.high_diversity_meta, artifact.public_data] + logfile_digests
if not self._cas.contains_files(digests):
self._cached = False
return False
self._proto = artifact
self._cached = True
return True
# cached()
#
# Return whether the artifact is available in the local cache. This must
# be called after `query_cache()` or `set_cached()`.
#
# Returns:
# (bool): Whether artifact is in local cache
#
def cached(self, *, buildtree=False):
assert self._cached is not None
ret = self._cached
if buildtree:
ret = ret and (self.cached_buildtree() or not self.buildtree_exists())
return ret
# cached_logs()
#
# Check if the artifact is cached with log files.
#
# Returns:
# (bool): True if artifact is cached with logs, False if
# element not cached or missing logs.
#
def cached_logs(self):
# Log files are currently considered an essential part of an artifact.
# If the artifact is cached, its log files are available as well.
return self._element._cached()
# set_cached()
#
# Mark the artifact as cached without querying the filesystem.
# This is used as optimization when we know the artifact is available.
#
def set_cached(self):
self._proto = self._load_proto()
assert self._proto
self._cached = True
# pull()
#
# Pull artifact from remote artifact repository into local artifact cache.
#
# Args:
# pull_buildtrees (bool): Whether to pull buildtrees or not
#
# Returns: True if the artifact has been downloaded, False otherwise
#
def pull(self, *, pull_buildtrees):
artifacts = self._context.artifactcache
pull_key = self.get_extract_key()
if not artifacts.pull(self._element, pull_key, pull_buildtrees=pull_buildtrees):
return False
self.set_cached()
# Add reference for the other key (weak key when pulling with strong key,
# strong key when pulling with weak key)
for key in self.get_metadata_keys():
artifacts.link_key(self._element, pull_key, key)
return True
# load_proto()
#
# Returns:
# (Artifact): Artifact proto
#
def _load_proto(self):
key = self.get_extract_key()
proto_path = os.path.join(self._artifactdir, self._element.get_artifact_name(key=key))
artifact = ArtifactProto()
try:
with open(proto_path, mode="r+b") as f:
artifact.ParseFromString(f.read())
except FileNotFoundError:
return None
os.utime(proto_path)
return artifact
# _get_proto()
#
# Returns:
# (Artifact): Artifact proto
#
def _get_proto(self):
return self._proto
# _get_field_digest()
#
# Returns:
# (Digest): Digest of field specified
#
def _get_field_digest(self, field):
artifact_proto = self._get_proto()
digest = getattr(artifact_proto, field)
if not str(digest):
return None
return digest
| true | true |
f72f3137c35f25ad4295e8ff69e5522c6bc0fa3c | 466 | py | Python | database.py | Karasiq/flask-apachan | 11e1e6009910dfa762c8009e6ce96dc1407160b1 | [
"MIT"
] | null | null | null | database.py | Karasiq/flask-apachan | 11e1e6009910dfa762c8009e6ce96dc1407160b1 | [
"MIT"
] | null | null | null | database.py | Karasiq/flask-apachan | 11e1e6009910dfa762c8009e6ce96dc1407160b1 | [
"MIT"
] | null | null | null | from flask.ext.sqlalchemy import SQLAlchemy
import os, sys
sys.path.append(os.getcwd())
sys.path.append(os.path.join(os.getcwd(), '..'))
from app import app
db = SQLAlchemy(app)
db_session = db.session
def init_db():
# import all modules here that might define models so that
# they will be registered properly on the metadata. Otherwise
# you will have to import them first before calling init_db()
import models
db.Model.metadata.create_all() | 33.285714 | 66 | 0.736052 | from flask.ext.sqlalchemy import SQLAlchemy
import os, sys
sys.path.append(os.getcwd())
sys.path.append(os.path.join(os.getcwd(), '..'))
from app import app
db = SQLAlchemy(app)
db_session = db.session
def init_db():
import models
db.Model.metadata.create_all() | true | true |
f72f337038924789342a29bdf12f894156a4a5c5 | 17,605 | py | Python | sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2018_10_01/operations/_virtual_machine_images_operations.py | iscai-msft/azure-sdk-for-python | 83715b95c41e519d5be7f1180195e2fba136fc0f | [
"MIT"
] | 1 | 2020-05-12T23:29:15.000Z | 2020-05-12T23:29:15.000Z | sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2018_10_01/operations/_virtual_machine_images_operations.py | iscai-msft/azure-sdk-for-python | 83715b95c41e519d5be7f1180195e2fba136fc0f | [
"MIT"
] | 226 | 2019-07-24T07:57:21.000Z | 2019-10-15T01:07:24.000Z | sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2018_10_01/operations/_virtual_machine_images_operations.py | iscai-msft/azure-sdk-for-python | 83715b95c41e519d5be7f1180195e2fba136fc0f | [
"MIT"
] | null | null | null | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class VirtualMachineImagesOperations(object):
"""VirtualMachineImagesOperations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
:ivar api_version: Client Api Version. Constant value: "2018-10-01".
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2018-10-01"
self.config = config
def get(
self, location, publisher_name, offer, skus, version, custom_headers=None, raw=False, **operation_config):
"""Gets a virtual machine image.
:param location: The name of a supported Azure region.
:type location: str
:param publisher_name: A valid image publisher.
:type publisher_name: str
:param offer: A valid image publisher offer.
:type offer: str
:param skus: A valid image SKU.
:type skus: str
:param version: A valid image SKU version.
:type version: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: VirtualMachineImage or ClientRawResponse if raw=true
:rtype: ~azure.mgmt.compute.v2018_10_01.models.VirtualMachineImage or
~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
# Construct URL
url = self.get.metadata['url']
path_format_arguments = {
'location': self._serialize.url("location", location, 'str'),
'publisherName': self._serialize.url("publisher_name", publisher_name, 'str'),
'offer': self._serialize.url("offer", offer, 'str'),
'skus': self._serialize.url("skus", skus, 'str'),
'version': self._serialize.url("version", version, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('VirtualMachineImage', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions/{version}'}
def list(
self, location, publisher_name, offer, skus, expand=None, top=None, orderby=None, custom_headers=None, raw=False, **operation_config):
"""Gets a list of all virtual machine image versions for the specified
location, publisher, offer, and SKU.
:param location: The name of a supported Azure region.
:type location: str
:param publisher_name: A valid image publisher.
:type publisher_name: str
:param offer: A valid image publisher offer.
:type offer: str
:param skus: A valid image SKU.
:type skus: str
:param expand: The expand expression to apply on the operation.
:type expand: str
:param top:
:type top: int
:param orderby:
:type orderby: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~azure.mgmt.compute.v2018_10_01.models.VirtualMachineImageResource]
or ~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
# Construct URL
url = self.list.metadata['url']
path_format_arguments = {
'location': self._serialize.url("location", location, 'str'),
'publisherName': self._serialize.url("publisher_name", publisher_name, 'str'),
'offer': self._serialize.url("offer", offer, 'str'),
'skus': self._serialize.url("skus", skus, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')
if top is not None:
query_parameters['$top'] = self._serialize.query("top", top, 'int')
if orderby is not None:
query_parameters['$orderby'] = self._serialize.query("orderby", orderby, 'str')
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[VirtualMachineImageResource]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions'}
def list_offers(
self, location, publisher_name, custom_headers=None, raw=False, **operation_config):
"""Gets a list of virtual machine image offers for the specified location
and publisher.
:param location: The name of a supported Azure region.
:type location: str
:param publisher_name: A valid image publisher.
:type publisher_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~azure.mgmt.compute.v2018_10_01.models.VirtualMachineImageResource]
or ~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
# Construct URL
url = self.list_offers.metadata['url']
path_format_arguments = {
'location': self._serialize.url("location", location, 'str'),
'publisherName': self._serialize.url("publisher_name", publisher_name, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[VirtualMachineImageResource]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
list_offers.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers'}
def list_publishers(
self, location, custom_headers=None, raw=False, **operation_config):
"""Gets a list of virtual machine image publishers for the specified Azure
location.
:param location: The name of a supported Azure region.
:type location: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~azure.mgmt.compute.v2018_10_01.models.VirtualMachineImageResource]
or ~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
# Construct URL
url = self.list_publishers.metadata['url']
path_format_arguments = {
'location': self._serialize.url("location", location, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[VirtualMachineImageResource]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
list_publishers.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers'}
def list_skus(
self, location, publisher_name, offer, custom_headers=None, raw=False, **operation_config):
"""Gets a list of virtual machine image SKUs for the specified location,
publisher, and offer.
:param location: The name of a supported Azure region.
:type location: str
:param publisher_name: A valid image publisher.
:type publisher_name: str
:param offer: A valid image publisher offer.
:type offer: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype:
list[~azure.mgmt.compute.v2018_10_01.models.VirtualMachineImageResource]
or ~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
# Construct URL
url = self.list_skus.metadata['url']
path_format_arguments = {
'location': self._serialize.url("location", location, 'str'),
'publisherName': self._serialize.url("publisher_name", publisher_name, 'str'),
'offer': self._serialize.url("offer", offer, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[VirtualMachineImageResource]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
list_skus.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus'}
| 46.207349 | 205 | 0.663334 |
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class VirtualMachineImagesOperations(object):
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2018-10-01"
self.config = config
def get(
self, location, publisher_name, offer, skus, version, custom_headers=None, raw=False, **operation_config):
url = self.get.metadata['url']
path_format_arguments = {
'location': self._serialize.url("location", location, 'str'),
'publisherName': self._serialize.url("publisher_name", publisher_name, 'str'),
'offer': self._serialize.url("offer", offer, 'str'),
'skus': self._serialize.url("skus", skus, 'str'),
'version': self._serialize.url("version", version, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('VirtualMachineImage', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions/{version}'}
def list(
self, location, publisher_name, offer, skus, expand=None, top=None, orderby=None, custom_headers=None, raw=False, **operation_config):
url = self.list.metadata['url']
path_format_arguments = {
'location': self._serialize.url("location", location, 'str'),
'publisherName': self._serialize.url("publisher_name", publisher_name, 'str'),
'offer': self._serialize.url("offer", offer, 'str'),
'skus': self._serialize.url("skus", skus, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, 'str')
if top is not None:
query_parameters['$top'] = self._serialize.query("top", top, 'int')
if orderby is not None:
query_parameters['$orderby'] = self._serialize.query("orderby", orderby, 'str')
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[VirtualMachineImageResource]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions'}
def list_offers(
self, location, publisher_name, custom_headers=None, raw=False, **operation_config):
url = self.list_offers.metadata['url']
path_format_arguments = {
'location': self._serialize.url("location", location, 'str'),
'publisherName': self._serialize.url("publisher_name", publisher_name, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[VirtualMachineImageResource]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
list_offers.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers'}
def list_publishers(
self, location, custom_headers=None, raw=False, **operation_config):
url = self.list_publishers.metadata['url']
path_format_arguments = {
'location': self._serialize.url("location", location, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[VirtualMachineImageResource]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
list_publishers.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers'}
def list_skus(
self, location, publisher_name, offer, custom_headers=None, raw=False, **operation_config):
url = self.list_skus.metadata['url']
path_format_arguments = {
'location': self._serialize.url("location", location, 'str'),
'publisherName': self._serialize.url("publisher_name", publisher_name, 'str'),
'offer': self._serialize.url("offer", offer, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[VirtualMachineImageResource]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
list_skus.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus'}
| true | true |
f72f33b9736a53f5a2d0f2502ca8c3c7b2c0d2fa | 1,601 | py | Python | neural_compressor/ux/utils/yaml_utils.py | intel/neural-compressor | 16a4a12045fcb468da4d33769aff2c1a5e2ba6ba | [
"Apache-2.0"
] | 172 | 2021-09-14T18:34:17.000Z | 2022-03-30T06:49:53.000Z | neural_compressor/ux/utils/yaml_utils.py | intel/lp-opt-tool | 130eefa3586b38df6c0ff78cc8807ae273f6a63f | [
"Apache-2.0"
] | 40 | 2021-09-14T02:26:12.000Z | 2022-03-29T08:34:04.000Z | neural_compressor/ux/utils/yaml_utils.py | intel/neural-compressor | 16a4a12045fcb468da4d33769aff2c1a5e2ba6ba | [
"Apache-2.0"
] | 33 | 2021-09-15T07:27:25.000Z | 2022-03-25T08:30:57.000Z | # -*- coding: utf-8 -*-
# Copyright (c) 2021-2022 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""UX server utils module."""
from typing import Any
from neural_compressor.conf.config import Pruner
def float_representer(dumper: Any, value: float) -> Any:
"""Float representer for yaml dumper."""
if value.is_integer():
float_out = f"{int(value)}.0"
else:
float_out = f"{value}"
return dumper.represent_scalar("tag:yaml.org,2002:float", float_out)
def pruner_representer(dumper: Any, pruner: Pruner) -> Any:
"""Pruner representer for yaml dumper."""
pruner_data = {
"start_epoch": pruner.start_epoch,
"end_epoch": pruner.end_epoch,
"update_frequency": pruner.update_frequency,
"target_sparsity": pruner.target_sparsity,
"initial_sparsity": pruner.initial_sparsity,
"prune_type": pruner.prune_type,
"method": pruner.method,
"names": pruner.names,
"parameters": pruner.parameters,
}
return dumper.represent_mapping(
"!Pruner",
pruner_data,
)
| 33.354167 | 74 | 0.690194 |
from typing import Any
from neural_compressor.conf.config import Pruner
def float_representer(dumper: Any, value: float) -> Any:
if value.is_integer():
float_out = f"{int(value)}.0"
else:
float_out = f"{value}"
return dumper.represent_scalar("tag:yaml.org,2002:float", float_out)
def pruner_representer(dumper: Any, pruner: Pruner) -> Any:
pruner_data = {
"start_epoch": pruner.start_epoch,
"end_epoch": pruner.end_epoch,
"update_frequency": pruner.update_frequency,
"target_sparsity": pruner.target_sparsity,
"initial_sparsity": pruner.initial_sparsity,
"prune_type": pruner.prune_type,
"method": pruner.method,
"names": pruner.names,
"parameters": pruner.parameters,
}
return dumper.represent_mapping(
"!Pruner",
pruner_data,
)
| true | true |
f72f3403b78785de5709a2d85b9f6807eb47d1ee | 5,584 | py | Python | im2scene/camera.py | miramirakim227/SwapNeRF_single_GT | 55a842ec4155fa782ca1c48b5c6863aeca8ca295 | [
"MIT"
] | null | null | null | im2scene/camera.py | miramirakim227/SwapNeRF_single_GT | 55a842ec4155fa782ca1c48b5c6863aeca8ca295 | [
"MIT"
] | null | null | null | im2scene/camera.py | miramirakim227/SwapNeRF_single_GT | 55a842ec4155fa782ca1c48b5c6863aeca8ca295 | [
"MIT"
] | 2 | 2021-12-07T04:02:02.000Z | 2021-12-30T04:44:50.000Z | import numpy as np
import torch
from scipy.spatial.transform import Rotation as Rot
import pdb
import math
def get_camera_mat(fov=49.13, invert=True):
# fov = 2 * arctan( sensor / (2 * focal))
# focal = (sensor / 2) * 1 / (tan(0.5 * fov))
# in our case, sensor = 2 as pixels are in [-1, 1]
focal = 1. / np.tan(0.5 * fov * np.pi/180.)
focal = focal.astype(np.float32)
mat = torch.tensor([
[focal, 0., 0., 0.],
[0., focal, 0., 0.],
[0., 0., 1, 0.],
[0., 0., 0., 1.]
]).reshape(1, 4, 4)
if invert:
mat = torch.inverse(mat)
return mat
def get_random_pose(u, v, range_radius, batch_size=16, # batch size 유동적으로 바꿀 수 있도록!
invert=False):
# edit mira start
if isinstance(u, int):
device = 'cpu'
u = torch.zeros(batch_size,).to(device)
v = torch.ones(batch_size,).to(device) * 0.25
loc = sample_on_sphere(u, v, size=(batch_size))
radius = range_radius[0] + \
torch.rand(batch_size) * (range_radius[1] - range_radius[0])
if loc.is_cuda:
radius = radius.cuda()
loc = loc * radius.unsqueeze(-1)
R = look_at(loc)
RT = torch.eye(4).reshape(1, 4, 4).repeat(batch_size, 1, 1)
RT[:, :3, :3] = R
RT[:, :3, -1] = loc
if invert:
RT = torch.inverse(RT)
return radius, RT
def get_middle_pose(range_u, range_v, range_radius, batch_size=32,
invert=False):
u_m, u_v, r_v = sum(range_u) * 0.5, sum(range_v) * \
0.5, sum(range_radius) * 0.5
loc = sample_on_sphere((u_m, u_m), (u_v, u_v), size=(batch_size))
radius = torch.ones(batch_size) * r_v
loc = loc * radius.unsqueeze(-1)
R = look_at(loc)
RT = torch.eye(4).reshape(1, 4, 4).repeat(batch_size, 1, 1)
RT[:, :3, :3] = R
RT[:, :3, -1] = loc
if invert:
RT = torch.inverse(RT)
return RT
def get_camera_pose(range_u, range_v, range_r, val_u=0.5, val_v=0.5, val_r=0.5,
batch_size=32, invert=False):
u0, ur = range_u[0], range_u[1] - range_u[0]
v0, vr = range_v[0], range_v[1] - range_v[0]
r0, rr = range_r[0], range_r[1] - range_r[0]
u = u0 + val_u * ur
v = v0 + val_v * vr
r = r0 + val_r * rr
loc = sample_on_sphere((u, u), (v, v), size=(batch_size))
radius = torch.ones(batch_size) * r
loc = loc * radius.unsqueeze(-1)
R = look_at(loc)
RT = torch.eye(4).reshape(1, 4, 4).repeat(batch_size, 1, 1)
RT[:, :3, :3] = R
RT[:, :3, -1] = loc
if invert:
RT = torch.inverse(RT)
return RT
# edit: np -> torch
def to_sphere(u, v):
theta = 2 * math.pi * u
phi = torch.arccos(1 - 2 * v)
cx = torch.sin(phi) * torch.cos(theta)
cy = torch.sin(phi) * torch.sin(theta)
cz = torch.cos(phi)
return torch.stack([cx, cy, cz], dim=-1)
def sample_on_sphere(u=None, v=None, size=(1,),
to_pytorch=True): # range_u (0, 0) range_v (0.25, 0.25)
sample = to_sphere(u, v) # sample expect to be (16, 3)
if to_pytorch:
sample = torch.tensor(sample).float()
return sample
def look_at(eye, at=np.array([0, 0, 0]), up=np.array([0, 0, 1]), eps=1e-5,
to_pytorch=True):
at = at.reshape(1, 3)
up = up.reshape(1, 3)
eye = eye.reshape(-1, 3)
if isinstance(eye, torch.Tensor):
if eye.is_cuda:
device=torch.device('cuda:0')
else:
device=torch.device('cpu') # array
at = torch.tensor(at).to(device).float()
up = torch.tensor(up).to(device).float()
up = up.repeat(eye.shape[0] // up.shape[0], 1)
eps = torch.tensor([eps]).reshape(1, 1).repeat(up.shape[0], 1).to(device).float()
z_axis = eye - at
z_axis = z_axis / torch.max(torch.stack([torch.norm(z_axis,
dim=1, keepdim=True), eps]))
x_axis = torch.cross(up, z_axis)
x_axis = x_axis / torch.max(torch.stack([torch.norm(x_axis,
dim=1, keepdim=True), eps]))
y_axis = torch.cross(z_axis, x_axis)
y_axis = y_axis / torch.max(torch.stack([torch.norm(y_axis,
dim=1, keepdim=True), eps]))
r_mat = torch.cat(
(x_axis.reshape(-1, 3, 1), y_axis.reshape(-1, 3, 1), z_axis.reshape(
-1, 3, 1)), dim=2)
else:
print('pass here? oh my gaadd....') # 여기 안들어간다 오우쨔쓰!!
up = up.repeat(eye.shape[0] // up.shape[0], axis = 0)
eps = np.array([eps]).reshape(1, 1).repeat(up.shape[0], axis=0)
z_axis = eye - at
z_axis /= np.max(np.stack([np.linalg.norm(z_axis,
axis=1, keepdims=True), eps]))
x_axis = np.cross(up, z_axis)
x_axis /= np.max(np.stack([np.linalg.norm(x_axis,
axis=1, keepdims=True), eps]))
y_axis = np.cross(z_axis, x_axis)
y_axis /= np.max(np.stack([np.linalg.norm(y_axis,
axis=1, keepdims=True), eps]))
r_mat = np.concatenate(
(x_axis.reshape(-1, 3, 1), y_axis.reshape(-1, 3, 1), z_axis.reshape(
-1, 3, 1)), axis=2)
if to_pytorch:
r_mat = torch.tensor(r_mat).float()
return r_mat
def get_rotation_matrix(axis='z', value=0., batch_size=32):
r = Rot.from_euler(axis, value * 2 * np.pi).as_dcm()
r = torch.from_numpy(r).reshape(1, 3, 3).repeat(batch_size, 1, 1)
return r
| 33.238095 | 89 | 0.530802 | import numpy as np
import torch
from scipy.spatial.transform import Rotation as Rot
import pdb
import math
def get_camera_mat(fov=49.13, invert=True):
focal = 1. / np.tan(0.5 * fov * np.pi/180.)
focal = focal.astype(np.float32)
mat = torch.tensor([
[focal, 0., 0., 0.],
[0., focal, 0., 0.],
[0., 0., 1, 0.],
[0., 0., 0., 1.]
]).reshape(1, 4, 4)
if invert:
mat = torch.inverse(mat)
return mat
def get_random_pose(u, v, range_radius, batch_size=16,
invert=False):
if isinstance(u, int):
device = 'cpu'
u = torch.zeros(batch_size,).to(device)
v = torch.ones(batch_size,).to(device) * 0.25
loc = sample_on_sphere(u, v, size=(batch_size))
radius = range_radius[0] + \
torch.rand(batch_size) * (range_radius[1] - range_radius[0])
if loc.is_cuda:
radius = radius.cuda()
loc = loc * radius.unsqueeze(-1)
R = look_at(loc)
RT = torch.eye(4).reshape(1, 4, 4).repeat(batch_size, 1, 1)
RT[:, :3, :3] = R
RT[:, :3, -1] = loc
if invert:
RT = torch.inverse(RT)
return radius, RT
def get_middle_pose(range_u, range_v, range_radius, batch_size=32,
invert=False):
u_m, u_v, r_v = sum(range_u) * 0.5, sum(range_v) * \
0.5, sum(range_radius) * 0.5
loc = sample_on_sphere((u_m, u_m), (u_v, u_v), size=(batch_size))
radius = torch.ones(batch_size) * r_v
loc = loc * radius.unsqueeze(-1)
R = look_at(loc)
RT = torch.eye(4).reshape(1, 4, 4).repeat(batch_size, 1, 1)
RT[:, :3, :3] = R
RT[:, :3, -1] = loc
if invert:
RT = torch.inverse(RT)
return RT
def get_camera_pose(range_u, range_v, range_r, val_u=0.5, val_v=0.5, val_r=0.5,
batch_size=32, invert=False):
u0, ur = range_u[0], range_u[1] - range_u[0]
v0, vr = range_v[0], range_v[1] - range_v[0]
r0, rr = range_r[0], range_r[1] - range_r[0]
u = u0 + val_u * ur
v = v0 + val_v * vr
r = r0 + val_r * rr
loc = sample_on_sphere((u, u), (v, v), size=(batch_size))
radius = torch.ones(batch_size) * r
loc = loc * radius.unsqueeze(-1)
R = look_at(loc)
RT = torch.eye(4).reshape(1, 4, 4).repeat(batch_size, 1, 1)
RT[:, :3, :3] = R
RT[:, :3, -1] = loc
if invert:
RT = torch.inverse(RT)
return RT
def to_sphere(u, v):
theta = 2 * math.pi * u
phi = torch.arccos(1 - 2 * v)
cx = torch.sin(phi) * torch.cos(theta)
cy = torch.sin(phi) * torch.sin(theta)
cz = torch.cos(phi)
return torch.stack([cx, cy, cz], dim=-1)
def sample_on_sphere(u=None, v=None, size=(1,),
to_pytorch=True):
sample = to_sphere(u, v)
if to_pytorch:
sample = torch.tensor(sample).float()
return sample
def look_at(eye, at=np.array([0, 0, 0]), up=np.array([0, 0, 1]), eps=1e-5,
to_pytorch=True):
at = at.reshape(1, 3)
up = up.reshape(1, 3)
eye = eye.reshape(-1, 3)
if isinstance(eye, torch.Tensor):
if eye.is_cuda:
device=torch.device('cuda:0')
else:
device=torch.device('cpu')
at = torch.tensor(at).to(device).float()
up = torch.tensor(up).to(device).float()
up = up.repeat(eye.shape[0] // up.shape[0], 1)
eps = torch.tensor([eps]).reshape(1, 1).repeat(up.shape[0], 1).to(device).float()
z_axis = eye - at
z_axis = z_axis / torch.max(torch.stack([torch.norm(z_axis,
dim=1, keepdim=True), eps]))
x_axis = torch.cross(up, z_axis)
x_axis = x_axis / torch.max(torch.stack([torch.norm(x_axis,
dim=1, keepdim=True), eps]))
y_axis = torch.cross(z_axis, x_axis)
y_axis = y_axis / torch.max(torch.stack([torch.norm(y_axis,
dim=1, keepdim=True), eps]))
r_mat = torch.cat(
(x_axis.reshape(-1, 3, 1), y_axis.reshape(-1, 3, 1), z_axis.reshape(
-1, 3, 1)), dim=2)
else:
print('pass here? oh my gaadd....')
up = up.repeat(eye.shape[0] // up.shape[0], axis = 0)
eps = np.array([eps]).reshape(1, 1).repeat(up.shape[0], axis=0)
z_axis = eye - at
z_axis /= np.max(np.stack([np.linalg.norm(z_axis,
axis=1, keepdims=True), eps]))
x_axis = np.cross(up, z_axis)
x_axis /= np.max(np.stack([np.linalg.norm(x_axis,
axis=1, keepdims=True), eps]))
y_axis = np.cross(z_axis, x_axis)
y_axis /= np.max(np.stack([np.linalg.norm(y_axis,
axis=1, keepdims=True), eps]))
r_mat = np.concatenate(
(x_axis.reshape(-1, 3, 1), y_axis.reshape(-1, 3, 1), z_axis.reshape(
-1, 3, 1)), axis=2)
if to_pytorch:
r_mat = torch.tensor(r_mat).float()
return r_mat
def get_rotation_matrix(axis='z', value=0., batch_size=32):
r = Rot.from_euler(axis, value * 2 * np.pi).as_dcm()
r = torch.from_numpy(r).reshape(1, 3, 3).repeat(batch_size, 1, 1)
return r
| true | true |
f72f348a5b9935ce6a4cb36600f5af78d9693402 | 4,948 | py | Python | 01_process_reads/at_combo_lib_ex58/01_usearch_merge.py | ddingding/coevolution_mechanism | 4a03f7a105a2606e812dd8a4fa88272519ddab86 | [
"MIT"
] | 1 | 2022-01-16T09:32:33.000Z | 2022-01-16T09:32:33.000Z | 01_process_reads/at_combo_lib_ex58/01_usearch_merge.py | ddingding/coevolution_mechanism | 4a03f7a105a2606e812dd8a4fa88272519ddab86 | [
"MIT"
] | null | null | null | 01_process_reads/at_combo_lib_ex58/01_usearch_merge.py | ddingding/coevolution_mechanism | 4a03f7a105a2606e812dd8a4fa88272519ddab86 | [
"MIT"
] | null | null | null | '''
## using flash 1.2.11 to merge paired end reads
# at combo mutant files
# the sample identified is in the middle of the filename: 'D21-169', refer to ex58_config.csv for description of that
# sample
# each paired end read are split in the files ending in '1_sequence.fastq' and '2_sequence.fastq'
"210105Lau_D21-169_1_sequence.fastq 210105Lau_D21-169_2_sequence.fastq"
"210105Lau_D21-170_1_sequence.fastq 210105Lau_D21-170_2_sequence.fastq"
"210105Lau_D21-171_1_sequence.fastq 210105Lau_D21-171_2_sequence.fastq"
"210105Lau_D21-172_1_sequence.fastq 210105Lau_D21-172_2_sequence.fastq"
"210105Lau_D21-173_1_sequence.fastq 210105Lau_D21-173_2_sequence.fastq"
"210105Lau_D21-174_1_sequence.fastq 210105Lau_D21-174_2_sequence.fastq"
"210105Lau_D21-175_1_sequence.fastq 210105Lau_D21-175_2_sequence.fastq"
"210105Lau_D21-176_1_sequence.fastq 210105Lau_D21-176_2_sequence.fastq"
"210105Lau_D21-177_1_sequence.fastq 210105Lau_D21-177_2_sequence.fastq"
"210105Lau_D21-178_1_sequence.fastq 210105Lau_D21-178_2_sequence.fastq"
"210105Lau_D21-179_1_sequence.fastq 210105Lau_D21-179_2_sequence.fastq"
"210105Lau_D21-180_1_sequence.fastq 210105Lau_D21-180_2_sequence.fastq"
"210105Lau_D21-181_1_sequence.fastq 210105Lau_D21-181_2_sequence.fastq"
"210105Lau_D21-182_1_sequence.fastq 210105Lau_D21-182_2_sequence.fastq"
"210105Lau_D21-183_1_sequence.fastq 210105Lau_D21-183_2_sequence.fastq"
"210105Lau_D21-184_1_sequence.fastq 210105Lau_D21-184_2_sequence.fastq"
"210105Lau_D21-185_1_sequence.fastq 210105Lau_D21-185_2_sequence.fastq"
"210105Lau_D21-186_1_sequence.fastq 210105Lau_D21-186_2_sequence.fastq"
"210105Lau_D21-187_1_sequence.fastq 210105Lau_D21-187_2_sequence.fastq"
"210105Lau_D21-188_1_sequence.fastq 210105Lau_D21-188_2_sequence.fastq"
"210105Lau_D21-189_1_sequence.fastq 210105Lau_D21-189_2_sequence.fastq"
"210105Lau_D21-190_1_sequence.fastq 210105Lau_D21-190_2_sequence.fastq"
"210105Lau_D21-191_1_sequence.fastq 210105Lau_D21-191_2_sequence.fastq"
"210105Lau_D21-192_1_sequence.fastq 210105Lau_D21-192_2_sequence.fastq"
"210105Lau_D21-193_1_sequence.fastq 210105Lau_D21-193_2_sequence.fastq"
"210105Lau_D21-194_1_sequence.fastq 210105Lau_D21-194_2_sequence.fastq"
"210105Lau_D21-195_1_sequence.fastq 210105Lau_D21-195_2_sequence.fastq"
"210105Lau_D21-196_1_sequence.fastq 210105Lau_D21-196_2_sequence.fastq"
"210105Lau_D21-197_1_sequence.fastq 210105Lau_D21-197_2_sequence.fastq"
"210105Lau_D21-198_1_sequence.fastq 210105Lau_D21-198_2_sequence.fastq"
"210105Lau_D21-199_1_sequence.fastq 210105Lau_D21-199_2_sequence.fastq"
"210105Lau_D21-200_1_sequence.fastq 210105Lau_D21-200_2_sequence.fastq"
"210105Lau_D21-201_1_sequence.fastq 210105Lau_D21-201_2_sequence.fastq"
"210105Lau_D21-202_1_sequence.fastq 210105Lau_D21-202_2_sequence.fastq"
"210105Lau_D21-203_1_sequence.fastq 210105Lau_D21-203_2_sequence.fastq"
"210105Lau_D21-204_1_sequence.fastq 210105Lau_D21-204_2_sequence.fastq"
"210105Lau_D21-205_1_sequence.fastq 210105Lau_D21-205_2_sequence.fastq"
"210105Lau_D21-206_1_sequence.fastq 210105Lau_D21-206_2_sequence.fastq"
"210105Lau_D21-207_1_sequence.fastq 210105Lau_D21-207_2_sequence.fastq"
"210105Lau_D21-208_1_sequence.fastq 210105Lau_D21-208_2_sequence.fastq"
"210105Lau_D21-209_1_sequence.fastq 210105Lau_D21-209_2_sequence.fastq"
"210105Lau_D21-210_1_sequence.fastq 210105Lau_D21-210_2_sequence.fastq"
"210105Lau_D21-211_1_sequence.fastq 210105Lau_D21-211_2_sequence.fastq"
"210105Lau_D21-212_1_sequence.fastq 210105Lau_D21-212_2_sequence.fastq"
"210105Lau_D21-213_1_sequence.fastq 210105Lau_D21-213_2_sequence.fastq"
"210105Lau_D21-214_1_sequence.fastq 210105Lau_D21-214_2_sequence.fastq"
"210105Lau_D21-215_1_sequence.fastq 210105Lau_D21-215_2_sequence.fastq"
"210105Lau_D21-216_1_sequence.fastq 210105Lau_D21-216_2_sequence.fastq"
'''
import os
from os import listdir
from os.path import isfile, join
from constants import AT_COMBO_RAW_DIR, AT_COMBO_MERGED_DIR, FLASH_PATH
fastqPath = AT_COMBO_RAW_DIR
outputDir = AT_COMBO_MERGED_DIR
# merge dirs
n_to_do = 1000
c = 0
with open(outputDir + 'cmdsUsed.txt', 'w') as fout:
# get a list of files that are already merged.
done_nums = [f.rstrip('-_merged.fastq')[-3:] for f in listdir(outputDir)
if isfile(join(outputDir, f))]
print('doing filepahts:{}{}'.format(fastqPath, outputDir))
print('file numbers already done:', done_nums)
fastq = [f.rstrip('_sequence.fastq')[:-1]
for f in listdir(fastqPath) if isfile(join(fastqPath, f))]
print('fastq files to do ', sorted(fastq))
# merge each file
for fa in fastq:
if c < n_to_do:
flash_cmd = '{} {}{}1_sequence.fastq {}{' \
'}2_sequence.fastq -o {} -d {}'.format(FLASH_PATH,
fastqPath, fa, fastqPath, fa, fa, outputDir)
print(flash_cmd)
os.system(flash_cmd)
# print('merging files: {} \n {}'.format(fastqPath+fa+'1_sequence.fastq', fastqPath+fa+'2_sequence.fastq'))
c += 1
| 55.595506 | 119 | 0.818108 |
import os
from os import listdir
from os.path import isfile, join
from constants import AT_COMBO_RAW_DIR, AT_COMBO_MERGED_DIR, FLASH_PATH
fastqPath = AT_COMBO_RAW_DIR
outputDir = AT_COMBO_MERGED_DIR
n_to_do = 1000
c = 0
with open(outputDir + 'cmdsUsed.txt', 'w') as fout:
done_nums = [f.rstrip('-_merged.fastq')[-3:] for f in listdir(outputDir)
if isfile(join(outputDir, f))]
print('doing filepahts:{}{}'.format(fastqPath, outputDir))
print('file numbers already done:', done_nums)
fastq = [f.rstrip('_sequence.fastq')[:-1]
for f in listdir(fastqPath) if isfile(join(fastqPath, f))]
print('fastq files to do ', sorted(fastq))
for fa in fastq:
if c < n_to_do:
flash_cmd = '{} {}{}1_sequence.fastq {}{' \
'}2_sequence.fastq -o {} -d {}'.format(FLASH_PATH,
fastqPath, fa, fastqPath, fa, fa, outputDir)
print(flash_cmd)
os.system(flash_cmd)
c += 1
| true | true |
f72f34ca09732af9330ae8c7aad9a5737ef4a76b | 3,985 | py | Python | server/rake.py | arpit73/ad-recommendation | 6409e437215f192bbce3235d070b642705ef75cd | [
"Apache-2.0"
] | 1 | 2021-12-27T08:45:35.000Z | 2021-12-27T08:45:35.000Z | server/rake.py | arpit73/ad-recommendation | 6409e437215f192bbce3235d070b642705ef75cd | [
"Apache-2.0"
] | 2 | 2021-03-10T14:26:51.000Z | 2021-05-11T10:20:20.000Z | server/rake.py | onygami/ad-recommendation | 6409e437215f192bbce3235d070b642705ef75cd | [
"Apache-2.0"
] | null | null | null | import re
def is_number(s):
try:
float(s) if "." in s else int(s)
return True
except ValueError:
return False
def load_stop_words(stop_word_file, regex):
with open(stop_word_file, "r") as stop_word_file:
stop_words = re.split(regex, stop_word_file.read())
return [
word for word in stop_words if word not in ("", " ")
] # filters empty string matches
def separate_words(text):
splitter = re.compile("(?u)\W+")
words = []
for single_word in splitter.split(text):
current_word = single_word.strip().lower()
# leave numbers in phrase, but don't count as words, since they tend to invalidate scores of their phrases
if current_word != "" and not is_number(current_word):
words.append(current_word)
return words
def split_sentences(text):
sentence_delimiters = re.compile(
u"[.!?,-;:\t\\\\\"\\(\\)\\'\u2019\u2013]|\\s\\-\\s"
)
sentences = sentence_delimiters.split(text)
return sentences
def build_stop_word_regex(stop_word_list):
stop_word_regex_list = []
for word in stop_word_list:
word_regex = r"\b" + word + r"(?![\w-])"
stop_word_regex_list.append(word_regex)
return re.compile("(?u)" + "|".join(stop_word_regex_list), re.IGNORECASE)
def generate_candidate_keywords(
sentence_list, stop_word_pattern, minCharacters, maxWords
):
phrase_list = []
for s in sentence_list:
tmp = re.sub(stop_word_pattern, "|", s.strip())
phrases = tmp.split("|")
for phrase in phrases:
phrase = phrase.strip().lower()
if (
phrase != ""
and len(phrase) >= minCharacters
and len(phrase.split()) <= maxWords
):
phrase_list.append(phrase)
return phrase_list
def calculate_word_scores(phraseList):
word_frequency = {}
word_degree = {}
for phrase in phraseList:
word_list = separate_words(phrase)
word_list_length = len(word_list)
word_list_degree = word_list_length - 1
for word in word_list:
word_frequency.setdefault(word, 0)
word_frequency[word] += 1
word_degree.setdefault(word, 0)
word_degree[word] += word_list_degree
for item in word_frequency:
word_degree[item] = word_degree[item] + word_frequency[item]
# Calculate Word scores = degree(w)/frequency(w)
word_score = {}
for item in word_frequency:
word_score.setdefault(item, 0)
word_score[item] = word_degree[item] / (word_frequency[item] * 1.0)
return word_score
def generate_candidate_keyword_scores(phrase_list, word_score, minFrequency):
keyword_candidates = {}
for phrase in phrase_list:
if phrase_list.count(phrase) >= minFrequency:
keyword_candidates.setdefault(phrase, 0)
word_list = separate_words(phrase)
candidate_score = 0
for word in word_list:
candidate_score += word_score[word]
keyword_candidates[phrase] = candidate_score
return keyword_candidates
class Rake:
def __init__(self, stop_words, regex="[\W\n]+"):
self.__stop_words_pattern = build_stop_word_regex(
load_stop_words(stop_words, regex)
)
def run(self, text, minCharacters=1, maxWords=5, minFrequency=1):
sentence_list = split_sentences(text)
phrase_list = generate_candidate_keywords(
sentence_list, self.__stop_words_pattern, minCharacters, maxWords
)
word_scores = calculate_word_scores(phrase_list)
keyword_candidates = generate_candidate_keyword_scores(
phrase_list, word_scores, minFrequency
)
# Sort according to word score, higher comes first
sorted_keywords = sorted(
keyword_candidates.items(), key=lambda x: x[1], reverse=True
)
return sorted_keywords
| 31.88 | 114 | 0.636637 | import re
def is_number(s):
try:
float(s) if "." in s else int(s)
return True
except ValueError:
return False
def load_stop_words(stop_word_file, regex):
with open(stop_word_file, "r") as stop_word_file:
stop_words = re.split(regex, stop_word_file.read())
return [
word for word in stop_words if word not in ("", " ")
]
def separate_words(text):
splitter = re.compile("(?u)\W+")
words = []
for single_word in splitter.split(text):
current_word = single_word.strip().lower()
if current_word != "" and not is_number(current_word):
words.append(current_word)
return words
def split_sentences(text):
sentence_delimiters = re.compile(
u"[.!?,-;:\t\\\\\"\\(\\)\\'\u2019\u2013]|\\s\\-\\s"
)
sentences = sentence_delimiters.split(text)
return sentences
def build_stop_word_regex(stop_word_list):
stop_word_regex_list = []
for word in stop_word_list:
word_regex = r"\b" + word + r"(?![\w-])"
stop_word_regex_list.append(word_regex)
return re.compile("(?u)" + "|".join(stop_word_regex_list), re.IGNORECASE)
def generate_candidate_keywords(
sentence_list, stop_word_pattern, minCharacters, maxWords
):
phrase_list = []
for s in sentence_list:
tmp = re.sub(stop_word_pattern, "|", s.strip())
phrases = tmp.split("|")
for phrase in phrases:
phrase = phrase.strip().lower()
if (
phrase != ""
and len(phrase) >= minCharacters
and len(phrase.split()) <= maxWords
):
phrase_list.append(phrase)
return phrase_list
def calculate_word_scores(phraseList):
word_frequency = {}
word_degree = {}
for phrase in phraseList:
word_list = separate_words(phrase)
word_list_length = len(word_list)
word_list_degree = word_list_length - 1
for word in word_list:
word_frequency.setdefault(word, 0)
word_frequency[word] += 1
word_degree.setdefault(word, 0)
word_degree[word] += word_list_degree
for item in word_frequency:
word_degree[item] = word_degree[item] + word_frequency[item]
# Calculate Word scores = degree(w)/frequency(w)
word_score = {}
for item in word_frequency:
word_score.setdefault(item, 0)
word_score[item] = word_degree[item] / (word_frequency[item] * 1.0)
return word_score
def generate_candidate_keyword_scores(phrase_list, word_score, minFrequency):
keyword_candidates = {}
for phrase in phrase_list:
if phrase_list.count(phrase) >= minFrequency:
keyword_candidates.setdefault(phrase, 0)
word_list = separate_words(phrase)
candidate_score = 0
for word in word_list:
candidate_score += word_score[word]
keyword_candidates[phrase] = candidate_score
return keyword_candidates
class Rake:
def __init__(self, stop_words, regex="[\W\n]+"):
self.__stop_words_pattern = build_stop_word_regex(
load_stop_words(stop_words, regex)
)
def run(self, text, minCharacters=1, maxWords=5, minFrequency=1):
sentence_list = split_sentences(text)
phrase_list = generate_candidate_keywords(
sentence_list, self.__stop_words_pattern, minCharacters, maxWords
)
word_scores = calculate_word_scores(phrase_list)
keyword_candidates = generate_candidate_keyword_scores(
phrase_list, word_scores, minFrequency
)
# Sort according to word score, higher comes first
sorted_keywords = sorted(
keyword_candidates.items(), key=lambda x: x[1], reverse=True
)
return sorted_keywords
| true | true |
f72f354e1adca42e4471f5b1917ec8f37ef9888a | 13,156 | py | Python | src/game.py | mapto/4oBe4e | e3b11ad4ac5c5f4f7462b2066ca3a3851b07230f | [
"MIT"
] | 2 | 2020-04-02T19:44:12.000Z | 2020-04-08T19:18:17.000Z | src/game.py | mapto/4oBe4e | e3b11ad4ac5c5f4f7462b2066ca3a3851b07230f | [
"MIT"
] | 5 | 2020-04-26T15:36:52.000Z | 2020-05-14T19:21:29.000Z | src/game.py | mapto/4oBe4e | e3b11ad4ac5c5f4f7462b2066ca3a3851b07230f | [
"MIT"
] | 2 | 2020-04-07T18:03:25.000Z | 2020-04-21T09:05:34.000Z | #!/usr/bin/env python3
# coding: utf-8
"""The game logic.
This should be independent of media used to interact with player."""
from typing import Tuple, List, Set, Dict
from const import PLAYER_SHIFT, LAST_ON_PATH, END_PROGRESS
from piece import Piece
from player import Player
from util import progress_to_position
from action import roll_dice
def set_board(num_players: int, num_pieces: int):
pieces: List[Piece] = []
for player_num in range(num_players):
for piece_num in range(num_pieces):
pieces.append(Piece(player_num, piece_num))
return pieces
def do_move(
status: List[Piece],
player: Player,
piece_to_move: int,
dice: int,
player_shift: int = PLAYER_SHIFT,
last_on_path: int = LAST_ON_PATH,
) -> bool:
"""Check if the move is valid. If it is, perform it. Returns whether it is valid."""
movable_piece_nums = [p.index() for p in get_valid_moves(player, dice, status)]
if not (piece_to_move in movable_piece_nums):
return False
current = [
p for p in status if p.player() == player.number and p.index() == piece_to_move
]
assert len(current) == 1
piece = current[0]
if piece.progress() == 0:
if dice == 6:
piece.move(1)
else:
raise ValueError("Home can only be left with a full dice")
else:
piece.move(dice)
if 0 < piece.progress() <= last_on_path:
others = others_on_position(
status, player.number, piece.position(), player_shift, last_on_path
)
for other in others:
other.send_home()
return True
def choose_first(players: Set[Player]) -> Player:
""" score 0 means player hasn't drawn, -1 means is already out of drawing
"""
m = 0
score = [0] * len(players)
need_more = True
while need_more:
for i in range(len(score)):
if score[i] != -1:
# TODO: Decouple this logic from console interaction
score[i] = roll_dice(player_num=i)
m = max(score)
if len([v for v in score if v == m]) > 1:
for i in range(len(score)):
score[i] = 0 if score[i] == m else -1
else:
need_more = False
return Player.get(score.index(m))
def check_endgame(status: List[Piece]) -> bool:
"""Check if any of the players has ended the game.
>>> check_endgame([Piece(0, 0),Piece(0, 1),Piece(0, 2),Piece(0, 3),\
Piece(1, 0),Piece(1, 1),Piece(1, 2),Piece(1, 3),\
Piece(2, 0),Piece(2, 1),Piece(2, 2),Piece(2, 3),\
Piece(3, 0),Piece(3, 1),Piece(3, 2),Piece(3, 3)])
False
>>> check_endgame([Piece(0, 0),Piece(0, 1),Piece(0, 2),Piece(0, 3),\
Piece(1, 0),Piece(1, 1),Piece(1, 2),Piece(1, 3),\
Piece(2, 0),Piece(2, 1),Piece(2, 2),Piece(2, 3),\
Piece(3, 0, 62),Piece(3, 1, 62),Piece(3, 2, 62),Piece(3, 3, 62)])
True
>>> check_endgame([Piece(0, 0),Piece(0, 1),Piece(0, 2),Piece(0, 3),\
Piece(1, 0, 62),Piece(1, 1, 62),Piece(1, 2, 62),Piece(1, 3, 61),\
Piece(2, 0, 60),Piece(2, 1, 60),Piece(2, 2, 60),Piece(2, 3, 60),\
Piece(3, 0, 10),Piece(3, 1, 20),Piece(3, 2, 30),Piece(3, 3, 40)])
False
A real game we played that had a bug:
>>> check_endgame([Piece(0,0,62),Piece(0,1,57),Piece(0,2,62),Piece(0,3,21),\
Piece(1,0,28),Piece(1,1,62),Piece(1,2,62),Piece(1,3,62),\
Piece(2,0,62),Piece(2,1,20),Piece(2,2,58),Piece(2,3,62),\
Piece(3,0,62),Piece(3,1,62),Piece(3,2,0),Piece(3,3,62)])
False
"""
player_finished: Dict[int, bool] = {}
for piece in status:
player = piece.player()
preexisting = player_finished[player] if player in player_finished else True
player_finished[player] = preexisting and piece.is_finished()
return len([k for k, v in player_finished.items() if v]) > 0
def __coord_in_home(piece: Piece) -> Tuple[int, int]:
"""Draw in home positions: each piece has its location. Progress is always same, thus irrelevant
>>> __coord_in_home(Piece(0, 0))
(5, 2)
>>> __coord_in_home(Piece(1, 1))
(2, 13)
>>> __coord_in_home(Piece(2, 2))
(13, 15)
>>> __coord_in_home(Piece(3, 3))
(16, 6)
"""
assert piece.progress() == 0
zones = [(5, 2), (2, 12), (12, 15), (15, 5)]
shift = [(0, 0), (0, 1), (1, 0), (1, 1)]
return (
zones[piece.player()][0] + shift[piece.index()][0],
zones[piece.player()][1] + shift[piece.index()][1],
)
def __coord_on_path(piece: Piece) -> Tuple[int, int]:
"""Draws on path: if two or more pieces on same cell, instead of number,
draws a placeholder, which does not need to show piece number
Logic split this in 4 different cases, determined by player offset.
Parameter piece does't influence logic.
Player Progress to Position conversion:
P0 1..56: (pos)
P1 1..42: (p_num * shift + pos)
43..56: (p_num * shift + pos) % end_progress
P2 1..28: (p_num * shift + pos)
29..56: (p_num * shift + pos) % end_progress
P3 1..14: (p_num * shift + pos)
15..56: (p_num * shift + pos) % end_progress
Test player 1:
>>> __coord_on_path(Piece(0, 1, 1))
(8, 2)
Test player 2:
>>> __coord_on_path(Piece(1, 1, 1))
(2, 10)
Test player 3:
>>> __coord_on_path(Piece(2, 1, 1))
(10, 16)
Test player 4:
>>> __coord_on_path(Piece(3, 1, 1))
(16, 8)
Test path wrap:
>>> __coord_on_path(Piece(3, 1, 56))
(16, 9)
Test overlap:
>> __coord_on_path(Piece(2, 1, 17))
(10, 14)
"""
assert 1 <= piece.progress() <= LAST_ON_PATH and 0 <= piece.player() <= 3
POSITION_TO_ROWCOL: Tuple[Tuple[int, int], ...] = (
(0, 0),
(8, 2),
(8, 3),
(8, 4),
(8, 5),
(7, 5),
(6, 5),
(5, 5),
(5, 6),
(5, 7),
(5, 8),
(4, 8),
(3, 8),
(2, 8),
(2, 9),
(2, 10),
(3, 10),
(4, 10),
(5, 10),
(5, 11),
(5, 12),
(5, 13),
(6, 13),
(7, 13),
(8, 13),
(8, 14),
(8, 15),
(8, 16),
(9, 16),
(10, 16),
(10, 15),
(10, 14),
(10, 13),
(11, 13),
(12, 13),
(13, 13),
(13, 12),
(13, 11),
(13, 10),
(14, 10),
(15, 10),
(16, 10),
(16, 9),
(16, 8),
(15, 8),
(14, 8),
(13, 8),
(13, 7),
(13, 6),
(13, 5),
(12, 5),
(11, 5),
(10, 5),
(10, 4),
(10, 3),
(10, 2),
(9, 2),
)
return POSITION_TO_ROWCOL[piece.position()]
def __coord_on_finish(piece: Piece) -> Tuple[int, int]:
"""Piece number is irrelevant
>>> __coord_on_finish(Piece(0, 1, 57))
(9, 3)
>>> __coord_on_finish(Piece(0, 1, 61))
(9, 7)
>>> __coord_on_finish(Piece(1, 1, 57))
(3, 9)
>>> __coord_on_finish(Piece(2, 1, 58))
(9, 14)
>>> __coord_on_finish(Piece(3, 1, 59))
(13, 9)
>>> __coord_on_finish(Piece(3, 1, 61))
(11, 9)
"""
pos = piece.progress() - LAST_ON_PATH
assert 0 < pos < 6
player = piece.player()
(x, y) = (0, 0)
if player in [0, 2]:
x = 9
y = pos + 2 if player == 0 else 15 - (pos - 1)
elif player in [1, 3]:
x = pos + 2 if player == 1 else 15 - (pos - 1)
y = 9
else:
raise NotImplementedError()
return (x, y)
def __coord_in_target(piece: Piece) -> Tuple[int, int]:
"""Draw in target positions: each piece has its location.
Progress is always same, thus irrelevant
>>> __coord_in_target(Piece(0, 0, 62))
(7, 6)
>>> __coord_in_target(Piece(1, 1, 62))
(6, 11)
>>> __coord_in_target(Piece(2, 2, 62))
(11, 11)
>>> __coord_in_target(Piece(3, 3, 62))
(12, 8)
"""
assert piece.progress() == 62
zones = [(7, 6), (6, 10), (10, 11), (11, 7)]
shift = [(0, 0), (0, 1), (1, 0), (1, 1)]
return (
zones[piece.player()][0] + shift[piece.index()][0],
zones[piece.player()][1] + shift[piece.index()][1],
)
def put_piece_on_board(piece: Piece) -> Tuple[int, int]:
"""Currently player is in [1..4], piece is in [0..3]. Do we need to change this?
TODO: Refactor to implement startegy pattern
"""
coords = (0, 0)
progress = piece.progress()
if progress == 0:
coords = __coord_in_home(piece)
elif 0 < progress <= LAST_ON_PATH:
coords = __coord_on_path(piece)
elif LAST_ON_PATH < progress < END_PROGRESS:
coords = __coord_on_finish(piece)
elif progress == END_PROGRESS:
coords = __coord_in_target(piece)
else:
raise NotImplementedError()
return coords
def is_valid_move(
piece: Piece,
dice: int,
status: List[Piece],
player_shift: int = PLAYER_SHIFT,
last_on_path: int = LAST_ON_PATH,
end_progress: int = END_PROGRESS,
) -> bool:
"""
>>> p = Piece(1, 1); is_valid_move(p, 6, [p])
True
>>> p = Piece(1, 1); is_valid_move(p, 1, [p])
False
>>> p = Piece(1, 1, 1); is_valid_move(p, 1, [p])
True
>>> p = Piece(1, 1, 1); is_valid_move(p, 6, [p])
True
>> p = Piece(1, 1); is_valid_move(p, 6, [p, Piece(0, 0, 15)])
True
>>> p = Piece(1, 1); is_valid_move(p, 6, [p, Piece(0, 0, 15), Piece(0, 1, 15)])
False
>>> piece = Piece(0, 0, 58); is_valid_move(piece, 6, [piece])
False
>>> piece = Piece(1, 0, 0); is_valid_move(piece, 5, [piece])
False
>>> piece = Piece(2, 0, 28); is_valid_move(piece, 1, [piece, Piece(0, 0, 1), Piece(0, 1, 1)])
False
>>> p = Piece(0,0,0); is_valid_move(p, 6, [p, Piece(0,1,0), Piece(1,0,29), Piece(1,1,29)],28,56)
False
>>> p = Piece(0,1,0); is_valid_move(p, 6, [Piece(0,0,0), p, Piece(1,0,29), Piece(1,1,29)],28,56)
False
"""
if dice < 1 or dice > 6:
raise ValueError("Invalid dice: {}".format(dice))
# can exit from home?
pos = piece.progress()
if pos == 0:
if dice != 6:
return False
# Do other players block exit from home
expected = progress_to_position(piece.player(), 1, player_shift, last_on_path)
return 2 > len(
others_on_position(
status, piece.player(), expected, player_shift, last_on_path
)
)
if 0 < pos <= last_on_path:
if pos + dice > last_on_path:
return True
expected = progress_to_position(
piece.player(), pos + dice, player_shift, last_on_path
)
return 2 > len(
others_on_position(
status, piece.player(), expected, player_shift, last_on_path
)
)
if last_on_path < pos < end_progress:
return pos + dice <= end_progress
assert pos == end_progress
return False
def get_valid_moves(player: Player, dice: int, status: List[Piece]) -> List[Piece]:
"""
>>> p = Player.create(); p2 = Player.create(); p = Player.get(0)
>>> get_valid_moves(p, 6, [Piece(0, 0), Piece(0, 1), Piece(1, 0), Piece(1, 1)])
[0, 1]
>>> get_valid_moves(p, 1, [Piece(0, 0), Piece(0, 1), Piece(0, 2), Piece(1, 0)])
[]
>>> get_valid_moves(p, 1, [Piece(0, 0, 1), Piece(0, 1), Piece(0, 2), Piece(1, 0)])
[0]
>>> get_valid_moves(p, 1, [Piece(0, 0, 1), Piece(0, 1, 57), Piece(0, 2), Piece(1, 0)])
[0, 1]
>>> get_valid_moves(p, 6, [Piece(0, 0, 1), Piece(0, 1, 60), Piece(0, 2), Piece(0, 3, 0)])
[0, 2, 3]
"""
own = [p for p in status if p.player() == player.number]
return [p for p in own if is_valid_move(p, dice, status)]
def __pieces_on_path_position(
pieces: List[Piece],
path_pos: int,
player_shift: int = PLAYER_SHIFT,
last_on_path: int = LAST_ON_PATH,
) -> List[Piece]:
"""
>>> __pieces_on_path_position([Piece(1, 0, 1)], 15)
[0]
>>> __pieces_on_path_position([Piece(2, 0, 1)], 29)
[0]
>>> __pieces_on_path_position([Piece(0, 0, 15), Piece(0, 1, 15)], 15)
[0, 1]
"""
return [p for p in pieces if path_pos == p.position(player_shift, last_on_path)]
def __other_player_pieces(pieces: List[Piece], player_num: int) -> List[Piece]:
return [p for p in pieces if p.player() != player_num]
def others_on_position(
pieces: List[Piece],
player: int,
pos: int,
player_shift: int = PLAYER_SHIFT,
last_on_path: int = LAST_ON_PATH,
) -> List[Piece]:
"""Do other players block the position by having more than one piece on it.
Position argument is board position, not piece progress.
>>> others_on_position([Piece(1,0,29)], 0, 1, 28, 56)
[0]
>>> others_on_position([Piece(1,0,29), Piece(1,1,29)], 0, 1, 28, 56)
[0, 1]
"""
assert 0 < pos <= last_on_path
at_dest = __pieces_on_path_position(pieces, pos, player_shift, last_on_path)
others = __other_player_pieces(at_dest, player)
return others
| 27.408333 | 100 | 0.54363 |
from typing import Tuple, List, Set, Dict
from const import PLAYER_SHIFT, LAST_ON_PATH, END_PROGRESS
from piece import Piece
from player import Player
from util import progress_to_position
from action import roll_dice
def set_board(num_players: int, num_pieces: int):
pieces: List[Piece] = []
for player_num in range(num_players):
for piece_num in range(num_pieces):
pieces.append(Piece(player_num, piece_num))
return pieces
def do_move(
status: List[Piece],
player: Player,
piece_to_move: int,
dice: int,
player_shift: int = PLAYER_SHIFT,
last_on_path: int = LAST_ON_PATH,
) -> bool:
movable_piece_nums = [p.index() for p in get_valid_moves(player, dice, status)]
if not (piece_to_move in movable_piece_nums):
return False
current = [
p for p in status if p.player() == player.number and p.index() == piece_to_move
]
assert len(current) == 1
piece = current[0]
if piece.progress() == 0:
if dice == 6:
piece.move(1)
else:
raise ValueError("Home can only be left with a full dice")
else:
piece.move(dice)
if 0 < piece.progress() <= last_on_path:
others = others_on_position(
status, player.number, piece.position(), player_shift, last_on_path
)
for other in others:
other.send_home()
return True
def choose_first(players: Set[Player]) -> Player:
m = 0
score = [0] * len(players)
need_more = True
while need_more:
for i in range(len(score)):
if score[i] != -1:
score[i] = roll_dice(player_num=i)
m = max(score)
if len([v for v in score if v == m]) > 1:
for i in range(len(score)):
score[i] = 0 if score[i] == m else -1
else:
need_more = False
return Player.get(score.index(m))
def check_endgame(status: List[Piece]) -> bool:
player_finished: Dict[int, bool] = {}
for piece in status:
player = piece.player()
preexisting = player_finished[player] if player in player_finished else True
player_finished[player] = preexisting and piece.is_finished()
return len([k for k, v in player_finished.items() if v]) > 0
def __coord_in_home(piece: Piece) -> Tuple[int, int]:
assert piece.progress() == 0
zones = [(5, 2), (2, 12), (12, 15), (15, 5)]
shift = [(0, 0), (0, 1), (1, 0), (1, 1)]
return (
zones[piece.player()][0] + shift[piece.index()][0],
zones[piece.player()][1] + shift[piece.index()][1],
)
def __coord_on_path(piece: Piece) -> Tuple[int, int]:
assert 1 <= piece.progress() <= LAST_ON_PATH and 0 <= piece.player() <= 3
POSITION_TO_ROWCOL: Tuple[Tuple[int, int], ...] = (
(0, 0),
(8, 2),
(8, 3),
(8, 4),
(8, 5),
(7, 5),
(6, 5),
(5, 5),
(5, 6),
(5, 7),
(5, 8),
(4, 8),
(3, 8),
(2, 8),
(2, 9),
(2, 10),
(3, 10),
(4, 10),
(5, 10),
(5, 11),
(5, 12),
(5, 13),
(6, 13),
(7, 13),
(8, 13),
(8, 14),
(8, 15),
(8, 16),
(9, 16),
(10, 16),
(10, 15),
(10, 14),
(10, 13),
(11, 13),
(12, 13),
(13, 13),
(13, 12),
(13, 11),
(13, 10),
(14, 10),
(15, 10),
(16, 10),
(16, 9),
(16, 8),
(15, 8),
(14, 8),
(13, 8),
(13, 7),
(13, 6),
(13, 5),
(12, 5),
(11, 5),
(10, 5),
(10, 4),
(10, 3),
(10, 2),
(9, 2),
)
return POSITION_TO_ROWCOL[piece.position()]
def __coord_on_finish(piece: Piece) -> Tuple[int, int]:
pos = piece.progress() - LAST_ON_PATH
assert 0 < pos < 6
player = piece.player()
(x, y) = (0, 0)
if player in [0, 2]:
x = 9
y = pos + 2 if player == 0 else 15 - (pos - 1)
elif player in [1, 3]:
x = pos + 2 if player == 1 else 15 - (pos - 1)
y = 9
else:
raise NotImplementedError()
return (x, y)
def __coord_in_target(piece: Piece) -> Tuple[int, int]:
assert piece.progress() == 62
zones = [(7, 6), (6, 10), (10, 11), (11, 7)]
shift = [(0, 0), (0, 1), (1, 0), (1, 1)]
return (
zones[piece.player()][0] + shift[piece.index()][0],
zones[piece.player()][1] + shift[piece.index()][1],
)
def put_piece_on_board(piece: Piece) -> Tuple[int, int]:
coords = (0, 0)
progress = piece.progress()
if progress == 0:
coords = __coord_in_home(piece)
elif 0 < progress <= LAST_ON_PATH:
coords = __coord_on_path(piece)
elif LAST_ON_PATH < progress < END_PROGRESS:
coords = __coord_on_finish(piece)
elif progress == END_PROGRESS:
coords = __coord_in_target(piece)
else:
raise NotImplementedError()
return coords
def is_valid_move(
piece: Piece,
dice: int,
status: List[Piece],
player_shift: int = PLAYER_SHIFT,
last_on_path: int = LAST_ON_PATH,
end_progress: int = END_PROGRESS,
) -> bool:
if dice < 1 or dice > 6:
raise ValueError("Invalid dice: {}".format(dice))
pos = piece.progress()
if pos == 0:
if dice != 6:
return False
expected = progress_to_position(piece.player(), 1, player_shift, last_on_path)
return 2 > len(
others_on_position(
status, piece.player(), expected, player_shift, last_on_path
)
)
if 0 < pos <= last_on_path:
if pos + dice > last_on_path:
return True
expected = progress_to_position(
piece.player(), pos + dice, player_shift, last_on_path
)
return 2 > len(
others_on_position(
status, piece.player(), expected, player_shift, last_on_path
)
)
if last_on_path < pos < end_progress:
return pos + dice <= end_progress
assert pos == end_progress
return False
def get_valid_moves(player: Player, dice: int, status: List[Piece]) -> List[Piece]:
own = [p for p in status if p.player() == player.number]
return [p for p in own if is_valid_move(p, dice, status)]
def __pieces_on_path_position(
pieces: List[Piece],
path_pos: int,
player_shift: int = PLAYER_SHIFT,
last_on_path: int = LAST_ON_PATH,
) -> List[Piece]:
return [p for p in pieces if path_pos == p.position(player_shift, last_on_path)]
def __other_player_pieces(pieces: List[Piece], player_num: int) -> List[Piece]:
return [p for p in pieces if p.player() != player_num]
def others_on_position(
pieces: List[Piece],
player: int,
pos: int,
player_shift: int = PLAYER_SHIFT,
last_on_path: int = LAST_ON_PATH,
) -> List[Piece]:
assert 0 < pos <= last_on_path
at_dest = __pieces_on_path_position(pieces, pos, player_shift, last_on_path)
others = __other_player_pieces(at_dest, player)
return others
| true | true |
f72f3647e3f3d20d8cbdf1ce0a5a0bce8e752cca | 3,615 | py | Python | VisCostCallback.py | halalyon/mxnet_workshop | 0cf83051e639893c8b4a04b90d91d93bf55f0f5b | [
"Apache-2.0"
] | null | null | null | VisCostCallback.py | halalyon/mxnet_workshop | 0cf83051e639893c8b4a04b90d91d93bf55f0f5b | [
"Apache-2.0"
] | null | null | null | VisCostCallback.py | halalyon/mxnet_workshop | 0cf83051e639893c8b4a04b90d91d93bf55f0f5b | [
"Apache-2.0"
] | null | null | null | from bokeh.plotting import output_notebook, figure, ColumnDataSource, show
from bokeh.io import push_notebook
from timeit import default_timer
import math
from collections import deque
class CostVisCallback(object):
"""
Callback providing a live updating console based progress bar.
"""
def __init__(self, epoch_freq=1, y_range=(0, 4.5), fig=None, handle=None,
update_thresh_s=0.65, w=400, h=300, nepochs=1.0, total_batches=10.0,
train_source=None, val_source=None, history=10):
self.update_thresh_s = update_thresh_s
self.w = w
self.h = h
self.nepochs = nepochs
self.total = total_batches
self.last_update = 0
self.epoch = -1
self.history = history
self.cost_history = deque(maxlen=history)
if handle is None:
output_notebook()
self.handle = None
else:
self.handle = handle
if fig is None:
self.fig = figure(name="cost", y_axis_label="Cost", x_range=(0, self.nepochs), y_range=y_range,
x_axis_label="Epoch", plot_width=self.w, plot_height=self.h)
else:
self.fig = fig
if train_source is None:
self.train_source = ColumnDataSource(data=dict(x=[], y=[]))
else:
self.train_source = train_source
self.train_source.data = dict(x=[], y=[])
self.train_cost = self.fig.line('x', 'y', source=self.train_source)
if val_source is None:
self.val_source = ColumnDataSource(data=dict(x=[], y=[]))
else:
self.val_source = val_source
self.val_source.data = dict(x=[], y=[])
self.val_cost = self.fig.line('x', 'y', source=self.val_source, color='red')
def get_average_cost(self, cost):
self.cost_history.append(cost)
return sum(list(self.cost_history))/ float(len(self.cost_history))
def train_callback(self, param):
self._process_batch(param, 'train')
def eval_callback(self, param):
self._process_batch(param, 'eval')
def _process_batch(self, param, name):
if self.handle is None:
self.handle = show(self.fig, notebook_handle=True)
now = default_timer()
# print "{}_{}".format(param.nbatch, param.epoch)
if param.nbatch == 0:
self.epoch = self.epoch + 1
time = float(param.nbatch) / self.total + param.epoch
if param.eval_metric is not None:
name_value = param.eval_metric.get_name_value()
param.eval_metric.reset()
cost = name_value[0][1]
if name == 'train':
cost = self.get_average_cost(cost)
if math.isnan(cost) or cost > 4000:
cost = 4000
if name == 'train':
self.train_source.data['x'].append(time)
self.train_source.data['y'].append(cost)
elif name == 'eval':
self.val_source.data['x'].append(param.epoch+1)
self.val_source.data['y'].append(cost)
if (now - self.last_update > self.update_thresh_s):
self.last_update = now
if self.handle is not None:
push_notebook(handle=self.handle)
else:
push_notebook()
def get_callbacks(self):
return {'train_cost': self.train_callback,
'eval_cost': self.eval_callback}
| 33.785047 | 107 | 0.562656 | from bokeh.plotting import output_notebook, figure, ColumnDataSource, show
from bokeh.io import push_notebook
from timeit import default_timer
import math
from collections import deque
class CostVisCallback(object):
def __init__(self, epoch_freq=1, y_range=(0, 4.5), fig=None, handle=None,
update_thresh_s=0.65, w=400, h=300, nepochs=1.0, total_batches=10.0,
train_source=None, val_source=None, history=10):
self.update_thresh_s = update_thresh_s
self.w = w
self.h = h
self.nepochs = nepochs
self.total = total_batches
self.last_update = 0
self.epoch = -1
self.history = history
self.cost_history = deque(maxlen=history)
if handle is None:
output_notebook()
self.handle = None
else:
self.handle = handle
if fig is None:
self.fig = figure(name="cost", y_axis_label="Cost", x_range=(0, self.nepochs), y_range=y_range,
x_axis_label="Epoch", plot_width=self.w, plot_height=self.h)
else:
self.fig = fig
if train_source is None:
self.train_source = ColumnDataSource(data=dict(x=[], y=[]))
else:
self.train_source = train_source
self.train_source.data = dict(x=[], y=[])
self.train_cost = self.fig.line('x', 'y', source=self.train_source)
if val_source is None:
self.val_source = ColumnDataSource(data=dict(x=[], y=[]))
else:
self.val_source = val_source
self.val_source.data = dict(x=[], y=[])
self.val_cost = self.fig.line('x', 'y', source=self.val_source, color='red')
def get_average_cost(self, cost):
self.cost_history.append(cost)
return sum(list(self.cost_history))/ float(len(self.cost_history))
def train_callback(self, param):
self._process_batch(param, 'train')
def eval_callback(self, param):
self._process_batch(param, 'eval')
def _process_batch(self, param, name):
if self.handle is None:
self.handle = show(self.fig, notebook_handle=True)
now = default_timer()
if param.nbatch == 0:
self.epoch = self.epoch + 1
time = float(param.nbatch) / self.total + param.epoch
if param.eval_metric is not None:
name_value = param.eval_metric.get_name_value()
param.eval_metric.reset()
cost = name_value[0][1]
if name == 'train':
cost = self.get_average_cost(cost)
if math.isnan(cost) or cost > 4000:
cost = 4000
if name == 'train':
self.train_source.data['x'].append(time)
self.train_source.data['y'].append(cost)
elif name == 'eval':
self.val_source.data['x'].append(param.epoch+1)
self.val_source.data['y'].append(cost)
if (now - self.last_update > self.update_thresh_s):
self.last_update = now
if self.handle is not None:
push_notebook(handle=self.handle)
else:
push_notebook()
def get_callbacks(self):
return {'train_cost': self.train_callback,
'eval_cost': self.eval_callback}
| true | true |
f72f36daaa65d5a7d57ac806a3e885a93cc7e16f | 2,218 | py | Python | nipype/interfaces/mrtrix3/tests/test_auto_DWIBiasCorrect.py | vferat/nipype | 536c57da150d157dcb5c121af43aaeab71cdbd5f | [
"Apache-2.0"
] | null | null | null | nipype/interfaces/mrtrix3/tests/test_auto_DWIBiasCorrect.py | vferat/nipype | 536c57da150d157dcb5c121af43aaeab71cdbd5f | [
"Apache-2.0"
] | 2 | 2018-04-17T19:18:16.000Z | 2020-03-04T22:05:02.000Z | nipype/interfaces/mrtrix3/tests/test_auto_DWIBiasCorrect.py | oesteban/nipype | c14f24eba1da08711bbb894e049ee858ed740096 | [
"Apache-2.0"
] | null | null | null | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..preprocess import DWIBiasCorrect
def test_DWIBiasCorrect_inputs():
input_map = dict(
args=dict(argstr='%s', ),
bias=dict(
argstr='-bias %s',
extensions=None,
),
bval_scale=dict(argstr='-bvalue_scaling %s', ),
environ=dict(
nohash=True,
usedefault=True,
),
grad_file=dict(
argstr='-grad %s',
extensions=None,
xor=['grad_fsl'],
),
grad_fsl=dict(
argstr='-fslgrad %s %s',
xor=['grad_file'],
),
in_bval=dict(extensions=None, ),
in_bvec=dict(
argstr='-fslgrad %s %s',
extensions=None,
),
in_file=dict(
argstr='%s',
extensions=None,
mandatory=True,
position=-2,
),
in_mask=dict(
argstr='-mask %s',
extensions=None,
),
nthreads=dict(
argstr='-nthreads %d',
nohash=True,
),
out_file=dict(
argstr='%s',
extensions=None,
genfile=True,
keep_extension=True,
name_source='in_file',
name_template='%s_biascorr',
position=-1,
),
use_ants=dict(
argstr='-ants',
mandatory=True,
xor=['use_fsl'],
),
use_fsl=dict(
argstr='-fsl',
mandatory=True,
xor=['use_ants'],
),
)
inputs = DWIBiasCorrect.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_DWIBiasCorrect_outputs():
output_map = dict(
bias=dict(extensions=None, ),
out_file=dict(extensions=None, ),
)
outputs = DWIBiasCorrect.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
| 27.382716 | 67 | 0.506763 |
from __future__ import unicode_literals
from ..preprocess import DWIBiasCorrect
def test_DWIBiasCorrect_inputs():
input_map = dict(
args=dict(argstr='%s', ),
bias=dict(
argstr='-bias %s',
extensions=None,
),
bval_scale=dict(argstr='-bvalue_scaling %s', ),
environ=dict(
nohash=True,
usedefault=True,
),
grad_file=dict(
argstr='-grad %s',
extensions=None,
xor=['grad_fsl'],
),
grad_fsl=dict(
argstr='-fslgrad %s %s',
xor=['grad_file'],
),
in_bval=dict(extensions=None, ),
in_bvec=dict(
argstr='-fslgrad %s %s',
extensions=None,
),
in_file=dict(
argstr='%s',
extensions=None,
mandatory=True,
position=-2,
),
in_mask=dict(
argstr='-mask %s',
extensions=None,
),
nthreads=dict(
argstr='-nthreads %d',
nohash=True,
),
out_file=dict(
argstr='%s',
extensions=None,
genfile=True,
keep_extension=True,
name_source='in_file',
name_template='%s_biascorr',
position=-1,
),
use_ants=dict(
argstr='-ants',
mandatory=True,
xor=['use_fsl'],
),
use_fsl=dict(
argstr='-fsl',
mandatory=True,
xor=['use_ants'],
),
)
inputs = DWIBiasCorrect.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_DWIBiasCorrect_outputs():
output_map = dict(
bias=dict(extensions=None, ),
out_file=dict(extensions=None, ),
)
outputs = DWIBiasCorrect.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
| true | true |
f72f3823ff02324815fc7e4ba4d736a76c0e7db7 | 1,123 | py | Python | src/tests/part1/q380_test_ins_del_rand_const.py | hychrisli/PyAlgorithms | 71e537180f3b371d0d2cc47b11cb68ec13a8ac68 | [
"Apache-2.0"
] | null | null | null | src/tests/part1/q380_test_ins_del_rand_const.py | hychrisli/PyAlgorithms | 71e537180f3b371d0d2cc47b11cb68ec13a8ac68 | [
"Apache-2.0"
] | null | null | null | src/tests/part1/q380_test_ins_del_rand_const.py | hychrisli/PyAlgorithms | 71e537180f3b371d0d2cc47b11cb68ec13a8ac68 | [
"Apache-2.0"
] | null | null | null | from src.base.test_cases import TestCases
from src.utility.constants import INSERT, REMOVE, GET_RANDOM
class InsDelRandConstTestCases(TestCases):
def __init__(self):
super(InsDelRandConstTestCases, self).__init__()
self.__add_test_case__('Test Insert 1', (INSERT, 1), True)
self.__add_test_case__('Test Remove 2', (REMOVE, 2), False)
self.__add_test_case__('Test Insert 2', (INSERT, 2), True)
self.__add_test_case__('Test Random', (GET_RANDOM, [1,2]), True)
self.__add_test_case__('Test Remove 1', (REMOVE, 1), True)
self.__add_test_case__('Test Insert 2', (INSERT, 2), False)
self.__add_test_case__('Test Random', (GET_RANDOM, [2]), True)
self.__add_test_case__('Test Remove 0', (REMOVE, 0), False)
self.__add_test_case__('Test Remove 0', (REMOVE, 0), False)
self.__add_test_case__('Test Insert 0', (INSERT, 0), True)
self.__add_test_case__('Test Random', (GET_RANDOM, [0,2]), True)
self.__add_test_case__('Test Remove 0', (REMOVE, 0), True)
self.__add_test_case__('Test Insert 0', (INSERT, 0), True)
| 46.791667 | 72 | 0.672306 | from src.base.test_cases import TestCases
from src.utility.constants import INSERT, REMOVE, GET_RANDOM
class InsDelRandConstTestCases(TestCases):
def __init__(self):
super(InsDelRandConstTestCases, self).__init__()
self.__add_test_case__('Test Insert 1', (INSERT, 1), True)
self.__add_test_case__('Test Remove 2', (REMOVE, 2), False)
self.__add_test_case__('Test Insert 2', (INSERT, 2), True)
self.__add_test_case__('Test Random', (GET_RANDOM, [1,2]), True)
self.__add_test_case__('Test Remove 1', (REMOVE, 1), True)
self.__add_test_case__('Test Insert 2', (INSERT, 2), False)
self.__add_test_case__('Test Random', (GET_RANDOM, [2]), True)
self.__add_test_case__('Test Remove 0', (REMOVE, 0), False)
self.__add_test_case__('Test Remove 0', (REMOVE, 0), False)
self.__add_test_case__('Test Insert 0', (INSERT, 0), True)
self.__add_test_case__('Test Random', (GET_RANDOM, [0,2]), True)
self.__add_test_case__('Test Remove 0', (REMOVE, 0), True)
self.__add_test_case__('Test Insert 0', (INSERT, 0), True)
| true | true |
f72f3832ba1149229f6c76d9070a1eb9a4a8c2c8 | 2,496 | py | Python | tests/token/TestUtil.py | gbm001/ebay_rest | 077d3478423ccd80ff35e0361821d6a11180bc54 | [
"MIT"
] | 3 | 2021-12-12T04:28:03.000Z | 2022-03-10T03:29:18.000Z | tests/token/TestUtil.py | jdavv/ebay_rest | 20fc88c6aefdae9ab90f9c1330e79abddcd750cd | [
"MIT"
] | 33 | 2021-06-16T20:44:36.000Z | 2022-03-30T14:55:06.000Z | tests/token/TestUtil.py | jdavv/ebay_rest | 20fc88c6aefdae9ab90f9c1330e79abddcd750cd | [
"MIT"
] | 7 | 2021-06-03T09:30:23.000Z | 2022-03-08T19:51:33.000Z | # -*- coding: utf-8 -*-
"""
Copyright 2019 eBay Inc.
Licensed under the Apache License, Version 2.0 (the "License");
You may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os, logging, json, time, urllib, re, yaml
from selenium import webdriver
sandbox_key = "sandbox-user"
production_key = "production-user"
_user_credential_list = {}
def read_user_info(conf=None):
logging.info("Loading user credential configuration file at: %s", conf)
with open(conf, 'r') as f:
if conf.endswith('.yaml') or conf.endswith('.yml'):
content = yaml.load(f)
elif conf.endswith('.json'):
content = json.loads(f.read())
else:
raise ValueError('Configuration file need to be in JSON or YAML')
for key in content:
logging.debug("Environment attempted: %s", key)
if key in [sandbox_key, production_key]:
userid = content[key]['username']
password = content[key]['password']
_user_credential_list.update({key: [userid, password]})
def get_authorization_code(signin_url):
user_config_path = os.path.join(os.path.split(__file__)[0], 'config\\test-config-sample.yaml')
read_user_info(user_config_path)
env_key = production_key
if "sandbox" in signin_url:
env_key = sandbox_key
userid = _user_credential_list[env_key][0]
password = _user_credential_list[env_key][1]
browser = webdriver.Chrome()
browser.get(signin_url)
time.sleep(5)
form_userid = browser.find_element_by_name('userid')
form_pw = browser.find_element_by_name('pass')
form_userid.send_keys(userid)
form_pw.send_keys(password)
browser.find_element_by_id('sgnBt').submit()
time.sleep(5)
url = browser.current_url
browser.quit()
if 'code=' in url:
code = re.findall('code=(.*?)&', url)[0]
logging.info("Code Obtained: %s", code)
else:
logging.error("Unable to obtain code via sign in URL")
decoded_code = urllib.unquote(code).decode('utf8')
return decoded_code
| 30.439024 | 98 | 0.679087 |
import os, logging, json, time, urllib, re, yaml
from selenium import webdriver
sandbox_key = "sandbox-user"
production_key = "production-user"
_user_credential_list = {}
def read_user_info(conf=None):
logging.info("Loading user credential configuration file at: %s", conf)
with open(conf, 'r') as f:
if conf.endswith('.yaml') or conf.endswith('.yml'):
content = yaml.load(f)
elif conf.endswith('.json'):
content = json.loads(f.read())
else:
raise ValueError('Configuration file need to be in JSON or YAML')
for key in content:
logging.debug("Environment attempted: %s", key)
if key in [sandbox_key, production_key]:
userid = content[key]['username']
password = content[key]['password']
_user_credential_list.update({key: [userid, password]})
def get_authorization_code(signin_url):
user_config_path = os.path.join(os.path.split(__file__)[0], 'config\\test-config-sample.yaml')
read_user_info(user_config_path)
env_key = production_key
if "sandbox" in signin_url:
env_key = sandbox_key
userid = _user_credential_list[env_key][0]
password = _user_credential_list[env_key][1]
browser = webdriver.Chrome()
browser.get(signin_url)
time.sleep(5)
form_userid = browser.find_element_by_name('userid')
form_pw = browser.find_element_by_name('pass')
form_userid.send_keys(userid)
form_pw.send_keys(password)
browser.find_element_by_id('sgnBt').submit()
time.sleep(5)
url = browser.current_url
browser.quit()
if 'code=' in url:
code = re.findall('code=(.*?)&', url)[0]
logging.info("Code Obtained: %s", code)
else:
logging.error("Unable to obtain code via sign in URL")
decoded_code = urllib.unquote(code).decode('utf8')
return decoded_code
| true | true |
f72f39431d58d174acc8a451fc3f5024a7a67581 | 3,474 | py | Python | scrapy/contrib/downloadermiddleware/retry.py | h4ck3rm1k3/scrapy | 59dcdbe84769c9d204f552a2b545b1e096a2d42c | [
"BSD-3-Clause"
] | 26 | 2015-02-07T17:35:26.000Z | 2020-04-27T21:11:00.000Z | scrapy/contrib/downloadermiddleware/retry.py | h4ck3rm1k3/scrapy | 59dcdbe84769c9d204f552a2b545b1e096a2d42c | [
"BSD-3-Clause"
] | 2 | 2021-09-20T19:54:29.000Z | 2022-03-22T21:47:39.000Z | scrapy/contrib/downloadermiddleware/retry.py | h4ck3rm1k3/scrapy | 59dcdbe84769c9d204f552a2b545b1e096a2d42c | [
"BSD-3-Clause"
] | 9 | 2015-09-21T08:17:20.000Z | 2021-02-07T02:31:36.000Z | """
An extension to retry failed requests that are potentially caused by temporary
problems such as a connection timeout or HTTP 500 error.
You can change the behaviour of this middleware by modifing the scraping settings:
RETRY_TIMES - how many times to retry a failed page
RETRY_HTTP_CODES - which HTTP response codes to retry
Failed pages are collected on the scraping process and rescheduled at the end,
once the spider has finished crawling all regular (non failed) pages. Once
there is no more failed pages to retry this middleware sends a signal
(retry_complete), so other extensions could connect to that signal.
About HTTP errors to consider:
- You may want to remove 400 from RETRY_HTTP_CODES, if you stick to the HTTP
protocol. It's included by default because it's a common code used to
indicate server overload, which would be something we want to retry
"""
from twisted.internet import defer
from twisted.internet.error import TimeoutError, DNSLookupError, \
ConnectionRefusedError, ConnectionDone, ConnectError, \
ConnectionLost, TCPTimedOutError
from scrapy import log
from scrapy.exceptions import NotConfigured
from scrapy.utils.response import response_status_message
from scrapy.xlib.tx import ResponseFailed
class RetryMiddleware(object):
# IOError is raised by the HttpCompression middleware when trying to
# decompress an empty response
EXCEPTIONS_TO_RETRY = (defer.TimeoutError, TimeoutError, DNSLookupError,
ConnectionRefusedError, ConnectionDone, ConnectError,
ConnectionLost, TCPTimedOutError, ResponseFailed,
IOError)
def __init__(self, settings):
if not settings.getbool('RETRY_ENABLED'):
raise NotConfigured
self.max_retry_times = settings.getint('RETRY_TIMES')
self.retry_http_codes = set(int(x) for x in settings.getlist('RETRY_HTTP_CODES'))
self.priority_adjust = settings.getint('RETRY_PRIORITY_ADJUST')
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.settings)
def process_response(self, request, response, spider):
if request.meta.get('dont_retry', False):
return response
if response.status in self.retry_http_codes:
reason = response_status_message(response.status)
return self._retry(request, reason, spider) or response
return response
def process_exception(self, request, exception, spider):
if isinstance(exception, self.EXCEPTIONS_TO_RETRY) \
and not request.meta.get('dont_retry', False):
return self._retry(request, exception, spider)
def _retry(self, request, reason, spider):
retries = request.meta.get('retry_times', 0) + 1
if retries <= self.max_retry_times:
log.msg(format="Retrying %(request)s (failed %(retries)d times): %(reason)s",
level=log.DEBUG, spider=spider, request=request, retries=retries, reason=reason)
retryreq = request.copy()
retryreq.meta['retry_times'] = retries
retryreq.dont_filter = True
retryreq.priority = request.priority + self.priority_adjust
return retryreq
else:
log.msg(format="Gave up retrying %(request)s (failed %(retries)d times): %(reason)s",
level=log.DEBUG, spider=spider, request=request, retries=retries, reason=reason)
| 43.974684 | 100 | 0.704088 |
from twisted.internet import defer
from twisted.internet.error import TimeoutError, DNSLookupError, \
ConnectionRefusedError, ConnectionDone, ConnectError, \
ConnectionLost, TCPTimedOutError
from scrapy import log
from scrapy.exceptions import NotConfigured
from scrapy.utils.response import response_status_message
from scrapy.xlib.tx import ResponseFailed
class RetryMiddleware(object):
EXCEPTIONS_TO_RETRY = (defer.TimeoutError, TimeoutError, DNSLookupError,
ConnectionRefusedError, ConnectionDone, ConnectError,
ConnectionLost, TCPTimedOutError, ResponseFailed,
IOError)
def __init__(self, settings):
if not settings.getbool('RETRY_ENABLED'):
raise NotConfigured
self.max_retry_times = settings.getint('RETRY_TIMES')
self.retry_http_codes = set(int(x) for x in settings.getlist('RETRY_HTTP_CODES'))
self.priority_adjust = settings.getint('RETRY_PRIORITY_ADJUST')
@classmethod
def from_crawler(cls, crawler):
return cls(crawler.settings)
def process_response(self, request, response, spider):
if request.meta.get('dont_retry', False):
return response
if response.status in self.retry_http_codes:
reason = response_status_message(response.status)
return self._retry(request, reason, spider) or response
return response
def process_exception(self, request, exception, spider):
if isinstance(exception, self.EXCEPTIONS_TO_RETRY) \
and not request.meta.get('dont_retry', False):
return self._retry(request, exception, spider)
def _retry(self, request, reason, spider):
retries = request.meta.get('retry_times', 0) + 1
if retries <= self.max_retry_times:
log.msg(format="Retrying %(request)s (failed %(retries)d times): %(reason)s",
level=log.DEBUG, spider=spider, request=request, retries=retries, reason=reason)
retryreq = request.copy()
retryreq.meta['retry_times'] = retries
retryreq.dont_filter = True
retryreq.priority = request.priority + self.priority_adjust
return retryreq
else:
log.msg(format="Gave up retrying %(request)s (failed %(retries)d times): %(reason)s",
level=log.DEBUG, spider=spider, request=request, retries=retries, reason=reason)
| true | true |
f72f39ea13255cbce714cd52ecd6820c01e3e27b | 10,487 | py | Python | tests/test_phase_change.py | volpatto/chemicals | 721904ee17604f5e8685b0e5fff12e0bac567f73 | [
"MIT"
] | null | null | null | tests/test_phase_change.py | volpatto/chemicals | 721904ee17604f5e8685b0e5fff12e0bac567f73 | [
"MIT"
] | null | null | null | tests/test_phase_change.py | volpatto/chemicals | 721904ee17604f5e8685b0e5fff12e0bac567f73 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, Caleb Bell <Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import pytest
from fluids.numerics import assert_close, assert_close1d
from chemicals.phase_change import *
from chemicals.phase_change import (Hvap_data_CRC, Hfus_data_CRC,
Hvap_data_Gharagheizi, Hsub_data_Gharagheizi,
Tb_data_Yaws, Tm_ON_data,
phase_change_data_Perrys2_150,
phase_change_data_Alibakhshi_Cs,
phase_change_data_VDI_PPDS_4)
from chemicals.miscdata import CRC_inorganic_data, CRC_organic_data
from chemicals.identifiers import check_CAS
def test_Watson():
Hvap = Watson(T=320, Hvap_ref=43908, T_ref=300.0, Tc=647.14)
assert_close(Hvap, 42928.990094915454, rtol=1e-12)
def test_Clapeyron():
Hvap = Clapeyron(294.0, 466.0, 5.55E6)
assert_close(Hvap, 26512.36357131963)
# Test at 1/2 bar, sZ=0.98
Hvap = Clapeyron(264.0, 466.0, 5.55E6, 0.98, 5E4)
assert_close(Hvap, 23370.947571814384)
def test_Pitzer():
Hvap = Pitzer(452, 645.6, 0.35017)
assert_close(Hvap, 36696.749078320056)
def test_SMK():
Hvap = SMK(553.15, 751.35, 0.302)
assert_close(Hvap, 39866.18999046232)
def test_MK():
# Problem in article for SMK function.
Hv1 = MK(553.15, 751.35, 0.302)
# data in [1]_., should give 26.43 KJ/mol
Hv2 = MK(298.15, 469.69, 0.2507)
assert_close(Hv1, 38728.00667307733, rtol=1e-12)
assert_close(Hv2, 25940.988533726406, rtol=1e-12)
def test_Velasco():
Hv1 = Velasco(553.15, 751.35, 0.302)
Hv2 = Velasco(333.2, 476.0, 0.5559)
assert_close(Hv1, 39524.251054691274, rtol=1e-12)
assert_close(Hv2, 33299.428636069264, rtol=1e-12)
def test_Riedel():
# same problem as in Perry's examples
Hv1 = Riedel(294.0, 466.0, 5.55E6)
# Pyridine, 0.0% err vs. exp: 35090 J/mol; from Poling [2]_.
Hv2 = Riedel(388.4, 620.0, 56.3E5)
assert_close(Hv1, 26828.59040728512, rtol=1e-12)
assert_close(Hv2, 35089.80179000598, rtol=1e-12)
def test_Chen():
Hv1 = Chen(294.0, 466.0, 5.55E6)
assert_close(Hv1, 26705.902558030946)
def test_Liu():
Hv1 = Liu(294.0, 466.0, 5.55E6)
assert_close(Hv1, 26378.575260517395)
def test_Vetere():
Hv1 = Vetere(294.0, 466.0, 5.55E6)
assert_close(Hv1, 26363.43895706672)
def test_Hvap_CRC_data():
HvapTb_tot = Hvap_data_CRC['HvapTb'].sum()
assert_close(HvapTb_tot, 30251890.0)
Hvap298_tot = Hvap_data_CRC['Hvap298'].sum()
assert_close(Hvap298_tot, 29343710.0)
Tb_tot = Hvap_data_CRC['Tb'].sum()
assert_close(Tb_tot, 407502.95600000001)
assert Hvap_data_CRC.index.is_unique
assert Hvap_data_CRC.shape == (926, 5)
assert all([check_CAS(i) for i in list(Hvap_data_CRC.index)])
def test_Hfus_CRC_data():
Hfus_total = Hfus_data_CRC['Hfus'].sum()
assert_close(Hfus_total, 29131241)
assert Hfus_data_CRC.index.is_unique
assert Hfus_data_CRC.shape == (1112, 3)
assert all([check_CAS(i) for i in list(Hfus_data_CRC.index)])
def test_Hfus():
assert_close(Hfus('462-06-6', method='CRC'), 11310.0, rtol=1e-12)
assert_close(Hfus('462-06-6'), 11310.0, rtol=1e-12)
assert_close(Hfus(CASRN='75-07-0'), 2310.0)
assert Hfus(CASRN='75000-07-0') is None
assert Hfus_methods('7732-18-5') == ['CRC']
def test_Gharagheizi_Hvap_data():
# 51 CAS number DO NOT validate
Hvap298_tot = Hvap_data_Gharagheizi['Hvap298'].sum()
assert_close(Hvap298_tot, 173584900)
assert Hvap_data_Gharagheizi.index.is_unique
assert Hvap_data_Gharagheizi.shape == (2730, 2)
def test_Gharagheizi_Hsub_data():
tots = [Hsub_data_Gharagheizi[i].sum() for i in ['Hsub', 'error']]
assert_close(tots[0], 130537650)
assert_close(tots[1], 1522960.0)
assert Hsub_data_Gharagheizi.index.is_unique
assert Hsub_data_Gharagheizi.shape == (1241, 3)
def test_Yaws_Tb_data():
tot = Tb_data_Yaws.sum()
assert_close(tot, 6631287.51)
assert Tb_data_Yaws.index.is_unique
assert Tb_data_Yaws.shape == (13461, 1)
@pytest.mark.slow
def test_Yaws_Tb_CAS_valid():
assert all([check_CAS(i) for i in Tb_data_Yaws.index])
def test_Tm_ON_data():
tot = Tm_ON_data.sum()
assert_close(tot, 4059989.425)
assert Tm_ON_data.shape == (11549, 1)
assert Tm_ON_data.index.is_unique
@pytest.mark.slow
def test_Tm_ON_data_CAS_valid():
assert all([check_CAS(i) for i in Tm_ON_data.index])
def test_Perrys2_150_data():
# rtol=2E-4 for Tmin; only helium-4 needs a higher tolerance
# Everything hits 0 at Tmax except Difluoromethane, methane, and water;
# those needed their Tmax adjusted to their real Tc.
# C1 is divided by 1000, to give units of J/mol instead of J/kmol
# Terephthalic acid removed, was a constant value only.
assert all([check_CAS(i) for i in phase_change_data_Perrys2_150.index])
tots_calc = [phase_change_data_Perrys2_150[i].abs().sum() for i in [u'Tc', u'C1', u'C2', u'C3', u'C4', u'Tmin', u'Tmax']]
tots = [189407.42499999999, 18617223.739999998, 174.34494000000001, 112.51209900000001, 63.894040000000004, 70810.849999999991, 189407.005]
assert_close1d(tots_calc, tots)
assert phase_change_data_Perrys2_150.index.is_unique
assert phase_change_data_Perrys2_150.shape == (344, 8)
def test_Alibakhshi_Cs_data():
# Oops, a bunch of these now-lonely coefficients have an invalid CAS...
# assert all([check_CAS(i) for i in phase_change_data_Alibakhshi_Cs.index])
tots_calc = [phase_change_data_Alibakhshi_Cs[i].abs().sum() for i in [u'C']]
tots = [28154.361500000003]
assert_close1d(tots_calc, tots)
assert phase_change_data_Alibakhshi_Cs.index.is_unique
assert phase_change_data_Alibakhshi_Cs.shape == (1890, 2)
def test_VDI_PPDS_4_data():
"""I believe there are no errors here."""
assert all([check_CAS(i) for i in phase_change_data_VDI_PPDS_4.index])
tots_calc = [phase_change_data_VDI_PPDS_4[i].abs().sum() for i in [u'A', u'B', u'C', u'D', u'E', u'Tc', u'MW']]
tots = [1974.2929800000002, 2653.9399000000003, 2022.530649, 943.25633100000005, 3124.9258610000002, 150142.28, 27786.919999999998]
assert_close1d(tots_calc, tots)
assert phase_change_data_VDI_PPDS_4.index.is_unique
assert phase_change_data_VDI_PPDS_4.shape == (272, 8)
@pytest.mark.slow
@pytest.mark.fuzz
def test_Tb_all_values():
s1 = CRC_inorganic_data.index[CRC_inorganic_data['Tb'].notnull()]
s2 = CRC_organic_data.index[CRC_organic_data['Tb'].notnull()]
s3 = Tb_data_Yaws.index
tots = []
tots_exp = [639213.2310000042, 2280667.079999829, 6631287.510000873]
# These should match the sums of the respective series
for s, method in zip([s1, s2, s3], ['CRC_INORG', 'CRC_ORG', 'YAWS']):
tots.append(sum([Tb(i, method=method) for i in s]))
assert_close1d(tots, tots_exp, rtol=1e-11)
s = set(); s.update(s1); s.update(s2); s.update(s3)
assert len(s) == 13868
def test_Tb():
# CRC_inorg, CRC org, Yaws
Tbs_calc = Tb('993-50-0'), Tb('626-94-8'), Tb('7631-99-4')
Tbs = [399.15, 412.15, 653.15]
assert_close1d(Tbs, Tbs_calc)
hits = [Tb_methods(i) for i in ['993-50-0', '626-94-8', '7631-99-4']]
assert hits == [['CRC_INORG'], ['CRC_ORG'], ['YAWS']]
with pytest.raises(Exception):
Tb('993-50-0', method='BADMETHOD')
assert None == Tb('9923443-50-0')
assert [] == Tb_methods('9923443-50-0')
w_methods = Tb_methods('7732-18-5')
assert w_methods == ['CRC_INORG', 'YAWS']
Tbs = [Tb('7732-18-5', method=i) for i in w_methods]
assert_close1d(Tbs, [373.124, 373.15])
@pytest.mark.slow
@pytest.mark.fuzz
def test_Tm_all_values():
s1 = CRC_inorganic_data.index[CRC_inorganic_data['Tm'].notnull()]
s2 = CRC_organic_data.index[CRC_organic_data['Tm'].notnull()]
s3 = Tm_ON_data.index
tots = []
tots_exp = [1543322.6125999668, 2571284.480399755, 4059989.4249993376]
# These should match the sums of the respective series
for s, method in zip([s1, s2, s3], ['CRC_INORG', 'CRC_ORG', 'OPEN_NTBKM']):
tots.append(sum([Tm(i, method=method) for i in s]))
assert_close1d(tots, tots_exp, rtol=1e-11)
s = set(); s.update(s1); s.update(s2); s.update(s3)
assert len(s) == 14723
def test_Tm():
# Open notebook, CRC organic, CRC inorg
Tms_calc = Tm('996-50-9'), Tm('999-78-0'), Tm('993-50-0')
Tms = [263.15, 191.15, 274.15]
assert_close1d(Tms, Tms_calc)
hits = [Tm_methods(i) for i in ['996-50-9', '999-78-0', '993-50-0']]
assert hits == [['OPEN_NTBKM'], ['CRC_ORG'], ['CRC_INORG']]
with pytest.raises(Exception):
Tm('993-50-0', method='BADMETHOD')
assert Tm('9923443-50-0') is None
assert [] == Tm_methods('9923443-50-0')
w_methods = Tm_methods('7732-18-5')
assert w_methods == ['OPEN_NTBKM', 'CRC_INORG']
Tms = [Tm('7732-18-5', method=i) for i in w_methods]
assert_close1d(Tms, [273.15, 273.15])
def test_Alibakhshi():
Hvap = Alibakhshi(T=320.0, Tc=647.14, C=-16.7171)
assert_close(Hvap, 41961.30490225752, rtol=1e-13)
def test_PPDS12():
Hvap = PPDS12(300.0, 591.75, 4.60584, 13.97224, -10.592315, 2.120205, 4.277128)
assert_close(Hvap, 37948.76862035927, rtol=1e-13)
| 34.840532 | 143 | 0.685229 |
import pytest
from fluids.numerics import assert_close, assert_close1d
from chemicals.phase_change import *
from chemicals.phase_change import (Hvap_data_CRC, Hfus_data_CRC,
Hvap_data_Gharagheizi, Hsub_data_Gharagheizi,
Tb_data_Yaws, Tm_ON_data,
phase_change_data_Perrys2_150,
phase_change_data_Alibakhshi_Cs,
phase_change_data_VDI_PPDS_4)
from chemicals.miscdata import CRC_inorganic_data, CRC_organic_data
from chemicals.identifiers import check_CAS
def test_Watson():
Hvap = Watson(T=320, Hvap_ref=43908, T_ref=300.0, Tc=647.14)
assert_close(Hvap, 42928.990094915454, rtol=1e-12)
def test_Clapeyron():
Hvap = Clapeyron(294.0, 466.0, 5.55E6)
assert_close(Hvap, 26512.36357131963)
Hvap = Clapeyron(264.0, 466.0, 5.55E6, 0.98, 5E4)
assert_close(Hvap, 23370.947571814384)
def test_Pitzer():
Hvap = Pitzer(452, 645.6, 0.35017)
assert_close(Hvap, 36696.749078320056)
def test_SMK():
Hvap = SMK(553.15, 751.35, 0.302)
assert_close(Hvap, 39866.18999046232)
def test_MK():
Hv1 = MK(553.15, 751.35, 0.302)
Hv2 = MK(298.15, 469.69, 0.2507)
assert_close(Hv1, 38728.00667307733, rtol=1e-12)
assert_close(Hv2, 25940.988533726406, rtol=1e-12)
def test_Velasco():
Hv1 = Velasco(553.15, 751.35, 0.302)
Hv2 = Velasco(333.2, 476.0, 0.5559)
assert_close(Hv1, 39524.251054691274, rtol=1e-12)
assert_close(Hv2, 33299.428636069264, rtol=1e-12)
def test_Riedel():
Hv1 = Riedel(294.0, 466.0, 5.55E6)
# Pyridine, 0.0% err vs. exp: 35090 J/mol; from Poling [2]_.
Hv2 = Riedel(388.4, 620.0, 56.3E5)
assert_close(Hv1, 26828.59040728512, rtol=1e-12)
assert_close(Hv2, 35089.80179000598, rtol=1e-12)
def test_Chen():
Hv1 = Chen(294.0, 466.0, 5.55E6)
assert_close(Hv1, 26705.902558030946)
def test_Liu():
Hv1 = Liu(294.0, 466.0, 5.55E6)
assert_close(Hv1, 26378.575260517395)
def test_Vetere():
Hv1 = Vetere(294.0, 466.0, 5.55E6)
assert_close(Hv1, 26363.43895706672)
def test_Hvap_CRC_data():
HvapTb_tot = Hvap_data_CRC['HvapTb'].sum()
assert_close(HvapTb_tot, 30251890.0)
Hvap298_tot = Hvap_data_CRC['Hvap298'].sum()
assert_close(Hvap298_tot, 29343710.0)
Tb_tot = Hvap_data_CRC['Tb'].sum()
assert_close(Tb_tot, 407502.95600000001)
assert Hvap_data_CRC.index.is_unique
assert Hvap_data_CRC.shape == (926, 5)
assert all([check_CAS(i) for i in list(Hvap_data_CRC.index)])
def test_Hfus_CRC_data():
Hfus_total = Hfus_data_CRC['Hfus'].sum()
assert_close(Hfus_total, 29131241)
assert Hfus_data_CRC.index.is_unique
assert Hfus_data_CRC.shape == (1112, 3)
assert all([check_CAS(i) for i in list(Hfus_data_CRC.index)])
def test_Hfus():
assert_close(Hfus('462-06-6', method='CRC'), 11310.0, rtol=1e-12)
assert_close(Hfus('462-06-6'), 11310.0, rtol=1e-12)
assert_close(Hfus(CASRN='75-07-0'), 2310.0)
assert Hfus(CASRN='75000-07-0') is None
assert Hfus_methods('7732-18-5') == ['CRC']
def test_Gharagheizi_Hvap_data():
# 51 CAS number DO NOT validate
Hvap298_tot = Hvap_data_Gharagheizi['Hvap298'].sum()
assert_close(Hvap298_tot, 173584900)
assert Hvap_data_Gharagheizi.index.is_unique
assert Hvap_data_Gharagheizi.shape == (2730, 2)
def test_Gharagheizi_Hsub_data():
tots = [Hsub_data_Gharagheizi[i].sum() for i in ['Hsub', 'error']]
assert_close(tots[0], 130537650)
assert_close(tots[1], 1522960.0)
assert Hsub_data_Gharagheizi.index.is_unique
assert Hsub_data_Gharagheizi.shape == (1241, 3)
def test_Yaws_Tb_data():
tot = Tb_data_Yaws.sum()
assert_close(tot, 6631287.51)
assert Tb_data_Yaws.index.is_unique
assert Tb_data_Yaws.shape == (13461, 1)
@pytest.mark.slow
def test_Yaws_Tb_CAS_valid():
assert all([check_CAS(i) for i in Tb_data_Yaws.index])
def test_Tm_ON_data():
tot = Tm_ON_data.sum()
assert_close(tot, 4059989.425)
assert Tm_ON_data.shape == (11549, 1)
assert Tm_ON_data.index.is_unique
@pytest.mark.slow
def test_Tm_ON_data_CAS_valid():
assert all([check_CAS(i) for i in Tm_ON_data.index])
def test_Perrys2_150_data():
# rtol=2E-4 for Tmin; only helium-4 needs a higher tolerance
# Everything hits 0 at Tmax except Difluoromethane, methane, and water;
# those needed their Tmax adjusted to their real Tc.
# C1 is divided by 1000, to give units of J/mol instead of J/kmol
# Terephthalic acid removed, was a constant value only.
assert all([check_CAS(i) for i in phase_change_data_Perrys2_150.index])
tots_calc = [phase_change_data_Perrys2_150[i].abs().sum() for i in [u'Tc', u'C1', u'C2', u'C3', u'C4', u'Tmin', u'Tmax']]
tots = [189407.42499999999, 18617223.739999998, 174.34494000000001, 112.51209900000001, 63.894040000000004, 70810.849999999991, 189407.005]
assert_close1d(tots_calc, tots)
assert phase_change_data_Perrys2_150.index.is_unique
assert phase_change_data_Perrys2_150.shape == (344, 8)
def test_Alibakhshi_Cs_data():
# Oops, a bunch of these now-lonely coefficients have an invalid CAS...
# assert all([check_CAS(i) for i in phase_change_data_Alibakhshi_Cs.index])
tots_calc = [phase_change_data_Alibakhshi_Cs[i].abs().sum() for i in [u'C']]
tots = [28154.361500000003]
assert_close1d(tots_calc, tots)
assert phase_change_data_Alibakhshi_Cs.index.is_unique
assert phase_change_data_Alibakhshi_Cs.shape == (1890, 2)
def test_VDI_PPDS_4_data():
assert all([check_CAS(i) for i in phase_change_data_VDI_PPDS_4.index])
tots_calc = [phase_change_data_VDI_PPDS_4[i].abs().sum() for i in [u'A', u'B', u'C', u'D', u'E', u'Tc', u'MW']]
tots = [1974.2929800000002, 2653.9399000000003, 2022.530649, 943.25633100000005, 3124.9258610000002, 150142.28, 27786.919999999998]
assert_close1d(tots_calc, tots)
assert phase_change_data_VDI_PPDS_4.index.is_unique
assert phase_change_data_VDI_PPDS_4.shape == (272, 8)
@pytest.mark.slow
@pytest.mark.fuzz
def test_Tb_all_values():
s1 = CRC_inorganic_data.index[CRC_inorganic_data['Tb'].notnull()]
s2 = CRC_organic_data.index[CRC_organic_data['Tb'].notnull()]
s3 = Tb_data_Yaws.index
tots = []
tots_exp = [639213.2310000042, 2280667.079999829, 6631287.510000873]
# These should match the sums of the respective series
for s, method in zip([s1, s2, s3], ['CRC_INORG', 'CRC_ORG', 'YAWS']):
tots.append(sum([Tb(i, method=method) for i in s]))
assert_close1d(tots, tots_exp, rtol=1e-11)
s = set(); s.update(s1); s.update(s2); s.update(s3)
assert len(s) == 13868
def test_Tb():
# CRC_inorg, CRC org, Yaws
Tbs_calc = Tb('993-50-0'), Tb('626-94-8'), Tb('7631-99-4')
Tbs = [399.15, 412.15, 653.15]
assert_close1d(Tbs, Tbs_calc)
hits = [Tb_methods(i) for i in ['993-50-0', '626-94-8', '7631-99-4']]
assert hits == [['CRC_INORG'], ['CRC_ORG'], ['YAWS']]
with pytest.raises(Exception):
Tb('993-50-0', method='BADMETHOD')
assert None == Tb('9923443-50-0')
assert [] == Tb_methods('9923443-50-0')
w_methods = Tb_methods('7732-18-5')
assert w_methods == ['CRC_INORG', 'YAWS']
Tbs = [Tb('7732-18-5', method=i) for i in w_methods]
assert_close1d(Tbs, [373.124, 373.15])
@pytest.mark.slow
@pytest.mark.fuzz
def test_Tm_all_values():
s1 = CRC_inorganic_data.index[CRC_inorganic_data['Tm'].notnull()]
s2 = CRC_organic_data.index[CRC_organic_data['Tm'].notnull()]
s3 = Tm_ON_data.index
tots = []
tots_exp = [1543322.6125999668, 2571284.480399755, 4059989.4249993376]
# These should match the sums of the respective series
for s, method in zip([s1, s2, s3], ['CRC_INORG', 'CRC_ORG', 'OPEN_NTBKM']):
tots.append(sum([Tm(i, method=method) for i in s]))
assert_close1d(tots, tots_exp, rtol=1e-11)
s = set(); s.update(s1); s.update(s2); s.update(s3)
assert len(s) == 14723
def test_Tm():
# Open notebook, CRC organic, CRC inorg
Tms_calc = Tm('996-50-9'), Tm('999-78-0'), Tm('993-50-0')
Tms = [263.15, 191.15, 274.15]
assert_close1d(Tms, Tms_calc)
hits = [Tm_methods(i) for i in ['996-50-9', '999-78-0', '993-50-0']]
assert hits == [['OPEN_NTBKM'], ['CRC_ORG'], ['CRC_INORG']]
with pytest.raises(Exception):
Tm('993-50-0', method='BADMETHOD')
assert Tm('9923443-50-0') is None
assert [] == Tm_methods('9923443-50-0')
w_methods = Tm_methods('7732-18-5')
assert w_methods == ['OPEN_NTBKM', 'CRC_INORG']
Tms = [Tm('7732-18-5', method=i) for i in w_methods]
assert_close1d(Tms, [273.15, 273.15])
def test_Alibakhshi():
Hvap = Alibakhshi(T=320.0, Tc=647.14, C=-16.7171)
assert_close(Hvap, 41961.30490225752, rtol=1e-13)
def test_PPDS12():
Hvap = PPDS12(300.0, 591.75, 4.60584, 13.97224, -10.592315, 2.120205, 4.277128)
assert_close(Hvap, 37948.76862035927, rtol=1e-13)
| true | true |
f72f3a0ab9d913c2109ddb7b9fece41c54d596c4 | 11,902 | py | Python | typhon/retrieval/common.py | gerritholl/typhon | dbde147be12922ec730bd072dc4797c9da9a6d6b | [
"MIT"
] | null | null | null | typhon/retrieval/common.py | gerritholl/typhon | dbde147be12922ec730bd072dc4797c9da9a6d6b | [
"MIT"
] | null | null | null | typhon/retrieval/common.py | gerritholl/typhon | dbde147be12922ec730bd072dc4797c9da9a6d6b | [
"MIT"
] | null | null | null | from ast import literal_eval
import copy
from importlib import import_module
import json
import numpy as np
import pandas as pd
from sklearn.pipeline import Pipeline
from typhon.utils import to_array
__all__ = [
'RetrievalProduct',
]
class NotTrainedError(Exception):
"""Should be raised if someone runs a non-trained retrieval product
"""
def __init__(self, *args):
message = "You must train this retrieval product before running it!"
Exception.__init__(self, message, *args)
class RetrievalProduct:
"""Retrieval that can be trained with data and stored to json files
This is basically a wrapper around the scikit-learn estimator and trainer
classes and makes it possible to save the trained models as json file.
To save this object to a json file, the additional package json_tricks is
required.
"""
def __init__(self, verbose=False):
"""Initialize a Retriever object
Args:
verbose: The higher this value is the more debug messages are
printed. Default is False.
"""
# The trainer and/or model for this retriever:
self.estimator = None
self.verbose = verbose
self._inputs = []
self._outputs = []
@property
def inputs(self):
return self._inputs
@property
def outputs(self):
return self._outputs
@staticmethod
def _import_class(module_name, class_name):
"""Import a class dynamically to the namespace"""
mod = import_module(module_name)
klass = getattr(mod, class_name)
return klass
@staticmethod
def _encode_numpy(obj):
def _to_dict(item):
if isinstance(item, np.ndarray):
return {
"__ndarray__": item.tolist(),
"__dtype__": str(item.dtype),
"__shape__": item.shape,
}
else:
return np.asscalar(item)
def _is_numpy(item):
return type(item).__module__ == np.__name__
if isinstance(obj, dict):
obj = obj.copy()
iterator = obj.items()
elif isinstance(obj, list):
obj = obj.copy()
iterator = enumerate(obj)
else:
return obj
for key, value in iterator:
if _is_numpy(value):
obj[key] = _to_dict(value)
elif isinstance(value, (list, dict)):
obj[key] = RetrievalProduct._encode_numpy(value)
return obj
@staticmethod
def _decode_numpy(obj):
def _from_dict(item):
try:
return np.array(
item["__ndarray__"],
dtype=item["__dtype__"],
)
except TypeError:
return np.array(
item["__ndarray__"],
dtype=literal_eval(item["__dtype__"]),
)
def _is_numpy(item):
return isinstance(item, dict) and "__ndarray__" in item
if isinstance(obj, dict):
obj = obj.copy()
iterator = obj.items()
elif isinstance(obj, list):
obj = obj.copy()
iterator = enumerate(obj)
else:
return obj
for key, value in iterator:
if _is_numpy(value):
obj[key] = _from_dict(value)
elif isinstance(value, (list, tuple, dict)):
obj[key] = RetrievalProduct._decode_numpy(value)
return obj
@staticmethod
def _tree_to_dict(tree):
return {
"module": type(tree).__module__,
"class": type(tree).__name__,
"coefs": tree.__getstate__(),
}
@staticmethod
def _tree_from_dict(dictionary, coefs):
instance = RetrievalProduct._import_class(
dictionary["module"], dictionary["class"]
)
tree = instance(
to_array(coefs["n_features_"]),
to_array(coefs["n_classes_"]),
to_array(coefs["n_outputs_"])
)
tree.__setstate__(dictionary["coefs"])
return tree
@staticmethod
def _model_to_dict(model):
"""Convert a sklearn model object to a dictionary"""
dictionary = {
"module": type(model).__module__,
"class": type(model).__name__,
"params": model.get_params(deep=True),
"coefs": {
attr: copy.deepcopy(getattr(model, attr))
for attr in model.__dir__()
if not attr.startswith("__") and attr.endswith("_")
}
}
if "tree_" in dictionary["coefs"]:
# Not funny. sklearn.tree objects are not directly
# serializable to json. Hence, we must dump them by ourselves.
dictionary["coefs"]["tree_"] = RetrievalProduct._tree_to_dict(
dictionary["coefs"]["tree_"]
)
return RetrievalProduct._encode_numpy(dictionary)
@staticmethod
def _model_from_dict(dictionary):
"""Create a sklearn model object from a dictionary"""
dictionary = RetrievalProduct._decode_numpy(dictionary)
instance = RetrievalProduct._import_class(
dictionary["module"], dictionary["class"]
)
model = instance(**dictionary["params"])
for attr, value in dictionary["coefs"].items():
if attr == "tree_":
# We must treat a tree specially:
value = RetrievalProduct._tree_from_dict(
value, dictionary["coefs"]
)
try:
setattr(model, attr, value)
except AttributeError:
# Some attributes cannot be set such as feature_importances_
pass
return model
@staticmethod
def _pipeline_to_dict(pipeline):
"""Convert a pipeline object to a dictionary"""
if pipeline is None:
raise ValueError("No object trained!")
all_steps = {}
for name, model in pipeline.steps:
all_steps[name] = RetrievalProduct._model_to_dict(model)
return all_steps
@staticmethod
def _pipeline_from_dict(dictionary):
"""Create a pipeline object from a dictionary"""
all_steps = []
for name, step in dictionary.items():
model = RetrievalProduct._model_from_dict(step)
all_steps.append([name, model])
return Pipeline(all_steps)
def is_trained(self):
"""Return true if RetrievalProduct is trained"""
return self.estimator is not None
@classmethod
def from_dict(cls, parameter, *args, **kwargs):
"""Load a retrieval product from a dictionary
Args:
parameter: A dictionary with the training parameters. Simply the
output of :meth:`to_dict`.
*args: Positional arguments allowed for :meth:`__init__`.
**kwargs Keyword arguments allowed for :meth:`__init__`.
Returns:
A new :class:`RetrievalProduct` object.
"""
self = cls(*args, **kwargs)
estimator = parameter.get("estimator", None)
if estimator is None:
raise ValueError("Found no coefficients for estimator!")
is_pipeline = parameter["estimator_is_pipeline"]
if is_pipeline:
self.estimator = self._pipeline_from_dict(estimator)
else:
self.estimator = self._model_from_dict(estimator)
self._inputs = parameter["inputs"]
self._outputs = parameter["outputs"]
return self
def to_dict(self):
"""Dump this retrieval product to a dictionary"""
parameter = {}
if isinstance(self.estimator, Pipeline):
parameter["estimator"] = self._pipeline_to_dict(self.estimator)
parameter["estimator_is_pipeline"] = True
else:
parameter["estimator"] = self._model_to_dict(self.estimator)
parameter["estimator_is_pipeline"] = False
parameter["inputs"] = self.inputs
parameter["outputs"] = self.outputs
return parameter
@classmethod
def from_txt(cls, filename, *args, **kwargs):
"""Load a retrieval product from a txt file
Notes:
The output format is not standard json!
Training parameters are:
* weights of the estimator
* names of the input and target fields
Args:
filename: The name of file from where to load the training
parameters.
*args: Positional arguments allowed for :meth:`__init__`.
**kwargs Keyword arguments allowed for :meth:`__init__`.
Returns:
A new :class:`RetrievalProduct` object.
"""
with open(filename, 'r') as infile:
parameter = literal_eval(infile.read())
return cls.from_dict(parameter, *args, **kwargs)
def to_txt(self, filename):
"""Save this retrieval product to a txt file
Training parameters are:
* configuration of the used estimator
* names of the input, output, and target fields
Args:
filename: The name of the file where to store the training
parameters.
Returns:
None
"""
with open(filename, 'w') as outfile:
outfile.write(repr(self.to_dict()))
def retrieve(self, inputs):
"""Predict the target values for data coming from arrays
Args:
inputs: A pandas.DataFrame object. The keys must be the
same labels as used in :meth:`train`.
Returns:
A pandas.DataFrame object with the retrieved data.
Examples:
.. :code-block:: python
# TODO
"""
if self.estimator is None:
raise NotTrainedError()
# Skip empty datasets
if inputs.empty:
return None
# Retrieve the data from the neural network:
output_data = self.estimator.predict(inputs)
return pd.DataFrame(data=output_data, columns=self.outputs)
def score(self, inputs, targets):
"""
Args:
inputs: A pandas.DataFrame with input data.
targets: A pandas.DataFrame with target data.
Returns:
The metric score as a number
"""
if self.estimator is None:
raise NotTrainedError()
return self.estimator.score(inputs.squeeze(), targets.squeeze())
def train(self, estimator, inputs, targets):
"""Train this retriever with data from arrays
Args:
estimator: The object that will be trained. If it is a trainer
object such as a GridSearchCV, the best estimator will be
chosen after training. Can also be a Pipeline or a standard
Estimator from scikit-learn.
inputs: A pandas.DataFrame with input data.
targets: A pandas.DataFrame with target data.
Returns:
A float number indicating the training score.
"""
# The input and target labels will be saved because to know what this
# product retrieves and from what:
self._inputs = inputs.columns.tolist()
self._outputs = targets.columns.tolist()
# Start to train!
estimator.fit(inputs.squeeze(), targets.squeeze())
# Let's check whether the estimator was a trainer object such as
# GridSearchCV, etc. Then we save only the best estimator.
if hasattr(estimator, "best_estimator_"):
# Use the best estimator from now on:
self.estimator = estimator.best_estimator_
else:
self.estimator = estimator
return self.score(inputs, targets)
| 31.075718 | 77 | 0.582423 | from ast import literal_eval
import copy
from importlib import import_module
import json
import numpy as np
import pandas as pd
from sklearn.pipeline import Pipeline
from typhon.utils import to_array
__all__ = [
'RetrievalProduct',
]
class NotTrainedError(Exception):
def __init__(self, *args):
message = "You must train this retrieval product before running it!"
Exception.__init__(self, message, *args)
class RetrievalProduct:
def __init__(self, verbose=False):
self.estimator = None
self.verbose = verbose
self._inputs = []
self._outputs = []
@property
def inputs(self):
return self._inputs
@property
def outputs(self):
return self._outputs
@staticmethod
def _import_class(module_name, class_name):
mod = import_module(module_name)
klass = getattr(mod, class_name)
return klass
@staticmethod
def _encode_numpy(obj):
def _to_dict(item):
if isinstance(item, np.ndarray):
return {
"__ndarray__": item.tolist(),
"__dtype__": str(item.dtype),
"__shape__": item.shape,
}
else:
return np.asscalar(item)
def _is_numpy(item):
return type(item).__module__ == np.__name__
if isinstance(obj, dict):
obj = obj.copy()
iterator = obj.items()
elif isinstance(obj, list):
obj = obj.copy()
iterator = enumerate(obj)
else:
return obj
for key, value in iterator:
if _is_numpy(value):
obj[key] = _to_dict(value)
elif isinstance(value, (list, dict)):
obj[key] = RetrievalProduct._encode_numpy(value)
return obj
@staticmethod
def _decode_numpy(obj):
def _from_dict(item):
try:
return np.array(
item["__ndarray__"],
dtype=item["__dtype__"],
)
except TypeError:
return np.array(
item["__ndarray__"],
dtype=literal_eval(item["__dtype__"]),
)
def _is_numpy(item):
return isinstance(item, dict) and "__ndarray__" in item
if isinstance(obj, dict):
obj = obj.copy()
iterator = obj.items()
elif isinstance(obj, list):
obj = obj.copy()
iterator = enumerate(obj)
else:
return obj
for key, value in iterator:
if _is_numpy(value):
obj[key] = _from_dict(value)
elif isinstance(value, (list, tuple, dict)):
obj[key] = RetrievalProduct._decode_numpy(value)
return obj
@staticmethod
def _tree_to_dict(tree):
return {
"module": type(tree).__module__,
"class": type(tree).__name__,
"coefs": tree.__getstate__(),
}
@staticmethod
def _tree_from_dict(dictionary, coefs):
instance = RetrievalProduct._import_class(
dictionary["module"], dictionary["class"]
)
tree = instance(
to_array(coefs["n_features_"]),
to_array(coefs["n_classes_"]),
to_array(coefs["n_outputs_"])
)
tree.__setstate__(dictionary["coefs"])
return tree
@staticmethod
def _model_to_dict(model):
dictionary = {
"module": type(model).__module__,
"class": type(model).__name__,
"params": model.get_params(deep=True),
"coefs": {
attr: copy.deepcopy(getattr(model, attr))
for attr in model.__dir__()
if not attr.startswith("__") and attr.endswith("_")
}
}
if "tree_" in dictionary["coefs"]:
dictionary["coefs"]["tree_"] = RetrievalProduct._tree_to_dict(
dictionary["coefs"]["tree_"]
)
return RetrievalProduct._encode_numpy(dictionary)
@staticmethod
def _model_from_dict(dictionary):
dictionary = RetrievalProduct._decode_numpy(dictionary)
instance = RetrievalProduct._import_class(
dictionary["module"], dictionary["class"]
)
model = instance(**dictionary["params"])
for attr, value in dictionary["coefs"].items():
if attr == "tree_":
value = RetrievalProduct._tree_from_dict(
value, dictionary["coefs"]
)
try:
setattr(model, attr, value)
except AttributeError:
pass
return model
@staticmethod
def _pipeline_to_dict(pipeline):
if pipeline is None:
raise ValueError("No object trained!")
all_steps = {}
for name, model in pipeline.steps:
all_steps[name] = RetrievalProduct._model_to_dict(model)
return all_steps
@staticmethod
def _pipeline_from_dict(dictionary):
all_steps = []
for name, step in dictionary.items():
model = RetrievalProduct._model_from_dict(step)
all_steps.append([name, model])
return Pipeline(all_steps)
def is_trained(self):
return self.estimator is not None
@classmethod
def from_dict(cls, parameter, *args, **kwargs):
self = cls(*args, **kwargs)
estimator = parameter.get("estimator", None)
if estimator is None:
raise ValueError("Found no coefficients for estimator!")
is_pipeline = parameter["estimator_is_pipeline"]
if is_pipeline:
self.estimator = self._pipeline_from_dict(estimator)
else:
self.estimator = self._model_from_dict(estimator)
self._inputs = parameter["inputs"]
self._outputs = parameter["outputs"]
return self
def to_dict(self):
parameter = {}
if isinstance(self.estimator, Pipeline):
parameter["estimator"] = self._pipeline_to_dict(self.estimator)
parameter["estimator_is_pipeline"] = True
else:
parameter["estimator"] = self._model_to_dict(self.estimator)
parameter["estimator_is_pipeline"] = False
parameter["inputs"] = self.inputs
parameter["outputs"] = self.outputs
return parameter
@classmethod
def from_txt(cls, filename, *args, **kwargs):
with open(filename, 'r') as infile:
parameter = literal_eval(infile.read())
return cls.from_dict(parameter, *args, **kwargs)
def to_txt(self, filename):
with open(filename, 'w') as outfile:
outfile.write(repr(self.to_dict()))
def retrieve(self, inputs):
if self.estimator is None:
raise NotTrainedError()
if inputs.empty:
return None
output_data = self.estimator.predict(inputs)
return pd.DataFrame(data=output_data, columns=self.outputs)
def score(self, inputs, targets):
if self.estimator is None:
raise NotTrainedError()
return self.estimator.score(inputs.squeeze(), targets.squeeze())
def train(self, estimator, inputs, targets):
self._inputs = inputs.columns.tolist()
self._outputs = targets.columns.tolist()
estimator.fit(inputs.squeeze(), targets.squeeze())
# GridSearchCV, etc. Then we save only the best estimator.
if hasattr(estimator, "best_estimator_"):
# Use the best estimator from now on:
self.estimator = estimator.best_estimator_
else:
self.estimator = estimator
return self.score(inputs, targets)
| true | true |
f72f3abecda24bf11d5273a5655eafa5f2c18ecb | 10,729 | py | Python | src/minescrubber/mainwindow.py | alok1974/minescrubber | 0c18d960b385a4a59ac0cf38bc69271a23c667e7 | [
"MIT"
] | 1 | 2020-08-11T23:08:34.000Z | 2020-08-11T23:08:34.000Z | src/minescrubber/mainwindow.py | alok1974/minescrubber | 0c18d960b385a4a59ac0cf38bc69271a23c667e7 | [
"MIT"
] | null | null | null | src/minescrubber/mainwindow.py | alok1974/minescrubber | 0c18d960b385a4a59ac0cf38bc69271a23c667e7 | [
"MIT"
] | null | null | null | import os
import random
from . import imager, conf, animator
from .qt import BaseDialog, QtWidgets, QtCore, QtGui
class MainWidget(BaseDialog):
CELL_SELECTED_SIGNAL = QtCore.Signal(tuple)
CELL_FLAGGED_SIGNAL = QtCore.Signal(tuple)
NEW_GAME_SIGNAL = QtCore.Signal(tuple)
def __init__(self, parent=None):
super().__init__(parent=parent)
def init_board(self, board):
self._board = board
self._last_swept = self._board.last_swept
self._board_image = imager.BoardImage(self._board)
self._ac = animator.AnimController(board_image=self._board_image)
self._setup_ui()
self._timer = QtCore.QTimer()
self._time = 0
self._connect_signals()
def _setup_ui(self):
title = 'Minescrubber'
self.setWindowTitle(title)
self.setFixedSize(
max(304, self._board_image.qt_image.width() + 40),
self._board_image.qt_image.height() + 140
)
self._main_layout = QtWidgets.QVBoxLayout(self)
# Add top layout
self._top_layout = self._create_top_layout()
self._main_layout.addLayout(self._top_layout)
# Add image layout
self._image_layout_outer = self._create_image_layout()
self._main_layout.addLayout(self._image_layout_outer)
# Add bottom layout
self._bottom_layout = self._create_bottom_layout()
self._main_layout.addLayout(self._bottom_layout)
# Move focus away from the line edits
self._restart_image_label.setFocus()
def _create_top_layout(self):
self._top_layout = QtWidgets.QHBoxLayout()
# Create Image Label to act as a button
self._restart_image_label = QtWidgets.QLabel()
self._restart_image_label.setPixmap(
QtGui.QPixmap(
os.path.join(conf.RESOURCE_DIR, 'happy_48.png')
)
)
self._marked_mines_lcd = QtWidgets.QLCDNumber()
self._marked_mines_lcd.display('000')
self._marked_mines_lcd.setDigitCount(3)
self._marked_mines_lcd.setSegmentStyle(QtWidgets.QLCDNumber.Flat)
self._marked_mines_lcd.setStyleSheet(
"color: red;"
f"background-color: rgb{imager.COLOR.gray_50};"
"border: none;"
)
self._timer_lcd = QtWidgets.QLCDNumber()
self._timer_lcd.display('000')
self._timer_lcd.setDigitCount(3)
self._timer_lcd.setSegmentStyle(QtWidgets.QLCDNumber.Flat)
self._timer_lcd.setStyleSheet(
"color: red;"
f"background-color: rgb{imager.COLOR.gray_50};"
"border: none;"
)
self._top_layout.addWidget(self._marked_mines_lcd, 1)
self._top_layout.addWidget(self._restart_image_label)
self._top_layout.addWidget(self._timer_lcd, 1)
return self._top_layout
def _create_image_layout(self):
self._image_layout_inner = QtWidgets.QHBoxLayout()
# Create Pixmap
self._pixmap = QtGui.QPixmap.fromImage(self._board_image.qt_image)
# Create Label and add the pixmap
self._image_label = QtWidgets.QLabel()
self._image_label.setPixmap(self._pixmap)
self._image_label.setMinimumWidth(self._board_image.qt_image.width())
self._image_label.setMinimumHeight(self._board_image.qt_image.height())
self._image_label.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor)
)
# Create an innner layout to prohibit horizontal stretching of the
# image label
self._image_layout_inner.addWidget(self._image_label)
# Adding a spacer to the right of the label to make sure that the
# image label does not stretch otherwise we cannot get the right
# mouse position to pick the pixel
self._image_layout_inner.addStretch(1)
# Create an outer layout to prohibit the vertical stretching
# of the image label
self._image_layout_outer = QtWidgets.QVBoxLayout()
self._image_layout_outer.addLayout(self._image_layout_inner)
# Adding a spacer to the bottom of the label to make sure that the
# image label does not stretch otherwise we cannot get the right
# mouse position to pick the pixel
self._image_layout_outer.addStretch(1)
return self._image_layout_outer
def _create_bottom_layout(self):
self._bottom_layout = QtWidgets.QHBoxLayout()
self._fields_label = QtWidgets.QLabel("Fields")
font = self._fields_label.font()
font.setPointSize(18)
self._fields_label.setFont(font)
self._field_x_line_edit = QtWidgets.QLineEdit("9")
self._field_x_line_edit.setFixedHeight(32)
self._field_x_line_edit.setFixedWidth(32)
self._field_x_line_edit.setAlignment(QtCore.Qt.AlignCenter)
font = self._field_x_line_edit.font()
font.setPointSize(18)
self._field_x_line_edit.setFont(font)
self._x_label = QtWidgets.QLabel("X")
self._field_y_line_edit = QtWidgets.QLineEdit("9")
self._field_y_line_edit.setFixedHeight(32)
self._field_y_line_edit.setFixedWidth(32)
self._field_y_line_edit.setAlignment(QtCore.Qt.AlignCenter)
font = self._field_y_line_edit.font()
font.setPointSize(18)
self._field_y_line_edit.setFont(font)
self._mines_label = QtWidgets.QLabel("Mines")
font = self._mines_label.font()
font.setPointSize(18)
self._mines_label.setFont(font)
self._fields_label.setFont(font)
self._mines_line_edit = QtWidgets.QLineEdit("10")
self._mines_line_edit.setFixedHeight(32)
self._mines_line_edit.setFixedWidth(32)
self._mines_line_edit.setAlignment(QtCore.Qt.AlignCenter)
font = self._mines_line_edit.font()
font.setPointSize(18)
self._mines_line_edit.setFont(font)
self._bottom_layout.addWidget(self._fields_label)
self._bottom_layout.addWidget(self._field_x_line_edit)
self._bottom_layout.addWidget(self._x_label)
self._bottom_layout.addWidget(self._field_y_line_edit)
self._bottom_layout.addStretch(1)
self._bottom_layout.addWidget(self._mines_label)
self._bottom_layout.addWidget(self._mines_line_edit)
return self._bottom_layout
def _connect_signals(self):
self._restart_image_label.mousePressEvent = self._restart
self._image_label.mousePressEvent = self._on_image_clicked
self._timer.timeout.connect(self._on_timer_timeout)
self._ac.UPDATE_SIGNAL.connect(self._update_image_label)
self._ac.DONE_SIGNAL.connect(self._anim_done)
def _on_timer_timeout(self):
self._time += 1
self._timer_lcd.display(str(self._time).zfill(3))
def _restart(self, event=None):
try:
width = int(self._field_x_line_edit.text())
height = int(self._field_y_line_edit.text())
nb_mines = int(self._mines_line_edit.text())
args = (width, height, nb_mines)
except ValueError:
error_msg = 'Fields, Mines can only be valid numbers!'
msg_box = QtWidgets.QErrorMessage(parent=self)
msg_box.showMessage(error_msg)
return
min_cells, max_cells = self._board.MIN_CELLS, self._board.MAX_CELLS
invalid_width = not(min_cells <= width <= max_cells)
invalid_height = not(min_cells <= height <= max_cells)
if invalid_width or invalid_height:
error_msg = (
f'Fields should be between '
f'{min_cells} and {max_cells}!')
msg_box = QtWidgets.QErrorMessage(parent=self)
msg_box.showMessage(error_msg)
return
self._marked_mines_lcd.display(str(nb_mines).zfill(3))
self._restart_image_label.setPixmap(
QtGui.QPixmap(
os.path.join(conf.RESOURCE_DIR, 'happy_48.png')
)
)
self._restart_image_label.setFocus()
self._time = 0
self._timer.stop()
self._timer_lcd.display(str(self._time).zfill(3))
self._last_swept = []
self.NEW_GAME_SIGNAL.emit(args)
def _on_image_clicked(self, event):
if not self._timer.isActive():
self._timer.start(1000)
selected_cell = self._board_image.pixel_to_slot(event.x(), event.y())
if selected_cell is None:
return
button = event.button()
if button == QtCore.Qt.MouseButton.RightButton:
signal = self.CELL_FLAGGED_SIGNAL
else:
signal = self.CELL_SELECTED_SIGNAL
signal.emit(selected_cell)
def refresh(self, board, init_image=True):
self._board = board
if init_image:
self._board_image.init_image(self._board)
self._image_label.setMinimumWidth(self._board_image.qt_image.width())
self._image_label.setMinimumHeight(self._board_image.qt_image.height())
self.setFixedSize(
max(304, self._board_image.qt_image.width() + 40),
self._board_image.qt_image.height() + 140
)
remaining_mines = max(
0,
self._board.nb_mines - self._board.nb_flagged,
)
self._marked_mines_lcd.display(str(remaining_mines).zfill(3))
if self._last_swept != self._board.last_swept:
self._last_swept = self._board.last_swept
last_swept_cells = []
for slot in self._last_swept:
last_swept_cells.append(self._board.get_cell(slot))
self._ac.method = random.choice(list(animator.METHOD))
self._ac.reveal_cells(
cells=last_swept_cells,
fill=self._board_image.UNCOVERED_COLOR,
fill_from=self._board_image.COVERED_COLOR,
)
else:
self._update_image_label()
def _update_image_label(self):
self._pixmap = QtGui.QPixmap.fromImage(self._board_image.qt_image)
self._image_label.setPixmap(self._pixmap)
def _anim_done(self):
self._board_image.init_image(self._board)
self._update_image_label()
def game_over(self, board):
self.refresh(board=board)
self._timer.stop()
self._restart_image_label.setPixmap(
QtGui.QPixmap(
os.path.join(conf.RESOURCE_DIR, 'sad_48.png')
)
)
def game_solved(self, board):
self.refresh(board=board)
self._timer.stop()
self._restart_image_label.setPixmap(
QtGui.QPixmap(
os.path.join(conf.RESOURCE_DIR, 'shine_48.png')
)
)
| 36.246622 | 79 | 0.654208 | import os
import random
from . import imager, conf, animator
from .qt import BaseDialog, QtWidgets, QtCore, QtGui
class MainWidget(BaseDialog):
CELL_SELECTED_SIGNAL = QtCore.Signal(tuple)
CELL_FLAGGED_SIGNAL = QtCore.Signal(tuple)
NEW_GAME_SIGNAL = QtCore.Signal(tuple)
def __init__(self, parent=None):
super().__init__(parent=parent)
def init_board(self, board):
self._board = board
self._last_swept = self._board.last_swept
self._board_image = imager.BoardImage(self._board)
self._ac = animator.AnimController(board_image=self._board_image)
self._setup_ui()
self._timer = QtCore.QTimer()
self._time = 0
self._connect_signals()
def _setup_ui(self):
title = 'Minescrubber'
self.setWindowTitle(title)
self.setFixedSize(
max(304, self._board_image.qt_image.width() + 40),
self._board_image.qt_image.height() + 140
)
self._main_layout = QtWidgets.QVBoxLayout(self)
self._top_layout = self._create_top_layout()
self._main_layout.addLayout(self._top_layout)
self._image_layout_outer = self._create_image_layout()
self._main_layout.addLayout(self._image_layout_outer)
self._bottom_layout = self._create_bottom_layout()
self._main_layout.addLayout(self._bottom_layout)
self._restart_image_label.setFocus()
def _create_top_layout(self):
self._top_layout = QtWidgets.QHBoxLayout()
self._restart_image_label = QtWidgets.QLabel()
self._restart_image_label.setPixmap(
QtGui.QPixmap(
os.path.join(conf.RESOURCE_DIR, 'happy_48.png')
)
)
self._marked_mines_lcd = QtWidgets.QLCDNumber()
self._marked_mines_lcd.display('000')
self._marked_mines_lcd.setDigitCount(3)
self._marked_mines_lcd.setSegmentStyle(QtWidgets.QLCDNumber.Flat)
self._marked_mines_lcd.setStyleSheet(
"color: red;"
f"background-color: rgb{imager.COLOR.gray_50};"
"border: none;"
)
self._timer_lcd = QtWidgets.QLCDNumber()
self._timer_lcd.display('000')
self._timer_lcd.setDigitCount(3)
self._timer_lcd.setSegmentStyle(QtWidgets.QLCDNumber.Flat)
self._timer_lcd.setStyleSheet(
"color: red;"
f"background-color: rgb{imager.COLOR.gray_50};"
"border: none;"
)
self._top_layout.addWidget(self._marked_mines_lcd, 1)
self._top_layout.addWidget(self._restart_image_label)
self._top_layout.addWidget(self._timer_lcd, 1)
return self._top_layout
def _create_image_layout(self):
self._image_layout_inner = QtWidgets.QHBoxLayout()
self._pixmap = QtGui.QPixmap.fromImage(self._board_image.qt_image)
self._image_label = QtWidgets.QLabel()
self._image_label.setPixmap(self._pixmap)
self._image_label.setMinimumWidth(self._board_image.qt_image.width())
self._image_label.setMinimumHeight(self._board_image.qt_image.height())
self._image_label.setCursor(
QtGui.QCursor(QtCore.Qt.PointingHandCursor)
)
self._image_layout_inner.addWidget(self._image_label)
self._image_layout_inner.addStretch(1)
self._image_layout_outer = QtWidgets.QVBoxLayout()
self._image_layout_outer.addLayout(self._image_layout_inner)
self._image_layout_outer.addStretch(1)
return self._image_layout_outer
def _create_bottom_layout(self):
self._bottom_layout = QtWidgets.QHBoxLayout()
self._fields_label = QtWidgets.QLabel("Fields")
font = self._fields_label.font()
font.setPointSize(18)
self._fields_label.setFont(font)
self._field_x_line_edit = QtWidgets.QLineEdit("9")
self._field_x_line_edit.setFixedHeight(32)
self._field_x_line_edit.setFixedWidth(32)
self._field_x_line_edit.setAlignment(QtCore.Qt.AlignCenter)
font = self._field_x_line_edit.font()
font.setPointSize(18)
self._field_x_line_edit.setFont(font)
self._x_label = QtWidgets.QLabel("X")
self._field_y_line_edit = QtWidgets.QLineEdit("9")
self._field_y_line_edit.setFixedHeight(32)
self._field_y_line_edit.setFixedWidth(32)
self._field_y_line_edit.setAlignment(QtCore.Qt.AlignCenter)
font = self._field_y_line_edit.font()
font.setPointSize(18)
self._field_y_line_edit.setFont(font)
self._mines_label = QtWidgets.QLabel("Mines")
font = self._mines_label.font()
font.setPointSize(18)
self._mines_label.setFont(font)
self._fields_label.setFont(font)
self._mines_line_edit = QtWidgets.QLineEdit("10")
self._mines_line_edit.setFixedHeight(32)
self._mines_line_edit.setFixedWidth(32)
self._mines_line_edit.setAlignment(QtCore.Qt.AlignCenter)
font = self._mines_line_edit.font()
font.setPointSize(18)
self._mines_line_edit.setFont(font)
self._bottom_layout.addWidget(self._fields_label)
self._bottom_layout.addWidget(self._field_x_line_edit)
self._bottom_layout.addWidget(self._x_label)
self._bottom_layout.addWidget(self._field_y_line_edit)
self._bottom_layout.addStretch(1)
self._bottom_layout.addWidget(self._mines_label)
self._bottom_layout.addWidget(self._mines_line_edit)
return self._bottom_layout
def _connect_signals(self):
self._restart_image_label.mousePressEvent = self._restart
self._image_label.mousePressEvent = self._on_image_clicked
self._timer.timeout.connect(self._on_timer_timeout)
self._ac.UPDATE_SIGNAL.connect(self._update_image_label)
self._ac.DONE_SIGNAL.connect(self._anim_done)
def _on_timer_timeout(self):
self._time += 1
self._timer_lcd.display(str(self._time).zfill(3))
def _restart(self, event=None):
try:
width = int(self._field_x_line_edit.text())
height = int(self._field_y_line_edit.text())
nb_mines = int(self._mines_line_edit.text())
args = (width, height, nb_mines)
except ValueError:
error_msg = 'Fields, Mines can only be valid numbers!'
msg_box = QtWidgets.QErrorMessage(parent=self)
msg_box.showMessage(error_msg)
return
min_cells, max_cells = self._board.MIN_CELLS, self._board.MAX_CELLS
invalid_width = not(min_cells <= width <= max_cells)
invalid_height = not(min_cells <= height <= max_cells)
if invalid_width or invalid_height:
error_msg = (
f'Fields should be between '
f'{min_cells} and {max_cells}!')
msg_box = QtWidgets.QErrorMessage(parent=self)
msg_box.showMessage(error_msg)
return
self._marked_mines_lcd.display(str(nb_mines).zfill(3))
self._restart_image_label.setPixmap(
QtGui.QPixmap(
os.path.join(conf.RESOURCE_DIR, 'happy_48.png')
)
)
self._restart_image_label.setFocus()
self._time = 0
self._timer.stop()
self._timer_lcd.display(str(self._time).zfill(3))
self._last_swept = []
self.NEW_GAME_SIGNAL.emit(args)
def _on_image_clicked(self, event):
if not self._timer.isActive():
self._timer.start(1000)
selected_cell = self._board_image.pixel_to_slot(event.x(), event.y())
if selected_cell is None:
return
button = event.button()
if button == QtCore.Qt.MouseButton.RightButton:
signal = self.CELL_FLAGGED_SIGNAL
else:
signal = self.CELL_SELECTED_SIGNAL
signal.emit(selected_cell)
def refresh(self, board, init_image=True):
self._board = board
if init_image:
self._board_image.init_image(self._board)
self._image_label.setMinimumWidth(self._board_image.qt_image.width())
self._image_label.setMinimumHeight(self._board_image.qt_image.height())
self.setFixedSize(
max(304, self._board_image.qt_image.width() + 40),
self._board_image.qt_image.height() + 140
)
remaining_mines = max(
0,
self._board.nb_mines - self._board.nb_flagged,
)
self._marked_mines_lcd.display(str(remaining_mines).zfill(3))
if self._last_swept != self._board.last_swept:
self._last_swept = self._board.last_swept
last_swept_cells = []
for slot in self._last_swept:
last_swept_cells.append(self._board.get_cell(slot))
self._ac.method = random.choice(list(animator.METHOD))
self._ac.reveal_cells(
cells=last_swept_cells,
fill=self._board_image.UNCOVERED_COLOR,
fill_from=self._board_image.COVERED_COLOR,
)
else:
self._update_image_label()
def _update_image_label(self):
self._pixmap = QtGui.QPixmap.fromImage(self._board_image.qt_image)
self._image_label.setPixmap(self._pixmap)
def _anim_done(self):
self._board_image.init_image(self._board)
self._update_image_label()
def game_over(self, board):
self.refresh(board=board)
self._timer.stop()
self._restart_image_label.setPixmap(
QtGui.QPixmap(
os.path.join(conf.RESOURCE_DIR, 'sad_48.png')
)
)
def game_solved(self, board):
self.refresh(board=board)
self._timer.stop()
self._restart_image_label.setPixmap(
QtGui.QPixmap(
os.path.join(conf.RESOURCE_DIR, 'shine_48.png')
)
)
| true | true |
f72f3b30d80ddaeb33b04d28e7f95a0cabbea8cd | 2,075 | py | Python | integrations/tensorflow/e2e/broadcasting_test.py | BernhardRiemann/iree | 471349762b316f7d6b83eb5f9089255d78052758 | [
"Apache-2.0"
] | 1 | 2021-03-15T13:53:30.000Z | 2021-03-15T13:53:30.000Z | integrations/tensorflow/e2e/broadcasting_test.py | BernhardRiemann/iree | 471349762b316f7d6b83eb5f9089255d78052758 | [
"Apache-2.0"
] | null | null | null | integrations/tensorflow/e2e/broadcasting_test.py | BernhardRiemann/iree | 471349762b316f7d6b83eb5f9089255d78052758 | [
"Apache-2.0"
] | null | null | null | # Lint as: python3
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test broadcasting support."""
from absl import app
import numpy as np
from pyiree.tf.support import tf_test_utils
from pyiree.tf.support import tf_utils
import tensorflow.compat.v2 as tf
class BroadcastingModule(tf.Module):
@tf.function(input_signature=[
tf.TensorSpec([None], tf.float32),
tf.TensorSpec([None], tf.float32),
])
def add(self, lhs, rhs):
return lhs + rhs
class BroadcastingTest(tf_test_utils.TracedModuleTestCase):
def __init__(self, methodName="runTest"):
super(BroadcastingTest, self).__init__(methodName)
self._modules = tf_test_utils.compile_tf_module(BroadcastingModule)
def test_add_same_shape(self):
def add_same_shape(module):
lhs = tf_utils.uniform([4])
rhs = tf_utils.uniform([4])
module.add(lhs, rhs)
self.compare_backends(add_same_shape, self._modules)
def test_add_broadcast_lhs(self):
def add_broadcast_lhs(module):
lhs = tf_utils.uniform([1])
rhs = tf_utils.uniform([4])
module.add(lhs, rhs)
self.compare_backends(add_broadcast_lhs, self._modules)
def test_add_broadcast_rhs(self):
def add_broadcast_rhs(module):
lhs = tf_utils.uniform([4])
rhs = tf_utils.uniform([1])
module.add(lhs, rhs)
self.compare_backends(add_broadcast_rhs, self._modules)
def main(argv):
del argv # Unused
if hasattr(tf, 'enable_v2_behavior'):
tf.enable_v2_behavior()
tf.test.main()
if __name__ == '__main__':
app.run(main)
| 26.948052 | 74 | 0.723855 |
from absl import app
import numpy as np
from pyiree.tf.support import tf_test_utils
from pyiree.tf.support import tf_utils
import tensorflow.compat.v2 as tf
class BroadcastingModule(tf.Module):
@tf.function(input_signature=[
tf.TensorSpec([None], tf.float32),
tf.TensorSpec([None], tf.float32),
])
def add(self, lhs, rhs):
return lhs + rhs
class BroadcastingTest(tf_test_utils.TracedModuleTestCase):
def __init__(self, methodName="runTest"):
super(BroadcastingTest, self).__init__(methodName)
self._modules = tf_test_utils.compile_tf_module(BroadcastingModule)
def test_add_same_shape(self):
def add_same_shape(module):
lhs = tf_utils.uniform([4])
rhs = tf_utils.uniform([4])
module.add(lhs, rhs)
self.compare_backends(add_same_shape, self._modules)
def test_add_broadcast_lhs(self):
def add_broadcast_lhs(module):
lhs = tf_utils.uniform([1])
rhs = tf_utils.uniform([4])
module.add(lhs, rhs)
self.compare_backends(add_broadcast_lhs, self._modules)
def test_add_broadcast_rhs(self):
def add_broadcast_rhs(module):
lhs = tf_utils.uniform([4])
rhs = tf_utils.uniform([1])
module.add(lhs, rhs)
self.compare_backends(add_broadcast_rhs, self._modules)
def main(argv):
del argv
if hasattr(tf, 'enable_v2_behavior'):
tf.enable_v2_behavior()
tf.test.main()
if __name__ == '__main__':
app.run(main)
| true | true |
f72f3cd14665268a7017d487decd2770a51a8acf | 42,710 | py | Python | tests/tx_test.py | iterumllc/afdko | 42ad89290a42015dcdf2dfd778d826e928bf9b9b | [
"Apache-2.0"
] | null | null | null | tests/tx_test.py | iterumllc/afdko | 42ad89290a42015dcdf2dfd778d826e928bf9b9b | [
"Apache-2.0"
] | null | null | null | tests/tx_test.py | iterumllc/afdko | 42ad89290a42015dcdf2dfd778d826e928bf9b9b | [
"Apache-2.0"
] | null | null | null | import os
import pytest
import re
import subprocess
import time
from afdko.fdkutils import (
get_temp_file_path,
get_temp_dir_path,
)
from test_utils import (
get_input_path,
get_bad_input_path,
get_expected_path,
generate_ps_dump,
)
from runner import main as runner
from differ import main as differ, SPLIT_MARKER
TOOL = 'tx'
CMD = ['-t', TOOL]
def _get_extension(in_format):
if 'ufo' in in_format:
return '.ufo'
elif in_format == 'type1':
return '.pfa'
return '.' + in_format
PDF_SKIP = [
'/Creator' + SPLIT_MARKER +
'/Producer' + SPLIT_MARKER +
'/CreationDate' + SPLIT_MARKER +
'/ModDate' + SPLIT_MARKER +
'(Date:' + SPLIT_MARKER +
'(Time:',
]
PDF_SKIP_REGEX = [
'^.+30.00 Td',
'^.+0.00 Td',
]
PS_SKIP = [
'0 740 moveto (Filename:' + SPLIT_MARKER +
'560 (Date:' + SPLIT_MARKER +
'560 (Time:'
]
PS_SKIP2 = [
'%ADOt1write:'
]
PFA_SKIP = [
'%ADOt1write:' + SPLIT_MARKER +
'%%Copyright:' + SPLIT_MARKER
]
# -----------
# Basic tests
# -----------
@pytest.mark.parametrize('arg', ['-h', '-v', '-u'])
def test_exit_known_option(arg):
assert subprocess.call([TOOL, arg]) == 0
@pytest.mark.parametrize('arg', ['-bar', '-foo'])
def test_exit_unknown_option(arg):
assert subprocess.call([TOOL, arg]) == 1
@pytest.mark.parametrize('pth', [
['invalid_path'], # no such file or directory
[get_temp_file_path()], # end of file (not a font)
[get_input_path('type1.pfa'), 'a', 'b'], # too many file args
])
def test_exit_invalid_path_or_font(pth):
assert subprocess.call([TOOL] + pth) == 1
# -------------
# Options tests
# -------------
@pytest.mark.parametrize('args', [
['-s', '-t1'], # '-s' option must be last
['-t1', '-g', '0', '-gx', '1'], # options are mutually exclusive
['-dcf'], # non-CFF font
['-ps', '-1'], # must specify an all-glyph range
['-ufo'], ['-t1', '-pfb'], # must specify a destination path
['-t1', '-usefd'], # bad arg
['-t1', '-decid'], # input font is non-CID
])
def test_option_error_type1_input(args):
font_path = get_input_path('type1.pfa')
assert subprocess.call([TOOL] + args + [font_path]) == 1
@pytest.mark.parametrize('arg', ['-e', '-q', '+q', '-w', '+w', '-lf', '-cr',
'-crlf', '-decid', '-LWFN', '-pfb'])
def test_option_error_type1_clash(arg):
# options -pfb or -LWFN may not be used with other options
pfb = '-pfb' if arg != '-pfb' else '-LWFN'
assert subprocess.call([TOOL, '-t1', pfb, arg]) == 1
@pytest.mark.parametrize('args', [
['-cff', '-l'], ['-cff', '-0'], ['-cff', '-1'], ['-cff', '-2'],
['-cff', '-3'], ['-cff', '-4'], ['-cff', '-5'], ['-cff', '-6'],
['-cff', '-q'], ['-cff', '+q'], ['-cff', '-w'], ['-cff', '+w'],
['-cff', '-pfb'], ['-cff', '-usefd'], ['-cff', '-decid'],
['-cff', '-lf'], ['-cff', '-cr'], ['-cff', '-crlf'], ['-cff', '-LWFN'],
['-t1', '-gn0'], ['-t1', '-gn1'], ['-t1', '-gn2'], ['-t1', '-sa'],
['-t1', '-abs'], ['-t1', '-cefsvg'],
['-t1', '-no_futile'], ['-t1', '-no_opt'], ['-t1', '-d'], ['-t1', '+d'],
['-dcf', '-n'], ['-dcf', '-c'],
['-dump', '-E'], ['-dump', '+E'], ['-dump', '-F'], ['-dump', '+F'],
['-dump', '-O'], ['-dump', '+O'], ['-dump', '-S'], ['-dump', '+S'],
['-dump', '-T'], ['-dump', '+T'], ['-dump', '-V'], ['-dump', '+V'],
['-dump', '-b'], ['-dump', '+b'], ['-dump', '-e'], ['-dump', '+e'],
['-dump', '-Z'], ['-dump', '+Z'],
])
def test_option_error_wrong_mode(args):
assert subprocess.call([TOOL] + args) == 1
@pytest.mark.parametrize('arg', [
'-a', '-e', '-f', '-g', '-i', '-m', '-o', '-p', '-A', '-P', '-U', '-maxs',
'-usefd', '-fd', '-dd', '-sd', '-sr', ['-cef', '-F'], ['-dcf', '-T']
])
def test_option_error_no_args_left(arg):
if isinstance(arg, list):
arg_lst = [TOOL] + arg
else:
arg_lst = [TOOL, '-t1', arg]
assert subprocess.call(arg_lst) == 1
@pytest.mark.parametrize('args', [
['-maxs', 'X'], ['-m', 'X'], ['-e', 'X'], ['-e', '5'],
['-usefd', 'X'], ['-usefd', '-1']
])
def test_option_error_bad_arg(args):
assert subprocess.call([TOOL, '-t1'] + args) == 1
@pytest.mark.parametrize('arg2', ['-sd', '-sr', '-dd'])
@pytest.mark.parametrize('arg1', ['-a', '-f', '-A'])
def test_option_error_no_args_left2(arg1, arg2):
assert subprocess.call([TOOL, '-t1', arg1, arg2]) == 1
@pytest.mark.parametrize('arg2', ['-sd', '-sr', '-dd'])
@pytest.mark.parametrize('arg1', ['-a', '-f'])
def test_option_error_empty_list(arg1, arg2):
empty_dir = get_temp_dir_path()
assert subprocess.call([TOOL, '-t1', arg1, arg2, empty_dir]) == 1
@pytest.mark.parametrize('arg', ['-bc', '-z', '-cmp', '-sha1'])
def test_gone_options_bc(arg):
assert subprocess.call([TOOL, arg]) == 1
@pytest.mark.parametrize('mode, msg', [
('-h', b'tx (Type eXchange) is a test harness'),
('-u', b'tx {[mode][mode options][shared options][files]}*'),
('-afm', b'[-afm options: default none]'),
('-cef', b'[-cef options: default none]'),
('-cff', b'[-cff options: defaults -E, -F, -O, -S, +T, -V, -Z, -b, -d]'),
('-cff2', b'[-cff2 options: defaults -S, -b]'),
('-dcf', b'[-dcf options: defaults -T all, -5]'),
('-dump', b'[-dump options: default -1]'),
('-mtx', b'[-mtx options: default -0]'),
('-path', b'[-path options: default -0]'),
('-pdf', b'[-pdf options: default -0]'),
('-ps', b'[-ps options: default -0]'),
('-svg', b'[-svg options: defaults -lf, -gn0]'),
('-t1',
b'[-t1 options: defaults -0, -l, -E, -S, +T, -V, +q, -w, -e 4, -lf]'),
('-ufo', b'[-ufo options: default none]'),
])
def test_mode_help(mode, msg):
output = subprocess.check_output([TOOL, mode, '-h'])
assert msg in output
@pytest.mark.parametrize('dcf_dump_level', ['0', '1', '5'])
def test_script_file(dcf_dump_level):
font_path = get_input_path('cid.otf')
opts_path = get_temp_file_path()
opts_file_content = f'\n# foo\n # bar\r -{dcf_dump_level}\t"{font_path}"'
with open(opts_path, 'a') as fp:
fp.write(opts_file_content)
actual_path = runner(CMD + ['-s', '-a', '-o', 'dcf', 's', '-f', opts_path])
expected_path = get_expected_path(f'cid_dcf_{dcf_dump_level}.txt')
assert differ([expected_path, actual_path])
def test_nested_script():
# nested scripts not allowed
temp_path = get_temp_file_path()
assert subprocess.call([TOOL, '-s', 'foobar', '-s', temp_path]) == 1
@pytest.mark.parametrize('layer_name', ['', 'None', 'background', 'foobar'])
def test_ufo_altlayer(layer_name):
if not layer_name:
fname = 'processed'
args = []
else:
fname = 'foreground' if layer_name == 'None' else layer_name
args = ['altLayer', f'_{fname}']
actual_path = runner(CMD + ['-s', '-f', 'altlayer.ufo', '-o', '6'] + args)
expected_path = get_expected_path(f'altlayer_{fname}.txt')
assert differ([expected_path, actual_path])
@pytest.mark.parametrize('arg, filename', [
('-a', 'ufo3.t1'),
('-A', 'SourceSansPro-Regular.t1'),
])
def test_a_options(arg, filename):
input_path = get_input_path('ufo3.ufo')
output_path = os.path.join(os.getcwd(), filename)
assert os.path.exists(output_path) is False
subprocess.call([TOOL, '-t1', arg, input_path])
assert os.path.exists(output_path) is True
os.remove(output_path)
def test_o_option():
input_path = get_input_path('ufo3.ufo')
expected_path = get_expected_path('ufo3.pfa')
output_path = get_temp_file_path()
subprocess.call([TOOL, '-t1', '-o', output_path, input_path])
assert differ([expected_path, output_path, '-s', PFA_SKIP[0]])
def test_f_option():
fpath1 = get_input_path('type1.pfa')
fpath2 = get_input_path('cff2_vf.otf')
actual_path = runner(CMD + ['-s', '-o', 'mtx', '3',
'f', f'_{fpath1}', f'_{fpath2}'])
expected_path = get_expected_path('mtx_f_options.txt')
assert differ([expected_path, actual_path])
def test_stdin():
input_path = get_input_path('type1.pfa')
expected_path = get_expected_path('stdin.txt')
output_path = get_temp_file_path()
with open(input_path) as fp:
output = subprocess.check_output([TOOL], stdin=fp)
with open(output_path, 'wb') as fp:
fp.write(output)
assert differ([expected_path, output_path])
@pytest.mark.parametrize('arg', ['0', '-16'])
def test_m_option_success(arg):
# mem_manage() is called 16 times with the command 'tx -m 0 type1.pfa'
input_path = get_input_path('type1.pfa')
assert subprocess.call([TOOL, '-m', arg, input_path]) == 0
# Disabled because of https://github.com/adobe-type-tools/afdko/issues/933
# @pytest.mark.parametrize('arg', range(1, 16))
# def test_m_option_fail(arg):
# input_path = get_input_path('type1.pfa')
# assert subprocess.call([TOOL, '-m', f'-{arg}', input_path]) != 0
@pytest.mark.parametrize('arg, exp_filename', [(None, 'not_removed'),
('-V', 'not_removed'),
('+V', 'removed')])
def test_V_option(arg, exp_filename):
input_path = get_input_path('overlap.pfa')
expected_path = get_expected_path(f'overlap_{exp_filename}.pfa')
output_path = get_temp_file_path()
args = [TOOL, '-t1', '-o', output_path, input_path]
if arg:
args.insert(2, arg)
subprocess.call(args)
assert differ([expected_path, output_path] + ['-s'] + PFA_SKIP)
# -------------
# Convert tests
# -------------
@pytest.mark.parametrize('to_format', [
'ufo2',
'ufo3',
'type1',
'svg',
'mtx',
'afm',
'pdf',
'ps',
'cff',
])
@pytest.mark.parametrize('from_format', [
'ufo2',
'ufo3',
'type1',
])
def test_convert(from_format, to_format):
from_ext = _get_extension(from_format)
to_ext = _get_extension(to_format)
# input filename
from_filename = from_format + from_ext
# expected filename
exp_filename = from_format + to_ext
# runner args
if 'ufo' in to_format:
save_path = get_temp_dir_path('font.ufo')
else:
save_path = get_temp_file_path()
# diff mode
if to_format == 'cff':
diff_mode = ['-m', 'bin']
else:
diff_mode = []
# skip items
regex_skip = []
skip = []
if to_format == 'afm':
skip = ['Comment Creation Date:' + SPLIT_MARKER + 'Comment Copyright']
elif to_format == 'pdf':
skip = PDF_SKIP[:]
regex_skip = PDF_SKIP_REGEX[:]
elif to_format == 'ps':
skip = PS_SKIP[:]
elif to_format == 'type1':
skip = PFA_SKIP[:]
if skip:
skip.insert(0, '-s')
if regex_skip:
for regex in regex_skip:
skip.append('-r')
skip.append(regex)
# format arg fix
if to_format in ('ufo2', 'ufo3'):
format_arg = 'ufo'
elif to_format == 'type1':
format_arg = 't1'
else:
format_arg = to_format
runner(CMD + ['-a', '-f', get_input_path(from_filename), save_path,
'-o', format_arg])
expected_path = get_expected_path(exp_filename)
assert differ([expected_path, save_path] + skip + diff_mode)
def test_cef_cefsvg():
font_path = get_input_path('cff2_vf.otf')
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'cef', 'cefsvg', 'cr', 'gn1', 'abs', 'sa',
'-f', font_path, output_path])
expected_path = get_expected_path('cef_cefsvg_cr.svg')
assert differ([expected_path, output_path])
@pytest.mark.parametrize('file_ext', [
'pfa', 'pfabin', 'pfb', 'lwfn', 'bidf']) # TODO: 'bidf85'
def test_type1_inputs(file_ext):
bidf = '.bidf' if 'bidf' in file_ext else ''
actual_path = runner(CMD + ['-s', '-o', '2', '-f', f'type1.{file_ext}'])
expected_path = get_expected_path(f'type1.dump2{bidf}.txt')
assert differ([expected_path, actual_path, '-s', '## Filename'])
@pytest.mark.parametrize('args', [[], ['U', '_500,500'], ['U', '_0,0', 'n']])
@pytest.mark.parametrize('fname', ['zx', 'zy'])
def test_type1mm_inputs(fname, args):
fname2 = f'.{"".join(args)}' if args else ''
actual_path = runner(CMD + ['-s', '-f', f'{fname}.pfb', '-o', '2'] + args)
expected_path = get_expected_path(f'{fname}.dump2{fname2}.txt')
assert differ([expected_path, actual_path, '-s', '## Filename'])
@pytest.mark.parametrize('fext', ['otf', 'ttf', 'cff', 'cef', 'ttc'])
def test_other_input_formats(fext):
arg = ['y'] if fext == 'ttc' else []
actual_path = runner(CMD + ['-s', '-f', f'font.{fext}', '-o', '3'] + arg)
expected_path = get_expected_path(f'font.{fext}.dump3.txt')
assert differ([expected_path, actual_path, '-s', '## Filename'])
# ----------
# Dump tests
# ----------
@pytest.mark.parametrize('args', [
[],
['0'],
['dump', '0'],
['1'],
['2'],
['3'],
['4'],
['4', 'N'],
['5'],
['6'],
['6', 'd'],
['6', 'n'],
])
@pytest.mark.parametrize('font_filename', ['type1.pfa', 'svg.svg'])
def test_dump_option(args, font_filename):
if any([arg in args for arg in ('4', '5', '6')]):
skip = []
else:
skip = ['-s', '## Filename']
head = font_filename.split('.')[0]
midl = ''.join(args) if args else 'dump1'
if 'dump' not in midl:
midl = f'dump{midl}'
exp_filename = f'{head}.{midl}.txt'
opts = ['-o'] + args if args else []
actual_path = runner(CMD + ['-s', '-f', font_filename] + opts)
expected_path = get_expected_path(exp_filename)
assert differ([expected_path, actual_path] + skip)
@pytest.mark.parametrize('fext', ['pfa', 'ufo'])
def test_dump_flex_op(fext):
fname = 'flex'
actual_path = runner(CMD + ['-s', '-o', '6', '-f', f'{fname}.{fext}'])
expected_path = get_expected_path(f'{fname}.txt')
assert differ([expected_path, actual_path])
# ----------
# CFF2 tests
# ----------
@pytest.mark.parametrize('filename, msg', [
('avar_invalid_table_version',
b'(cfr) invalid avar table version'),
('fvar_invalid_table_version',
b'(cfr) invalid fvar table version'),
('avar_invalid_table_size',
b'(cfr) invalid avar table size'),
('fvar_invalid_table_size',
b'(cfr) invalid fvar table size'),
('fvar_invalid_table_header',
b'(cfr) invalid values in fvar table header'),
('avar_invalid_axis-instance_count-size',
b'(cfr) invalid avar table size or axis/instance count/size'),
('fvar_invalid_axis-instance_count-size',
b'(cfr) invalid fvar table size or axis/instance count/size'),
('avar_axis_value_map_out_of_bounds',
b'(cfr) avar axis value map out of bounds'),
('avar_fvar_axis_mismatch',
b'(cfr) mismatching axis counts in fvar and avar'),
])
def test_varread_errors(filename, msg):
font_path = get_bad_input_path(f'vf_{filename}.otf')
output = subprocess.check_output([TOOL, '-dcf', '-0', font_path],
stderr=subprocess.STDOUT)
assert msg in output
@pytest.mark.parametrize('args, exp_filename', [
([], 'SourceCodeVar-Roman_CFF2'),
(['*S', '*b', 'std'], 'SourceCodeVar-Roman_CFF2_subr'), # subroutinize
])
def test_cff2_extract(args, exp_filename):
# read CFF2 VF, write CFF2 table
font_path = get_input_path('SourceCodeVariable-Roman.otf')
cff2_path = get_temp_file_path()
runner(CMD + ['-a', '-f', font_path, cff2_path, '-o', 'cff2'] + args)
expected_path = get_expected_path(exp_filename)
assert differ([expected_path, cff2_path, '-m', 'bin'])
def test_cff2_sub_dump():
# Dump a subroutinized CFF2 font. This is a J font with 64K glyphs,
# and almost every subr and charstring is a single subr call.
# A good test for problems with charstrings with no endchar operator.
actual_path = runner(CMD + ['-s', '-o', 'dump', '6', 'g', '_21847',
'-f', 'CFF2-serif-sub.cff2'])
expected_path = get_expected_path('CFF2-serif-sub.cff2.txt')
assert differ([expected_path, actual_path])
def test_varread_pr355():
# read CFF2 VF, write Type1 snapshot
# Note that cff2_vf is built from the sources at:
# afdko/tests/buildmasterotfs_data/input/cff2_vf.
actual_path = runner(CMD + ['-s', '-o', 't1', '-f', 'cff2_vf.otf'])
expected_path = get_expected_path('cff2_vf.pfa')
skip = ['-s'] + PFA_SKIP[:]
assert differ([expected_path, actual_path] + skip)
def test_cff2_no_vf_bug353():
# read CFF2 WITHOUT VF info, write a CFF2 out. 'regular_CFF2.otf'
# is derived by taking the regular.otf file from the sfntdiff
# 'input_data' directory, and converting the CFF table to CFF2.
font_path = get_input_path('regular_CFF2.otf')
cff2_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'cff2', '-f', font_path, cff2_path])
expected_path = get_expected_path('regular_CFF2.cff2')
assert differ([expected_path, cff2_path, '-m', 'bin'])
def test_cff2_with_spare_masters_pr835():
# SetNumMasters was incorrectly passing the number of region indices to
# var_getIVSRegionIndices for the regionListCount. With PR #835 it now
# passes the total region count for regionListCount.
#
# Example of the bug -- this command:
# tx -cff2 +S +b -std SHSansJPVFTest.otf SHSansJPVFTest.cff2
# Would produce the following warning & error:
# inconsistent region indices detected in item variation store subtable 1
# memory error
font_path = get_input_path('SHSansJPVFTest.otf')
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o',
'cff2', '*S', '*b', 'std',
'-f', font_path, output_path])
expected_path = get_expected_path('SHSansJPVFTest.cff2')
assert differ([expected_path, output_path, '-m', 'bin'])
@pytest.mark.parametrize('vector, exp_filename', [
('9999,9999,9999,9999,999,9', 'psname_last_resort_no.txt'),
('9999,9999,9999,9999,999,99', 'psname_last_resort_yes.txt'),
])
def test_last_resort_instance_psname(vector, exp_filename):
font_path = get_input_path('cff2_vf_many_axes.otf')
output_path = get_temp_file_path()
runner(CMD + ['-o', '0', 'U', f'_{vector}', '-f', font_path, output_path])
expected_path = get_expected_path(exp_filename)
assert differ([expected_path, output_path, '-s', '## Filename'])
# -----------
# Other tests
# -----------
def test_trademark_string_pr425():
# the copyright symbol used in the trademark field of a UFO is
# converted to 'Copyright' and stored in Notice field of a Type1
actual_path = runner(CMD + ['-s', '-o', 't1', '-f', 'trademark.ufo'])
expected_path = get_expected_path('trademark.pfa')
skip = ['-s'] + PFA_SKIP[:]
assert differ([expected_path, actual_path] + skip)
def test_remove_hints_bug180():
font_path = get_input_path('cid.otf')
cid_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 't1', 'n', '-f', font_path, cid_path])
expected_path = get_expected_path('cid_nohints.ps')
expected_path = generate_ps_dump(expected_path)
actual_path = generate_ps_dump(cid_path)
skip = ['-s'] + PS_SKIP2
assert differ([expected_path, actual_path] + skip)
def test_long_charstring_read_bug444():
# read a CFF2 VF with a charstring longer that 65535, check output
actual_path = runner(CMD + ['-s', '-o', '0', '-f', 'CJK-VarTest.otf'])
expected_path = get_expected_path('CJK-VarTest_read.txt')
assert differ([expected_path, actual_path, '-s', '## Filename'])
def test_long_charstring_warning():
# read a CFF2 VF with a charstring longer that 65535, check warning message
# NOTE: can't diff the output against 'CJK-VarTest_warn.txt' because on
# Windows the lines start with 'tx.exe:' instead of just 'tx:'
actual_path = runner(
CMD + ['-s', '-e', '-o', '5', '-f', 'CJK-VarTest.otf'])
# expected_path = get_expected_path('CJK-VarTest_warn.txt')
with open(actual_path, 'rb') as f:
output = f.read()
assert b"(cfr) Warning: CharString of GID 1 is 71057 bytes long" in output
def test_long_charstring_write():
# read a CFF2 VF with a charstring longer that 65535, write out CFF2 file
# NOTE: the font 'CJK-VarTest.otf' cannot be used in this test because
# once its long charstring is optimized (floats -> ints) it's no longer
# over the 65535 bytes limit; the long charstring in 'CJK-VarTest2.otf' is
# already as small as possible, so it will trigger the check in cffwrite.c
font_path = get_input_path('CJK-VarTest2.otf')
cff2_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'cff2', '-f', font_path, cff2_path])
expected_path = get_expected_path('CJK-VarTest2.cff2')
assert differ([expected_path, cff2_path, '-m', 'bin'])
def test_many_hints_string_bug354():
# The glyph T@gid002 has 33 hstem hints. This tests a bug where
# tx defined an array of only 6 operands.
# This is encountered only when wrinting to a VF CFF2.
font_path = get_input_path('cff2_vf.otf')
cff2_path = get_temp_file_path()
dcf_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'cff2', '-f', font_path, cff2_path])
runner(CMD + ['-a', '-o', 'dcf', '-f', cff2_path, dcf_path])
expected_path = get_expected_path('cff2_vf.dcf.txt')
assert differ([expected_path, dcf_path])
def test_non_varying_glyphs_bug356():
"""A glyph which is non-varying in a variable font may be referenced by a
VariationStore data item subtable which has a region count of 0. The VF
support code assumed that this was an error, and issued a false warning.
File 'bug356.otf' is a handcrafted modification of 'cff2_vf.otf'. The
latter cannot be used as-is to validate the fix."""
actual_path = get_temp_file_path()
font_path = get_input_path('bug356.otf')
stderr_path = runner(CMD + ['-s', '-e', '-a', '-o', 'cff',
'-f', font_path, actual_path])
expected_path = get_expected_path('bug356.txt')
assert differ([expected_path, stderr_path, '-l', '1'])
@pytest.mark.parametrize('font_format', ['type1', 'cidfont', 'ufo2', 'ufo3'])
def test_no_psname_dump_bug437(font_format):
if 'cid' in font_format:
file_ext = 'ps'
elif 'ufo' in font_format:
file_ext = 'ufo'
else:
file_ext = 'pfa'
filename = f'{font_format}-noPSname.{file_ext}'
expected_path = get_expected_path(f'bug437/dump-{font_format}.txt')
actual_path = runner(CMD + ['-s', '-o', 'dump', '0', '-f', filename])
assert differ([expected_path, actual_path, '-l', '1'])
@pytest.mark.parametrize('font_format', ['type1', 'cidfont', 'ufo2', 'ufo3'])
def test_no_psname_convert_to_ufo_bug437(font_format):
if 'cid' in font_format:
file_ext = 'ps'
elif 'ufo' in font_format:
file_ext = 'ufo'
else:
file_ext = 'pfa'
font_path = get_input_path(f'{font_format}-noPSname.{file_ext}')
expected_path = get_expected_path(f'bug437/{font_format}.ufo')
save_path = get_temp_dir_path(f'{font_format}.ufo')
runner(CMD + ['-a', '-o', 'ufo', '-f', font_path, save_path])
assert differ([expected_path, save_path])
@pytest.mark.parametrize('font_format', ['type1', 'cidfont', 'ufo2', 'ufo3'])
def test_no_psname_convert_to_type1_bug437(font_format):
if 'cid' in font_format:
file_ext = 'ps'
elif 'ufo' in font_format:
file_ext = 'ufo'
else:
file_ext = 'pfa'
filename = f'{font_format}-noPSname.{file_ext}'
with pytest.raises(subprocess.CalledProcessError) as err:
runner(CMD + ['-o', 't1', '-f', filename])
assert err.value.returncode in (5, 6)
def test_illegal_chars_in_glyph_name_bug473():
font_path = get_input_path('bug473.ufo')
save_path = get_temp_dir_path('bug473.ufo')
runner(CMD + ['-a', '-o', 'ufo', '-f', font_path, save_path])
expected_path = get_expected_path('bug473.ufo')
assert differ([expected_path, save_path])
def test_subroutine_sorting_bug494():
""" The input file was made with the command:
tx -t1 -g 0-5 \
source-serif-pro/Roman/Instances/Regular/font.ufo bug494.pfa
The bug is that two subroutines in the Windows CFF output are swapped in
index order from the Mac version. This was because of an unstable
'qsort' done on the subroutines in the final stage of selection."""
font_path = get_input_path('bug494.pfa')
cff_path = get_temp_file_path()
dcf_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'cff', '*S', 'std', '*b',
'-f', font_path, cff_path])
runner(CMD + ['-a', '-o', 'dcf', '-f', cff_path, dcf_path])
expected_path = get_expected_path('bug494.dcf.txt')
assert differ([expected_path, dcf_path])
@pytest.mark.parametrize('args, exp_filename', [([], 'roundtrip'),
(['g', '_0-1'], 'subset')])
@pytest.mark.parametrize('to_format', ['t1', 'cff', 'afm'])
def test_recalculate_font_bbox_bug618(to_format, args, exp_filename):
font_path = get_input_path('bug618.pfa')
save_path = get_temp_file_path()
runner(CMD + ['-f', font_path, save_path, '-o', to_format] + args)
file_ext = to_format
if to_format == 't1':
file_ext = 'pfa'
elif to_format == 'afm':
file_ext = 'txt'
expected_path = get_expected_path(
f'bug618/{exp_filename}.{file_ext}')
diff_mode = []
if to_format == 'cff':
diff_mode = ['-m', 'bin']
skip = []
if to_format == 'afm':
skip = ['-s', 'Comment Creation Date:' + SPLIT_MARKER +
'Comment Copyright']
elif to_format == 't1':
skip = ['-s'] + PFA_SKIP[:]
assert differ([expected_path, save_path] + diff_mode + skip)
def test_glyph_bboxes_bug655():
actual_path = runner(CMD + ['-s', '-o', 'mtx', '2', '-f', 'bug655.ufo'])
expected_path = get_expected_path('bug655.txt')
assert differ([expected_path, actual_path])
@pytest.mark.parametrize('filename', ['SHSVF_9b3b', 'bug684'])
def test_cs_opt_bug684(filename):
""" The input CFF2 variable font contains a long single charstring
making the maximum use of the operand stack.
tx was generating a bad CFF2 charstring that would overflow
the operand stack of the standard size (513) after re-converted
to CFF2 unless -no_opt option is specified."""
font_path = get_input_path(f'{filename}.otf')
result_path = get_temp_file_path()
expected_path = get_expected_path(f'{filename}.cff2')
runner(CMD + ['-a', '-o', 'cff2', '-f', font_path, result_path])
assert differ([expected_path, result_path, '-m', 'bin'])
def test_standard_apple_glyph_names():
actual_path = runner(CMD + ['-s', '-o', 'dump', '4', '-f', 'post-v2.ttf'])
expected_path = get_expected_path('post-v2.txt')
assert differ([expected_path, actual_path])
def test_ufo_self_closing_dict_element_bug701():
actual_path = runner(CMD + ['-s', '-o', 'dump', '0', '-f', 'bug701.ufo'])
expected_path = get_expected_path('bug701.txt')
assert differ([expected_path, actual_path, '-s', '## Filename'])
def test_ufo3_guideline_bug705():
actual_path = runner(CMD + ['-s', '-o', 't1', '-f', 'bug705.ufo'])
expected_path = get_expected_path('bug705.pfa')
assert differ([expected_path, actual_path] + ['-s'] + PFA_SKIP)
def test_ufo_vertical_advance_bug786():
actual_path = runner(CMD + ['-s', '-o', 't1', '-f', 'bug786.ufo'])
expected_path = get_expected_path('bug786.pfa')
skip = ['-s'] + PFA_SKIP[:]
assert differ([expected_path, actual_path] + skip)
@pytest.mark.parametrize('filename', [
'a', # AE glyph in both default and processed layers
'b', # AE glyph in default layer only
'c', # AE glyph in processed layer only
])
def test_ufo_read_processed_contents_plist_bug740(filename):
actual_path = runner(CMD + ['-s', '-o', 'dump', '6', 'g', '_AE',
'-f', f'bug740/{filename}.ufo'])
expected_path = get_expected_path(f'bug740/{filename}.txt')
assert differ([expected_path, actual_path])
def test_dcf_with_infinite_recursion_bug775():
font_path = get_bad_input_path('subr_test_font_infinite_recursion.otf')
dcf_path = get_temp_file_path()
with pytest.raises(subprocess.CalledProcessError) as err:
runner(CMD + ['-a', '-o', 'dcf', '-f', font_path, dcf_path])
assert(err.value.returncode == 1) # exit code of 1, not segfault of -11
expected_path = get_expected_path(
'subr_test_font_infinite_recursion.dcf.txt')
assert differ([expected_path, dcf_path])
def test_dcf_call_depth_with_many_calls_bug846():
# This font was getting an invalid subroutine count because tx wasn't
# decrementing the subroutine call depth after the subroutine calls,
# so it was effectively just counting the total number of calls,
# not the call depth.
font_path = get_input_path('SHSansJPVFTest_SUBR.otf')
dcf_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'dcf', '-f', font_path, dcf_path])
expected_path = get_expected_path('SHSansJPVFTest_SUBR.dcf.txt')
assert differ([expected_path, dcf_path])
def test_svg_with_cid_font_bug822():
font_path = get_input_path('cid.otf')
cid_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'svg', '-f', font_path, cid_path])
expected_path = get_expected_path('cid.svg')
assert differ([expected_path, cid_path])
@pytest.mark.parametrize('filename',
['type1-noPSname.pfa', 'cidfont-noPSname.ps'])
def test_svg_missing_fontname_bug883(filename):
font_path = get_input_path(filename)
svg_path = get_temp_file_path()
with pytest.raises(subprocess.CalledProcessError) as err:
runner(CMD + ['-a', '-o', 'svg', '-f', font_path, svg_path])
assert(err.value.returncode == 6) # exit code of 6, not segfault of -11
@pytest.mark.parametrize('option', ['dump', 'dcf'])
def test_read_fdselect_format_4(option):
font_name = 'fdselect4.otf'
input_path = get_input_path(font_name)
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', option, '-f', input_path, output_path])
expected_path = get_expected_path(font_name + '.' + option)
assert differ([expected_path, output_path, '-s', '## Filename'])
def test_write_fdselect_format_4():
font_name = 'FDArrayTest257FontDicts.otf'
input_path = get_input_path(font_name)
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'cff2', '-f', input_path, output_path])
expected_path = get_expected_path('FDArrayTest257FontDicts.cff2')
assert differ([expected_path, output_path, '-m', 'bin'])
@pytest.mark.parametrize('option', ['cff', 'dcf'])
@pytest.mark.parametrize('font_name',
['bug895_charstring.otf', 'bug895_private_dict.otf'])
def test_read_short_charstring_bug895(option, font_name):
input_path = get_bad_input_path(font_name)
output_path = runner(CMD + ['-s', '-e', '-a', '-o', option,
'-f', input_path])
expected_path = get_expected_path(font_name + '.' + option)
skip = ['-s', 'tx: ---'] # skip line with filename
assert differ([expected_path, output_path] + skip)
@pytest.mark.parametrize('option', ['cff2', 'cff'])
def test_drop_defaultwidthx_when_writing_cff2_bug897(option):
input_path = get_bad_input_path('bug897.otf')
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', option, '-f', input_path, output_path])
dcf_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'dcf', '-f', output_path, dcf_path])
expected_path = get_expected_path('bug897.' + option + '.dcf')
assert differ([expected_path, dcf_path])
@pytest.mark.parametrize('option', ['afm', 'dump', 'svg'])
def test_missing_glyph_names_pr905(option):
input_path = get_bad_input_path('pr905.otf')
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', option, '-f', input_path, output_path])
expected_path = get_expected_path('pr905' + '.' + option)
if option == 'afm':
skip = ['-s',
'Comment Creation Date:' + SPLIT_MARKER + 'Comment Copyright']
elif option == 'dump':
skip = ['-s', '## Filename']
else:
skip = []
assert differ([expected_path, output_path] + skip)
def test_missing_glyph_names_pr905_cef():
input_path = get_bad_input_path('pr905.otf')
output_path = get_temp_file_path()
with pytest.raises(subprocess.CalledProcessError) as err:
runner(CMD + ['-a', '-o', 'cef', '-f', input_path, output_path])
assert(err.value.returncode > 0) # error code, not segfault of -11
def test_var_bug_913():
# AdobeVFPrototype_mod.otf is a modified copy of AdobeVFPrototype.otf 1.003
# so that the region indexes in HVAR are listed in a different order from
# those in CFF2. Also MVAR table has been modified to contain (dummy)
# deltas for underline offset and underline thickness just to exercize
# MVAR lookup code.
font_path = get_input_path('AdobeVFPrototype_mod.otf')
save_path = get_temp_file_path()
runner(CMD + ['-a', '-o',
'3', 'g', '_A,W,y', 'U', '_900,0',
'-f', font_path, save_path])
expected_path = get_expected_path('bug913.txt')
assert differ([expected_path, save_path, '-s', '## Filename'])
def test_bad_charset():
font_path = get_bad_input_path('bad_charset.otf')
save_path = get_temp_file_path()
runner(CMD + ['-a', '-f', font_path, save_path])
expected_path = get_expected_path('bad_charset.txt')
assert differ([expected_path, save_path, '-s', '## Filename'])
def test_bug_940():
input_path = get_bad_input_path('bug940_private_blend.otf')
output_path = get_temp_file_path()
with pytest.raises(subprocess.CalledProcessError) as err:
runner(CMD + ['-a', '-o', 'cff2', '-f', input_path, output_path])
assert(err.value.returncode > 0) # error code, not segfault or success
def test_too_many_glyphs_pr955():
input_path = get_bad_input_path('TooManyGlyphsCFF2.otf')
output_path = get_temp_file_path()
with pytest.raises(subprocess.CalledProcessError) as err:
runner(CMD + ['-a', '-o', 'cff', '-f', input_path, output_path])
assert(err.value.returncode > 0) # error code, not hang or success
def test_ttread_varinst():
font_path = get_input_path('AdobeVFPrototype.ttf')
save_path = get_temp_file_path()
runner(CMD + ['-a', '-o', '3', 'g', '_A', 'U', '_500,800',
'-f', font_path, save_path])
expected_path = get_expected_path('vfproto_tt_inst500_800.txt')
assert differ([expected_path, save_path, '-s', '## Filename'])
def test_unused_post2_names():
font_path = get_input_path('SourceSansPro-Regular-cff2-unused-post.otf')
save_path = get_temp_file_path()
runner(CMD + ['-a', '-o', '1', '-f', font_path, save_path])
expected_path = get_expected_path('ssr-cff2-unused-post.txt')
assert differ([expected_path, save_path, '-s', '## Filename'])
def test_seac_reporting():
# This test aims to show that the SEAC operator
# is not reported by all tx modes
font_path = get_input_path('seac.otf')
save_path = get_temp_file_path()
runner(CMD + ['-a', '-o', '6', '-f', font_path, save_path])
expected_path = get_expected_path('seac.dump.txt')
assert differ([expected_path, save_path])
runner(CMD + ['-a', '-o', 'dcf', '5', 'T', '_c',
'-f', font_path, save_path])
expected_path = get_expected_path('seac.dcf.txt')
assert differ([expected_path, save_path])
def test_date_and_time_afm():
"""
test the use of date and time functions in absfont_afm.c
"""
input_path = get_input_path('font.otf')
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'afm', '-f', input_path, output_path])
now = time.time()
year = '%s' % time.localtime().tm_year
with open(output_path) as output_file:
lines = output_file.readlines()
file_year = lines[1].split()[2]
assert year == file_year
file_time_str = lines[2].split(': ')[1].strip()
file_time = time.mktime(
time.strptime(file_time_str, '%a %b %d %H:%M:%S %Y'))
hours_diff = abs(now - file_time) / 3600
assert(hours_diff < 1)
def test_date_and_time_ps():
"""
test the use of date and time functions in absfont_draw.c
"""
input_path = get_input_path('font.otf')
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'ps', '-f', input_path, output_path])
now = time.time()
with open(output_path) as output_file:
lines = output_file.readlines()
date_str = re.split(r'[()]', lines[5])[1]
date_str = date_str.split(': ')[1]
time_str = re.split(r'[()]', lines[7])[1]
time_str = time_str.split(': ')[1]
file_date_and_time_str = date_str + ' ' + time_str
file_time = time.mktime(
time.strptime(file_date_and_time_str, '%m/%d/%y %H:%M'))
hours_diff = abs(now - file_time) / 3600
assert(hours_diff < 1)
def test_date_and_time_pdf():
"""
test the use of date and time functions in pdfwrite.c
"""
input_path = get_input_path('font.otf')
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'pdf', '-f', input_path, output_path])
now = time.time()
tz = time.timezone
tz_hr = abs(int(tz / 3600)) # ignore sign since we're splitting on +/-
tz_min = (tz % 3600) // 60
with open(output_path) as output_file:
lines = output_file.readlines()
creation_date_str = re.split(r'[()]', lines[13])[1]
mod_date_str = re.split(r'[()]', lines[14])[1]
assert(creation_date_str == mod_date_str)
(date_time_str, tz_hr_str, tz_min_str) = \
re.split(r"[:+\-Z']", creation_date_str)[1:4]
creation_time = time.mktime(
time.strptime(date_time_str, '%Y%m%d%H%M%S'))
hours_diff = abs(now - creation_time) / 3600
assert(hours_diff < 1)
creation_tz_hr = int(tz_hr_str)
assert(creation_tz_hr == tz_hr)
creation_tz_min = int(tz_min_str)
assert(creation_tz_min == tz_min)
file_date_str = re.split(r"[():]", lines[36])[2].strip()
file_time_str = re.split(r"[() ]", lines[38])[3]
file_date_time_str = file_date_str + ' ' + file_time_str
file_time = time.mktime(
time.strptime(file_date_time_str, "%d %b %y %H:%M"))
hours_diff = abs(now - file_time) / 3600
assert(hours_diff < 1)
def test_overlap_removal():
input_path = get_input_path('overlaps.ufo')
expected_path = get_expected_path('overlaps.pfa')
output_path = get_temp_file_path()
args = [TOOL, '-t1', '+V', '-o', output_path, input_path]
subprocess.call(args)
assert differ([expected_path, output_path, '-s', PFA_SKIP[0]])
@pytest.mark.parametrize("fmt", [
"cff",
"cff2",
])
def test_nonstd_fontmatrix(fmt):
input_path = get_input_path("nonstdfmtx.otf")
txt_filename = f"nonstdfmtx_{fmt}.txt"
expected_path = get_expected_path(txt_filename)
output_dir = get_temp_dir_path()
bin_output = os.path.join(output_dir, f"nonstdfmtx.{fmt}")
output_path = os.path.join(output_dir, txt_filename)
runner(CMD + ['-a', '-o', fmt, '*S', '*b', '-f', input_path, bin_output])
runner(CMD + ['-a', '-o', 'dump', '-f', bin_output, output_path])
skip = "## Filename "
assert differ([expected_path, output_path, '-s', skip])
def test_pdf_single_glyph():
input_path = get_input_path("bug1218.otf")
pdf_filename = "bug1218.pdf"
expected_path = get_expected_path(pdf_filename)
output_dir = get_temp_dir_path()
output_path = os.path.join(output_dir, pdf_filename)
runner(CMD + ['-a', '-o', 'pdf', '1', '-f', input_path, output_path])
skip = PDF_SKIP[:]
skip.insert(0, '-s')
regex_skip = PDF_SKIP_REGEX[:]
for regex in regex_skip:
skip.append('-r')
skip.append(regex)
assert differ([expected_path, output_path] + skip)
def test_cffread_bug1343():
"""
Check FontBBox values
"""
actual_path = runner(CMD + ['-s', '-f', 'font.otf', '-o', '3'])
expected_path = get_expected_path('font.otf.dump3.txt')
assert differ([expected_path, actual_path, '-s', '## Filename'])
@pytest.mark.parametrize('arg, input, output, expected', [
('ufo', 'cidfont.subset', 'cidfont_subset.ufo', 'testCID.ufo'),
('t1', 'testCID.ufo', 'cidfont_subset.ufo', 'cidfont.subset'),
(('ufo', 't1'), 'cidfont.subset', 'cidfont_subset.ufo', 'cidfont.subset'),
(('t1', 'ufo'), 'testCID.ufo', 'cidfont_subset.ufo', 'testCID.ufo'),
])
def test_cidkeyed_read_write(arg, input, output, expected):
"""
Tests reading & writing CID-Keyed fonts in tx (uforead & ufowrite)
CID -> UFO (one-way test)
UFO -> CID (one-way test)
CID -> UFO -> CID (round-trip test)
UFO -> CID -> UFO (round-trip test)
"""
folder = "cid_roundtrip/"
input_path = get_input_path(folder + input)
output_dir = get_temp_dir_path()
output_path = os.path.join(output_dir, output)
expected_path = get_expected_path(folder + expected)
if isinstance(arg, tuple): # round-trip tests
runner(CMD + ['-a', '-o', arg[0], '-f',
input_path, output_path])
final_output_dir = get_temp_dir_path()
final_output_path = os.path.join(final_output_dir, output)
runner(CMD + ['-a', '-o', arg[1], '-f',
output_path, final_output_path])
output_path = final_output_path
else: # one-way tests
runner(CMD + ['-a', '-o', arg, '-f',
input_path, output_path])
if '.subset' in expected_path:
expected_path = generate_ps_dump(expected_path)
output_path = generate_ps_dump(output_path)
assert differ([expected_path, output_path])
@pytest.mark.parametrize("file", [
"missing_CID.ufo",
"missing_iFD.ufo",
])
def test_cidkeyed_lib_missing(file):
folder = folder = "cidkeyed_missing_lib/"
ufo_input_path = get_input_path(folder + file)
arg = [TOOL, '-t1', '-f', ufo_input_path]
assert subprocess.call(arg) == 6
def test_cff2_windows_line_endings_bug1355():
# Testing writing binary to stdout on Windows
# to ensure line endings are not inserted.
font_path = get_input_path('regular_CFF2.otf')
actual_path = runner(CMD + ['-s', '-a', '-o', 'cff2',
'*S', '*b', '-f', font_path])
expected_path = get_expected_path('bug1355.cff2')
assert differ([expected_path, actual_path, '-m', 'bin'])
| 36.787252 | 79 | 0.624959 | import os
import pytest
import re
import subprocess
import time
from afdko.fdkutils import (
get_temp_file_path,
get_temp_dir_path,
)
from test_utils import (
get_input_path,
get_bad_input_path,
get_expected_path,
generate_ps_dump,
)
from runner import main as runner
from differ import main as differ, SPLIT_MARKER
TOOL = 'tx'
CMD = ['-t', TOOL]
def _get_extension(in_format):
if 'ufo' in in_format:
return '.ufo'
elif in_format == 'type1':
return '.pfa'
return '.' + in_format
PDF_SKIP = [
'/Creator' + SPLIT_MARKER +
'/Producer' + SPLIT_MARKER +
'/CreationDate' + SPLIT_MARKER +
'/ModDate' + SPLIT_MARKER +
'(Date:' + SPLIT_MARKER +
'(Time:',
]
PDF_SKIP_REGEX = [
'^.+30.00 Td',
'^.+0.00 Td',
]
PS_SKIP = [
'0 740 moveto (Filename:' + SPLIT_MARKER +
'560 (Date:' + SPLIT_MARKER +
'560 (Time:'
]
PS_SKIP2 = [
'%ADOt1write:'
]
PFA_SKIP = [
'%ADOt1write:' + SPLIT_MARKER +
'%%Copyright:' + SPLIT_MARKER
]
@pytest.mark.parametrize('arg', ['-h', '-v', '-u'])
def test_exit_known_option(arg):
assert subprocess.call([TOOL, arg]) == 0
@pytest.mark.parametrize('arg', ['-bar', '-foo'])
def test_exit_unknown_option(arg):
assert subprocess.call([TOOL, arg]) == 1
@pytest.mark.parametrize('pth', [
['invalid_path'],
[get_temp_file_path()],
[get_input_path('type1.pfa'), 'a', 'b'],
])
def test_exit_invalid_path_or_font(pth):
assert subprocess.call([TOOL] + pth) == 1
@pytest.mark.parametrize('args', [
['-s', '-t1'],
['-t1', '-g', '0', '-gx', '1'],
['-dcf'],
['-ps', '-1'],
['-ufo'], ['-t1', '-pfb'],
['-t1', '-usefd'],
['-t1', '-decid'],
])
def test_option_error_type1_input(args):
font_path = get_input_path('type1.pfa')
assert subprocess.call([TOOL] + args + [font_path]) == 1
@pytest.mark.parametrize('arg', ['-e', '-q', '+q', '-w', '+w', '-lf', '-cr',
'-crlf', '-decid', '-LWFN', '-pfb'])
def test_option_error_type1_clash(arg):
pfb = '-pfb' if arg != '-pfb' else '-LWFN'
assert subprocess.call([TOOL, '-t1', pfb, arg]) == 1
@pytest.mark.parametrize('args', [
['-cff', '-l'], ['-cff', '-0'], ['-cff', '-1'], ['-cff', '-2'],
['-cff', '-3'], ['-cff', '-4'], ['-cff', '-5'], ['-cff', '-6'],
['-cff', '-q'], ['-cff', '+q'], ['-cff', '-w'], ['-cff', '+w'],
['-cff', '-pfb'], ['-cff', '-usefd'], ['-cff', '-decid'],
['-cff', '-lf'], ['-cff', '-cr'], ['-cff', '-crlf'], ['-cff', '-LWFN'],
['-t1', '-gn0'], ['-t1', '-gn1'], ['-t1', '-gn2'], ['-t1', '-sa'],
['-t1', '-abs'], ['-t1', '-cefsvg'],
['-t1', '-no_futile'], ['-t1', '-no_opt'], ['-t1', '-d'], ['-t1', '+d'],
['-dcf', '-n'], ['-dcf', '-c'],
['-dump', '-E'], ['-dump', '+E'], ['-dump', '-F'], ['-dump', '+F'],
['-dump', '-O'], ['-dump', '+O'], ['-dump', '-S'], ['-dump', '+S'],
['-dump', '-T'], ['-dump', '+T'], ['-dump', '-V'], ['-dump', '+V'],
['-dump', '-b'], ['-dump', '+b'], ['-dump', '-e'], ['-dump', '+e'],
['-dump', '-Z'], ['-dump', '+Z'],
])
def test_option_error_wrong_mode(args):
assert subprocess.call([TOOL] + args) == 1
@pytest.mark.parametrize('arg', [
'-a', '-e', '-f', '-g', '-i', '-m', '-o', '-p', '-A', '-P', '-U', '-maxs',
'-usefd', '-fd', '-dd', '-sd', '-sr', ['-cef', '-F'], ['-dcf', '-T']
])
def test_option_error_no_args_left(arg):
if isinstance(arg, list):
arg_lst = [TOOL] + arg
else:
arg_lst = [TOOL, '-t1', arg]
assert subprocess.call(arg_lst) == 1
@pytest.mark.parametrize('args', [
['-maxs', 'X'], ['-m', 'X'], ['-e', 'X'], ['-e', '5'],
['-usefd', 'X'], ['-usefd', '-1']
])
def test_option_error_bad_arg(args):
assert subprocess.call([TOOL, '-t1'] + args) == 1
@pytest.mark.parametrize('arg2', ['-sd', '-sr', '-dd'])
@pytest.mark.parametrize('arg1', ['-a', '-f', '-A'])
def test_option_error_no_args_left2(arg1, arg2):
assert subprocess.call([TOOL, '-t1', arg1, arg2]) == 1
@pytest.mark.parametrize('arg2', ['-sd', '-sr', '-dd'])
@pytest.mark.parametrize('arg1', ['-a', '-f'])
def test_option_error_empty_list(arg1, arg2):
empty_dir = get_temp_dir_path()
assert subprocess.call([TOOL, '-t1', arg1, arg2, empty_dir]) == 1
@pytest.mark.parametrize('arg', ['-bc', '-z', '-cmp', '-sha1'])
def test_gone_options_bc(arg):
assert subprocess.call([TOOL, arg]) == 1
@pytest.mark.parametrize('mode, msg', [
('-h', b'tx (Type eXchange) is a test harness'),
('-u', b'tx {[mode][mode options][shared options][files]}*'),
('-afm', b'[-afm options: default none]'),
('-cef', b'[-cef options: default none]'),
('-cff', b'[-cff options: defaults -E, -F, -O, -S, +T, -V, -Z, -b, -d]'),
('-cff2', b'[-cff2 options: defaults -S, -b]'),
('-dcf', b'[-dcf options: defaults -T all, -5]'),
('-dump', b'[-dump options: default -1]'),
('-mtx', b'[-mtx options: default -0]'),
('-path', b'[-path options: default -0]'),
('-pdf', b'[-pdf options: default -0]'),
('-ps', b'[-ps options: default -0]'),
('-svg', b'[-svg options: defaults -lf, -gn0]'),
('-t1',
b'[-t1 options: defaults -0, -l, -E, -S, +T, -V, +q, -w, -e 4, -lf]'),
('-ufo', b'[-ufo options: default none]'),
])
def test_mode_help(mode, msg):
output = subprocess.check_output([TOOL, mode, '-h'])
assert msg in output
@pytest.mark.parametrize('dcf_dump_level', ['0', '1', '5'])
def test_script_file(dcf_dump_level):
font_path = get_input_path('cid.otf')
opts_path = get_temp_file_path()
opts_file_content = f'\n# foo\n # bar\r -{dcf_dump_level}\t"{font_path}"'
with open(opts_path, 'a') as fp:
fp.write(opts_file_content)
actual_path = runner(CMD + ['-s', '-a', '-o', 'dcf', 's', '-f', opts_path])
expected_path = get_expected_path(f'cid_dcf_{dcf_dump_level}.txt')
assert differ([expected_path, actual_path])
def test_nested_script():
temp_path = get_temp_file_path()
assert subprocess.call([TOOL, '-s', 'foobar', '-s', temp_path]) == 1
@pytest.mark.parametrize('layer_name', ['', 'None', 'background', 'foobar'])
def test_ufo_altlayer(layer_name):
if not layer_name:
fname = 'processed'
args = []
else:
fname = 'foreground' if layer_name == 'None' else layer_name
args = ['altLayer', f'_{fname}']
actual_path = runner(CMD + ['-s', '-f', 'altlayer.ufo', '-o', '6'] + args)
expected_path = get_expected_path(f'altlayer_{fname}.txt')
assert differ([expected_path, actual_path])
@pytest.mark.parametrize('arg, filename', [
('-a', 'ufo3.t1'),
('-A', 'SourceSansPro-Regular.t1'),
])
def test_a_options(arg, filename):
input_path = get_input_path('ufo3.ufo')
output_path = os.path.join(os.getcwd(), filename)
assert os.path.exists(output_path) is False
subprocess.call([TOOL, '-t1', arg, input_path])
assert os.path.exists(output_path) is True
os.remove(output_path)
def test_o_option():
input_path = get_input_path('ufo3.ufo')
expected_path = get_expected_path('ufo3.pfa')
output_path = get_temp_file_path()
subprocess.call([TOOL, '-t1', '-o', output_path, input_path])
assert differ([expected_path, output_path, '-s', PFA_SKIP[0]])
def test_f_option():
fpath1 = get_input_path('type1.pfa')
fpath2 = get_input_path('cff2_vf.otf')
actual_path = runner(CMD + ['-s', '-o', 'mtx', '3',
'f', f'_{fpath1}', f'_{fpath2}'])
expected_path = get_expected_path('mtx_f_options.txt')
assert differ([expected_path, actual_path])
def test_stdin():
input_path = get_input_path('type1.pfa')
expected_path = get_expected_path('stdin.txt')
output_path = get_temp_file_path()
with open(input_path) as fp:
output = subprocess.check_output([TOOL], stdin=fp)
with open(output_path, 'wb') as fp:
fp.write(output)
assert differ([expected_path, output_path])
@pytest.mark.parametrize('arg', ['0', '-16'])
def test_m_option_success(arg):
input_path = get_input_path('type1.pfa')
assert subprocess.call([TOOL, '-m', arg, input_path]) == 0
@pytest.mark.parametrize('arg, exp_filename', [(None, 'not_removed'),
('-V', 'not_removed'),
('+V', 'removed')])
def test_V_option(arg, exp_filename):
input_path = get_input_path('overlap.pfa')
expected_path = get_expected_path(f'overlap_{exp_filename}.pfa')
output_path = get_temp_file_path()
args = [TOOL, '-t1', '-o', output_path, input_path]
if arg:
args.insert(2, arg)
subprocess.call(args)
assert differ([expected_path, output_path] + ['-s'] + PFA_SKIP)
@pytest.mark.parametrize('to_format', [
'ufo2',
'ufo3',
'type1',
'svg',
'mtx',
'afm',
'pdf',
'ps',
'cff',
])
@pytest.mark.parametrize('from_format', [
'ufo2',
'ufo3',
'type1',
])
def test_convert(from_format, to_format):
from_ext = _get_extension(from_format)
to_ext = _get_extension(to_format)
from_filename = from_format + from_ext
exp_filename = from_format + to_ext
if 'ufo' in to_format:
save_path = get_temp_dir_path('font.ufo')
else:
save_path = get_temp_file_path()
if to_format == 'cff':
diff_mode = ['-m', 'bin']
else:
diff_mode = []
regex_skip = []
skip = []
if to_format == 'afm':
skip = ['Comment Creation Date:' + SPLIT_MARKER + 'Comment Copyright']
elif to_format == 'pdf':
skip = PDF_SKIP[:]
regex_skip = PDF_SKIP_REGEX[:]
elif to_format == 'ps':
skip = PS_SKIP[:]
elif to_format == 'type1':
skip = PFA_SKIP[:]
if skip:
skip.insert(0, '-s')
if regex_skip:
for regex in regex_skip:
skip.append('-r')
skip.append(regex)
if to_format in ('ufo2', 'ufo3'):
format_arg = 'ufo'
elif to_format == 'type1':
format_arg = 't1'
else:
format_arg = to_format
runner(CMD + ['-a', '-f', get_input_path(from_filename), save_path,
'-o', format_arg])
expected_path = get_expected_path(exp_filename)
assert differ([expected_path, save_path] + skip + diff_mode)
def test_cef_cefsvg():
font_path = get_input_path('cff2_vf.otf')
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'cef', 'cefsvg', 'cr', 'gn1', 'abs', 'sa',
'-f', font_path, output_path])
expected_path = get_expected_path('cef_cefsvg_cr.svg')
assert differ([expected_path, output_path])
@pytest.mark.parametrize('file_ext', [
'pfa', 'pfabin', 'pfb', 'lwfn', 'bidf'])
def test_type1_inputs(file_ext):
bidf = '.bidf' if 'bidf' in file_ext else ''
actual_path = runner(CMD + ['-s', '-o', '2', '-f', f'type1.{file_ext}'])
expected_path = get_expected_path(f'type1.dump2{bidf}.txt')
assert differ([expected_path, actual_path, '-s', '## Filename'])
@pytest.mark.parametrize('args', [[], ['U', '_500,500'], ['U', '_0,0', 'n']])
@pytest.mark.parametrize('fname', ['zx', 'zy'])
def test_type1mm_inputs(fname, args):
fname2 = f'.{"".join(args)}' if args else ''
actual_path = runner(CMD + ['-s', '-f', f'{fname}.pfb', '-o', '2'] + args)
expected_path = get_expected_path(f'{fname}.dump2{fname2}.txt')
assert differ([expected_path, actual_path, '-s', '## Filename'])
@pytest.mark.parametrize('fext', ['otf', 'ttf', 'cff', 'cef', 'ttc'])
def test_other_input_formats(fext):
arg = ['y'] if fext == 'ttc' else []
actual_path = runner(CMD + ['-s', '-f', f'font.{fext}', '-o', '3'] + arg)
expected_path = get_expected_path(f'font.{fext}.dump3.txt')
assert differ([expected_path, actual_path, '-s', '## Filename'])
@pytest.mark.parametrize('args', [
[],
['0'],
['dump', '0'],
['1'],
['2'],
['3'],
['4'],
['4', 'N'],
['5'],
['6'],
['6', 'd'],
['6', 'n'],
])
@pytest.mark.parametrize('font_filename', ['type1.pfa', 'svg.svg'])
def test_dump_option(args, font_filename):
if any([arg in args for arg in ('4', '5', '6')]):
skip = []
else:
skip = ['-s', '## Filename']
head = font_filename.split('.')[0]
midl = ''.join(args) if args else 'dump1'
if 'dump' not in midl:
midl = f'dump{midl}'
exp_filename = f'{head}.{midl}.txt'
opts = ['-o'] + args if args else []
actual_path = runner(CMD + ['-s', '-f', font_filename] + opts)
expected_path = get_expected_path(exp_filename)
assert differ([expected_path, actual_path] + skip)
@pytest.mark.parametrize('fext', ['pfa', 'ufo'])
def test_dump_flex_op(fext):
fname = 'flex'
actual_path = runner(CMD + ['-s', '-o', '6', '-f', f'{fname}.{fext}'])
expected_path = get_expected_path(f'{fname}.txt')
assert differ([expected_path, actual_path])
@pytest.mark.parametrize('filename, msg', [
('avar_invalid_table_version',
b'(cfr) invalid avar table version'),
('fvar_invalid_table_version',
b'(cfr) invalid fvar table version'),
('avar_invalid_table_size',
b'(cfr) invalid avar table size'),
('fvar_invalid_table_size',
b'(cfr) invalid fvar table size'),
('fvar_invalid_table_header',
b'(cfr) invalid values in fvar table header'),
('avar_invalid_axis-instance_count-size',
b'(cfr) invalid avar table size or axis/instance count/size'),
('fvar_invalid_axis-instance_count-size',
b'(cfr) invalid fvar table size or axis/instance count/size'),
('avar_axis_value_map_out_of_bounds',
b'(cfr) avar axis value map out of bounds'),
('avar_fvar_axis_mismatch',
b'(cfr) mismatching axis counts in fvar and avar'),
])
def test_varread_errors(filename, msg):
font_path = get_bad_input_path(f'vf_{filename}.otf')
output = subprocess.check_output([TOOL, '-dcf', '-0', font_path],
stderr=subprocess.STDOUT)
assert msg in output
@pytest.mark.parametrize('args, exp_filename', [
([], 'SourceCodeVar-Roman_CFF2'),
(['*S', '*b', 'std'], 'SourceCodeVar-Roman_CFF2_subr'),
])
def test_cff2_extract(args, exp_filename):
font_path = get_input_path('SourceCodeVariable-Roman.otf')
cff2_path = get_temp_file_path()
runner(CMD + ['-a', '-f', font_path, cff2_path, '-o', 'cff2'] + args)
expected_path = get_expected_path(exp_filename)
assert differ([expected_path, cff2_path, '-m', 'bin'])
def test_cff2_sub_dump():
actual_path = runner(CMD + ['-s', '-o', 'dump', '6', 'g', '_21847',
'-f', 'CFF2-serif-sub.cff2'])
expected_path = get_expected_path('CFF2-serif-sub.cff2.txt')
assert differ([expected_path, actual_path])
def test_varread_pr355():
actual_path = runner(CMD + ['-s', '-o', 't1', '-f', 'cff2_vf.otf'])
expected_path = get_expected_path('cff2_vf.pfa')
skip = ['-s'] + PFA_SKIP[:]
assert differ([expected_path, actual_path] + skip)
def test_cff2_no_vf_bug353():
font_path = get_input_path('regular_CFF2.otf')
cff2_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'cff2', '-f', font_path, cff2_path])
expected_path = get_expected_path('regular_CFF2.cff2')
assert differ([expected_path, cff2_path, '-m', 'bin'])
def test_cff2_with_spare_masters_pr835():
font_path = get_input_path('SHSansJPVFTest.otf')
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o',
'cff2', '*S', '*b', 'std',
'-f', font_path, output_path])
expected_path = get_expected_path('SHSansJPVFTest.cff2')
assert differ([expected_path, output_path, '-m', 'bin'])
@pytest.mark.parametrize('vector, exp_filename', [
('9999,9999,9999,9999,999,9', 'psname_last_resort_no.txt'),
('9999,9999,9999,9999,999,99', 'psname_last_resort_yes.txt'),
])
def test_last_resort_instance_psname(vector, exp_filename):
font_path = get_input_path('cff2_vf_many_axes.otf')
output_path = get_temp_file_path()
runner(CMD + ['-o', '0', 'U', f'_{vector}', '-f', font_path, output_path])
expected_path = get_expected_path(exp_filename)
assert differ([expected_path, output_path, '-s', '## Filename'])
def test_trademark_string_pr425():
actual_path = runner(CMD + ['-s', '-o', 't1', '-f', 'trademark.ufo'])
expected_path = get_expected_path('trademark.pfa')
skip = ['-s'] + PFA_SKIP[:]
assert differ([expected_path, actual_path] + skip)
def test_remove_hints_bug180():
font_path = get_input_path('cid.otf')
cid_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 't1', 'n', '-f', font_path, cid_path])
expected_path = get_expected_path('cid_nohints.ps')
expected_path = generate_ps_dump(expected_path)
actual_path = generate_ps_dump(cid_path)
skip = ['-s'] + PS_SKIP2
assert differ([expected_path, actual_path] + skip)
def test_long_charstring_read_bug444():
actual_path = runner(CMD + ['-s', '-o', '0', '-f', 'CJK-VarTest.otf'])
expected_path = get_expected_path('CJK-VarTest_read.txt')
assert differ([expected_path, actual_path, '-s', '## Filename'])
def test_long_charstring_warning():
# Windows the lines start with 'tx.exe:' instead of just 'tx:'
actual_path = runner(
CMD + ['-s', '-e', '-o', '5', '-f', 'CJK-VarTest.otf'])
# expected_path = get_expected_path('CJK-VarTest_warn.txt')
with open(actual_path, 'rb') as f:
output = f.read()
assert b"(cfr) Warning: CharString of GID 1 is 71057 bytes long" in output
def test_long_charstring_write():
# read a CFF2 VF with a charstring longer that 65535, write out CFF2 file
# NOTE: the font 'CJK-VarTest.otf' cannot be used in this test because
# once its long charstring is optimized (floats -> ints) it's no longer
font_path = get_input_path('CJK-VarTest2.otf')
cff2_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'cff2', '-f', font_path, cff2_path])
expected_path = get_expected_path('CJK-VarTest2.cff2')
assert differ([expected_path, cff2_path, '-m', 'bin'])
def test_many_hints_string_bug354():
font_path = get_input_path('cff2_vf.otf')
cff2_path = get_temp_file_path()
dcf_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'cff2', '-f', font_path, cff2_path])
runner(CMD + ['-a', '-o', 'dcf', '-f', cff2_path, dcf_path])
expected_path = get_expected_path('cff2_vf.dcf.txt')
assert differ([expected_path, dcf_path])
def test_non_varying_glyphs_bug356():
actual_path = get_temp_file_path()
font_path = get_input_path('bug356.otf')
stderr_path = runner(CMD + ['-s', '-e', '-a', '-o', 'cff',
'-f', font_path, actual_path])
expected_path = get_expected_path('bug356.txt')
assert differ([expected_path, stderr_path, '-l', '1'])
@pytest.mark.parametrize('font_format', ['type1', 'cidfont', 'ufo2', 'ufo3'])
def test_no_psname_dump_bug437(font_format):
if 'cid' in font_format:
file_ext = 'ps'
elif 'ufo' in font_format:
file_ext = 'ufo'
else:
file_ext = 'pfa'
filename = f'{font_format}-noPSname.{file_ext}'
expected_path = get_expected_path(f'bug437/dump-{font_format}.txt')
actual_path = runner(CMD + ['-s', '-o', 'dump', '0', '-f', filename])
assert differ([expected_path, actual_path, '-l', '1'])
@pytest.mark.parametrize('font_format', ['type1', 'cidfont', 'ufo2', 'ufo3'])
def test_no_psname_convert_to_ufo_bug437(font_format):
if 'cid' in font_format:
file_ext = 'ps'
elif 'ufo' in font_format:
file_ext = 'ufo'
else:
file_ext = 'pfa'
font_path = get_input_path(f'{font_format}-noPSname.{file_ext}')
expected_path = get_expected_path(f'bug437/{font_format}.ufo')
save_path = get_temp_dir_path(f'{font_format}.ufo')
runner(CMD + ['-a', '-o', 'ufo', '-f', font_path, save_path])
assert differ([expected_path, save_path])
@pytest.mark.parametrize('font_format', ['type1', 'cidfont', 'ufo2', 'ufo3'])
def test_no_psname_convert_to_type1_bug437(font_format):
if 'cid' in font_format:
file_ext = 'ps'
elif 'ufo' in font_format:
file_ext = 'ufo'
else:
file_ext = 'pfa'
filename = f'{font_format}-noPSname.{file_ext}'
with pytest.raises(subprocess.CalledProcessError) as err:
runner(CMD + ['-o', 't1', '-f', filename])
assert err.value.returncode in (5, 6)
def test_illegal_chars_in_glyph_name_bug473():
font_path = get_input_path('bug473.ufo')
save_path = get_temp_dir_path('bug473.ufo')
runner(CMD + ['-a', '-o', 'ufo', '-f', font_path, save_path])
expected_path = get_expected_path('bug473.ufo')
assert differ([expected_path, save_path])
def test_subroutine_sorting_bug494():
font_path = get_input_path('bug494.pfa')
cff_path = get_temp_file_path()
dcf_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'cff', '*S', 'std', '*b',
'-f', font_path, cff_path])
runner(CMD + ['-a', '-o', 'dcf', '-f', cff_path, dcf_path])
expected_path = get_expected_path('bug494.dcf.txt')
assert differ([expected_path, dcf_path])
@pytest.mark.parametrize('args, exp_filename', [([], 'roundtrip'),
(['g', '_0-1'], 'subset')])
@pytest.mark.parametrize('to_format', ['t1', 'cff', 'afm'])
def test_recalculate_font_bbox_bug618(to_format, args, exp_filename):
font_path = get_input_path('bug618.pfa')
save_path = get_temp_file_path()
runner(CMD + ['-f', font_path, save_path, '-o', to_format] + args)
file_ext = to_format
if to_format == 't1':
file_ext = 'pfa'
elif to_format == 'afm':
file_ext = 'txt'
expected_path = get_expected_path(
f'bug618/{exp_filename}.{file_ext}')
diff_mode = []
if to_format == 'cff':
diff_mode = ['-m', 'bin']
skip = []
if to_format == 'afm':
skip = ['-s', 'Comment Creation Date:' + SPLIT_MARKER +
'Comment Copyright']
elif to_format == 't1':
skip = ['-s'] + PFA_SKIP[:]
assert differ([expected_path, save_path] + diff_mode + skip)
def test_glyph_bboxes_bug655():
actual_path = runner(CMD + ['-s', '-o', 'mtx', '2', '-f', 'bug655.ufo'])
expected_path = get_expected_path('bug655.txt')
assert differ([expected_path, actual_path])
@pytest.mark.parametrize('filename', ['SHSVF_9b3b', 'bug684'])
def test_cs_opt_bug684(filename):
font_path = get_input_path(f'{filename}.otf')
result_path = get_temp_file_path()
expected_path = get_expected_path(f'{filename}.cff2')
runner(CMD + ['-a', '-o', 'cff2', '-f', font_path, result_path])
assert differ([expected_path, result_path, '-m', 'bin'])
def test_standard_apple_glyph_names():
actual_path = runner(CMD + ['-s', '-o', 'dump', '4', '-f', 'post-v2.ttf'])
expected_path = get_expected_path('post-v2.txt')
assert differ([expected_path, actual_path])
def test_ufo_self_closing_dict_element_bug701():
actual_path = runner(CMD + ['-s', '-o', 'dump', '0', '-f', 'bug701.ufo'])
expected_path = get_expected_path('bug701.txt')
assert differ([expected_path, actual_path, '-s', '## Filename'])
def test_ufo3_guideline_bug705():
actual_path = runner(CMD + ['-s', '-o', 't1', '-f', 'bug705.ufo'])
expected_path = get_expected_path('bug705.pfa')
assert differ([expected_path, actual_path] + ['-s'] + PFA_SKIP)
def test_ufo_vertical_advance_bug786():
actual_path = runner(CMD + ['-s', '-o', 't1', '-f', 'bug786.ufo'])
expected_path = get_expected_path('bug786.pfa')
skip = ['-s'] + PFA_SKIP[:]
assert differ([expected_path, actual_path] + skip)
@pytest.mark.parametrize('filename', [
'a',
'b',
'c',
])
def test_ufo_read_processed_contents_plist_bug740(filename):
actual_path = runner(CMD + ['-s', '-o', 'dump', '6', 'g', '_AE',
'-f', f'bug740/{filename}.ufo'])
expected_path = get_expected_path(f'bug740/{filename}.txt')
assert differ([expected_path, actual_path])
def test_dcf_with_infinite_recursion_bug775():
font_path = get_bad_input_path('subr_test_font_infinite_recursion.otf')
dcf_path = get_temp_file_path()
with pytest.raises(subprocess.CalledProcessError) as err:
runner(CMD + ['-a', '-o', 'dcf', '-f', font_path, dcf_path])
assert(err.value.returncode == 1)
expected_path = get_expected_path(
'subr_test_font_infinite_recursion.dcf.txt')
assert differ([expected_path, dcf_path])
def test_dcf_call_depth_with_many_calls_bug846():
# decrementing the subroutine call depth after the subroutine calls,
# so it was effectively just counting the total number of calls,
# not the call depth.
font_path = get_input_path('SHSansJPVFTest_SUBR.otf')
dcf_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'dcf', '-f', font_path, dcf_path])
expected_path = get_expected_path('SHSansJPVFTest_SUBR.dcf.txt')
assert differ([expected_path, dcf_path])
def test_svg_with_cid_font_bug822():
font_path = get_input_path('cid.otf')
cid_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'svg', '-f', font_path, cid_path])
expected_path = get_expected_path('cid.svg')
assert differ([expected_path, cid_path])
@pytest.mark.parametrize('filename',
['type1-noPSname.pfa', 'cidfont-noPSname.ps'])
def test_svg_missing_fontname_bug883(filename):
font_path = get_input_path(filename)
svg_path = get_temp_file_path()
with pytest.raises(subprocess.CalledProcessError) as err:
runner(CMD + ['-a', '-o', 'svg', '-f', font_path, svg_path])
assert(err.value.returncode == 6) # exit code of 6, not segfault of -11
@pytest.mark.parametrize('option', ['dump', 'dcf'])
def test_read_fdselect_format_4(option):
font_name = 'fdselect4.otf'
input_path = get_input_path(font_name)
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', option, '-f', input_path, output_path])
expected_path = get_expected_path(font_name + '.' + option)
assert differ([expected_path, output_path, '-s', 'rite_fdselect_format_4():
font_name = 'FDArrayTest257FontDicts.otf'
input_path = get_input_path(font_name)
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'cff2', '-f', input_path, output_path])
expected_path = get_expected_path('FDArrayTest257FontDicts.cff2')
assert differ([expected_path, output_path, '-m', 'bin'])
@pytest.mark.parametrize('option', ['cff', 'dcf'])
@pytest.mark.parametrize('font_name',
['bug895_charstring.otf', 'bug895_private_dict.otf'])
def test_read_short_charstring_bug895(option, font_name):
input_path = get_bad_input_path(font_name)
output_path = runner(CMD + ['-s', '-e', '-a', '-o', option,
'-f', input_path])
expected_path = get_expected_path(font_name + '.' + option)
skip = ['-s', 'tx: ---'] # skip line with filename
assert differ([expected_path, output_path] + skip)
@pytest.mark.parametrize('option', ['cff2', 'cff'])
def test_drop_defaultwidthx_when_writing_cff2_bug897(option):
input_path = get_bad_input_path('bug897.otf')
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', option, '-f', input_path, output_path])
dcf_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'dcf', '-f', output_path, dcf_path])
expected_path = get_expected_path('bug897.' + option + '.dcf')
assert differ([expected_path, dcf_path])
@pytest.mark.parametrize('option', ['afm', 'dump', 'svg'])
def test_missing_glyph_names_pr905(option):
input_path = get_bad_input_path('pr905.otf')
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', option, '-f', input_path, output_path])
expected_path = get_expected_path('pr905' + '.' + option)
if option == 'afm':
skip = ['-s',
'Comment Creation Date:' + SPLIT_MARKER + 'Comment Copyright']
elif option == 'dump':
skip = ['-s', ' skip = []
assert differ([expected_path, output_path] + skip)
def test_missing_glyph_names_pr905_cef():
input_path = get_bad_input_path('pr905.otf')
output_path = get_temp_file_path()
with pytest.raises(subprocess.CalledProcessError) as err:
runner(CMD + ['-a', '-o', 'cef', '-f', input_path, output_path])
assert(err.value.returncode > 0) # error code, not segfault of -11
def test_var_bug_913():
# AdobeVFPrototype_mod.otf is a modified copy of AdobeVFPrototype.otf 1.003
# so that the region indexes in HVAR are listed in a different order from
# those in CFF2. Also MVAR table has been modified to contain (dummy)
# deltas for underline offset and underline thickness just to exercize
# MVAR lookup code.
font_path = get_input_path('AdobeVFPrototype_mod.otf')
save_path = get_temp_file_path()
runner(CMD + ['-a', '-o',
'3', 'g', '_A,W,y', 'U', '_900,0',
'-f', font_path, save_path])
expected_path = get_expected_path('bug913.txt')
assert differ([expected_path, save_path, '-s', 'ad_charset():
font_path = get_bad_input_path('bad_charset.otf')
save_path = get_temp_file_path()
runner(CMD + ['-a', '-f', font_path, save_path])
expected_path = get_expected_path('bad_charset.txt')
assert differ([expected_path, save_path, '-s', 'ug_940():
input_path = get_bad_input_path('bug940_private_blend.otf')
output_path = get_temp_file_path()
with pytest.raises(subprocess.CalledProcessError) as err:
runner(CMD + ['-a', '-o', 'cff2', '-f', input_path, output_path])
assert(err.value.returncode > 0) # error code, not segfault or success
def test_too_many_glyphs_pr955():
input_path = get_bad_input_path('TooManyGlyphsCFF2.otf')
output_path = get_temp_file_path()
with pytest.raises(subprocess.CalledProcessError) as err:
runner(CMD + ['-a', '-o', 'cff', '-f', input_path, output_path])
assert(err.value.returncode > 0) # error code, not hang or success
def test_ttread_varinst():
font_path = get_input_path('AdobeVFPrototype.ttf')
save_path = get_temp_file_path()
runner(CMD + ['-a', '-o', '3', 'g', '_A', 'U', '_500,800',
'-f', font_path, save_path])
expected_path = get_expected_path('vfproto_tt_inst500_800.txt')
assert differ([expected_path, save_path, '-s', 'nused_post2_names():
font_path = get_input_path('SourceSansPro-Regular-cff2-unused-post.otf')
save_path = get_temp_file_path()
runner(CMD + ['-a', '-o', '1', '-f', font_path, save_path])
expected_path = get_expected_path('ssr-cff2-unused-post.txt')
assert differ([expected_path, save_path, '-s', 'eac_reporting():
# This test aims to show that the SEAC operator
# is not reported by all tx modes
font_path = get_input_path('seac.otf')
save_path = get_temp_file_path()
runner(CMD + ['-a', '-o', '6', '-f', font_path, save_path])
expected_path = get_expected_path('seac.dump.txt')
assert differ([expected_path, save_path])
runner(CMD + ['-a', '-o', 'dcf', '5', 'T', '_c',
'-f', font_path, save_path])
expected_path = get_expected_path('seac.dcf.txt')
assert differ([expected_path, save_path])
def test_date_and_time_afm():
input_path = get_input_path('font.otf')
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'afm', '-f', input_path, output_path])
now = time.time()
year = '%s' % time.localtime().tm_year
with open(output_path) as output_file:
lines = output_file.readlines()
file_year = lines[1].split()[2]
assert year == file_year
file_time_str = lines[2].split(': ')[1].strip()
file_time = time.mktime(
time.strptime(file_time_str, '%a %b %d %H:%M:%S %Y'))
hours_diff = abs(now - file_time) / 3600
assert(hours_diff < 1)
def test_date_and_time_ps():
input_path = get_input_path('font.otf')
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'ps', '-f', input_path, output_path])
now = time.time()
with open(output_path) as output_file:
lines = output_file.readlines()
date_str = re.split(r'[()]', lines[5])[1]
date_str = date_str.split(': ')[1]
time_str = re.split(r'[()]', lines[7])[1]
time_str = time_str.split(': ')[1]
file_date_and_time_str = date_str + ' ' + time_str
file_time = time.mktime(
time.strptime(file_date_and_time_str, '%m/%d/%y %H:%M'))
hours_diff = abs(now - file_time) / 3600
assert(hours_diff < 1)
def test_date_and_time_pdf():
input_path = get_input_path('font.otf')
output_path = get_temp_file_path()
runner(CMD + ['-a', '-o', 'pdf', '-f', input_path, output_path])
now = time.time()
tz = time.timezone
tz_hr = abs(int(tz / 3600)) # ignore sign since we're splitting on +/-
tz_min = (tz % 3600) // 60
with open(output_path) as output_file:
lines = output_file.readlines()
creation_date_str = re.split(r'[()]', lines[13])[1]
mod_date_str = re.split(r'[()]', lines[14])[1]
assert(creation_date_str == mod_date_str)
(date_time_str, tz_hr_str, tz_min_str) = \
re.split(r"[:+\-Z']", creation_date_str)[1:4]
creation_time = time.mktime(
time.strptime(date_time_str, '%Y%m%d%H%M%S'))
hours_diff = abs(now - creation_time) / 3600
assert(hours_diff < 1)
creation_tz_hr = int(tz_hr_str)
assert(creation_tz_hr == tz_hr)
creation_tz_min = int(tz_min_str)
assert(creation_tz_min == tz_min)
file_date_str = re.split(r"[():]", lines[36])[2].strip()
file_time_str = re.split(r"[() ]", lines[38])[3]
file_date_time_str = file_date_str + ' ' + file_time_str
file_time = time.mktime(
time.strptime(file_date_time_str, "%d %b %y %H:%M"))
hours_diff = abs(now - file_time) / 3600
assert(hours_diff < 1)
def test_overlap_removal():
input_path = get_input_path('overlaps.ufo')
expected_path = get_expected_path('overlaps.pfa')
output_path = get_temp_file_path()
args = [TOOL, '-t1', '+V', '-o', output_path, input_path]
subprocess.call(args)
assert differ([expected_path, output_path, '-s', PFA_SKIP[0]])
@pytest.mark.parametrize("fmt", [
"cff",
"cff2",
])
def test_nonstd_fontmatrix(fmt):
input_path = get_input_path("nonstdfmtx.otf")
txt_filename = f"nonstdfmtx_{fmt}.txt"
expected_path = get_expected_path(txt_filename)
output_dir = get_temp_dir_path()
bin_output = os.path.join(output_dir, f"nonstdfmtx.{fmt}")
output_path = os.path.join(output_dir, txt_filename)
runner(CMD + ['-a', '-o', fmt, '*S', '*b', '-f', input_path, bin_output])
runner(CMD + ['-a', '-o', 'dump', '-f', bin_output, output_path])
skip = "## Filename "
assert differ([expected_path, output_path, '-s', skip])
def test_pdf_single_glyph():
input_path = get_input_path("bug1218.otf")
pdf_filename = "bug1218.pdf"
expected_path = get_expected_path(pdf_filename)
output_dir = get_temp_dir_path()
output_path = os.path.join(output_dir, pdf_filename)
runner(CMD + ['-a', '-o', 'pdf', '1', '-f', input_path, output_path])
skip = PDF_SKIP[:]
skip.insert(0, '-s')
regex_skip = PDF_SKIP_REGEX[:]
for regex in regex_skip:
skip.append('-r')
skip.append(regex)
assert differ([expected_path, output_path] + skip)
def test_cffread_bug1343():
actual_path = runner(CMD + ['-s', '-f', 'font.otf', '-o', '3'])
expected_path = get_expected_path('font.otf.dump3.txt')
assert differ([expected_path, actual_path, '-s', 'rk.parametrize('arg, input, output, expected', [
('ufo', 'cidfont.subset', 'cidfont_subset.ufo', 'testCID.ufo'),
('t1', 'testCID.ufo', 'cidfont_subset.ufo', 'cidfont.subset'),
(('ufo', 't1'), 'cidfont.subset', 'cidfont_subset.ufo', 'cidfont.subset'),
(('t1', 'ufo'), 'testCID.ufo', 'cidfont_subset.ufo', 'testCID.ufo'),
])
def test_cidkeyed_read_write(arg, input, output, expected):
folder = "cid_roundtrip/"
input_path = get_input_path(folder + input)
output_dir = get_temp_dir_path()
output_path = os.path.join(output_dir, output)
expected_path = get_expected_path(folder + expected)
if isinstance(arg, tuple): # round-trip tests
runner(CMD + ['-a', '-o', arg[0], '-f',
input_path, output_path])
final_output_dir = get_temp_dir_path()
final_output_path = os.path.join(final_output_dir, output)
runner(CMD + ['-a', '-o', arg[1], '-f',
output_path, final_output_path])
output_path = final_output_path
else: # one-way tests
runner(CMD + ['-a', '-o', arg, '-f',
input_path, output_path])
if '.subset' in expected_path:
expected_path = generate_ps_dump(expected_path)
output_path = generate_ps_dump(output_path)
assert differ([expected_path, output_path])
@pytest.mark.parametrize("file", [
"missing_CID.ufo",
"missing_iFD.ufo",
])
def test_cidkeyed_lib_missing(file):
folder = folder = "cidkeyed_missing_lib/"
ufo_input_path = get_input_path(folder + file)
arg = [TOOL, '-t1', '-f', ufo_input_path]
assert subprocess.call(arg) == 6
def test_cff2_windows_line_endings_bug1355():
# Testing writing binary to stdout on Windows
# to ensure line endings are not inserted.
font_path = get_input_path('regular_CFF2.otf')
actual_path = runner(CMD + ['-s', '-a', '-o', 'cff2',
'*S', '*b', '-f', font_path])
expected_path = get_expected_path('bug1355.cff2')
assert differ([expected_path, actual_path, '-m', 'bin'])
| true | true |
f72f3d1c6a35bd919b59685338374f45d915640f | 2,886 | py | Python | python/init_db.py | arenadata/adcm | a499caa30adc2a53e7b3f46c96a865f9e4079e4e | [
"Apache-2.0"
] | 16 | 2019-11-28T18:05:21.000Z | 2021-12-08T18:09:18.000Z | python/init_db.py | arenadata/adcm | a499caa30adc2a53e7b3f46c96a865f9e4079e4e | [
"Apache-2.0"
] | 1,127 | 2019-11-29T08:57:25.000Z | 2022-03-31T20:21:32.000Z | python/init_db.py | arenadata/adcm | a499caa30adc2a53e7b3f46c96a865f9e4079e4e | [
"Apache-2.0"
] | 10 | 2019-11-28T18:05:06.000Z | 2022-01-13T06:16:40.000Z | #!/usr/bin/env python3
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import random
import string
from itertools import chain
import adcm.init_django # pylint: disable=unused-import
from django.contrib.auth.models import User
from cm import issue
from cm.logger import log
from cm.models import (
UserProfile,
DummyData,
CheckLog,
GroupCheckLog,
Cluster,
HostProvider,
ConcernType,
ConcernItem,
)
from cm.bundle import load_adcm
from cm.config import SECRETS_FILE
from cm.job import abort_all
from cm.status_api import Event
def random_string(strlen=10):
return "".join([random.choice(string.ascii_letters) for _ in range(strlen)])
def create_status_user():
user = "status"
try:
User.objects.get(username=user)
return
except User.DoesNotExist:
pass
password = random_string(40)
token = random_string(40)
User.objects.create_superuser(user, "", password)
with open(SECRETS_FILE, 'w', encoding='utf_8') as f:
json.dump({'adcmuser': {'user': user, 'password': password}, 'token': token}, f)
log.info('Update secret file %s OK', SECRETS_FILE)
def create_dummy_data():
DummyData.objects.create()
def clear_temp_tables():
CheckLog.objects.all().delete()
GroupCheckLog.objects.all().delete()
def drop_locks():
"""Drop orphaned locks"""
ConcernItem.objects.filter(type=ConcernType.Lock).delete()
def recheck_issues():
"""
Drop old issues and re-check from scratch
Could slow down startup process
"""
ConcernItem.objects.filter(type=ConcernType.Issue).delete()
for model in chain([Cluster, HostProvider]):
for obj in model.objects.all():
issue.update_hierarchy_issues(obj)
def init():
log.info("Start initializing ADCM DB...")
try:
User.objects.get(username='admin')
except User.DoesNotExist:
User.objects.create_superuser('admin', 'admin@example.com', 'admin')
try:
UserProfile.objects.get(login='admin')
except UserProfile.DoesNotExist:
UserProfile.objects.create(login='admin')
create_status_user()
event = Event()
abort_all(event)
clear_temp_tables()
event.send_state()
load_adcm()
create_dummy_data()
drop_locks()
recheck_issues()
log.info("ADCM DB is initialized")
if __name__ == '__main__':
init()
| 26.722222 | 88 | 0.700277 |
import json
import random
import string
from itertools import chain
import adcm.init_django
from django.contrib.auth.models import User
from cm import issue
from cm.logger import log
from cm.models import (
UserProfile,
DummyData,
CheckLog,
GroupCheckLog,
Cluster,
HostProvider,
ConcernType,
ConcernItem,
)
from cm.bundle import load_adcm
from cm.config import SECRETS_FILE
from cm.job import abort_all
from cm.status_api import Event
def random_string(strlen=10):
return "".join([random.choice(string.ascii_letters) for _ in range(strlen)])
def create_status_user():
user = "status"
try:
User.objects.get(username=user)
return
except User.DoesNotExist:
pass
password = random_string(40)
token = random_string(40)
User.objects.create_superuser(user, "", password)
with open(SECRETS_FILE, 'w', encoding='utf_8') as f:
json.dump({'adcmuser': {'user': user, 'password': password}, 'token': token}, f)
log.info('Update secret file %s OK', SECRETS_FILE)
def create_dummy_data():
DummyData.objects.create()
def clear_temp_tables():
CheckLog.objects.all().delete()
GroupCheckLog.objects.all().delete()
def drop_locks():
ConcernItem.objects.filter(type=ConcernType.Lock).delete()
def recheck_issues():
ConcernItem.objects.filter(type=ConcernType.Issue).delete()
for model in chain([Cluster, HostProvider]):
for obj in model.objects.all():
issue.update_hierarchy_issues(obj)
def init():
log.info("Start initializing ADCM DB...")
try:
User.objects.get(username='admin')
except User.DoesNotExist:
User.objects.create_superuser('admin', 'admin@example.com', 'admin')
try:
UserProfile.objects.get(login='admin')
except UserProfile.DoesNotExist:
UserProfile.objects.create(login='admin')
create_status_user()
event = Event()
abort_all(event)
clear_temp_tables()
event.send_state()
load_adcm()
create_dummy_data()
drop_locks()
recheck_issues()
log.info("ADCM DB is initialized")
if __name__ == '__main__':
init()
| true | true |
f72f3d6d80d945c5a335c62637d517ade6bb22c6 | 234 | py | Python | t/unit/test_exceptions.py | nlundquist/kombu | 483cadced77d82a6ecd0be553b91ce92f04f9617 | [
"BSD-3-Clause"
] | 5,079 | 2015-01-01T03:39:46.000Z | 2022-03-31T07:38:22.000Z | desktop/core/ext-py/kombu-4.3.0/t/unit/test_exceptions.py | zks888/hue | 93a8c370713e70b216c428caa2f75185ef809deb | [
"Apache-2.0"
] | 1,623 | 2015-01-01T08:06:24.000Z | 2022-03-30T19:48:52.000Z | desktop/core/ext-py/kombu-4.3.0/t/unit/test_exceptions.py | zks888/hue | 93a8c370713e70b216c428caa2f75185ef809deb | [
"Apache-2.0"
] | 2,033 | 2015-01-04T07:18:02.000Z | 2022-03-28T19:55:47.000Z | from __future__ import absolute_import, unicode_literals
from case import Mock
from kombu.exceptions import HttpError
class test_HttpError:
def test_str(self):
assert str(HttpError(200, 'msg', Mock(name='response')))
| 19.5 | 64 | 0.75641 | from __future__ import absolute_import, unicode_literals
from case import Mock
from kombu.exceptions import HttpError
class test_HttpError:
def test_str(self):
assert str(HttpError(200, 'msg', Mock(name='response')))
| true | true |
f72f3d7c4544ede280f22ec01cd308bf34c32e57 | 1,686 | py | Python | certbot-runner/setup.py | gerrito333/letsencrypt-cert-manager | 957ea555cc0f18fc3af9c275dc2fc5a8ab0a1668 | [
"MIT"
] | 2 | 2020-07-08T17:36:11.000Z | 2020-07-08T18:20:59.000Z | certbot-runner/setup.py | gerrito333/letsencrypt-cert-manager | 957ea555cc0f18fc3af9c275dc2fc5a8ab0a1668 | [
"MIT"
] | 2 | 2020-07-08T17:57:19.000Z | 2020-07-08T18:00:38.000Z | certbot-runner/setup.py | gerrito333/letsencrypt-cert-manager | 957ea555cc0f18fc3af9c275dc2fc5a8ab0a1668 | [
"MIT"
] | 1 | 2020-12-18T21:49:10.000Z | 2020-12-18T21:49:10.000Z | """Configure package."""
import os
from setuptools import setup, find_packages
# -----------------------------------------------------------------------------
# For information on this file, see:
# https://packaging.python.org/distributing/#setup-args
#
# For examples, look here:
# https://gitlab.pixsystem.net/groups/libraries
# -----------------------------------------------------------------------------
here = os.path.abspath(os.path.dirname(__file__))
# Store version in version['__version__'].
version = {}
with open(os.path.join(here, "lambda_function", "_version.py")) as ver_file:
exec(ver_file.read(), version)
# This is your package/library name.
packages = [
package
for package in find_packages()
if package.startswith("lambda_function")
]
# Put the pip-installable libraries your library depends on here;
# e.g. 'requests'
install_requires = ["certbot", "certbot-dns-route53"]
dependency_links = []
setup_requires = ["pytest-runner"]
tests_require = ["moto", "pytest", "pytest-cov", "pytest-sugar"]
extras_require = {
"dev": ["flake8", "autopep8", "cfn-lint", "sphinx"] + tests_require
}
setup(
name="certbot-runner",
version=version["__version__"],
description="Creates a certificate if it doesn't exist or is about to expire and uploads the files to S3 and ACM.",
packages=packages,
url="https://github.com/cgartner/letsencrypt-cert-manager",
author="Chad Gartner",
author_email="cgartner@x2x.media",
keywords=["lambda"],
install_requires=install_requires,
extras_require=extras_require,
setup_requires=setup_requires,
tests_require=tests_require,
dependency_links=dependency_links,
)
| 29.578947 | 119 | 0.651839 | import os
from setuptools import setup, find_packages
= os.path.abspath(os.path.dirname(__file__))
version = {}
with open(os.path.join(here, "lambda_function", "_version.py")) as ver_file:
exec(ver_file.read(), version)
packages = [
package
for package in find_packages()
if package.startswith("lambda_function")
]
install_requires = ["certbot", "certbot-dns-route53"]
dependency_links = []
setup_requires = ["pytest-runner"]
tests_require = ["moto", "pytest", "pytest-cov", "pytest-sugar"]
extras_require = {
"dev": ["flake8", "autopep8", "cfn-lint", "sphinx"] + tests_require
}
setup(
name="certbot-runner",
version=version["__version__"],
description="Creates a certificate if it doesn't exist or is about to expire and uploads the files to S3 and ACM.",
packages=packages,
url="https://github.com/cgartner/letsencrypt-cert-manager",
author="Chad Gartner",
author_email="cgartner@x2x.media",
keywords=["lambda"],
install_requires=install_requires,
extras_require=extras_require,
setup_requires=setup_requires,
tests_require=tests_require,
dependency_links=dependency_links,
)
| true | true |
f72f3e3c530fb085acf757d2eb07052013668b0a | 105,967 | py | Python | tests/system_tests_link_routes.py | santosh653/qpid-dispatch | cd35c975340f248ea46d35e8a709c0fb585be15c | [
"Apache-2.0"
] | null | null | null | tests/system_tests_link_routes.py | santosh653/qpid-dispatch | cd35c975340f248ea46d35e8a709c0fb585be15c | [
"Apache-2.0"
] | 121 | 2020-09-16T06:03:53.000Z | 2022-03-30T13:03:23.000Z | tests/system_tests_link_routes.py | astitcher/qpid-dispatch | b01c5a7286849c053db9548dbb7586713211eed3 | [
"Apache-2.0"
] | null | null | null | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import os
from time import sleep, time
from threading import Event
from subprocess import PIPE, STDOUT
from system_test import TestCase, Qdrouterd, main_module, TIMEOUT, Process, TestTimeout, \
AsyncTestSender, AsyncTestReceiver, MgmtMsgProxy, unittest, QdManager
from test_broker import FakeBroker
from test_broker import FakeService
from proton import Delivery
from proton import Message
from proton.handlers import MessagingHandler
from proton.reactor import AtMostOnce, Container, DynamicNodeProperties, LinkOption, AtLeastOnce
from proton.reactor import ApplicationEvent
from proton.reactor import EventInjector
from proton.utils import BlockingConnection
from system_tests_drain_support import DrainMessagesHandler, DrainOneMessageHandler, DrainNoMessagesHandler, DrainNoMoreMessagesHandler
from qpid_dispatch.management.client import Node
from qpid_dispatch.management.error import NotFoundStatus, BadRequestStatus
class LinkRouteTest(TestCase):
"""
Tests the linkRoute property of the dispatch router.
Sets up 4 routers (two of which are acting as brokers (QDR.A, QDR.D)). The other two routers have linkRoutes
configured such that matching traffic will be directed to/from the 'fake' brokers.
(please see configs in the setUpClass method to get a sense of how the routers and their connections are configured)
The tests in this class send and receive messages across this network of routers to link routable addresses.
Uses the Python Blocking API to send/receive messages. The blocking api plays neatly into the synchronous nature
of system tests.
QDR.A acting broker #1
+---------+ +---------+ +---------+ +-----------------+
| | <------ | | <----- | |<----| blocking_sender |
| QDR.A | | QDR.B | | QDR.C | +-----------------+
| | ------> | | ------> | | +-------------------+
+---------+ +---------+ +---------+---->| blocking_receiver |
^ | +-------------------+
| |
| V
+---------+
| |
| QDR.D |
| |
+---------+
QDR.D acting broker #2
"""
@classmethod
def get_router(cls, index):
return cls.routers[index]
@classmethod
def setUpClass(cls):
"""Start three routers"""
super(LinkRouteTest, cls).setUpClass()
def router(name, connection):
config = [
('router', {'mode': 'interior', 'id': 'QDR.%s'%name}),
] + connection
config = Qdrouterd.Config(config)
cls.routers.append(cls.tester.qdrouterd(name, config, wait=False))
cls.routers = []
a_listener_port = cls.tester.get_port()
b_listener_port = cls.tester.get_port()
c_listener_port = cls.tester.get_port()
d_listener_port = cls.tester.get_port()
test_tag_listener_port = cls.tester.get_port()
router('A',
[
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
])
router('B',
[
# Listener for clients, note that the tests assume this listener is first in this list:
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': b_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
('listener', {'name': 'test-tag', 'role': 'route-container', 'host': '0.0.0.0', 'port': test_tag_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
# This is an route-container connection made from QDR.B's ephemeral port to a_listener_port
('connector', {'name': 'broker', 'role': 'route-container', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
# Only inter router communication must happen on 'inter-router' connectors. This connector makes
# a connection from the router B's ephemeral port to c_listener_port
('connector', {'name': 'routerC', 'role': 'inter-router', 'host': '0.0.0.0', 'port': c_listener_port}),
# This is an on-demand connection made from QDR.B's ephemeral port to d_listener_port
('connector', {'name': 'routerD', 'role': 'route-container', 'host': '0.0.0.0', 'port': d_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
#('linkRoute', {'prefix': 'org.apache', 'connection': 'broker', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache', 'containerId': 'QDR.A', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache', 'containerId': 'QDR.A', 'direction': 'out'}),
('linkRoute', {'prefix': 'pulp.task', 'connection': 'test-tag', 'direction': 'in'}),
('linkRoute', {'prefix': 'pulp.task', 'connection': 'test-tag', 'direction': 'out'}),
# addresses matching pattern 'a.*.toA.#' route to QDR.A
('linkRoute', {'pattern': 'a.*.toA.#', 'containerId': 'QDR.A', 'direction': 'in'}),
('linkRoute', {'pattern': 'a.*.toA.#', 'containerId': 'QDR.A', 'direction': 'out'}),
# addresses matching pattern 'a.*.toD.#' route to QDR.D
# Dont change dir to direction here so we can make sure that the dir attribute is still working.
('linkRoute', {'pattern': 'a.*.toD.#', 'containerId': 'QDR.D', 'dir': 'in'}),
('linkRoute', {'pattern': 'a.*.toD.#', 'containerId': 'QDR.D', 'dir': 'out'})
]
)
router('C',
[
# The client will exclusively use the following listener to
# connect to QDR.C, the tests assume this is the first entry
# in the list
('listener', {'host': '0.0.0.0', 'role': 'normal', 'port': cls.tester.get_port(), 'saslMechanisms': 'ANONYMOUS'}),
('listener', {'host': '0.0.0.0', 'role': 'inter-router', 'port': c_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
# The dot(.) at the end is ignored by the address hashing scheme.
('linkRoute', {'prefix': 'org.apache.', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache.', 'direction': 'out'}),
('linkRoute', {'prefix': 'pulp.task', 'direction': 'in'}),
('linkRoute', {'prefix': 'pulp.task', 'direction': 'out'}),
('linkRoute', {'pattern': 'a.*.toA.#', 'direction': 'in'}),
('linkRoute', {'pattern': 'a.*.toA.#', 'direction': 'out'}),
('linkRoute', {'pattern': 'a.*.toD.#', 'direction': 'in'}),
('linkRoute', {'pattern': 'a.*.toD.#', 'direction': 'out'})
]
)
router('D', # sink for QDR.D routes
[
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': d_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
])
# Wait for the routers to locate each other, and for route propagation
# to settle
cls.routers[1].wait_router_connected('QDR.C')
cls.routers[2].wait_router_connected('QDR.B')
cls.routers[2].wait_address("org.apache", remotes=1, delay=0.5, count=2)
# This is not a classic router network in the sense that QDR.A and D are acting as brokers. We allow a little
# bit more time for the routers to stabilize.
sleep(2)
def run_qdstat_linkRoute(self, address, args=None):
cmd = ['qdstat', '--bus', str(address), '--timeout', str(TIMEOUT) ] + ['--linkroute']
if args:
cmd = cmd + args
p = self.popen(
cmd,
name='qdstat-'+self.id(), stdout=PIPE, expect=None,
universal_newlines=True)
out = p.communicate()[0]
assert p.returncode == 0, "qdstat exit status %s, output:\n%s" % (p.returncode, out)
return out
def run_qdmanage(self, cmd, input=None, expect=Process.EXIT_OK, address=None):
p = self.popen(
['qdmanage'] + cmd.split(' ') + ['--bus', address or self.address(), '--indent=-1', '--timeout', str(TIMEOUT)],
stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
universal_newlines=True)
out = p.communicate(input)[0]
try:
p.teardown()
except Exception as e:
raise Exception("%s\n%s" % (e, out))
return out
def test_aaa_qdmanage_query_link_route(self):
"""
qdmanage converts short type to long type and this test specifically tests if qdmanage is actually doing
the type conversion correctly by querying with short type and long type.
"""
cmd = 'QUERY --type=linkRoute'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
# Make sure there is a dir of in and out.
self.assertIn('"direction": "in"', out)
self.assertIn('"direction": "out"', out)
self.assertIn('"containerId": "QDR.A"', out)
# Use the long type and make sure that qdmanage does not mess up the long type
cmd = 'QUERY --type=org.apache.qpid.dispatch.router.config.linkRoute'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
# Make sure there is a dir of in and out.
self.assertIn('"direction": "in"', out)
self.assertIn('"direction": "out"', out)
self.assertIn('"containerId": "QDR.A"', out)
identity = out[out.find("identity") + 12: out.find("identity") + 13]
cmd = 'READ --type=linkRoute --identity=' + identity
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
self.assertIn(identity, out)
exception_occurred = False
try:
# This identity should not be found
cmd = 'READ --type=linkRoute --identity=9999'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
except Exception as e:
exception_occurred = True
self.assertIn("NotFoundStatus: Not Found", str(e))
self.assertTrue(exception_occurred)
exception_occurred = False
try:
# There is no identity specified, this is a bad request
cmd = 'READ --type=linkRoute'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
except Exception as e:
exception_occurred = True
self.assertIn("BadRequestStatus: No name or identity provided", str(e))
self.assertTrue(exception_occurred)
cmd = 'CREATE --type=autoLink address=127.0.0.1 direction=in connection=routerC'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
identity = out[out.find("identity") + 12: out.find("identity") + 14]
cmd = 'READ --type=autoLink --identity=' + identity
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
self.assertIn(identity, out)
def test_bbb_qdstat_link_routes_routerB(self):
"""
Runs qdstat on router B to make sure that router B has 4 link routes,
each having one 'in' and one 'out' entry
"""
out = self.run_qdstat_linkRoute(self.routers[1].addresses[0])
for route in ['a.*.toA.#', 'a.*.toD.#', 'org.apache', 'pulp.task']:
self.assertIn(route, out)
out_list = out.split()
self.assertEqual(out_list.count('in'), 4)
self.assertEqual(out_list.count('out'), 4)
parts = out.split("\n")
self.assertEqual(len(parts), 15)
out = self.run_qdstat_linkRoute(self.routers[1].addresses[0], args=['--limit=1'])
parts = out.split("\n")
self.assertEqual(len(parts), 8)
def test_ccc_qdstat_link_routes_routerC(self):
"""
Runs qdstat on router C to make sure that router C has 4 link routes,
each having one 'in' and one 'out' entry
"""
out = self.run_qdstat_linkRoute(self.routers[2].addresses[0])
out_list = out.split()
self.assertEqual(out_list.count('in'), 4)
self.assertEqual(out_list.count('out'), 4)
def test_ddd_partial_link_route_match(self):
"""
The linkRoute on Routers C and B is set to org.apache.
Creates a receiver listening on the address 'org.apache.dev' and a sender that sends to address 'org.apache.dev'.
Sends a message to org.apache.dev via router QDR.C and makes sure that the message was successfully
routed (using partial address matching) and received using pre-created links that were created as a
result of specifying addresses in the linkRoute attribute('org.apache.').
"""
hello_world_1 = "Hello World_1!"
# Connects to listener #2 on QDR.C
addr = self.routers[2].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache.dev
blocking_receiver = blocking_connection.create_receiver(address="org.apache.dev")
apply_options = AtMostOnce()
# Sender to org.apache.dev
blocking_sender = blocking_connection.create_sender(address="org.apache.dev", options=apply_options)
msg = Message(body=hello_world_1)
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_1, received_message.body)
# Connect to the router acting like the broker (QDR.A) and check the deliveriesIngress and deliveriesEgress
local_node = Node.connect(self.routers[0].addresses[0], timeout=TIMEOUT)
self.assertEqual(u'QDR.A', local_node.query(type='org.apache.qpid.dispatch.router',
attribute_names=[u'id']).results[0][0])
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.dev').deliveriesEgress)
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.dev').deliveriesIngress)
# There should be 4 links -
# 1. outbound receiver link on org.apache.dev
# 2. inbound sender link on blocking_sender
# 3. inbound link to the $management
# 4. outbound link to $management
# self.assertEqual(4, len()
self.assertEqual(4, len(local_node.query(type='org.apache.qpid.dispatch.router.link').results))
blocking_connection.close()
def test_partial_link_route_match_1(self):
"""
This test is pretty much the same as the previous test (test_partial_link_route_match) but the connection is
made to router QDR.B instead of QDR.C and we expect to see the same behavior.
"""
hello_world_2 = "Hello World_2!"
addr = self.routers[1].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache.dev
blocking_receiver = blocking_connection.create_receiver(address="org.apache.dev.1")
apply_options = AtMostOnce()
# Sender to to org.apache.dev
blocking_sender = blocking_connection.create_sender(address="org.apache.dev.1", options=apply_options)
msg = Message(body=hello_world_2)
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_2, received_message.body)
local_node = Node.connect(self.routers[0].addresses[0], timeout=TIMEOUT)
# Make sure that the router node acting as the broker (QDR.A) had one message routed through it. This confirms
# that the message was link routed
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.dev.1').deliveriesEgress)
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.dev.1').deliveriesIngress)
blocking_connection.close()
def test_full_link_route_match(self):
"""
The linkRoute on Routers C and B is set to org.apache.
Creates a receiver listening on the address 'org.apache' and a sender that sends to address 'org.apache'.
Sends a message to org.apache via router QDR.C and makes sure that the message was successfully
routed (using full address matching) and received using pre-created links that were created as a
result of specifying addresses in the linkRoute attribute('org.apache.').
"""
hello_world_3 = "Hello World_3!"
# Connects to listener #2 on QDR.C
addr = self.routers[2].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache
blocking_receiver = blocking_connection.create_receiver(address="org.apache")
apply_options = AtMostOnce()
# Sender to to org.apache
blocking_sender = blocking_connection.create_sender(address="org.apache", options=apply_options)
msg = Message(body=hello_world_3)
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_3, received_message.body)
local_node = Node.connect(self.routers[0].addresses[0], timeout=TIMEOUT)
# Make sure that the router node acting as the broker (QDR.A) had one message routed through it. This confirms
# that the message was link routed
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache').deliveriesEgress)
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache').deliveriesIngress)
blocking_connection.close()
def _link_route_pattern_match(self, connect_node, include_host,
exclude_host, test_address,
expected_pattern):
"""
This helper function ensures that messages sent to 'test_address' pass
through 'include_host', and are *not* routed to 'exclude_host'
"""
hello_pattern = "Hello Pattern!"
route = 'M0' + test_address
# Connect to the two 'waypoints', ensure the route is not present on
# either
node_A = Node.connect(include_host, timeout=TIMEOUT)
node_B = Node.connect(exclude_host, timeout=TIMEOUT)
for node in [node_A, node_B]:
self.assertRaises(NotFoundStatus,
node.read,
type='org.apache.qpid.dispatch.router.address',
name=route)
# wait until the host we're connecting to gets its next hop for the
# pattern we're connecting to
connect_node.wait_address(expected_pattern, remotes=1, delay=0.1, count=2)
# Connect to 'connect_node' and send message to 'address'
blocking_connection = BlockingConnection(connect_node.addresses[0])
blocking_receiver = blocking_connection.create_receiver(address=test_address)
blocking_sender = blocking_connection.create_sender(address=test_address,
options=AtMostOnce())
msg = Message(body=hello_pattern)
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_pattern, received_message.body)
# verify test_address is only present on include_host and not on exclude_host
self.assertRaises(NotFoundStatus,
node_B.read,
type='org.apache.qpid.dispatch.router.address',
name=route)
self.assertEqual(1, node_A.read(type='org.apache.qpid.dispatch.router.address',
name=route).deliveriesIngress)
self.assertEqual(1, node_A.read(type='org.apache.qpid.dispatch.router.address',
name=route).deliveriesIngress)
# drop the connection and verify that test_address is no longer on include_host
blocking_connection.close()
timeout = time() + TIMEOUT
while True:
try:
node_A.read(type='org.apache.qpid.dispatch.router.address',
name=route)
if time() > timeout:
raise Exception("Expected route '%s' to expire!" % route)
sleep(0.1)
except NotFoundStatus:
break;
node_A.close()
node_B.close()
def test_link_route_pattern_match(self):
"""
Verify the addresses match the proper patterns and are routed to the
proper 'waypoint' only
"""
qdr_A = self.routers[0].addresses[0]
qdr_D = self.routers[3].addresses[0]
qdr_C = self.routers[2] # note: the node, not the address!
self._link_route_pattern_match(connect_node=qdr_C,
include_host=qdr_A,
exclude_host=qdr_D,
test_address='a.notD.toA',
expected_pattern='a.*.toA.#')
self._link_route_pattern_match(connect_node=qdr_C,
include_host=qdr_D,
exclude_host=qdr_A,
test_address='a.notA.toD',
expected_pattern='a.*.toD.#')
self._link_route_pattern_match(connect_node=qdr_C,
include_host=qdr_A,
exclude_host=qdr_D,
test_address='a.toD.toA.xyz',
expected_pattern='a.*.toA.#')
self._link_route_pattern_match(connect_node=qdr_C,
include_host=qdr_D,
exclude_host=qdr_A,
test_address='a.toA.toD.abc',
expected_pattern='a.*.toD.#')
def test_custom_annotations_match(self):
"""
The linkRoute on Routers C and B is set to org.apache.
Creates a receiver listening on the address 'org.apache' and a sender that sends to address 'org.apache'.
Sends a message with custom annotations to org.apache via router QDR.C and makes sure that the message was successfully
routed (using full address matching) and received using pre-created links that were created as a
result of specifying addresses in the linkRoute attribute('org.apache.'). Make sure custom annotations arrived as well.
"""
hello_world_3 = "Hello World_3!"
# Connects to listener #2 on QDR.C
addr = self.routers[2].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache
blocking_receiver = blocking_connection.create_receiver(address="org.apache.2")
apply_options = AtMostOnce()
# Sender to to org.apache
blocking_sender = blocking_connection.create_sender(address="org.apache.2", options=apply_options)
msg = Message(body=hello_world_3)
annotations = {'custom-annotation': '1/Custom_Annotation'}
msg.annotations = annotations
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_3, received_message.body)
self.assertEqual(received_message.annotations, annotations)
blocking_connection.close()
def test_full_link_route_match_1(self):
"""
This test is pretty much the same as the previous test (test_full_link_route_match) but the connection is
made to router QDR.B instead of QDR.C and we expect the message to be link routed successfully.
"""
hello_world_4 = "Hello World_4!"
addr = self.routers[1].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache
blocking_receiver = blocking_connection.create_receiver(address="org.apache.1")
apply_options = AtMostOnce()
# Sender to to org.apache
blocking_sender = blocking_connection.create_sender(address="org.apache.1", options=apply_options)
msg = Message(body=hello_world_4)
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_4, received_message.body)
local_node = Node.connect(self.routers[0].addresses[0], timeout=TIMEOUT)
# Make sure that the router node acting as the broker (QDR.A) had one message routed through it. This confirms
# that the message was link routed
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.1').deliveriesEgress)
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.1').deliveriesIngress)
blocking_connection.close()
def test_zzz_qdmanage_delete_link_route(self):
"""
We are deleting the link route using qdmanage short name. This should be the last test to run
"""
local_node = Node.connect(self.routers[1].addresses[0], timeout=TIMEOUT)
res = local_node.query(type='org.apache.qpid.dispatch.router')
results = res.results[0]
attribute_list = res.attribute_names
result_list = local_node.query(type='org.apache.qpid.dispatch.router.config.linkRoute').results
self.assertEqual(results[attribute_list.index('linkRouteCount')], len(result_list))
# First delete linkRoutes on QDR.B
for rid in range(8):
cmd = 'DELETE --type=linkRoute --identity=' + result_list[rid][1]
self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
cmd = 'QUERY --type=linkRoute'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
self.assertEqual(out.rstrip(), '[]')
# linkRoutes now gone on QDR.B but remember that it still exist on QDR.C
# We will now try to create a receiver on address org.apache.dev on QDR.C.
# Since the linkRoute on QDR.B is gone, QDR.C
# will not allow a receiver to be created since there is no route to destination.
# Connects to listener #2 on QDR.C
addr = self.routers[2].addresses[0]
# Now delete linkRoutes on QDR.C to eradicate linkRoutes completely
local_node = Node.connect(addr, timeout=TIMEOUT)
result_list = local_node.query(type='org.apache.qpid.dispatch.router.config.linkRoute').results
# QDR.C has 8 link routes configured, nuke 'em:
self.assertEqual(8, len(result_list))
for rid in range(8):
cmd = 'DELETE --type=linkRoute --identity=' + result_list[rid][1]
self.run_qdmanage(cmd=cmd, address=addr)
cmd = 'QUERY --type=linkRoute'
out = self.run_qdmanage(cmd=cmd, address=addr)
self.assertEqual(out.rstrip(), '[]')
res = local_node.query(type='org.apache.qpid.dispatch.router')
results = res.results[0]
attribute_list = res.attribute_names
self.assertEqual(results[attribute_list.index('linkRouteCount')], 0)
blocking_connection = BlockingConnection(addr, timeout=3)
# Receive on org.apache.dev (this address used to be linkRouted but not anymore since we deleted linkRoutes
# on both QDR.C and QDR.B)
blocking_receiver = blocking_connection.create_receiver(address="org.apache.dev")
apply_options = AtMostOnce()
hello_world_1 = "Hello World_1!"
# Sender to org.apache.dev
blocking_sender = blocking_connection.create_sender(address="org.apache.dev", options=apply_options)
msg = Message(body=hello_world_1)
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive(timeout=5)
self.assertEqual(hello_world_1, received_message.body)
def test_yyy_delivery_tag(self):
"""
Tests that the router carries over the delivery tag on a link routed delivery
"""
listening_address = self.routers[1].addresses[1]
sender_address = self.routers[2].addresses[0]
qdstat_address = self.routers[2].addresses[0]
test = DeliveryTagsTest(sender_address, listening_address, qdstat_address)
test.run()
self.assertEqual(None, test.error)
def test_yyy_invalid_delivery_tag(self):
test = InvalidTagTest(self.routers[2].addresses[0])
test.run()
self.assertEqual(None, test.error)
def test_close_with_unsettled(self):
test = CloseWithUnsettledTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def test_www_drain_support_all_messages(self):
drain_support = DrainMessagesHandler(self.routers[2].addresses[0])
drain_support.run()
self.assertEqual(None, drain_support.error)
def test_www_drain_support_one_message(self):
drain_support = DrainOneMessageHandler(self.routers[2].addresses[0])
drain_support.run()
self.assertEqual(None, drain_support.error)
def test_www_drain_support_no_messages(self):
drain_support = DrainNoMessagesHandler(self.routers[2].addresses[0])
drain_support.run()
self.assertEqual(None, drain_support.error)
def test_www_drain_support_no_more_messages(self):
drain_support = DrainNoMoreMessagesHandler(self.routers[2].addresses[0])
drain_support.run()
self.assertEqual(None, drain_support.error)
def test_link_route_terminus_address(self):
# The receiver is attaching to router B to a listener that has link route for address 'pulp.task' setup.
listening_address = self.routers[1].addresses[1]
# Run the query on a normal port
query_address_listening = self.routers[1].addresses[0]
# Sender is attaching to router C
sender_address = self.routers[2].addresses[0]
query_address_sending = self.routers[2].addresses[0]
test = TerminusAddrTest(sender_address, listening_address, query_address_sending, query_address_listening)
test.run()
self.assertTrue(test.in_receiver_found)
self.assertTrue(test.out_receiver_found)
self.assertTrue(test.in_sender_found)
self.assertTrue(test.out_sender_found)
def test_dynamic_source(self):
test = DynamicSourceTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def test_dynamic_target(self):
test = DynamicTargetTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def test_detach_without_close(self):
test = DetachNoCloseTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def test_detach_mixed_close(self):
test = DetachMixedCloseTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def _multi_link_send_receive(self, send_host, receive_host, name):
senders = ["%s/%s" % (send_host, address) for address in ["org.apache.foo", "org.apache.bar"]]
receivers = ["%s/%s" % (receive_host, address) for address in ["org.apache.foo", "org.apache.bar"]]
test = MultiLinkSendReceive(senders, receivers, name)
test.run()
self.assertEqual(None, test.error)
def test_same_name_route_receivers_through_B(self):
self._multi_link_send_receive(self.routers[0].addresses[0], self.routers[1].addresses[0], "recv_through_B")
def test_same_name_route_senders_through_B(self):
self._multi_link_send_receive(self.routers[1].addresses[0], self.routers[0].addresses[0], "send_through_B")
def test_same_name_route_receivers_through_C(self):
self._multi_link_send_receive(self.routers[0].addresses[0], self.routers[2].addresses[0], "recv_through_C")
def test_same_name_route_senders_through_C(self):
self._multi_link_send_receive(self.routers[2].addresses[0], self.routers[0].addresses[0], "send_through_C")
def test_echo_detach_received(self):
"""
Create two receivers to link routed address org.apache.dev
Create a sender to the same address that the receiver is listening on and send 100 messages.
After the receivers receive 10 messages each, the receivers will detach and expect to receive ten
detaches in response.
"""
test = EchoDetachReceived(self.routers[2].addresses[0], self.routers[2].addresses[0])
test.run()
self.assertEqual(None, test.error)
def test_bad_link_route_config(self):
"""
What happens when the link route create request is malformed?
"""
mgmt = self.routers[1].management
# zero length prefix
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-1",
attributes={'prefix': '',
'containerId': 'FakeBroker',
'direction': 'in'})
# pattern wrong type
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-2",
attributes={'pattern': 666,
'containerId': 'FakeBroker',
'direction': 'in'})
# invalid pattern (no tokens)
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-3",
attributes={'pattern': '///',
'containerId': 'FakeBroker',
'direction': 'in'})
# empty attributes
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-4",
attributes={})
# both pattern and prefix
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-5",
attributes={'prefix': 'a1',
'pattern': 'b2',
'containerId': 'FakeBroker',
'direction': 'in'})
# bad direction
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-6",
attributes={'pattern': 'b2',
'containerId': 'FakeBroker',
'direction': 'nowhere'})
# bad distribution
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-7",
attributes={'pattern': 'b2',
'containerId': 'FakeBroker',
'direction': 'in',
"distribution": "dilly dilly"})
# no direction
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-8",
attributes={'prefix': 'b2',
'containerId': 'FakeBroker'})
# neither pattern nor prefix
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-9",
attributes={'direction': 'out',
'containerId': 'FakeBroker'})
class DeliveryTagsTest(MessagingHandler):
def __init__(self, sender_address, listening_address, qdstat_address):
super(DeliveryTagsTest, self).__init__()
self.sender_address = sender_address
self.listening_address = listening_address
self.sender = None
self.receiver_connection = None
self.sender_connection = None
self.qdstat_address = qdstat_address
self.id = '1235'
self.times = 1
self.sent = 0
self.rcvd = 0
self.delivery_tag_verified = False
# The delivery tag we are going to send in the transfer frame
# We will later make sure that the same delivery tag shows up on the receiving end in the link routed case.
# KAG: force the literal to type 'str' due to SWIG weirdness: on 2.X a
# delivery tag cannot be unicode (must be binary), but on 3.X it must
# be unicode! See https://issues.apache.org/jira/browse/PROTON-1843
self.delivery_tag = str('92319')
self.error = None
def timeout(self):
self.error = "Timeout expired: sent=%d rcvd=%d" % (self.sent, self.rcvd)
if self.receiver_connection:
self.receiver_connection.close()
if self.sender_connection:
self.sender_connection.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.receiver_connection = event.container.connect(self.listening_address)
def on_connection_remote_open(self, event):
if event.connection == self.receiver_connection:
continue_loop = True
# Don't open the sender connection unless we can make sure that there is a remote receiver ready to
# accept the message.
# If there is no remote receiver, the router will throw a 'No route to destination' error when
# creating sender connection.
# The following loops introduces a wait before creating the sender connection. It gives time to the
# router so that the address Dpulp.task can show up on the remoteCount
i = 0
while continue_loop:
if i > 100: # If we have run the read command for more than hundred times and we still do not have
# the remoteCount set to 1, there is a problem, just exit out of the function instead
# of looping to infinity.
self.receiver_connection.close()
return
local_node = Node.connect(self.qdstat_address, timeout=TIMEOUT)
out = local_node.read(type='org.apache.qpid.dispatch.router.address', name='Dpulp.task').remoteCount
if out == 1:
continue_loop = False
else:
i += 1
sleep(0.25)
self.sender_connection = event.container.connect(self.sender_address)
self.sender = event.container.create_sender(self.sender_connection, "pulp.task", options=AtMostOnce())
def on_sendable(self, event):
if self.times == 1:
msg = Message(body="Hello World")
self.sender.send(msg, tag=self.delivery_tag)
self.times += 1
self.sent += 1
def on_message(self, event):
if "Hello World" == event.message.body:
self.rcvd += 1
# If the tag on the delivery is the same as the tag we sent with the initial transfer, it means
# that the router has propagated the delivery tag successfully because of link routing.
if self.delivery_tag != event.delivery.tag:
self.error = "Delivery-tag: expected:%r got:%r" % (self.delivery_tag, event.delivery.tag)
self.receiver_connection.close()
self.sender_connection.close()
self.timer.cancel()
def run(self):
Container(self).run()
class CloseWithUnsettledTest(MessagingHandler):
##
## This test sends a message across an attach-routed link. While the message
## is unsettled, the client link is closed. The test is ensuring that the
## router does not crash during the closing of the links.
##
def __init__(self, normal_addr, route_addr):
super(CloseWithUnsettledTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.CWUtest"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.sender = event.container.create_sender(self.conn_normal, self.dest)
def on_connection_closed(self, event):
self.conn_route.close()
self.timer.cancel()
def on_link_opened(self, event):
if event.receiver:
self.receiver = event.receiver
self.receiver.flow(1)
def on_sendable(self, event):
msg = Message(body="CloseWithUnsettled")
event.sender.send(msg)
def on_message(self, event):
self.conn_normal.close()
def run(self):
Container(self).run()
class DynamicSourceTest(MessagingHandler):
##
## This test verifies that a dynamic source can be propagated via link-route to
## a route-container.
##
def __init__(self, normal_addr, route_addr):
super(DynamicSourceTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.DynamicSource"
self.address = "DynamicSourceAddress"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.receiver = event.container.create_receiver(self.conn_normal, None, dynamic=True,options=DynamicNodeProperties({"x-opt-qd.address":u"pulp.task.abc"}))
def on_link_opened(self, event):
if event.receiver == self.receiver:
if self.receiver.remote_source.address != self.address:
self.error = "Expected %s, got %s" % (self.address, self.receiver.remote_source.address)
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
def on_link_opening(self, event):
if event.sender:
self.sender = event.sender
if not self.sender.remote_source.dynamic:
self.error = "Expected sender with dynamic source"
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
self.sender.source.address = self.address
self.sender.open()
def run(self):
Container(self).run()
class DynamicTarget(LinkOption):
def apply(self, link):
link.target.dynamic = True
link.target.address = None
class DynamicTargetTest(MessagingHandler):
##
## This test verifies that a dynamic source can be propagated via link-route to
## a route-container.
##
def __init__(self, normal_addr, route_addr):
super(DynamicTargetTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.DynamicTarget"
self.address = "DynamicTargetAddress"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.sender = event.container.create_sender(self.conn_normal, None, options=\
[DynamicTarget(), DynamicNodeProperties({"x-opt-qd.address":u"pulp.task.abc"})])
def on_link_opened(self, event):
if event.sender == self.sender:
if self.sender.remote_target.address != self.address:
self.error = "Expected %s, got %s" % (self.address, self.receiver.remote_source.address)
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
def on_link_opening(self, event):
if event.receiver:
self.receiver = event.receiver
if not self.receiver.remote_target.dynamic:
self.error = "Expected receiver with dynamic source"
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
self.receiver.target.address = self.address
self.receiver.open()
def run(self):
Container(self).run()
class DetachNoCloseTest(MessagingHandler):
##
## This test verifies that link-detach (not close) is propagated properly
##
def __init__(self, normal_addr, route_addr):
super(DetachNoCloseTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.DetachNoClose"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def stop(self):
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.receiver = event.container.create_receiver(self.conn_normal, self.dest)
def on_link_opened(self, event):
if event.receiver == self.receiver:
self.receiver.detach()
def on_link_remote_detach(self, event):
if event.sender == self.sender:
self.sender.detach()
if event.receiver == self.receiver:
##
## Test passed, we expected a detach on the propagated sender and back
##
self.stop()
def on_link_closing(self, event):
if event.sender == self.sender:
self.error = 'Propagated link was closed. Expected it to be detached'
self.stop()
if event.receiver == self.receiver:
self.error = 'Client link was closed. Expected it to be detached'
self.stop()
def on_link_opening(self, event):
if event.sender:
self.sender = event.sender
self.sender.source.address = self.sender.remote_source.address
self.sender.open()
def run(self):
Container(self).run()
class DetachMixedCloseTest(MessagingHandler):
##
## This test verifies that link-detach (not close) is propagated properly
##
def __init__(self, normal_addr, route_addr):
super(DetachMixedCloseTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.DetachMixedClose"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def stop(self):
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.receiver = event.container.create_receiver(self.conn_normal, self.dest)
def on_link_opened(self, event):
if event.receiver == self.receiver:
self.receiver.detach()
def on_link_remote_detach(self, event):
if event.sender == self.sender:
self.sender.close()
if event.receiver == self.receiver:
self.error = 'Client link was detached. Expected it to be closed'
self.stop()
def on_link_closing(self, event):
if event.sender == self.sender:
self.error = 'Propagated link was closed. Expected it to be detached'
self.stop()
if event.receiver == self.receiver:
##
## Test Passed
##
self.stop()
def on_link_opening(self, event):
if event.sender:
self.sender = event.sender
self.sender.source.address = self.sender.remote_source.address
self.sender.open()
def run(self):
Container(self).run()
# Test to validate fix for DISPATCH-927
class EchoDetachReceived(MessagingHandler):
def __init__(self, sender_address, recv_address):
super(EchoDetachReceived, self).__init__()
self.sender_address = sender_address
self.recv_address = recv_address
self.dest = "org.apache.dev"
self.num_msgs = 100
self.num_receivers = 10
self.msgs_sent = 0
self.receiver_conn = None
self.sender_conn = None
self.sender = None
self.receiver_dict = {}
self.error = None
self.receiver_attaches = 0
self.timer = None
self.sender_attached = False
self.received_msgs_dict = {}
self.receiver_detach_dict = {}
self.num_detaches_echoed = 0
@property
def msgs_received(self):
return sum(self.received_msgs_dict.values())
def timeout(self):
self.bail("Timeout Expired: msgs_sent=%d msgs_received=%d, number of detaches received=%d"
% (self.msgs_sent, self.msgs_received, self.num_detaches_echoed))
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
# Create two separate connections for sender and receivers
self.receiver_conn = event.container.connect(self.recv_address)
self.sender_conn = event.container.connect(self.sender_address)
for i in range(self.num_receivers):
name = "R%d" % i
self.receiver_dict[name] = event.container.create_receiver(self.receiver_conn, self.dest, name=name)
self.received_msgs_dict[name] = 0
def bail(self, text=None):
self.error = text
self.sender_conn.close()
self.receiver_conn.close()
self.timer.cancel()
def on_link_opened(self, event):
if event.receiver:
if event.receiver.name in list(self.receiver_dict):
self.receiver_attaches+=1
# The response receiver attaches have been received. The receiver sent attaches which was link routed
# all the way to the 'broker' router and the response attaches have come back.
# It is now time to create the sender.
if self.receiver_attaches == self.num_receivers:
self.sender = event.container.create_sender(self.sender_conn, self.dest)
elif event.sender:
if not self.sender_attached:
if event.sender == self.sender:
# The sender attaches were link routed as well and the response attach has been received.
self.sender_attached = True
def on_sendable(self, event):
# The sender will send 100 messages
if self.receiver_attaches == self.num_receivers and self.sender_attached:
if self.msgs_sent < self.num_msgs:
msg = Message(body="Hello World")
self.sender.send(msg)
self.msgs_sent += 1
def on_message(self, event):
if event.receiver and event.receiver.name in list(self.receiver_dict):
self.received_msgs_dict[event.receiver.name] += 1
if sum(self.received_msgs_dict.values()) == self.num_msgs:
# The receivers have received a total of 100 messages. Close the receivers. The detach sent by these
# receivers will travel all the way over the link route and the 'broker' router will respond with a
# detach
for receiver in list(self.receiver_dict):
self.receiver_dict[receiver].close()
def on_link_closed(self, event):
if event.receiver.name in list(self.receiver_dict) and event.receiver.name not in list(self.receiver_detach_dict):
self.receiver_detach_dict[event.receiver.name] = event.receiver
self.num_detaches_echoed += 1
# Terminate the test only if both detach frames have been received.
if all(receiver in list(self.receiver_detach_dict) for receiver in list(self.receiver_dict)):
self.bail()
def run(self):
Container(self).run()
class TerminusAddrTest(MessagingHandler):
"""
This tests makes sure that the link route address is visible in the output of qdstat -l command.
Sets up a sender on address pulp.task.terminusTestSender and a receiver on pulp.task.terminusTestReceiver.
Connects to the router to which the sender is attached and makes sure that the pulp.task.terminusTestSender address
shows up with an 'in' and 'out'
Similarly connects to the router to which the receiver is attached and makes sure that the
pulp.task.terminusTestReceiver address shows up with an 'in' and 'out'
"""
def __init__(self, sender_address, listening_address, query_address_sending, query_address_listening):
super(TerminusAddrTest, self).__init__()
self.sender_address = sender_address
self.listening_address = listening_address
self.sender = None
self.receiver = None
self.message_received = False
self.receiver_connection = None
self.sender_connection = None
# We will run a query on the same router where the sender is attached
self.query_address_sending = query_address_sending
# We will run a query on the same router where the receiver is attached
self.query_address_listening = query_address_listening
self.count = 0
self.in_receiver_found = False
self.out_receiver_found = False
self.in_sender_found = False
self.out_sender_found = False
self.receiver_link_opened = False
self.sender_link_opened = False
def on_start(self, event):
self.receiver_connection = event.container.connect(self.listening_address)
def on_connection_remote_open(self, event):
if event.connection == self.receiver_connection:
continue_loop = True
# The following loops introduces a wait. It gives time to the
# router so that the address Dpulp.task can show up on the remoteCount
i = 0
while continue_loop:
if i > 100: # If we have run the read command for more than hundred times and we still do not have
# the remoteCount set to 1, there is a problem, just exit out of the function instead
# of looping to infinity.
self.receiver_connection.close()
return
local_node = Node.connect(self.query_address_sending, timeout=TIMEOUT)
out = local_node.read(type='org.apache.qpid.dispatch.router.address', name='Dpulp.task').remoteCount
if out == 1:
continue_loop = False
i += 1
sleep(0.25)
self.sender_connection = event.container.connect(self.sender_address)
# Notice here that the receiver and sender are listening on different addresses. Receiver on
# pulp.task.terminusTestReceiver and the sender on pulp.task.terminusTestSender
self.receiver = event.container.create_receiver(self.receiver_connection, "pulp.task.terminusTestReceiver")
self.sender = event.container.create_sender(self.sender_connection, "pulp.task.terminusTestSender", options=AtMostOnce())
def on_link_opened(self, event):
if event.receiver == self.receiver:
self.receiver_link_opened = True
local_node = Node.connect(self.query_address_listening, timeout=TIMEOUT)
out = local_node.query(type='org.apache.qpid.dispatch.router.link')
link_dir_index = out.attribute_names.index("linkDir")
owning_addr_index = out.attribute_names.index("owningAddr")
# Make sure that the owningAddr M0pulp.task.terminusTestReceiver shows up on both in and out.
# The 'out' link is on address M0pulp.task.terminusTestReceiver outgoing from the router B to the receiver
# The 'in' link is on address M0pulp.task.terminusTestReceiver incoming from router C to router B
for result in out.results:
if result[link_dir_index] == 'in' and result[owning_addr_index] == 'M0pulp.task.terminusTestReceiver':
self.in_receiver_found = True
if result[link_dir_index] == 'out' and result[owning_addr_index] == 'M0pulp.task.terminusTestReceiver':
self.out_receiver_found = True
if event.sender == self.sender:
self.sender_link_opened = True
local_node = Node.connect(self.query_address_sending, timeout=TIMEOUT)
out = local_node.query(type='org.apache.qpid.dispatch.router.link')
link_dir_index = out.attribute_names.index("linkDir")
owning_addr_index = out.attribute_names.index("owningAddr")
# Make sure that the owningAddr M0pulp.task.terminusTestSender shows up on both in and out.
# The 'in' link is on address M0pulp.task.terminusTestSender incoming from sender to router
# The 'out' link is on address M0pulp.task.terminusTestSender outgoing from router C to router B
for result in out.results:
if result[link_dir_index] == 'in' and result[owning_addr_index] == 'M0pulp.task.terminusTestSender':
self.in_sender_found = True
if result[link_dir_index] == 'out' and result[owning_addr_index] == 'M0pulp.task.terminusTestSender':
self.out_sender_found = True
# Shutdown the connections only if the on_link_opened has been called for sender and receiver links.
if self.sender_link_opened and self.receiver_link_opened:
self.sender.close()
self.receiver.close()
self.sender_connection.close()
self.receiver_connection.close()
def run(self):
Container(self).run()
class MultiLinkSendReceive(MessagingHandler):
class SendState(object):
def __init__(self, link):
self.link = link
self.sent = False
self.accepted = False
self.done = False
self.closed = False
def send(self, subject, body):
if not self.sent:
self.link.send(Message(subject=subject,body=body,address=self.link.target.address))
self.sent = True
def on_accepted(self):
self.accepted = True
self.done = True
def close(self):
if not self.closed:
self.closed = True
self.link.close()
self.link.connection.close()
class RecvState(object):
def __init__(self, link):
self.link = link
self.received = False
self.done = False
self.closed = False
def on_message(self):
self.received = True
self.done = True
def close(self):
if not self.closed:
self.closed = True
self.link.close()
self.link.connection.close()
def __init__(self, send_urls, recv_urls, name, message=None):
super(MultiLinkSendReceive, self).__init__()
self.send_urls = send_urls
self.recv_urls = recv_urls
self.senders = {}
self.receivers = {}
self.message = message or "SendReceiveTest"
self.sent = False
self.error = None
self.name = name
def close(self):
for sender in self.senders.values():
sender.close()
for receiver in self.receivers.values():
receiver.close()
def all_done(self):
for sender in self.senders.values():
if not sender.done:
return False
for receiver in self.receivers.values():
if not receiver.done:
return False
return True
def timeout(self):
self.error = "Timeout Expired"
self.close()
def stop_if_all_done(self):
if self.all_done():
self.stop()
def stop(self):
self.close()
self.timer.cancel()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
event.container.container_id = None
for u in self.send_urls:
s = self.SendState(event.container.create_sender(u, name=self.name))
self.senders[s.link.connection.container] = s
for u in self.recv_urls:
r = self.RecvState(event.container.create_receiver(u, name=self.name))
self.receivers[r.link.connection.container] = r
def on_sendable(self, event):
self.senders[event.connection.container].send(self.name, self.message)
def on_message(self, event):
if self.message != event.message.body:
error = "Incorrect message. Got %s, expected %s" % (event.message.body, self.message.body)
self.receivers[event.connection.container].on_message()
self.stop_if_all_done()
def on_accepted(self, event):
self.senders[event.connection.container].on_accepted()
self.stop_if_all_done()
def run(self):
Container(self).run()
class LinkRouteProtocolTest(TestCase):
"""
Test link route implementation against "misbehaving" containers
Uses a custom fake broker (not a router) that can do weird things at the
protocol level.
+-------------+ +---------+ +-----------------+
| | <------ | | <----- | blocking_sender |
| fake broker | | QDR.A | +-----------------+
| | ------> | | ------> +-------------------+
+-------------+ +---------+ | blocking_receiver |
+-------------------+
"""
@classmethod
def setUpClass(cls):
"""Configure and start QDR.A"""
super(LinkRouteProtocolTest, cls).setUpClass()
config = [
('router', {'mode': 'standalone', 'id': 'QDR.A'}),
# for client connections:
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the fake broker
('connector', {'name': 'broker',
'role': 'route-container',
'host': '127.0.0.1',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# forward 'org.apache' messages to + from fake broker:
('linkRoute', {'prefix': 'org.apache', 'containerId': 'FakeBroker', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache', 'containerId': 'FakeBroker', 'direction': 'out'})
]
config = Qdrouterd.Config(config)
cls.router = cls.tester.qdrouterd('A', config, wait=False)
def _fake_broker(self, cls):
"""Spawn a fake broker listening on the broker's connector
"""
fake_broker = cls(self.router.connector_addresses[0])
# wait until the connection to the fake broker activates
self.router.wait_connectors()
return fake_broker
def test_DISPATCH_1092(self):
# This fake broker will force the session closed after the link
# detaches. Verify that the session comes back up correctly when the
# next client attaches
killer = self._fake_broker(SessionKiller)
for i in range(2):
bconn = BlockingConnection(self.router.addresses[0])
bsender = bconn.create_sender(address="org.apache",
options=AtLeastOnce())
msg = Message(body="Hey!")
bsender.send(msg)
bsender.close()
bconn.close()
killer.join()
class SessionKiller(FakeBroker):
"""DISPATCH-1092: force a session close when the link closes. This should
cause the router to re-create the session when the next client attaches.
"""
def __init__(self, url):
super(SessionKiller, self).__init__(url)
def on_link_closing(self, event):
event.link.close()
event.session.close()
class FakeBrokerDrain(FakeBroker):
"""
DISPATCH-1496 - Make sure that the router does not grant additional credit
when drain is issued by a receiver connected to the router on a
link routed address
"""
def __init__(self, url):
super(FakeBrokerDrain, self).__init__(url)
self.first_flow_received = False
self.first_drain_mode = False
self.second_drain_mode = False
self.error = None
self.num_flows = 0
self.success = False
def on_link_flow(self, event):
if event.link.is_sender:
if event.sender.drain_mode:
if not self.first_drain_mode:
self.first_drain_mode = True
event.sender.drained()
elif not self.second_drain_mode:
self.second_drain_mode = True
if event.link.credit == 1000:
# Without the patch for DISPATCH-1496,
# the event.link.credit value would be 2000
self.success = True
else:
self.success = False
event.sender.drained()
else:
if not self.first_flow_received:
self.first_flow_received = True
msg = Message(body="First Drain Transfer")
event.link.send(msg)
class DrainReceiver(MessagingHandler):
def __init__(self, url, fake_broker):
super(DrainReceiver, self).__init__(prefetch=0, auto_accept=False)
self.url = url
self.received = 0
self.receiver = None
self.first_drain_sent = False
self.second_drain_sent = False
self.first_flow_sent = False
self.receiver_conn = None
self.error = None
self.num_flows = 0
self.fake_broker = fake_broker
def on_start(self, event):
self.receiver_conn = event.container.connect(self.url)
self.receiver = event.container.create_receiver(self.receiver_conn, "org.apache")
# Step 1: Send a flow of 1000 to the router. The router will forward this
# flow to the FakeBroker
self.receiver.flow(1000)
self.first_flow_sent = True
def on_link_flow(self, event):
if event.receiver == self.receiver:
self.num_flows += 1
if self.num_flows == 1:
# Step 4: The response drain received from the FakeBroker
# Step 5: Send second flow of 1000 credits. This is forwarded to the FakeBroker
self.receiver.flow(1000)
self.timer = event.reactor.schedule(3, TestTimeout(self))
elif self.num_flows == 2:
if not self.fake_broker.success:
self.error = "The FakeBroker did not receive correct credit of 1000"
self.receiver_conn.close()
def timeout(self):
# Step 6: The second drain is sent to the router. The router was forwarding the wrong credit (2000) to the FakeBroker
# but with the fix for DISPATCH-1496, the correct credit is forwarded (1000)
self.receiver.drain(0)
self.second_drain_sent = True
def on_message(self, event):
if event.receiver == self.receiver:
self.received += 1
# Step 2: In response to Step 1, the broker has sent the only message in its queue
if self.received == 1:
self.first_drain_sent = True
#print ("First message received. Doing first drain")
# Step 3: The receiver drains after receiving the first message.
# This drain is forwarded to the FakeBroker
self.receiver.drain(0)
def run(self):
Container(self).run()
class LinkRouteDrainTest(TestCase):
"""
Test link route drain implementation.
DISPATCH-1496 alleges that the router is granting extra credit when
forwarding the drain.
Uses a router which connects to a FakeBroker (FB)
+-------------+ +---------+
| | <------ | |
| fake broker | | QDR.A |
| | ------> | | ------> +-------------------+
+-------------+ +---------+ | receiver |
+-------------------+
The router will grant extra credit when the following sequence is used
1. The receiver attaches to the router on a a link routed address called "org.apache"
2. Receiver issues a flow of 1000. The FakeBroker has only one message in its
"examples" queue and it sends it over to the router which forwards it to the receiver
3. After receiving the message the receiver issues a drain(0). This drain is
forwarded to the FakeBroker by the router and the FB responds. There
is not problem with this drain
4. The receiver again gives a flow of 1000 and it is forwarded to the FB. There
are no messages in the broker queue, so the FB sends no messages
5. The receiver again issues a drain(0). At this time, without the fix for
DISPATCH-1496, the router issues double the credit to the FB. Instead
of issuing a credit of 1000, it issues a credit of 2000.
"""
@classmethod
def setUpClass(cls):
"""Configure and start QDR.A"""
super(LinkRouteDrainTest, cls).setUpClass()
config = [
('router', {'mode': 'standalone', 'id': 'QDR.A'}),
# for client connections:
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the fake broker
('connector', {'name': 'broker',
'role': 'route-container',
'host': '127.0.0.1',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# forward 'org.apache' messages to + from fake broker:
('linkRoute', {'prefix': 'org.apache', 'containerId': 'FakeBroker', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache', 'containerId': 'FakeBroker', 'direction': 'out'})
]
config = Qdrouterd.Config(config)
cls.router = cls.tester.qdrouterd('A', config, wait=False)
def _fake_broker(self, cls):
"""Spawn a fake broker listening on the broker's connector
"""
fake_broker = cls(self.router.connector_addresses[0])
# wait until the connection to the fake broker activates
self.router.wait_connectors()
return fake_broker
def test_DISPATCH_1496(self):
fake_broker = self._fake_broker(FakeBrokerDrain)
drain_receiver = DrainReceiver(self.router.addresses[0], fake_broker)
drain_receiver.run()
self.assertEquals(drain_receiver.error, None)
class ConnectionLinkRouteTest(TestCase):
"""
Test connection scoped link route implementation
Base configuration:
+-----------------+
+---------+ +---------+<--| blocking_sender |
+-----------------+ | | | | +-----------------+
| Fake LR Service |<==>| QDR.A |<==>| QDR.B |
+-----------------+ | | | | +-------------------+
+---------+ +---------+-->| blocking_receiver |
+-------------------+
The Fake Link Route Service will create connection-scoped link routes to
QDR.A, while blocking sender/receivers on QDR.B will send/receive messages
via the link route.
"""
_AS_TYPE = "org.apache.qpid.dispatch.router.connection.linkRoute"
@classmethod
def setUpClass(cls):
super(ConnectionLinkRouteTest, cls).setUpClass()
b_port = cls.tester.get_port()
configs = [
# QDR.A:
[('router', {'mode': 'interior', 'id': 'QDR.A'}),
# for fake connection-scoped LRs:
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# for fake route-container LR connections:
('listener', {'role': 'route-container',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the QDR.B
('connector', {'role': 'inter-router',
'host': '127.0.0.1',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'})],
# QDR.B:
[('router', {'mode': 'interior', 'id': 'QDR.B'}),
# for client connections
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# for connection to QDR.A
('listener', {'role': 'inter-router',
'host': '0.0.0.0',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'})]
]
cls.routers=[]
for c in configs:
config = Qdrouterd.Config(c)
cls.routers.append(cls.tester.qdrouterd(config=config, wait=False))
cls.QDR_A = cls.routers[0]
cls.QDR_B = cls.routers[1]
cls.QDR_A.wait_router_connected('QDR.B')
cls.QDR_B.wait_router_connected('QDR.A')
def _get_address(self, mgmt, addr):
a_type = 'org.apache.qpid.dispatch.router.address'
return list(filter(lambda a: a['name'].endswith(addr),
mgmt.query(a_type)))
def test_config_file_bad(self):
# verify that specifying a connection link route in the configuration
# file fails
config = [('router', {'mode': 'interior', 'id': 'QDR.X'}),
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': self.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
('connection.linkRoute',
{'pattern': "i/am/bad",
'direction': "out"})
]
cfg = Qdrouterd.Config(config)
# we expect the router to fail
router = self.tester.qdrouterd("X", cfg, wait=False, expect=Process.EXIT_FAIL)
def test_mgmt(self):
# test create, delete, and query
mgmt_conn = BlockingConnection(self.QDR_A.addresses[0])
mgmt_proxy = ConnLinkRouteMgmtProxy(mgmt_conn)
for i in range(10):
rsp = mgmt_proxy.create_conn_link_route("lr1-%d" % i,
{'pattern': "*/hi/there/%d" % i,
'direction':
'out' if i % 2 else 'in'})
self.assertEqual(201, rsp.status_code)
# test query
rsp = mgmt_proxy.query_conn_link_routes()
self.assertEqual(200, rsp.status_code)
self.assertEqual(10, len(rsp.results))
entities = rsp.results
# test read
rsp = mgmt_proxy.read_conn_link_route('lr1-5')
self.assertEqual(200, rsp.status_code)
self.assertEqual("lr1-5", rsp.attrs['name'])
self.assertEqual("*/hi/there/5", rsp.attrs['pattern'])
self.assertEqual(mgmt_conn.container.container_id,
rsp.attrs['containerId'])
# bad creates
attrs = [{'pattern': "bad", 'direction': "bad"},
{'direction': 'in'},
{},
{'pattern': ''},
{'pattern': 7}]
for a in attrs:
rsp = mgmt_proxy.create_conn_link_route("iamnoone", a)
self.assertEqual(400, rsp.status_code)
# bad read
rsp = mgmt_proxy.read_conn_link_route('iamnoone')
self.assertEqual(404, rsp.status_code)
# bad delete
rsp = mgmt_proxy.delete_conn_link_route('iamnoone')
self.assertEqual(404, rsp.status_code)
# delete all
for r in entities:
self.assertEqual(200, r.status_code)
rsp = mgmt_proxy.delete_conn_link_route(r.attrs['name'])
self.assertEqual(204, rsp.status_code)
# query - should be none left
rsp = mgmt_proxy.query_conn_link_routes()
self.assertEqual(200, rsp.status_code)
self.assertEqual(0, len(rsp.results))
def test_address_propagation(self):
# test service that creates and deletes connection link routes
fs = ConnLinkRouteService(self.QDR_A.addresses[1], container_id="FakeService",
config = [("clr1",
{"pattern": "flea.*",
"direction": "out"}),
("clr2",
{"pattern": "flea.*",
"direction": "in"})])
self.assertEqual(2, len(fs.values))
# the address should propagate to A and B
self.QDR_A.wait_address(address="flea.*", count=2)
self.QDR_B.wait_address(address="flea.*", count=2)
# now have the service delete the config
fs.delete_config()
# eventually the addresses will be un-published
mgmt_A = QdManager(self, address=self.QDR_A.addresses[0])
mgmt_B = QdManager(self, address=self.QDR_B.addresses[0])
deadline = time() + TIMEOUT
while (self._get_address(mgmt_A, "flea.*")
or self._get_address(mgmt_B, "flea.*")):
self.assertTrue(time() < deadline)
sleep(0.1)
fs.join();
# simple forwarding tests with auto delete
def test_send_receive(self):
COUNT = 5
mgmt_A = QdManager(self, address=self.QDR_A.addresses[0])
mgmt_B = QdManager(self, address=self.QDR_B.addresses[0])
# connect broker to A route-container
fs = ConnLinkRouteService(self.QDR_A.addresses[1], container_id="FakeService",
config = [("clr1",
{"pattern": "flea.*",
"direction": "out"}),
("clr2",
{"pattern": "flea.*",
"direction": "in"})])
self.assertEqual(2, len(fs.values))
# wait for the address to propagate to B
self.QDR_B.wait_address(address="flea.*", count=2)
# ensure the link routes are not visible via other connections
clrs = mgmt_A.query(self._AS_TYPE)
self.assertEqual(0, len(clrs))
# send from A to B
r = AsyncTestReceiver(self.QDR_B.addresses[0],
"flea.B",
container_id="flea.BReceiver")
s = AsyncTestSender(self.QDR_A.addresses[0],
"flea.B",
container_id="flea.BSender",
message=Message(body="SENDING TO flea.B"),
count=COUNT)
s.wait() # for sender to complete
for i in range(COUNT):
self.assertEqual("SENDING TO flea.B",
r.queue.get(timeout=TIMEOUT).body)
r.stop()
self.assertEqual(COUNT, fs.in_count)
# send from B to A
r = AsyncTestReceiver(self.QDR_A.addresses[0],
"flea.A",
container_id="flea.AReceiver")
s = AsyncTestSender(self.QDR_B.addresses[0],
"flea.A",
container_id="flea.ASender",
message=Message(body="SENDING TO flea.A"),
count=COUNT)
s.wait()
for i in range(COUNT):
self.assertEqual("SENDING TO flea.A",
r.queue.get(timeout=TIMEOUT).body)
r.stop()
self.assertEqual(2 * COUNT, fs.in_count)
# once the fake service closes its conn the link routes
# are removed so the link route addresses must be gone
fs.join()
mgmt_A = QdManager(self, address=self.QDR_A.addresses[0])
mgmt_B = QdManager(self, address=self.QDR_B.addresses[0])
deadline = time() + TIMEOUT
while (self._get_address(mgmt_A, "flea.*")
or self._get_address(mgmt_B, "flea.*")):
self.assertTrue(time() < deadline)
sleep(0.1)
class ConnLinkRouteService(FakeBroker):
def __init__(self, url, container_id, config, timeout=TIMEOUT):
self.conn = None
self.mgmt_proxy = None
self.mgmt_sender = None
self.mgmt_receiver = None
self._config = config
self._config_index = 0
self._config_done = Event()
self._config_error = None
self._config_values = []
self._cleaning_up = False
self._delete_done = Event()
self._delete_count = 0
self._event_injector = EventInjector()
self._delete_event = ApplicationEvent("delete_config")
super(ConnLinkRouteService, self).__init__(url, container_id)
if self._config_done.wait(timeout) is False:
raise Exception("Timed out waiting for configuration setup")
if self._config_error is not None:
raise Exception("Error: %s" % self._config_error)
@property
def values(self):
return self._config_values
def delete_config(self):
self._event_injector.trigger(self._delete_event)
if self._delete_done.wait(TIMEOUT) is False:
raise Exception("Timed out waiting for configuration delete")
def on_start(self, event):
"""
Do not create an acceptor, actively connect instead
"""
event.container.selectable(self._event_injector)
self.conn = event.container.connect(self.url)
def on_connection_opened(self, event):
if event.connection == self.conn:
if self.mgmt_receiver is None:
self.mgmt_receiver = event.container.create_receiver(self.conn,
dynamic=True)
super(ConnLinkRouteService, self).on_connection_opened(event)
def on_connection_closed(self, event):
if self._event_injector:
self._event_injector.close()
self._event_injector = None
super(ConnLinkRouteService, self).on_connection_closed(event)
def on_link_opened(self, event):
if event.link == self.mgmt_receiver:
self.mgmt_proxy = MgmtMsgProxy(self.mgmt_receiver.remote_source.address)
self.mgmt_sender = event.container.create_sender(self.conn,
target="$management")
def on_link_error(self, event):
# when a remote client disconnects the service will get a link error
# that is expected - simply clean up the link
self.on_link_closing(event)
def on_sendable(self, event):
if event.sender == self.mgmt_sender:
if not self._cleaning_up:
if self._config_index < len(self._config):
cfg = self._config[self._config_index]
msg = self.mgmt_proxy.create_conn_link_route(cfg[0], cfg[1])
self.mgmt_sender.send(msg)
self._config_index += 1
elif self._config_values:
cv = self._config_values.pop()
msg = self.mgmt_proxy.delete_conn_link_route(cv['name'])
self._delete_count += 1
else:
super(ConnLinkRouteService, self).on_sendable(event)
def on_message(self, event):
if event.receiver == self.mgmt_receiver:
response = self.mgmt_proxy.response(event.message)
if response.status_code == 201:
# created:
self._config_values.append(response.attrs)
if len(self._config_values) == len(self._config):
self._config_done.set()
elif response.status_code == 204:
# deleted
self._delete_count -= 1
if (not self._config_values) and self._delete_count == 0:
self._delete_done.set()
else:
# error
self._config_error = ("mgmt failed: %s" %
response.status_description)
self._config_done.set()
self._delete_done.set()
else:
super(ConnLinkRouteService, self).on_message(event)
def on_delete_config(self, event):
if not self._cleaning_up:
self._cleaning_up = True
if not self._config_values:
self._delete_done.set()
else:
try:
while self.mgmt_sender.credit > 0:
cv = self._config_values.pop()
msg = self.mgmt_proxy.delete_conn_link_route(cv["name"])
self.mgmt_sender.send(msg)
self._delete_count += 1
except IndexError:
pass
class ConnLinkRouteMgmtProxy(object):
"""
Manage connection scoped link routes over a given connection.
While the connection remains open the connection scoped links will remain
configured and active
"""
def __init__(self, bconn, credit=250):
self._receiver = bconn.create_receiver(address=None, dynamic=True, credit=credit)
self._sender = bconn.create_sender(address="$management")
self._proxy = MgmtMsgProxy(self._receiver.link.remote_source.address)
def __getattr__(self, key):
# wrap accesses to the management message functions so we can send and
# receive the messages using the blocking links
f = getattr(self._proxy, key)
if not callable(f):
return f
def _func(*args, **kwargs):
self._sender.send(f(*args, **kwargs))
return self._proxy.response(self._receiver.receive())
return _func
class InvalidTagTest(MessagingHandler):
"""Verify that a message with an invalid tag length is rejected
"""
def __init__(self, router_addr):
super(InvalidTagTest, self).__init__(auto_accept=False, auto_settle=False)
self.test_conn = None
self.test_address = router_addr
self.tx_ct = 0;
self.accept_ct = 0;
self.reject_ct = 0;
self.error = None
def timeout(self):
self.error = "Timeout expired: sent=%d rcvd=%d" % (self.tx_ct,
self.accept_ct
+ self.reject_ct)
if self.test_conn:
self.test_conn.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.test_conn = event.container.connect(self.test_address)
rx = event.container.create_receiver(self.test_conn, "org.apache.foo")
def on_link_opened(self, event):
if event.receiver:
event.receiver.flow(100)
event.container.create_sender(event.connection, "org.apache.foo")
def on_sendable(self, event):
if self.tx_ct < 10:
self.tx_ct += 1
if self.tx_ct == 5:
event.sender.send(Message(body="YO"), tag=str("X" * 64))
else:
event.sender.send(Message(body="YO"), tag=str("BLAH%d" %
self.tx_ct))
def on_accepted(self, event):
self.accept_ct += 1
event.delivery.settle()
if self.accept_ct == 9 and self.reject_ct == 1:
event.connection.close()
self.timer.cancel()
def on_rejected(self, event):
self.reject_ct += 1
event.delivery.settle()
def on_message(self, event):
event.delivery.update(Delivery.ACCEPTED)
event.delivery.settle()
def run(self):
Container(self).run()
class Dispatch1428(TestCase):
"""
Sets up 2 routers (one of which are acting as brokers (QDR.A)).
QDR.A acting broker #1
+---------+ +---------+
| | <------ | |
| QDR.A | | QDR.B |
| | ------> | |
+---------+ +---------+
"""
@classmethod
def get_router(cls, index):
return cls.routers[index]
@classmethod
def setUpClass(cls):
"""Start two routers"""
super(Dispatch1428, cls).setUpClass()
def router(name, connection):
config = [
('router', {'mode': 'interior', 'id': 'QDR.%s'%name}),
] + connection
config = Qdrouterd.Config(config)
cls.routers.append(cls.tester.qdrouterd(name, config, wait=False))
cls.routers = []
a_listener_port = cls.tester.get_port()
b_listener_port = cls.tester.get_port()
router('A',
[
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
])
router('B',
[
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': b_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
('connector', {'name': 'one', 'role': 'route-container', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
('connector', {'name': 'two', 'role': 'route-container', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'})
]
)
sleep(2)
def run_qdmanage(self, cmd, input=None, expect=Process.EXIT_OK, address=None):
p = self.popen(
['qdmanage'] + cmd.split(' ') + ['--bus', address or self.address(), '--indent=-1', '--timeout', str(TIMEOUT)],
stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
universal_newlines=True)
out = p.communicate(input)[0]
try:
p.teardown()
except Exception as e:
raise Exception("%s\n%s" % (e, out))
return out
def test_both_link_routes_active(self):
cmds = [
'CREATE --type=linkRoute name=foo prefix=foo direction=in connection=one',
'CREATE --type=linkRoute name=bar prefix=bar direction=in connection=two',
'CREATE --type=linkRoute name=baz prefix=baz direction=in containerId=QDR.A'
]
for c in cmds:
self.run_qdmanage(cmd=c, address=self.routers[1].addresses[0])
# Now that the qdmanage has run, query the link routes and make sure that their "operStatus" is "active" before
# running any of the tests.
long_type = 'org.apache.qpid.dispatch.router.config.linkRoute'
qd_manager = QdManager(self, address=self.routers[1].addresses[0])
for i in range(5):
all_link_routes_activated = True
link_routes = qd_manager.query(long_type)
for link_route in link_routes:
oper_status = link_route['operStatus']
if oper_status != "active":
all_link_routes_activated = False
break
if not all_link_routes_activated:
# One or more of the link routes have not been activated.
# Check after one second.
sleep(1)
else:
break
# All link routes created in this test MUST be activated before
# we can continue further testing.
self.assertTrue(all_link_routes_activated)
first = SendReceive("%s/foo" % self.routers[1].addresses[0], "%s/foo" % self.routers[0].addresses[0])
first.run()
self.assertEqual(None, first.error)
second = SendReceive("%s/bar" % self.routers[1].addresses[0], "%s/bar" % self.routers[0].addresses[0])
second.run()
self.assertEqual(None, second.error)
third = SendReceive("%s/baz" % self.routers[1].addresses[0], "%s/baz" % self.routers[0].addresses[0])
third.run()
self.assertEqual(None, third.error)
class SendReceive(MessagingHandler):
def __init__(self, send_url, recv_url, message=None):
super(SendReceive, self).__init__()
self.send_url = send_url
self.recv_url = recv_url
self.message = message or Message(body="SendReceiveTest")
self.sent = False
self.error = None
def close(self):
self.sender.close()
self.receiver.close()
self.sender.connection.close()
self.receiver.connection.close()
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.close()
def stop(self):
self.close()
self.timer.cancel()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
event.container.container_id = "SendReceiveTestClient"
self.sender = event.container.create_sender(self.send_url)
self.receiver = event.container.create_receiver(self.recv_url)
def on_sendable(self, event):
if not self.sent:
event.sender.send(self.message)
self.sent = True
def on_message(self, event):
if self.message.body != event.message.body:
self.error = "Incorrect message. Got %s, expected %s" % (event.message.body, self.message.body)
def on_accepted(self, event):
self.stop()
def run(self):
Container(self).run()
class LinkRoute3Hop(TestCase):
"""
Sets up a linear 3 hop router network for testing multi-hop link routes.
+---------+ +---------+ +---------+ +------------------+
| | <------ | | <----- | |<----| blocking_senders |
| QDR.A | | QDR.B | | QDR.C | +------------------+
| | ------> | | ------> | | +--------------------+
+---------+ +---------+ +---------+---->| blocking_receivers |
^ +--------------------+
|
V
+-------------+
| FakeService |
+-------------+
"""
@classmethod
def setUpClass(cls):
super(LinkRoute3Hop, cls).setUpClass()
b_port = cls.tester.get_port()
configs = [
# QDR.A:
[('router', {'mode': 'interior', 'id': 'QDR.A'}),
# for client access
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# for fake service:
('listener', {'role': 'route-container',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the QDR.B
('connector', {'role': 'inter-router',
'host': '127.0.0.1',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'}),
# the routes
('linkRoute', {'prefix': 'closest/test-client', 'containerId': 'FakeService', 'direction': 'in'}),
('linkRoute', {'prefix': 'closest/test-client', 'containerId': 'FakeService', 'direction': 'out'})
],
# QDR.B:
[('router', {'mode': 'interior', 'id': 'QDR.B'}),
# for client connections
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# for inter-router connections from QDR.A and QDR.C
('listener', {'role': 'inter-router',
'host': '0.0.0.0',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'}),
('linkRoute', {'prefix': 'closest/test-client', 'direction': 'in'}),
('linkRoute', {'prefix': 'closest/test-client', 'direction': 'out'})
],
# QDR.C
[('router', {'mode': 'interior', 'id': 'QDR.C'}),
# for client connections
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the QDR.B
('connector', {'role': 'inter-router',
'host': '127.0.0.1',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'}),
('linkRoute', {'prefix': 'closest/test-client', 'direction': 'in'}),
('linkRoute', {'prefix': 'closest/test-client', 'direction': 'out'})
]
]
cls.routers=[]
for c in configs:
config = Qdrouterd.Config(c)
cls.routers.append(cls.tester.qdrouterd(config=config, wait=False))
cls.QDR_A = cls.routers[0]
cls.QDR_B = cls.routers[1]
cls.QDR_C = cls.routers[2]
cls.QDR_A.wait_router_connected('QDR.B')
cls.QDR_B.wait_router_connected('QDR.A')
cls.QDR_B.wait_router_connected('QDR.C')
cls.QDR_C.wait_router_connected('QDR.B')
cls.QDR_C.wait_router_connected('QDR.A')
cls.QDR_A.wait_router_connected('QDR.C')
cls.fake_service = FakeService(cls.QDR_A.addresses[1],
container_id="FakeService")
cls.QDR_C.wait_address("closest/test-client",
remotes=1, count=2)
def test_01_parallel_link_routes(self):
"""
Verify Q2/Q3 recovery in the case of multiple link-routes sharing the
same session.
"""
send_clients = 10
send_batch = 10
total = send_clients * send_batch
start_in = self.fake_service.in_count
start_out = self.fake_service.out_count
env = dict(os.environ, PN_TRACE_FRM="1")
rx = self.popen(["test-receiver",
"-a", self.QDR_C.addresses[0],
"-c", str(total),
"-s", "closest/test-client"],
env=env,
expect=Process.EXIT_OK)
def _spawn_sender(x):
return self.popen(["test-sender",
"-a", self.QDR_C.addresses[0],
"-c", str(send_batch),
"-i", "TestSender-%s" % x,
"-sx", # huge message size to trigger Q2/Q3
"-t", "closest/test-client"],
env=env,
expect=Process.EXIT_OK)
senders = [_spawn_sender(s) for s in range(send_clients)]
for tx in senders:
out_text, out_err = tx.communicate(timeout=TIMEOUT)
if tx.returncode:
raise Exception("Sender failed: %s %s" % (out_text, out_err))
if rx.wait(timeout=TIMEOUT):
raise Exception("Receiver failed to consume all messages in=%s out=%s",
self.fake_service.in_count,
self.fake_service.out_count)
self.assertEqual(start_in + total, self.fake_service.in_count)
self.assertEqual(start_out + total, self.fake_service.out_count)
if __name__ == '__main__':
unittest.main(main_module())
| 42.437725 | 166 | 0.577038 |
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import os
from time import sleep, time
from threading import Event
from subprocess import PIPE, STDOUT
from system_test import TestCase, Qdrouterd, main_module, TIMEOUT, Process, TestTimeout, \
AsyncTestSender, AsyncTestReceiver, MgmtMsgProxy, unittest, QdManager
from test_broker import FakeBroker
from test_broker import FakeService
from proton import Delivery
from proton import Message
from proton.handlers import MessagingHandler
from proton.reactor import AtMostOnce, Container, DynamicNodeProperties, LinkOption, AtLeastOnce
from proton.reactor import ApplicationEvent
from proton.reactor import EventInjector
from proton.utils import BlockingConnection
from system_tests_drain_support import DrainMessagesHandler, DrainOneMessageHandler, DrainNoMessagesHandler, DrainNoMoreMessagesHandler
from qpid_dispatch.management.client import Node
from qpid_dispatch.management.error import NotFoundStatus, BadRequestStatus
class LinkRouteTest(TestCase):
@classmethod
def get_router(cls, index):
return cls.routers[index]
@classmethod
def setUpClass(cls):
super(LinkRouteTest, cls).setUpClass()
def router(name, connection):
config = [
('router', {'mode': 'interior', 'id': 'QDR.%s'%name}),
] + connection
config = Qdrouterd.Config(config)
cls.routers.append(cls.tester.qdrouterd(name, config, wait=False))
cls.routers = []
a_listener_port = cls.tester.get_port()
b_listener_port = cls.tester.get_port()
c_listener_port = cls.tester.get_port()
d_listener_port = cls.tester.get_port()
test_tag_listener_port = cls.tester.get_port()
router('A',
[
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
])
router('B',
[
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': b_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
('listener', {'name': 'test-tag', 'role': 'route-container', 'host': '0.0.0.0', 'port': test_tag_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
('connector', {'name': 'broker', 'role': 'route-container', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
# Only inter router communication must happen on 'inter-router' connectors. This connector makes
# a connection from the router B's ephemeral port to c_listener_port
('connector', {'name': 'routerC', 'role': 'inter-router', 'host': '0.0.0.0', 'port': c_listener_port}),
('connector', {'name': 'routerD', 'role': 'route-container', 'host': '0.0.0.0', 'port': d_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
#('linkRoute', {'prefix': 'org.apache', 'connection': 'broker', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache', 'containerId': 'QDR.A', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache', 'containerId': 'QDR.A', 'direction': 'out'}),
('linkRoute', {'prefix': 'pulp.task', 'connection': 'test-tag', 'direction': 'in'}),
('linkRoute', {'prefix': 'pulp.task', 'connection': 'test-tag', 'direction': 'out'}),
# addresses matching pattern 'a.*.toA.
('linkRoute', {'pattern': 'a.*.toA.
('linkRoute', {'pattern': 'a.*.toA.
# addresses matching pattern 'a.*.toD.
# Dont change dir to direction here so we can make sure that the dir attribute is still working.
('linkRoute', {'pattern': 'a.*.toD.
('linkRoute', {'pattern': 'a.*.toD.
]
)
router('C',
[
# The client will exclusively use the following listener to
# connect to QDR.C, the tests assume this is the first entry
# in the list
('listener', {'host': '0.0.0.0', 'role': 'normal', 'port': cls.tester.get_port(), 'saslMechanisms': 'ANONYMOUS'}),
('listener', {'host': '0.0.0.0', 'role': 'inter-router', 'port': c_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
# The dot(.) at the end is ignored by the address hashing scheme.
('linkRoute', {'prefix': 'org.apache.', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache.', 'direction': 'out'}),
('linkRoute', {'prefix': 'pulp.task', 'direction': 'in'}),
('linkRoute', {'prefix': 'pulp.task', 'direction': 'out'}),
('linkRoute', {'pattern': 'a.*.toA.
('linkRoute', {'pattern': 'a.*.toA.
('linkRoute', {'pattern': 'a.*.toD.
('linkRoute', {'pattern': 'a.*.toD.
]
)
router('D', # sink for QDR.D routes
[
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': d_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
])
# Wait for the routers to locate each other, and for route propagation
# to settle
cls.routers[1].wait_router_connected('QDR.C')
cls.routers[2].wait_router_connected('QDR.B')
cls.routers[2].wait_address("org.apache", remotes=1, delay=0.5, count=2)
# This is not a classic router network in the sense that QDR.A and D are acting as brokers. We allow a little
# bit more time for the routers to stabilize.
sleep(2)
def run_qdstat_linkRoute(self, address, args=None):
cmd = ['qdstat', '--bus', str(address), '--timeout', str(TIMEOUT) ] + ['--linkroute']
if args:
cmd = cmd + args
p = self.popen(
cmd,
name='qdstat-'+self.id(), stdout=PIPE, expect=None,
universal_newlines=True)
out = p.communicate()[0]
assert p.returncode == 0, "qdstat exit status %s, output:\n%s" % (p.returncode, out)
return out
def run_qdmanage(self, cmd, input=None, expect=Process.EXIT_OK, address=None):
p = self.popen(
['qdmanage'] + cmd.split(' ') + ['--bus', address or self.address(), '--indent=-1', '--timeout', str(TIMEOUT)],
stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
universal_newlines=True)
out = p.communicate(input)[0]
try:
p.teardown()
except Exception as e:
raise Exception("%s\n%s" % (e, out))
return out
def test_aaa_qdmanage_query_link_route(self):
cmd = 'QUERY --type=linkRoute'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
# Make sure there is a dir of in and out.
self.assertIn('"direction": "in"', out)
self.assertIn('"direction": "out"', out)
self.assertIn('"containerId": "QDR.A"', out)
# Use the long type and make sure that qdmanage does not mess up the long type
cmd = 'QUERY --type=org.apache.qpid.dispatch.router.config.linkRoute'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
# Make sure there is a dir of in and out.
self.assertIn('"direction": "in"', out)
self.assertIn('"direction": "out"', out)
self.assertIn('"containerId": "QDR.A"', out)
identity = out[out.find("identity") + 12: out.find("identity") + 13]
cmd = 'READ --type=linkRoute --identity=' + identity
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
self.assertIn(identity, out)
exception_occurred = False
try:
# This identity should not be found
cmd = 'READ --type=linkRoute --identity=9999'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
except Exception as e:
exception_occurred = True
self.assertIn("NotFoundStatus: Not Found", str(e))
self.assertTrue(exception_occurred)
exception_occurred = False
try:
# There is no identity specified, this is a bad request
cmd = 'READ --type=linkRoute'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
except Exception as e:
exception_occurred = True
self.assertIn("BadRequestStatus: No name or identity provided", str(e))
self.assertTrue(exception_occurred)
cmd = 'CREATE --type=autoLink address=127.0.0.1 direction=in connection=routerC'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
identity = out[out.find("identity") + 12: out.find("identity") + 14]
cmd = 'READ --type=autoLink --identity=' + identity
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
self.assertIn(identity, out)
def test_bbb_qdstat_link_routes_routerB(self):
out = self.run_qdstat_linkRoute(self.routers[1].addresses[0])
for route in ['a.*.toA., out)
out_list = out.split()
self.assertEqual(out_list.count('in'), 4)
self.assertEqual(out_list.count('out'), 4)
parts = out.split("\n")
self.assertEqual(len(parts), 15)
out = self.run_qdstat_linkRoute(self.routers[1].addresses[0], args=['--limit=1'])
parts = out.split("\n")
self.assertEqual(len(parts), 8)
def test_ccc_qdstat_link_routes_routerC(self):
out = self.run_qdstat_linkRoute(self.routers[2].addresses[0])
out_list = out.split()
self.assertEqual(out_list.count('in'), 4)
self.assertEqual(out_list.count('out'), 4)
def test_ddd_partial_link_route_match(self):
hello_world_1 = "Hello World_1!"
# Connects to listener #2 on QDR.C
addr = self.routers[2].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache.dev
blocking_receiver = blocking_connection.create_receiver(address="org.apache.dev")
apply_options = AtMostOnce()
# Sender to org.apache.dev
blocking_sender = blocking_connection.create_sender(address="org.apache.dev", options=apply_options)
msg = Message(body=hello_world_1)
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_1, received_message.body)
# Connect to the router acting like the broker (QDR.A) and check the deliveriesIngress and deliveriesEgress
local_node = Node.connect(self.routers[0].addresses[0], timeout=TIMEOUT)
self.assertEqual(u'QDR.A', local_node.query(type='org.apache.qpid.dispatch.router',
attribute_names=[u'id']).results[0][0])
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.dev').deliveriesEgress)
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.dev').deliveriesIngress)
# There should be 4 links -
# 1. outbound receiver link on org.apache.dev
# 2. inbound sender link on blocking_sender
# 3. inbound link to the $management
# 4. outbound link to $management
# self.assertEqual(4, len()
self.assertEqual(4, len(local_node.query(type='org.apache.qpid.dispatch.router.link').results))
blocking_connection.close()
def test_partial_link_route_match_1(self):
hello_world_2 = "Hello World_2!"
addr = self.routers[1].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache.dev
blocking_receiver = blocking_connection.create_receiver(address="org.apache.dev.1")
apply_options = AtMostOnce()
# Sender to to org.apache.dev
blocking_sender = blocking_connection.create_sender(address="org.apache.dev.1", options=apply_options)
msg = Message(body=hello_world_2)
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_2, received_message.body)
local_node = Node.connect(self.routers[0].addresses[0], timeout=TIMEOUT)
# Make sure that the router node acting as the broker (QDR.A) had one message routed through it. This confirms
# that the message was link routed
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.dev.1').deliveriesEgress)
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.dev.1').deliveriesIngress)
blocking_connection.close()
def test_full_link_route_match(self):
hello_world_3 = "Hello World_3!"
# Connects to listener #2 on QDR.C
addr = self.routers[2].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache
blocking_receiver = blocking_connection.create_receiver(address="org.apache")
apply_options = AtMostOnce()
# Sender to to org.apache
blocking_sender = blocking_connection.create_sender(address="org.apache", options=apply_options)
msg = Message(body=hello_world_3)
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_3, received_message.body)
local_node = Node.connect(self.routers[0].addresses[0], timeout=TIMEOUT)
# Make sure that the router node acting as the broker (QDR.A) had one message routed through it. This confirms
# that the message was link routed
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache').deliveriesEgress)
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache').deliveriesIngress)
blocking_connection.close()
def _link_route_pattern_match(self, connect_node, include_host,
exclude_host, test_address,
expected_pattern):
hello_pattern = "Hello Pattern!"
route = 'M0' + test_address
# Connect to the two 'waypoints', ensure the route is not present on
# either
node_A = Node.connect(include_host, timeout=TIMEOUT)
node_B = Node.connect(exclude_host, timeout=TIMEOUT)
for node in [node_A, node_B]:
self.assertRaises(NotFoundStatus,
node.read,
type='org.apache.qpid.dispatch.router.address',
name=route)
# wait until the host we're connecting to gets its next hop for the
connect_node.wait_address(expected_pattern, remotes=1, delay=0.1, count=2)
# Connect to 'connect_node' and send message to 'address'
blocking_connection = BlockingConnection(connect_node.addresses[0])
blocking_receiver = blocking_connection.create_receiver(address=test_address)
blocking_sender = blocking_connection.create_sender(address=test_address,
options=AtMostOnce())
msg = Message(body=hello_pattern)
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_pattern, received_message.body)
# verify test_address is only present on include_host and not on exclude_host
self.assertRaises(NotFoundStatus,
node_B.read,
type='org.apache.qpid.dispatch.router.address',
name=route)
self.assertEqual(1, node_A.read(type='org.apache.qpid.dispatch.router.address',
name=route).deliveriesIngress)
self.assertEqual(1, node_A.read(type='org.apache.qpid.dispatch.router.address',
name=route).deliveriesIngress)
# drop the connection and verify that test_address is no longer on include_host
blocking_connection.close()
timeout = time() + TIMEOUT
while True:
try:
node_A.read(type='org.apache.qpid.dispatch.router.address',
name=route)
if time() > timeout:
raise Exception("Expected route '%s' to expire!" % route)
sleep(0.1)
except NotFoundStatus:
break;
node_A.close()
node_B.close()
def test_link_route_pattern_match(self):
qdr_A = self.routers[0].addresses[0]
qdr_D = self.routers[3].addresses[0]
qdr_C = self.routers[2] # note: the node, not the address!
self._link_route_pattern_match(connect_node=qdr_C,
include_host=qdr_A,
exclude_host=qdr_D,
test_address='a.notD.toA',
expected_pattern='a.*.toA.
self._link_route_pattern_match(connect_node=qdr_C,
include_host=qdr_D,
exclude_host=qdr_A,
test_address='a.notA.toD',
expected_pattern='a.*.toD.
self._link_route_pattern_match(connect_node=qdr_C,
include_host=qdr_A,
exclude_host=qdr_D,
test_address='a.toD.toA.xyz',
expected_pattern='a.*.toA.
self._link_route_pattern_match(connect_node=qdr_C,
include_host=qdr_D,
exclude_host=qdr_A,
test_address='a.toA.toD.abc',
expected_pattern='a.*.toD.
def test_custom_annotations_match(self):
hello_world_3 = "Hello World_3!"
# Connects to listener #2 on QDR.C
addr = self.routers[2].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache
blocking_receiver = blocking_connection.create_receiver(address="org.apache.2")
apply_options = AtMostOnce()
# Sender to to org.apache
blocking_sender = blocking_connection.create_sender(address="org.apache.2", options=apply_options)
msg = Message(body=hello_world_3)
annotations = {'custom-annotation': '1/Custom_Annotation'}
msg.annotations = annotations
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_3, received_message.body)
self.assertEqual(received_message.annotations, annotations)
blocking_connection.close()
def test_full_link_route_match_1(self):
hello_world_4 = "Hello World_4!"
addr = self.routers[1].addresses[0]
blocking_connection = BlockingConnection(addr)
# Receive on org.apache
blocking_receiver = blocking_connection.create_receiver(address="org.apache.1")
apply_options = AtMostOnce()
# Sender to to org.apache
blocking_sender = blocking_connection.create_sender(address="org.apache.1", options=apply_options)
msg = Message(body=hello_world_4)
# Send a message
blocking_sender.send(msg)
received_message = blocking_receiver.receive()
self.assertEqual(hello_world_4, received_message.body)
local_node = Node.connect(self.routers[0].addresses[0], timeout=TIMEOUT)
# Make sure that the router node acting as the broker (QDR.A) had one message routed through it. This confirms
# that the message was link routed
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.1').deliveriesEgress)
self.assertEqual(1, local_node.read(type='org.apache.qpid.dispatch.router.address',
name='M0org.apache.1').deliveriesIngress)
blocking_connection.close()
def test_zzz_qdmanage_delete_link_route(self):
local_node = Node.connect(self.routers[1].addresses[0], timeout=TIMEOUT)
res = local_node.query(type='org.apache.qpid.dispatch.router')
results = res.results[0]
attribute_list = res.attribute_names
result_list = local_node.query(type='org.apache.qpid.dispatch.router.config.linkRoute').results
self.assertEqual(results[attribute_list.index('linkRouteCount')], len(result_list))
# First delete linkRoutes on QDR.B
for rid in range(8):
cmd = 'DELETE --type=linkRoute --identity=' + result_list[rid][1]
self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
cmd = 'QUERY --type=linkRoute'
out = self.run_qdmanage(cmd=cmd, address=self.routers[1].addresses[0])
self.assertEqual(out.rstrip(), '[]')
# linkRoutes now gone on QDR.B but remember that it still exist on QDR.C
# We will now try to create a receiver on address org.apache.dev on QDR.C.
# Since the linkRoute on QDR.B is gone, QDR.C
# will not allow a receiver to be created since there is no route to destination.
# Connects to listener #2 on QDR.C
addr = self.routers[2].addresses[0]
# Now delete linkRoutes on QDR.C to eradicate linkRoutes completely
local_node = Node.connect(addr, timeout=TIMEOUT)
result_list = local_node.query(type='org.apache.qpid.dispatch.router.config.linkRoute').results
# QDR.C has 8 link routes configured, nuke 'em:
self.assertEqual(8, len(result_list))
for rid in range(8):
cmd = 'DELETE --type=linkRoute --identity=' + result_list[rid][1]
self.run_qdmanage(cmd=cmd, address=addr)
cmd = 'QUERY --type=linkRoute'
out = self.run_qdmanage(cmd=cmd, address=addr)
self.assertEqual(out.rstrip(), '[]')
res = local_node.query(type='org.apache.qpid.dispatch.router')
results = res.results[0]
attribute_list = res.attribute_names
self.assertEqual(results[attribute_list.index('linkRouteCount')], 0)
blocking_connection = BlockingConnection(addr, timeout=3)
blocking_receiver = blocking_connection.create_receiver(address="org.apache.dev")
apply_options = AtMostOnce()
hello_world_1 = "Hello World_1!"
blocking_sender = blocking_connection.create_sender(address="org.apache.dev", options=apply_options)
msg = Message(body=hello_world_1)
blocking_sender.send(msg)
received_message = blocking_receiver.receive(timeout=5)
self.assertEqual(hello_world_1, received_message.body)
def test_yyy_delivery_tag(self):
listening_address = self.routers[1].addresses[1]
sender_address = self.routers[2].addresses[0]
qdstat_address = self.routers[2].addresses[0]
test = DeliveryTagsTest(sender_address, listening_address, qdstat_address)
test.run()
self.assertEqual(None, test.error)
def test_yyy_invalid_delivery_tag(self):
test = InvalidTagTest(self.routers[2].addresses[0])
test.run()
self.assertEqual(None, test.error)
def test_close_with_unsettled(self):
test = CloseWithUnsettledTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def test_www_drain_support_all_messages(self):
drain_support = DrainMessagesHandler(self.routers[2].addresses[0])
drain_support.run()
self.assertEqual(None, drain_support.error)
def test_www_drain_support_one_message(self):
drain_support = DrainOneMessageHandler(self.routers[2].addresses[0])
drain_support.run()
self.assertEqual(None, drain_support.error)
def test_www_drain_support_no_messages(self):
drain_support = DrainNoMessagesHandler(self.routers[2].addresses[0])
drain_support.run()
self.assertEqual(None, drain_support.error)
def test_www_drain_support_no_more_messages(self):
drain_support = DrainNoMoreMessagesHandler(self.routers[2].addresses[0])
drain_support.run()
self.assertEqual(None, drain_support.error)
def test_link_route_terminus_address(self):
listening_address = self.routers[1].addresses[1]
query_address_listening = self.routers[1].addresses[0]
sender_address = self.routers[2].addresses[0]
query_address_sending = self.routers[2].addresses[0]
test = TerminusAddrTest(sender_address, listening_address, query_address_sending, query_address_listening)
test.run()
self.assertTrue(test.in_receiver_found)
self.assertTrue(test.out_receiver_found)
self.assertTrue(test.in_sender_found)
self.assertTrue(test.out_sender_found)
def test_dynamic_source(self):
test = DynamicSourceTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def test_dynamic_target(self):
test = DynamicTargetTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def test_detach_without_close(self):
test = DetachNoCloseTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def test_detach_mixed_close(self):
test = DetachMixedCloseTest(self.routers[1].addresses[0], self.routers[1].addresses[1])
test.run()
self.assertEqual(None, test.error)
def _multi_link_send_receive(self, send_host, receive_host, name):
senders = ["%s/%s" % (send_host, address) for address in ["org.apache.foo", "org.apache.bar"]]
receivers = ["%s/%s" % (receive_host, address) for address in ["org.apache.foo", "org.apache.bar"]]
test = MultiLinkSendReceive(senders, receivers, name)
test.run()
self.assertEqual(None, test.error)
def test_same_name_route_receivers_through_B(self):
self._multi_link_send_receive(self.routers[0].addresses[0], self.routers[1].addresses[0], "recv_through_B")
def test_same_name_route_senders_through_B(self):
self._multi_link_send_receive(self.routers[1].addresses[0], self.routers[0].addresses[0], "send_through_B")
def test_same_name_route_receivers_through_C(self):
self._multi_link_send_receive(self.routers[0].addresses[0], self.routers[2].addresses[0], "recv_through_C")
def test_same_name_route_senders_through_C(self):
self._multi_link_send_receive(self.routers[2].addresses[0], self.routers[0].addresses[0], "send_through_C")
def test_echo_detach_received(self):
test = EchoDetachReceived(self.routers[2].addresses[0], self.routers[2].addresses[0])
test.run()
self.assertEqual(None, test.error)
def test_bad_link_route_config(self):
mgmt = self.routers[1].management
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-1",
attributes={'prefix': '',
'containerId': 'FakeBroker',
'direction': 'in'})
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-2",
attributes={'pattern': 666,
'containerId': 'FakeBroker',
'direction': 'in'})
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-3",
attributes={'pattern': '///',
'containerId': 'FakeBroker',
'direction': 'in'})
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-4",
attributes={})
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-5",
attributes={'prefix': 'a1',
'pattern': 'b2',
'containerId': 'FakeBroker',
'direction': 'in'})
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-6",
attributes={'pattern': 'b2',
'containerId': 'FakeBroker',
'direction': 'nowhere'})
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-7",
attributes={'pattern': 'b2',
'containerId': 'FakeBroker',
'direction': 'in',
"distribution": "dilly dilly"})
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-8",
attributes={'prefix': 'b2',
'containerId': 'FakeBroker'})
self.assertRaises(BadRequestStatus,
mgmt.create,
type="org.apache.qpid.dispatch.router.config.linkRoute",
name="bad-9",
attributes={'direction': 'out',
'containerId': 'FakeBroker'})
class DeliveryTagsTest(MessagingHandler):
def __init__(self, sender_address, listening_address, qdstat_address):
super(DeliveryTagsTest, self).__init__()
self.sender_address = sender_address
self.listening_address = listening_address
self.sender = None
self.receiver_connection = None
self.sender_connection = None
self.qdstat_address = qdstat_address
self.id = '1235'
self.times = 1
self.sent = 0
self.rcvd = 0
self.delivery_tag_verified = False
self.delivery_tag = str('92319')
self.error = None
def timeout(self):
self.error = "Timeout expired: sent=%d rcvd=%d" % (self.sent, self.rcvd)
if self.receiver_connection:
self.receiver_connection.close()
if self.sender_connection:
self.sender_connection.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.receiver_connection = event.container.connect(self.listening_address)
def on_connection_remote_open(self, event):
if event.connection == self.receiver_connection:
continue_loop = True
# accept the message.
# If there is no remote receiver, the router will throw a 'No route to destination' error when
# creating sender connection.
# The following loops introduces a wait before creating the sender connection. It gives time to the
# router so that the address Dpulp.task can show up on the remoteCount
i = 0
while continue_loop:
if i > 100: # If we have run the read command for more than hundred times and we still do not have
# the remoteCount set to 1, there is a problem, just exit out of the function instead
# of looping to infinity.
self.receiver_connection.close()
return
local_node = Node.connect(self.qdstat_address, timeout=TIMEOUT)
out = local_node.read(type='org.apache.qpid.dispatch.router.address', name='Dpulp.task').remoteCount
if out == 1:
continue_loop = False
else:
i += 1
sleep(0.25)
self.sender_connection = event.container.connect(self.sender_address)
self.sender = event.container.create_sender(self.sender_connection, "pulp.task", options=AtMostOnce())
def on_sendable(self, event):
if self.times == 1:
msg = Message(body="Hello World")
self.sender.send(msg, tag=self.delivery_tag)
self.times += 1
self.sent += 1
def on_message(self, event):
if "Hello World" == event.message.body:
self.rcvd += 1
# If the tag on the delivery is the same as the tag we sent with the initial transfer, it means
# that the router has propagated the delivery tag successfully because of link routing.
if self.delivery_tag != event.delivery.tag:
self.error = "Delivery-tag: expected:%r got:%r" % (self.delivery_tag, event.delivery.tag)
self.receiver_connection.close()
self.sender_connection.close()
self.timer.cancel()
def run(self):
Container(self).run()
class CloseWithUnsettledTest(MessagingHandler):
##
## This test sends a message across an attach-routed link. While the message
## is unsettled, the client link is closed. The test is ensuring that the
## router does not crash during the closing of the links.
##
def __init__(self, normal_addr, route_addr):
super(CloseWithUnsettledTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.CWUtest"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.sender = event.container.create_sender(self.conn_normal, self.dest)
def on_connection_closed(self, event):
self.conn_route.close()
self.timer.cancel()
def on_link_opened(self, event):
if event.receiver:
self.receiver = event.receiver
self.receiver.flow(1)
def on_sendable(self, event):
msg = Message(body="CloseWithUnsettled")
event.sender.send(msg)
def on_message(self, event):
self.conn_normal.close()
def run(self):
Container(self).run()
class DynamicSourceTest(MessagingHandler):
##
## This test verifies that a dynamic source can be propagated via link-route to
## a route-container.
##
def __init__(self, normal_addr, route_addr):
super(DynamicSourceTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.DynamicSource"
self.address = "DynamicSourceAddress"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.receiver = event.container.create_receiver(self.conn_normal, None, dynamic=True,options=DynamicNodeProperties({"x-opt-qd.address":u"pulp.task.abc"}))
def on_link_opened(self, event):
if event.receiver == self.receiver:
if self.receiver.remote_source.address != self.address:
self.error = "Expected %s, got %s" % (self.address, self.receiver.remote_source.address)
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
def on_link_opening(self, event):
if event.sender:
self.sender = event.sender
if not self.sender.remote_source.dynamic:
self.error = "Expected sender with dynamic source"
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
self.sender.source.address = self.address
self.sender.open()
def run(self):
Container(self).run()
class DynamicTarget(LinkOption):
def apply(self, link):
link.target.dynamic = True
link.target.address = None
class DynamicTargetTest(MessagingHandler):
##
## This test verifies that a dynamic source can be propagated via link-route to
## a route-container.
##
def __init__(self, normal_addr, route_addr):
super(DynamicTargetTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.DynamicTarget"
self.address = "DynamicTargetAddress"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.sender = event.container.create_sender(self.conn_normal, None, options=\
[DynamicTarget(), DynamicNodeProperties({"x-opt-qd.address":u"pulp.task.abc"})])
def on_link_opened(self, event):
if event.sender == self.sender:
if self.sender.remote_target.address != self.address:
self.error = "Expected %s, got %s" % (self.address, self.receiver.remote_source.address)
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
def on_link_opening(self, event):
if event.receiver:
self.receiver = event.receiver
if not self.receiver.remote_target.dynamic:
self.error = "Expected receiver with dynamic source"
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
self.receiver.target.address = self.address
self.receiver.open()
def run(self):
Container(self).run()
class DetachNoCloseTest(MessagingHandler):
##
## This test verifies that link-detach (not close) is propagated properly
##
def __init__(self, normal_addr, route_addr):
super(DetachNoCloseTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.DetachNoClose"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def stop(self):
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.receiver = event.container.create_receiver(self.conn_normal, self.dest)
def on_link_opened(self, event):
if event.receiver == self.receiver:
self.receiver.detach()
def on_link_remote_detach(self, event):
if event.sender == self.sender:
self.sender.detach()
if event.receiver == self.receiver:
##
## Test passed, we expected a detach on the propagated sender and back
##
self.stop()
def on_link_closing(self, event):
if event.sender == self.sender:
self.error = 'Propagated link was closed. Expected it to be detached'
self.stop()
if event.receiver == self.receiver:
self.error = 'Client link was closed. Expected it to be detached'
self.stop()
def on_link_opening(self, event):
if event.sender:
self.sender = event.sender
self.sender.source.address = self.sender.remote_source.address
self.sender.open()
def run(self):
Container(self).run()
class DetachMixedCloseTest(MessagingHandler):
##
## This test verifies that link-detach (not close) is propagated properly
##
def __init__(self, normal_addr, route_addr):
super(DetachMixedCloseTest, self).__init__(prefetch=0, auto_accept=False)
self.normal_addr = normal_addr
self.route_addr = route_addr
self.dest = "pulp.task.DetachMixedClose"
self.error = None
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.conn_normal.close()
self.conn_route.close()
def stop(self):
self.conn_normal.close()
self.conn_route.close()
self.timer.cancel()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.conn_route = event.container.connect(self.route_addr)
def on_connection_opened(self, event):
if event.connection == self.conn_route:
self.conn_normal = event.container.connect(self.normal_addr)
elif event.connection == self.conn_normal:
self.receiver = event.container.create_receiver(self.conn_normal, self.dest)
def on_link_opened(self, event):
if event.receiver == self.receiver:
self.receiver.detach()
def on_link_remote_detach(self, event):
if event.sender == self.sender:
self.sender.close()
if event.receiver == self.receiver:
self.error = 'Client link was detached. Expected it to be closed'
self.stop()
def on_link_closing(self, event):
if event.sender == self.sender:
self.error = 'Propagated link was closed. Expected it to be detached'
self.stop()
if event.receiver == self.receiver:
##
## Test Passed
##
self.stop()
def on_link_opening(self, event):
if event.sender:
self.sender = event.sender
self.sender.source.address = self.sender.remote_source.address
self.sender.open()
def run(self):
Container(self).run()
# Test to validate fix for DISPATCH-927
class EchoDetachReceived(MessagingHandler):
def __init__(self, sender_address, recv_address):
super(EchoDetachReceived, self).__init__()
self.sender_address = sender_address
self.recv_address = recv_address
self.dest = "org.apache.dev"
self.num_msgs = 100
self.num_receivers = 10
self.msgs_sent = 0
self.receiver_conn = None
self.sender_conn = None
self.sender = None
self.receiver_dict = {}
self.error = None
self.receiver_attaches = 0
self.timer = None
self.sender_attached = False
self.received_msgs_dict = {}
self.receiver_detach_dict = {}
self.num_detaches_echoed = 0
@property
def msgs_received(self):
return sum(self.received_msgs_dict.values())
def timeout(self):
self.bail("Timeout Expired: msgs_sent=%d msgs_received=%d, number of detaches received=%d"
% (self.msgs_sent, self.msgs_received, self.num_detaches_echoed))
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
# Create two separate connections for sender and receivers
self.receiver_conn = event.container.connect(self.recv_address)
self.sender_conn = event.container.connect(self.sender_address)
for i in range(self.num_receivers):
name = "R%d" % i
self.receiver_dict[name] = event.container.create_receiver(self.receiver_conn, self.dest, name=name)
self.received_msgs_dict[name] = 0
def bail(self, text=None):
self.error = text
self.sender_conn.close()
self.receiver_conn.close()
self.timer.cancel()
def on_link_opened(self, event):
if event.receiver:
if event.receiver.name in list(self.receiver_dict):
self.receiver_attaches+=1
# The response receiver attaches have been received. The receiver sent attaches which was link routed
# all the way to the 'broker' router and the response attaches have come back.
# It is now time to create the sender.
if self.receiver_attaches == self.num_receivers:
self.sender = event.container.create_sender(self.sender_conn, self.dest)
elif event.sender:
if not self.sender_attached:
if event.sender == self.sender:
# The sender attaches were link routed as well and the response attach has been received.
self.sender_attached = True
def on_sendable(self, event):
# The sender will send 100 messages
if self.receiver_attaches == self.num_receivers and self.sender_attached:
if self.msgs_sent < self.num_msgs:
msg = Message(body="Hello World")
self.sender.send(msg)
self.msgs_sent += 1
def on_message(self, event):
if event.receiver and event.receiver.name in list(self.receiver_dict):
self.received_msgs_dict[event.receiver.name] += 1
if sum(self.received_msgs_dict.values()) == self.num_msgs:
# The receivers have received a total of 100 messages. Close the receivers. The detach sent by these
# receivers will travel all the way over the link route and the 'broker' router will respond with a
# detach
for receiver in list(self.receiver_dict):
self.receiver_dict[receiver].close()
def on_link_closed(self, event):
if event.receiver.name in list(self.receiver_dict) and event.receiver.name not in list(self.receiver_detach_dict):
self.receiver_detach_dict[event.receiver.name] = event.receiver
self.num_detaches_echoed += 1
# Terminate the test only if both detach frames have been received.
if all(receiver in list(self.receiver_detach_dict) for receiver in list(self.receiver_dict)):
self.bail()
def run(self):
Container(self).run()
class TerminusAddrTest(MessagingHandler):
def __init__(self, sender_address, listening_address, query_address_sending, query_address_listening):
super(TerminusAddrTest, self).__init__()
self.sender_address = sender_address
self.listening_address = listening_address
self.sender = None
self.receiver = None
self.message_received = False
self.receiver_connection = None
self.sender_connection = None
# We will run a query on the same router where the sender is attached
self.query_address_sending = query_address_sending
# We will run a query on the same router where the receiver is attached
self.query_address_listening = query_address_listening
self.count = 0
self.in_receiver_found = False
self.out_receiver_found = False
self.in_sender_found = False
self.out_sender_found = False
self.receiver_link_opened = False
self.sender_link_opened = False
def on_start(self, event):
self.receiver_connection = event.container.connect(self.listening_address)
def on_connection_remote_open(self, event):
if event.connection == self.receiver_connection:
continue_loop = True
# The following loops introduces a wait. It gives time to the
# router so that the address Dpulp.task can show up on the remoteCount
i = 0
while continue_loop:
if i > 100: # If we have run the read command for more than hundred times and we still do not have
# the remoteCount set to 1, there is a problem, just exit out of the function instead
# of looping to infinity.
self.receiver_connection.close()
return
local_node = Node.connect(self.query_address_sending, timeout=TIMEOUT)
out = local_node.read(type='org.apache.qpid.dispatch.router.address', name='Dpulp.task').remoteCount
if out == 1:
continue_loop = False
i += 1
sleep(0.25)
self.sender_connection = event.container.connect(self.sender_address)
# Notice here that the receiver and sender are listening on different addresses. Receiver on
# pulp.task.terminusTestReceiver and the sender on pulp.task.terminusTestSender
self.receiver = event.container.create_receiver(self.receiver_connection, "pulp.task.terminusTestReceiver")
self.sender = event.container.create_sender(self.sender_connection, "pulp.task.terminusTestSender", options=AtMostOnce())
def on_link_opened(self, event):
if event.receiver == self.receiver:
self.receiver_link_opened = True
local_node = Node.connect(self.query_address_listening, timeout=TIMEOUT)
out = local_node.query(type='org.apache.qpid.dispatch.router.link')
link_dir_index = out.attribute_names.index("linkDir")
owning_addr_index = out.attribute_names.index("owningAddr")
# Make sure that the owningAddr M0pulp.task.terminusTestReceiver shows up on both in and out.
# The 'out' link is on address M0pulp.task.terminusTestReceiver outgoing from the router B to the receiver
# The 'in' link is on address M0pulp.task.terminusTestReceiver incoming from router C to router B
for result in out.results:
if result[link_dir_index] == 'in' and result[owning_addr_index] == 'M0pulp.task.terminusTestReceiver':
self.in_receiver_found = True
if result[link_dir_index] == 'out' and result[owning_addr_index] == 'M0pulp.task.terminusTestReceiver':
self.out_receiver_found = True
if event.sender == self.sender:
self.sender_link_opened = True
local_node = Node.connect(self.query_address_sending, timeout=TIMEOUT)
out = local_node.query(type='org.apache.qpid.dispatch.router.link')
link_dir_index = out.attribute_names.index("linkDir")
owning_addr_index = out.attribute_names.index("owningAddr")
# Make sure that the owningAddr M0pulp.task.terminusTestSender shows up on both in and out.
# The 'in' link is on address M0pulp.task.terminusTestSender incoming from sender to router
# The 'out' link is on address M0pulp.task.terminusTestSender outgoing from router C to router B
for result in out.results:
if result[link_dir_index] == 'in' and result[owning_addr_index] == 'M0pulp.task.terminusTestSender':
self.in_sender_found = True
if result[link_dir_index] == 'out' and result[owning_addr_index] == 'M0pulp.task.terminusTestSender':
self.out_sender_found = True
# Shutdown the connections only if the on_link_opened has been called for sender and receiver links.
if self.sender_link_opened and self.receiver_link_opened:
self.sender.close()
self.receiver.close()
self.sender_connection.close()
self.receiver_connection.close()
def run(self):
Container(self).run()
class MultiLinkSendReceive(MessagingHandler):
class SendState(object):
def __init__(self, link):
self.link = link
self.sent = False
self.accepted = False
self.done = False
self.closed = False
def send(self, subject, body):
if not self.sent:
self.link.send(Message(subject=subject,body=body,address=self.link.target.address))
self.sent = True
def on_accepted(self):
self.accepted = True
self.done = True
def close(self):
if not self.closed:
self.closed = True
self.link.close()
self.link.connection.close()
class RecvState(object):
def __init__(self, link):
self.link = link
self.received = False
self.done = False
self.closed = False
def on_message(self):
self.received = True
self.done = True
def close(self):
if not self.closed:
self.closed = True
self.link.close()
self.link.connection.close()
def __init__(self, send_urls, recv_urls, name, message=None):
super(MultiLinkSendReceive, self).__init__()
self.send_urls = send_urls
self.recv_urls = recv_urls
self.senders = {}
self.receivers = {}
self.message = message or "SendReceiveTest"
self.sent = False
self.error = None
self.name = name
def close(self):
for sender in self.senders.values():
sender.close()
for receiver in self.receivers.values():
receiver.close()
def all_done(self):
for sender in self.senders.values():
if not sender.done:
return False
for receiver in self.receivers.values():
if not receiver.done:
return False
return True
def timeout(self):
self.error = "Timeout Expired"
self.close()
def stop_if_all_done(self):
if self.all_done():
self.stop()
def stop(self):
self.close()
self.timer.cancel()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
event.container.container_id = None
for u in self.send_urls:
s = self.SendState(event.container.create_sender(u, name=self.name))
self.senders[s.link.connection.container] = s
for u in self.recv_urls:
r = self.RecvState(event.container.create_receiver(u, name=self.name))
self.receivers[r.link.connection.container] = r
def on_sendable(self, event):
self.senders[event.connection.container].send(self.name, self.message)
def on_message(self, event):
if self.message != event.message.body:
error = "Incorrect message. Got %s, expected %s" % (event.message.body, self.message.body)
self.receivers[event.connection.container].on_message()
self.stop_if_all_done()
def on_accepted(self, event):
self.senders[event.connection.container].on_accepted()
self.stop_if_all_done()
def run(self):
Container(self).run()
class LinkRouteProtocolTest(TestCase):
@classmethod
def setUpClass(cls):
super(LinkRouteProtocolTest, cls).setUpClass()
config = [
('router', {'mode': 'standalone', 'id': 'QDR.A'}),
# for client connections:
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the fake broker
('connector', {'name': 'broker',
'role': 'route-container',
'host': '127.0.0.1',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# forward 'org.apache' messages to + from fake broker:
('linkRoute', {'prefix': 'org.apache', 'containerId': 'FakeBroker', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache', 'containerId': 'FakeBroker', 'direction': 'out'})
]
config = Qdrouterd.Config(config)
cls.router = cls.tester.qdrouterd('A', config, wait=False)
def _fake_broker(self, cls):
fake_broker = cls(self.router.connector_addresses[0])
# wait until the connection to the fake broker activates
self.router.wait_connectors()
return fake_broker
def test_DISPATCH_1092(self):
# This fake broker will force the session closed after the link
# detaches. Verify that the session comes back up correctly when the
# next client attaches
killer = self._fake_broker(SessionKiller)
for i in range(2):
bconn = BlockingConnection(self.router.addresses[0])
bsender = bconn.create_sender(address="org.apache",
options=AtLeastOnce())
msg = Message(body="Hey!")
bsender.send(msg)
bsender.close()
bconn.close()
killer.join()
class SessionKiller(FakeBroker):
def __init__(self, url):
super(SessionKiller, self).__init__(url)
def on_link_closing(self, event):
event.link.close()
event.session.close()
class FakeBrokerDrain(FakeBroker):
def __init__(self, url):
super(FakeBrokerDrain, self).__init__(url)
self.first_flow_received = False
self.first_drain_mode = False
self.second_drain_mode = False
self.error = None
self.num_flows = 0
self.success = False
def on_link_flow(self, event):
if event.link.is_sender:
if event.sender.drain_mode:
if not self.first_drain_mode:
self.first_drain_mode = True
event.sender.drained()
elif not self.second_drain_mode:
self.second_drain_mode = True
if event.link.credit == 1000:
# Without the patch for DISPATCH-1496,
# the event.link.credit value would be 2000
self.success = True
else:
self.success = False
event.sender.drained()
else:
if not self.first_flow_received:
self.first_flow_received = True
msg = Message(body="First Drain Transfer")
event.link.send(msg)
class DrainReceiver(MessagingHandler):
def __init__(self, url, fake_broker):
super(DrainReceiver, self).__init__(prefetch=0, auto_accept=False)
self.url = url
self.received = 0
self.receiver = None
self.first_drain_sent = False
self.second_drain_sent = False
self.first_flow_sent = False
self.receiver_conn = None
self.error = None
self.num_flows = 0
self.fake_broker = fake_broker
def on_start(self, event):
self.receiver_conn = event.container.connect(self.url)
self.receiver = event.container.create_receiver(self.receiver_conn, "org.apache")
# Step 1: Send a flow of 1000 to the router. The router will forward this
# flow to the FakeBroker
self.receiver.flow(1000)
self.first_flow_sent = True
def on_link_flow(self, event):
if event.receiver == self.receiver:
self.num_flows += 1
if self.num_flows == 1:
# Step 4: The response drain received from the FakeBroker
# Step 5: Send second flow of 1000 credits. This is forwarded to the FakeBroker
self.receiver.flow(1000)
self.timer = event.reactor.schedule(3, TestTimeout(self))
elif self.num_flows == 2:
if not self.fake_broker.success:
self.error = "The FakeBroker did not receive correct credit of 1000"
self.receiver_conn.close()
def timeout(self):
# Step 6: The second drain is sent to the router. The router was forwarding the wrong credit (2000) to the FakeBroker
# but with the fix for DISPATCH-1496, the correct credit is forwarded (1000)
self.receiver.drain(0)
self.second_drain_sent = True
def on_message(self, event):
if event.receiver == self.receiver:
self.received += 1
# Step 2: In response to Step 1, the broker has sent the only message in its queue
if self.received == 1:
self.first_drain_sent = True
#print ("First message received. Doing first drain")
# Step 3: The receiver drains after receiving the first message.
# This drain is forwarded to the FakeBroker
self.receiver.drain(0)
def run(self):
Container(self).run()
class LinkRouteDrainTest(TestCase):
@classmethod
def setUpClass(cls):
super(LinkRouteDrainTest, cls).setUpClass()
config = [
('router', {'mode': 'standalone', 'id': 'QDR.A'}),
# for client connections:
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the fake broker
('connector', {'name': 'broker',
'role': 'route-container',
'host': '127.0.0.1',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# forward 'org.apache' messages to + from fake broker:
('linkRoute', {'prefix': 'org.apache', 'containerId': 'FakeBroker', 'direction': 'in'}),
('linkRoute', {'prefix': 'org.apache', 'containerId': 'FakeBroker', 'direction': 'out'})
]
config = Qdrouterd.Config(config)
cls.router = cls.tester.qdrouterd('A', config, wait=False)
def _fake_broker(self, cls):
fake_broker = cls(self.router.connector_addresses[0])
# wait until the connection to the fake broker activates
self.router.wait_connectors()
return fake_broker
def test_DISPATCH_1496(self):
fake_broker = self._fake_broker(FakeBrokerDrain)
drain_receiver = DrainReceiver(self.router.addresses[0], fake_broker)
drain_receiver.run()
self.assertEquals(drain_receiver.error, None)
class ConnectionLinkRouteTest(TestCase):
_AS_TYPE = "org.apache.qpid.dispatch.router.connection.linkRoute"
@classmethod
def setUpClass(cls):
super(ConnectionLinkRouteTest, cls).setUpClass()
b_port = cls.tester.get_port()
configs = [
# QDR.A:
[('router', {'mode': 'interior', 'id': 'QDR.A'}),
# for fake connection-scoped LRs:
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# for fake route-container LR connections:
('listener', {'role': 'route-container',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the QDR.B
('connector', {'role': 'inter-router',
'host': '127.0.0.1',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'})],
# QDR.B:
[('router', {'mode': 'interior', 'id': 'QDR.B'}),
# for client connections
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# for connection to QDR.A
('listener', {'role': 'inter-router',
'host': '0.0.0.0',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'})]
]
cls.routers=[]
for c in configs:
config = Qdrouterd.Config(c)
cls.routers.append(cls.tester.qdrouterd(config=config, wait=False))
cls.QDR_A = cls.routers[0]
cls.QDR_B = cls.routers[1]
cls.QDR_A.wait_router_connected('QDR.B')
cls.QDR_B.wait_router_connected('QDR.A')
def _get_address(self, mgmt, addr):
a_type = 'org.apache.qpid.dispatch.router.address'
return list(filter(lambda a: a['name'].endswith(addr),
mgmt.query(a_type)))
def test_config_file_bad(self):
# verify that specifying a connection link route in the configuration
# file fails
config = [('router', {'mode': 'interior', 'id': 'QDR.X'}),
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': self.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
('connection.linkRoute',
{'pattern': "i/am/bad",
'direction': "out"})
]
cfg = Qdrouterd.Config(config)
# we expect the router to fail
router = self.tester.qdrouterd("X", cfg, wait=False, expect=Process.EXIT_FAIL)
def test_mgmt(self):
# test create, delete, and query
mgmt_conn = BlockingConnection(self.QDR_A.addresses[0])
mgmt_proxy = ConnLinkRouteMgmtProxy(mgmt_conn)
for i in range(10):
rsp = mgmt_proxy.create_conn_link_route("lr1-%d" % i,
{'pattern': "*/hi/there/%d" % i,
'direction':
'out' if i % 2 else 'in'})
self.assertEqual(201, rsp.status_code)
# test query
rsp = mgmt_proxy.query_conn_link_routes()
self.assertEqual(200, rsp.status_code)
self.assertEqual(10, len(rsp.results))
entities = rsp.results
# test read
rsp = mgmt_proxy.read_conn_link_route('lr1-5')
self.assertEqual(200, rsp.status_code)
self.assertEqual("lr1-5", rsp.attrs['name'])
self.assertEqual("*/hi/there/5", rsp.attrs['pattern'])
self.assertEqual(mgmt_conn.container.container_id,
rsp.attrs['containerId'])
# bad creates
attrs = [{'pattern': "bad", 'direction': "bad"},
{'direction': 'in'},
{},
{'pattern': ''},
{'pattern': 7}]
for a in attrs:
rsp = mgmt_proxy.create_conn_link_route("iamnoone", a)
self.assertEqual(400, rsp.status_code)
# bad read
rsp = mgmt_proxy.read_conn_link_route('iamnoone')
self.assertEqual(404, rsp.status_code)
# bad delete
rsp = mgmt_proxy.delete_conn_link_route('iamnoone')
self.assertEqual(404, rsp.status_code)
# delete all
for r in entities:
self.assertEqual(200, r.status_code)
rsp = mgmt_proxy.delete_conn_link_route(r.attrs['name'])
self.assertEqual(204, rsp.status_code)
# query - should be none left
rsp = mgmt_proxy.query_conn_link_routes()
self.assertEqual(200, rsp.status_code)
self.assertEqual(0, len(rsp.results))
def test_address_propagation(self):
# test service that creates and deletes connection link routes
fs = ConnLinkRouteService(self.QDR_A.addresses[1], container_id="FakeService",
config = [("clr1",
{"pattern": "flea.*",
"direction": "out"}),
("clr2",
{"pattern": "flea.*",
"direction": "in"})])
self.assertEqual(2, len(fs.values))
# the address should propagate to A and B
self.QDR_A.wait_address(address="flea.*", count=2)
self.QDR_B.wait_address(address="flea.*", count=2)
# now have the service delete the config
fs.delete_config()
# eventually the addresses will be un-published
mgmt_A = QdManager(self, address=self.QDR_A.addresses[0])
mgmt_B = QdManager(self, address=self.QDR_B.addresses[0])
deadline = time() + TIMEOUT
while (self._get_address(mgmt_A, "flea.*")
or self._get_address(mgmt_B, "flea.*")):
self.assertTrue(time() < deadline)
sleep(0.1)
fs.join();
# simple forwarding tests with auto delete
def test_send_receive(self):
COUNT = 5
mgmt_A = QdManager(self, address=self.QDR_A.addresses[0])
mgmt_B = QdManager(self, address=self.QDR_B.addresses[0])
# connect broker to A route-container
fs = ConnLinkRouteService(self.QDR_A.addresses[1], container_id="FakeService",
config = [("clr1",
{"pattern": "flea.*",
"direction": "out"}),
("clr2",
{"pattern": "flea.*",
"direction": "in"})])
self.assertEqual(2, len(fs.values))
# wait for the address to propagate to B
self.QDR_B.wait_address(address="flea.*", count=2)
# ensure the link routes are not visible via other connections
clrs = mgmt_A.query(self._AS_TYPE)
self.assertEqual(0, len(clrs))
# send from A to B
r = AsyncTestReceiver(self.QDR_B.addresses[0],
"flea.B",
container_id="flea.BReceiver")
s = AsyncTestSender(self.QDR_A.addresses[0],
"flea.B",
container_id="flea.BSender",
message=Message(body="SENDING TO flea.B"),
count=COUNT)
s.wait() # for sender to complete
for i in range(COUNT):
self.assertEqual("SENDING TO flea.B",
r.queue.get(timeout=TIMEOUT).body)
r.stop()
self.assertEqual(COUNT, fs.in_count)
# send from B to A
r = AsyncTestReceiver(self.QDR_A.addresses[0],
"flea.A",
container_id="flea.AReceiver")
s = AsyncTestSender(self.QDR_B.addresses[0],
"flea.A",
container_id="flea.ASender",
message=Message(body="SENDING TO flea.A"),
count=COUNT)
s.wait()
for i in range(COUNT):
self.assertEqual("SENDING TO flea.A",
r.queue.get(timeout=TIMEOUT).body)
r.stop()
self.assertEqual(2 * COUNT, fs.in_count)
# once the fake service closes its conn the link routes
# are removed so the link route addresses must be gone
fs.join()
mgmt_A = QdManager(self, address=self.QDR_A.addresses[0])
mgmt_B = QdManager(self, address=self.QDR_B.addresses[0])
deadline = time() + TIMEOUT
while (self._get_address(mgmt_A, "flea.*")
or self._get_address(mgmt_B, "flea.*")):
self.assertTrue(time() < deadline)
sleep(0.1)
class ConnLinkRouteService(FakeBroker):
def __init__(self, url, container_id, config, timeout=TIMEOUT):
self.conn = None
self.mgmt_proxy = None
self.mgmt_sender = None
self.mgmt_receiver = None
self._config = config
self._config_index = 0
self._config_done = Event()
self._config_error = None
self._config_values = []
self._cleaning_up = False
self._delete_done = Event()
self._delete_count = 0
self._event_injector = EventInjector()
self._delete_event = ApplicationEvent("delete_config")
super(ConnLinkRouteService, self).__init__(url, container_id)
if self._config_done.wait(timeout) is False:
raise Exception("Timed out waiting for configuration setup")
if self._config_error is not None:
raise Exception("Error: %s" % self._config_error)
@property
def values(self):
return self._config_values
def delete_config(self):
self._event_injector.trigger(self._delete_event)
if self._delete_done.wait(TIMEOUT) is False:
raise Exception("Timed out waiting for configuration delete")
def on_start(self, event):
event.container.selectable(self._event_injector)
self.conn = event.container.connect(self.url)
def on_connection_opened(self, event):
if event.connection == self.conn:
if self.mgmt_receiver is None:
self.mgmt_receiver = event.container.create_receiver(self.conn,
dynamic=True)
super(ConnLinkRouteService, self).on_connection_opened(event)
def on_connection_closed(self, event):
if self._event_injector:
self._event_injector.close()
self._event_injector = None
super(ConnLinkRouteService, self).on_connection_closed(event)
def on_link_opened(self, event):
if event.link == self.mgmt_receiver:
self.mgmt_proxy = MgmtMsgProxy(self.mgmt_receiver.remote_source.address)
self.mgmt_sender = event.container.create_sender(self.conn,
target="$management")
def on_link_error(self, event):
# when a remote client disconnects the service will get a link error
# that is expected - simply clean up the link
self.on_link_closing(event)
def on_sendable(self, event):
if event.sender == self.mgmt_sender:
if not self._cleaning_up:
if self._config_index < len(self._config):
cfg = self._config[self._config_index]
msg = self.mgmt_proxy.create_conn_link_route(cfg[0], cfg[1])
self.mgmt_sender.send(msg)
self._config_index += 1
elif self._config_values:
cv = self._config_values.pop()
msg = self.mgmt_proxy.delete_conn_link_route(cv['name'])
self._delete_count += 1
else:
super(ConnLinkRouteService, self).on_sendable(event)
def on_message(self, event):
if event.receiver == self.mgmt_receiver:
response = self.mgmt_proxy.response(event.message)
if response.status_code == 201:
# created:
self._config_values.append(response.attrs)
if len(self._config_values) == len(self._config):
self._config_done.set()
elif response.status_code == 204:
# deleted
self._delete_count -= 1
if (not self._config_values) and self._delete_count == 0:
self._delete_done.set()
else:
# error
self._config_error = ("mgmt failed: %s" %
response.status_description)
self._config_done.set()
self._delete_done.set()
else:
super(ConnLinkRouteService, self).on_message(event)
def on_delete_config(self, event):
if not self._cleaning_up:
self._cleaning_up = True
if not self._config_values:
self._delete_done.set()
else:
try:
while self.mgmt_sender.credit > 0:
cv = self._config_values.pop()
msg = self.mgmt_proxy.delete_conn_link_route(cv["name"])
self.mgmt_sender.send(msg)
self._delete_count += 1
except IndexError:
pass
class ConnLinkRouteMgmtProxy(object):
def __init__(self, bconn, credit=250):
self._receiver = bconn.create_receiver(address=None, dynamic=True, credit=credit)
self._sender = bconn.create_sender(address="$management")
self._proxy = MgmtMsgProxy(self._receiver.link.remote_source.address)
def __getattr__(self, key):
# wrap accesses to the management message functions so we can send and
# receive the messages using the blocking links
f = getattr(self._proxy, key)
if not callable(f):
return f
def _func(*args, **kwargs):
self._sender.send(f(*args, **kwargs))
return self._proxy.response(self._receiver.receive())
return _func
class InvalidTagTest(MessagingHandler):
def __init__(self, router_addr):
super(InvalidTagTest, self).__init__(auto_accept=False, auto_settle=False)
self.test_conn = None
self.test_address = router_addr
self.tx_ct = 0;
self.accept_ct = 0;
self.reject_ct = 0;
self.error = None
def timeout(self):
self.error = "Timeout expired: sent=%d rcvd=%d" % (self.tx_ct,
self.accept_ct
+ self.reject_ct)
if self.test_conn:
self.test_conn.close()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.test_conn = event.container.connect(self.test_address)
rx = event.container.create_receiver(self.test_conn, "org.apache.foo")
def on_link_opened(self, event):
if event.receiver:
event.receiver.flow(100)
event.container.create_sender(event.connection, "org.apache.foo")
def on_sendable(self, event):
if self.tx_ct < 10:
self.tx_ct += 1
if self.tx_ct == 5:
event.sender.send(Message(body="YO"), tag=str("X" * 64))
else:
event.sender.send(Message(body="YO"), tag=str("BLAH%d" %
self.tx_ct))
def on_accepted(self, event):
self.accept_ct += 1
event.delivery.settle()
if self.accept_ct == 9 and self.reject_ct == 1:
event.connection.close()
self.timer.cancel()
def on_rejected(self, event):
self.reject_ct += 1
event.delivery.settle()
def on_message(self, event):
event.delivery.update(Delivery.ACCEPTED)
event.delivery.settle()
def run(self):
Container(self).run()
class Dispatch1428(TestCase):
@classmethod
def get_router(cls, index):
return cls.routers[index]
@classmethod
def setUpClass(cls):
super(Dispatch1428, cls).setUpClass()
def router(name, connection):
config = [
('router', {'mode': 'interior', 'id': 'QDR.%s'%name}),
] + connection
config = Qdrouterd.Config(config)
cls.routers.append(cls.tester.qdrouterd(name, config, wait=False))
cls.routers = []
a_listener_port = cls.tester.get_port()
b_listener_port = cls.tester.get_port()
router('A',
[
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
])
router('B',
[
('listener', {'role': 'normal', 'host': '0.0.0.0', 'port': b_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
('connector', {'name': 'one', 'role': 'route-container', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'}),
('connector', {'name': 'two', 'role': 'route-container', 'host': '0.0.0.0', 'port': a_listener_port, 'saslMechanisms': 'ANONYMOUS'})
]
)
sleep(2)
def run_qdmanage(self, cmd, input=None, expect=Process.EXIT_OK, address=None):
p = self.popen(
['qdmanage'] + cmd.split(' ') + ['--bus', address or self.address(), '--indent=-1', '--timeout', str(TIMEOUT)],
stdin=PIPE, stdout=PIPE, stderr=STDOUT, expect=expect,
universal_newlines=True)
out = p.communicate(input)[0]
try:
p.teardown()
except Exception as e:
raise Exception("%s\n%s" % (e, out))
return out
def test_both_link_routes_active(self):
cmds = [
'CREATE --type=linkRoute name=foo prefix=foo direction=in connection=one',
'CREATE --type=linkRoute name=bar prefix=bar direction=in connection=two',
'CREATE --type=linkRoute name=baz prefix=baz direction=in containerId=QDR.A'
]
for c in cmds:
self.run_qdmanage(cmd=c, address=self.routers[1].addresses[0])
# Now that the qdmanage has run, query the link routes and make sure that their "operStatus" is "active" before
# running any of the tests.
long_type = 'org.apache.qpid.dispatch.router.config.linkRoute'
qd_manager = QdManager(self, address=self.routers[1].addresses[0])
for i in range(5):
all_link_routes_activated = True
link_routes = qd_manager.query(long_type)
for link_route in link_routes:
oper_status = link_route['operStatus']
if oper_status != "active":
all_link_routes_activated = False
break
if not all_link_routes_activated:
# One or more of the link routes have not been activated.
# Check after one second.
sleep(1)
else:
break
# All link routes created in this test MUST be activated before
# we can continue further testing.
self.assertTrue(all_link_routes_activated)
first = SendReceive("%s/foo" % self.routers[1].addresses[0], "%s/foo" % self.routers[0].addresses[0])
first.run()
self.assertEqual(None, first.error)
second = SendReceive("%s/bar" % self.routers[1].addresses[0], "%s/bar" % self.routers[0].addresses[0])
second.run()
self.assertEqual(None, second.error)
third = SendReceive("%s/baz" % self.routers[1].addresses[0], "%s/baz" % self.routers[0].addresses[0])
third.run()
self.assertEqual(None, third.error)
class SendReceive(MessagingHandler):
def __init__(self, send_url, recv_url, message=None):
super(SendReceive, self).__init__()
self.send_url = send_url
self.recv_url = recv_url
self.message = message or Message(body="SendReceiveTest")
self.sent = False
self.error = None
def close(self):
self.sender.close()
self.receiver.close()
self.sender.connection.close()
self.receiver.connection.close()
def timeout(self):
self.error = "Timeout Expired - Check for cores"
self.close()
def stop(self):
self.close()
self.timer.cancel()
def on_start(self, event):
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
event.container.container_id = "SendReceiveTestClient"
self.sender = event.container.create_sender(self.send_url)
self.receiver = event.container.create_receiver(self.recv_url)
def on_sendable(self, event):
if not self.sent:
event.sender.send(self.message)
self.sent = True
def on_message(self, event):
if self.message.body != event.message.body:
self.error = "Incorrect message. Got %s, expected %s" % (event.message.body, self.message.body)
def on_accepted(self, event):
self.stop()
def run(self):
Container(self).run()
class LinkRoute3Hop(TestCase):
@classmethod
def setUpClass(cls):
super(LinkRoute3Hop, cls).setUpClass()
b_port = cls.tester.get_port()
configs = [
# QDR.A:
[('router', {'mode': 'interior', 'id': 'QDR.A'}),
# for client access
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# for fake service:
('listener', {'role': 'route-container',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the QDR.B
('connector', {'role': 'inter-router',
'host': '127.0.0.1',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'}),
# the routes
('linkRoute', {'prefix': 'closest/test-client', 'containerId': 'FakeService', 'direction': 'in'}),
('linkRoute', {'prefix': 'closest/test-client', 'containerId': 'FakeService', 'direction': 'out'})
],
# QDR.B:
[('router', {'mode': 'interior', 'id': 'QDR.B'}),
# for client connections
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# for inter-router connections from QDR.A and QDR.C
('listener', {'role': 'inter-router',
'host': '0.0.0.0',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'}),
('linkRoute', {'prefix': 'closest/test-client', 'direction': 'in'}),
('linkRoute', {'prefix': 'closest/test-client', 'direction': 'out'})
],
# QDR.C
[('router', {'mode': 'interior', 'id': 'QDR.C'}),
# for client connections
('listener', {'role': 'normal',
'host': '0.0.0.0',
'port': cls.tester.get_port(),
'saslMechanisms': 'ANONYMOUS'}),
# to connect to the QDR.B
('connector', {'role': 'inter-router',
'host': '127.0.0.1',
'port': b_port,
'saslMechanisms': 'ANONYMOUS'}),
('linkRoute', {'prefix': 'closest/test-client', 'direction': 'in'}),
('linkRoute', {'prefix': 'closest/test-client', 'direction': 'out'})
]
]
cls.routers=[]
for c in configs:
config = Qdrouterd.Config(c)
cls.routers.append(cls.tester.qdrouterd(config=config, wait=False))
cls.QDR_A = cls.routers[0]
cls.QDR_B = cls.routers[1]
cls.QDR_C = cls.routers[2]
cls.QDR_A.wait_router_connected('QDR.B')
cls.QDR_B.wait_router_connected('QDR.A')
cls.QDR_B.wait_router_connected('QDR.C')
cls.QDR_C.wait_router_connected('QDR.B')
cls.QDR_C.wait_router_connected('QDR.A')
cls.QDR_A.wait_router_connected('QDR.C')
cls.fake_service = FakeService(cls.QDR_A.addresses[1],
container_id="FakeService")
cls.QDR_C.wait_address("closest/test-client",
remotes=1, count=2)
def test_01_parallel_link_routes(self):
send_clients = 10
send_batch = 10
total = send_clients * send_batch
start_in = self.fake_service.in_count
start_out = self.fake_service.out_count
env = dict(os.environ, PN_TRACE_FRM="1")
rx = self.popen(["test-receiver",
"-a", self.QDR_C.addresses[0],
"-c", str(total),
"-s", "closest/test-client"],
env=env,
expect=Process.EXIT_OK)
def _spawn_sender(x):
return self.popen(["test-sender",
"-a", self.QDR_C.addresses[0],
"-c", str(send_batch),
"-i", "TestSender-%s" % x,
"-sx", # huge message size to trigger Q2/Q3
"-t", "closest/test-client"],
env=env,
expect=Process.EXIT_OK)
senders = [_spawn_sender(s) for s in range(send_clients)]
for tx in senders:
out_text, out_err = tx.communicate(timeout=TIMEOUT)
if tx.returncode:
raise Exception("Sender failed: %s %s" % (out_text, out_err))
if rx.wait(timeout=TIMEOUT):
raise Exception("Receiver failed to consume all messages in=%s out=%s",
self.fake_service.in_count,
self.fake_service.out_count)
self.assertEqual(start_in + total, self.fake_service.in_count)
self.assertEqual(start_out + total, self.fake_service.out_count)
if __name__ == '__main__':
unittest.main(main_module())
| true | true |
f72f3f14c41617165cb68986338ef49ad0c75ee8 | 3,116 | py | Python | python_implementation/example/example7.py | mannyray/sort | f0ee0488aa4e7213d30ff50bcb848a843fedde42 | [
"MIT"
] | 2 | 2021-11-08T09:25:23.000Z | 2022-03-14T08:44:09.000Z | python_implementation/example/example7.py | mannyray/sort | f0ee0488aa4e7213d30ff50bcb848a843fedde42 | [
"MIT"
] | null | null | null | python_implementation/example/example7.py | mannyray/sort | f0ee0488aa4e7213d30ff50bcb848a843fedde42 | [
"MIT"
] | null | null | null | import commonExample
import math
import sys
sys.path.insert(0,'..')
import generate
import constants
from numpy import random
import intersection
from PIL import Image, ImageDraw, ImageFont
gif_file="example7"
xcoords = [constants.width,constants.width,constants.width,100,400,700,1000,1300]
ycoords = [50,350,700,constants.height, constants.height, constants.height, constants.height, constants.height]
def updateCoords(xCor,yCor,frameNumber):
lastFrame = False
turnBackHorizontal = False
turnBackVertical = False
if frameNumber > constants.width/constants.step_size:
turnBackHorizontal = True
if frameNumber > constants.height/constants.step_size:
turnBackVertical = True
if yCor[3] > constants.height + 10:
lastFrame = True
for i in range(0,len(xCor)):
if i < 3:
if turnBackHorizontal == False:
xCor[i] = xCor[i] - constants.step_size
else:
xCor[i] = xCor[i] + constants.step_size
else:
if turnBackVertical == False:
yCor[i] = yCor[i] - constants.step_size
else:
yCor[i] = yCor[i] + constants.step_size
return lastFrame, xCor, yCor
def drawImage7(image,draw,xcoords,ycoords,index):
if index == 0:
original = Image.open('assets/orange.jpg')
elif index == 1:
original = Image.open('assets/apple.jpg')
elif index == 2:
original = Image.open('assets/watermellon.jpg')
elif index == 3:
original = Image.open('assets/orange.jpg')
elif index == 4:
original = Image.open('assets/apple.jpg')
elif index == 5:
original = Image.open('assets/watermellon.jpg')
elif index == 6:
original = Image.open('assets/apple.jpg')
elif index == 7:
original = Image.open('assets/watermellon.jpg')
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 20)
image.paste(original, box=(xcoords[index],ycoords[index]))
draw.text((xcoords[index]+constants.orange_width/2,ycoords[index]+constants.orange_width/2),str(index+1),fill=(0,0,0), font=font)
def boundBoxNoNoise7(x,y,index):
center = 25
objectType = None
if index == 0:
objectType = "orange"
if index == 1:
objectType = "apple"
if index == 2:
objectType = "watermellon"
if index == 3:
objectType = "orange"
if index == 4:
objectType = "apple"
if index == 5:
objectType = "watermellon"
elif index == 6:
objectType = "apple"
elif index == 7:
objectType = "watermellon"
return x+center, y+center, constants.orange_width - center*2, constants.orange_width - center*2.5,objectType
def boundBoxNoise7(x,y,index):
multiplier = 10
x,y,w,h,objectType = boundBoxNoNoise7(x,y,index)
arr = random.normal(size=(4,1))*multiplier
return x+arr[0], y+arr[1], w+arr[2], h+arr[3], objectType
commonExample.common_run(updateCoords,gif_file,xcoords,ycoords,boundBoxNoise=boundBoxNoise7,boundBoxNoNoise=boundBoxNoNoise7,drawImage=drawImage7,saveData=True)
| 34.622222 | 160 | 0.652118 | import commonExample
import math
import sys
sys.path.insert(0,'..')
import generate
import constants
from numpy import random
import intersection
from PIL import Image, ImageDraw, ImageFont
gif_file="example7"
xcoords = [constants.width,constants.width,constants.width,100,400,700,1000,1300]
ycoords = [50,350,700,constants.height, constants.height, constants.height, constants.height, constants.height]
def updateCoords(xCor,yCor,frameNumber):
lastFrame = False
turnBackHorizontal = False
turnBackVertical = False
if frameNumber > constants.width/constants.step_size:
turnBackHorizontal = True
if frameNumber > constants.height/constants.step_size:
turnBackVertical = True
if yCor[3] > constants.height + 10:
lastFrame = True
for i in range(0,len(xCor)):
if i < 3:
if turnBackHorizontal == False:
xCor[i] = xCor[i] - constants.step_size
else:
xCor[i] = xCor[i] + constants.step_size
else:
if turnBackVertical == False:
yCor[i] = yCor[i] - constants.step_size
else:
yCor[i] = yCor[i] + constants.step_size
return lastFrame, xCor, yCor
def drawImage7(image,draw,xcoords,ycoords,index):
if index == 0:
original = Image.open('assets/orange.jpg')
elif index == 1:
original = Image.open('assets/apple.jpg')
elif index == 2:
original = Image.open('assets/watermellon.jpg')
elif index == 3:
original = Image.open('assets/orange.jpg')
elif index == 4:
original = Image.open('assets/apple.jpg')
elif index == 5:
original = Image.open('assets/watermellon.jpg')
elif index == 6:
original = Image.open('assets/apple.jpg')
elif index == 7:
original = Image.open('assets/watermellon.jpg')
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 20)
image.paste(original, box=(xcoords[index],ycoords[index]))
draw.text((xcoords[index]+constants.orange_width/2,ycoords[index]+constants.orange_width/2),str(index+1),fill=(0,0,0), font=font)
def boundBoxNoNoise7(x,y,index):
center = 25
objectType = None
if index == 0:
objectType = "orange"
if index == 1:
objectType = "apple"
if index == 2:
objectType = "watermellon"
if index == 3:
objectType = "orange"
if index == 4:
objectType = "apple"
if index == 5:
objectType = "watermellon"
elif index == 6:
objectType = "apple"
elif index == 7:
objectType = "watermellon"
return x+center, y+center, constants.orange_width - center*2, constants.orange_width - center*2.5,objectType
def boundBoxNoise7(x,y,index):
multiplier = 10
x,y,w,h,objectType = boundBoxNoNoise7(x,y,index)
arr = random.normal(size=(4,1))*multiplier
return x+arr[0], y+arr[1], w+arr[2], h+arr[3], objectType
commonExample.common_run(updateCoords,gif_file,xcoords,ycoords,boundBoxNoise=boundBoxNoise7,boundBoxNoNoise=boundBoxNoNoise7,drawImage=drawImage7,saveData=True)
| true | true |
f72f3f9773cb57978179d7d03d2f532c34dbe335 | 869 | py | Python | setup.py | ngoet/markdowndocs | 8154276bd943c8a641d1c5ef6e3aa07395beee1c | [
"MIT"
] | null | null | null | setup.py | ngoet/markdowndocs | 8154276bd943c8a641d1c5ef6e3aa07395beee1c | [
"MIT"
] | null | null | null | setup.py | ngoet/markdowndocs | 8154276bd943c8a641d1c5ef6e3aa07395beee1c | [
"MIT"
] | null | null | null | from setuptools import find_packages, setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="markdowndocs",
version="0.1.0",
author="ngoet",
author_email="ndgoet@gmail.com",
description="A light-weight markdown code documentation generator",
install_requires=[
"tabulate>=0.8.7",
"pandas>=1.1.2",
"typer>=0.3.2",
],
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/ngoet/MarkdownDocs",
packages=find_packages(exclude=["tests"]),
entry_points={"console_scripts": ["markdowndocs = markdowndocs.cli:main"]},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
include_package_data=True,
)
| 29.965517 | 79 | 0.650173 | from setuptools import find_packages, setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="markdowndocs",
version="0.1.0",
author="ngoet",
author_email="ndgoet@gmail.com",
description="A light-weight markdown code documentation generator",
install_requires=[
"tabulate>=0.8.7",
"pandas>=1.1.2",
"typer>=0.3.2",
],
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/ngoet/MarkdownDocs",
packages=find_packages(exclude=["tests"]),
entry_points={"console_scripts": ["markdowndocs = markdowndocs.cli:main"]},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
include_package_data=True,
)
| true | true |
f72f3f991d29cfcde8c404665347a2b2067bd01a | 3,145 | py | Python | tests/test_game_map.py | brittleshinpass/mossbread | 6a225e5d11fdf1957d1bfe74c5a76d105561e12e | [
"MIT"
] | 1 | 2020-05-30T19:45:58.000Z | 2020-05-30T19:45:58.000Z | tests/test_game_map.py | brittleshinpass/mossbread | 6a225e5d11fdf1957d1bfe74c5a76d105561e12e | [
"MIT"
] | null | null | null | tests/test_game_map.py | brittleshinpass/mossbread | 6a225e5d11fdf1957d1bfe74c5a76d105561e12e | [
"MIT"
] | null | null | null | import pytest
from array import array
from game_map import GameMap
from tests.conftest import get_relative_path
sample_map_data = tuple(
reversed(
(
array("I", (0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0)),
array("I", (0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0)),
array("I", (1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1)),
array("I", (1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1)),
array("I", (1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)),
array("I", (1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1)),
array("I", (0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0)),
array("I", (0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0)),
)
)
)
def test_game_map_from_file(sample_game_map, sample_tiles):
assert sample_game_map.map_data == sample_map_data
assert sample_game_map.width == 21
assert sample_game_map.height == 21
assert sample_game_map.tile_data == sample_tiles
# Assert map is read right-up
assert sample_game_map.get(16, 2) == 0
assert sample_game_map.get(16, 18) == 1
def test_game_map_get_out_of_bounds(sample_game_map):
with pytest.raises(AssertionError):
sample_game_map.get(-1, 0)
sample_game_map.get(0, -1)
sample_game_map.get(-1, -1)
sample_game_map.get(21, 0)
sample_game_map.get(0, 21)
sample_game_map.get(21, 21)
def test_game_map_load_mapfile_nonrectangular():
with pytest.raises(AssertionError):
GameMap.load_mapfile(get_relative_path("fixtures/map_nonrectangular.csv"))
def test_game_map_traversable(sample_game_map):
assert sample_game_map.traversable(2, 2)
assert not sample_game_map.traversable(1, 1)
assert sample_game_map.traversable(16, 2)
assert not sample_game_map.traversable(16, 18)
| 46.25 | 88 | 0.475994 | import pytest
from array import array
from game_map import GameMap
from tests.conftest import get_relative_path
sample_map_data = tuple(
reversed(
(
array("I", (0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0)),
array("I", (0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0)),
array("I", (1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1)),
array("I", (1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1)),
array("I", (1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)),
array("I", (1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)),
array("I", (1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1)),
array("I", (0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0)),
array("I", (0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0)),
)
)
)
def test_game_map_from_file(sample_game_map, sample_tiles):
assert sample_game_map.map_data == sample_map_data
assert sample_game_map.width == 21
assert sample_game_map.height == 21
assert sample_game_map.tile_data == sample_tiles
assert sample_game_map.get(16, 2) == 0
assert sample_game_map.get(16, 18) == 1
def test_game_map_get_out_of_bounds(sample_game_map):
with pytest.raises(AssertionError):
sample_game_map.get(-1, 0)
sample_game_map.get(0, -1)
sample_game_map.get(-1, -1)
sample_game_map.get(21, 0)
sample_game_map.get(0, 21)
sample_game_map.get(21, 21)
def test_game_map_load_mapfile_nonrectangular():
with pytest.raises(AssertionError):
GameMap.load_mapfile(get_relative_path("fixtures/map_nonrectangular.csv"))
def test_game_map_traversable(sample_game_map):
assert sample_game_map.traversable(2, 2)
assert not sample_game_map.traversable(1, 1)
assert sample_game_map.traversable(16, 2)
assert not sample_game_map.traversable(16, 18)
| true | true |
f72f3fcfa3fab2976c56d4dd80f662765c94c4d1 | 700 | py | Python | src/owmpy/utils/_classes.py | ernieIzde8ski/open_weather_mappy | c50629065de85f6d2f4fcf46b741ff3320182a55 | [
"MIT"
] | null | null | null | src/owmpy/utils/_classes.py | ernieIzde8ski/open_weather_mappy | c50629065de85f6d2f4fcf46b741ff3320182a55 | [
"MIT"
] | null | null | null | src/owmpy/utils/_classes.py | ernieIzde8ski/open_weather_mappy | c50629065de85f6d2f4fcf46b741ff3320182a55 | [
"MIT"
] | null | null | null | from typing import NamedTuple
import aiohttp as _aiohttp
Number = int | float
class ShortLong(NamedTuple):
"""Represents shorthand and longhand of a unit."""
short: str
"""Shorthand form, eg '°C'"""
long: str
"""Longhandform, eg 'Celsius'"""
class _AutomaticClient:
client: _aiohttp.ClientSession
appid: str | None
def __init__(self, client: _aiohttp.ClientSession | None = None, appid: str | None = None) -> None:
self.client = client or _aiohttp.ClientSession()
self.appid = appid or None
async def __aenter__(self, *args):
return self
async def __aexit__(self, *args):
await self.client.close()
return self
| 22.580645 | 103 | 0.651429 | from typing import NamedTuple
import aiohttp as _aiohttp
Number = int | float
class ShortLong(NamedTuple):
short: str
long: str
class _AutomaticClient:
client: _aiohttp.ClientSession
appid: str | None
def __init__(self, client: _aiohttp.ClientSession | None = None, appid: str | None = None) -> None:
self.client = client or _aiohttp.ClientSession()
self.appid = appid or None
async def __aenter__(self, *args):
return self
async def __aexit__(self, *args):
await self.client.close()
return self
| true | true |
f72f409ee17d5e96bd756971f13976c6028fd85e | 6,212 | py | Python | models/00_db.py | samsruti/eden | 8f6bdd070fa8435dafea6e8fb65db246280bb3ea | [
"MIT"
] | null | null | null | models/00_db.py | samsruti/eden | 8f6bdd070fa8435dafea6e8fb65db246280bb3ea | [
"MIT"
] | null | null | null | models/00_db.py | samsruti/eden | 8f6bdd070fa8435dafea6e8fb65db246280bb3ea | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Import Modules
Configure the Database
Instantiate Classes
"""
if settings.get_L10n_languages_readonly():
# Make the Language files read-only for improved performance
T.is_writable = False
get_vars = request.get_vars
# Are we running in debug mode?
settings.check_debug()
import datetime
try:
import json # try stdlib (Python 2.6)
except ImportError:
try:
import simplejson as json # try external module
except:
import gluon.contrib.simplejson as json # fallback to pure-Python module
########################
# Database Configuration
########################
migrate = settings.get_base_migrate()
fake_migrate = settings.get_base_fake_migrate()
if migrate:
check_reserved = ["mysql", "postgres"]
else:
check_reserved = None
(db_string, pool_size) = settings.get_database_string()
if db_string.find("sqlite") != -1:
db = DAL(db_string,
check_reserved=check_reserved,
migrate_enabled = migrate,
fake_migrate_all = fake_migrate,
lazy_tables = not migrate)
# on SQLite 3.6.19+ this enables foreign key support (included in Python 2.7+)
# db.executesql("PRAGMA foreign_keys=ON")
else:
try:
if db_string.find("mysql") != -1:
# Use MySQLdb where available (pymysql has given broken pipes)
# - done automatically now, no need to add this manually
#try:
# import MySQLdb
# from gluon.dal import MySQLAdapter
# MySQLAdapter.driver = MySQLdb
#except ImportError:
# # Fallback to pymysql
# pass
if check_reserved:
check_reserved = ["postgres"]
db = DAL(db_string,
check_reserved = check_reserved,
pool_size = pool_size,
migrate_enabled = migrate,
lazy_tables = not migrate)
else:
# PostgreSQL
if check_reserved:
check_reserved = ["mysql"]
db = DAL(db_string,
check_reserved = check_reserved,
pool_size = pool_size,
migrate_enabled = migrate,
lazy_tables = not migrate)
except:
db_type = db_string.split(":", 1)[0]
db_location = db_string.split("@", 1)[1]
raise(HTTP(503, "Cannot connect to %s Database: %s" % (db_type, db_location)))
current.db = db
db.set_folder("upload")
# Sessions Storage
if settings.get_base_session_memcache():
# Store sessions in Memcache
from gluon.contrib.memcache import MemcacheClient
cache.memcache = MemcacheClient(request,
[settings.get_base_session_memcache()])
from gluon.contrib.memdb import MEMDB
session.connect(request, response, db=MEMDB(cache.memcache))
####################################################################
# Instantiate Classes from Modules #
# - store instances in current to be accessible from other modules #
####################################################################
from gluon.tools import Mail
mail = Mail()
current.mail = mail
from gluon.storage import Messages
messages = Messages(T)
current.messages = messages
ERROR = Messages(T)
current.ERROR = ERROR
# Import the S3 Framework
if update_check_needed:
# Reload the Field definitions
reload(s3base.s3fields)
else:
import s3 as s3base
# Set up logger (before any module attempts to use it!)
import s3log
s3log.S3Log.setup()
# AAA
current.auth = auth = s3base.AuthS3()
# Use session for persistent per-user variables
# - beware of a user having multiple tabs open!
# - don't save callables or class instances as these can't be pickled
if not session.s3:
session.s3 = Storage()
# Use username instead of email address for logins
# - would probably require further customisation
# to get this fully-working within Eden as it's not a Tested configuration
#auth.settings.login_userfield = "username"
auth.settings.hmac_key = settings.get_auth_hmac_key()
auth.define_tables(migrate=migrate, fake_migrate=fake_migrate)
current.audit = audit = s3base.S3Audit(migrate=migrate, fake_migrate=fake_migrate)
# Shortcuts for models/controllers/views
s3_has_role = auth.s3_has_role
s3_has_permission = auth.s3_has_permission
s3_logged_in_person = auth.s3_logged_in_person
# CRUD
s3.crud = Storage()
# S3 Custom Validators and Widgets, imported here into the global
# namespace in order to access them without the s3base namespace prefix
s3_action_buttons = s3base.S3CRUD.action_buttons
s3_fullname = s3base.s3_fullname
S3ResourceHeader = s3base.S3ResourceHeader
from s3.s3navigation import s3_rheader_tabs
from s3.s3validators import *
from s3.s3widgets import *
from s3.s3data import *
# GIS Module
gis = s3base.GIS()
current.gis = gis
# s3_request
s3_request = s3base.s3_request
# Field Selectors
FS = s3base.FS
# S3XML
s3xml = s3base.S3XML()
current.xml = s3xml
# Messaging
msg = s3base.S3Msg()
current.msg = msg
# Sync
sync = s3base.S3Sync()
current.sync = sync
# -----------------------------------------------------------------------------
def s3_clear_session():
# CRUD last opened records (rcvars)
s3base.s3_remove_last_record_id()
# Session-owned records
if "owned_records" in session:
del session["owned_records"]
if "s3" in session:
s3 = session.s3
opts = ["hrm", "report_options", "utc_offset", "deduplicate"]
for o in opts:
if o in s3:
del s3[o]
# -----------------------------------------------------------------------------
def s3_auth_on_login(form):
"""
Actions to be performed upon successful login
Do not redirect from here!
"""
s3_clear_session()
# -----------------------------------------------------------------------------
def s3_auth_on_logout(user):
"""
Actions to be performed after logout
Do not redirect from here!
"""
s3_clear_session()
# END =========================================================================
| 29.028037 | 86 | 0.609627 |
if settings.get_L10n_languages_readonly():
T.is_writable = False
get_vars = request.get_vars
settings.check_debug()
import datetime
try:
import json
except ImportError:
try:
import simplejson as json
except:
import gluon.contrib.simplejson as json
if check_reserved:
check_reserved = ["postgres"]
db = DAL(db_string,
check_reserved = check_reserved,
pool_size = pool_size,
migrate_enabled = migrate,
lazy_tables = not migrate)
else:
if check_reserved:
check_reserved = ["mysql"]
db = DAL(db_string,
check_reserved = check_reserved,
pool_size = pool_size,
migrate_enabled = migrate,
lazy_tables = not migrate)
except:
db_type = db_string.split(":", 1)[0]
db_location = db_string.split("@", 1)[1]
raise(HTTP(503, "Cannot connect to %s Database: %s" % (db_type, db_location)))
current.db = db
db.set_folder("upload")
if settings.get_base_session_memcache():
from gluon.contrib.memcache import MemcacheClient
cache.memcache = MemcacheClient(request,
[settings.get_base_session_memcache()])
from gluon.contrib.memdb import MEMDB
session.connect(request, response, db=MEMDB(cache.memcache))
| true | true |
f72f40b797e835bc5608be07f220c5da9a9c3a64 | 37,904 | py | Python | LAD-AMA-Common/telegraf_utils/telegraf_config_handler.py | shridpant/azure-linux-extensions | 4b5e66f33d5b93b15b427a9438931f0414f12a6e | [
"Apache-2.0"
] | null | null | null | LAD-AMA-Common/telegraf_utils/telegraf_config_handler.py | shridpant/azure-linux-extensions | 4b5e66f33d5b93b15b427a9438931f0414f12a6e | [
"Apache-2.0"
] | null | null | null | LAD-AMA-Common/telegraf_utils/telegraf_config_handler.py | shridpant/azure-linux-extensions | 4b5e66f33d5b93b15b427a9438931f0414f12a6e | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
#
# Azure Linux extension
#
# Copyright (c) Microsoft Corporation
# All rights reserved.
# MIT License
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
# Software.
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# future imports have no effect on python 3 (verified in official docs)
# importing from source causes import errors on python 3, lets skip import
import sys
if sys.version_info[0] < 3:
from future import standard_library
standard_library.install_aliases()
from builtins import str
import json
import os
from telegraf_utils.telegraf_name_map import name_map
import subprocess
import signal
import urllib.request, urllib.error, urllib.parse
from shutil import copyfile, rmtree
import time
import metrics_ext_utils.metrics_constants as metrics_constants
import metrics_ext_utils.metrics_common_utils as metrics_utils
"""
Sample input data received by this script
[
{
"displayName" : "Network->Packets sent",
"interval" : "15s",
"sink" : ["mdsd" , "me"]
},
{
"displayName" : "Network->Packets recieved",
"interval" : "15s",
"sink" : ["mdsd" , "me"]
}
]
"""
def parse_config(data, me_url, mdsd_url, is_lad, az_resource_id, subscription_id, resource_group, region, virtual_machine_name):
"""
Main parser method to convert Metrics config from extension configuration to telegraf configuration
:param data: Parsed Metrics Configuration from which telegraf config is created
:param me_url: The url to which telegraf will send metrics to for MetricsExtension
:param mdsd_url: The url to which telegraf will send metrics to for MDSD
:param is_lad: Boolean value for whether the extension is Lad or not (AMA)
:param az_resource_id: Azure Resource ID value for the VM
:param subscription_id: Azure Subscription ID value for the VM
:param resource_group: Azure Resource Group value for the VM
:param region: Azure Region value for the VM
:param virtual_machine_name: Azure Virtual Machine Name value (Only in the case for VMSS) for the VM
"""
storage_namepass_list = []
storage_namepass_str = ""
vmi_rate_counters_list = ["LogicalDisk\\BytesPerSecond", "LogicalDisk\\ReadBytesPerSecond", "LogicalDisk\\ReadsPerSecond", "LogicalDisk\\WriteBytesPerSecond", "LogicalDisk\\WritesPerSecond", "LogicalDisk\\TransfersPerSecond", "Network\\ReadBytesPerSecond", "Network\\WriteBytesPerSecond"]
MetricsExtensionNamepsace = metrics_constants.metrics_extension_namespace
has_mdsd_output = False
if len(data) == 0:
raise Exception("Empty config data received.")
if me_url is None or mdsd_url is None:
raise Exception("No url provided for Influxdb output plugin to ME, AMA.")
telegraf_json = {}
for item in data:
sink = item["sink"]
if "mdsd" in sink:
has_mdsd_output = True
counter = item["displayName"]
if counter in name_map:
plugin = name_map[counter]["plugin"]
omiclass = ""
if is_lad:
omiclass = counter.split("->")[0]
else:
omiclass = name_map[counter]["module"]
if omiclass not in telegraf_json:
telegraf_json[omiclass] = {}
if plugin not in telegraf_json[omiclass]:
telegraf_json[omiclass][plugin] = {}
telegraf_json[omiclass][plugin][name_map[counter]["field"]] = {}
if is_lad:
telegraf_json[omiclass][plugin][name_map[counter]["field"]]["displayName"] = counter.split("->")[1]
else:
telegraf_json[omiclass][plugin][name_map[counter]["field"]]["displayName"] = counter
telegraf_json[omiclass][plugin][name_map[counter]["field"]]["interval"] = item["interval"]
if is_lad:
telegraf_json[omiclass][plugin][name_map[counter]["field"]]["ladtablekey"] = name_map[counter]["ladtablekey"]
if "op" in name_map[counter]:
telegraf_json[omiclass][plugin][name_map[counter]["field"]]["op"] = name_map[counter]["op"]
"""
Sample converted telegraf conf dict -
"network": {
"net": {
"bytes_total": {"interval": "15s","displayName": "Network total bytes","ladtablekey": "/builtin/network/bytestotal"},
"drop_total": {"interval": "15s","displayName": "Network collisions","ladtablekey": "/builtin/network/totalcollisions"},
"err_in": {"interval": "15s","displayName": "Packets received errors","ladtablekey": "/builtin/network/totalrxerrors"},
"packets_sent": {"interval": "15s","displayName": "Packets sent","ladtablekey": "/builtin/network/packetstransmitted"},
}
},
"filesystem": {
"disk": {
"used_percent": {"interval": "15s","displayName": "Filesystem % used space","ladtablekey": "/builtin/filesystem/percentusedspace"},
"used": {"interval": "15s","displayName": "Filesystem used space","ladtablekey": "/builtin/filesystem/usedspace"},
"free": {"interval": "15s","displayName": "Filesystem free space","ladtablekey": "/builtin/filesystem/freespace"},
"inodes_free_percent": {"interval": "15s","displayName": "Filesystem % free inodes","ladtablekey": "/builtin/filesystem/percentfreeinodes"},
},
"diskio": {
"writes_filesystem": {"interval": "15s","displayName": "Filesystem writes/sec","ladtablekey": "/builtin/filesystem/writespersecond","op": "rate"},
"total_transfers_filesystem": {"interval": "15s","displayName": "Filesystem transfers/sec","ladtablekey": "/builtin/filesystem/transferspersecond","op": "rate"},
"reads_filesystem": {"interval": "15s","displayName": "Filesystem reads/sec","ladtablekey": "/builtin/filesystem/readspersecond","op": "rate"},
}
},
"""
if len(telegraf_json) == 0:
raise Exception("Unable to parse telegraf config into intermediate dictionary.")
excess_diskio_plugin_list_lad = ["total_transfers_filesystem", "read_bytes_filesystem", "total_bytes_filesystem", "write_bytes_filesystem", "reads_filesystem", "writes_filesystem"]
excess_diskio_field_drop_list_str = ""
int_file = {"filename":"intermediate.json", "data": json.dumps(telegraf_json)}
output = []
output.append(int_file)
for omiclass in telegraf_json:
input_str = ""
ama_rename_str = ""
metricsext_rename_str = ""
lad_specific_rename_str = ""
rate_specific_aggregator_str = ""
aggregator_str = ""
for plugin in telegraf_json[omiclass]:
config_file = {"filename" : omiclass+".conf"}
# Arbitrary max value for finding min
min_interval = "999999999s"
is_vmi = plugin.endswith("_vmi")
is_vmi_rate_counter = False
for field in telegraf_json[omiclass][plugin]:
if not is_vmi_rate_counter:
is_vmi_rate_counter = telegraf_json[omiclass][plugin][field]["displayName"] in vmi_rate_counters_list
# if is_vmi_rate_counter:
# min_interval = "1s"
if is_vmi or is_vmi_rate_counter:
splitResult = plugin.split('_')
telegraf_plugin = splitResult[0]
input_str += "[[inputs." + telegraf_plugin + "]]\n"
# plugin = plugin[:-4]
else:
input_str += "[[inputs." + plugin + "]]\n"
# input_str += " "*2 + "name_override = \"" + omiclass + "\"\n"
# If it's a lad config then add the namepass fields for sending totals to storage
# always skip lad plugin names as they should be dropped from ME
lad_plugin_name = plugin + "_total"
if lad_plugin_name not in storage_namepass_list:
storage_namepass_list.append(lad_plugin_name)
if is_lad:
lad_specific_rename_str += "\n[[processors.rename]]\n"
lad_specific_rename_str += " "*2 + "namepass = [\"" + lad_plugin_name + "\"]\n"
elif is_vmi or is_vmi_rate_counter:
if plugin not in storage_namepass_list:
storage_namepass_list.append(plugin + "_mdsd")
else:
ama_plugin_name = plugin + "_mdsd_la_perf"
ama_rename_str += "\n[[processors.rename]]\n"
ama_rename_str += " "*2 + "namepass = [\"" + ama_plugin_name + "\"]\n"
if ama_plugin_name not in storage_namepass_list:
storage_namepass_list.append(ama_plugin_name)
namespace = MetricsExtensionNamepsace
if is_vmi or is_vmi_rate_counter:
namespace = "insights.virtualmachine"
if is_vmi_rate_counter:
# Adding "_rated" as a substring for vmi rate metrics to avoid renaming collisions
plugin_name = plugin + "_rated"
else:
plugin_name = plugin
metricsext_rename_str += "\n[[processors.rename]]\n"
metricsext_rename_str += " "*2 + "namepass = [\"" + plugin_name + "\"]\n"
metricsext_rename_str += "\n" + " "*2 + "[[processors.rename.replace]]\n"
metricsext_rename_str += " "*4 + "measurement = \"" + plugin_name + "\"\n"
metricsext_rename_str += " "*4 + "dest = \"" + namespace + "\"\n"
fields = ""
ops_fields = ""
non_ops_fields = ""
non_rate_aggregate = False
ops = ""
min_agg_period = ""
rate_aggregate = False
for field in telegraf_json[omiclass][plugin]:
fields += "\"" + field + "\", "
if is_vmi or is_vmi_rate_counter :
if "MB" in field:
fields += "\"" + field.replace('MB','Bytes') + "\", "
#Use the shortest interval time for the whole plugin
new_interval = telegraf_json[omiclass][plugin][field]["interval"]
if int(new_interval[:-1]) < int(min_interval[:-1]):
min_interval = new_interval
#compute values for aggregator options
if "op" in telegraf_json[omiclass][plugin][field]:
if telegraf_json[omiclass][plugin][field]["op"] == "rate":
rate_aggregate = True
ops = "\"rate\", \"rate_min\", \"rate_max\", \"rate_count\", \"rate_sum\", \"rate_mean\""
if is_lad:
ops_fields += "\"" + telegraf_json[omiclass][plugin][field]["ladtablekey"] + "\", "
else:
ops_fields += "\"" + telegraf_json[omiclass][plugin][field]["displayName"] + "\", "
else:
non_rate_aggregate = True
if is_lad:
non_ops_fields += "\"" + telegraf_json[omiclass][plugin][field]["ladtablekey"] + "\", "
else:
non_ops_fields += "\"" + telegraf_json[omiclass][plugin][field]["displayName"] + "\", "
# #Aggregation perdiod needs to be double of interval/polling period for metrics for rate aggegation to work properly
# This is only for metrics going to MDSD. for VMI metrics aggregation,
# the requirement is to have ALL the metrics at 60 seconds and that is handled later by sourcing the VMI metrics that need to be aggregated at 30 seconds
if int(min_interval[:-1]) > 30:
min_agg_period = str(int(min_interval[:-1])*2) #if the min interval is greater than 30, use the double value
else:
min_agg_period = "60" #else use 60 as mininum so that we can maintain 1 event per minute
#Add respective rename processor plugin based on the displayname
if is_lad:
lad_specific_rename_str += "\n" + " "*2 + "[[processors.rename.replace]]\n"
lad_specific_rename_str += " "*4 + "field = \"" + field + "\"\n"
lad_specific_rename_str += " "*4 + "dest = \"" + telegraf_json[omiclass][plugin][field]["ladtablekey"] + "\"\n"
elif not is_vmi and not is_vmi_rate_counter:
# no rename of fields as they are set in telegraf directly
ama_rename_str += "\n" + " "*2 + "[[processors.rename.replace]]\n"
ama_rename_str += " "*4 + "field = \"" + field + "\"\n"
ama_rename_str += " "*4 + "dest = \"" + telegraf_json[omiclass][plugin][field]["displayName"] + "\"\n"
# Avoid adding the rename logic for the redundant *_filesystem fields for diskio which were added specifically for OMI parity in LAD
# Had to re-use these six fields to avoid renaming issues since both Filesystem and Disk in OMI-LAD use them
# AMA only uses them once so only need this for LAD
if is_lad:
if field in excess_diskio_plugin_list_lad:
excess_diskio_field_drop_list_str += "\"" + field + "\", "
else:
metricsext_rename_str += "\n" + " "*2 + "[[processors.rename.replace]]\n"
metricsext_rename_str += " "*4 + "field = \"" + field + "\"\n"
metricsext_rename_str += " "*4 + "dest = \"" + plugin + "/" + field + "\"\n"
elif not is_vmi and not is_vmi_rate_counter:
# no rename of fields as they are set in telegraf directly
metricsext_rename_str += "\n" + " "*2 + "[[processors.rename.replace]]\n"
metricsext_rename_str += " "*4 + "field = \"" + field + "\"\n"
metricsext_rename_str += " "*4 + "dest = \"" + plugin + "/" + field + "\"\n"
#Add respective operations for aggregators
# if is_lad:
if not is_vmi and not is_vmi_rate_counter:
suffix = ""
if is_lad:
suffix = "_total\"]\n"
else:
suffix = "_mdsd_la_perf\"]\n"
if rate_aggregate:
aggregator_str += "[[aggregators.basicstats]]\n"
aggregator_str += " "*2 + "namepass = [\"" + plugin + suffix
aggregator_str += " "*2 + "period = \"" + min_agg_period + "s\"\n"
aggregator_str += " "*2 + "drop_original = true\n"
aggregator_str += " "*2 + "fieldpass = [" + ops_fields[:-2] + "]\n" #-2 to strip the last comma and space
aggregator_str += " "*2 + "stats = [" + ops + "]\n"
if non_rate_aggregate:
aggregator_str += "[[aggregators.basicstats]]\n"
aggregator_str += " "*2 + "namepass = [\"" + plugin + suffix
aggregator_str += " "*2 + "period = \"" + min_agg_period + "s\"\n"
aggregator_str += " "*2 + "drop_original = true\n"
aggregator_str += " "*2 + "fieldpass = [" + non_ops_fields[:-2] + "]\n" #-2 to strip the last comma and space
aggregator_str += " "*2 + "stats = [\"mean\", \"max\", \"min\", \"sum\", \"count\"]\n\n"
elif is_vmi_rate_counter:
# Aggregator config for MDSD
aggregator_str += "[[aggregators.basicstats]]\n"
aggregator_str += " "*2 + "namepass = [\"" + plugin + "_mdsd\"]\n"
aggregator_str += " "*2 + "period = \"" + min_interval + "\"\n"
aggregator_str += " "*2 + "drop_original = true\n"
aggregator_str += " "*2 + "fieldpass = [" + ops_fields[:-2].replace('\\','\\\\\\\\') + "]\n" #-2 to strip the last comma and space
aggregator_str += " "*2 + "stats = [" + ops + "]\n\n"
# Aggregator config for ME
aggregator_str += "[[aggregators.mdmratemetrics]]\n"
aggregator_str += " "*2 + "namepass = [\"" + plugin + "\"]\n"
aggregator_str += " "*2 + "period = \"" + min_interval + "\"\n"
aggregator_str += " "*2 + "drop_original = true\n"
aggregator_str += " "*2 + "fieldpass = [" + ops_fields[:-2].replace('\\','\\\\\\\\') + "]\n" #-2 to strip the last comma and space
aggregator_str += " "*2 + "stats = [\"rate\"]\n\n"
if is_lad:
lad_specific_rename_str += "\n"
elif not is_vmi and not is_vmi_rate_counter:
# no rename of fields as they are set in telegraf directly
ama_rename_str += "\n"
# Using fields[: -2] here to get rid of the last ", " at the end of the string
input_str += " "*2 + "fieldpass = ["+fields[:-2]+"]\n"
if plugin == "cpu":
input_str += " "*2 + "report_active = true\n"
if is_vmi_rate_counter:
# Rate interval needs to be atleast twice the regular sourcing interval for aggregation to work.
# Since we want all the VMI metrics to be sent at the same interval as selected by the customer, To overcome the twice the min internval limitation,
# We are sourcing the VMI metrics that need to be aggregated at half the selected frequency
rated_min_interval = str(int(min_interval[:-1]) // 2) + "s"
input_str += " "*2 + "interval = " + "\"" + rated_min_interval + "\"\n\n"
else:
input_str += " "*2 + "interval = " + "\"" + min_interval + "\"\n\n"
config_file["data"] = input_str + "\n" + metricsext_rename_str + "\n" + ama_rename_str + "\n" + lad_specific_rename_str + "\n" +aggregator_str
output.append(config_file)
config_file = {}
"""
Sample telegraf TOML file output
[[inputs.net]]
fieldpass = ["err_out", "packets_sent", "err_in", "bytes_sent", "packets_recv"]
interval = "5s"
[[inputs.cpu]]
fieldpass = ["usage_nice", "usage_user", "usage_idle", "usage_active", "usage_irq", "usage_system"]
interval = "15s"
[[processors.rename]]
[[processors.rename.replace]]
measurement = "net"
dest = "network"
[[processors.rename.replace]]
field = "err_out"
dest = "Packets sent errors"
[[aggregators.basicstats]]
period = "30s"
drop_original = false
fieldpass = ["Disk reads", "Disk writes", "Filesystem write bytes/sec"]
stats = ["rate"]
"""
## Get the log folder directory from HandlerEnvironment.json and use that for the telegraf default logging
logFolder, _ = get_handler_vars()
for measurement in storage_namepass_list:
storage_namepass_str += "\"" + measurement + "\", "
# Telegraf basic agent and output config
agentconf = "[agent]\n"
agentconf += " interval = \"10s\"\n"
agentconf += " round_interval = true\n"
agentconf += " metric_batch_size = 1000\n"
agentconf += " metric_buffer_limit = 1000000\n"
agentconf += " collection_jitter = \"0s\"\n"
agentconf += " flush_interval = \"10s\"\n"
agentconf += " flush_jitter = \"0s\"\n"
agentconf += " logtarget = \"file\"\n"
agentconf += " quiet = true\n"
agentconf += " logfile = \"" + logFolder + "/telegraf.log\"\n"
agentconf += " logfile_rotation_max_size = \"100MB\"\n"
agentconf += " logfile_rotation_max_archives = 5\n"
agentconf += "\n# Configuration for adding gloabl tags\n"
agentconf += "[global_tags]\n"
if is_lad:
agentconf += " DeploymentId= \"${DeploymentId}\"\n"
agentconf += " \"microsoft.subscriptionId\"= \"" + subscription_id + "\"\n"
agentconf += " \"microsoft.resourceGroupName\"= \"" + resource_group + "\"\n"
agentconf += " \"microsoft.regionName\"= \"" + region + "\"\n"
agentconf += " \"microsoft.resourceId\"= \"" + az_resource_id + "\"\n"
if virtual_machine_name != "":
agentconf += " \"VMInstanceId\"= \"" + virtual_machine_name + "\"\n"
agentconf += "\n# Configuration for sending metrics to MetricsExtension\n"
agentconf += "[[outputs.influxdb]]\n"
agentconf += " namedrop = [" + storage_namepass_str[:-2] + "]\n"
if is_lad:
agentconf += " fielddrop = [" + excess_diskio_field_drop_list_str[:-2] + "]\n"
agentconf += " urls = [\"" + str(me_url) + "\"]\n\n"
agentconf += " udp_payload = \"1024B\"\n\n"
if has_mdsd_output:
agentconf += "\n# Configuration for sending metrics to MDSD\n"
agentconf += "[[outputs.socket_writer]]\n"
agentconf += " namepass = [" + storage_namepass_str[:-2] + "]\n"
agentconf += " data_format = \"influx\"\n"
agentconf += " address = \"" + str(mdsd_url) + "\"\n\n"
agentconf += "\n# Configuration for outputing metrics to file. Uncomment to enable.\n"
agentconf += "#[[outputs.file]]\n"
agentconf += "# files = [\"./metrics_to_file.out\"]\n\n"
agent_file = {"filename":"telegraf.conf", "data": agentconf}
output.append(agent_file)
return output, storage_namepass_list
def write_configs(configs, telegraf_conf_dir, telegraf_d_conf_dir):
"""
Write the telegraf config created by config parser method to disk at the telegraf config location
:param configs: Telegraf config data parsed by the parse_config method above
:param telegraf_conf_dir: Path where the telegraf.conf is written to on the disk
:param telegraf_d_conf_dir: Path where the individual module telegraf configs are written to on the disk
"""
# Delete the older config folder to prevent telegraf from loading older configs
if os.path.exists(telegraf_conf_dir):
rmtree(telegraf_conf_dir)
os.mkdir(telegraf_conf_dir)
os.mkdir(telegraf_d_conf_dir)
for configfile in configs:
if configfile["filename"] == "telegraf.conf" or configfile["filename"] == "intermediate.json":
path = telegraf_conf_dir + configfile["filename"]
else:
path = telegraf_d_conf_dir + configfile["filename"]
with open(path, "w") as f:
f.write(configfile["data"])
def get_handler_vars():
"""
This method is taken from the Waagent code. This is used to grab the log and config file location from the json public setting for the Extension
"""
logFolder = ""
configFolder = ""
handler_env_path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'HandlerEnvironment.json'))
if os.path.exists(handler_env_path):
with open(handler_env_path, 'r') as handler_env_file:
handler_env_txt = handler_env_file.read()
handler_env = json.loads(handler_env_txt)
if type(handler_env) == list:
handler_env = handler_env[0]
if "handlerEnvironment" in handler_env:
if "logFolder" in handler_env["handlerEnvironment"]:
logFolder = handler_env["handlerEnvironment"]["logFolder"]
if "configFolder" in handler_env["handlerEnvironment"]:
configFolder = handler_env["handlerEnvironment"]["configFolder"]
return logFolder, configFolder
def is_running(is_lad):
"""
This method is used to check if telegraf binary is currently running on the system or not.
In order to check whether it needs to be restarted from the watcher daemon
"""
if is_lad:
telegraf_bin = metrics_constants.lad_telegraf_bin
else:
telegraf_bin = metrics_constants.ama_telegraf_bin
proc = subprocess.Popen(["ps aux | grep telegraf | grep -v grep"], stdout=subprocess.PIPE, shell=True)
output = proc.communicate()[0]
if telegraf_bin in output.decode('utf-8', 'ignore'):
return True
else:
return False
def stop_telegraf_service(is_lad):
"""
Stop the telegraf service if VM is using is systemd, otherwise check if the pid_file exists,
and if the pid belongs to the Telegraf process, if yes, then kill the process
This method is called before remove_telegraf_service by the main extension code
:param is_lad: boolean whether the extension is LAD or not (AMA)
"""
if is_lad:
telegraf_bin = metrics_constants.lad_telegraf_bin
else:
telegraf_bin = metrics_constants.ama_telegraf_bin
# If the VM has systemd, then we will use that to stop
if metrics_utils.is_systemd():
code = 1
telegraf_service_path = get_telegraf_service_path()
if os.path.isfile(telegraf_service_path):
code = os.system("sudo systemctl stop metrics-sourcer")
else:
return False, "Telegraf service file does not exist. Failed to stop telegraf service: metrics-sourcer.service."
if code != 0:
return False, "Unable to stop telegraf service: metrics-sourcer.service. Run systemctl status metrics-sourcer.service for more info."
# Whether or not VM has systemd, let's check if we have any telegraf pids saved and if so, terminate the associated process
_, configFolder = get_handler_vars()
telegraf_conf_dir = configFolder + "/telegraf_configs/"
telegraf_pid_path = telegraf_conf_dir + "telegraf_pid.txt"
if os.path.isfile(telegraf_pid_path):
with open(telegraf_pid_path, "r") as f:
for pid in f.readlines():
# Verify the pid actually belongs to telegraf
cmd_path = os.path.join("/proc", str(pid.strip("\n")), "cmdline")
if os.path.exists(cmd_path):
with open(cmd_path, "r") as cmd_f:
cmdline = cmd_f.readlines()
if cmdline[0].find(telegraf_bin) >= 0:
os.kill(int(pid), signal.SIGKILL)
os.remove(telegraf_pid_path)
elif not metrics_utils.is_systemd():
return False, "Could not find telegraf service nor process to stop."
return True, "Successfully stopped metrics-sourcer service"
def remove_telegraf_service():
"""
Remove the telegraf service if the VM is using systemd as well as the telegraf Binary
This method is called after stop_telegraf_service by the main extension code during Extension uninstall
:param is_lad: boolean whether the extension is LAD or not (AMA)
"""
telegraf_service_path = get_telegraf_service_path()
if os.path.isfile(telegraf_service_path):
os.remove(telegraf_service_path)
else:
return True, "Unable to remove the Telegraf service as the file doesn't exist."
# Checking To see if the file was successfully removed, since os.remove doesn't return an error code
if os.path.isfile(telegraf_service_path):
return False, "Unable to remove telegraf service: metrics-sourcer.service at {0}.".format(telegraf_service_path)
return True, "Successfully removed metrics-sourcer service"
def setup_telegraf_service(telegraf_bin, telegraf_d_conf_dir, telegraf_agent_conf):
"""
Add the metrics-sourcer service if the VM is using systemd
This method is called in handle_config
:param telegraf_bin: path to the telegraf binary
:param telegraf_d_conf_dir: path to telegraf .d conf subdirectory
:param telegraf_agent_conf: path to telegraf .conf file
"""
telegraf_service_path = get_telegraf_service_path()
telegraf_service_template_path = os.getcwd() + "/services/metrics-sourcer.service"
if not os.path.exists(telegraf_d_conf_dir):
raise Exception("Telegraf config directory does not exist. Failed to setup telegraf service.")
if not os.path.isfile(telegraf_agent_conf):
raise Exception("Telegraf agent config does not exist. Failed to setup telegraf service.")
if os.path.isfile(telegraf_service_template_path):
copyfile(telegraf_service_template_path, telegraf_service_path)
if os.path.isfile(telegraf_service_path):
os.system(r"sed -i 's+%TELEGRAF_BIN%+{1}+' {0}".format(telegraf_service_path, telegraf_bin))
os.system(r"sed -i 's+%TELEGRAF_AGENT_CONFIG%+{1}+' {0}".format(telegraf_service_path, telegraf_agent_conf))
os.system(r"sed -i 's+%TELEGRAF_CONFIG_DIR%+{1}+' {0}".format(telegraf_service_path, telegraf_d_conf_dir))
daemon_reload_status = os.system("sudo systemctl daemon-reload")
if daemon_reload_status != 0:
raise Exception("Unable to reload systemd after Telegraf service file change. Failed to setup telegraf service.")
else:
raise Exception("Unable to copy Telegraf service template file to {0}. Failed to setup telegraf service.".format(telegraf_service_path))
else:
raise Exception("Telegraf service template file does not exist at {0}. Failed to setup telegraf service.".format(telegraf_service_template_path))
return True
def start_telegraf(is_lad):
"""
Start the telegraf service if VM is using is systemd, otherwise start the binary as a process and store the pid
to a file in the telegraf config directory
This method is called after config setup is completed by the main extension code
:param is_lad: boolean whether the extension is LAD or not (AMA)
"""
# Re using the code to grab the config directories and imds values because start will be called from Enable process outside this script
log_messages = ""
if is_lad:
telegraf_bin = metrics_constants.lad_telegraf_bin
else:
telegraf_bin = metrics_constants.ama_telegraf_bin
if not os.path.isfile(telegraf_bin):
log_messages += "Telegraf binary does not exist. Failed to start telegraf service."
return False, log_messages
# Ensure that any old telegraf processes are cleaned up to avoid duplication
stop_telegraf_service(is_lad)
# If the VM has systemd, telegraf will be managed as a systemd service
if metrics_utils.is_systemd():
service_restart_status = os.system("sudo systemctl restart metrics-sourcer")
if service_restart_status != 0:
log_messages += "Unable to start Telegraf service. Failed to start telegraf service."
return False, log_messages
# Otherwise, start telegraf as a process and save the pid to a file so that we can terminate it while disabling/uninstalling
else:
_, configFolder = get_handler_vars()
telegraf_conf_dir = configFolder + "/telegraf_configs/"
telegraf_agent_conf = telegraf_conf_dir + "telegraf.conf"
telegraf_d_conf_dir = telegraf_conf_dir + "telegraf.d/"
telegraf_pid_path = telegraf_conf_dir + "telegraf_pid.txt"
binary_exec_command = "{0} --config {1} --config-directory {2}".format(telegraf_bin, telegraf_agent_conf, telegraf_d_conf_dir)
proc = subprocess.Popen(binary_exec_command.split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Sleeping for 3 seconds before checking if the process is still running, to give it ample time to relay crash info
time.sleep(3)
p = proc.poll()
# Process is running successfully
if p is None:
telegraf_pid = proc.pid
# Write this pid to a file for future use
try:
with open(telegraf_pid_path, "a") as f:
f.write(str(telegraf_pid) + '\n')
except Exception as e:
log_messages += "Successfully started telegraf binary, but could not save telegraf pidfile."
else:
out, err = proc.communicate()
log_messages += "Unable to run telegraf binary as a process due to error - {0}. Failed to start telegraf.".format(err)
return False, log_messages
return True, log_messages
def get_telegraf_service_path():
"""
Utility method to get the service path in case /lib/systemd/system doesnt exist on the OS
"""
if os.path.exists("/lib/systemd/system/"):
return metrics_constants.telegraf_service_path
elif os.path.exists("/usr/lib/systemd/system/"):
return metrics_constants.telegraf_service_path_usr_lib
else:
raise Exception("Systemd unit files do not exist at /lib/systemd/system or /usr/lib/systemd/system/. Failed to setup telegraf service.")
def handle_config(config_data, me_url, mdsd_url, is_lad):
"""
The main method to perfom the task of parsing the config , writing them to disk, setting up, stopping, removing and starting telegraf
:param config_data: Parsed Metrics Configuration from which telegraf config is created
:param me_url: The url to which telegraf will send metrics to for MetricsExtension
:param mdsd_url: The url to which telegraf will send metrics to for MDSD
:param is_lad: Boolean value for whether the extension is Lad or not (AMA)
"""
# Making the imds call to get resource id, sub id, resource group and region for the dimensions for telegraf metrics
retries = 1
max_retries = 3
sleep_time = 5
imdsurl = ""
is_arc = False
if is_lad:
imdsurl = "http://169.254.169.254/metadata/instance?api-version=2019-03-11"
else:
if metrics_utils.is_arc_installed():
imdsurl = metrics_utils.get_arc_endpoint()
imdsurl += "/metadata/instance?api-version=2019-11-01"
is_arc = True
else:
imdsurl = "http://169.254.169.254/metadata/instance?api-version=2019-03-11"
data = None
while retries <= max_retries:
req = urllib.request.Request(imdsurl, headers={'Metadata':'true'})
res = urllib.request.urlopen(req)
data = json.loads(res.read().decode('utf-8', 'ignore'))
if "compute" not in data:
retries += 1
else:
break
time.sleep(sleep_time)
if retries > max_retries:
raise Exception("Unable to find 'compute' key in imds query response. Reached max retry limit of - {0} times. Failed to setup Telegraf.".format(max_retries))
if "resourceId" not in data["compute"]:
raise Exception("Unable to find 'resourceId' key in imds query response. Failed to setup Telegraf.")
az_resource_id = data["compute"]["resourceId"]
# If the instance is VMSS then trim the last two values from the resource id ie - "/virtualMachines/0"
# Since ME expects the resource id in a particular format. For egs -
# IMDS returned ID - /subscriptions/<sub-id>/resourceGroups/<rg_name>/providers/Microsoft.Compute/virtualMachineScaleSets/<VMSSName>/virtualMachines/0
# ME expected ID- /subscriptions/<sub-id>/resourceGroups/<rg_name>/providers/Microsoft.Compute/virtualMachineScaleSets/<VMSSName>
if "virtualMachineScaleSets" in az_resource_id:
az_resource_id = "/".join(az_resource_id.split("/")[:-2])
if "subscriptionId" not in data["compute"]:
raise Exception("Unable to find 'subscriptionId' key in imds query response. Failed to setup Telegraf.")
subscription_id = data["compute"]["subscriptionId"]
if "resourceGroupName" not in data["compute"]:
raise Exception("Unable to find 'resourceGroupName' key in imds query response. Failed to setup Telegraf.")
resource_group = data["compute"]["resourceGroupName"]
if "location" not in data["compute"]:
raise Exception("Unable to find 'location' key in imds query response. Failed to setup Telegraf.")
region = data["compute"]["location"]
virtual_machine_name = ""
if "vmScaleSetName" in data["compute"] and data["compute"]["vmScaleSetName"] != "":
virtual_machine_name = data["compute"]["name"]
#call the method to first parse the configs
output, namespaces = parse_config(config_data, me_url, mdsd_url, is_lad, az_resource_id, subscription_id, resource_group, region, virtual_machine_name)
_, configFolder = get_handler_vars()
if is_lad:
telegraf_bin = metrics_constants.lad_telegraf_bin
else:
telegraf_bin = metrics_constants.ama_telegraf_bin
telegraf_conf_dir = configFolder + "/telegraf_configs/"
telegraf_agent_conf = telegraf_conf_dir + "telegraf.conf"
telegraf_d_conf_dir = telegraf_conf_dir + "telegraf.d/"
#call the method to write the configs
write_configs(output, telegraf_conf_dir, telegraf_d_conf_dir)
# Setup Telegraf service.
# If the VM has systemd, then we will copy over the systemd unit file and use that to start/stop
if metrics_utils.is_systemd():
telegraf_service_setup = setup_telegraf_service(telegraf_bin, telegraf_d_conf_dir, telegraf_agent_conf)
if not telegraf_service_setup:
return False, []
return True, namespaces
| 48.594872 | 293 | 0.627454 |
import sys
if sys.version_info[0] < 3:
from future import standard_library
standard_library.install_aliases()
from builtins import str
import json
import os
from telegraf_utils.telegraf_name_map import name_map
import subprocess
import signal
import urllib.request, urllib.error, urllib.parse
from shutil import copyfile, rmtree
import time
import metrics_ext_utils.metrics_constants as metrics_constants
import metrics_ext_utils.metrics_common_utils as metrics_utils
def parse_config(data, me_url, mdsd_url, is_lad, az_resource_id, subscription_id, resource_group, region, virtual_machine_name):
storage_namepass_list = []
storage_namepass_str = ""
vmi_rate_counters_list = ["LogicalDisk\\BytesPerSecond", "LogicalDisk\\ReadBytesPerSecond", "LogicalDisk\\ReadsPerSecond", "LogicalDisk\\WriteBytesPerSecond", "LogicalDisk\\WritesPerSecond", "LogicalDisk\\TransfersPerSecond", "Network\\ReadBytesPerSecond", "Network\\WriteBytesPerSecond"]
MetricsExtensionNamepsace = metrics_constants.metrics_extension_namespace
has_mdsd_output = False
if len(data) == 0:
raise Exception("Empty config data received.")
if me_url is None or mdsd_url is None:
raise Exception("No url provided for Influxdb output plugin to ME, AMA.")
telegraf_json = {}
for item in data:
sink = item["sink"]
if "mdsd" in sink:
has_mdsd_output = True
counter = item["displayName"]
if counter in name_map:
plugin = name_map[counter]["plugin"]
omiclass = ""
if is_lad:
omiclass = counter.split("->")[0]
else:
omiclass = name_map[counter]["module"]
if omiclass not in telegraf_json:
telegraf_json[omiclass] = {}
if plugin not in telegraf_json[omiclass]:
telegraf_json[omiclass][plugin] = {}
telegraf_json[omiclass][plugin][name_map[counter]["field"]] = {}
if is_lad:
telegraf_json[omiclass][plugin][name_map[counter]["field"]]["displayName"] = counter.split("->")[1]
else:
telegraf_json[omiclass][plugin][name_map[counter]["field"]]["displayName"] = counter
telegraf_json[omiclass][plugin][name_map[counter]["field"]]["interval"] = item["interval"]
if is_lad:
telegraf_json[omiclass][plugin][name_map[counter]["field"]]["ladtablekey"] = name_map[counter]["ladtablekey"]
if "op" in name_map[counter]:
telegraf_json[omiclass][plugin][name_map[counter]["field"]]["op"] = name_map[counter]["op"]
if len(telegraf_json) == 0:
raise Exception("Unable to parse telegraf config into intermediate dictionary.")
excess_diskio_plugin_list_lad = ["total_transfers_filesystem", "read_bytes_filesystem", "total_bytes_filesystem", "write_bytes_filesystem", "reads_filesystem", "writes_filesystem"]
excess_diskio_field_drop_list_str = ""
int_file = {"filename":"intermediate.json", "data": json.dumps(telegraf_json)}
output = []
output.append(int_file)
for omiclass in telegraf_json:
input_str = ""
ama_rename_str = ""
metricsext_rename_str = ""
lad_specific_rename_str = ""
rate_specific_aggregator_str = ""
aggregator_str = ""
for plugin in telegraf_json[omiclass]:
config_file = {"filename" : omiclass+".conf"}
min_interval = "999999999s"
is_vmi = plugin.endswith("_vmi")
is_vmi_rate_counter = False
for field in telegraf_json[omiclass][plugin]:
if not is_vmi_rate_counter:
is_vmi_rate_counter = telegraf_json[omiclass][plugin][field]["displayName"] in vmi_rate_counters_list
if is_vmi or is_vmi_rate_counter:
splitResult = plugin.split('_')
telegraf_plugin = splitResult[0]
input_str += "[[inputs." + telegraf_plugin + "]]\n"
else:
input_str += "[[inputs." + plugin + "]]\n"
# always skip lad plugin names as they should be dropped from ME
lad_plugin_name = plugin + "_total"
if lad_plugin_name not in storage_namepass_list:
storage_namepass_list.append(lad_plugin_name)
if is_lad:
lad_specific_rename_str += "\n[[processors.rename]]\n"
lad_specific_rename_str += " "*2 + "namepass = [\"" + lad_plugin_name + "\"]\n"
elif is_vmi or is_vmi_rate_counter:
if plugin not in storage_namepass_list:
storage_namepass_list.append(plugin + "_mdsd")
else:
ama_plugin_name = plugin + "_mdsd_la_perf"
ama_rename_str += "\n[[processors.rename]]\n"
ama_rename_str += " "*2 + "namepass = [\"" + ama_plugin_name + "\"]\n"
if ama_plugin_name not in storage_namepass_list:
storage_namepass_list.append(ama_plugin_name)
namespace = MetricsExtensionNamepsace
if is_vmi or is_vmi_rate_counter:
namespace = "insights.virtualmachine"
if is_vmi_rate_counter:
# Adding "_rated" as a substring for vmi rate metrics to avoid renaming collisions
plugin_name = plugin + "_rated"
else:
plugin_name = plugin
metricsext_rename_str += "\n[[processors.rename]]\n"
metricsext_rename_str += " "*2 + "namepass = [\"" + plugin_name + "\"]\n"
metricsext_rename_str += "\n" + " "*2 + "[[processors.rename.replace]]\n"
metricsext_rename_str += " "*4 + "measurement = \"" + plugin_name + "\"\n"
metricsext_rename_str += " "*4 + "dest = \"" + namespace + "\"\n"
fields = ""
ops_fields = ""
non_ops_fields = ""
non_rate_aggregate = False
ops = ""
min_agg_period = ""
rate_aggregate = False
for field in telegraf_json[omiclass][plugin]:
fields += "\"" + field + "\", "
if is_vmi or is_vmi_rate_counter :
if "MB" in field:
fields += "\"" + field.replace('MB','Bytes') + "\", "
#Use the shortest interval time for the whole plugin
new_interval = telegraf_json[omiclass][plugin][field]["interval"]
if int(new_interval[:-1]) < int(min_interval[:-1]):
min_interval = new_interval
#compute values for aggregator options
if "op" in telegraf_json[omiclass][plugin][field]:
if telegraf_json[omiclass][plugin][field]["op"] == "rate":
rate_aggregate = True
ops = "\"rate\", \"rate_min\", \"rate_max\", \"rate_count\", \"rate_sum\", \"rate_mean\""
if is_lad:
ops_fields += "\"" + telegraf_json[omiclass][plugin][field]["ladtablekey"] + "\", "
else:
ops_fields += "\"" + telegraf_json[omiclass][plugin][field]["displayName"] + "\", "
else:
non_rate_aggregate = True
if is_lad:
non_ops_fields += "\"" + telegraf_json[omiclass][plugin][field]["ladtablekey"] + "\", "
else:
non_ops_fields += "\"" + telegraf_json[omiclass][plugin][field]["displayName"] + "\", "
# #Aggregation perdiod needs to be double of interval/polling period for metrics for rate aggegation to work properly
# This is only for metrics going to MDSD. for VMI metrics aggregation,
# the requirement is to have ALL the metrics at 60 seconds and that is handled later by sourcing the VMI metrics that need to be aggregated at 30 seconds
if int(min_interval[:-1]) > 30:
min_agg_period = str(int(min_interval[:-1])*2) #if the min interval is greater than 30, use the double value
else:
min_agg_period = "60" #else use 60 as mininum so that we can maintain 1 event per minute
#Add respective rename processor plugin based on the displayname
if is_lad:
lad_specific_rename_str += "\n" + " "*2 + "[[processors.rename.replace]]\n"
lad_specific_rename_str += " "*4 + "field = \"" + field + "\"\n"
lad_specific_rename_str += " "*4 + "dest = \"" + telegraf_json[omiclass][plugin][field]["ladtablekey"] + "\"\n"
elif not is_vmi and not is_vmi_rate_counter:
# no rename of fields as they are set in telegraf directly
ama_rename_str += "\n" + " "*2 + "[[processors.rename.replace]]\n"
ama_rename_str += " "*4 + "field = \"" + field + "\"\n"
ama_rename_str += " "*4 + "dest = \"" + telegraf_json[omiclass][plugin][field]["displayName"] + "\"\n"
# Avoid adding the rename logic for the redundant *_filesystem fields for diskio which were added specifically for OMI parity in LAD
# Had to re-use these six fields to avoid renaming issues since both Filesystem and Disk in OMI-LAD use them
# AMA only uses them once so only need this for LAD
if is_lad:
if field in excess_diskio_plugin_list_lad:
excess_diskio_field_drop_list_str += "\"" + field + "\", "
else:
metricsext_rename_str += "\n" + " "*2 + "[[processors.rename.replace]]\n"
metricsext_rename_str += " "*4 + "field = \"" + field + "\"\n"
metricsext_rename_str += " "*4 + "dest = \"" + plugin + "/" + field + "\"\n"
elif not is_vmi and not is_vmi_rate_counter:
# no rename of fields as they are set in telegraf directly
metricsext_rename_str += "\n" + " "*2 + "[[processors.rename.replace]]\n"
metricsext_rename_str += " "*4 + "field = \"" + field + "\"\n"
metricsext_rename_str += " "*4 + "dest = \"" + plugin + "/" + field + "\"\n"
#Add respective operations for aggregators
# if is_lad:
if not is_vmi and not is_vmi_rate_counter:
suffix = ""
if is_lad:
suffix = "_total\"]\n"
else:
suffix = "_mdsd_la_perf\"]\n"
if rate_aggregate:
aggregator_str += "[[aggregators.basicstats]]\n"
aggregator_str += " "*2 + "namepass = [\"" + plugin + suffix
aggregator_str += " "*2 + "period = \"" + min_agg_period + "s\"\n"
aggregator_str += " "*2 + "drop_original = true\n"
aggregator_str += " "*2 + "fieldpass = [" + ops_fields[:-2] + "]\n" #-2 to strip the last comma and space
aggregator_str += " "*2 + "stats = [" + ops + "]\n"
if non_rate_aggregate:
aggregator_str += "[[aggregators.basicstats]]\n"
aggregator_str += " "*2 + "namepass = [\"" + plugin + suffix
aggregator_str += " "*2 + "period = \"" + min_agg_period + "s\"\n"
aggregator_str += " "*2 + "drop_original = true\n"
aggregator_str += " "*2 + "fieldpass = [" + non_ops_fields[:-2] + "]\n" #-2 to strip the last comma and space
aggregator_str += " "*2 + "stats = [\"mean\", \"max\", \"min\", \"sum\", \"count\"]\n\n"
elif is_vmi_rate_counter:
# Aggregator config for MDSD
aggregator_str += "[[aggregators.basicstats]]\n"
aggregator_str += " "*2 + "namepass = [\"" + plugin + "_mdsd\"]\n"
aggregator_str += " "*2 + "period = \"" + min_interval + "\"\n"
aggregator_str += " "*2 + "drop_original = true\n"
aggregator_str += " "*2 + "fieldpass = [" + ops_fields[:-2].replace('\\','\\\\\\\\') + "]\n" #-2 to strip the last comma and space
aggregator_str += " "*2 + "stats = [" + ops + "]\n\n"
# Aggregator config for ME
aggregator_str += "[[aggregators.mdmratemetrics]]\n"
aggregator_str += " "*2 + "namepass = [\"" + plugin + "\"]\n"
aggregator_str += " "*2 + "period = \"" + min_interval + "\"\n"
aggregator_str += " "*2 + "drop_original = true\n"
aggregator_str += " "*2 + "fieldpass = [" + ops_fields[:-2].replace('\\','\\\\\\\\') + "]\n" #-2 to strip the last comma and space
aggregator_str += " "*2 + "stats = [\"rate\"]\n\n"
if is_lad:
lad_specific_rename_str += "\n"
elif not is_vmi and not is_vmi_rate_counter:
# no rename of fields as they are set in telegraf directly
ama_rename_str += "\n"
# Using fields[: -2] here to get rid of the last ", " at the end of the string
input_str += " "*2 + "fieldpass = ["+fields[:-2]+"]\n"
if plugin == "cpu":
input_str += " "*2 + "report_active = true\n"
if is_vmi_rate_counter:
# Rate interval needs to be atleast twice the regular sourcing interval for aggregation to work.
# Since we want all the VMI metrics to be sent at the same interval as selected by the customer, To overcome the twice the min internval limitation,
# We are sourcing the VMI metrics that need to be aggregated at half the selected frequency
rated_min_interval = str(int(min_interval[:-1]) // 2) + "s"
input_str += " "*2 + "interval = " + "\"" + rated_min_interval + "\"\n\n"
else:
input_str += " "*2 + "interval = " + "\"" + min_interval + "\"\n\n"
config_file["data"] = input_str + "\n" + metricsext_rename_str + "\n" + ama_rename_str + "\n" + lad_specific_rename_str + "\n" +aggregator_str
output.append(config_file)
config_file = {}
## Get the log folder directory from HandlerEnvironment.json and use that for the telegraf default logging
logFolder, _ = get_handler_vars()
for measurement in storage_namepass_list:
storage_namepass_str += "\"" + measurement + "\", "
# Telegraf basic agent and output config
agentconf = "[agent]\n"
agentconf += " interval = \"10s\"\n"
agentconf += " round_interval = true\n"
agentconf += " metric_batch_size = 1000\n"
agentconf += " metric_buffer_limit = 1000000\n"
agentconf += " collection_jitter = \"0s\"\n"
agentconf += " flush_interval = \"10s\"\n"
agentconf += " flush_jitter = \"0s\"\n"
agentconf += " logtarget = \"file\"\n"
agentconf += " quiet = true\n"
agentconf += " logfile = \"" + logFolder + "/telegraf.log\"\n"
agentconf += " logfile_rotation_max_size = \"100MB\"\n"
agentconf += " logfile_rotation_max_archives = 5\n"
agentconf += "\n# Configuration for adding gloabl tags\n"
agentconf += "[global_tags]\n"
if is_lad:
agentconf += " DeploymentId= \"${DeploymentId}\"\n"
agentconf += " \"microsoft.subscriptionId\"= \"" + subscription_id + "\"\n"
agentconf += " \"microsoft.resourceGroupName\"= \"" + resource_group + "\"\n"
agentconf += " \"microsoft.regionName\"= \"" + region + "\"\n"
agentconf += " \"microsoft.resourceId\"= \"" + az_resource_id + "\"\n"
if virtual_machine_name != "":
agentconf += " \"VMInstanceId\"= \"" + virtual_machine_name + "\"\n"
agentconf += "\n# Configuration for sending metrics to MetricsExtension\n"
agentconf += "[[outputs.influxdb]]\n"
agentconf += " namedrop = [" + storage_namepass_str[:-2] + "]\n"
if is_lad:
agentconf += " fielddrop = [" + excess_diskio_field_drop_list_str[:-2] + "]\n"
agentconf += " urls = [\"" + str(me_url) + "\"]\n\n"
agentconf += " udp_payload = \"1024B\"\n\n"
if has_mdsd_output:
agentconf += "\n# Configuration for sending metrics to MDSD\n"
agentconf += "[[outputs.socket_writer]]\n"
agentconf += " namepass = [" + storage_namepass_str[:-2] + "]\n"
agentconf += " data_format = \"influx\"\n"
agentconf += " address = \"" + str(mdsd_url) + "\"\n\n"
agentconf += "\n# Configuration for outputing metrics to file. Uncomment to enable.\n"
agentconf += "#[[outputs.file]]\n"
agentconf += "# files = [\"./metrics_to_file.out\"]\n\n"
agent_file = {"filename":"telegraf.conf", "data": agentconf}
output.append(agent_file)
return output, storage_namepass_list
def write_configs(configs, telegraf_conf_dir, telegraf_d_conf_dir):
# Delete the older config folder to prevent telegraf from loading older configs
if os.path.exists(telegraf_conf_dir):
rmtree(telegraf_conf_dir)
os.mkdir(telegraf_conf_dir)
os.mkdir(telegraf_d_conf_dir)
for configfile in configs:
if configfile["filename"] == "telegraf.conf" or configfile["filename"] == "intermediate.json":
path = telegraf_conf_dir + configfile["filename"]
else:
path = telegraf_d_conf_dir + configfile["filename"]
with open(path, "w") as f:
f.write(configfile["data"])
def get_handler_vars():
logFolder = ""
configFolder = ""
handler_env_path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'HandlerEnvironment.json'))
if os.path.exists(handler_env_path):
with open(handler_env_path, 'r') as handler_env_file:
handler_env_txt = handler_env_file.read()
handler_env = json.loads(handler_env_txt)
if type(handler_env) == list:
handler_env = handler_env[0]
if "handlerEnvironment" in handler_env:
if "logFolder" in handler_env["handlerEnvironment"]:
logFolder = handler_env["handlerEnvironment"]["logFolder"]
if "configFolder" in handler_env["handlerEnvironment"]:
configFolder = handler_env["handlerEnvironment"]["configFolder"]
return logFolder, configFolder
def is_running(is_lad):
if is_lad:
telegraf_bin = metrics_constants.lad_telegraf_bin
else:
telegraf_bin = metrics_constants.ama_telegraf_bin
proc = subprocess.Popen(["ps aux | grep telegraf | grep -v grep"], stdout=subprocess.PIPE, shell=True)
output = proc.communicate()[0]
if telegraf_bin in output.decode('utf-8', 'ignore'):
return True
else:
return False
def stop_telegraf_service(is_lad):
if is_lad:
telegraf_bin = metrics_constants.lad_telegraf_bin
else:
telegraf_bin = metrics_constants.ama_telegraf_bin
# If the VM has systemd, then we will use that to stop
if metrics_utils.is_systemd():
code = 1
telegraf_service_path = get_telegraf_service_path()
if os.path.isfile(telegraf_service_path):
code = os.system("sudo systemctl stop metrics-sourcer")
else:
return False, "Telegraf service file does not exist. Failed to stop telegraf service: metrics-sourcer.service."
if code != 0:
return False, "Unable to stop telegraf service: metrics-sourcer.service. Run systemctl status metrics-sourcer.service for more info."
# Whether or not VM has systemd, let's check if we have any telegraf pids saved and if so, terminate the associated process
_, configFolder = get_handler_vars()
telegraf_conf_dir = configFolder + "/telegraf_configs/"
telegraf_pid_path = telegraf_conf_dir + "telegraf_pid.txt"
if os.path.isfile(telegraf_pid_path):
with open(telegraf_pid_path, "r") as f:
for pid in f.readlines():
cmd_path = os.path.join("/proc", str(pid.strip("\n")), "cmdline")
if os.path.exists(cmd_path):
with open(cmd_path, "r") as cmd_f:
cmdline = cmd_f.readlines()
if cmdline[0].find(telegraf_bin) >= 0:
os.kill(int(pid), signal.SIGKILL)
os.remove(telegraf_pid_path)
elif not metrics_utils.is_systemd():
return False, "Could not find telegraf service nor process to stop."
return True, "Successfully stopped metrics-sourcer service"
def remove_telegraf_service():
telegraf_service_path = get_telegraf_service_path()
if os.path.isfile(telegraf_service_path):
os.remove(telegraf_service_path)
else:
return True, "Unable to remove the Telegraf service as the file doesn't exist."
# Checking To see if the file was successfully removed, since os.remove doesn't return an error code
if os.path.isfile(telegraf_service_path):
return False, "Unable to remove telegraf service: metrics-sourcer.service at {0}.".format(telegraf_service_path)
return True, "Successfully removed metrics-sourcer service"
def setup_telegraf_service(telegraf_bin, telegraf_d_conf_dir, telegraf_agent_conf):
telegraf_service_path = get_telegraf_service_path()
telegraf_service_template_path = os.getcwd() + "/services/metrics-sourcer.service"
if not os.path.exists(telegraf_d_conf_dir):
raise Exception("Telegraf config directory does not exist. Failed to setup telegraf service.")
if not os.path.isfile(telegraf_agent_conf):
raise Exception("Telegraf agent config does not exist. Failed to setup telegraf service.")
if os.path.isfile(telegraf_service_template_path):
copyfile(telegraf_service_template_path, telegraf_service_path)
if os.path.isfile(telegraf_service_path):
os.system(r"sed -i 's+%TELEGRAF_BIN%+{1}+' {0}".format(telegraf_service_path, telegraf_bin))
os.system(r"sed -i 's+%TELEGRAF_AGENT_CONFIG%+{1}+' {0}".format(telegraf_service_path, telegraf_agent_conf))
os.system(r"sed -i 's+%TELEGRAF_CONFIG_DIR%+{1}+' {0}".format(telegraf_service_path, telegraf_d_conf_dir))
daemon_reload_status = os.system("sudo systemctl daemon-reload")
if daemon_reload_status != 0:
raise Exception("Unable to reload systemd after Telegraf service file change. Failed to setup telegraf service.")
else:
raise Exception("Unable to copy Telegraf service template file to {0}. Failed to setup telegraf service.".format(telegraf_service_path))
else:
raise Exception("Telegraf service template file does not exist at {0}. Failed to setup telegraf service.".format(telegraf_service_template_path))
return True
def start_telegraf(is_lad):
log_messages = ""
if is_lad:
telegraf_bin = metrics_constants.lad_telegraf_bin
else:
telegraf_bin = metrics_constants.ama_telegraf_bin
if not os.path.isfile(telegraf_bin):
log_messages += "Telegraf binary does not exist. Failed to start telegraf service."
return False, log_messages
stop_telegraf_service(is_lad)
if metrics_utils.is_systemd():
service_restart_status = os.system("sudo systemctl restart metrics-sourcer")
if service_restart_status != 0:
log_messages += "Unable to start Telegraf service. Failed to start telegraf service."
return False, log_messages
else:
_, configFolder = get_handler_vars()
telegraf_conf_dir = configFolder + "/telegraf_configs/"
telegraf_agent_conf = telegraf_conf_dir + "telegraf.conf"
telegraf_d_conf_dir = telegraf_conf_dir + "telegraf.d/"
telegraf_pid_path = telegraf_conf_dir + "telegraf_pid.txt"
binary_exec_command = "{0} --config {1} --config-directory {2}".format(telegraf_bin, telegraf_agent_conf, telegraf_d_conf_dir)
proc = subprocess.Popen(binary_exec_command.split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
time.sleep(3)
p = proc.poll()
if p is None:
telegraf_pid = proc.pid
try:
with open(telegraf_pid_path, "a") as f:
f.write(str(telegraf_pid) + '\n')
except Exception as e:
log_messages += "Successfully started telegraf binary, but could not save telegraf pidfile."
else:
out, err = proc.communicate()
log_messages += "Unable to run telegraf binary as a process due to error - {0}. Failed to start telegraf.".format(err)
return False, log_messages
return True, log_messages
def get_telegraf_service_path():
if os.path.exists("/lib/systemd/system/"):
return metrics_constants.telegraf_service_path
elif os.path.exists("/usr/lib/systemd/system/"):
return metrics_constants.telegraf_service_path_usr_lib
else:
raise Exception("Systemd unit files do not exist at /lib/systemd/system or /usr/lib/systemd/system/. Failed to setup telegraf service.")
def handle_config(config_data, me_url, mdsd_url, is_lad):
retries = 1
max_retries = 3
sleep_time = 5
imdsurl = ""
is_arc = False
if is_lad:
imdsurl = "http://169.254.169.254/metadata/instance?api-version=2019-03-11"
else:
if metrics_utils.is_arc_installed():
imdsurl = metrics_utils.get_arc_endpoint()
imdsurl += "/metadata/instance?api-version=2019-11-01"
is_arc = True
else:
imdsurl = "http://169.254.169.254/metadata/instance?api-version=2019-03-11"
data = None
while retries <= max_retries:
req = urllib.request.Request(imdsurl, headers={'Metadata':'true'})
res = urllib.request.urlopen(req)
data = json.loads(res.read().decode('utf-8', 'ignore'))
if "compute" not in data:
retries += 1
else:
break
time.sleep(sleep_time)
if retries > max_retries:
raise Exception("Unable to find 'compute' key in imds query response. Reached max retry limit of - {0} times. Failed to setup Telegraf.".format(max_retries))
if "resourceId" not in data["compute"]:
raise Exception("Unable to find 'resourceId' key in imds query response. Failed to setup Telegraf.")
az_resource_id = data["compute"]["resourceId"]
if "virtualMachineScaleSets" in az_resource_id:
az_resource_id = "/".join(az_resource_id.split("/")[:-2])
if "subscriptionId" not in data["compute"]:
raise Exception("Unable to find 'subscriptionId' key in imds query response. Failed to setup Telegraf.")
subscription_id = data["compute"]["subscriptionId"]
if "resourceGroupName" not in data["compute"]:
raise Exception("Unable to find 'resourceGroupName' key in imds query response. Failed to setup Telegraf.")
resource_group = data["compute"]["resourceGroupName"]
if "location" not in data["compute"]:
raise Exception("Unable to find 'location' key in imds query response. Failed to setup Telegraf.")
region = data["compute"]["location"]
virtual_machine_name = ""
if "vmScaleSetName" in data["compute"] and data["compute"]["vmScaleSetName"] != "":
virtual_machine_name = data["compute"]["name"]
output, namespaces = parse_config(config_data, me_url, mdsd_url, is_lad, az_resource_id, subscription_id, resource_group, region, virtual_machine_name)
_, configFolder = get_handler_vars()
if is_lad:
telegraf_bin = metrics_constants.lad_telegraf_bin
else:
telegraf_bin = metrics_constants.ama_telegraf_bin
telegraf_conf_dir = configFolder + "/telegraf_configs/"
telegraf_agent_conf = telegraf_conf_dir + "telegraf.conf"
telegraf_d_conf_dir = telegraf_conf_dir + "telegraf.d/"
write_configs(output, telegraf_conf_dir, telegraf_d_conf_dir)
if metrics_utils.is_systemd():
telegraf_service_setup = setup_telegraf_service(telegraf_bin, telegraf_d_conf_dir, telegraf_agent_conf)
if not telegraf_service_setup:
return False, []
return True, namespaces
| true | true |
f72f41e99b9e572abeb953f1f643d46f46a98281 | 8,713 | py | Python | ros2_ws/src/utils/logger/logger/logger.py | FastSense/rosbot-ros2 | c2d274ce179534fec5b2786a6f96b6d638019ac4 | [
"MIT"
] | null | null | null | ros2_ws/src/utils/logger/logger/logger.py | FastSense/rosbot-ros2 | c2d274ce179534fec5b2786a6f96b6d638019ac4 | [
"MIT"
] | 2 | 2021-07-05T14:50:09.000Z | 2021-09-14T15:21:11.000Z | ros2_ws/src/utils/logger/logger/logger.py | FastSense/metalbot | 063c897a16129d9aa88c2c7c52bdf6547af894e4 | [
"MIT"
] | null | null | null | import os
import pandas as pd
from matplotlib import pyplot as plt
import rclpy
import numpy as np
from rclpy.node import Node
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from std_srvs.srv import Empty
from logger.utils import convert_ros2_time_to_float
from logger.create_graphs import build_general_graph_for_rosbot
from scipy.spatial.transform import Rotation
class Logger(Node):
"""
Class for logging the state of the rosbot
Node for logging the state of the robot,
kinematic model (optional) and neural network
model (optional), control and time stamps
:Attributes:
:first_tick: (bool) srue if it is first callbcak
:init_time: (float) node start time (time of the first callback)
:curr_control: (list) current control [u_v, u_w]
:output_path: (str) Absolute path to the directory
where the logged data will be saved
:control_topic: (str) nam of the control topic (/cmd_vel)
:parent_frame: (str) name of the origin tf frame
:kinetic_model_frame: (str) name of the kinematic model tf frame
:nn_model_frame: (str) name of the NN model tf frame
:robot_state: (pandas.DataFrame) container for rosbot state
:kinetic_model_state: (pandas.DataFrame) container for
kinematic model state
:nn_model_state: (pandas.DataFrame) container for NN model state
:robot_control: (pandas.DataFrame) container for rosbot control
:time: (list) container for time stamps
:odom_sub: subscriber to /odom topic
:control_sub: subscriber to control topic
"""
def __init__(self):
"""
"""
super().__init__('logger')
self.init_parameters()
self.get_node_parametes()
self.init_subs()
self.init_containers()
self.first_tick = True
self.init_time = None
self.curr_control = list()
self.srv = self.create_service(Empty, 'shutdown_logger', self.shutdown_logger_callback)
rclpy.get_default_context().on_shutdown(self.on_shutdown)
def init_parameters(self):
"""
Declares node parameters
"""
self.declare_parameter('output_path', "")
self.declare_parameter('control_topic', '/cmd_vel')
self.declare_parameter('parent_frame', 'odom')
self.declare_parameter('kinetic_model_frame', 'model_link')
self.declare_parameter('nn_model_frame', 'nn_model_link')
# self.declare_parameter('tf_topic', '/tf')
def get_node_parametes(self):
"""
Gets node parameters
"""
self.output_path = self.get_parameter('output_path').get_parameter_value().string_value
self.control_topic = self.get_parameter('control_topic').get_parameter_value().string_value
self.parent_frame = self.get_parameter('parent_frame').get_parameter_value().string_value
self.kinetic_model_frame = self.get_parameter('kinetic_model_frame').get_parameter_value().string_value
self.nn_model_frame = self.get_parameter('nn_model_frame').get_parameter_value().string_value
# self.tf_topic = self.get_parameter('tf_topic').get_parameter_value().string_value
def init_containers(self):
"""
Declares containers for logged data
"""
self.robot_state = pd.DataFrame(
columns=[
'x', 'y', 'z', 'roll', 'pitch', 'yaw',
'v_x', 'v_y', 'v_z', 'w_x', 'w_y', 'w_z',
]
)
self.kinetic_model_state = pd.DataFrame(
columns=[
'x', 'y', 'z', 'roll', 'pitch', 'yaw',
'v_x', 'v_y', 'v_z', 'w_x', 'w_y', 'w_z',
]
)
self.nn_model_state = pd.DataFrame(
columns=[
'x', 'y', 'z', 'roll', 'pitch', 'yaw',
'v_x', 'v_y', 'v_z', 'w_x', 'w_y', 'w_z',
]
)
self.robot_control = pd.DataFrame(
columns=[
'v_x', 'w_z'
]
)
self.time = list()
def init_subs(self):
"""
Declares node subscribers
"""
self.odom_sub = self.create_subscription(
Odometry,
'/odom',
self.odom_callback,
1
)
self.control_sub = self.create_subscription(
Twist,
self.control_topic,
self.control_callback,
1
)
# prevent unused variable warning
self.control_sub
self.odom_sub
def odom_callback(self, odom_msg):
"""
Callback on odom message
Robot position, current time and control are logged
Args:
:odom_msg: (nav_msgs.msg.Odometry): odom msg
"""
if (len(self.curr_control) == 0):
return
curr_time = convert_ros2_time_to_float(
self.get_clock().now().seconds_nanoseconds()
)
# update time container
self.time.append(curr_time - self.init_time)
# update control container
self.robot_control.loc[len(self.robot_control)] = self.curr_control
# update robot_state container
rosbot_pose = odom_msg.pose.pose
rosbot_velocities = odom_msg.twist.twist
x, y, z = rosbot_pose.position.x, rosbot_pose.position.y, rosbot_pose.position.z
rpy = Rotation.from_quat([
np.float(rosbot_pose.orientation.x),
np.float(rosbot_pose.orientation.y),
np.float(rosbot_pose.orientation.z),
np.float(rosbot_pose.orientation.w)]
).as_euler('xyz')
rpy = list(rpy)
v_x = rosbot_velocities.linear.x # Linear velocity
v_y = rosbot_velocities.linear.y
v_z = rosbot_velocities.linear.z
w_x = rosbot_velocities.angular.x
w_y = rosbot_velocities.angular.y
w_z = rosbot_velocities.angular.z # YAW velocity
last_row = len(self.robot_state)
self.robot_state.loc[last_row] = [x,y,z] + rpy + [v_x, v_y, v_z, w_x, w_y, w_z]
def control_callback(self, control):
"""
Updates the current control
Args:
:control: (geometry_msgs.msg.Twist) control msg
"""
if self.first_tick:
self.first_tick = False
self.init_time = convert_ros2_time_to_float(
self.get_clock().now().seconds_nanoseconds()
)
self.curr_control = [control.linear.x, control.angular.z]
def save_collected_data_to_csv(self):
"""
Saves logged data in csv format
"""
# if not os.path.exists(self.output_path):
# os.makedirs(self.output_path)
self.robot_state.to_csv(
path_or_buf=os.path.join(self.output_path, "rosbot_state.csv"),
sep=' ',
index=False
)
self.kinetic_model_state.to_csv(
path_or_buf=os.path.join(self.output_path, "kinematic_model_state.csv"),
sep=' ',
index=False
)
self.nn_model_state.to_csv(
path_or_buf=os.path.join(self.output_path, "nn_model_state.csv"),
sep=' ',
index=False
)
self.robot_control.to_csv(
path_or_buf= os.path.join(self.output_path,"control.csv"),
sep=' ',
index=False
)
pd.DataFrame(data=self.time, columns=['t']).to_csv(
path_or_buf= os.path.join(self.output_path, "time.csv"),
sep=' ',
index=False
)
def shutdown_logger_callback(self):
"""
Callback for the shutdown_logger service,
turns off the logger node
"""
rclpy.try_shutdown()
def on_shutdown(self):
"""
A function that is executed when a node shutdown.
Plots a graph of all collected data, saves it in csv format.
"""
if not os.path.exists(self.output_path):
os.makedirs(self.output_path)
data_plots = build_general_graph_for_rosbot(
robot_state_df=self.robot_state,
control_df=self.robot_control,
time_list=self.time,
save_to_png=True,
path=self.output_path
)
self.save_collected_data_to_csv()
self.get_logger().warn("Output path = {}".format(self.output_path))
def main():
"""
Declares the logger node.
Node works
"""
rclpy.init()
logger = Logger()
try:
rclpy.spin(logger)
except:
pass
logger.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
| 32.033088 | 111 | 0.596236 | import os
import pandas as pd
from matplotlib import pyplot as plt
import rclpy
import numpy as np
from rclpy.node import Node
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from std_srvs.srv import Empty
from logger.utils import convert_ros2_time_to_float
from logger.create_graphs import build_general_graph_for_rosbot
from scipy.spatial.transform import Rotation
class Logger(Node):
def __init__(self):
super().__init__('logger')
self.init_parameters()
self.get_node_parametes()
self.init_subs()
self.init_containers()
self.first_tick = True
self.init_time = None
self.curr_control = list()
self.srv = self.create_service(Empty, 'shutdown_logger', self.shutdown_logger_callback)
rclpy.get_default_context().on_shutdown(self.on_shutdown)
def init_parameters(self):
self.declare_parameter('output_path', "")
self.declare_parameter('control_topic', '/cmd_vel')
self.declare_parameter('parent_frame', 'odom')
self.declare_parameter('kinetic_model_frame', 'model_link')
self.declare_parameter('nn_model_frame', 'nn_model_link')
def get_node_parametes(self):
self.output_path = self.get_parameter('output_path').get_parameter_value().string_value
self.control_topic = self.get_parameter('control_topic').get_parameter_value().string_value
self.parent_frame = self.get_parameter('parent_frame').get_parameter_value().string_value
self.kinetic_model_frame = self.get_parameter('kinetic_model_frame').get_parameter_value().string_value
self.nn_model_frame = self.get_parameter('nn_model_frame').get_parameter_value().string_value
def init_containers(self):
self.robot_state = pd.DataFrame(
columns=[
'x', 'y', 'z', 'roll', 'pitch', 'yaw',
'v_x', 'v_y', 'v_z', 'w_x', 'w_y', 'w_z',
]
)
self.kinetic_model_state = pd.DataFrame(
columns=[
'x', 'y', 'z', 'roll', 'pitch', 'yaw',
'v_x', 'v_y', 'v_z', 'w_x', 'w_y', 'w_z',
]
)
self.nn_model_state = pd.DataFrame(
columns=[
'x', 'y', 'z', 'roll', 'pitch', 'yaw',
'v_x', 'v_y', 'v_z', 'w_x', 'w_y', 'w_z',
]
)
self.robot_control = pd.DataFrame(
columns=[
'v_x', 'w_z'
]
)
self.time = list()
def init_subs(self):
self.odom_sub = self.create_subscription(
Odometry,
'/odom',
self.odom_callback,
1
)
self.control_sub = self.create_subscription(
Twist,
self.control_topic,
self.control_callback,
1
)
self.control_sub
self.odom_sub
def odom_callback(self, odom_msg):
if (len(self.curr_control) == 0):
return
curr_time = convert_ros2_time_to_float(
self.get_clock().now().seconds_nanoseconds()
)
self.time.append(curr_time - self.init_time)
self.robot_control.loc[len(self.robot_control)] = self.curr_control
rosbot_pose = odom_msg.pose.pose
rosbot_velocities = odom_msg.twist.twist
x, y, z = rosbot_pose.position.x, rosbot_pose.position.y, rosbot_pose.position.z
rpy = Rotation.from_quat([
np.float(rosbot_pose.orientation.x),
np.float(rosbot_pose.orientation.y),
np.float(rosbot_pose.orientation.z),
np.float(rosbot_pose.orientation.w)]
).as_euler('xyz')
rpy = list(rpy)
v_x = rosbot_velocities.linear.x
v_y = rosbot_velocities.linear.y
v_z = rosbot_velocities.linear.z
w_x = rosbot_velocities.angular.x
w_y = rosbot_velocities.angular.y
w_z = rosbot_velocities.angular.z
last_row = len(self.robot_state)
self.robot_state.loc[last_row] = [x,y,z] + rpy + [v_x, v_y, v_z, w_x, w_y, w_z]
def control_callback(self, control):
if self.first_tick:
self.first_tick = False
self.init_time = convert_ros2_time_to_float(
self.get_clock().now().seconds_nanoseconds()
)
self.curr_control = [control.linear.x, control.angular.z]
def save_collected_data_to_csv(self):
self.robot_state.to_csv(
path_or_buf=os.path.join(self.output_path, "rosbot_state.csv"),
sep=' ',
index=False
)
self.kinetic_model_state.to_csv(
path_or_buf=os.path.join(self.output_path, "kinematic_model_state.csv"),
sep=' ',
index=False
)
self.nn_model_state.to_csv(
path_or_buf=os.path.join(self.output_path, "nn_model_state.csv"),
sep=' ',
index=False
)
self.robot_control.to_csv(
path_or_buf= os.path.join(self.output_path,"control.csv"),
sep=' ',
index=False
)
pd.DataFrame(data=self.time, columns=['t']).to_csv(
path_or_buf= os.path.join(self.output_path, "time.csv"),
sep=' ',
index=False
)
def shutdown_logger_callback(self):
rclpy.try_shutdown()
def on_shutdown(self):
if not os.path.exists(self.output_path):
os.makedirs(self.output_path)
data_plots = build_general_graph_for_rosbot(
robot_state_df=self.robot_state,
control_df=self.robot_control,
time_list=self.time,
save_to_png=True,
path=self.output_path
)
self.save_collected_data_to_csv()
self.get_logger().warn("Output path = {}".format(self.output_path))
def main():
rclpy.init()
logger = Logger()
try:
rclpy.spin(logger)
except:
pass
logger.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
| true | true |
f72f437483431e8f3efc25864bfdb0b9a97d1f2b | 195,406 | py | Python | yggdrasil/drivers/ModelDriver.py | cropsinsilico/yggdrasil | 466a4f77605a6f461d57ef7b165a6db7eec4d1fd | [
"BSD-3-Clause"
] | 22 | 2019-02-05T15:20:07.000Z | 2022-02-25T09:00:40.000Z | yggdrasil/drivers/ModelDriver.py | cropsinsilico/yggdrasil | 466a4f77605a6f461d57ef7b165a6db7eec4d1fd | [
"BSD-3-Clause"
] | 48 | 2019-02-15T20:41:24.000Z | 2022-03-16T20:52:02.000Z | yggdrasil/drivers/ModelDriver.py | cropsinsilico/yggdrasil | 466a4f77605a6f461d57ef7b165a6db7eec4d1fd | [
"BSD-3-Clause"
] | 16 | 2019-04-27T03:36:40.000Z | 2021-12-02T09:47:06.000Z | import os
import re
import sys
import copy
import logging
import warnings
import subprocess
import shutil
import uuid
import tempfile
import asyncio
from collections import OrderedDict
from pprint import pformat
from yggdrasil import platform, tools, languages, multitasking, constants
from yggdrasil.components import import_component
from yggdrasil.drivers.Driver import Driver
from yggdrasil.metaschema.datatypes import is_default_typedef
from queue import Empty
logger = logging.getLogger(__name__)
_map_language_ext = OrderedDict()
def remove_product(product, check_for_source=False, **kwargs):
r"""Delete a single product after checking that the product is not (or
does not contain, in the case of directories), source files.
Args:
product (str): Full path to a file or directory that should be
removed.
check_for_source (bool, optional): If True, the specified product
will be checked to ensure that no source files are present. If
a source file is present, a RuntimeError will be raised.
Defaults to False.
**kwargs: Additional keyword arguments are passed to tools.remove_path.
Raises:
RuntimeError: If the specified product is a source file and
check_for_source is False.
RuntimeError: If the specified product is a directory that contains
a source file and check_for_source is False.
RuntimeError: If the product cannot be removed.
"""
tools.import_all_modules('yggdrasil.drivers')
source_keys = list(_map_language_ext.keys())
if '.exe' in source_keys: # pragma: windows
source_keys.remove('.exe')
if check_for_source:
if os.path.isdir(product):
ext_tuple = tuple(source_keys)
for root, dirs, files in os.walk(product):
for f in files:
if f.endswith(ext_tuple):
raise RuntimeError(("%s contains a source file "
"(%s)") % (product, f))
elif os.path.isfile(product):
ext = os.path.splitext(product)[-1]
if ext in source_keys:
raise RuntimeError("%s is a source file." % product)
tools.remove_path(product, **kwargs)
def remove_products(products, source_products):
r"""Delete products produced during the process of running the model.
Args:
products (list): List of products that should be removed after
checking that they are not source files.
source_products (list): List of products that should be removed
without checking that they are not source files.
"""
for p in source_products:
remove_product(p)
for p in products:
remove_product(p, check_for_source=True)
class ModelDriver(Driver):
r"""Base class for Model drivers and for running executable based models.
Args:
name (str): Unique name used to identify the model. This will
be used to report errors associated with the model.
args (str or list): The path to the file containing the model
program that will be run by the driver for the model's language
and/or a list of arguments that should be passed as input to the
model program or language executable (e.g. source code or
configuration file for a domain specific language).
products (list, optional): Paths to files created by the model that
should be cleaned up when the model exits. Entries can be absolute
paths or paths relative to the working directory. Defaults to [].
function (str, optional): If provided, an integrated model is
created by wrapping the function named here. The function must be
located within the file specified by the source file listed in the
first argument. If not provided, the model must contain it's own
calls to the |yggdrasil| interface.
iter_function_over (array, optional): Variable(s) that should be
received or sent as an array, but iterated over. Defaults to an
empty array and is ignored.
source_products (list, optional): Files created by running the model
that are source files. These files will be removed without checking
their extension so users should avoid adding files to this list
unless they are sure they should be deleted. Defaults to [].
is_server (bool, dict, optional): If `True`, the model is assumed to be a
server for one or more client models and an instance of
:class:`yggdrasil.drivers.ServerDriver` is started. The
corresponding channel that should be passed to the yggdrasil API
will be the name of the model. If is_server is a dictionary, it
should contain an 'input' key and an 'output' key. These are
required to be the names of existing input and output channels in
the model that will be co-opted by the server. (Note: This requires
that the co-opted output channel's send method is called once for
each time the co-opted input channel's recv method is called. If
used with the `function` parameter, `is_server` must be a dictionary.
Defaults to False.
client_of (str, list, optional): The names of one or more models that
this model will call as a server. If there are more than one, this
should be specified as a sequence collection (list). The
corresponding channel(s) that should be passed to the yggdrasil API
will be the name of the server model joined with the name of the
client model with an underscore `<server_model>_<client_model>`.
There will be one channel created for each server the model is a
client of. Defaults to empty list. Use of `client_of` with `function`
is not currently supported.
timesync (bool, str, optional): If set, the model is assumed to
call a send then receive of the state at each timestep
for syncronization with other models that are also
integrating in time. If a string is provided, it is assumed
to be the name of the server that will handle timestep
synchronization. If a boolean is provided, the name of the
server will be assumed to be 'timestep'. Defaults to False.
overwrite (bool, optional): If True, any existing model products
(compilation products, wrapper scripts, etc.) are removed prior to
the run. If False, the products are not removed. Defaults to True.
Setting this to False can improve the performance, particularly for
models that take a long time to compile, but this should only be
done once the model has been fully debugged to ensure that each run
is tested on a clean copy of the model. The value of this keyword
also determines whether or not products are removed after a run.
preserve_cache (bool, optional): If True model products will be kept
following the run, otherwise all products will be cleaned up.
Defaults to False. This keyword is superceeded by overwrite.
with_strace (bool, optional): If True, the command is run with strace (on
Linux) or dtrace (on MacOS). Defaults to False.
strace_flags (list, optional): Flags to pass to strace (or dtrace).
Defaults to [].
with_valgrind (bool, optional): If True, the command is run with valgrind.
Defaults to False.
valgrind_flags (list, optional): Flags to pass to valgrind. Defaults to [].
model_index (int, optional): Index of model in list of models being run.
Defaults to 0.
copy_index (int, optional): Index of model in set of copies. Defaults
to -1 indicating there is only one copy of the model.
outputs_in_inputs (bool, optional): If True, outputs from wrapped model
functions are passed by pointer as inputs for modification and the
return value will be a flag. If False, outputs are limited to
return values. Defaults to the value of the class attribute
outputs_in_inputs.
logging_level (str, optional): The level of logging messages that should
be displayed by the model. Defaults to the logging level as
determined by the configuration file and environment variables.
allow_threading (bool, optional): If True, comm connections will be set up
so that the model-side comms can be used by more than one thread.
Defaults to False.
copies (int, optional): The number of copies of the model that should be
created. Defaults to 1.
repository_url (str, optional): URL for the git repository containing
the model source code. If provided, relative paths in the model
YAML definition will be considered relative to the repository root
directory.
repository_commit (str, optional): Commit that should be checked out
in the model repository specified by repository_url. If not
provided, the most recent commit on the default branch will be used.
description (str, optional): Description of the model. This parameter
is only used in the model repository or when providing the model
as a service.
contact_email (str, optional): Email address that should be used to
contact the maintainer of the model. This parameter is only used
in the model repository.
validation_command (str, optional): Path to a validation command that
can be used to verify that the model ran as expected. A non-zero
return code is taken to indicate failure.
dependencies (list, optional): A list of packages required by the
model that are written in the same language as the model. If the
package requires dependencies outside the language of the model.
use the additional_dependencies parameter to provide them. If you
need a version of the package from a specific package manager,
a mapping with 'package' and 'package_manager' fields can be
provided instead of just the name of the package.
additional_dependencies (dict, optional): A mapping between languages
and lists of packages in those languages that are required by the
model.
**kwargs: Additional keyword arguments are passed to parent class.
Class Attributes:
language (str): Primary name for the programming language that this
compiler should be used for. [REQUIRED]
language_aliases (list): Additional/alternative names that the language
may be known by.
language_ext (list): Extensions for programs written in the target
language. [REQUIRED]
base_languages (list): Other programming languages that this driver
and the interpreter for the target language are dependent on (e.g.
Matlab models require Python).
executable_type (str): 'compiler' or 'interpreter' to indicate the type
of the executable for the language. [AUTOMATED]
interface_library (list): Name of the library containing the yggdrasil
interface for the target language. [REQUIRED]
interface_directories (list): Directories containing code in the
interface library for the target language.
interface_dependencies (list): List of names of libraries that are
required to use the interface on the current platform. This dosn't
include libraries required by specific communication types which are
described by supported_comm_options.
supported_comms (list): Name of comms supported in the target language.
[REQUIRED]
supported_comm_options (dict): Options for the supported comms like the
platforms they are available on and the external libraries required
to use them. [REQUIRED]
external_libraries (dict): Information on external libraries required
for running models in the target language using yggdrasil.
internal_libraries (dict): Information on internal libraries required
for running models in the target language using yggdrasil.
type_map (dict): Mapping of |yggdrasil| extended JSON types to
datatypes in the target programming language. [REQUIRED]
function_param (dict): Options specifying how different operations
would be encoded in the target language (e.g. if statements, for
loops, while loops). [REQUIRED]
version_flags (list): Flags that should be called with the language
executable to determine the version of the compiler/interpreter.
Defaults to ['--version'].
outputs_in_inputs (bool): If True, outputs are passed by pointer as
inputs for modification and the return value should be a flag.
Defaults to False.
include_arg_count (bool): If True, the number of arguments passed
to send/recv calls is prepended to the arguments to the function.
Defaults to False.
include_channel_obj (bool): If True, the channel object is passed as
input to the send/recv calls (after the argument count if it is
also present due to include_arg_count being True). Defaults to
False.
is_typed (bool): True if the language is typed, False otherwise.
brackets (tuple): A pair of opening and clossing characters that
are used by the language to mark blocks. Set to None and
ignored by default.
no_executable (bool): True if there is not an executable associated
with the language driver. Defaults to False.
comms_implicit (bool): True if the comms installed for this driver
are not explicitly defined (depend on input parameters). Defaults
to False.
Attributes:
args (list): Argument(s) for running the model on the command line.
model_file (str): Full path to the model executable or interpretable
script.
model_args (list): Runtime arguments for running the model on the
command line.
model_src (str): Full path to the model source code. For interpreted
languages, this will be the same as model_file.
model_function_info (dict): Parameters recovered by parsing the
provided model function definition.
overwrite (bool): If True, any existing compilation products will be
overwritten by compilation and cleaned up following the run.
Otherwise, existing products will be used and will remain after
the run.
products (list): Files created by running the model. This includes
compilation products such as executables and/or object files.
source_products (list): Files created by running the model that
are source files. These files will be removed without checking
their extension so users should avoid adding files to this list
unless they are sure they should be deleted.
wrapper_products (list): Files created in order to wrap the model.
process (:class:`yggdrasil.tools.YggPopen`): Process used to run
the model.
function (str): The name of the model function that should be wrapped.
iter_function_over (array): Variable(s) that should be received or
sent as an array, but iterated over.
is_server (bool, dict): If True, the model is assumed to be a server
and an instance of :class:`yggdrasil.drivers.ServerDriver` is
started. If a dict, the input/output channels with the specified
names in the dict will be replaced with a server.
client_of (list): The names of server models that this model is a
client of.
timesync (str): If set, the name of the server performing
timestep synchronization for the model.
with_strace (bool): If True, the command is run with strace or dtrace.
strace_flags (list): Flags to pass to strace/dtrace.
with_valgrind (bool): If True, the command is run with valgrind.
valgrind_flags (list): Flags to pass to valgrind.
model_index (int): Index of model in list of models being run.
copy_index (int): Index of model in set of copies.
modified_files (list): List of pairs of originals and copies of files
that should be restored during cleanup.
allow_threading (bool): If True, comm connections will be set up so that
the model-side comms can be used by more than one thread.
copies (int): The number of copies of the model that should be created.
repository_url (str): URL for the git repository containing the model
source code. If provided, relative paths in the model YAML
definition will be considered relative to the repository root
directory.
repository_commit (str): Commit that should be checked out in the
model repository specified by repository_url.
description (str): Description of the model. This parameter is only
used in the model repository or when providing the model as a
service.
contact_email (str): Email address that should be used to contact the
maintainer of the model. This parameter is only used in the model
repository.
validation_command (str): Path to a validation command that can be
used to verify that the model ran as expected. A non-zero return
code is taken to indicate failure.
dependencies (list): A list of packages required by the model that are
written in the same language as the model. If the package requires
dependencies outside the language of the model, use the
additional_dependencies parameter to provide them. If you need a
version of the package from a specific package manager, a mapping
with 'package' and 'package_manager' fields can be provided
instead of just the name of the package.
additional_dependencies (dict): A mapping between languages and lists
of packages in those languages that are required by the model.
Raises:
RuntimeError: If both with_strace and with_valgrind are True.
"""
_schema_type = 'model'
_schema_subtype_key = 'language'
_schema_required = ['name', 'language', 'args', 'working_dir']
_schema_properties = {
'name': {'type': 'string'},
'language': {'type': 'string', 'default': 'executable',
'description': (
'The programming language that the model '
'is written in. A list of available '
'languages can be found :ref:`here <'
'schema_table_model_subtype_rst>`.')},
'args': {'type': 'array',
'items': {'type': 'string', 'minLength': 1}},
'inputs': {'type': 'array', 'default': [],
'items': {'$ref': '#/definitions/comm'},
'description': (
'Zero or more channels carrying input to the model. '
'A full description of channel entries and the '
'options available for channels can be found '
':ref:`here<yaml_comm_options>`.')},
'outputs': {'type': 'array', 'default': [],
'items': {'$ref': '#/definitions/comm'},
'description': (
'Zero or more channels carrying output from the '
'model. A full description of channel entries and '
'the options available for channels can be found '
':ref:`here<yaml_comm_options>`.')},
'env': {'type': 'object', 'default': {},
'additional_properties': {'type': 'string'}},
'products': {'type': 'array', 'default': [],
'items': {'type': 'string'}},
'source_products': {'type': 'array', 'default': [],
'items': {'type': 'string'}},
'working_dir': {'type': 'string'},
'overwrite': {'type': 'boolean'},
'preserve_cache': {'type': 'boolean', 'default': False},
'function': {'type': 'string'},
'iter_function_over': {'type': 'array', 'default': [],
'items': {'type': 'string'}},
'is_server': {'anyOf': [{'type': 'boolean'},
{'type': 'object',
'properties': {'input': {'type': 'string'},
'output': {'type': 'string'}},
'additionalProperties': False}],
'default': False},
'client_of': {'type': 'array', 'items': {'type': 'string'},
'default': []},
'timesync': {
'anyOf': [
{'type': 'boolean'}, {'type': 'string'},
{'type': 'object',
'required': ['name'],
'properties': {
'name': {'type': 'string', 'default': 'timesync'},
'inputs': {'anyOf': [
{'type': 'string'},
{'type': 'array',
'items': {'type': 'string'}}]},
'outputs': {'anyOf': [
{'type': 'string'},
{'type': 'array',
'items': {'type': 'string'}}]}}},
{'type': 'array',
'items': {
'anyOf': [
{'type': 'string'},
{'type': 'object',
'required': ['name'],
'properties': {
'name': {'type': 'string',
'default': 'timesync'},
'inputs': {'anyOf': [
{'type': 'string'},
{'type': 'array',
'items': {'type': 'string'}}]},
'outputs': {'anyOf': [
{'type': 'string'},
{'type': 'array',
'items': {'type': 'string'}}]}}}]}}],
'default': False},
'with_strace': {'type': 'boolean', 'default': False},
'strace_flags': {'type': 'array',
'default': ['-e', 'trace=memory'],
'items': {'type': 'string'}},
'with_valgrind': {'type': 'boolean', 'default': False},
'valgrind_flags': {'type': 'array',
'default': ['--leak-check=full',
'--show-leak-kinds=all'], # '-v'
'items': {'type': 'string'}},
'outputs_in_inputs': {'type': 'boolean'},
'logging_level': {'type': 'string', 'default': ''},
'allow_threading': {'type': 'boolean'},
'copies': {'type': 'integer', 'default': 1, 'minimum': 1},
'repository_url': {'type': 'string'},
'repository_commit': {'type': 'string'},
'description': {'type': 'string'},
'contact_email': {'type': 'string'},
'validation_command': {'type': 'string'},
'dependencies': {
'type': 'array',
'items': {'oneOf': [
{'type': 'string'},
{'type': 'object',
'required': ['package'],
'properties': {
'package': {'type': 'string'},
'package_manager': {'type': 'string'},
'arguments': {'type': 'string'}},
'additionalProperties': False}]}},
'additional_dependencies': {
'type': 'object',
'additionalProperties': {
'type': 'array',
'items': {'oneOf': [
{'type': 'string'},
{'type': 'object',
'required': ['package'],
'properties': {
'package': {'type': 'string'},
'package_manager': {'type': 'string'},
'arguments': {'type': 'string'}},
'additionalProperties': False}]}}}}
_schema_excluded_from_class = ['name', 'language', 'args', 'working_dir']
_schema_excluded_from_class_validation = ['inputs', 'outputs']
language = None
language_ext = None
language_aliases = []
base_languages = []
executable_type = None
interface_library = None
interface_directories = []
interface_dependencies = []
supported_comms = []
supported_comm_options = {}
external_libraries = {}
internal_libraries = {}
type_map = None
inverse_type_map = None
function_param = None
version_flags = ['--version']
full_language = True
outputs_in_inputs = False
include_arg_count = False
include_channel_obj = False
is_typed = False
types_in_funcdef = True
interface_inside_exec = False
dont_declare_channel = False
is_dsl = False
brackets = None
zero_based = True
max_line_width = None
no_executable = False
comms_implicit = False
python_interface = {'table_input': 'YggAsciiTableInput',
'table_output': 'YggAsciiTableOutput',
'array_input': 'YggArrayInput',
'array_output': 'YggArrayOutput',
'pandas_input': 'YggPandasInput',
'pandas_output': 'YggPandasOutput'}
_library_cache = {}
_config_keys = []
_config_attr_map = []
_executable_search_dirs = None
_disconnect_attr = (Driver._disconnect_attr
+ ['queue', 'queue_thread',
'event_process_kill_called',
'event_process_kill_complete',
'model_process'])
_mpi_tags = {'ENV': 1,
'START': 2,
'STOP_RANK0': 3, # Stopped by partner
'STOP_RANKX': 4, # Stopped by root
'BUILDFILE': 5,
'LOCK_BUILDFILE': 6,
'UNLOCK_BUILDFILE': 7}
def __init__(self, name, args, model_index=0, copy_index=-1, clients=[],
preparsed_function=None, outputs_in_inputs=None,
mpi_rank=0, mpi_tag_start=None, **kwargs):
self._inv_mpi_tags = {v: k for k, v in self._mpi_tags.items()}
self.model_outputs_in_inputs = outputs_in_inputs
self.preparsed_function = preparsed_function
super(ModelDriver, self).__init__(name, **kwargs)
if self.overwrite is None:
self.overwrite = (not self.preserve_cache)
# Setup process things
self.model_process = None
self.queue = multitasking.Queue()
self.queue_thread = None
self.event_process_kill_called = multitasking.Event()
self.event_process_kill_complete = multitasking.Event()
# Strace/valgrind
if self.with_strace and self.with_valgrind:
raise RuntimeError("Trying to run with strace and valgrind.")
if (((self.with_strace or self.with_valgrind)
and platform._is_win)): # pragma: windows
raise RuntimeError("strace/valgrind options invalid on windows.")
self.model_index = model_index
self.copy_index = copy_index
self.clients = clients
self.env_copy = ['LANG', 'PATH', 'USER']
self._exit_line = b'EXIT'
for k in self.env_copy:
if k in os.environ:
self.env[k] = os.environ[k]
if not self.is_installed():
raise RuntimeError("%s is not installed" % self.language)
self.raw_model_file = None
self.model_function_file = None
self.model_function_info = None
self.model_function_inputs = None
self.model_function_outputs = None
self.model_file = None
self.model_args = []
self.model_dir = None
self.model_src = None
self.args = args
self.modified_files = []
self.wrapper_products = []
self._mpi_comm = False
self._mpi_rank = 0
self._mpi_size = 1
self._mpi_requests = {}
self._mpi_tag = (len(self._mpi_tags) * self.model_index)
if mpi_tag_start is not None:
self._mpi_tag += mpi_tag_start
if multitasking._on_mpi:
self._mpi_comm = multitasking.MPI.COMM_WORLD
self._mpi_rank = self._mpi_comm.Get_rank()
self._mpi_size = self._mpi_comm.Get_size()
self._mpi_partner_rank = mpi_rank
# Update for function
if self.function:
args = [self.init_from_function(args)]
# Parse arguments
self.debug(str(args))
self.parse_arguments(args)
assert(self.model_file is not None)
# Remove products
if self.overwrite:
self.remove_products()
# Write wrapper
if self.function:
self.wrapper_products.append(args[0])
self.wrapper_products += self.write_wrappers()
# Install dependencies
if self.dependencies:
self.install_model_dependencies(self.dependencies)
if self.additional_dependencies:
for language, v in self.additional_dependencies.items():
drv = import_component('model', language)
drv.install_model_dependencies(v)
@staticmethod
def before_registration(cls):
r"""Operations that should be performed to modify class attributes prior
to registration including things like platform dependent properties and
checking environment variables for default settings.
"""
Driver.before_registration(cls)
cls.inverse_type_map = None
cls._language = cls.language
cls._language_aliases = cls.language_aliases
if (((cls.language_ext is not None)
and (not isinstance(cls.language_ext, (list, tuple))))):
cls.language_ext = [cls.language_ext]
@staticmethod
def after_registration(cls, cfg=None, second_pass=False):
r"""Operations that should be performed to modify class attributes after
registration. For compiled languages this includes selecting the
default compiler. The order of precedence is the config file 'compiler'
option for the language, followed by the environment variable set by
_compiler_env, followed by the existing class attribute.
Args:
cfg (YggConfigParser, optional): Config class that should
be used to set options for the driver. Defaults to
None and yggdrasil.config.ygg_cfg is used.
second_pass (bool, optional): If True, the class as already
been registered. Defaults to False.
"""
if cfg is None:
from yggdrasil.config import ygg_cfg
cfg = ygg_cfg
cfg.reload()
Driver.after_registration(cls)
cls.cfg = cfg
for x in cls._config_attr_map:
ka = x['attr']
k0 = x.get('key', ka)
setattr(cls, ka, cls.cfg.get(cls.language, k0,
getattr(cls, ka)))
@staticmethod
def finalize_registration(cls):
r"""Operations that should be performed after a class has been fully
initialized and registered."""
global _map_language_ext
for x in cls.get_language_ext():
if x not in _map_language_ext:
_map_language_ext[x] = []
_map_language_ext[x].append(cls.language)
@classmethod
def mpi_partner_init(cls, self):
r"""Actions initializing an MPIPartnerModel."""
pass
@classmethod
def mpi_partner_cleanup(cls, self):
r"""Actions cleaning up an MPIPartnerModel."""
pass
@classmethod
def get_inverse_type_map(cls):
r"""Get the inverse type map.
Returns:
dict: Mapping from native type to JSON type.
"""
if cls.inverse_type_map is None:
cls.inverse_type_map = {}
for k, v in cls.type_map.items():
if k != 'flag':
cls.inverse_type_map[v] = k
return cls.inverse_type_map
@classmethod
def get_language_for_source(cls, fname, languages=None, early_exit=False,
**kwargs):
r"""Determine the language that can be used with the provided source
file(s). If more than one language applies to a set of multiple files,
the language that applies to the most files is returned.
Args:
fname (str, list): The full path to one or more files. If more than
one
languages (list, optional): The list of languages that are acceptable.
Defaults to None and any language will be acceptable.
early_exit (bool, optional): If True, the first language identified
will be returned if fname is a list of files. Defaults to False.
**kwargs: Additional keyword arguments are passed to recursive calls.
Returns:
str: The language that can operate on the specified file.
"""
if isinstance(fname, list):
lang_dict = {}
for f in fname:
try:
ilang = cls.get_language_for_source(f, languages=languages,
**kwargs)
if early_exit:
return ilang
except ValueError:
continue
lang_dict.setdefault(ilang, 0)
lang_dict[ilang] += 1
if lang_dict:
return max(lang_dict, key=lang_dict.get)
else:
ext = os.path.splitext(fname)[-1]
for ilang in cls.get_map_language_ext().get(ext, []):
if (languages is None) or (ilang in languages):
return ilang
raise ValueError("Cannot determine language for file(s): '%s'" % fname)
@classmethod
def get_map_language_ext(cls):
r"""Return the mapping of all language extensions."""
return _map_language_ext
@classmethod
def get_all_language_ext(cls):
r"""Return the list of all language extensions."""
return list(_map_language_ext.keys())
@classmethod
def get_language_dir(cls):
r"""Return the langauge directory."""
return languages.get_language_dir(cls.language)
@classmethod
def get_language_ext(cls):
r"""Return the language extension, including from the base classes."""
out = cls.language_ext
if out is None:
out = []
for x in cls.base_languages:
out += import_component('model', x).get_language_ext()
return out
def parse_arguments(self, args, default_model_dir=None):
r"""Sort model arguments to determine which one is the executable
and which ones are arguments.
Args:
args (list): List of arguments provided.
default_model_dir (str, optional): Path to directory that should be
used to normalize the model file path if it is not absolute.
Defaults to None and is set to the working_dir.
"""
if isinstance(args, (str, bytes)):
args = args.split()
for i in range(len(args)):
args[i] = str(args[i])
assert(isinstance(args, list))
if default_model_dir is None:
default_model_dir = self.working_dir
self.raw_model_file = args[0]
self.model_file = self.raw_model_file
self.model_args = args[1:]
if (self.language != 'executable') and (not os.path.isabs(self.model_file)):
model_file = os.path.normpath(os.path.join(default_model_dir,
self.model_file))
self.model_file = model_file
self.model_dir = os.path.dirname(self.model_file)
self.debug("model_file = '%s', model_dir = '%s', model_args = '%s'",
self.model_file, self.model_dir, self.model_args)
def init_from_function(self, args):
r"""Initialize model parameters based on the wrapped function."""
if not self.preparsed_function:
yml_mock = dict(self.yml,
name=self.name,
args=self.args,
function=self.function,
is_server=self.is_server,
client_of=self.client_of,
inputs=self.inputs,
outputs=self.outputs,
iter_function_over=self.iter_function_over,
copies=self.copies)
self.preparsed_function = self.preparse_function(yml_mock)
self.model_function_info = self.preparsed_function['model_file']
self.model_function_file = self.model_function_info['model_file']
self.model_function_inputs = self.preparsed_function['inputs']
self.model_function_outputs = self.preparsed_function['outputs']
self.model_outputs_in_inputs = self.preparsed_function['outputs_in_inputs']
model_dir, model_base = os.path.split(self.model_function_file)
model_base = os.path.splitext(model_base)[0]
wrapper_fname = os.path.join(model_dir,
'ygg_%s_%s%s' % (model_base, self.name,
self.language_ext[0]))
lines = self.write_model_wrapper(model_name=self.name,
**self.preparsed_function)
# Write file
if (not os.path.isfile(wrapper_fname)) or self.overwrite:
with open(wrapper_fname, 'w') as fd:
fd.write('\n'.join(lines))
return wrapper_fname
@property
def numeric_logging_level(self):
r"""int: Logging level for the model."""
out = self.logger.getEffectiveLevel()
if self.logging_level:
out = logging.getLevelName(self.logging_level)
return out
@property
def n_sent_messages(self):
r"""dict: Number of messages sent by the model via each connection."""
if (self._mpi_rank > 0) and self.check_mpi_request('stopped'):
out = self._mpi_requests['stopped'].result
return out
out = {}
for x in self.yml.get('output_drivers', []):
x_inst = x.get('instance', None)
if x_inst:
out[x_inst.name] = x_inst.models_recvd.get(self.name, 0)
if self.is_server:
for x in self.yml.get('input_drivers', []):
x_inst = x.get('instance', None)
if x_inst and (x_inst._connection_type == 'rpc_request'):
out[x_inst.name] = x_inst.servers_recvd.get(self.name, 0)
return out
@property
def has_sent_messages(self):
r"""bool: True if output has been received from the model."""
n_msg = self.n_sent_messages
if not n_msg:
return True
return bool(sum(n_msg.values()))
def write_wrappers(self, **kwargs):
r"""Write any wrappers needed to compile and/or run a model.
Args:
**kwargs: Keyword arguments are ignored (only included to
allow cascade from child classes).
Returns:
list: Full paths to any created wrappers.
"""
return []
@classmethod
def install_model_dependencies(cls, dependencies, always_yes=False):
r"""Install any dependencies required by the model.
Args:
dependencies (list): Dependencies that should be installed.
always_yes (bool, optional): If True, the package manager will
not ask users for input during installation. Defaults to
False.
"""
packages = {}
for x in dependencies:
if isinstance(x, str):
x = {'package': x}
if x.get('arguments', None):
cls.install_dependency(always_yes=always_yes, **x)
else:
packages.setdefault(x.get('package_manager', None), [])
packages[x.get('package_manager', None)].append(
x['package'])
for k, v in packages.items():
cls.install_dependency(v, package_manager=k,
always_yes=always_yes)
@classmethod
def install_dependency(cls, package=None, package_manager=None,
arguments=None, command=None, always_yes=False):
r"""Install a dependency.
Args:
package (str): Name of the package that should be installed. If
the package manager supports it, this can include version
requirements.
package_manager (str, optional): Package manager that should be
used to install the package.
arguments (str, optional): Additional arguments that should be
passed to the package manager.
command (list, optional): Command that should be used to
install the package.
always_yes (bool, optional): If True, the package manager will
not ask users for input during installation. Defaults to
False.
"""
assert(package)
if isinstance(package, str):
package = package.split()
if package_manager is None:
if tools.get_conda_prefix():
package_manager = 'conda'
elif platform._is_mac:
package_manager = 'brew'
elif platform._is_linux:
package_manager = 'apt'
elif platform._is_win:
package_manager = 'choco'
yes_cmd = []
cmd_kwargs = {}
if command:
cmd = copy.copy(command)
elif package_manager == 'conda':
cmd = ['conda', 'install'] + package
if platform._is_win: # pragma: windows
# Conda commands must be run on the shell on windows as it
# is implemented as a batch script
cmd.insert(0, 'call')
cmd_kwargs['shell'] = True
yes_cmd = ['-y']
elif package_manager == 'brew':
cmd = ['brew', 'install'] + package
elif package_manager == 'apt':
cmd = ['apt-get', 'install'] + package
if bool(os.environ.get('GITHUB_ACTIONS', False)):
# Only enable sudo for testing, otherwise allow the user to
# decide if they want to run yggdrasil with sudo, or just
# install the dependencies themselves
cmd.insert(0, 'sudo')
yes_cmd = ['-y']
elif package_manager == 'choco':
cmd = ['choco', 'install'] + package
elif package_manager == 'vcpkg':
cmd = ['vcpkg.exe', 'install', '--triplet', 'x64-windows']
cmd += package
else:
package_managers = {'pip': 'python',
'cran': 'r'}
if package_manager in package_managers:
drv = import_component(
'model', package_managers[package_manager])
return drv.install_dependency(
package=package, package_manager=package_manager,
arguments=arguments, always_yes=always_yes)
raise NotImplementedError(f"Unsupported package manager: "
f"{package_manager}")
if arguments:
cmd += arguments.split()
if always_yes:
cmd += yes_cmd
if cmd_kwargs.get('shell', False):
cmd = ' '.join(cmd)
subprocess.check_call(cmd, **cmd_kwargs)
def model_command(self):
r"""Return the command that should be used to run the model.
Returns:
list: Any commands/arguments needed to run the model from the
command line.
"""
return [self.model_file] + self.model_args
@classmethod
def language_executable(cls, **kwargs):
r"""Command required to compile/run a model written in this language
from the command line.
Returns:
str: Name of (or path to) compiler/interpreter executable required
to run the compiler/interpreter from the command line.
"""
if cls.no_executable:
return ''
raise NotImplementedError("language_executable not implemented for '%s'"
% cls.language)
@classmethod
def executable_command(cls, args, unused_kwargs=None, **kwargs):
r"""Compose a command for running a program using the exectuable for
this language (compiler/interpreter) with the provided arguments.
Args:
args (list): The program that returned command should run and any
arguments that should be provided to it.
unused_kwargs (dict, optional): Existing dictionary that unused
keyword arguments should be added to. Defaults to None and is
ignored.
**kwargs: Additional keyword arguments are ignored.
Returns:
list: Arguments composing the command required to run the program
from the command line using the executable for this language.
"""
raise NotImplementedError("executable_command not implemented for '%s'"
% cls.language)
@classmethod
def run_executable(cls, args, return_process=False, debug_flags=None,
**kwargs):
r"""Run a program using the executable for this language and the
provided arguments.
Args:
args (list): The program that should be run and any arguments
that should be provided to it.
return_process (bool, optional): If True, the process class is
returned without checking the process output. If False,
communicate is called on the process and the output is parsed
for errors. Defaults to False.
debug_flags (list, optional): Debug executable and flags that should
be prepended to the executable command. Defaults to None and
is ignored.
**kwargs: Additional keyword arguments are passed to
cls.executable_command and tools.popen_nobuffer.
Returns:
str: Output to stdout from the run command if return_process is
False, the process if return_process is True.
Raises:
RuntimeError: If the language is not installed.
RuntimeError: If there is an error when running the command.
"""
unused_kwargs = {}
cmd = cls.executable_command(args, unused_kwargs=unused_kwargs, **kwargs)
if isinstance(debug_flags, list):
cmd = debug_flags + cmd
try:
# Add default keyword arguments
if 'working_dir' in unused_kwargs:
unused_kwargs.setdefault('cwd', unused_kwargs.pop('working_dir'))
unused_kwargs.setdefault('shell', platform._is_win)
# Call command
logger.debug("Running '%s' from %s"
% (' '.join(cmd), unused_kwargs.get('cwd', os.getcwd())))
logger.debug("Process keyword arguments:\n%s\n",
' ' + pformat(unused_kwargs).replace('\n', '\n '))
print(' '.join(cmd))
proc = tools.popen_nobuffer(cmd, **unused_kwargs)
if return_process:
return proc
out, err = proc.communicate()
if proc.returncode != 0:
if out:
logger.info('\n%s' % out.decode('utf-8'))
if err: # pragma: debug
logger.info('\n%s' % err.decode('utf-8'))
raise RuntimeError("Command '%s' failed with code %d."
% (' '.join(cmd), proc.returncode))
out = out.decode("utf-8")
logger.debug('%s\n%s' % (' '.join(cmd), out))
return out
except (subprocess.CalledProcessError, OSError) as e: # pragma: debug
raise RuntimeError("Could not call command '%s': %s"
% (' '.join(cmd), e))
def run_validation(self):
r"""Run the validation script for the model."""
if not self.validation_command:
return
subprocess.check_call(self.validation_command.split(),
cwd=self.working_dir)
def run_model(self, return_process=True, **kwargs):
r"""Run the model. Unless overridden, the model will be run using
run_executable.
Args:
return_process (bool, optional): If True, the process running
the model is returned. If False, the process will block until
the model finishes running. Defaults to True.
**kwargs: Keyword arguments are passed to run_executable.
"""
env = self.set_env()
command = self.model_command()
if self.with_strace or self.with_valgrind:
kwargs.setdefault('debug_flags', self.debug_flags)
self.debug('Working directory: %s', self.working_dir)
self.debug('Command: %s', ' '.join(command))
self.debug('Environment Variables:\n%s', self.pprint(env, block_indent=1))
# Update keywords
# NOTE: Setting forward_signals to False allows faster debugging
# but should not be used in deployment for cases where models are not
# running locally.
default_kwargs = dict(env=env, working_dir=self.working_dir,
forward_signals=False,
shell=platform._is_win)
for k, v in default_kwargs.items():
kwargs.setdefault(k, v)
return self.run_executable(command, return_process=return_process, **kwargs)
@property
def debug_flags(self):
r"""list: Flags that should be prepended to an executable command to
enable debugging."""
pre_args = []
if self.with_strace:
if platform._is_linux:
pre_args += ['strace'] + self.strace_flags
else: # pragma: debug
raise RuntimeError("strace not supported on this OS.")
# TODO: dtruss cannot be run without sudo, sudo cannot be
# added to the model process command if it is not in the original
# yggdrasil CLI call, and must be tested with an executable that
# is not "signed with restricted entitlements" (which most built-in
# utilities (e.g. sleep) are).
# elif platform._is_mac:
# if 'sudo' in sys.argv:
# pre_args += ['sudo']
# pre_args += ['dtruss']
elif self.with_valgrind:
pre_args += ['valgrind'] + self.valgrind_flags
return pre_args
@classmethod
def language_version(cls, version_flags=None, **kwargs):
r"""Determine the version of this language.
Args:
**kwargs: Keyword arguments are passed to cls.run_executable.
Returns:
str: Version of compiler/interpreter for this language.
"""
if version_flags is None:
version_flags = cls.version_flags
return cls.run_executable(version_flags, **kwargs).splitlines()[0].strip()
@classmethod
def is_installed(cls):
r"""Determine if this model driver is installed on the current
machine.
Returns:
bool: Truth of if this model driver can be run on the current
machine.
"""
return (cls.is_language_installed()
and cls.are_base_languages_installed()
and cls.are_dependencies_installed()
and cls.is_interface_installed() and cls.is_comm_installed()
and cls.is_configured() and (not cls.is_disabled()))
@classmethod
def are_base_languages_installed(cls, missing=None):
r"""Determine if the base languages are installed.
Args:
missing (list, optional): A pre-existing list that
missing base languages should be appended to.
Returns:
bool: True if the base langauges are installed. False otherwise.
"""
out = True
for x in cls.base_languages:
if (not out) and (not isinstance(missing, list)): # pragma: no cover
break
out = import_component('model', x).is_installed()
if isinstance(missing, list) and (not out):
missing.append(x)
if missing:
out = False
return out
@classmethod
def are_dependencies_installed(cls):
r"""Determine if the dependencies are installed for the interface (not
including dependencies needed by a particular communication type).
Returns:
bool: True if the dependencies are installed. False otherwise.
"""
out = (cls.language is not None)
for x in cls.interface_dependencies:
if not out: # pragma: no cover
break
out = cls.is_library_installed(x)
return out
@classmethod
def is_interface_installed(cls):
r"""Determine if the interface library for the associated programming
language is installed.
Returns:
bool: True if the interface library is installed.
"""
out = (cls.language is not None)
if out and (cls.interface_library is not None):
out = cls.is_library_installed(cls.interface_library)
return out
@classmethod
def is_language_installed(cls):
r"""Determine if the interpreter/compiler for the associated programming
language is installed.
Returns:
bool: True if the language interpreter/compiler is installed.
"""
out = False
if cls.language is not None:
try:
out = (shutil.which(cls.language_executable()) is not None)
except NotImplementedError: # pragma: debug
out = False
return out
@classmethod
def identify_source_files(cls, args=None, working_dir=None, **kwargs):
r"""Determine the source file based on model arguments.
Args:
args (list, optional): Arguments provided.
working_dir (str, optional): Working directory.
**kwargs: Additional keyword arguments are ignored.
Returns:
list: Source files.
"""
out = []
if args:
src = args[0]
if (((not cls.is_source_file(src))
and (cls.language_ext is not None)
and (os.path.splitext(src)[-1]
not in cls.get_all_language_ext()))):
src = os.path.splitext(src)[0] + cls.language_ext[0]
if working_dir and (not os.path.isabs(src)):
src = os.path.normpath(os.path.join(working_dir, src))
if os.path.isfile(src):
out.append(src)
return out
@classmethod
def is_source_file(cls, fname):
r"""Determine if the provided file name points to a source files for
the associated programming language by checking the extension.
Args:
fname (str): Path to file.
Returns:
bool: True if the provided file is a source file, False otherwise.
"""
out = False
model_ext = os.path.splitext(fname)[-1]
if len(model_ext) > 0:
out = (model_ext in cls.get_language_ext())
return out
@classmethod
def is_library_installed(cls, lib, **kwargs):
r"""Determine if a dependency is installed.
Args:
lib (str): Name of the library that should be checked.
**kwargs: Additional keyword arguments are ignored.
Returns:
bool: True if the library is installed, False otherwise.
"""
raise NotImplementedError("Method is_library_installed missing for '%s'"
% cls.language)
@classmethod
def is_disabled(cls):
return (cls.cfg.get(cls.language, 'disable', 'false').lower() == 'true')
@classmethod
def is_configured(cls):
r"""Determine if the appropriate configuration has been performed (e.g.
installation of supporting libraries etc.)
Returns:
bool: True if the language has been configured.
"""
# Check for section & diable
disable_flag = cls.is_disabled()
out = (cls.cfg.has_section(cls.language) and (not disable_flag))
# Check for commtypes
if out and (len(cls.base_languages) == 0):
out = (cls.cfg.get(cls.language, 'commtypes', None) is not None)
# Check for config keys
for k in cls._config_keys:
if not out: # pragma: no cover
break
out = (cls.cfg.get(cls.language, k, None) is not None)
return out
@classmethod
def is_comm_installed(cls, commtype=None, skip_config=False, **kwargs):
r"""Determine if a comm is installed for the associated programming
language.
Args:
commtype (str, optional): If provided, this method will only test
for installation of the specified communication type. Defaults
to None and will check for any installed comm.
skip_config (bool, optional): If True, the config list of comms
installed for this language will not be used to determine if
the comm is installed and the class attribute
supported_comm_options will be processed. Defaults to False and
config options are used in order to improve performance after
initial configuration.
platforms (list, optional): Platforms on which the comm can be
installed. Defaults to None and is ignored unless there is a
value for the commtype in supported_comm_options. This
keyword argument is ignored if skip_config is False.
libraries (list, optional): External libraries that are required
by the specified commtype. Defaults to None and is ignored
unless there is a value for the commtype in supported_comm_options.
This keyword argument is ignored if skip_config is False.
**kwargs: Additional keyword arguments are passed to either
is_comm_installed for the base languages, supported languages,
or is_library_installed as appropriate.
Returns:
bool: True if a comm is installed for this language.
"""
# If there are base_languages for this language, use that language's
# driver to check for comm installation.
if len(cls.base_languages) > 0:
out = True
for x in cls.base_languages:
if not out: # pragma: no cover
break
out = import_component('model', x).is_comm_installed(
commtype=commtype, skip_config=skip_config, **kwargs)
return out
if cls.comms_implicit:
if commtype is None:
return True
return (commtype in tools.get_supported_comm())
# Check for installation based on config option
if not skip_config:
installed_comms = cls.cfg.get(cls.language, 'commtypes', [])
if commtype is None:
return (len(installed_comms) > 0)
else:
return (commtype in installed_comms)
# Check for any comm
if commtype is None:
for c in cls.supported_comms:
if cls.is_comm_installed(commtype=c, skip_config=skip_config,
**kwargs):
return True
# Check that comm is explicitly supported
if commtype not in cls.supported_comms:
return False
# Set & pop keywords
for k, v in cls.supported_comm_options.get(commtype, {}).items():
if kwargs.get(k, None) is None:
kwargs[k] = v
platforms = kwargs.pop('platforms', None)
libraries = kwargs.pop('libraries', [])
# Check platforms
if (platforms is not None) and (platform._platform not in platforms):
return False # pragma: windows
# Check libraries
if (libraries is not None):
for lib in libraries:
if not cls.is_library_installed(lib, **kwargs):
return False
# Check for server on RabbitMQ
if commtype in ['rmq', 'rmq_async']:
from yggdrasil.communication.RMQComm import check_rmq_server
if not check_rmq_server():
return False
return True
@classmethod
def configure(cls, cfg):
r"""Add configuration options for this language.
Args:
cfg (CisConfigParser): Config class that options should be set for.
Returns:
list: Section, option, description tuples for options that could not
be set.
"""
out = []
# Section and executable
if (cls.language is not None) and (not cfg.has_section(cls.language)):
cfg.add_section(cls.language)
# Executable type configuration
out += cls.configure_executable_type(cfg)
# Locate executable
if (((not cls.is_language_installed())
and (cls.executable_type is not None))): # pragma: debug
try:
exec_file = cls.language_executable()
if exec_file is not None:
fpath = tools.locate_file(
exec_file, directory_list=cls._executable_search_dirs)
if fpath:
cfg.set(cls.language, cls.executable_type, fpath)
except NotImplementedError:
pass
# Configure libraries
out += cls.configure_libraries(cfg)
# Only do additional configuration if no base languages
if not cls.base_languages:
# Installed comms
comms = []
for c in cls.supported_comms:
if cls.is_comm_installed(commtype=c, cfg=cfg, skip_config=True):
comms.append(c)
cfg.set(cls.language, 'commtypes', comms)
cls.after_registration(cls, cfg=cfg, second_pass=True)
return out
@classmethod
def configure_executable_type(cls, cfg):
r"""Add configuration options specific in the executable type
before the libraries are configured.
Args:
cfg (YggConfigParser): Config class that options should be set for.
Returns:
list: Section, option, description tuples for options that could not
be set.
"""
return []
@classmethod
def configure_libraries(cls, cfg):
r"""Add configuration options for external libraries in this language.
Args:
cfg (YggConfigParser): Config class that options should be set for.
Returns:
list: Section, option, description tuples for options that could not
be set.
"""
return []
def get_io_env(self, input_drivers=None, output_drivers=None):
r"""Get environment variables set by the input/output drivers.
Args:
input_drivers (list, optional): Input drivers. Defaults to the
yaml entry if not provided.
output_drivers (list, optional): Output drivers. Defaults to the
yaml entry if not provided.
Returns:
dict: Environment variables.
"""
if input_drivers is None:
input_drivers = self.yml.get('input_drivers', [])
if output_drivers is None:
output_drivers = self.yml.get('output_drivers', [])
out = {}
if self.copies > 1:
from yggdrasil.drivers.DuplicatedModelDriver import (
DuplicatedModelDriver)
base_name = DuplicatedModelDriver.get_base_name(self.name)
else:
base_name = self.name
for x in input_drivers + output_drivers:
if 'instance' in x:
model_env = x['instance'].model_env
if self.name in model_env:
out.update(model_env[self.name])
elif base_name in model_env:
out.update(model_env[base_name])
return out
@classmethod
def set_env_class(cls, existing=None, **kwargs):
r"""Set environment variables that are instance independent.
Args:
existing (dict, optional): Existing dictionary of environment
variables that new variables should be added to. Defaults
to a copy of os.environ.
**kwargs: Additional keyword arguments are ignored.
Returns:
dict: Environment variables for the model process.
"""
if existing is None: # pragma: no cover
existing = {}
existing.update(os.environ)
return existing
def set_env(self, existing=None, **kwargs):
r"""Get environment variables that should be set for the model process.
Args:
existing (dict, optional): Existing dictionary of environment
variables that new variables should be added to. Defaults
to a copy of os.environ.
**kwargs: Additional keyword arguments are passed to set_env_class.
Returns:
dict: Environment variables for the model process.
"""
from yggdrasil.config import ygg_cfg
if existing is None:
existing = {}
existing.update(copy.deepcopy(self.env))
existing.update(self.get_io_env())
env = self.set_env_class(existing=existing, **kwargs)
env.update(YGG_SUBPROCESS="True",
YGG_MODEL_INDEX=str(self.model_index),
YGG_MODEL_LANGUAGE=self.language,
YGG_MODEL_COPIES=str(self.copies),
# YGG_PYTHON_EXEC=sys.executable,
YGG_DEFAULT_COMM=tools.get_default_comm(),
YGG_NCLIENTS=str(len(self.clients)))
if multitasking._on_mpi:
env['YGG_MPI_RANK'] = str(multitasking._mpi_rank)
if self.copies > 1:
from yggdrasil.drivers.DuplicatedModelDriver import (
DuplicatedModelDriver)
env['YGG_MODEL_COPY'] = str(self.copy_index)
env['YGG_MODEL_NAME'] = DuplicatedModelDriver.get_base_name(
self.name)
else:
env['YGG_MODEL_NAME'] = self.name
if self.allow_threading or (self.copies > 1):
env['YGG_THREADING'] = '1'
if isinstance(self.is_server, dict):
env['YGG_SERVER_INPUT'] = self.is_server['input']
env['YGG_SERVER_OUTPUT'] = self.is_server['output']
if self.logging_level:
env['YGG_MODEL_DEBUG'] = self.logging_level
replace = [k for k in env.keys() if ':' in k]
for k in replace:
env[k.replace(':', '__COLON__')] = env.pop(k)
if ygg_cfg.get('general', 'allow_multiple_omp', False):
env['KMP_DUPLICATE_LIB_OK'] = 'True'
return env
def before_start(self, no_queue_thread=False, **kwargs):
r"""Actions to perform before the run starts.
Args:
no_queue_thread (bool, optional): If True, the queue_thread is not
created/started. Defaults to False.
**kwargs: Keyword arguments are pased to run_model.
"""
# if multitasking._on_mpi:
# self.init_mpi_env()
self.model_process = self.run_model(**kwargs)
# Start thread to queue output
if not no_queue_thread:
self.queue_thread = multitasking.YggTaskLoop(
target=self.enqueue_output_loop,
name=self.name + '.EnqueueLoop')
self.queue_thread.start()
if multitasking._on_mpi:
self.init_mpi()
def queue_close(self):
r"""Close the queue for messages from the model process."""
self.model_process.stdout.close()
def queue_recv(self):
r"""Receive a message from the model process."""
return self.model_process.stdout.readline()
def enqueue_output_loop(self):
r"""Keep passing lines to queue."""
try:
line = self.queue_recv()
except BaseException as e: # pragma: debug
print(e)
line = ""
if (len(line) == 0):
self.queue_thread.set_break_flag()
try:
self.queue.put(self._exit_line)
except multitasking.AliasDisconnectError: # pragma: debug
self.error("Queue disconnected")
self.debug("End of model output")
try:
self.queue_close()
except BaseException: # pragma: debug
pass
else:
try:
self.queue.put(line.decode('utf-8'))
except BaseException as e: # pragma: debug
warnings.warn("Error in printing output: %s" % e)
def before_loop(self):
r"""Actions before loop."""
self.debug('Running %s from %s with cwd %s and env %s',
self.model_command(), os.getcwd(), self.working_dir,
pformat(self.env))
# def init_mpi_env(self):
# r"""Receive env information to the partner model."""
# self.env = self.recv_mpi(tag=self._mpi_tags['ENV'])
def init_mpi(self):
r"""Initialize MPI communicator."""
if self._mpi_rank == 0:
self._mpi_comm = None
else:
self.recv_mpi(tag=self._mpi_tags['START'])
self._mpi_requests['stopped'] = multitasking.MPIRequestWrapper(
self.recv_mpi(tag=self._mpi_tags['STOP_RANKX'],
dont_block=True))
def send_mpi(self, msg, tag=0, dont_block=False):
r"""Send an MPI message."""
self.debug("send %d (%d) [%s]: %s (blocking=%s)", tag,
self._mpi_tag + tag, self._inv_mpi_tags[tag],
msg, not dont_block)
kws = {'dest': self._mpi_partner_rank, 'tag': (self._mpi_tag + tag)}
if dont_block: # pragma: debug
# return self._mpi_comm.isend(msg, **kws)
raise NotImplementedError("Non-blocking MPI send not tested.")
else:
return self._mpi_comm.send(msg, **kws)
def recv_mpi(self, tag=0, dont_block=False):
r"""Receive an MPI message."""
self.debug('recv %d (%d) [%s] (blocking=%s)', tag,
self._mpi_tag + tag, self._inv_mpi_tags[tag],
not dont_block)
kws = {'source': self._mpi_partner_rank, 'tag': (self._mpi_tag + tag)}
if dont_block:
return self._mpi_comm.irecv(**kws)
else:
return self._mpi_comm.recv(**kws)
def stop_mpi_partner(self, msg=None, dest=0, tag=None):
r"""Send a message to stop the MPI partner model on the main process."""
if self._mpi_comm and (not self.check_mpi_request('stopping')):
if tag is None:
tag = self._mpi_tags['STOP_RANK0']
if msg is None:
if self.errors or self.model_process_returncode:
msg = 'ERROR'
else:
msg = 'STOPPING'
self.debug("stop_mpi_partner: %d, %s", tag, msg)
# Don't call test()
self._mpi_requests['stopping'] = multitasking.MPIRequestWrapper(
self.send_mpi(msg, tag=tag), completed=True)
def wait_on_mpi_request(self, name, timeout=False):
r"""Wait for a request to be completed.
Args:
name (str): Name that request was registered under.
Returns:
bool, str: Received message or False if the request does not
exist or is not complete.
"""
self.debug("Waiting on '%s' (timeout=%s)", name, timeout)
try:
out = self._mpi_requests[name].wait(timeout=timeout)
if out == 'ERROR': # pragma: debug
self.errors.append(out)
return out
except asyncio.TimeoutError: # pragma: debug
self.info("Timeout for MPI '%s' request", name)
def check_mpi_request(self, name):
r"""Check if a request has been completed.
Args:
name (str): Name that request was registered under.
Returns:
bool, str: Received message or False if the request does not
exist or is not complete.
"""
if self._mpi_comm and (name in self._mpi_requests):
out, msg = self._mpi_requests[name].test()
if out and (msg == 'ERROR'): # pragma: debug
self.errors.append(msg)
return out
return False
def set_break_flag(self, *args, **kwargs):
r"""Stop the model loop."""
self.stop_mpi_partner()
super(ModelDriver, self).set_break_flag(*args, **kwargs)
def run_loop(self):
r"""Loop to check if model is still running and forward output."""
# Continue reading until there is not any output
if self.model_process_returncode:
self.errors.append(self.model_process_returncode)
if self.check_mpi_request('stopped'):
self.debug("Stop requested by MPI partner.")
self.set_break_flag()
try:
line = self.queue.get_nowait()
except Empty:
# This sleep is necessary to allow changes in queue without lock
self.sleep()
return
except multitasking.AliasDisconnectError: # pragma: debug
self.error("Queue disconnected")
self.set_break_flag()
else:
if (line == self._exit_line) or self.check_mpi_request('stopped'):
self.debug("No more output")
self.set_break_flag()
else:
self.print_encoded(line, end="")
sys.stdout.flush()
def run_finally(self):
r"""Actions to perform in finally clause of try/except wrapping
run."""
# Ensure the MPI partner gets cleaned up following an error
self.stop_mpi_partner()
super(ModelDriver, self).run_finally()
def after_loop(self):
r"""Actions to perform after run_loop has finished. Mainly checking
if there was an error and then handling it."""
self.debug('')
self.stop_mpi_partner()
if self.queue_thread is not None:
self.queue_thread.join(self.sleeptime)
if self.queue_thread.is_alive():
self.debug("Queue thread still alive")
# Loop was broken from outside, kill the queueing thread
self.kill_process()
return
self.wait_process(self.timeout, key_suffix='.after_loop')
self.kill_process()
self.debug(("Closing input/output drivers:\n"
"\tinput: %s\n\toutput: %s")
% ([drv['name'] for drv in
self.yml.get('input_drivers', [])],
[drv['name'] for drv in
self.yml.get('output_drivers', [])]))
for drv in self.yml.get('input_drivers', []):
if 'instance' in drv:
if self.language == 'mpi':
drv['instance'].wait(self.timeout)
drv['instance'].on_model_exit('output', self.name,
errors=self.errors)
for drv in self.yml.get('output_drivers', []):
if 'instance' in drv:
if self.language == 'mpi':
drv['instance'].wait(self.timeout)
drv['instance'].on_model_exit('input', self.name,
errors=self.errors)
@property
def io_errors(self):
r"""list: Errors produced by input/output drivers to this model."""
errors = []
for drv in self.yml.get('input_drivers', []):
if 'instance' in drv:
errors += drv['instance'].errors
for drv in self.yml.get('output_drivers', []):
if 'instance' in drv:
errors += drv['instance'].errors
return errors
@property
def model_process_complete(self):
r"""bool: Has the process finished or not. Returns True if the process
has not started."""
if self.model_process is None: # pragma: debug
return True
return (self.model_process.poll() is not None)
@property
def model_process_returncode(self):
r"""int: Return code for the model process where non-zero values
indicate that there was an error."""
if self.model_process_complete and (self.model_process is not None):
return self.model_process.returncode
return 0
def wait_process(self, timeout=None, key=None, key_suffix=None):
r"""Wait for some amount of time for the process to finish.
Args:
timeout (float, optional): Time (in seconds) that should be waited.
Defaults to None and is infinite.
key (str, optional): Key that should be used to register the timeout.
Defaults to None and set based on the stack trace.
Returns:
bool: True if the process completed. False otherwise.
"""
if not self.was_started: # pragma: debug
return True
return self.wait_on_function(lambda: self.model_process_complete,
timeout=timeout, key_level=1, key=key,
key_suffix=key_suffix)
def kill_process(self):
r"""Kill the process running the model, checking return code."""
if not self.was_started: # pragma: debug
self.debug('Process was never started.')
self.set_break_flag()
self.event_process_kill_called.set()
self.event_process_kill_complete.set()
if self.event_process_kill_called.is_set(): # pragma: debug
self.debug('Process has already been killed.')
return
self.event_process_kill_called.set()
with self.lock:
self.debug('')
ignore_error_code = False
if not self.model_process_complete: # pragma: debug
self.debug("Process is still running. Killing it.")
try:
self.model_process.kill()
self.debug("Waiting %f s for process to be killed",
self.timeout)
self.wait_process(self.timeout, key_suffix='.kill_process')
except BaseException: # pragma: debug
self.exception("Error killing model process")
if not self.has_sent_messages:
ignore_error_code = True
assert(self.model_process_complete)
if (((self.model_process_returncode != 0)
and (not ignore_error_code))):
self.error(("return code of %s indicates model error. "
"(sent messages: %s)"),
str(self.model_process_returncode),
self.n_sent_messages)
self.event_process_kill_complete.set()
if self.queue_thread is not None:
if not self.was_break: # pragma: debug
# Wait for messages to be printed
self.debug("Waiting for queue_thread to finish up.")
self.queue_thread.wait(self.timeout)
if self.queue_thread.is_alive(): # pragma: debug
self.debug("Setting break flag for queue_thread to finish up.")
self.queue_thread.set_break_flag()
self.queue_thread.wait(self.timeout)
try:
self.queue_close()
self.queue_thread.wait(self.timeout)
except BaseException: # pragma: debug
self.exception("Closed during concurrent action")
if self.queue_thread.is_alive(): # pragma: debug
self.error("Queue thread was not terminated.")
def graceful_stop(self):
r"""Gracefully stop the driver."""
self.debug('')
if self.has_sent_messages:
self.wait_process(self.timeout, key_suffix='.graceful_stop')
super(ModelDriver, self).graceful_stop()
def cleanup_products(self):
r"""Remove products created in order to run the model."""
if self.overwrite and (not self.preserve_cache):
self.remove_products()
self.restore_files()
def cleanup(self):
r"""Remove compile executable."""
self.cleanup_products()
super(ModelDriver, self).cleanup()
def restore_files(self):
r"""Restore modified files to their original form."""
for (original, modified) in self.modified_files:
if os.path.isfile(original):
os.remove(modified)
shutil.move(original, modified)
def remove_products(self):
r"""Delete products produced during the process of running the model."""
products = self.products
source_products = self.source_products + self.wrapper_products
remove_products(products, source_products)
@classmethod
def cleanup_dependencies(cls, products=[], verbose=False):
r"""Cleanup dependencies."""
for x in products:
if os.path.isfile(x):
if verbose: # pragma: debug
print("Removing %s" % x)
os.remove(x)
# Methods for automated model wrapping
@classmethod
def run_code(cls, lines, process_kwargs={}, **kwargs):
r"""Run code by first writing it as an executable and then calling
the driver.
Args:
lines (list): Lines of code to be wrapped as an executable.
process_kwargs (dict, optional): Keyword arguments that should
be passed to run_model. Defaults to {}.
**kwargs: Additional keyword arguments are passed to the
write_executable method.
"""
name = 'test_code_%s' % str(uuid.uuid4())[:13].replace('-', '_')
working_dir = os.getcwd()
code_dir = tempfile.gettempdir()
# code_dir = working_dir
fname = os.path.join(code_dir, name + cls.get_language_ext()[0])
lines = cls.write_executable(lines, **kwargs)
with open(fname, 'w') as fd:
fd.write('\n'.join(lines))
inst = None
try:
assert(os.path.isfile(fname))
inst = cls(name, [fname], working_dir=working_dir)
inst.run_model(return_process=False, **process_kwargs)
except BaseException: # pragma: debug
logger.error('Failed generated code:\n%s' % '\n'.join(lines))
raise
finally:
if os.path.isfile(fname):
os.remove(fname)
if inst is not None:
inst.cleanup()
@classmethod
def format_function_param(cls, key, default=None, replacement=None,
ignore_method=False, **kwargs):
r"""Return the formatted version of the specified key.
Args:
key (str): Key in cls.function_param mapping that should be
formatted.
default (str, optional): Format that should be returned if key
is not in cls.function_param. Defaults to None.
replacement (str, optional): Format that should be used instead
of the one in cls.function_param. Defaults to None.
**kwargs: Additional keyword arguments are used in formatting the
request function parameter.
Returns:
str: Formatted string.
Raises:
NotImplementedError: If key is not in cls.function_param and default
is not set.
"""
if replacement is not None:
fmt = replacement
elif (not ignore_method) and hasattr(cls, 'format_function_param_%s' % key):
return getattr(cls, 'format_function_param_%s' % key)(**kwargs)
else:
if (key not in cls.function_param) and (default is None):
raise NotImplementedError(("Language %s dosn't have an entry in "
"function_param for key '%s'")
% (cls.language, key))
fmt = cls.function_param.get(key, default)
return fmt.format(**kwargs)
@classmethod
def parse_var_definition(cls, io, value, outputs_in_inputs=None):
r"""Extract information about input/output variables from a
string definition.
Args:
io (str): Description of variables contained in the provided
string. Must be 'inputs' or 'outputs'.
value (str): String containing one or more variable definitions.
outputs_in_inputs (bool, optional): If True, the outputs are
presented in the function definition as inputs. Defaults
to False.
Returns:
list: List of information about the variables contained in
the provided string.
Raises:
AssertionError: If io is not 'inputs' or 'outputs'.
NotImplementedError: If the def_regex for the specified
io is not defined.
"""
if outputs_in_inputs is None:
outputs_in_inputs = cls.outputs_in_inputs
assert(io in ['inputs', 'outputs'])
if ('%s_def_regex' % io) not in cls.function_param: # pragma: debug
raise NotImplementedError(
("'%s_def_regex' not defined for "
"language %s.") % (io, cls.language))
if 'multiple_outputs' in cls.function_param:
multi_re = cls.function_param['multiple_outputs']
for x in '[]()':
multi_re = multi_re.replace(x, '\\' + x)
multi_re = multi_re.format(outputs='(.*?)')
match = re.search(multi_re, value)
if match is not None:
value = match.group(1)
new_val = []
io_re = cls.format_function_param('%s_def_regex' % io)
for i, ivar in enumerate(cls.split_variables(value)):
igrp = {'name': ivar}
x = re.search(io_re, ivar)
if x is not None:
igrp = x.groupdict()
for k in list(igrp.keys()):
if igrp[k] is None:
del igrp[k]
if 'native_type' in igrp:
igrp['native_type'] = igrp['native_type'].replace(' ', '')
igrp['datatype'] = cls.get_json_type(igrp['native_type'])
igrp['position'] = i
if (io == 'outputs') and outputs_in_inputs:
igrp = cls.input2output(igrp)
new_val.append(igrp)
return new_val
@classmethod
def parse_function_definition(cls, model_file, model_function,
contents=None, match=None,
expected_outputs=[], outputs_in_inputs=None):
r"""Get information about the inputs & outputs to a model from its
defintition if possible.
Args:
model_file (str): Full path to the file containing the model
function's declaration.
model_function (str): Name of the model function.
contents (str, optional): String containing the function definition.
If not provided, the function definition is read from model_file.
match (re.Match, optional): Match object for the function regex. If
not provided, a search is performed using function_def_regex.
expected_outputs (list, optional): List of names or variable
information dictionaries for outputs that are expected
to be extracted from the function's definition. This
variable is only used if outputs_in_inputs is True and
outputs are not extracted from the function's defintion
using the regex for this language. Defaults to [].
outputs_in_inputs (bool, optional): If True, the outputs are
presented in the function definition as inputs. Defaults
to False.
Returns:
dict: Parameters extracted from the function definitions.
"""
if outputs_in_inputs is None:
outputs_in_inputs = cls.outputs_in_inputs
out = {}
if match or ('function_def_regex' in cls.function_param):
if not match:
function_regex = cls.format_function_param(
'function_def_regex', function_name=model_function)
if contents is None:
with open(model_file, 'r') as fd:
contents = fd.read()
match = re.search(function_regex, contents)
if not match: # pragma: debug
raise RuntimeError(("Could not find function match in file:\n"
"%s\nfor regex:\nr'%s'")
% (pformat(contents), function_regex))
# Match brackets to determine where the function definition is
if isinstance(cls.brackets, tuple):
assert(len(cls.brackets) == 2)
contents = match.group(0)
counts = {k: 0 for k in cls.brackets}
first_zero = 0
re_brackets = r'[\%s\%s]' % cls.brackets
for x in re.finditer(re_brackets, contents):
counts[x.group(0)] += 1
if (((counts[cls.brackets[0]] > 0)
and (counts[cls.brackets[0]]
== counts[cls.brackets[1]]))):
first_zero = x.span(0)[1]
break
assert((first_zero == 0) or (first_zero == len(contents)))
# This is currently commented as regex's are
# sufficient so far, but this may be needed in the
# future to isolate single definitions.
# if (first_zero != 0) and first_zero != len(contents):
# contents = contents[:first_zero]
# match = re.search(function_regex, contents)
# assert(match)
out = match.groupdict()
for k in list(out.keys()):
if out[k] is None:
del out[k]
for io in ['inputs', 'outputs']:
if io in out:
out[io] = cls.parse_var_definition(
io, out[io], outputs_in_inputs=outputs_in_inputs)
out['model_file'] = model_file
if outputs_in_inputs and expected_outputs and (not out.get('outputs', False)):
missing_expected_outputs = []
for o in expected_outputs:
if isinstance(o, dict):
o = o['name']
missing_expected_outputs.append(o)
out['outputs'] = []
for x in out['inputs']:
if x['name'] not in missing_expected_outputs:
continue
missing_expected_outputs.remove(x['name'])
out['outputs'].append(cls.input2output(x))
if missing_expected_outputs: # pragma: debug
raise ValueError(("Could not locate %d output "
"variable(s) in input: %s")
% (len(missing_expected_outputs),
missing_expected_outputs))
for x in out['outputs']:
out['inputs'].remove(x)
if out.get('flag_var', None):
flag_var = {'name': out.pop('flag_var'),
'datatype': {'type': 'flag'}}
if out.get('flag_type', None):
flag_var['native_type'] = out.pop('flag_type').replace(' ', '')
flag_var['datatype'] = cls.get_json_type(flag_var['native_type'])
out['flag_var'] = flag_var
cls.check_flag_var(out, outputs_in_inputs=outputs_in_inputs)
return out
@classmethod
def check_flag_var(cls, info, outputs_in_inputs=None):
r"""Check if the flag variable should be treated as an output.
Args:
info (dict): Information about the function.
outputs_in_inputs (bool, optional): If True, the outputs are
presented in the function definition as inputs. Defaults
to False.
"""
if outputs_in_inputs is None: # pragma: debug
outputs_in_inputs = cls.outputs_in_inputs
flag_t = cls.type_map['flag']
if (((info.get('flag_var', {}).get('native_type', flag_t) != flag_t)
or (not outputs_in_inputs))):
if info.get('outputs', []): # pragma: debug
logger.warn("Support for returning outputs via parameter(s) "
"and return value is not yet support. The return "
"value will be assumed to be a flag indicating "
"the success of the model.")
info['outputs_in_inputs'] = True
else:
info['outputs'] = [info.pop('flag_var')]
info['outputs_in_inputs'] = False
@classmethod
def channels2vars(cls, channels):
r"""Convert a list of channels to a list of variables.
Args:
channels (list): List of channel dictionaries.
Returns:
list: List of variables.
"""
if not isinstance(channels, list):
channels = [channels]
variables = []
for x in channels:
variables += x['vars']
def get_pos(x):
return x.get('position', 0)
variables = sorted(variables, key=get_pos)
return variables
@classmethod
def expand_server_io(cls, inputs, outputs, client_comms=[]):
r"""Update inputs/outputs w/ information about server that will be
using them.
Args:
inputs (list): List of model inputs including types.
outputs (list): List of model outputs including types.
client_comms (list, optional): List of the names of client comms
that should be removed from the list of outputs. Defaults to [].
"""
if client_comms:
warnings.warn("When wrapping a model function, client comms "
"must either be initialized outside the function, "
"pass a 'global_scope' parameter to the "
"comm initialization (e.g. Python, R, Matlab), "
"or use a 'WITH_GLOBAL_SCOPE' macro "
"(e.g. C, C++, Fortran) around the initialization "
"so that they are persistent "
"across calls and the call or recv/send methods "
"must be called explicitly (as opposed to the "
"function inputs/outputs which will be handled "
"by the wrapper). This model's client comms are:\n"
"\t%s" % client_comms)
# Replace server input w/ split input/output and remove client
# connections from inputs
for i, x in enumerate(inputs):
if x.get('server_replaces', False):
inputs[x['server_replaces']['input_index']] = (
x['server_replaces']['input'])
outputs.insert(x['server_replaces']['output_index'],
x['server_replaces']['output'])
rm_outputs = [i for i, x in enumerate(outputs)
if x['name'] in client_comms]
for i in rm_outputs[::-1]:
outputs.pop(i)
@classmethod
def preparse_function(cls, yml):
r"""Extract information about inputs and outputs based on the
function being wrapped.
Args:
yml (dict): Options that will be used to initialize the model.
Returns:
dict: Information about the parsed function.
"""
if 'function' not in yml:
return
if yml.get('is_server', False):
assert(isinstance(yml['is_server'], dict))
if cls.function_param is None:
raise ValueError(("Language %s is not parameterized "
"and so functions cannot be automatically "
"wrapped as a model.") % cls.language)
source_files = cls.identify_source_files(**yml)
if not source_files: # pragma: debug
raise ValueError("Could not identify any source files.")
model_function_file = source_files[0]
if not os.path.isfile(model_function_file): # pragma: debug
raise ValueError("Source file does not exist: '%s'"
% model_function_file)
# Update input/outputs based on parsed source code
client_comms = ['%s:%s_%s' % (yml['name'], x, yml['name'])
for x in yml.get('client_of', [])]
model_function_inputs = copy.copy(yml.get('inputs', []))
model_function_outputs = copy.copy(yml.get('outputs', []))
cls.expand_server_io(
model_function_inputs, model_function_outputs,
client_comms=client_comms)
expected_outputs = []
for x in model_function_outputs:
expected_outputs += x.get('vars', [])
model_outputs_in_inputs = yml.get('outputs_in_inputs', None)
model_function_info = cls.parse_function_definition(
model_function_file, yml['function'],
expected_outputs=expected_outputs,
outputs_in_inputs=model_outputs_in_inputs)
if model_outputs_in_inputs is None:
model_outputs_in_inputs = model_function_info.get(
'outputs_in_inputs', None)
model_flag = cls.update_io_from_function(
model_function_info, yml['function'],
inputs=model_function_inputs,
outputs=model_function_outputs,
iter_function_over=yml.get('iter_function_over', []))
yml['preparsed_function'] = {
'model_file': model_function_info,
'model_function': yml['function'],
'inputs': model_function_inputs,
'outputs': model_function_outputs,
'model_flag': model_flag,
'outputs_in_inputs': model_outputs_in_inputs,
'copies': yml.get('copies', 1),
'iter_function_over': yml.get('iter_function_over', []),
'skip_update_io': True}
return yml['preparsed_function']
@classmethod
def update_io_from_function(cls, model_file, model_function,
inputs=[], outputs=[], contents=None,
outputs_in_inputs=None, iter_function_over=[]):
r"""Update inputs/outputs from the function definition.
Args:
model_file (str): Full path to the file containing the model
function's declaration.
model_function (str): Name of the model function.
inputs (list, optional): List of model inputs including types.
Defaults to [].
outputs (list, optional): List of model outputs including types.
Defaults to [].
contents (str, optional): Contents of file to parse rather than
re-reading the file. Defaults to None and is ignored.
outputs_in_inputs (bool, optional): If True, the outputs are
presented in the function definition as inputs. Defaults
to False.
iter_function_over (array, optional): Variable(s) that should be
received or sent as an array, but iterated over. Defaults to
an empty array and is ignored.
Returns:
dict, None: Flag variable used by the model. If None, the
model does not use a flag variable.
"""
# Read info from the source code
if (((isinstance(model_file, str) and os.path.isfile(model_file))
or (contents is not None))): # pragma: debug
expected_outputs = []
for x in outputs:
expected_outputs += x.get('vars', [])
info = cls.parse_function_definition(model_file, model_function,
contents=contents,
expected_outputs=expected_outputs)
logger.warn("The new execution pattern reuses the parsed "
"source code parameters. Double check results:\n%s."
% pformat(info))
elif isinstance(model_file, dict):
info = model_file
else:
info = {"inputs": [], "outputs": []}
if outputs_in_inputs is None: # pragma: debug
outputs_in_inputs = info.get('outputs_in_inputs',
cls.outputs_in_inputs)
info_map = {io: OrderedDict([(x['name'], x) for x in info.get(io, [])])
for io in ['inputs', 'outputs']}
# Determine flag variable
flag_var = None
if info.get('flag_var', None):
flag_var = dict(info['flag_var'], name='model_flag')
# Check for vars matching names of input/output channels
for io, io_var in zip(['inputs', 'outputs'], [inputs, outputs]):
if (io == 'outputs') and outputs_in_inputs:
io_map = info_map['inputs']
else:
io_map = info_map[io]
for x in io_var:
if x.get('vars', []):
continue
var_name = x['name'].split(':')[-1]
if var_name in io_map:
x['vars'] = [var_name]
for k in ['length', 'shape', 'ndim']:
kvar = '%s_var' % k
if kvar in io_map[var_name]:
x['vars'].append(io_map[var_name][kvar])
# Move variables if outputs in inputs
if outputs_in_inputs:
if ((((len(inputs) + len(outputs)) == len(info.get('inputs', [])))
and (len(info.get('outputs', [])) == 0))):
for i, vdict in enumerate(info['inputs'][:len(inputs)]):
inputs[i].setdefault('vars', [vdict['name']])
assert(inputs[i]['vars'] == [vdict['name']])
for i, vdict in enumerate(info['inputs'][len(inputs):]):
outputs[i].setdefault('vars', [vdict['name']])
assert(outputs[i]['vars'] == [vdict['name']])
for x in outputs:
for i, v in enumerate(x.get('vars', [])):
if v in info_map['inputs']:
info_map['outputs'][v] = cls.input2output(
info_map['inputs'].pop(v))
for io, io_var in zip(['inputs', 'outputs'], [inputs, outputs]):
for x in io_var:
x['channel_name'] = x['name']
x['channel'] = (x['name'].split(':', 1)[-1]
+ '_%s_channel' % io[:-1])
for i, v in enumerate(x.get('vars', [])):
if v in info_map[io]:
x['vars'][i] = info_map[io][v]
if (len(io_var) == 1) and info_map.get(io, False):
io_var[0].setdefault('vars', list(info_map[io].values()))
for x in io_var:
if 'vars' not in x:
x['vars'] = [copy.deepcopy(x)]
x['vars'][0]['name'] = x['name'].split(':', 1)[-1]
for v in x['vars']:
if isinstance(v.get('datatype', None), str):
v['datatype'] = {'type': v['datatype']}
if isinstance(x.get('datatype', None), str):
x['datatype'] = {'type': x['datatype']}
# Check for user defined length variables and add flag to
# length variables
for x in io_var:
for k in ['length', 'shape', 'ndim']:
for v in x['vars']:
if k + '_var' in v:
v[k + '_var'] = info_map[io][v[k + '_var']]
# v[k + '_var']['is_' + k + '_var'] = True
v[k + '_var']['is_length_var'] = True
else:
v[k + '_var'] = False
# Update datatypes
if cls.is_typed:
for x in io_var:
non_length = []
for v in x['vars']:
if not v.get('is_length_var', False):
non_length.append(v)
if ((x.get('datatype', None)
and (not is_default_typedef(x['datatype'])))):
if (len(non_length) == 1):
non_length[0]['datatype'] = x['datatype']
else:
# TODO: Remove types associated with length?
assert(x['datatype']['type'] == 'array')
assert(len(x['datatype']['items'])
== len(non_length))
for v, t in zip(non_length, x['datatype']['items']):
v['datatype'] = t
else:
if (len(non_length) == 1):
x['datatype'] = non_length[0]['datatype']
else:
x['datatype'] = {
'type': 'array',
'items': [v['datatype'] for v in non_length]}
x['datatype']['from_function'] = True
for v in x['vars']:
if 'native_type' not in v:
v['native_type'] = cls.get_native_type(**v)
# Update types based on iteration
for x in io_var:
for v in x.get('vars', [x]):
if v['name'] in iter_function_over:
v['iter_datatype'] = copy.deepcopy(v.get('datatype', {}))
if v.get('datatype', {}):
assert(v['datatype']['type'] == 'scalar')
v['datatype']['type'] = '1darray'
v.pop('native_type', None)
v['native_type'] = cls.get_native_type(**v)
# Finalize io variables
for x in inputs:
cls.finalize_function_io('input', x)
for x in outputs:
cls.finalize_function_io('output', x)
return flag_var
@classmethod
def finalize_function_io(cls, direction, x):
r"""Finalize info for an input/output channel following function
parsing.
Args:
direction (str): Direction of channel ('input' or 'output')
"""
assert(direction in ['input', 'output'])
@classmethod
def write_model_wrapper(cls, model_file, model_function,
inputs=[], outputs=[], model_flag=None,
outputs_in_inputs=None, verbose=False, copies=1,
iter_function_over=[], verbose_model=False,
skip_update_io=False, model_name=None):
r"""Return the lines required to wrap a model function as an integrated
model.
Args:
model_file (str): Full path to the file containing the model
function's declaration.
model_function (str): Name of the model function.
inputs (list, optional): List of model inputs including types.
Defaults to [].
outputs (list, optional): List of model outputs including types.
Defaults to [].
model_flag (dict, optional): Information about the flag that
should be used to track the success of yggdrasil send/recv
calls. This should only be provided if update_io_from_function
has already been called. Defaults to None and is determined
by update_io_from_function.
outputs_in_inputs (bool, optional): If True, the outputs are
presented in the function definition as inputs. Defaults
to the class attribute outputs_in_inputs.
verbose (bool, optional): If True, the contents of the created file
are displayed. Defaults to False.
copies (int, optional): Number of times the model driver is
duplicated. If more than one, no error will be raised in the
event there is never a call the the function. Defaults to 1.
iter_function_over (array, optional): Variable(s) that should be
received or sent as an array, but iterated over. Defaults to
an empty array and is ignored.
skip_update_io (bool, optional): If True, update_io_from_function
will not be called. Defaults to False.
verbose_model (bool, optional): If True, print statements will
be added after every line in the model. Defaults to False.
model_name (str, optional): Name given to the model. Defaults to
None.
Returns:
list: Lines of code wrapping the provided model with the necessary
code to run it as part of an integration.
"""
if outputs_in_inputs is None:
outputs_in_inputs = cls.outputs_in_inputs
# TODO: Determine how to encode dependencies on external variables in models
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
# Update types based on the function definition for typed languages
if not skip_update_io:
model_flag = cls.update_io_from_function(
model_file, model_function,
inputs=inputs, outputs=outputs,
outputs_in_inputs=outputs_in_inputs,
iter_function_over=iter_function_over)
if isinstance(model_file, dict):
model_file = model_file['model_file']
# Update types based on iteration
iter_function_idx = None
iter_ivars = []
iter_ovars = []
if iter_function_over:
iter_function_idx = {'name': 'idx_func_iter',
'datatype': {'type': 'int'}}
if cls.zero_based:
iter_function_idx['begin'] = int(0)
else:
iter_function_idx['begin'] = int(1)
for x in inputs:
iter_ivars += [v for v in x.get('vars', [x])
if v['name'] in iter_function_over]
if not iter_ivars: # pragma: debug
raise RuntimeError("The iter_function_over model "
"parameter must include an input to "
"iterate over. To expand output arrays "
"into component elements, use the "
"'iterate' transformation.")
for x in outputs:
iter_ovars += [v for v in x.get('vars', [x])
if v['name'] in iter_function_over]
if iter_ivars[0].get('length_var', False):
iter_function_idx['end'] = iter_ivars[0]['length_var']
for v in iter_ovars:
v['length_var'] = iter_ivars[0]['length_var']['name']
if isinstance(iter_function_idx['end'], dict):
iter_function_idx['end'] = iter_function_idx['end']['name']
else:
iter_function_idx['end'] = cls.format_function_param(
'len', variable=iter_ivars[0]['name'],
extra=iter_ivars[0])
for v in iter_ivars + iter_ovars:
v['iter_var'] = iter_function_idx
# Declare variables and flag, then define flag
lines = []
flag_var = {'name': 'flag', 'datatype': {'type': 'flag'}}
iter_var = {'name': 'first_iter', 'datatype': {'type': 'flag'}}
free_vars = []
definitions = []
if 'declare' in cls.function_param:
for x in inputs + outputs:
lines += cls.write_channel_decl(
x, definitions=definitions,
requires_freeing=free_vars)
lines += cls.write_declaration(flag_var,
definitions=definitions,
requires_freeing=free_vars)
lines += cls.write_declaration(iter_var,
definitions=definitions,
requires_freeing=free_vars)
if model_flag:
lines += cls.write_declaration(
model_flag, definitions=definitions,
requires_freeing=free_vars)
if iter_function_idx:
lines += cls.write_declaration(
iter_function_idx, definitions=definitions,
requires_freeing=free_vars)
for x in inputs + outputs:
for v in x.get('vars', [x]):
lines += cls.write_declaration(
v, definitions=definitions,
requires_freeing=free_vars)
lines += definitions
nline_preamble = len(lines)
lines.append(cls.format_function_param(
'assign', name=flag_var['name'],
value=cls.function_param.get(
'true_flag', cls.function_param['true'])))
lines.append(cls.format_function_param(
'assign', name=iter_var['name'],
value=cls.function_param.get(
'true_flag', cls.function_param['true'])))
# Declare/define input and output channels
for x in inputs:
lines += cls.write_channel_def('input',
requires_freeing=free_vars, **x)
for x in outputs:
lines += cls.write_channel_def('output',
requires_freeing=free_vars, **x)
# Receive inputs before loop
for x in inputs:
if x.get('outside_loop', False):
lines += cls.write_model_recv(x['channel'], x,
flag_var=flag_var)
# Loop
loop_lines = []
# Receive inputs
any_loop_inputs = False
loop_iter_var = iter_var
if copies > 1:
loop_iter_var = None
for x in inputs:
if not x.get('outside_loop', False):
any_loop_inputs = True
loop_lines += cls.write_model_recv(x['channel'], x,
flag_var=flag_var,
iter_var=loop_iter_var,
allow_failure=True)
# Prepare output array
if iter_function_over:
for v in iter_ivars:
if v['name'] in iter_function_over:
loop_lines += cls.write_finalize_iiter(v)
for v in iter_ovars:
if v['name'] in iter_function_over:
loop_lines += cls.write_initialize_oiter(v)
# Call model
loop_lines += cls.write_model_function_call(
model_function, model_flag, inputs, outputs,
outputs_in_inputs=outputs_in_inputs,
iter_function_idx=iter_function_idx)
# Finalize output array
if iter_function_over:
for v in iter_ovars:
if v['name'] in iter_function_over:
loop_lines += cls.write_finalize_oiter(v)
# Send outputs
for x in outputs:
if not x.get('outside_loop', False):
loop_lines += cls.write_model_send(x['channel'], x,
flag_var=flag_var)
loop_lines.append(cls.format_function_param(
'assign', name=iter_var['name'],
value=cls.function_param.get('false_flag',
cls.function_param['false'])))
# Add break if there are not any inputs inside the loop
if not any_loop_inputs:
loop_lines.append(cls.format_function_param(
'assign', name=flag_var['name'],
value=cls.function_param.get(
'false_flag', cls.function_param['false'])))
# Add loop in while block
flag_cond = cls.format_function_param('flag_cond',
default='{flag_var}',
flag_var=flag_var['name'])
lines += cls.write_while_loop(flag_cond, loop_lines)
# Send outputs after loop
for x in outputs:
if x.get('outside_loop', False):
lines += cls.write_model_send(x['channel'], x,
flag_var=flag_var)
# Free variables
for x in free_vars:
lines += cls.write_free(x)
# Add prints
if verbose_model: # pragma: debug
idx = len(lines) - 1
while (idx > nline_preamble):
if 'else' not in lines[idx]:
indent = ' ' * (len(lines[idx])
- len(lines[idx].lstrip()))
lines.insert(idx, indent + cls.format_function_param(
'print', message=("%s: line %d" % (model_file, idx))))
idx -= 1
# Wrap as executable with interface & model import
prefix = None
if 'interface' in cls.function_param:
ygglib = cls.interface_library
if ygglib in cls.internal_libraries:
ygglib = cls.internal_libraries[ygglib]['source']
if cls.interface_inside_exec:
lines.insert(0, cls.format_function_param(
'interface', interface_library=ygglib))
else:
prefix = [cls.format_function_param(
'interface', interface_library=ygglib)]
out = cls.write_executable(lines, prefix=prefix,
model_name=model_name,
imports={'filename': model_file,
'function': model_function})
if verbose: # pragma: debug
logger.info('\n' + '\n'.join(out))
else:
logger.debug('\n' + '\n'.join(out))
return out
@classmethod
def write_channel_decl(cls, var, **kwargs):
r"""Write a channel declaration.
Args:
var (dict): Information dictionary for the channel.
being declared.
**kwargs: Additional keyword arguments are passed to class's
write_declaration.
Returns:
list: The lines declaring the variable.
"""
out = []
if not cls.dont_declare_channel:
out = cls.write_declaration(
{'name': var['channel'], 'type': 'comm'}, **kwargs)
if (((var.get('datatype', None) is not None)
and ('{channel_type}' in cls.function_param['input']))):
var['channel_type'] = '%s_type' % var['channel']
out += cls.write_type_decl(
var['channel_type'], var['datatype'],
definitions=kwargs.get('definitions', None),
requires_freeing=kwargs.get('requires_freeing', None))
return out
@classmethod
def write_type_decl(cls, name, datatype, name_base=None,
requires_freeing=None, definitions=None,
no_decl=False):
r"""Get lines declaring the datatype within the language.
Args:
name (str): Name of variable that should be declared.
datatype (dict): Type definition.
requires_freeing (list, optional): List that variables requiring
freeing should be appended to. Defaults to None.
definitions (list, optional): Existing list that variable
definitions should be added to. Defaults to None if not
provided and definitions will be included in the returned
lines.
no_decl (bool, optional): If True, the variable is not
declared, but supporting variables will be. Defaults
to False.
Returns:
list: Lines required to define a type declaration.
"""
out = []
if name_base is None:
name_base = name
if datatype['type'] == 'array':
if 'items' in datatype:
assert(isinstance(datatype['items'], list))
out += cls.write_declaration(
{'name': '%s_items' % name_base,
'datatype': {
'type': '1darray', 'subtype': 'dtype',
'length': len(datatype['items'])}},
definitions=definitions,
requires_freeing=requires_freeing)
for i, x in enumerate(datatype['items']):
# Prevent recusion
x_copy = copy.deepcopy(x)
x_copy.pop('items', None)
x_copy.pop('properties', None)
out += cls.write_type_decl(
None, x_copy,
name_base=('%s_item%d' % (name_base, i)),
definitions=definitions,
requires_freeing=requires_freeing,
no_decl=True)
elif datatype['type'] == 'object':
if 'properties' in datatype:
assert(isinstance(datatype['properties'], dict))
precision = 0
if datatype['properties']:
precision = max([len(k) for k in
datatype['properties'].keys()])
precision = max(80, precision)
out += cls.write_declaration(
{'name': '%s_keys' % name_base,
'datatype': {
'type': '1darray', 'subtype': 'bytes',
'length': len(datatype['properties']),
'precision': precision}},
definitions=definitions,
requires_freeing=requires_freeing)
out += cls.write_declaration(
{'name': '%s_vals' % name_base,
'datatype': {
'type': '1darray', 'subtype': 'dtype',
'length': len(datatype['properties'])}},
definitions=definitions,
requires_freeing=requires_freeing)
for i, (k, v) in enumerate(datatype['properties'].items()):
# Prevent recusion
v_copy = copy.deepcopy(v)
v_copy.pop('items', None)
v_copy.pop('properties', None)
out += cls.write_type_decl(
None, v_copy,
name_base=('%s_prop%d' % (name_base, i)),
requires_freeing=requires_freeing,
definitions=definitions,
no_decl=True)
elif datatype['type'] == 'ndarray':
if 'shape' in datatype:
out += cls.write_declaration(
{'name': '%s_shape' % name_base,
'datatype': {
'type': '1darray', 'subtype': 'int',
'precision': 64, 'length': len(datatype['shape'])}},
definitions=definitions,
requires_freeing=requires_freeing)
elif datatype['type'] in (['ply', 'obj', '1darray', 'scalar',
'boolean', 'null', 'number', 'integer',
'string', 'class', 'function', 'instance',
'schema', 'any']
+ list(constants.VALID_TYPES.keys())):
pass
else: # pragma: debug
raise ValueError(("Cannot create %s version of type "
"'%s'") % (cls.language, datatype['type']))
if not no_decl:
out += cls.write_declaration(
{'name': name, 'type': 'dtype'})
return out
@classmethod
def write_type_def(cls, name, datatype, name_base=None,
use_generic=False):
r"""Get lines declaring the data type within the language.
Args:
name (str): Name of variable that definition should be stored in.
datatype (dict): Type definition.
use_generic (bool, optional): If True variables serialized
and/or deserialized by the type will be assumed to be
generic objects. Defaults to False.
Returns:
list: Lines required to define a type definition.
"""
out = []
fmt = None
keys = {}
if use_generic:
keys['use_generic'] = cls.function_param['true']
else:
keys['use_generic'] = cls.function_param['false']
typename = datatype['type']
if name_base is None:
name_base = name
if datatype['type'] == 'array':
if 'items' in datatype:
assert(isinstance(datatype['items'], list))
keys['nitems'] = len(datatype['items'])
keys['items'] = '%s_items' % name_base
if cls.zero_based:
idx_offset = 0
else:
idx_offset = 1
for i, x in enumerate(datatype['items']):
# Prevent recusion
x_copy = copy.deepcopy(x)
x_copy.pop('items', None)
x_copy.pop('properties', None)
out += cls.write_type_def(
cls.format_function_param(
'index', variable=keys['items'],
index=(i + idx_offset)), x_copy,
name_base=('%s_item%d' % (name_base, i)),
use_generic=use_generic)
else:
keys['nitems'] = 0
keys['items'] = cls.function_param['null']
keys['use_generic'] = cls.function_param['true']
elif datatype['type'] == 'object':
keys['use_generic'] = cls.function_param['true']
if 'properties' in datatype:
assert(isinstance(datatype['properties'], dict))
keys['nitems'] = len(datatype['properties'])
keys['keys'] = '%s_keys' % name_base
keys['values'] = '%s_vals' % name_base
if cls.zero_based:
idx_offset = 0
else:
idx_offset = 1
for i, (k, v) in enumerate(datatype['properties'].items()):
# Prevent recusion
v_copy = copy.deepcopy(v)
v_copy.pop('items', None)
v_copy.pop('properties', None)
out.append(cls.format_function_param(
'assign', value='\"%s\"' % k,
name=cls.format_function_param(
'index', variable=keys['keys'],
index=(i + idx_offset))))
out += cls.write_type_def(
cls.format_function_param(
'index', variable=keys['values'],
index=(i + idx_offset)), v_copy,
name_base=('%s_prop%d' % (name_base, i)),
use_generic=use_generic)
else:
keys['nitems'] = 0
keys['keys'] = cls.function_param['null']
keys['values'] = cls.function_param['null']
elif datatype['type'] in ['ply', 'obj']:
pass
elif datatype['type'] == '1darray':
for k in ['subtype', 'precision']:
keys[k] = datatype[k]
keys['precision'] = int(keys['precision'])
keys['length'] = datatype.get('length', '0')
keys['units'] = datatype.get('units', '')
elif datatype['type'] == 'ndarray':
for k in ['subtype', 'precision']:
keys[k] = datatype[k]
keys['precision'] = int(keys['precision'])
if 'shape' in datatype:
shape_var = '%s_shape' % name_base
if cls.zero_based:
idx_offset = 0
else:
idx_offset = 1
for i, x in enumerate(datatype['shape']):
out.append(cls.format_function_param(
'assign', value=x,
name=cls.format_function_param(
'index', variable=shape_var,
index=(i + idx_offset))))
keys['ndim'] = len(datatype['shape'])
keys['shape'] = shape_var
typename = 'ndarray_arr'
else:
keys['ndim'] = 0
keys['shape'] = cls.function_param['null']
keys['units'] = datatype.get('units', '')
elif (typename == 'scalar') or (typename in constants.VALID_TYPES):
keys['subtype'] = datatype.get('subtype', datatype['type'])
keys['units'] = datatype.get('units', '')
if keys['subtype'] in ['bytes', 'string', 'unicode']:
keys['precision'] = int(datatype.get('precision', 0))
else:
keys['precision'] = int(datatype['precision'])
typename = 'scalar'
elif datatype['type'] in ['boolean', 'null', 'number',
'integer', 'string']:
keys['type'] = datatype['type']
typename = 'default'
elif (typename in ['class', 'function']):
keys['type'] = typename
typename = 'pyobj'
elif typename in ['instance', 'any']:
keys['use_generic'] = cls.function_param['true']
typename = 'empty'
elif typename in ['schema']:
keys['use_generic'] = cls.function_param['true']
else: # pragma: debug
raise ValueError("Cannot create %s version of type '%s'"
% (cls.language, typename))
fmt = cls.format_function_param('init_type_%s' % typename, **keys)
out.append(cls.format_function_param('assign', name=name,
value=fmt))
return out
@classmethod
def write_channel_def(cls, key, datatype=None, **kwargs):
r"""Write an channel definition.
Args:
key (str): Entry in cls.function_param that should be used.
datatype (dict, optional): Data type associated with the channel.
Defaults to None and is ignored.
**kwargs: Additional keyword arguments are passed as parameters
to format_function_param.
Returns:
list: Lines required to declare and define an output channel.
"""
out = []
if (datatype is not None) and ('{channel_type}' in cls.function_param[key]):
kwargs['channel_type'] = '%s_type' % kwargs['channel']
out += cls.write_type_def(
kwargs['channel_type'], datatype,
use_generic=kwargs.get('use_generic', False))
dir_map = {'input': 'recv', 'output': 'send'}
try_keys = [dir_map[key] + '_converter', 'transform']
try_vals = []
if all([bool(kwargs.get(k, False)) for k in try_keys]): # pragma: debug
# TODO: Handling merger of the transforms in yaml or
# remove the *_converter options entirely
raise RuntimeError(("Transforms are specified in multiple "
"locations for this input: %s")
% str(try_keys))
for k in try_keys:
if k in kwargs:
v = kwargs[k]
if not isinstance(v, list):
v = [v]
try_vals += v
# This last transform is used because the others are assumed
# to be applied by the connection driver
if try_vals and isinstance(try_vals[-1], str):
try_key = '%s_%s' % (try_vals[-1], key)
if ((('python_interface' in cls.function_param)
and (try_key in cls.python_interface))):
kwargs['python_interface'] = cls.python_interface[try_key]
if ((('format_str' in kwargs)
and ('python_interface_format' in cls.function_param))):
key = 'python_interface_format'
kwargs['format_str'] = kwargs['format_str'].encode(
"unicode_escape").decode('utf-8')
else:
key = 'python_interface'
out += [cls.format_function_param(key, **kwargs)]
return out
@classmethod
def write_model_function_call(cls, model_function, flag_var, inputs, outputs,
outputs_in_inputs=None, on_failure=None,
format_not_flag_cond=None, format_flag_cond=None,
iter_function_idx=None):
r"""Write lines necessary to call the model function.
Args:
model_function (str): Handle of the model function that should be
called.
flag_var (str): Name of variable that should be used as a flag.
inputs (list): List of dictionaries describing inputs to the model.
outputs (list): List of dictionaries describing outputs from the model.
outputs_in_inputs (bool, optional): If True, the outputs are
presented in the function definition as inputs. Defaults
to the class attribute outputs_in_inputs.
on_failure (list, optional): Lines to be executed if the model
call fails. Defaults to an error message. This variable
is only used if flag_var is not None and outputs_in_inputs
is True.
format_not_flag_cond (str, optional): Format string that produces
a conditional expression that evaluates to False when the
model flag indicates a failure. Defaults to None and the
class's value for 'not_flag_cond' in function_param is used
if it exists. If it does not exist, format_flag_cond is used.
format_flag_cond (str, optional): Format string that produces
a conditional expression that evaluates to True when the
model flag indicates a success. Defaults to None and the
defaults class's value for 'flag_cond' in function_param is
used if it exists. If it does not exist, the flag is
directly evaluated as if it were a boolean.
iter_function_idx (dict, optional): Variable that serves as an
index to iterate over variables. Defaults to None.
Returns:
list: Lines required to carry out a call to a model function in
this language.
"""
if outputs_in_inputs is None: # pragma: debug
outputs_in_inputs = cls.outputs_in_inputs
func_inputs = cls.channels2vars(inputs)
func_outputs = cls.channels2vars(outputs)
if iter_function_idx:
for src in [func_inputs, func_outputs]:
for i, x in enumerate(src):
if 'iter_datatype' in x:
src[i] = dict(
x, datatype=x['iter_datatype'],
name=cls.format_function_param(
'index', variable=x['name'],
index=iter_function_idx['name'],
extra=x),
length_var=False)
if isinstance(flag_var, dict):
flag_var = flag_var['name']
out = cls.write_function_call(
model_function, inputs=func_inputs, outputs=func_outputs,
flag_var=flag_var, outputs_in_inputs=outputs_in_inputs)
if flag_var and outputs_in_inputs:
if (not format_flag_cond) and ('not_flag_cond' in cls.function_param):
flag_cond = cls.format_function_param(
'not_flag_cond', flag_var=flag_var,
replacement=format_not_flag_cond)
else: # pragma: debug
# flag_cond = '%s (%s)' % (
# cls.function_param['not'],
# cls.format_function_param(
# 'flag_cond', default='{flag_var}', flag_var=flag_var,
# replacement=format_flag_cond))
raise RuntimeError("Untested code below. Uncomment "
"at your own risk if you find "
"use case for it.")
if on_failure is None:
on_failure = [cls.format_function_param(
'error', error_msg="Model call failed.")]
out += cls.write_if_block(flag_cond, on_failure)
if iter_function_idx:
out = cls.write_for_loop(iter_function_idx['name'],
iter_function_idx['begin'],
iter_function_idx['end'],
out)
return out
@classmethod
def write_model_recv(cls, channel, recv_var, flag_var='flag',
iter_var=None, allow_failure=False,
alt_recv_function=None):
r"""Write a model receive call include checking the return flag.
Args:
channel (str): Name of variable that the channel being received from
was stored in.
recv_var (dict, list): Information of one or more variables that
receieved information should be stored in.
flag_var (str, optional): Name of flag variable that the flag should
be stored in. Defaults to 'flag',
iter_var (str, optional): Name of flag signifying when the
model is in it's first iteration. If allow_failure is
True and iter_var is provided, an error will be raised
if iter_var is True. Defaults to None.
allow_failure (bool, optional): If True, the returned lines will
call a break if the flag is False. Otherwise, the returned
lines will issue an error. Defaults to False.
alt_recv_function (str, optional): Alternate receive function
format string. Defaults to None and is ignored.
Returns:
list: Lines required to carry out a receive call in this language.
"""
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
recv_var_str = recv_var
if not isinstance(recv_var, str):
recv_var_par = cls.channels2vars(recv_var)
recv_var_str = cls.prepare_output_variables(
recv_var_par, in_inputs=cls.outputs_in_inputs,
for_yggdrasil=True)
else:
recv_var_par = cls.split_variables(recv_var_str)
expanded_recv_var = None
if (len(recv_var_par) > 1) and ('multiple_outputs' in cls.function_param):
expanded_recv_var = recv_var_str
recv_var_str = 'temp_%s' % recv_var_par[0]['name']
if isinstance(flag_var, dict):
flag_var = flag_var['name']
if isinstance(iter_var, dict):
iter_var = iter_var['name']
if cls.outputs_in_inputs:
inputs = [recv_var_str]
outputs = [flag_var]
else:
inputs = []
outputs = [flag_var, recv_var_str]
if cls.include_channel_obj:
inputs.insert(0, channel)
lines = cls.write_function_call(
cls.format_function_param('recv_function', channel=channel,
replacement=alt_recv_function),
inputs=inputs, outputs=outputs, include_arg_count=cls.include_arg_count)
if 'not_flag_cond' in cls.function_param:
flag_cond = cls.format_function_param('not_flag_cond',
flag_var=flag_var)
else:
flag_cond = '%s (%s)' % (
cls.function_param['not'],
cls.format_function_param('flag_cond', default='{flag_var}',
flag_var=flag_var))
fail_message = cls.escape_quotes(
"Could not receive %s." % recv_var_str)
if allow_failure:
fail_message = cls.escape_quotes(
'End of input from %s.' % recv_var_str)
if_block = [cls.format_function_param('print', message=fail_message),
cls.function_param.get('break', 'break')]
if iter_var is not None:
if_block = cls.write_if_block(
iter_var,
[cls.format_function_param(
'error', error_msg=cls.escape_quotes(
'No input from %s.' % recv_var_str))],
if_block)
else:
if_block = [cls.format_function_param('error', error_msg=fail_message)]
lines += cls.write_if_block(flag_cond, if_block)
# Check if single element should be expanded
if expanded_recv_var:
# lines.append(cls.format_function_param(
# 'print_generic', object=recv_var_str))
if 'expand_mult' in cls.function_param: # pragma: matlab
lines.append(cls.format_function_param(
'expand_mult', name=expanded_recv_var, value=recv_var_str))
elif 'assign_mult' in cls.function_param:
lines.append(cls.format_function_param(
'assign_mult', name=expanded_recv_var, value=recv_var_str))
else:
lines.append(cls.format_function_param(
'assign', name=expanded_recv_var, value=recv_var_str))
elif len(recv_var_par) == 1:
lines += cls.write_expand_single_element(recv_var_str)
return lines
@classmethod
def write_model_send(cls, channel, send_var, flag_var='flag',
allow_failure=False):
r"""Write a model send call include checking the return flag.
Args:
channel (str): Name of variable that the channel being sent to
was stored in.
send_var (dict, list): Information on one or more variables
containing information that will be sent.
flag_var (str, optional): Name of flag variable that the flag should
be stored in. Defaults to 'flag',
allow_failure (bool, optional): If True, the returned lines will
call a break if the flag is False. Otherwise, the returned
lines will issue an error. Defaults to False.
Returns:
list: Lines required to carry out a send call in this language.
"""
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
send_var_str = send_var
if not isinstance(send_var_str, str):
send_var_par = cls.channels2vars(send_var)
send_var_str = cls.prepare_input_variables(
send_var_par, for_yggdrasil=True)
if isinstance(flag_var, dict):
flag_var = flag_var['name']
if cls.include_channel_obj:
send_var_str = [channel, send_var_str]
lines = cls.write_function_call(
cls.format_function_param('send_function', channel=channel),
inputs=send_var_str,
outputs=flag_var, include_arg_count=cls.include_arg_count)
flag_cond = '%s (%s)' % (
cls.function_param['not'],
cls.format_function_param('flag_cond', default='{flag_var}',
flag_var=flag_var))
fail_message = cls.escape_quotes(
"Could not send %s." % send_var_str)
if allow_failure: # pragma: no cover
# This is not particularly useful, but is included for completion
if_block = [cls.format_function_param('print', message=fail_message),
cls.function_param.get('break', 'break')]
else:
if_block = [cls.format_function_param('error', error_msg=fail_message)]
lines += cls.write_if_block(flag_cond, if_block)
return lines
@classmethod
def write_print_var(cls, var, prefix_msg=None):
r"""Get the lines necessary to print a variable in this language.
Args:
var (dict): Variable information.
prefix_msg (str, optional): Message that should be printed
before the variable. Defaults to None and is ignored.
Returns:
list: Lines printing the specified variable.
"""
out = []
print_key = None
varname = var
if isinstance(var, dict):
varname = var['name']
typename = var.get(
'datatype',
{'type': var.get('type', None)}).get('type', None)
if ('print_%s' % typename) in cls.function_param:
print_key = ('print_%s' % typename)
elif 'print_generic' in cls.function_param:
print_key = 'print_generic'
elif 'print_generic' in cls.function_param:
print_key = 'print_generic'
if print_key:
if prefix_msg is not None:
out.append(cls.format_function_param(
'print', message=prefix_msg))
out += [cls.format_function_param(
print_key, object=varname)]
return out
@classmethod
def write_print_input_var(cls, var, **kwargs):
r"""Get the lines necessary to print an input variable in this
language.
Args:
var (dict): Variable information.
**kwargs: Additional keyword arguments are passed to write_print_var.
Returns:
list: Lines printing the specified variable.
"""
return cls.write_print_var(var, **kwargs)
@classmethod
def write_print_output_var(cls, var, in_inputs=False, **kwargs):
r"""Get the lines necessary to print an output variable in this
language.
Args:
var (dict): Variable information.
in_inputs (bool, optional): If True, the output variable
is passed in as an input variable to be populated.
Defaults to False.
**kwargs: Additional keyword arguments are passed to write_print_var.
Returns:
list: Lines printing the specified variable.
"""
return cls.write_print_var(var, **kwargs)
@classmethod
def write_function_def(cls, function_name, inputs=[], outputs=[],
input_var=None, output_var=None,
function_contents=[],
outputs_in_inputs=False,
opening_msg=None, closing_msg=None,
print_inputs=False, print_outputs=False,
skip_interface=False, function_keys=None,
verbose=False, **kwargs):
r"""Write a function definition.
Args:
function_name (str): Name fo the function being defined.
inputs (list, optional): List of inputs to the function.
Defaults to []. Ignored if input_var provided.
outputs (list, optional): List of outputs from the function.
Defaults to []. If not provided, no return call is
added to the function body. Ignored if output_var
provided.
input_var (str, optional): Full string specifying input in
the function definition. If not provided, this will be
created based on the contents of the inputs variable.
output_var (str, optional): Full string specifying output in
the function definition. If not provided, this will be
created based on the contents of the outputs variable.
function_contents (list, optional): List of lines comprising
the body of the function. Defaults to [].
outputs_in_inputs (bool, optional): If True, the outputs are
presented in the function definition as inputs. Defaults
to False.
opening_msg (str, optional): String that should be printed
before the function contents (and inputs if print_inputs
is True). Defaults to None and is ignored.
closing_msg (str, optional): String that should be printed
after the function contents (and outputs if print_outputs
is True). Defaults to None and is ignored.
print_inputs (bool, optional): If True, the input variables
will be printed before the function contents. Defaults
to False.
print_outputs (bool, optional): If True, the output variables
will be printed after the function contents. Defaults to
False.
skip_interface (bool, optional): If True, the line including
the interface will be skipped. Defaults to False.
function_keys (tuple, optional): 2 element tuple that
specifies the keys for the function_param entries that
should be used to begin & end a function definition.
Defaults to ('function_def_begin', function_def_end').
verbose (bool, optional): If True, the contents of the created file
are displayed. Defaults to False.
**kwargs: Additional keyword arguments are passed to
cls.format_function_param.
Returns:
list: Lines completing the function call.
Raises:
NotImplementedError: If the function_param attribute for the
class is not defined.
"""
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
if function_keys is None:
function_keys = ('function_def_begin', 'function_def_end')
out = []
interface_lines = []
if ('interface' in cls.function_param) and (not skip_interface):
ygglib = cls.interface_library
if ygglib in cls.internal_libraries:
ygglib = cls.internal_libraries[ygglib]['source']
interface_lines.append(cls.format_function_param(
'interface', interface_library=ygglib))
if not cls.interface_inside_exec:
out += interface_lines
flag_var = {}
if input_var is None:
input_var = cls.prepare_input_variables(
inputs, in_definition=True)
if output_var is None:
output_var = cls.prepare_output_variables(
outputs, in_inputs=outputs_in_inputs, in_definition=True)
print_input_lines = []
if print_inputs and inputs:
for x in inputs:
print_input_lines += cls.write_print_input_var(
x, prefix_msg=('INPUT[%s]:' % x['name']))
print_output_lines = []
if print_outputs and outputs:
for x in outputs:
print_output_lines += cls.write_print_output_var(
x, prefix_msg=('OUTPUT[%s]:' % x['name']),
in_inputs=outputs_in_inputs)
old_outputs = []
if outputs_in_inputs:
if output_var:
input_var = cls.prepare_input_variables(
[input_var, output_var])
flag_var = kwargs.get('flag_var', 'flag')
if isinstance(flag_var, str):
flag_var = {'name': flag_var}
flag_var.setdefault('datatype', 'flag')
flag_var.setdefault('value', cls.function_param.get(
'true_flag', cls.function_param['true']))
old_outputs = outputs
outputs = [flag_var]
output_var = cls.prepare_output_variables(outputs)
out.append(cls.format_function_param(
function_keys[0], function_name=function_name,
input_var=input_var, output_var=output_var, **kwargs))
if cls.interface_inside_exec:
out += [cls.function_param['indent'] + x
for x in interface_lines]
free_vars = []
if 'declare' in cls.function_param:
definitions = []
if not cls.types_in_funcdef:
for o in (inputs + old_outputs):
out += [cls.function_param['indent'] + x for
x in cls.write_declaration(
o, definitions=definitions,
requires_freeing=free_vars,
is_argument=True)]
for o in outputs:
out += [cls.function_param['indent'] + x for
x in cls.write_declaration(
o, definitions=definitions,
requires_freeing=free_vars)]
out += [cls.function_param['indent'] + x
for x in definitions]
if outputs_in_inputs:
out.append(cls.function_param['indent']
+ cls.format_function_param(
'assign', **flag_var))
if opening_msg:
out.append(cls.function_param['indent']
+ cls.format_function_param(
'print', message=opening_msg))
if print_inputs:
for x in print_input_lines:
out.append(cls.function_param['indent'] + x)
for x in function_contents:
out.append(cls.function_param['indent'] + x)
if print_outputs:
for x in print_output_lines:
out.append(cls.function_param['indent'] + x)
if closing_msg:
out.append(cls.function_param['indent']
+ cls.format_function_param(
'print', message=closing_msg))
# This is not currently used by the tests, but may be
# needed in the future
assert(not free_vars)
# for x in free_vars:
# out += [cls.function_param['indent'] + line
# for line in cls.write_free(x)]
if output_var and ('return' in cls.function_param):
out.append(cls.function_param['indent']
+ cls.format_function_param(
'return', output_var=output_var))
if function_keys[1] in cls.function_param:
out.append(cls.format_function_param(
function_keys[1], function_name=function_name))
else:
out.append(cls.function_param.get('block_end', ''))
if verbose: # pragma: debug
logger.info('\n' + '\n'.join(out))
else:
logger.debug('\n' + '\n'.join(out))
return out
@classmethod
def write_function_call(cls, function_name, inputs=[], outputs=[],
include_arg_count=False,
outputs_in_inputs=False, **kwargs):
r"""Write a function call.
Args:
function_name (str): Name of the function being called.
inputs (list, optional): List of inputs to the function.
Defaults to [].
outputs (list, optional): List of outputs from the function.
Defaults to [].
include_arg_count (bool, optional): If True, the count of input
arguments is included as the first argument. Defaults to
False.
outputs_in_inputs (bool, optional): If True, the outputs are
presented in the function definition as inputs. Defaults
to False.
**kwargs: Additional keyword arguments are passed to
cls.format_function_param.
Returns:
list: Lines completing the function call.
"""
if outputs_in_inputs:
inputs = inputs + [cls.prepare_output_variables(
outputs, in_inputs=outputs_in_inputs)]
flag_var = kwargs.get('flag_var', None)
if (flag_var is None) and ('function_call_noout' not in cls.function_param):
flag_var = 'flag'
outputs = []
if flag_var:
outputs.append(flag_var)
kwargs.setdefault('input_var', cls.prepare_input_variables(inputs))
kwargs.setdefault('output_var', cls.prepare_output_variables(outputs))
nout = len(cls.split_variables(kwargs['output_var']))
if include_arg_count:
narg = len(cls.split_variables(kwargs['input_var']))
kwargs['input_var'] = cls.prepare_input_variables(
[str(narg), kwargs['input_var']])
if (nout == 0) and ('function_call_noout' in cls.function_param):
call_str = cls.format_function_param(
'function_call_noout', function_name=function_name, **kwargs)
else:
call_str = cls.format_function_param(
'function_call', default='{function_name}({input_var})',
function_name=function_name, **kwargs)
if nout == 0:
out = [call_str + cls.function_param.get('line_end', '')]
elif (nout > 1) and ('assign_mult' in cls.function_param):
out = [cls.format_function_param(
'assign_mult', name=kwargs['output_var'], value=call_str)]
else:
out = [cls.format_function_param(
'assign', name=kwargs['output_var'], value=call_str)]
return out
@classmethod
def write_executable_import(cls, model_name=None, **kwargs):
r"""Add import statements to executable lines.
Args:
**kwargs: Keyword arguments for import statement.
Returns:
list: Lines required to complete the import.
"""
# This code is currently unused, but may be needed in the
# future to import a dependency directly
# if ('filename' not in kwargs) and ('import_nofile' in cls.function_param):
# key = 'import_nofile'
# else:
# key = 'import'
# return [cls.format_function_param(key, **kwargs)]
out = []
if 'import' in cls.function_param:
out = [cls.format_function_param('import', **kwargs)]
return out
@classmethod
def write_executable(cls, lines, prefix=None, suffix=None,
function_definitions=None, imports=None,
model_name=None):
r"""Return the lines required to complete a program that will run
the provided lines.
Args:
lines (list): Lines of code to be wrapped as an executable.
prefix (list, optional): Lines of code that should proceed the
wrapped code. Defaults to None and is ignored. (e.g. C/C++
include statements).
suffix (list, optional): Lines of code that should follow the
wrapped code. Defaults to None and is ignored.
function_definitions (list, optional): Lines of code defining
functions that will beused by the code contained in lines.
Defaults to None and is ignored.
imports (list, optional): Kwargs for packages that should
be imported for use by the executable. Defaults to
None and is ignored.
model_name (str, optional): Name given to the model. Defaults to
None.
Returns:
lines: Lines of code wrapping the provided lines with the
necessary code to run it as an executable (e.g. C/C++'s main).
"""
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
out = []
# Add imports
if imports is not None:
if not isinstance(imports, list):
imports = [imports]
import_lines = []
for kws in imports:
import_lines += cls.write_executable_import(**kws)
if prefix is None:
prefix = []
prefix += import_lines
# Add standard & user defined prefixes
if ((('exec_prefix' in cls.function_param)
and (cls.function_param['exec_prefix'] not in lines))):
out.append(cls.function_param['exec_prefix'])
out.append('')
if prefix is not None:
if not isinstance(prefix, (list, tuple)):
prefix = [prefix]
out += prefix
out.append('')
if (((not cls.function_param.get('functions_defined_last', False))
and (function_definitions is not None))):
out += function_definitions
out.append('')
# Add code with begin/end book ends
if ((('exec_begin' in cls.function_param)
and (cls.function_param['exec_begin'] not in '\n'.join(lines)))):
out.append(cls.function_param['exec_begin'])
if not isinstance(lines, (list, tuple)):
lines = [lines]
for x in lines:
out.append(cls.function_param['indent'] + x)
out.append(cls.function_param.get('exec_end',
cls.function_param.get(
'block_end', '')))
else:
out += lines
if out[-1]:
out.append('')
# Add standard & user defined suffixes
if suffix is not None:
if not isinstance(suffix, (list, tuple)):
suffix = [suffix]
out += suffix
out.append('')
if ((('exec_suffix' in cls.function_param)
and (cls.function_param['exec_suffix'] not in lines))):
out.append(cls.function_param['exec_suffix'])
out.append('')
if (((cls.function_param.get('functions_defined_last', False))
and (function_definitions is not None))): # pragma: matlab
out += function_definitions
out.append('')
if cls.max_line_width:
new_out = []
for iout in out:
new_out += cls.split_line(iout)
out = new_out
return out
@classmethod
def escape_quotes(cls, x):
r"""Escape quotes in a string.
Args:
x (str): String to escape quotes in.
Returns:
str: x with escaped quotes.
"""
out = x.replace('"', '\\\"')
out = out.replace("'", "\\\'")
return out
@classmethod
def split_line(cls, line, length=None, force_split=False):
r"""Split a line as close to (or before) a given character as
possible.
Args:
line (str): Line to split.
length (int, optional): Maximum length of split lines. Defaults
to cls.max_line_width if not provided.
force_split (bool, optional): If True, force a split to
occur at the specified length. Defauts to False.
Returns:
list: Set of lines resulting from spliting the provided line.
"""
out = []
if not line.lstrip():
return [line]
nindent = line.index(line.lstrip()[0])
block_end = cls.function_param['block_end'].lower()
if '\n' in line:
out = line.split('\n')
for i in range(1, len(out)):
if out[i].lstrip().lower().startswith(block_end):
nindent -= len(cls.function_param['indent'])
out[i] = (nindent * ' ') + out[i]
new_out = []
for x in out:
new_out += cls.split_line(x, length=length,
force_split=force_split)
return new_out
if length is None:
length = cls.max_line_width
if (length is None) or (len(line) < length):
return [line]
length_allow = (length - len(cls.function_param.get(
'continuation_before', '')))
if force_split:
isplit = length_allow
else:
isplit = line[:length_allow].rindex(' ') + 1
if (isplit < nindent + 1) or (isplit >= len(line)):
out = [line]
else:
out.append(line[:isplit] + cls.function_param.get(
'continuation_before', ''))
out += cls.split_line(
((nindent * ' ') + cls.function_param.get(
'continuation_after', '') + line[isplit:]),
length=length, force_split=force_split)
return out
@classmethod
def input2output(cls, var):
r"""Perform conversion necessary to turn a variable extracted from a
function definition from an input to an output.
Args:
var (dict): Variable definition.
Returns:
dict: Updated variable definition.
"""
return var
@classmethod
def output2input(cls, var, in_definition=True):
r"""Perform conversion necessary to turn an output variable
into an corresponding input that can be used to format a
function definition.
Args:
var (dict): Variable definition.
in_definition (bool, optional): If True, the returned
dictionary corresponds to an input variable in a
function definition. If False, the returned value
will correspond to an input to a function. Defaults to
True.
Returns:
dict: Updated variable definition.
"""
return var
@classmethod
def get_native_type(cls, **kwargs):
r"""Get the native type.
Args:
type (str, optional): Name of |yggdrasil| extended JSON
type or JSONSchema dictionary defining a datatype.
**kwargs: Additional keyword arguments may be used in determining
the precise declaration that should be used.
Returns:
str: The native type.
"""
if 'native_type' in kwargs:
return kwargs['native_type']
assert('json_type' not in kwargs)
json_type = kwargs.get('datatype', kwargs)
if isinstance(json_type, dict):
type_name = json_type.get('type', 'bytes')
else:
type_name = json_type
json_type = kwargs
if type_name == 'scalar':
type_name = json_type['subtype']
if (type_name == 'flag') and (type_name not in cls.type_map):
type_name = 'boolean'
return cls.type_map[type_name]
@classmethod
def get_json_type(cls, native_type):
r"""Get the JSON type from the native language type.
Args:
native_type (str): The native language type.
Returns:
str, dict: The JSON type.
"""
return cls.get_inverse_type_map()[native_type]
@classmethod
def write_finalize_iiter(cls, var):
r"""Get the lines necessary to finalize an input array for iteration.
Args:
var (dict, str): Name or information dictionary for the variable
finalized.
Returns:
list: The lines finalizing the variable.
"""
return []
@classmethod
def write_initialize_oiter(cls, var, value=None, requires_freeing=None):
r"""Get the lines necessary to initialize an array for iteration
output.
Args:
var (dict, str): Name or information dictionary for the variable
being initialized.
value (str, optional): Value that should be assigned to the
variable.
requires_freeing (list, optional): Existing list that variables
requiring freeing should be appended to. Defaults to None
and is ignored.
Returns:
list: The lines initializing the variable.
"""
return cls.write_initialize(var, value=value,
requires_freeing=requires_freeing)
@classmethod
def write_finalize_oiter(cls, var, value=None, requires_freeing=None):
r"""Get the lines necessary to finalize an array after iteration.
Args:
var (dict, str): Name or information dictionary for the variable
being initialized.
value (str, optional): Value that should be assigned to the
variable.
requires_freeing (list, optional): Existing list of variables
requiring freeing. Defaults to None and is ignored.
Returns:
list: The lines finalizing the variable.
"""
return []
@classmethod
def write_initialize(cls, var, value=None, requires_freeing=None):
r"""Get the code necessary to initialize a variable.
Args:
var (dict, str): Name or information dictionary for the variable
being declared.
value (str, optional): Value that should be assigned to the
variable after it is declared.
requires_freeing (list, optional): Existing list that variables
requiring freeing should be appended to. Defaults to None
and is ignored.
Returns:
list: The lines initializing the variable.
"""
out = []
if isinstance(var, str): # pragma: no cover
var = {'name': var}
if (value is None) and isinstance(var.get('datatype', False), dict):
init_type = 'init_%s' % var['datatype']['type']
free_type = 'free_%s' % var['datatype']['type']
if init_type in cls.function_param:
assert(free_type in cls.function_param)
# value = cls.format_function_param(init_type, **var['datatype'])
value = cls.function_param[init_type]
if requires_freeing is not None:
requires_freeing.append(var)
if value is not None:
out.append(cls.format_function_param(
'assign', name=var['name'], value=value))
return out
@classmethod
def write_declaration(cls, var, value=None, requires_freeing=None,
definitions=None, is_argument=False):
r"""Return the lines required to declare a variable with a certain
type.
Args:
var (dict, str): Name or information dictionary for the variable
being declared.
value (str, optional): Value that should be assigned to the
variable after it is declared.
requires_freeing (list, optional): Existing list that variables
requiring freeing should be appended to. Defaults to None
and is ignored.
definitions (list, optional): Existing list that variable
definitions should be added to. Defaults to None if not
provided and definitions will be included in the returned
lines.
dont_define (bool, optional): If True, the variable will not
be defined. Defaults to False.
is_argument (bool, optional): If True, the variable being
declared is an input argument. Defaults to False.
Returns:
list: The lines declaring the variable.
"""
if isinstance(var, str): # pragma: no cover
var = {'name': var}
type_name = cls.get_native_type(**var)
out = [cls.format_function_param('declare',
type_name=type_name,
variable=cls.get_name_declare(var))]
if is_argument:
return out
if definitions is None:
definitions = out
definitions += cls.write_initialize(var, value=value,
requires_freeing=requires_freeing)
return out
@classmethod
def get_name_declare(cls, var):
r"""Determine the name that should be used for declaration.
Args:
var (str, dict): Name of variable or dictionary of information.
Returns:
str: Modified name for declaration.
"""
if isinstance(var, str): # pragma: no cover
return var
assert(isinstance(var, dict))
out = var['name']
return out
@classmethod
def write_free(cls, var, **kwargs):
r"""Return the lines required to free a variable with a certain type.
Args:
var (dict, str): Name or information dictionary for the variable
being declared.
**kwargs: Additional keyword arguments are passed to format_function_param.
Returns:
list: The lines freeing the variable.
"""
if isinstance(var, str): # pragma: no cover
var = {'name': var}
out = []
if not var.get('dont_free', False):
if ((isinstance(var.get('datatype', False), dict)
and (('free_%s' % var['datatype']['type'])
in cls.function_param))):
out = [cls.format_function_param(
'free_%s' % var['datatype']['type'],
variable=var['name'], **kwargs)]
else:
out = [cls.format_function_param(
'free', variable=var['name'], **kwargs)]
return out
@classmethod
def write_assign_to_output(cls, dst_var, src_var, copy=False,
outputs_in_inputs=False, **kwargs):
r"""Write lines assigning a value to an output variable.
Args:
dst_var (str, dict): Name or information dictionary for
variable being assigned to.
src_var (str, dict): Name or information dictionary for
value being assigned to dst_var.
copy (bool, optional): If True, the assigned value is copied
during assignment. Defaults to False.
outputs_in_inputs (bool, optional): If True, outputs are passed
as input parameters. In some languages, this means that a
pointer or reference is passed (e.g. C) and so the assignment
should be to the memory indicated rather than the variable.
Defaults to False.
Returns:
list: Lines achieving assignment.
"""
datatype = None
if isinstance(dst_var, dict):
kwargs['name'] = dst_var['name']
datatype = dst_var['datatype']
else:
kwargs['name'] = dst_var
if isinstance(src_var, dict):
kwargs['value'] = src_var['name']
datatype = src_var['datatype']
else:
kwargs['value'] = src_var
if ((outputs_in_inputs and isinstance(dst_var, dict)
and isinstance(dst_var['datatype'], dict)
and ('copy_' + dst_var['datatype']['type']
in cls.function_param))):
copy = True
if copy:
if ((isinstance(datatype, dict)
and ('copy_' + datatype['type'] in cls.function_param))):
return [cls.format_function_param(
'copy_' + datatype['type'], **kwargs)]
else:
return [cls.format_function_param('assign_copy', **kwargs)]
else:
return [cls.format_function_param('assign', **kwargs)]
@classmethod
def write_expand_single_element(cls, output_var, add_cond=False):
r"""Write lines allowing extraction of the only element from a single
element array as a stand-alone variable if the variable is an array
and only has one element.
Args:
output_var (str): Name of the variable that should be conditionally
expanded.
add_cond (list, optional): Additional conditions that must be
satisfied for the array element to be extracted. Defaults to
False and is ignored.
Returns:
list: Lines added the conditional expansion of single element
arrays.
"""
if 'istype' not in cls.function_param:
return []
cond = ('(%s) %s (%s %s 1)' % (
cls.format_function_param('istype',
variable=output_var,
type=cls.type_map['array']),
cls.function_param.get('and', '&&'),
cls.format_function_param('len',
variable=output_var),
cls.function_param.get('equ', '==')))
if add_cond:
for x in add_cond:
cond += f" {cls.function_param.get('and', '&&')} {x}"
out = cls.write_if_block(
cond,
cls.format_function_param(
'assign', name=output_var,
value=cls.format_function_param(
'index', variable=output_var,
index=int(cls.function_param.get('first_index', 0)))))
return out
@classmethod
def split_variables(cls, var_str):
r"""Split variable string include individual variables.
Args:
var_str (str): String containing multiple variables.
Returns:
list: Split variables.
"""
out = []
if var_str:
pairs = [(r'\[', r'\]'),
(r'\(', r'\)'),
(r'\{', r'\}'),
(r"'", r"'"),
(r'"', r'"')]
regex_ele = r''
present = False
for p in pairs:
if not any([(str(ip)[-1] in var_str) for ip in p]):
continue
present = True
regex_ele += (r'(?:%s[.\n]*?%s)|' % p)
if present:
regex_ele += '(?:.+?)'
regex_ele = r'\s*(%s)\s*(?:,|$)' % regex_ele
out = [x.group(1) for x in re.finditer(regex_ele, var_str)]
else:
out = [x.strip() for x in var_str.split(',')]
return out
@classmethod
def prepare_variables(cls, vars_list, in_definition=False,
for_yggdrasil=False):
r"""Concatenate a set of input variables such that it can be passed as a
single string to the function_call parameter.
Args:
vars_list (list): List of variable dictionaries containing info
(e.g. names) that should be used to prepare a string representing
input/output to/from a function call.
in_definition (bool, optional): If True, the returned sequence
will be of the format required for specifying variables
in a function definition. Defaults to False.
for_yggdrasil (bool, optional): If True, the variables will be
prepared in the formated expected by calls to yggdarsil
send/recv methods. Defaults to False.
Returns:
str: Concatentated variables list.
"""
name_list = []
if not isinstance(vars_list, list):
vars_list = [vars_list]
for x in vars_list:
if isinstance(x, str):
name_list.append(x)
else:
assert(isinstance(x, dict))
name_list.append(x['name'])
return ', '.join(name_list)
@classmethod
def prepare_input_variables(cls, vars_list, in_definition=False,
for_yggdrasil=False):
r"""Concatenate a set of input variables such that it can be passed as a
single string to the function_call parameter.
Args:
vars_list (list): List of variable dictionaries containing info
(e.g. names) that should be used to prepare a string representing
input to a function call.
in_definition (bool, optional): If True, the returned sequence
will be of the format required for specifying input
variables in a function definition. Defaults to False.
for_yggdrasil (bool, optional): If True, the variables will be
prepared in the formated expected by calls to yggdarsil
send/recv methods. Defaults to False.
Returns:
str: Concatentated variables list.
"""
return cls.prepare_variables(vars_list, in_definition=in_definition,
for_yggdrasil=for_yggdrasil)
@classmethod
def prepare_output_variables(cls, vars_list, in_definition=False,
in_inputs=False, for_yggdrasil=False):
r"""Concatenate a set of output variables such that it can be passed as
a single string to the function_call parameter.
Args:
vars_list (list): List of variable dictionaries containing info
(e.g. names) that should be used to prepare a string representing
output from a function call.
in_definition (bool, optional): If True, the returned sequence
will be of the format required for specifying output
variables in a function definition. Defaults to False.
in_inputs (bool, optional): If True, the output variables should
be formated to be included as input variables. Defaults to
False.
for_yggdrasil (bool, optional): If True, the variables will be
prepared in the formated expected by calls to yggdarsil
send/recv methods. Defaults to False.
Returns:
str: Concatentated variables list.
"""
if in_inputs:
vars_list = [cls.output2input(x, in_definition=in_definition)
for x in vars_list]
out = cls.prepare_variables(vars_list, in_definition=in_definition,
for_yggdrasil=for_yggdrasil)
if isinstance(vars_list, list) and (len(vars_list) > 1):
if in_definition and ('multiple_outputs_def' in cls.function_param):
out = cls.format_function_param('multiple_outputs_def', outputs=out)
elif 'multiple_outputs' in cls.function_param:
out = cls.format_function_param('multiple_outputs', outputs=out)
return out
@classmethod
def write_if_block(cls, cond, block_contents, else_block_contents=False):
r"""Return the lines required to complete a conditional block.
Args:
cond (str): Conditional that should determine block execution.
block_contents (list): Lines of code that should be executed inside
the block.
else_block_contents (list, optional): Lines of code that should be
executed inside the else clause of the block. Defaults to False
if not provided and an else clause is omitted.
Returns:
list: Lines of code performing conditional execution of a block.
"""
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
out = []
if not isinstance(cond, list):
cond = [cond]
block_contents = [block_contents]
assert(len(cond) == len(block_contents))
for i, (icond, iblock_contents) in enumerate(zip(cond, block_contents)):
if i == 0:
out.append(cls.format_function_param('if_begin', cond=icond))
else:
out.append(cls.format_function_param('if_elif', cond=icond))
if not isinstance(iblock_contents, (list, tuple)):
iblock_contents = [iblock_contents]
for x in iblock_contents:
out.append(cls.function_param['indent'] + x)
if else_block_contents:
out.append(cls.format_function_param('if_else'))
if not isinstance(else_block_contents, (list, tuple)):
else_block_contents = [else_block_contents]
for x in else_block_contents:
out.append(cls.function_param['indent'] + x)
# Close block
out.append(cls.function_param.get('if_end',
cls.function_param.get(
'block_end', '')))
return out
@classmethod
def write_for_loop(cls, iter_var, iter_begin, iter_end, loop_contents):
r"""Return the lines required to complete a for loop.
Args:
iter_var (str): Name of variable that iterator should use.
iter_begin (int): Beginning of iteration.
iter_end (int): End of iteration.
loop_contents (list): Lines of code that should be executed inside
the loop.
Returns:
list: Lines of code performing a loop.
"""
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
out = []
# Opening for statement line
out.append(cls.format_function_param('for_begin', iter_var=iter_var,
iter_begin=iter_begin,
iter_end=iter_end))
# Indent loop contents
if not isinstance(loop_contents, (list, tuple)):
loop_contents = [loop_contents]
for x in loop_contents:
out.append(cls.function_param['indent'] + x)
# Close block
out.append(cls.function_param.get('for_end',
cls.function_param.get(
'block_end', '')))
return out
@classmethod
def write_while_loop(cls, cond, loop_contents):
r"""Return the lines required to complete a for loop.
Args:
cond (str): Conditional that should determine loop execution.
loop_contents (list): Lines of code that should be executed inside
the loop.
Returns:
list: Lines of code performing a loop.
"""
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
out = []
# Opening for statement line
out.append(cls.format_function_param('while_begin', cond=cond))
# Indent loop contents
if not isinstance(loop_contents, (list, tuple)):
loop_contents = [loop_contents]
for x in loop_contents:
out.append(cls.function_param['indent'] + x)
# Close block
out.append(cls.function_param.get('while_end',
cls.function_param.get(
'block_end', '')))
return out
@classmethod
def write_try_except(cls, try_contents, except_contents, error_var='e',
error_type=None):
r"""Return the lines required to complete a try/except block.
Args:
try_contents (list): Lines of code that should be executed inside
the try block.
except_contents (list): Lines of code that should be executed inside
the except block.
error_var (str, optional): Name of variable where the caught error
should be stored. Defaults to 'e'.
error_type (str, optional): Name of error type that should be caught.
If not provided, defaults to None and will be set based on the
class function_param entry for 'try_error_type'.
Returns:
Lines of code perfoming a try/except block.
"""
if (cls.function_param is None) or ('try_begin' not in cls.function_param):
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
if error_type is None:
error_type = cls.function_param.get('try_error_type', None)
out = []
# Try block contents
if not isinstance(try_contents, (list, tuple)):
try_contents = [try_contents]
out.append(cls.function_param['try_begin'])
for x in try_contents:
out.append(cls.function_param['indent'] + x)
# Except block contents
if not isinstance(except_contents, (list, tuple)):
except_contents = [except_contents]
out.append(cls.format_function_param('try_except', error_var=error_var,
error_type=error_type))
for x in except_contents:
out.append(cls.function_param['indent'] + x)
# Close block
out.append(cls.function_param.get('try_end',
cls.function_param.get(
'block_end', '')))
return out
@classmethod
def get_testing_options(cls):
r"""Method to return a dictionary of testing options for this class.
Returns:
dict: Dictionary of variables to use for testing. Key/value pairs:
kwargs (dict): Keyword arguments for driver instance.
deps (list): Dependencies to install.
"""
out = dict(
kwargs={}, deps=[],
write_function_def_params=[
{'inputs': [{'name': 'x', 'value': 1.0,
'datatype': {'type': 'float',
'precision': 32,
'units': 'cm'}}],
'outputs': [{'name': 'y',
'datatype': {'type': 'float',
'precision': 32,
'units': 'cm'}}]}],
split_lines=[('abcdef', {'length': 3, 'force_split': True},
['abc', 'def']),
(' abc', {'length': 3, 'force_split': True},
[' abc'])])
return out
| 44.62343 | 88 | 0.555684 | import os
import re
import sys
import copy
import logging
import warnings
import subprocess
import shutil
import uuid
import tempfile
import asyncio
from collections import OrderedDict
from pprint import pformat
from yggdrasil import platform, tools, languages, multitasking, constants
from yggdrasil.components import import_component
from yggdrasil.drivers.Driver import Driver
from yggdrasil.metaschema.datatypes import is_default_typedef
from queue import Empty
logger = logging.getLogger(__name__)
_map_language_ext = OrderedDict()
def remove_product(product, check_for_source=False, **kwargs):
tools.import_all_modules('yggdrasil.drivers')
source_keys = list(_map_language_ext.keys())
if '.exe' in source_keys:
source_keys.remove('.exe')
if check_for_source:
if os.path.isdir(product):
ext_tuple = tuple(source_keys)
for root, dirs, files in os.walk(product):
for f in files:
if f.endswith(ext_tuple):
raise RuntimeError(("%s contains a source file "
"(%s)") % (product, f))
elif os.path.isfile(product):
ext = os.path.splitext(product)[-1]
if ext in source_keys:
raise RuntimeError("%s is a source file." % product)
tools.remove_path(product, **kwargs)
def remove_products(products, source_products):
for p in source_products:
remove_product(p)
for p in products:
remove_product(p, check_for_source=True)
class ModelDriver(Driver):
_schema_type = 'model'
_schema_subtype_key = 'language'
_schema_required = ['name', 'language', 'args', 'working_dir']
_schema_properties = {
'name': {'type': 'string'},
'language': {'type': 'string', 'default': 'executable',
'description': (
'The programming language that the model '
'is written in. A list of available '
'languages can be found :ref:`here <'
'schema_table_model_subtype_rst>`.')},
'args': {'type': 'array',
'items': {'type': 'string', 'minLength': 1}},
'inputs': {'type': 'array', 'default': [],
'items': {'$ref': '#/definitions/comm'},
'description': (
'Zero or more channels carrying input to the model. '
'A full description of channel entries and the '
'options available for channels can be found '
':ref:`here<yaml_comm_options>`.')},
'outputs': {'type': 'array', 'default': [],
'items': {'$ref': '#/definitions/comm'},
'description': (
'Zero or more channels carrying output from the '
'model. A full description of channel entries and '
'the options available for channels can be found '
':ref:`here<yaml_comm_options>`.')},
'env': {'type': 'object', 'default': {},
'additional_properties': {'type': 'string'}},
'products': {'type': 'array', 'default': [],
'items': {'type': 'string'}},
'source_products': {'type': 'array', 'default': [],
'items': {'type': 'string'}},
'working_dir': {'type': 'string'},
'overwrite': {'type': 'boolean'},
'preserve_cache': {'type': 'boolean', 'default': False},
'function': {'type': 'string'},
'iter_function_over': {'type': 'array', 'default': [],
'items': {'type': 'string'}},
'is_server': {'anyOf': [{'type': 'boolean'},
{'type': 'object',
'properties': {'input': {'type': 'string'},
'output': {'type': 'string'}},
'additionalProperties': False}],
'default': False},
'client_of': {'type': 'array', 'items': {'type': 'string'},
'default': []},
'timesync': {
'anyOf': [
{'type': 'boolean'}, {'type': 'string'},
{'type': 'object',
'required': ['name'],
'properties': {
'name': {'type': 'string', 'default': 'timesync'},
'inputs': {'anyOf': [
{'type': 'string'},
{'type': 'array',
'items': {'type': 'string'}}]},
'outputs': {'anyOf': [
{'type': 'string'},
{'type': 'array',
'items': {'type': 'string'}}]}}},
{'type': 'array',
'items': {
'anyOf': [
{'type': 'string'},
{'type': 'object',
'required': ['name'],
'properties': {
'name': {'type': 'string',
'default': 'timesync'},
'inputs': {'anyOf': [
{'type': 'string'},
{'type': 'array',
'items': {'type': 'string'}}]},
'outputs': {'anyOf': [
{'type': 'string'},
{'type': 'array',
'items': {'type': 'string'}}]}}}]}}],
'default': False},
'with_strace': {'type': 'boolean', 'default': False},
'strace_flags': {'type': 'array',
'default': ['-e', 'trace=memory'],
'items': {'type': 'string'}},
'with_valgrind': {'type': 'boolean', 'default': False},
'valgrind_flags': {'type': 'array',
'default': ['--leak-check=full',
'--show-leak-kinds=all'],
'items': {'type': 'string'}},
'outputs_in_inputs': {'type': 'boolean'},
'logging_level': {'type': 'string', 'default': ''},
'allow_threading': {'type': 'boolean'},
'copies': {'type': 'integer', 'default': 1, 'minimum': 1},
'repository_url': {'type': 'string'},
'repository_commit': {'type': 'string'},
'description': {'type': 'string'},
'contact_email': {'type': 'string'},
'validation_command': {'type': 'string'},
'dependencies': {
'type': 'array',
'items': {'oneOf': [
{'type': 'string'},
{'type': 'object',
'required': ['package'],
'properties': {
'package': {'type': 'string'},
'package_manager': {'type': 'string'},
'arguments': {'type': 'string'}},
'additionalProperties': False}]}},
'additional_dependencies': {
'type': 'object',
'additionalProperties': {
'type': 'array',
'items': {'oneOf': [
{'type': 'string'},
{'type': 'object',
'required': ['package'],
'properties': {
'package': {'type': 'string'},
'package_manager': {'type': 'string'},
'arguments': {'type': 'string'}},
'additionalProperties': False}]}}}}
_schema_excluded_from_class = ['name', 'language', 'args', 'working_dir']
_schema_excluded_from_class_validation = ['inputs', 'outputs']
language = None
language_ext = None
language_aliases = []
base_languages = []
executable_type = None
interface_library = None
interface_directories = []
interface_dependencies = []
supported_comms = []
supported_comm_options = {}
external_libraries = {}
internal_libraries = {}
type_map = None
inverse_type_map = None
function_param = None
version_flags = ['--version']
full_language = True
outputs_in_inputs = False
include_arg_count = False
include_channel_obj = False
is_typed = False
types_in_funcdef = True
interface_inside_exec = False
dont_declare_channel = False
is_dsl = False
brackets = None
zero_based = True
max_line_width = None
no_executable = False
comms_implicit = False
python_interface = {'table_input': 'YggAsciiTableInput',
'table_output': 'YggAsciiTableOutput',
'array_input': 'YggArrayInput',
'array_output': 'YggArrayOutput',
'pandas_input': 'YggPandasInput',
'pandas_output': 'YggPandasOutput'}
_library_cache = {}
_config_keys = []
_config_attr_map = []
_executable_search_dirs = None
_disconnect_attr = (Driver._disconnect_attr
+ ['queue', 'queue_thread',
'event_process_kill_called',
'event_process_kill_complete',
'model_process'])
_mpi_tags = {'ENV': 1,
'START': 2,
'STOP_RANK0': 3,
'STOP_RANKX': 4,
'BUILDFILE': 5,
'LOCK_BUILDFILE': 6,
'UNLOCK_BUILDFILE': 7}
def __init__(self, name, args, model_index=0, copy_index=-1, clients=[],
preparsed_function=None, outputs_in_inputs=None,
mpi_rank=0, mpi_tag_start=None, **kwargs):
self._inv_mpi_tags = {v: k for k, v in self._mpi_tags.items()}
self.model_outputs_in_inputs = outputs_in_inputs
self.preparsed_function = preparsed_function
super(ModelDriver, self).__init__(name, **kwargs)
if self.overwrite is None:
self.overwrite = (not self.preserve_cache)
self.model_process = None
self.queue = multitasking.Queue()
self.queue_thread = None
self.event_process_kill_called = multitasking.Event()
self.event_process_kill_complete = multitasking.Event()
if self.with_strace and self.with_valgrind:
raise RuntimeError("Trying to run with strace and valgrind.")
if (((self.with_strace or self.with_valgrind)
and platform._is_win)):
raise RuntimeError("strace/valgrind options invalid on windows.")
self.model_index = model_index
self.copy_index = copy_index
self.clients = clients
self.env_copy = ['LANG', 'PATH', 'USER']
self._exit_line = b'EXIT'
for k in self.env_copy:
if k in os.environ:
self.env[k] = os.environ[k]
if not self.is_installed():
raise RuntimeError("%s is not installed" % self.language)
self.raw_model_file = None
self.model_function_file = None
self.model_function_info = None
self.model_function_inputs = None
self.model_function_outputs = None
self.model_file = None
self.model_args = []
self.model_dir = None
self.model_src = None
self.args = args
self.modified_files = []
self.wrapper_products = []
self._mpi_comm = False
self._mpi_rank = 0
self._mpi_size = 1
self._mpi_requests = {}
self._mpi_tag = (len(self._mpi_tags) * self.model_index)
if mpi_tag_start is not None:
self._mpi_tag += mpi_tag_start
if multitasking._on_mpi:
self._mpi_comm = multitasking.MPI.COMM_WORLD
self._mpi_rank = self._mpi_comm.Get_rank()
self._mpi_size = self._mpi_comm.Get_size()
self._mpi_partner_rank = mpi_rank
if self.function:
args = [self.init_from_function(args)]
self.debug(str(args))
self.parse_arguments(args)
assert(self.model_file is not None)
if self.overwrite:
self.remove_products()
if self.function:
self.wrapper_products.append(args[0])
self.wrapper_products += self.write_wrappers()
if self.dependencies:
self.install_model_dependencies(self.dependencies)
if self.additional_dependencies:
for language, v in self.additional_dependencies.items():
drv = import_component('model', language)
drv.install_model_dependencies(v)
@staticmethod
def before_registration(cls):
Driver.before_registration(cls)
cls.inverse_type_map = None
cls._language = cls.language
cls._language_aliases = cls.language_aliases
if (((cls.language_ext is not None)
and (not isinstance(cls.language_ext, (list, tuple))))):
cls.language_ext = [cls.language_ext]
@staticmethod
def after_registration(cls, cfg=None, second_pass=False):
if cfg is None:
from yggdrasil.config import ygg_cfg
cfg = ygg_cfg
cfg.reload()
Driver.after_registration(cls)
cls.cfg = cfg
for x in cls._config_attr_map:
ka = x['attr']
k0 = x.get('key', ka)
setattr(cls, ka, cls.cfg.get(cls.language, k0,
getattr(cls, ka)))
@staticmethod
def finalize_registration(cls):
global _map_language_ext
for x in cls.get_language_ext():
if x not in _map_language_ext:
_map_language_ext[x] = []
_map_language_ext[x].append(cls.language)
@classmethod
def mpi_partner_init(cls, self):
pass
@classmethod
def mpi_partner_cleanup(cls, self):
pass
@classmethod
def get_inverse_type_map(cls):
if cls.inverse_type_map is None:
cls.inverse_type_map = {}
for k, v in cls.type_map.items():
if k != 'flag':
cls.inverse_type_map[v] = k
return cls.inverse_type_map
@classmethod
def get_language_for_source(cls, fname, languages=None, early_exit=False,
**kwargs):
if isinstance(fname, list):
lang_dict = {}
for f in fname:
try:
ilang = cls.get_language_for_source(f, languages=languages,
**kwargs)
if early_exit:
return ilang
except ValueError:
continue
lang_dict.setdefault(ilang, 0)
lang_dict[ilang] += 1
if lang_dict:
return max(lang_dict, key=lang_dict.get)
else:
ext = os.path.splitext(fname)[-1]
for ilang in cls.get_map_language_ext().get(ext, []):
if (languages is None) or (ilang in languages):
return ilang
raise ValueError("Cannot determine language for file(s): '%s'" % fname)
@classmethod
def get_map_language_ext(cls):
return _map_language_ext
@classmethod
def get_all_language_ext(cls):
return list(_map_language_ext.keys())
@classmethod
def get_language_dir(cls):
return languages.get_language_dir(cls.language)
@classmethod
def get_language_ext(cls):
out = cls.language_ext
if out is None:
out = []
for x in cls.base_languages:
out += import_component('model', x).get_language_ext()
return out
def parse_arguments(self, args, default_model_dir=None):
if isinstance(args, (str, bytes)):
args = args.split()
for i in range(len(args)):
args[i] = str(args[i])
assert(isinstance(args, list))
if default_model_dir is None:
default_model_dir = self.working_dir
self.raw_model_file = args[0]
self.model_file = self.raw_model_file
self.model_args = args[1:]
if (self.language != 'executable') and (not os.path.isabs(self.model_file)):
model_file = os.path.normpath(os.path.join(default_model_dir,
self.model_file))
self.model_file = model_file
self.model_dir = os.path.dirname(self.model_file)
self.debug("model_file = '%s', model_dir = '%s', model_args = '%s'",
self.model_file, self.model_dir, self.model_args)
def init_from_function(self, args):
if not self.preparsed_function:
yml_mock = dict(self.yml,
name=self.name,
args=self.args,
function=self.function,
is_server=self.is_server,
client_of=self.client_of,
inputs=self.inputs,
outputs=self.outputs,
iter_function_over=self.iter_function_over,
copies=self.copies)
self.preparsed_function = self.preparse_function(yml_mock)
self.model_function_info = self.preparsed_function['model_file']
self.model_function_file = self.model_function_info['model_file']
self.model_function_inputs = self.preparsed_function['inputs']
self.model_function_outputs = self.preparsed_function['outputs']
self.model_outputs_in_inputs = self.preparsed_function['outputs_in_inputs']
model_dir, model_base = os.path.split(self.model_function_file)
model_base = os.path.splitext(model_base)[0]
wrapper_fname = os.path.join(model_dir,
'ygg_%s_%s%s' % (model_base, self.name,
self.language_ext[0]))
lines = self.write_model_wrapper(model_name=self.name,
**self.preparsed_function)
if (not os.path.isfile(wrapper_fname)) or self.overwrite:
with open(wrapper_fname, 'w') as fd:
fd.write('\n'.join(lines))
return wrapper_fname
@property
def numeric_logging_level(self):
out = self.logger.getEffectiveLevel()
if self.logging_level:
out = logging.getLevelName(self.logging_level)
return out
@property
def n_sent_messages(self):
if (self._mpi_rank > 0) and self.check_mpi_request('stopped'):
out = self._mpi_requests['stopped'].result
return out
out = {}
for x in self.yml.get('output_drivers', []):
x_inst = x.get('instance', None)
if x_inst:
out[x_inst.name] = x_inst.models_recvd.get(self.name, 0)
if self.is_server:
for x in self.yml.get('input_drivers', []):
x_inst = x.get('instance', None)
if x_inst and (x_inst._connection_type == 'rpc_request'):
out[x_inst.name] = x_inst.servers_recvd.get(self.name, 0)
return out
@property
def has_sent_messages(self):
n_msg = self.n_sent_messages
if not n_msg:
return True
return bool(sum(n_msg.values()))
def write_wrappers(self, **kwargs):
return []
@classmethod
def install_model_dependencies(cls, dependencies, always_yes=False):
packages = {}
for x in dependencies:
if isinstance(x, str):
x = {'package': x}
if x.get('arguments', None):
cls.install_dependency(always_yes=always_yes, **x)
else:
packages.setdefault(x.get('package_manager', None), [])
packages[x.get('package_manager', None)].append(
x['package'])
for k, v in packages.items():
cls.install_dependency(v, package_manager=k,
always_yes=always_yes)
@classmethod
def install_dependency(cls, package=None, package_manager=None,
arguments=None, command=None, always_yes=False):
assert(package)
if isinstance(package, str):
package = package.split()
if package_manager is None:
if tools.get_conda_prefix():
package_manager = 'conda'
elif platform._is_mac:
package_manager = 'brew'
elif platform._is_linux:
package_manager = 'apt'
elif platform._is_win:
package_manager = 'choco'
yes_cmd = []
cmd_kwargs = {}
if command:
cmd = copy.copy(command)
elif package_manager == 'conda':
cmd = ['conda', 'install'] + package
if platform._is_win:
cmd.insert(0, 'call')
cmd_kwargs['shell'] = True
yes_cmd = ['-y']
elif package_manager == 'brew':
cmd = ['brew', 'install'] + package
elif package_manager == 'apt':
cmd = ['apt-get', 'install'] + package
if bool(os.environ.get('GITHUB_ACTIONS', False)):
cmd.insert(0, 'sudo')
yes_cmd = ['-y']
elif package_manager == 'choco':
cmd = ['choco', 'install'] + package
elif package_manager == 'vcpkg':
cmd = ['vcpkg.exe', 'install', '--triplet', 'x64-windows']
cmd += package
else:
package_managers = {'pip': 'python',
'cran': 'r'}
if package_manager in package_managers:
drv = import_component(
'model', package_managers[package_manager])
return drv.install_dependency(
package=package, package_manager=package_manager,
arguments=arguments, always_yes=always_yes)
raise NotImplementedError(f"Unsupported package manager: "
f"{package_manager}")
if arguments:
cmd += arguments.split()
if always_yes:
cmd += yes_cmd
if cmd_kwargs.get('shell', False):
cmd = ' '.join(cmd)
subprocess.check_call(cmd, **cmd_kwargs)
def model_command(self):
return [self.model_file] + self.model_args
@classmethod
def language_executable(cls, **kwargs):
if cls.no_executable:
return ''
raise NotImplementedError("language_executable not implemented for '%s'"
% cls.language)
@classmethod
def executable_command(cls, args, unused_kwargs=None, **kwargs):
raise NotImplementedError("executable_command not implemented for '%s'"
% cls.language)
@classmethod
def run_executable(cls, args, return_process=False, debug_flags=None,
**kwargs):
unused_kwargs = {}
cmd = cls.executable_command(args, unused_kwargs=unused_kwargs, **kwargs)
if isinstance(debug_flags, list):
cmd = debug_flags + cmd
try:
if 'working_dir' in unused_kwargs:
unused_kwargs.setdefault('cwd', unused_kwargs.pop('working_dir'))
unused_kwargs.setdefault('shell', platform._is_win)
logger.debug("Running '%s' from %s"
% (' '.join(cmd), unused_kwargs.get('cwd', os.getcwd())))
logger.debug("Process keyword arguments:\n%s\n",
' ' + pformat(unused_kwargs).replace('\n', '\n '))
print(' '.join(cmd))
proc = tools.popen_nobuffer(cmd, **unused_kwargs)
if return_process:
return proc
out, err = proc.communicate()
if proc.returncode != 0:
if out:
logger.info('\n%s' % out.decode('utf-8'))
if err:
logger.info('\n%s' % err.decode('utf-8'))
raise RuntimeError("Command '%s' failed with code %d."
% (' '.join(cmd), proc.returncode))
out = out.decode("utf-8")
logger.debug('%s\n%s' % (' '.join(cmd), out))
return out
except (subprocess.CalledProcessError, OSError) as e:
raise RuntimeError("Could not call command '%s': %s"
% (' '.join(cmd), e))
def run_validation(self):
if not self.validation_command:
return
subprocess.check_call(self.validation_command.split(),
cwd=self.working_dir)
def run_model(self, return_process=True, **kwargs):
env = self.set_env()
command = self.model_command()
if self.with_strace or self.with_valgrind:
kwargs.setdefault('debug_flags', self.debug_flags)
self.debug('Working directory: %s', self.working_dir)
self.debug('Command: %s', ' '.join(command))
self.debug('Environment Variables:\n%s', self.pprint(env, block_indent=1))
default_kwargs = dict(env=env, working_dir=self.working_dir,
forward_signals=False,
shell=platform._is_win)
for k, v in default_kwargs.items():
kwargs.setdefault(k, v)
return self.run_executable(command, return_process=return_process, **kwargs)
@property
def debug_flags(self):
pre_args = []
if self.with_strace:
if platform._is_linux:
pre_args += ['strace'] + self.strace_flags
else:
raise RuntimeError("strace not supported on this OS.")
elif self.with_valgrind:
pre_args += ['valgrind'] + self.valgrind_flags
return pre_args
@classmethod
def language_version(cls, version_flags=None, **kwargs):
if version_flags is None:
version_flags = cls.version_flags
return cls.run_executable(version_flags, **kwargs).splitlines()[0].strip()
@classmethod
def is_installed(cls):
return (cls.is_language_installed()
and cls.are_base_languages_installed()
and cls.are_dependencies_installed()
and cls.is_interface_installed() and cls.is_comm_installed()
and cls.is_configured() and (not cls.is_disabled()))
@classmethod
def are_base_languages_installed(cls, missing=None):
out = True
for x in cls.base_languages:
if (not out) and (not isinstance(missing, list)):
break
out = import_component('model', x).is_installed()
if isinstance(missing, list) and (not out):
missing.append(x)
if missing:
out = False
return out
@classmethod
def are_dependencies_installed(cls):
out = (cls.language is not None)
for x in cls.interface_dependencies:
if not out:
break
out = cls.is_library_installed(x)
return out
@classmethod
def is_interface_installed(cls):
out = (cls.language is not None)
if out and (cls.interface_library is not None):
out = cls.is_library_installed(cls.interface_library)
return out
@classmethod
def is_language_installed(cls):
out = False
if cls.language is not None:
try:
out = (shutil.which(cls.language_executable()) is not None)
except NotImplementedError:
out = False
return out
@classmethod
def identify_source_files(cls, args=None, working_dir=None, **kwargs):
out = []
if args:
src = args[0]
if (((not cls.is_source_file(src))
and (cls.language_ext is not None)
and (os.path.splitext(src)[-1]
not in cls.get_all_language_ext()))):
src = os.path.splitext(src)[0] + cls.language_ext[0]
if working_dir and (not os.path.isabs(src)):
src = os.path.normpath(os.path.join(working_dir, src))
if os.path.isfile(src):
out.append(src)
return out
@classmethod
def is_source_file(cls, fname):
out = False
model_ext = os.path.splitext(fname)[-1]
if len(model_ext) > 0:
out = (model_ext in cls.get_language_ext())
return out
@classmethod
def is_library_installed(cls, lib, **kwargs):
raise NotImplementedError("Method is_library_installed missing for '%s'"
% cls.language)
@classmethod
def is_disabled(cls):
return (cls.cfg.get(cls.language, 'disable', 'false').lower() == 'true')
@classmethod
def is_configured(cls):
disable_flag = cls.is_disabled()
out = (cls.cfg.has_section(cls.language) and (not disable_flag))
if out and (len(cls.base_languages) == 0):
out = (cls.cfg.get(cls.language, 'commtypes', None) is not None)
for k in cls._config_keys:
if not out:
break
out = (cls.cfg.get(cls.language, k, None) is not None)
return out
@classmethod
def is_comm_installed(cls, commtype=None, skip_config=False, **kwargs):
# driver to check for comm installation.
if len(cls.base_languages) > 0:
out = True
for x in cls.base_languages:
if not out: # pragma: no cover
break
out = import_component('model', x).is_comm_installed(
commtype=commtype, skip_config=skip_config, **kwargs)
return out
if cls.comms_implicit:
if commtype is None:
return True
return (commtype in tools.get_supported_comm())
# Check for installation based on config option
if not skip_config:
installed_comms = cls.cfg.get(cls.language, 'commtypes', [])
if commtype is None:
return (len(installed_comms) > 0)
else:
return (commtype in installed_comms)
# Check for any comm
if commtype is None:
for c in cls.supported_comms:
if cls.is_comm_installed(commtype=c, skip_config=skip_config,
**kwargs):
return True
# Check that comm is explicitly supported
if commtype not in cls.supported_comms:
return False
# Set & pop keywords
for k, v in cls.supported_comm_options.get(commtype, {}).items():
if kwargs.get(k, None) is None:
kwargs[k] = v
platforms = kwargs.pop('platforms', None)
libraries = kwargs.pop('libraries', [])
# Check platforms
if (platforms is not None) and (platform._platform not in platforms):
return False # pragma: windows
# Check libraries
if (libraries is not None):
for lib in libraries:
if not cls.is_library_installed(lib, **kwargs):
return False
# Check for server on RabbitMQ
if commtype in ['rmq', 'rmq_async']:
from yggdrasil.communication.RMQComm import check_rmq_server
if not check_rmq_server():
return False
return True
@classmethod
def configure(cls, cfg):
out = []
# Section and executable
if (cls.language is not None) and (not cfg.has_section(cls.language)):
cfg.add_section(cls.language)
# Executable type configuration
out += cls.configure_executable_type(cfg)
# Locate executable
if (((not cls.is_language_installed())
and (cls.executable_type is not None))): # pragma: debug
try:
exec_file = cls.language_executable()
if exec_file is not None:
fpath = tools.locate_file(
exec_file, directory_list=cls._executable_search_dirs)
if fpath:
cfg.set(cls.language, cls.executable_type, fpath)
except NotImplementedError:
pass
# Configure libraries
out += cls.configure_libraries(cfg)
# Only do additional configuration if no base languages
if not cls.base_languages:
# Installed comms
comms = []
for c in cls.supported_comms:
if cls.is_comm_installed(commtype=c, cfg=cfg, skip_config=True):
comms.append(c)
cfg.set(cls.language, 'commtypes', comms)
cls.after_registration(cls, cfg=cfg, second_pass=True)
return out
@classmethod
def configure_executable_type(cls, cfg):
return []
@classmethod
def configure_libraries(cls, cfg):
return []
def get_io_env(self, input_drivers=None, output_drivers=None):
if input_drivers is None:
input_drivers = self.yml.get('input_drivers', [])
if output_drivers is None:
output_drivers = self.yml.get('output_drivers', [])
out = {}
if self.copies > 1:
from yggdrasil.drivers.DuplicatedModelDriver import (
DuplicatedModelDriver)
base_name = DuplicatedModelDriver.get_base_name(self.name)
else:
base_name = self.name
for x in input_drivers + output_drivers:
if 'instance' in x:
model_env = x['instance'].model_env
if self.name in model_env:
out.update(model_env[self.name])
elif base_name in model_env:
out.update(model_env[base_name])
return out
@classmethod
def set_env_class(cls, existing=None, **kwargs):
if existing is None: # pragma: no cover
existing = {}
existing.update(os.environ)
return existing
def set_env(self, existing=None, **kwargs):
from yggdrasil.config import ygg_cfg
if existing is None:
existing = {}
existing.update(copy.deepcopy(self.env))
existing.update(self.get_io_env())
env = self.set_env_class(existing=existing, **kwargs)
env.update(YGG_SUBPROCESS="True",
YGG_MODEL_INDEX=str(self.model_index),
YGG_MODEL_LANGUAGE=self.language,
YGG_MODEL_COPIES=str(self.copies),
# YGG_PYTHON_EXEC=sys.executable,
YGG_DEFAULT_COMM=tools.get_default_comm(),
YGG_NCLIENTS=str(len(self.clients)))
if multitasking._on_mpi:
env['YGG_MPI_RANK'] = str(multitasking._mpi_rank)
if self.copies > 1:
from yggdrasil.drivers.DuplicatedModelDriver import (
DuplicatedModelDriver)
env['YGG_MODEL_COPY'] = str(self.copy_index)
env['YGG_MODEL_NAME'] = DuplicatedModelDriver.get_base_name(
self.name)
else:
env['YGG_MODEL_NAME'] = self.name
if self.allow_threading or (self.copies > 1):
env['YGG_THREADING'] = '1'
if isinstance(self.is_server, dict):
env['YGG_SERVER_INPUT'] = self.is_server['input']
env['YGG_SERVER_OUTPUT'] = self.is_server['output']
if self.logging_level:
env['YGG_MODEL_DEBUG'] = self.logging_level
replace = [k for k in env.keys() if ':' in k]
for k in replace:
env[k.replace(':', '__COLON__')] = env.pop(k)
if ygg_cfg.get('general', 'allow_multiple_omp', False):
env['KMP_DUPLICATE_LIB_OK'] = 'True'
return env
def before_start(self, no_queue_thread=False, **kwargs):
# if multitasking._on_mpi:
# self.init_mpi_env()
self.model_process = self.run_model(**kwargs)
# Start thread to queue output
if not no_queue_thread:
self.queue_thread = multitasking.YggTaskLoop(
target=self.enqueue_output_loop,
name=self.name + '.EnqueueLoop')
self.queue_thread.start()
if multitasking._on_mpi:
self.init_mpi()
def queue_close(self):
self.model_process.stdout.close()
def queue_recv(self):
return self.model_process.stdout.readline()
def enqueue_output_loop(self):
try:
line = self.queue_recv()
except BaseException as e: # pragma: debug
print(e)
line = ""
if (len(line) == 0):
self.queue_thread.set_break_flag()
try:
self.queue.put(self._exit_line)
except multitasking.AliasDisconnectError: # pragma: debug
self.error("Queue disconnected")
self.debug("End of model output")
try:
self.queue_close()
except BaseException: # pragma: debug
pass
else:
try:
self.queue.put(line.decode('utf-8'))
except BaseException as e: # pragma: debug
warnings.warn("Error in printing output: %s" % e)
def before_loop(self):
self.debug('Running %s from %s with cwd %s and env %s',
self.model_command(), os.getcwd(), self.working_dir,
pformat(self.env))
# def init_mpi_env(self):
# r"""Receive env information to the partner model."""
# self.env = self.recv_mpi(tag=self._mpi_tags['ENV'])
def init_mpi(self):
if self._mpi_rank == 0:
self._mpi_comm = None
else:
self.recv_mpi(tag=self._mpi_tags['START'])
self._mpi_requests['stopped'] = multitasking.MPIRequestWrapper(
self.recv_mpi(tag=self._mpi_tags['STOP_RANKX'],
dont_block=True))
def send_mpi(self, msg, tag=0, dont_block=False):
self.debug("send %d (%d) [%s]: %s (blocking=%s)", tag,
self._mpi_tag + tag, self._inv_mpi_tags[tag],
msg, not dont_block)
kws = {'dest': self._mpi_partner_rank, 'tag': (self._mpi_tag + tag)}
if dont_block: # pragma: debug
# return self._mpi_comm.isend(msg, **kws)
raise NotImplementedError("Non-blocking MPI send not tested.")
else:
return self._mpi_comm.send(msg, **kws)
def recv_mpi(self, tag=0, dont_block=False):
self.debug('recv %d (%d) [%s] (blocking=%s)', tag,
self._mpi_tag + tag, self._inv_mpi_tags[tag],
not dont_block)
kws = {'source': self._mpi_partner_rank, 'tag': (self._mpi_tag + tag)}
if dont_block:
return self._mpi_comm.irecv(**kws)
else:
return self._mpi_comm.recv(**kws)
def stop_mpi_partner(self, msg=None, dest=0, tag=None):
if self._mpi_comm and (not self.check_mpi_request('stopping')):
if tag is None:
tag = self._mpi_tags['STOP_RANK0']
if msg is None:
if self.errors or self.model_process_returncode:
msg = 'ERROR'
else:
msg = 'STOPPING'
self.debug("stop_mpi_partner: %d, %s", tag, msg)
# Don't call test()
self._mpi_requests['stopping'] = multitasking.MPIRequestWrapper(
self.send_mpi(msg, tag=tag), completed=True)
def wait_on_mpi_request(self, name, timeout=False):
self.debug("Waiting on '%s' (timeout=%s)", name, timeout)
try:
out = self._mpi_requests[name].wait(timeout=timeout)
if out == 'ERROR':
self.errors.append(out)
return out
except asyncio.TimeoutError:
self.info("Timeout for MPI '%s' request", name)
def check_mpi_request(self, name):
if self._mpi_comm and (name in self._mpi_requests):
out, msg = self._mpi_requests[name].test()
if out and (msg == 'ERROR'):
self.errors.append(msg)
return out
return False
def set_break_flag(self, *args, **kwargs):
self.stop_mpi_partner()
super(ModelDriver, self).set_break_flag(*args, **kwargs)
def run_loop(self):
if self.model_process_returncode:
self.errors.append(self.model_process_returncode)
if self.check_mpi_request('stopped'):
self.debug("Stop requested by MPI partner.")
self.set_break_flag()
try:
line = self.queue.get_nowait()
except Empty:
self.sleep()
return
except multitasking.AliasDisconnectError:
self.error("Queue disconnected")
self.set_break_flag()
else:
if (line == self._exit_line) or self.check_mpi_request('stopped'):
self.debug("No more output")
self.set_break_flag()
else:
self.print_encoded(line, end="")
sys.stdout.flush()
def run_finally(self):
self.stop_mpi_partner()
super(ModelDriver, self).run_finally()
def after_loop(self):
self.debug('')
self.stop_mpi_partner()
if self.queue_thread is not None:
self.queue_thread.join(self.sleeptime)
if self.queue_thread.is_alive():
self.debug("Queue thread still alive")
self.kill_process()
return
self.wait_process(self.timeout, key_suffix='.after_loop')
self.kill_process()
self.debug(("Closing input/output drivers:\n"
"\tinput: %s\n\toutput: %s")
% ([drv['name'] for drv in
self.yml.get('input_drivers', [])],
[drv['name'] for drv in
self.yml.get('output_drivers', [])]))
for drv in self.yml.get('input_drivers', []):
if 'instance' in drv:
if self.language == 'mpi':
drv['instance'].wait(self.timeout)
drv['instance'].on_model_exit('output', self.name,
errors=self.errors)
for drv in self.yml.get('output_drivers', []):
if 'instance' in drv:
if self.language == 'mpi':
drv['instance'].wait(self.timeout)
drv['instance'].on_model_exit('input', self.name,
errors=self.errors)
@property
def io_errors(self):
errors = []
for drv in self.yml.get('input_drivers', []):
if 'instance' in drv:
errors += drv['instance'].errors
for drv in self.yml.get('output_drivers', []):
if 'instance' in drv:
errors += drv['instance'].errors
return errors
@property
def model_process_complete(self):
if self.model_process is None:
return True
return (self.model_process.poll() is not None)
@property
def model_process_returncode(self):
if self.model_process_complete and (self.model_process is not None):
return self.model_process.returncode
return 0
def wait_process(self, timeout=None, key=None, key_suffix=None):
if not self.was_started:
return True
return self.wait_on_function(lambda: self.model_process_complete,
timeout=timeout, key_level=1, key=key,
key_suffix=key_suffix)
def kill_process(self):
if not self.was_started:
self.debug('Process was never started.')
self.set_break_flag()
self.event_process_kill_called.set()
self.event_process_kill_complete.set()
if self.event_process_kill_called.is_set():
self.debug('Process has already been killed.')
return
self.event_process_kill_called.set()
with self.lock:
self.debug('')
ignore_error_code = False
if not self.model_process_complete:
self.debug("Process is still running. Killing it.")
try:
self.model_process.kill()
self.debug("Waiting %f s for process to be killed",
self.timeout)
self.wait_process(self.timeout, key_suffix='.kill_process')
except BaseException:
self.exception("Error killing model process")
if not self.has_sent_messages:
ignore_error_code = True
assert(self.model_process_complete)
if (((self.model_process_returncode != 0)
and (not ignore_error_code))):
self.error(("return code of %s indicates model error. "
"(sent messages: %s)"),
str(self.model_process_returncode),
self.n_sent_messages)
self.event_process_kill_complete.set()
if self.queue_thread is not None:
if not self.was_break:
self.debug("Waiting for queue_thread to finish up.")
self.queue_thread.wait(self.timeout)
if self.queue_thread.is_alive():
self.debug("Setting break flag for queue_thread to finish up.")
self.queue_thread.set_break_flag()
self.queue_thread.wait(self.timeout)
try:
self.queue_close()
self.queue_thread.wait(self.timeout)
except BaseException:
self.exception("Closed during concurrent action")
if self.queue_thread.is_alive():
self.error("Queue thread was not terminated.")
def graceful_stop(self):
self.debug('')
if self.has_sent_messages:
self.wait_process(self.timeout, key_suffix='.graceful_stop')
super(ModelDriver, self).graceful_stop()
def cleanup_products(self):
if self.overwrite and (not self.preserve_cache):
self.remove_products()
self.restore_files()
def cleanup(self):
self.cleanup_products()
super(ModelDriver, self).cleanup()
def restore_files(self):
for (original, modified) in self.modified_files:
if os.path.isfile(original):
os.remove(modified)
shutil.move(original, modified)
def remove_products(self):
products = self.products
source_products = self.source_products + self.wrapper_products
remove_products(products, source_products)
@classmethod
def cleanup_dependencies(cls, products=[], verbose=False):
for x in products:
if os.path.isfile(x):
if verbose:
print("Removing %s" % x)
os.remove(x)
@classmethod
def run_code(cls, lines, process_kwargs={}, **kwargs):
name = 'test_code_%s' % str(uuid.uuid4())[:13].replace('-', '_')
working_dir = os.getcwd()
code_dir = tempfile.gettempdir()
fname = os.path.join(code_dir, name + cls.get_language_ext()[0])
lines = cls.write_executable(lines, **kwargs)
with open(fname, 'w') as fd:
fd.write('\n'.join(lines))
inst = None
try:
assert(os.path.isfile(fname))
inst = cls(name, [fname], working_dir=working_dir)
inst.run_model(return_process=False, **process_kwargs)
except BaseException:
logger.error('Failed generated code:\n%s' % '\n'.join(lines))
raise
finally:
if os.path.isfile(fname):
os.remove(fname)
if inst is not None:
inst.cleanup()
@classmethod
def format_function_param(cls, key, default=None, replacement=None,
ignore_method=False, **kwargs):
if replacement is not None:
fmt = replacement
elif (not ignore_method) and hasattr(cls, 'format_function_param_%s' % key):
return getattr(cls, 'format_function_param_%s' % key)(**kwargs)
else:
if (key not in cls.function_param) and (default is None):
raise NotImplementedError(("Language %s dosn't have an entry in "
"function_param for key '%s'")
% (cls.language, key))
fmt = cls.function_param.get(key, default)
return fmt.format(**kwargs)
@classmethod
def parse_var_definition(cls, io, value, outputs_in_inputs=None):
if outputs_in_inputs is None:
outputs_in_inputs = cls.outputs_in_inputs
assert(io in ['inputs', 'outputs'])
if ('%s_def_regex' % io) not in cls.function_param: # pragma: debug
raise NotImplementedError(
("'%s_def_regex' not defined for "
"language %s.") % (io, cls.language))
if 'multiple_outputs' in cls.function_param:
multi_re = cls.function_param['multiple_outputs']
for x in '[]()':
multi_re = multi_re.replace(x, '\\' + x)
multi_re = multi_re.format(outputs='(.*?)')
match = re.search(multi_re, value)
if match is not None:
value = match.group(1)
new_val = []
io_re = cls.format_function_param('%s_def_regex' % io)
for i, ivar in enumerate(cls.split_variables(value)):
igrp = {'name': ivar}
x = re.search(io_re, ivar)
if x is not None:
igrp = x.groupdict()
for k in list(igrp.keys()):
if igrp[k] is None:
del igrp[k]
if 'native_type' in igrp:
igrp['native_type'] = igrp['native_type'].replace(' ', '')
igrp['datatype'] = cls.get_json_type(igrp['native_type'])
igrp['position'] = i
if (io == 'outputs') and outputs_in_inputs:
igrp = cls.input2output(igrp)
new_val.append(igrp)
return new_val
@classmethod
def parse_function_definition(cls, model_file, model_function,
contents=None, match=None,
expected_outputs=[], outputs_in_inputs=None):
if outputs_in_inputs is None:
outputs_in_inputs = cls.outputs_in_inputs
out = {}
if match or ('function_def_regex' in cls.function_param):
if not match:
function_regex = cls.format_function_param(
'function_def_regex', function_name=model_function)
if contents is None:
with open(model_file, 'r') as fd:
contents = fd.read()
match = re.search(function_regex, contents)
if not match: # pragma: debug
raise RuntimeError(("Could not find function match in file:\n"
"%s\nfor regex:\nr'%s'")
% (pformat(contents), function_regex))
# Match brackets to determine where the function definition is
if isinstance(cls.brackets, tuple):
assert(len(cls.brackets) == 2)
contents = match.group(0)
counts = {k: 0 for k in cls.brackets}
first_zero = 0
re_brackets = r'[\%s\%s]' % cls.brackets
for x in re.finditer(re_brackets, contents):
counts[x.group(0)] += 1
if (((counts[cls.brackets[0]] > 0)
and (counts[cls.brackets[0]]
== counts[cls.brackets[1]]))):
first_zero = x.span(0)[1]
break
assert((first_zero == 0) or (first_zero == len(contents)))
# This is currently commented as regex's are
out = match.groupdict()
for k in list(out.keys()):
if out[k] is None:
del out[k]
for io in ['inputs', 'outputs']:
if io in out:
out[io] = cls.parse_var_definition(
io, out[io], outputs_in_inputs=outputs_in_inputs)
out['model_file'] = model_file
if outputs_in_inputs and expected_outputs and (not out.get('outputs', False)):
missing_expected_outputs = []
for o in expected_outputs:
if isinstance(o, dict):
o = o['name']
missing_expected_outputs.append(o)
out['outputs'] = []
for x in out['inputs']:
if x['name'] not in missing_expected_outputs:
continue
missing_expected_outputs.remove(x['name'])
out['outputs'].append(cls.input2output(x))
if missing_expected_outputs:
raise ValueError(("Could not locate %d output "
"variable(s) in input: %s")
% (len(missing_expected_outputs),
missing_expected_outputs))
for x in out['outputs']:
out['inputs'].remove(x)
if out.get('flag_var', None):
flag_var = {'name': out.pop('flag_var'),
'datatype': {'type': 'flag'}}
if out.get('flag_type', None):
flag_var['native_type'] = out.pop('flag_type').replace(' ', '')
flag_var['datatype'] = cls.get_json_type(flag_var['native_type'])
out['flag_var'] = flag_var
cls.check_flag_var(out, outputs_in_inputs=outputs_in_inputs)
return out
@classmethod
def check_flag_var(cls, info, outputs_in_inputs=None):
if outputs_in_inputs is None:
outputs_in_inputs = cls.outputs_in_inputs
flag_t = cls.type_map['flag']
if (((info.get('flag_var', {}).get('native_type', flag_t) != flag_t)
or (not outputs_in_inputs))):
if info.get('outputs', []):
logger.warn("Support for returning outputs via parameter(s) "
"and return value is not yet support. The return "
"value will be assumed to be a flag indicating "
"the success of the model.")
info['outputs_in_inputs'] = True
else:
info['outputs'] = [info.pop('flag_var')]
info['outputs_in_inputs'] = False
@classmethod
def channels2vars(cls, channels):
if not isinstance(channels, list):
channels = [channels]
variables = []
for x in channels:
variables += x['vars']
def get_pos(x):
return x.get('position', 0)
variables = sorted(variables, key=get_pos)
return variables
@classmethod
def expand_server_io(cls, inputs, outputs, client_comms=[]):
if client_comms:
warnings.warn("When wrapping a model function, client comms "
"must either be initialized outside the function, "
"pass a 'global_scope' parameter to the "
"comm initialization (e.g. Python, R, Matlab), "
"or use a 'WITH_GLOBAL_SCOPE' macro "
"(e.g. C, C++, Fortran) around the initialization "
"so that they are persistent "
"across calls and the call or recv/send methods "
"must be called explicitly (as opposed to the "
"function inputs/outputs which will be handled "
"by the wrapper). This model's client comms are:\n"
"\t%s" % client_comms)
# Replace server input w/ split input/output and remove client
# connections from inputs
for i, x in enumerate(inputs):
if x.get('server_replaces', False):
inputs[x['server_replaces']['input_index']] = (
x['server_replaces']['input'])
outputs.insert(x['server_replaces']['output_index'],
x['server_replaces']['output'])
rm_outputs = [i for i, x in enumerate(outputs)
if x['name'] in client_comms]
for i in rm_outputs[::-1]:
outputs.pop(i)
@classmethod
def preparse_function(cls, yml):
if 'function' not in yml:
return
if yml.get('is_server', False):
assert(isinstance(yml['is_server'], dict))
if cls.function_param is None:
raise ValueError(("Language %s is not parameterized "
"and so functions cannot be automatically "
"wrapped as a model.") % cls.language)
source_files = cls.identify_source_files(**yml)
if not source_files: # pragma: debug
raise ValueError("Could not identify any source files.")
model_function_file = source_files[0]
if not os.path.isfile(model_function_file): # pragma: debug
raise ValueError("Source file does not exist: '%s'"
% model_function_file)
# Update input/outputs based on parsed source code
client_comms = ['%s:%s_%s' % (yml['name'], x, yml['name'])
for x in yml.get('client_of', [])]
model_function_inputs = copy.copy(yml.get('inputs', []))
model_function_outputs = copy.copy(yml.get('outputs', []))
cls.expand_server_io(
model_function_inputs, model_function_outputs,
client_comms=client_comms)
expected_outputs = []
for x in model_function_outputs:
expected_outputs += x.get('vars', [])
model_outputs_in_inputs = yml.get('outputs_in_inputs', None)
model_function_info = cls.parse_function_definition(
model_function_file, yml['function'],
expected_outputs=expected_outputs,
outputs_in_inputs=model_outputs_in_inputs)
if model_outputs_in_inputs is None:
model_outputs_in_inputs = model_function_info.get(
'outputs_in_inputs', None)
model_flag = cls.update_io_from_function(
model_function_info, yml['function'],
inputs=model_function_inputs,
outputs=model_function_outputs,
iter_function_over=yml.get('iter_function_over', []))
yml['preparsed_function'] = {
'model_file': model_function_info,
'model_function': yml['function'],
'inputs': model_function_inputs,
'outputs': model_function_outputs,
'model_flag': model_flag,
'outputs_in_inputs': model_outputs_in_inputs,
'copies': yml.get('copies', 1),
'iter_function_over': yml.get('iter_function_over', []),
'skip_update_io': True}
return yml['preparsed_function']
@classmethod
def update_io_from_function(cls, model_file, model_function,
inputs=[], outputs=[], contents=None,
outputs_in_inputs=None, iter_function_over=[]):
# Read info from the source code
if (((isinstance(model_file, str) and os.path.isfile(model_file))
or (contents is not None))): # pragma: debug
expected_outputs = []
for x in outputs:
expected_outputs += x.get('vars', [])
info = cls.parse_function_definition(model_file, model_function,
contents=contents,
expected_outputs=expected_outputs)
logger.warn("The new execution pattern reuses the parsed "
"source code parameters. Double check results:\n%s."
% pformat(info))
elif isinstance(model_file, dict):
info = model_file
else:
info = {"inputs": [], "outputs": []}
if outputs_in_inputs is None: # pragma: debug
outputs_in_inputs = info.get('outputs_in_inputs',
cls.outputs_in_inputs)
info_map = {io: OrderedDict([(x['name'], x) for x in info.get(io, [])])
for io in ['inputs', 'outputs']}
# Determine flag variable
flag_var = None
if info.get('flag_var', None):
flag_var = dict(info['flag_var'], name='model_flag')
# Check for vars matching names of input/output channels
for io, io_var in zip(['inputs', 'outputs'], [inputs, outputs]):
if (io == 'outputs') and outputs_in_inputs:
io_map = info_map['inputs']
else:
io_map = info_map[io]
for x in io_var:
if x.get('vars', []):
continue
var_name = x['name'].split(':')[-1]
if var_name in io_map:
x['vars'] = [var_name]
for k in ['length', 'shape', 'ndim']:
kvar = '%s_var' % k
if kvar in io_map[var_name]:
x['vars'].append(io_map[var_name][kvar])
# Move variables if outputs in inputs
if outputs_in_inputs:
if ((((len(inputs) + len(outputs)) == len(info.get('inputs', [])))
and (len(info.get('outputs', [])) == 0))):
for i, vdict in enumerate(info['inputs'][:len(inputs)]):
inputs[i].setdefault('vars', [vdict['name']])
assert(inputs[i]['vars'] == [vdict['name']])
for i, vdict in enumerate(info['inputs'][len(inputs):]):
outputs[i].setdefault('vars', [vdict['name']])
assert(outputs[i]['vars'] == [vdict['name']])
for x in outputs:
for i, v in enumerate(x.get('vars', [])):
if v in info_map['inputs']:
info_map['outputs'][v] = cls.input2output(
info_map['inputs'].pop(v))
for io, io_var in zip(['inputs', 'outputs'], [inputs, outputs]):
for x in io_var:
x['channel_name'] = x['name']
x['channel'] = (x['name'].split(':', 1)[-1]
+ '_%s_channel' % io[:-1])
for i, v in enumerate(x.get('vars', [])):
if v in info_map[io]:
x['vars'][i] = info_map[io][v]
if (len(io_var) == 1) and info_map.get(io, False):
io_var[0].setdefault('vars', list(info_map[io].values()))
for x in io_var:
if 'vars' not in x:
x['vars'] = [copy.deepcopy(x)]
x['vars'][0]['name'] = x['name'].split(':', 1)[-1]
for v in x['vars']:
if isinstance(v.get('datatype', None), str):
v['datatype'] = {'type': v['datatype']}
if isinstance(x.get('datatype', None), str):
x['datatype'] = {'type': x['datatype']}
# Check for user defined length variables and add flag to
# length variables
for x in io_var:
for k in ['length', 'shape', 'ndim']:
for v in x['vars']:
if k + '_var' in v:
v[k + '_var'] = info_map[io][v[k + '_var']]
# v[k + '_var']['is_' + k + '_var'] = True
v[k + '_var']['is_length_var'] = True
else:
v[k + '_var'] = False
# Update datatypes
if cls.is_typed:
for x in io_var:
non_length = []
for v in x['vars']:
if not v.get('is_length_var', False):
non_length.append(v)
if ((x.get('datatype', None)
and (not is_default_typedef(x['datatype'])))):
if (len(non_length) == 1):
non_length[0]['datatype'] = x['datatype']
else:
# TODO: Remove types associated with length?
assert(x['datatype']['type'] == 'array')
assert(len(x['datatype']['items'])
== len(non_length))
for v, t in zip(non_length, x['datatype']['items']):
v['datatype'] = t
else:
if (len(non_length) == 1):
x['datatype'] = non_length[0]['datatype']
else:
x['datatype'] = {
'type': 'array',
'items': [v['datatype'] for v in non_length]}
x['datatype']['from_function'] = True
for v in x['vars']:
if 'native_type' not in v:
v['native_type'] = cls.get_native_type(**v)
# Update types based on iteration
for x in io_var:
for v in x.get('vars', [x]):
if v['name'] in iter_function_over:
v['iter_datatype'] = copy.deepcopy(v.get('datatype', {}))
if v.get('datatype', {}):
assert(v['datatype']['type'] == 'scalar')
v['datatype']['type'] = '1darray'
v.pop('native_type', None)
v['native_type'] = cls.get_native_type(**v)
# Finalize io variables
for x in inputs:
cls.finalize_function_io('input', x)
for x in outputs:
cls.finalize_function_io('output', x)
return flag_var
@classmethod
def finalize_function_io(cls, direction, x):
assert(direction in ['input', 'output'])
@classmethod
def write_model_wrapper(cls, model_file, model_function,
inputs=[], outputs=[], model_flag=None,
outputs_in_inputs=None, verbose=False, copies=1,
iter_function_over=[], verbose_model=False,
skip_update_io=False, model_name=None):
if outputs_in_inputs is None:
outputs_in_inputs = cls.outputs_in_inputs
# TODO: Determine how to encode dependencies on external variables in models
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
# Update types based on the function definition for typed languages
if not skip_update_io:
model_flag = cls.update_io_from_function(
model_file, model_function,
inputs=inputs, outputs=outputs,
outputs_in_inputs=outputs_in_inputs,
iter_function_over=iter_function_over)
if isinstance(model_file, dict):
model_file = model_file['model_file']
# Update types based on iteration
iter_function_idx = None
iter_ivars = []
iter_ovars = []
if iter_function_over:
iter_function_idx = {'name': 'idx_func_iter',
'datatype': {'type': 'int'}}
if cls.zero_based:
iter_function_idx['begin'] = int(0)
else:
iter_function_idx['begin'] = int(1)
for x in inputs:
iter_ivars += [v for v in x.get('vars', [x])
if v['name'] in iter_function_over]
if not iter_ivars: # pragma: debug
raise RuntimeError("The iter_function_over model "
"parameter must include an input to "
"iterate over. To expand output arrays "
"into component elements, use the "
"'iterate' transformation.")
for x in outputs:
iter_ovars += [v for v in x.get('vars', [x])
if v['name'] in iter_function_over]
if iter_ivars[0].get('length_var', False):
iter_function_idx['end'] = iter_ivars[0]['length_var']
for v in iter_ovars:
v['length_var'] = iter_ivars[0]['length_var']['name']
if isinstance(iter_function_idx['end'], dict):
iter_function_idx['end'] = iter_function_idx['end']['name']
else:
iter_function_idx['end'] = cls.format_function_param(
'len', variable=iter_ivars[0]['name'],
extra=iter_ivars[0])
for v in iter_ivars + iter_ovars:
v['iter_var'] = iter_function_idx
# Declare variables and flag, then define flag
lines = []
flag_var = {'name': 'flag', 'datatype': {'type': 'flag'}}
iter_var = {'name': 'first_iter', 'datatype': {'type': 'flag'}}
free_vars = []
definitions = []
if 'declare' in cls.function_param:
for x in inputs + outputs:
lines += cls.write_channel_decl(
x, definitions=definitions,
requires_freeing=free_vars)
lines += cls.write_declaration(flag_var,
definitions=definitions,
requires_freeing=free_vars)
lines += cls.write_declaration(iter_var,
definitions=definitions,
requires_freeing=free_vars)
if model_flag:
lines += cls.write_declaration(
model_flag, definitions=definitions,
requires_freeing=free_vars)
if iter_function_idx:
lines += cls.write_declaration(
iter_function_idx, definitions=definitions,
requires_freeing=free_vars)
for x in inputs + outputs:
for v in x.get('vars', [x]):
lines += cls.write_declaration(
v, definitions=definitions,
requires_freeing=free_vars)
lines += definitions
nline_preamble = len(lines)
lines.append(cls.format_function_param(
'assign', name=flag_var['name'],
value=cls.function_param.get(
'true_flag', cls.function_param['true'])))
lines.append(cls.format_function_param(
'assign', name=iter_var['name'],
value=cls.function_param.get(
'true_flag', cls.function_param['true'])))
# Declare/define input and output channels
for x in inputs:
lines += cls.write_channel_def('input',
requires_freeing=free_vars, **x)
for x in outputs:
lines += cls.write_channel_def('output',
requires_freeing=free_vars, **x)
# Receive inputs before loop
for x in inputs:
if x.get('outside_loop', False):
lines += cls.write_model_recv(x['channel'], x,
flag_var=flag_var)
# Loop
loop_lines = []
# Receive inputs
any_loop_inputs = False
loop_iter_var = iter_var
if copies > 1:
loop_iter_var = None
for x in inputs:
if not x.get('outside_loop', False):
any_loop_inputs = True
loop_lines += cls.write_model_recv(x['channel'], x,
flag_var=flag_var,
iter_var=loop_iter_var,
allow_failure=True)
# Prepare output array
if iter_function_over:
for v in iter_ivars:
if v['name'] in iter_function_over:
loop_lines += cls.write_finalize_iiter(v)
for v in iter_ovars:
if v['name'] in iter_function_over:
loop_lines += cls.write_initialize_oiter(v)
# Call model
loop_lines += cls.write_model_function_call(
model_function, model_flag, inputs, outputs,
outputs_in_inputs=outputs_in_inputs,
iter_function_idx=iter_function_idx)
# Finalize output array
if iter_function_over:
for v in iter_ovars:
if v['name'] in iter_function_over:
loop_lines += cls.write_finalize_oiter(v)
# Send outputs
for x in outputs:
if not x.get('outside_loop', False):
loop_lines += cls.write_model_send(x['channel'], x,
flag_var=flag_var)
loop_lines.append(cls.format_function_param(
'assign', name=iter_var['name'],
value=cls.function_param.get('false_flag',
cls.function_param['false'])))
# Add break if there are not any inputs inside the loop
if not any_loop_inputs:
loop_lines.append(cls.format_function_param(
'assign', name=flag_var['name'],
value=cls.function_param.get(
'false_flag', cls.function_param['false'])))
# Add loop in while block
flag_cond = cls.format_function_param('flag_cond',
default='{flag_var}',
flag_var=flag_var['name'])
lines += cls.write_while_loop(flag_cond, loop_lines)
# Send outputs after loop
for x in outputs:
if x.get('outside_loop', False):
lines += cls.write_model_send(x['channel'], x,
flag_var=flag_var)
# Free variables
for x in free_vars:
lines += cls.write_free(x)
# Add prints
if verbose_model: # pragma: debug
idx = len(lines) - 1
while (idx > nline_preamble):
if 'else' not in lines[idx]:
indent = ' ' * (len(lines[idx])
- len(lines[idx].lstrip()))
lines.insert(idx, indent + cls.format_function_param(
'print', message=("%s: line %d" % (model_file, idx))))
idx -= 1
# Wrap as executable with interface & model import
prefix = None
if 'interface' in cls.function_param:
ygglib = cls.interface_library
if ygglib in cls.internal_libraries:
ygglib = cls.internal_libraries[ygglib]['source']
if cls.interface_inside_exec:
lines.insert(0, cls.format_function_param(
'interface', interface_library=ygglib))
else:
prefix = [cls.format_function_param(
'interface', interface_library=ygglib)]
out = cls.write_executable(lines, prefix=prefix,
model_name=model_name,
imports={'filename': model_file,
'function': model_function})
if verbose: # pragma: debug
logger.info('\n' + '\n'.join(out))
else:
logger.debug('\n' + '\n'.join(out))
return out
@classmethod
def write_channel_decl(cls, var, **kwargs):
out = []
if not cls.dont_declare_channel:
out = cls.write_declaration(
{'name': var['channel'], 'type': 'comm'}, **kwargs)
if (((var.get('datatype', None) is not None)
and ('{channel_type}' in cls.function_param['input']))):
var['channel_type'] = '%s_type' % var['channel']
out += cls.write_type_decl(
var['channel_type'], var['datatype'],
definitions=kwargs.get('definitions', None),
requires_freeing=kwargs.get('requires_freeing', None))
return out
@classmethod
def write_type_decl(cls, name, datatype, name_base=None,
requires_freeing=None, definitions=None,
no_decl=False):
out = []
if name_base is None:
name_base = name
if datatype['type'] == 'array':
if 'items' in datatype:
assert(isinstance(datatype['items'], list))
out += cls.write_declaration(
{'name': '%s_items' % name_base,
'datatype': {
'type': '1darray', 'subtype': 'dtype',
'length': len(datatype['items'])}},
definitions=definitions,
requires_freeing=requires_freeing)
for i, x in enumerate(datatype['items']):
# Prevent recusion
x_copy = copy.deepcopy(x)
x_copy.pop('items', None)
x_copy.pop('properties', None)
out += cls.write_type_decl(
None, x_copy,
name_base=('%s_item%d' % (name_base, i)),
definitions=definitions,
requires_freeing=requires_freeing,
no_decl=True)
elif datatype['type'] == 'object':
if 'properties' in datatype:
assert(isinstance(datatype['properties'], dict))
precision = 0
if datatype['properties']:
precision = max([len(k) for k in
datatype['properties'].keys()])
precision = max(80, precision)
out += cls.write_declaration(
{'name': '%s_keys' % name_base,
'datatype': {
'type': '1darray', 'subtype': 'bytes',
'length': len(datatype['properties']),
'precision': precision}},
definitions=definitions,
requires_freeing=requires_freeing)
out += cls.write_declaration(
{'name': '%s_vals' % name_base,
'datatype': {
'type': '1darray', 'subtype': 'dtype',
'length': len(datatype['properties'])}},
definitions=definitions,
requires_freeing=requires_freeing)
for i, (k, v) in enumerate(datatype['properties'].items()):
# Prevent recusion
v_copy = copy.deepcopy(v)
v_copy.pop('items', None)
v_copy.pop('properties', None)
out += cls.write_type_decl(
None, v_copy,
name_base=('%s_prop%d' % (name_base, i)),
requires_freeing=requires_freeing,
definitions=definitions,
no_decl=True)
elif datatype['type'] == 'ndarray':
if 'shape' in datatype:
out += cls.write_declaration(
{'name': '%s_shape' % name_base,
'datatype': {
'type': '1darray', 'subtype': 'int',
'precision': 64, 'length': len(datatype['shape'])}},
definitions=definitions,
requires_freeing=requires_freeing)
elif datatype['type'] in (['ply', 'obj', '1darray', 'scalar',
'boolean', 'null', 'number', 'integer',
'string', 'class', 'function', 'instance',
'schema', 'any']
+ list(constants.VALID_TYPES.keys())):
pass
else: # pragma: debug
raise ValueError(("Cannot create %s version of type "
"'%s'") % (cls.language, datatype['type']))
if not no_decl:
out += cls.write_declaration(
{'name': name, 'type': 'dtype'})
return out
@classmethod
def write_type_def(cls, name, datatype, name_base=None,
use_generic=False):
out = []
fmt = None
keys = {}
if use_generic:
keys['use_generic'] = cls.function_param['true']
else:
keys['use_generic'] = cls.function_param['false']
typename = datatype['type']
if name_base is None:
name_base = name
if datatype['type'] == 'array':
if 'items' in datatype:
assert(isinstance(datatype['items'], list))
keys['nitems'] = len(datatype['items'])
keys['items'] = '%s_items' % name_base
if cls.zero_based:
idx_offset = 0
else:
idx_offset = 1
for i, x in enumerate(datatype['items']):
# Prevent recusion
x_copy = copy.deepcopy(x)
x_copy.pop('items', None)
x_copy.pop('properties', None)
out += cls.write_type_def(
cls.format_function_param(
'index', variable=keys['items'],
index=(i + idx_offset)), x_copy,
name_base=('%s_item%d' % (name_base, i)),
use_generic=use_generic)
else:
keys['nitems'] = 0
keys['items'] = cls.function_param['null']
keys['use_generic'] = cls.function_param['true']
elif datatype['type'] == 'object':
keys['use_generic'] = cls.function_param['true']
if 'properties' in datatype:
assert(isinstance(datatype['properties'], dict))
keys['nitems'] = len(datatype['properties'])
keys['keys'] = '%s_keys' % name_base
keys['values'] = '%s_vals' % name_base
if cls.zero_based:
idx_offset = 0
else:
idx_offset = 1
for i, (k, v) in enumerate(datatype['properties'].items()):
# Prevent recusion
v_copy = copy.deepcopy(v)
v_copy.pop('items', None)
v_copy.pop('properties', None)
out.append(cls.format_function_param(
'assign', value='\"%s\"' % k,
name=cls.format_function_param(
'index', variable=keys['keys'],
index=(i + idx_offset))))
out += cls.write_type_def(
cls.format_function_param(
'index', variable=keys['values'],
index=(i + idx_offset)), v_copy,
name_base=('%s_prop%d' % (name_base, i)),
use_generic=use_generic)
else:
keys['nitems'] = 0
keys['keys'] = cls.function_param['null']
keys['values'] = cls.function_param['null']
elif datatype['type'] in ['ply', 'obj']:
pass
elif datatype['type'] == '1darray':
for k in ['subtype', 'precision']:
keys[k] = datatype[k]
keys['precision'] = int(keys['precision'])
keys['length'] = datatype.get('length', '0')
keys['units'] = datatype.get('units', '')
elif datatype['type'] == 'ndarray':
for k in ['subtype', 'precision']:
keys[k] = datatype[k]
keys['precision'] = int(keys['precision'])
if 'shape' in datatype:
shape_var = '%s_shape' % name_base
if cls.zero_based:
idx_offset = 0
else:
idx_offset = 1
for i, x in enumerate(datatype['shape']):
out.append(cls.format_function_param(
'assign', value=x,
name=cls.format_function_param(
'index', variable=shape_var,
index=(i + idx_offset))))
keys['ndim'] = len(datatype['shape'])
keys['shape'] = shape_var
typename = 'ndarray_arr'
else:
keys['ndim'] = 0
keys['shape'] = cls.function_param['null']
keys['units'] = datatype.get('units', '')
elif (typename == 'scalar') or (typename in constants.VALID_TYPES):
keys['subtype'] = datatype.get('subtype', datatype['type'])
keys['units'] = datatype.get('units', '')
if keys['subtype'] in ['bytes', 'string', 'unicode']:
keys['precision'] = int(datatype.get('precision', 0))
else:
keys['precision'] = int(datatype['precision'])
typename = 'scalar'
elif datatype['type'] in ['boolean', 'null', 'number',
'integer', 'string']:
keys['type'] = datatype['type']
typename = 'default'
elif (typename in ['class', 'function']):
keys['type'] = typename
typename = 'pyobj'
elif typename in ['instance', 'any']:
keys['use_generic'] = cls.function_param['true']
typename = 'empty'
elif typename in ['schema']:
keys['use_generic'] = cls.function_param['true']
else: # pragma: debug
raise ValueError("Cannot create %s version of type '%s'"
% (cls.language, typename))
fmt = cls.format_function_param('init_type_%s' % typename, **keys)
out.append(cls.format_function_param('assign', name=name,
value=fmt))
return out
@classmethod
def write_channel_def(cls, key, datatype=None, **kwargs):
out = []
if (datatype is not None) and ('{channel_type}' in cls.function_param[key]):
kwargs['channel_type'] = '%s_type' % kwargs['channel']
out += cls.write_type_def(
kwargs['channel_type'], datatype,
use_generic=kwargs.get('use_generic', False))
dir_map = {'input': 'recv', 'output': 'send'}
try_keys = [dir_map[key] + '_converter', 'transform']
try_vals = []
if all([bool(kwargs.get(k, False)) for k in try_keys]): # pragma: debug
# TODO: Handling merger of the transforms in yaml or
# remove the *_converter options entirely
raise RuntimeError(("Transforms are specified in multiple "
"locations for this input: %s")
% str(try_keys))
for k in try_keys:
if k in kwargs:
v = kwargs[k]
if not isinstance(v, list):
v = [v]
try_vals += v
# This last transform is used because the others are assumed
# to be applied by the connection driver
if try_vals and isinstance(try_vals[-1], str):
try_key = '%s_%s' % (try_vals[-1], key)
if ((('python_interface' in cls.function_param)
and (try_key in cls.python_interface))):
kwargs['python_interface'] = cls.python_interface[try_key]
if ((('format_str' in kwargs)
and ('python_interface_format' in cls.function_param))):
key = 'python_interface_format'
kwargs['format_str'] = kwargs['format_str'].encode(
"unicode_escape").decode('utf-8')
else:
key = 'python_interface'
out += [cls.format_function_param(key, **kwargs)]
return out
@classmethod
def write_model_function_call(cls, model_function, flag_var, inputs, outputs,
outputs_in_inputs=None, on_failure=None,
format_not_flag_cond=None, format_flag_cond=None,
iter_function_idx=None):
if outputs_in_inputs is None: # pragma: debug
outputs_in_inputs = cls.outputs_in_inputs
func_inputs = cls.channels2vars(inputs)
func_outputs = cls.channels2vars(outputs)
if iter_function_idx:
for src in [func_inputs, func_outputs]:
for i, x in enumerate(src):
if 'iter_datatype' in x:
src[i] = dict(
x, datatype=x['iter_datatype'],
name=cls.format_function_param(
'index', variable=x['name'],
index=iter_function_idx['name'],
extra=x),
length_var=False)
if isinstance(flag_var, dict):
flag_var = flag_var['name']
out = cls.write_function_call(
model_function, inputs=func_inputs, outputs=func_outputs,
flag_var=flag_var, outputs_in_inputs=outputs_in_inputs)
if flag_var and outputs_in_inputs:
if (not format_flag_cond) and ('not_flag_cond' in cls.function_param):
flag_cond = cls.format_function_param(
'not_flag_cond', flag_var=flag_var,
replacement=format_not_flag_cond)
else: # pragma: debug
# flag_cond = '%s (%s)' % (
# cls.function_param['not'],
# cls.format_function_param(
# 'flag_cond', default='{flag_var}', flag_var=flag_var,
# replacement=format_flag_cond))
raise RuntimeError("Untested code below. Uncomment "
"at your own risk if you find "
"use case for it.")
if on_failure is None:
on_failure = [cls.format_function_param(
'error', error_msg="Model call failed.")]
out += cls.write_if_block(flag_cond, on_failure)
if iter_function_idx:
out = cls.write_for_loop(iter_function_idx['name'],
iter_function_idx['begin'],
iter_function_idx['end'],
out)
return out
@classmethod
def write_model_recv(cls, channel, recv_var, flag_var='flag',
iter_var=None, allow_failure=False,
alt_recv_function=None):
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
recv_var_str = recv_var
if not isinstance(recv_var, str):
recv_var_par = cls.channels2vars(recv_var)
recv_var_str = cls.prepare_output_variables(
recv_var_par, in_inputs=cls.outputs_in_inputs,
for_yggdrasil=True)
else:
recv_var_par = cls.split_variables(recv_var_str)
expanded_recv_var = None
if (len(recv_var_par) > 1) and ('multiple_outputs' in cls.function_param):
expanded_recv_var = recv_var_str
recv_var_str = 'temp_%s' % recv_var_par[0]['name']
if isinstance(flag_var, dict):
flag_var = flag_var['name']
if isinstance(iter_var, dict):
iter_var = iter_var['name']
if cls.outputs_in_inputs:
inputs = [recv_var_str]
outputs = [flag_var]
else:
inputs = []
outputs = [flag_var, recv_var_str]
if cls.include_channel_obj:
inputs.insert(0, channel)
lines = cls.write_function_call(
cls.format_function_param('recv_function', channel=channel,
replacement=alt_recv_function),
inputs=inputs, outputs=outputs, include_arg_count=cls.include_arg_count)
if 'not_flag_cond' in cls.function_param:
flag_cond = cls.format_function_param('not_flag_cond',
flag_var=flag_var)
else:
flag_cond = '%s (%s)' % (
cls.function_param['not'],
cls.format_function_param('flag_cond', default='{flag_var}',
flag_var=flag_var))
fail_message = cls.escape_quotes(
"Could not receive %s." % recv_var_str)
if allow_failure:
fail_message = cls.escape_quotes(
'End of input from %s.' % recv_var_str)
if_block = [cls.format_function_param('print', message=fail_message),
cls.function_param.get('break', 'break')]
if iter_var is not None:
if_block = cls.write_if_block(
iter_var,
[cls.format_function_param(
'error', error_msg=cls.escape_quotes(
'No input from %s.' % recv_var_str))],
if_block)
else:
if_block = [cls.format_function_param('error', error_msg=fail_message)]
lines += cls.write_if_block(flag_cond, if_block)
# Check if single element should be expanded
if expanded_recv_var:
# lines.append(cls.format_function_param(
# 'print_generic', object=recv_var_str))
if 'expand_mult' in cls.function_param: # pragma: matlab
lines.append(cls.format_function_param(
'expand_mult', name=expanded_recv_var, value=recv_var_str))
elif 'assign_mult' in cls.function_param:
lines.append(cls.format_function_param(
'assign_mult', name=expanded_recv_var, value=recv_var_str))
else:
lines.append(cls.format_function_param(
'assign', name=expanded_recv_var, value=recv_var_str))
elif len(recv_var_par) == 1:
lines += cls.write_expand_single_element(recv_var_str)
return lines
@classmethod
def write_model_send(cls, channel, send_var, flag_var='flag',
allow_failure=False):
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
send_var_str = send_var
if not isinstance(send_var_str, str):
send_var_par = cls.channels2vars(send_var)
send_var_str = cls.prepare_input_variables(
send_var_par, for_yggdrasil=True)
if isinstance(flag_var, dict):
flag_var = flag_var['name']
if cls.include_channel_obj:
send_var_str = [channel, send_var_str]
lines = cls.write_function_call(
cls.format_function_param('send_function', channel=channel),
inputs=send_var_str,
outputs=flag_var, include_arg_count=cls.include_arg_count)
flag_cond = '%s (%s)' % (
cls.function_param['not'],
cls.format_function_param('flag_cond', default='{flag_var}',
flag_var=flag_var))
fail_message = cls.escape_quotes(
"Could not send %s." % send_var_str)
if allow_failure: # pragma: no cover
# This is not particularly useful, but is included for completion
if_block = [cls.format_function_param('print', message=fail_message),
cls.function_param.get('break', 'break')]
else:
if_block = [cls.format_function_param('error', error_msg=fail_message)]
lines += cls.write_if_block(flag_cond, if_block)
return lines
@classmethod
def write_print_var(cls, var, prefix_msg=None):
out = []
print_key = None
varname = var
if isinstance(var, dict):
varname = var['name']
typename = var.get(
'datatype',
{'type': var.get('type', None)}).get('type', None)
if ('print_%s' % typename) in cls.function_param:
print_key = ('print_%s' % typename)
elif 'print_generic' in cls.function_param:
print_key = 'print_generic'
elif 'print_generic' in cls.function_param:
print_key = 'print_generic'
if print_key:
if prefix_msg is not None:
out.append(cls.format_function_param(
'print', message=prefix_msg))
out += [cls.format_function_param(
print_key, object=varname)]
return out
@classmethod
def write_print_input_var(cls, var, **kwargs):
return cls.write_print_var(var, **kwargs)
@classmethod
def write_print_output_var(cls, var, in_inputs=False, **kwargs):
return cls.write_print_var(var, **kwargs)
@classmethod
def write_function_def(cls, function_name, inputs=[], outputs=[],
input_var=None, output_var=None,
function_contents=[],
outputs_in_inputs=False,
opening_msg=None, closing_msg=None,
print_inputs=False, print_outputs=False,
skip_interface=False, function_keys=None,
verbose=False, **kwargs):
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
if function_keys is None:
function_keys = ('function_def_begin', 'function_def_end')
out = []
interface_lines = []
if ('interface' in cls.function_param) and (not skip_interface):
ygglib = cls.interface_library
if ygglib in cls.internal_libraries:
ygglib = cls.internal_libraries[ygglib]['source']
interface_lines.append(cls.format_function_param(
'interface', interface_library=ygglib))
if not cls.interface_inside_exec:
out += interface_lines
flag_var = {}
if input_var is None:
input_var = cls.prepare_input_variables(
inputs, in_definition=True)
if output_var is None:
output_var = cls.prepare_output_variables(
outputs, in_inputs=outputs_in_inputs, in_definition=True)
print_input_lines = []
if print_inputs and inputs:
for x in inputs:
print_input_lines += cls.write_print_input_var(
x, prefix_msg=('INPUT[%s]:' % x['name']))
print_output_lines = []
if print_outputs and outputs:
for x in outputs:
print_output_lines += cls.write_print_output_var(
x, prefix_msg=('OUTPUT[%s]:' % x['name']),
in_inputs=outputs_in_inputs)
old_outputs = []
if outputs_in_inputs:
if output_var:
input_var = cls.prepare_input_variables(
[input_var, output_var])
flag_var = kwargs.get('flag_var', 'flag')
if isinstance(flag_var, str):
flag_var = {'name': flag_var}
flag_var.setdefault('datatype', 'flag')
flag_var.setdefault('value', cls.function_param.get(
'true_flag', cls.function_param['true']))
old_outputs = outputs
outputs = [flag_var]
output_var = cls.prepare_output_variables(outputs)
out.append(cls.format_function_param(
function_keys[0], function_name=function_name,
input_var=input_var, output_var=output_var, **kwargs))
if cls.interface_inside_exec:
out += [cls.function_param['indent'] + x
for x in interface_lines]
free_vars = []
if 'declare' in cls.function_param:
definitions = []
if not cls.types_in_funcdef:
for o in (inputs + old_outputs):
out += [cls.function_param['indent'] + x for
x in cls.write_declaration(
o, definitions=definitions,
requires_freeing=free_vars,
is_argument=True)]
for o in outputs:
out += [cls.function_param['indent'] + x for
x in cls.write_declaration(
o, definitions=definitions,
requires_freeing=free_vars)]
out += [cls.function_param['indent'] + x
for x in definitions]
if outputs_in_inputs:
out.append(cls.function_param['indent']
+ cls.format_function_param(
'assign', **flag_var))
if opening_msg:
out.append(cls.function_param['indent']
+ cls.format_function_param(
'print', message=opening_msg))
if print_inputs:
for x in print_input_lines:
out.append(cls.function_param['indent'] + x)
for x in function_contents:
out.append(cls.function_param['indent'] + x)
if print_outputs:
for x in print_output_lines:
out.append(cls.function_param['indent'] + x)
if closing_msg:
out.append(cls.function_param['indent']
+ cls.format_function_param(
'print', message=closing_msg))
# This is not currently used by the tests, but may be
# needed in the future
assert(not free_vars)
# for x in free_vars:
# out += [cls.function_param['indent'] + line
# for line in cls.write_free(x)]
if output_var and ('return' in cls.function_param):
out.append(cls.function_param['indent']
+ cls.format_function_param(
'return', output_var=output_var))
if function_keys[1] in cls.function_param:
out.append(cls.format_function_param(
function_keys[1], function_name=function_name))
else:
out.append(cls.function_param.get('block_end', ''))
if verbose: # pragma: debug
logger.info('\n' + '\n'.join(out))
else:
logger.debug('\n' + '\n'.join(out))
return out
@classmethod
def write_function_call(cls, function_name, inputs=[], outputs=[],
include_arg_count=False,
outputs_in_inputs=False, **kwargs):
if outputs_in_inputs:
inputs = inputs + [cls.prepare_output_variables(
outputs, in_inputs=outputs_in_inputs)]
flag_var = kwargs.get('flag_var', None)
if (flag_var is None) and ('function_call_noout' not in cls.function_param):
flag_var = 'flag'
outputs = []
if flag_var:
outputs.append(flag_var)
kwargs.setdefault('input_var', cls.prepare_input_variables(inputs))
kwargs.setdefault('output_var', cls.prepare_output_variables(outputs))
nout = len(cls.split_variables(kwargs['output_var']))
if include_arg_count:
narg = len(cls.split_variables(kwargs['input_var']))
kwargs['input_var'] = cls.prepare_input_variables(
[str(narg), kwargs['input_var']])
if (nout == 0) and ('function_call_noout' in cls.function_param):
call_str = cls.format_function_param(
'function_call_noout', function_name=function_name, **kwargs)
else:
call_str = cls.format_function_param(
'function_call', default='{function_name}({input_var})',
function_name=function_name, **kwargs)
if nout == 0:
out = [call_str + cls.function_param.get('line_end', '')]
elif (nout > 1) and ('assign_mult' in cls.function_param):
out = [cls.format_function_param(
'assign_mult', name=kwargs['output_var'], value=call_str)]
else:
out = [cls.format_function_param(
'assign', name=kwargs['output_var'], value=call_str)]
return out
@classmethod
def write_executable_import(cls, model_name=None, **kwargs):
# This code is currently unused, but may be needed in the
# future to import a dependency directly
# if ('filename' not in kwargs) and ('import_nofile' in cls.function_param):
# key = 'import_nofile'
# else:
# key = 'import'
# return [cls.format_function_param(key, **kwargs)]
out = []
if 'import' in cls.function_param:
out = [cls.format_function_param('import', **kwargs)]
return out
@classmethod
def write_executable(cls, lines, prefix=None, suffix=None,
function_definitions=None, imports=None,
model_name=None):
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
out = []
# Add imports
if imports is not None:
if not isinstance(imports, list):
imports = [imports]
import_lines = []
for kws in imports:
import_lines += cls.write_executable_import(**kws)
if prefix is None:
prefix = []
prefix += import_lines
# Add standard & user defined prefixes
if ((('exec_prefix' in cls.function_param)
and (cls.function_param['exec_prefix'] not in lines))):
out.append(cls.function_param['exec_prefix'])
out.append('')
if prefix is not None:
if not isinstance(prefix, (list, tuple)):
prefix = [prefix]
out += prefix
out.append('')
if (((not cls.function_param.get('functions_defined_last', False))
and (function_definitions is not None))):
out += function_definitions
out.append('')
# Add code with begin/end book ends
if ((('exec_begin' in cls.function_param)
and (cls.function_param['exec_begin'] not in '\n'.join(lines)))):
out.append(cls.function_param['exec_begin'])
if not isinstance(lines, (list, tuple)):
lines = [lines]
for x in lines:
out.append(cls.function_param['indent'] + x)
out.append(cls.function_param.get('exec_end',
cls.function_param.get(
'block_end', '')))
else:
out += lines
if out[-1]:
out.append('')
# Add standard & user defined suffixes
if suffix is not None:
if not isinstance(suffix, (list, tuple)):
suffix = [suffix]
out += suffix
out.append('')
if ((('exec_suffix' in cls.function_param)
and (cls.function_param['exec_suffix'] not in lines))):
out.append(cls.function_param['exec_suffix'])
out.append('')
if (((cls.function_param.get('functions_defined_last', False))
and (function_definitions is not None))): # pragma: matlab
out += function_definitions
out.append('')
if cls.max_line_width:
new_out = []
for iout in out:
new_out += cls.split_line(iout)
out = new_out
return out
@classmethod
def escape_quotes(cls, x):
out = x.replace('"', '\\\"')
out = out.replace("'", "\\\'")
return out
@classmethod
def split_line(cls, line, length=None, force_split=False):
out = []
if not line.lstrip():
return [line]
nindent = line.index(line.lstrip()[0])
block_end = cls.function_param['block_end'].lower()
if '\n' in line:
out = line.split('\n')
for i in range(1, len(out)):
if out[i].lstrip().lower().startswith(block_end):
nindent -= len(cls.function_param['indent'])
out[i] = (nindent * ' ') + out[i]
new_out = []
for x in out:
new_out += cls.split_line(x, length=length,
force_split=force_split)
return new_out
if length is None:
length = cls.max_line_width
if (length is None) or (len(line) < length):
return [line]
length_allow = (length - len(cls.function_param.get(
'continuation_before', '')))
if force_split:
isplit = length_allow
else:
isplit = line[:length_allow].rindex(' ') + 1
if (isplit < nindent + 1) or (isplit >= len(line)):
out = [line]
else:
out.append(line[:isplit] + cls.function_param.get(
'continuation_before', ''))
out += cls.split_line(
((nindent * ' ') + cls.function_param.get(
'continuation_after', '') + line[isplit:]),
length=length, force_split=force_split)
return out
@classmethod
def input2output(cls, var):
return var
@classmethod
def output2input(cls, var, in_definition=True):
return var
@classmethod
def get_native_type(cls, **kwargs):
if 'native_type' in kwargs:
return kwargs['native_type']
assert('json_type' not in kwargs)
json_type = kwargs.get('datatype', kwargs)
if isinstance(json_type, dict):
type_name = json_type.get('type', 'bytes')
else:
type_name = json_type
json_type = kwargs
if type_name == 'scalar':
type_name = json_type['subtype']
if (type_name == 'flag') and (type_name not in cls.type_map):
type_name = 'boolean'
return cls.type_map[type_name]
@classmethod
def get_json_type(cls, native_type):
return cls.get_inverse_type_map()[native_type]
@classmethod
def write_finalize_iiter(cls, var):
return []
@classmethod
def write_initialize_oiter(cls, var, value=None, requires_freeing=None):
return cls.write_initialize(var, value=value,
requires_freeing=requires_freeing)
@classmethod
def write_finalize_oiter(cls, var, value=None, requires_freeing=None):
return []
@classmethod
def write_initialize(cls, var, value=None, requires_freeing=None):
out = []
if isinstance(var, str): # pragma: no cover
var = {'name': var}
if (value is None) and isinstance(var.get('datatype', False), dict):
init_type = 'init_%s' % var['datatype']['type']
free_type = 'free_%s' % var['datatype']['type']
if init_type in cls.function_param:
assert(free_type in cls.function_param)
# value = cls.format_function_param(init_type, **var['datatype'])
value = cls.function_param[init_type]
if requires_freeing is not None:
requires_freeing.append(var)
if value is not None:
out.append(cls.format_function_param(
'assign', name=var['name'], value=value))
return out
@classmethod
def write_declaration(cls, var, value=None, requires_freeing=None,
definitions=None, is_argument=False):
if isinstance(var, str): # pragma: no cover
var = {'name': var}
type_name = cls.get_native_type(**var)
out = [cls.format_function_param('declare',
type_name=type_name,
variable=cls.get_name_declare(var))]
if is_argument:
return out
if definitions is None:
definitions = out
definitions += cls.write_initialize(var, value=value,
requires_freeing=requires_freeing)
return out
@classmethod
def get_name_declare(cls, var):
if isinstance(var, str): # pragma: no cover
return var
assert(isinstance(var, dict))
out = var['name']
return out
@classmethod
def write_free(cls, var, **kwargs):
if isinstance(var, str): # pragma: no cover
var = {'name': var}
out = []
if not var.get('dont_free', False):
if ((isinstance(var.get('datatype', False), dict)
and (('free_%s' % var['datatype']['type'])
in cls.function_param))):
out = [cls.format_function_param(
'free_%s' % var['datatype']['type'],
variable=var['name'], **kwargs)]
else:
out = [cls.format_function_param(
'free', variable=var['name'], **kwargs)]
return out
@classmethod
def write_assign_to_output(cls, dst_var, src_var, copy=False,
outputs_in_inputs=False, **kwargs):
datatype = None
if isinstance(dst_var, dict):
kwargs['name'] = dst_var['name']
datatype = dst_var['datatype']
else:
kwargs['name'] = dst_var
if isinstance(src_var, dict):
kwargs['value'] = src_var['name']
datatype = src_var['datatype']
else:
kwargs['value'] = src_var
if ((outputs_in_inputs and isinstance(dst_var, dict)
and isinstance(dst_var['datatype'], dict)
and ('copy_' + dst_var['datatype']['type']
in cls.function_param))):
copy = True
if copy:
if ((isinstance(datatype, dict)
and ('copy_' + datatype['type'] in cls.function_param))):
return [cls.format_function_param(
'copy_' + datatype['type'], **kwargs)]
else:
return [cls.format_function_param('assign_copy', **kwargs)]
else:
return [cls.format_function_param('assign', **kwargs)]
@classmethod
def write_expand_single_element(cls, output_var, add_cond=False):
if 'istype' not in cls.function_param:
return []
cond = ('(%s) %s (%s %s 1)' % (
cls.format_function_param('istype',
variable=output_var,
type=cls.type_map['array']),
cls.function_param.get('and', '&&'),
cls.format_function_param('len',
variable=output_var),
cls.function_param.get('equ', '==')))
if add_cond:
for x in add_cond:
cond += f" {cls.function_param.get('and', '&&')} {x}"
out = cls.write_if_block(
cond,
cls.format_function_param(
'assign', name=output_var,
value=cls.format_function_param(
'index', variable=output_var,
index=int(cls.function_param.get('first_index', 0)))))
return out
@classmethod
def split_variables(cls, var_str):
out = []
if var_str:
pairs = [(r'\[', r'\]'),
(r'\(', r'\)'),
(r'\{', r'\}'),
(r"'", r"'"),
(r'"', r'"')]
regex_ele = r''
present = False
for p in pairs:
if not any([(str(ip)[-1] in var_str) for ip in p]):
continue
present = True
regex_ele += (r'(?:%s[.\n]*?%s)|' % p)
if present:
regex_ele += '(?:.+?)'
regex_ele = r'\s*(%s)\s*(?:,|$)' % regex_ele
out = [x.group(1) for x in re.finditer(regex_ele, var_str)]
else:
out = [x.strip() for x in var_str.split(',')]
return out
@classmethod
def prepare_variables(cls, vars_list, in_definition=False,
for_yggdrasil=False):
name_list = []
if not isinstance(vars_list, list):
vars_list = [vars_list]
for x in vars_list:
if isinstance(x, str):
name_list.append(x)
else:
assert(isinstance(x, dict))
name_list.append(x['name'])
return ', '.join(name_list)
@classmethod
def prepare_input_variables(cls, vars_list, in_definition=False,
for_yggdrasil=False):
return cls.prepare_variables(vars_list, in_definition=in_definition,
for_yggdrasil=for_yggdrasil)
@classmethod
def prepare_output_variables(cls, vars_list, in_definition=False,
in_inputs=False, for_yggdrasil=False):
if in_inputs:
vars_list = [cls.output2input(x, in_definition=in_definition)
for x in vars_list]
out = cls.prepare_variables(vars_list, in_definition=in_definition,
for_yggdrasil=for_yggdrasil)
if isinstance(vars_list, list) and (len(vars_list) > 1):
if in_definition and ('multiple_outputs_def' in cls.function_param):
out = cls.format_function_param('multiple_outputs_def', outputs=out)
elif 'multiple_outputs' in cls.function_param:
out = cls.format_function_param('multiple_outputs', outputs=out)
return out
@classmethod
def write_if_block(cls, cond, block_contents, else_block_contents=False):
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
out = []
if not isinstance(cond, list):
cond = [cond]
block_contents = [block_contents]
assert(len(cond) == len(block_contents))
for i, (icond, iblock_contents) in enumerate(zip(cond, block_contents)):
if i == 0:
out.append(cls.format_function_param('if_begin', cond=icond))
else:
out.append(cls.format_function_param('if_elif', cond=icond))
if not isinstance(iblock_contents, (list, tuple)):
iblock_contents = [iblock_contents]
for x in iblock_contents:
out.append(cls.function_param['indent'] + x)
if else_block_contents:
out.append(cls.format_function_param('if_else'))
if not isinstance(else_block_contents, (list, tuple)):
else_block_contents = [else_block_contents]
for x in else_block_contents:
out.append(cls.function_param['indent'] + x)
# Close block
out.append(cls.function_param.get('if_end',
cls.function_param.get(
'block_end', '')))
return out
@classmethod
def write_for_loop(cls, iter_var, iter_begin, iter_end, loop_contents):
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
out = []
# Opening for statement line
out.append(cls.format_function_param('for_begin', iter_var=iter_var,
iter_begin=iter_begin,
iter_end=iter_end))
# Indent loop contents
if not isinstance(loop_contents, (list, tuple)):
loop_contents = [loop_contents]
for x in loop_contents:
out.append(cls.function_param['indent'] + x)
# Close block
out.append(cls.function_param.get('for_end',
cls.function_param.get(
'block_end', '')))
return out
@classmethod
def write_while_loop(cls, cond, loop_contents):
if cls.function_param is None:
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
out = []
# Opening for statement line
out.append(cls.format_function_param('while_begin', cond=cond))
# Indent loop contents
if not isinstance(loop_contents, (list, tuple)):
loop_contents = [loop_contents]
for x in loop_contents:
out.append(cls.function_param['indent'] + x)
# Close block
out.append(cls.function_param.get('while_end',
cls.function_param.get(
'block_end', '')))
return out
@classmethod
def write_try_except(cls, try_contents, except_contents, error_var='e',
error_type=None):
if (cls.function_param is None) or ('try_begin' not in cls.function_param):
raise NotImplementedError("function_param attribute not set for"
"language '%s'" % cls.language)
if error_type is None:
error_type = cls.function_param.get('try_error_type', None)
out = []
# Try block contents
if not isinstance(try_contents, (list, tuple)):
try_contents = [try_contents]
out.append(cls.function_param['try_begin'])
for x in try_contents:
out.append(cls.function_param['indent'] + x)
# Except block contents
if not isinstance(except_contents, (list, tuple)):
except_contents = [except_contents]
out.append(cls.format_function_param('try_except', error_var=error_var,
error_type=error_type))
for x in except_contents:
out.append(cls.function_param['indent'] + x)
# Close block
out.append(cls.function_param.get('try_end',
cls.function_param.get(
'block_end', '')))
return out
@classmethod
def get_testing_options(cls):
out = dict(
kwargs={}, deps=[],
write_function_def_params=[
{'inputs': [{'name': 'x', 'value': 1.0,
'datatype': {'type': 'float',
'precision': 32,
'units': 'cm'}}],
'outputs': [{'name': 'y',
'datatype': {'type': 'float',
'precision': 32,
'units': 'cm'}}]}],
split_lines=[('abcdef', {'length': 3, 'force_split': True},
['abc', 'def']),
(' abc', {'length': 3, 'force_split': True},
[' abc'])])
return out
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.