hexsha stringlengths 40 40 | size int64 1 1.03M | ext stringclasses 10 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 239 | max_stars_repo_name stringlengths 5 130 | max_stars_repo_head_hexsha stringlengths 40 78 | 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 3 239 | max_issues_repo_name stringlengths 5 130 | max_issues_repo_head_hexsha stringlengths 40 78 | 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 3 239 | max_forks_repo_name stringlengths 5 130 | max_forks_repo_head_hexsha stringlengths 40 78 | 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 1 1.03M | avg_line_length float64 1 958k | max_line_length int64 1 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
acefc97a2000f5eed204b7cbe14e194f9e7980e7 | 8,627 | py | Python | nova/api/openstack/compute/migrations.py | pdo2013/nova | 3c86ff5b25f02aa45d71e35b3d7f722ab4c36fde | [
"Apache-2.0"
] | null | null | null | nova/api/openstack/compute/migrations.py | pdo2013/nova | 3c86ff5b25f02aa45d71e35b3d7f722ab4c36fde | [
"Apache-2.0"
] | 2 | 2021-03-31T20:04:16.000Z | 2021-12-13T20:45:03.000Z | nova/api/openstack/compute/migrations.py | pdo2013/nova | 3c86ff5b25f02aa45d71e35b3d7f722ab4c36fde | [
"Apache-2.0"
] | 1 | 2020-07-24T02:31:45.000Z | 2020-07-24T02:31:45.000Z | # 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 oslo_utils import timeutils
from webob import exc
from nova.api.openstack import api_version_request
from nova.api.openstack import common
from nova.api.openstack.compute.schemas import migrations as schema_migrations
from nova.api.openstack.compute.views import migrations as migrations_view
from nova.api.openstack import wsgi
from nova.api import validation
from nova.compute import api as compute
from nova import exception
from nova.i18n import _
from nova.objects import base as obj_base
from nova.policies import migrations as migrations_policies
class MigrationsController(wsgi.Controller):
"""Controller for accessing migrations in OpenStack API."""
_view_builder_class = migrations_view.ViewBuilder
_collection_name = "servers/%s/migrations"
def __init__(self):
super(MigrationsController, self).__init__()
self.compute_api = compute.API()
def _output(self, req, migrations_obj, add_link=False,
add_uuid=False, add_user_project=False):
"""Returns the desired output of the API from an object.
From a MigrationsList's object this method returns a list of
primitive objects with the only necessary fields.
"""
detail_keys = ['memory_total', 'memory_processed', 'memory_remaining',
'disk_total', 'disk_processed', 'disk_remaining']
# TODO(Shaohe Feng) we should share the in-progress list.
live_migration_in_progress = ['queued', 'preparing',
'running', 'post-migrating']
# Note(Shaohe Feng): We need to leverage the oslo.versionedobjects.
# Then we can pass the target version to it's obj_to_primitive.
objects = obj_base.obj_to_primitive(migrations_obj)
objects = [x for x in objects if not x['hidden']]
for obj in objects:
del obj['deleted']
del obj['deleted_at']
del obj['hidden']
del obj['cross_cell_move']
if not add_uuid:
del obj['uuid']
if 'memory_total' in obj:
for key in detail_keys:
del obj[key]
if not add_user_project:
if 'user_id' in obj:
del obj['user_id']
if 'project_id' in obj:
del obj['project_id']
# NOTE(Shaohe Feng) above version 2.23, add migration_type for all
# kinds of migration, but we only add links just for in-progress
# live-migration.
if add_link and obj['migration_type'] == "live-migration" and (
obj["status"] in live_migration_in_progress):
obj["links"] = self._view_builder._get_links(
req, obj["id"],
self._collection_name % obj['instance_uuid'])
elif add_link is False:
del obj['migration_type']
return objects
def _index(self, req, add_link=False, next_link=False, add_uuid=False,
sort_dirs=None, sort_keys=None, limit=None, marker=None,
allow_changes_since=False, allow_changes_before=False):
context = req.environ['nova.context']
context.can(migrations_policies.POLICY_ROOT % 'index', target={})
search_opts = {}
search_opts.update(req.GET)
if 'changes-since' in search_opts:
if allow_changes_since:
search_opts['changes-since'] = timeutils.parse_isotime(
search_opts['changes-since'])
else:
# Before microversion 2.59, the changes-since filter was not
# supported in the DB API. However, the schema allowed
# additionalProperties=True, so a user could pass it before
# 2.59 and filter by the updated_at field if we don't remove
# it from search_opts.
del search_opts['changes-since']
if 'changes-before' in search_opts:
if allow_changes_before:
search_opts['changes-before'] = timeutils.parse_isotime(
search_opts['changes-before'])
changes_since = search_opts.get('changes-since')
if (changes_since and search_opts['changes-before'] <
search_opts['changes-since']):
msg = _('The value of changes-since must be less than '
'or equal to changes-before.')
raise exc.HTTPBadRequest(explanation=msg)
else:
# Before microversion 2.59 the schema allowed
# additionalProperties=True, so a user could pass
# changes-before before 2.59 and filter by the updated_at
# field if we don't remove it from search_opts.
del search_opts['changes-before']
if sort_keys:
try:
migrations = self.compute_api.get_migrations_sorted(
context, search_opts,
sort_dirs=sort_dirs, sort_keys=sort_keys,
limit=limit, marker=marker)
except exception.MarkerNotFound as e:
raise exc.HTTPBadRequest(explanation=e.format_message())
else:
migrations = self.compute_api.get_migrations(
context, search_opts)
add_user_project = api_version_request.is_supported(req, '2.80')
migrations = self._output(req, migrations, add_link,
add_uuid, add_user_project)
migrations_dict = {'migrations': migrations}
if next_link:
migrations_links = self._view_builder.get_links(req, migrations)
if migrations_links:
migrations_dict['migrations_links'] = migrations_links
return migrations_dict
@wsgi.Controller.api_version("2.1", "2.22") # noqa
@wsgi.expected_errors(())
@validation.query_schema(schema_migrations.list_query_schema_v20,
"2.0", "2.22")
def index(self, req):
"""Return all migrations using the query parameters as filters."""
return self._index(req)
@wsgi.Controller.api_version("2.23", "2.58") # noqa
@wsgi.expected_errors(())
@validation.query_schema(schema_migrations.list_query_schema_v20,
"2.23", "2.58")
def index(self, req): # noqa
"""Return all migrations using the query parameters as filters."""
return self._index(req, add_link=True)
@wsgi.Controller.api_version("2.59", "2.65") # noqa
@wsgi.expected_errors(400)
@validation.query_schema(schema_migrations.list_query_params_v259,
"2.59", "2.65")
def index(self, req): # noqa
"""Return all migrations using the query parameters as filters."""
limit, marker = common.get_limit_and_marker(req)
return self._index(req, add_link=True, next_link=True, add_uuid=True,
sort_keys=['created_at', 'id'],
sort_dirs=['desc', 'desc'],
limit=limit, marker=marker,
allow_changes_since=True)
@wsgi.Controller.api_version("2.66") # noqa
@wsgi.expected_errors(400)
@validation.query_schema(schema_migrations.list_query_params_v266,
"2.66", "2.79")
@validation.query_schema(schema_migrations.list_query_params_v280,
"2.80")
def index(self, req): # noqa
"""Return all migrations using the query parameters as filters."""
limit, marker = common.get_limit_and_marker(req)
return self._index(req, add_link=True, next_link=True, add_uuid=True,
sort_keys=['created_at', 'id'],
sort_dirs=['desc', 'desc'],
limit=limit, marker=marker,
allow_changes_since=True,
allow_changes_before=True)
| 45.888298 | 78 | 0.607859 |
acefcc003d5c6536c31135d3e548eec8cf29e088 | 551 | py | Python | naz/__init__.py | profx5/naz | dd27fff6fcf84d755eabe092b67275d4a9ef3ed5 | [
"MIT"
] | null | null | null | naz/__init__.py | profx5/naz | dd27fff6fcf84d755eabe092b67275d4a9ef3ed5 | [
"MIT"
] | null | null | null | naz/__init__.py | profx5/naz | dd27fff6fcf84d755eabe092b67275d4a9ef3ed5 | [
"MIT"
] | null | null | null | from .client import Client # noqa: F401
from . import log # noqa: F401
from . import broker # noqa: F401
from . import codec # noqa: F401
from . import protocol # noqa: F401
from . import throttle # noqa: F401
from . import sequence # noqa: F401
from . import correlater # noqa: F401
from . import ratelimiter # noqa: F401
from .state import ( # noqa: F401
SmppSessionState,
SmppCommand,
CommandStatus,
SmppCommandStatus,
DataCoding,
SmppDataCoding,
SmppOptionalTag,
)
from . import __version__ # noqa: F401
| 22.958333 | 40 | 0.69147 |
acefd08c533a9842b4a1f9631ba93a884a27df75 | 7,084 | py | Python | myBlog/serializers.py | terrence85561/CMPUT404-Winter-2019-GroupProject | e9b6f995852267fb85e6218212944c4e42d96066 | [
"Apache-2.0"
] | 4 | 2019-02-09T21:42:14.000Z | 2019-07-05T16:04:37.000Z | myBlog/serializers.py | terrence85561/CMPUT404-Winter-2019-GroupProject | e9b6f995852267fb85e6218212944c4e42d96066 | [
"Apache-2.0"
] | 67 | 2019-02-21T01:41:23.000Z | 2019-04-08T15:38:11.000Z | myBlog/serializers.py | terrence85561/CMPUT404-Winter-2019-GroupProject | e9b6f995852267fb85e6218212944c4e42d96066 | [
"Apache-2.0"
] | 2 | 2019-02-09T21:51:11.000Z | 2019-02-09T21:57:09.000Z | from rest_framework import serializers
from .models import Post, Comment, Author, Friend
import uuid
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
# Reference: https://www.django-rest-framework.org/api-guide/serializers/#modelserializer
# https://stackoverflow.com/questions/35522768/django-serializer-imagefield-to-get-full-url answered Feb 20 '16 at 11:57 blacklwhite
# https://www.django-rest-framework.org/api-guide/fields/
# https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
# https://stackoverflow.com/questions/45446953/django-rest-framework-adding-a-custom-field-to-a-paginated-viewset answered Aug 1 '17 at 20:33 Bear Brown
# https://www.django-rest-framework.org/api-guide/pagination/
# https://www.django-rest-framework.org/api-guide/pagination/#pagenumberpagination
# https://www.programcreek.com/python/example/92963/rest_framework.pagination.PageNumberPagination
class CustomPagination(PageNumberPagination):
page_size = 50
page_size_query_param = 'size'
max_page_size = 10000
def get_paginated_response(self, data):
if ('posts' in self.request.path and 'comments' not in self.request.path):
query = 'posts'
else:
query = 'comments'
try:
page_size = int(self.request.query_params['size'])
except:
page_size = self.page_size
if self.get_previous_link() is None and self.get_next_link() is None:
responsBody = {
'query': query,
'count': self.page.paginator.count,
"size": page_size,
query:data,
}
elif self.get_next_link() is None:
responsBody = {
'query': query,
'count': self.page.paginator.count,
"size": page_size,
'previous': self.get_previous_link(),
query:data,
}
elif self.get_previous_link() is None:
responsBody = {
'query': query,
'count': self.page.paginator.count,
"size": page_size,
'next': self.get_next_link(),
query:data,
}
else:
responsBody = {
'query': query,
'count': self.page.paginator.count,
"size": page_size,
'next': self.get_next_link(),
'previous': self.get_previous_link(),
query:data,
}
return Response(responsBody)
class AuthorSerializer(serializers.ModelSerializer):
url = serializers.SerializerMethodField()
class Meta:
model = Author
fields = ('id','displayName', 'url','host', 'github')
def get_url(self, obj):
url = obj.host+"service/author/"+str(obj.id)
return url
def update(self, instance, validated_data):
instance.displayName = validated_data.get('displayName', instance.displayName)
instance.github = validated_data.get('github', instance.github)
instance.save()
return instance
class FriendSerializer(serializers.ModelSerializer):
author = AuthorSerializer(read_only=True)
friend = AuthorSerializer(read_only=True)
class Meta:
model = Friend
fields = ('id','author','friend', 'status', 'last_modified_time')
class PostSerializer(serializers.ModelSerializer):
comments = serializers.SerializerMethodField()
#https://www.django-rest-framework.org/api-guide/serializers/#specifying-fields-explicitly
author = AuthorSerializer(read_only=True)
count = serializers.SerializerMethodField()
size = serializers.SerializerMethodField()
next = serializers.SerializerMethodField()
id = serializers.SerializerMethodField()
pagination_class = CustomPagination
class Meta:
model = Post
fields = ('title','source','origin','description','contentType','content','author','categories','count','size','next','comments','published','id','visibility','visibleTo','unlisted')
def get_comments(self, obj):
comments = Comment.objects.filter(postid=obj.postid).order_by('published')
serializer = CommentSerializer(comments, many=True)
return serializer.data
def get_count(self, obj):
comments_count = Comment.objects.filter(postid=obj.postid).order_by('published').count()
return comments_count
def get_size(self, obj):
return 50
def get_id(self, obj):
return obj.postid
def get_next(self, obj):
try:
return obj.origin+"/comments"
except:
return None
# https://www.django-rest-framework.org/api-guide/serializers/#saving-instances
def create(self, validated_data):
author=self.context['author']
origin=self.context['origin']
post = Post.objects.create(author=author, origin=origin, source=origin, **validated_data)
newPost = Post.objects.get(postid=post.postid)
newPost.origin=post.origin+"service/posts/"+str(post.postid)
newPost.source=post.source+"service/posts/"+str(post.postid)
newPost.save()
return newPost
# https://www.django-rest-framework.org/api-guide/serializers/#saving-instances
def update(self, instance, validated_data):
instance.title = validated_data.get('title', instance.title)
instance.content = validated_data.get('content', instance.content)
instance.contentType = validated_data.get('contentType', instance.contentType)
instance.visibility = validated_data.get('visibility', instance.visibility)
instance.categories = validated_data.get('categories', instance.categories)
instance.description = validated_data.get('description', instance.description)
instance.visibleTo = validated_data.get('visibleTo', instance.visibleTo)
instance.unlisted = validated_data.get('unlisted', instance.unlisted)
instance.origin = validated_data.get('origin', instance.origin)
instance.source = validated_data.get('source', instance.source)
instance.save()
return instance
class CommentSerializer(serializers.ModelSerializer):
author = AuthorSerializer(read_only=True)
class Meta:
model = Comment
fields = '__all__'
def create(self, validated_data):
author = self.context['author']
postid = self.context['postid']
comment = Comment.objects.create(author=author, postid=postid, **validated_data)
comment.save()
return comment
class AuthorProfileSerializer(serializers.ModelSerializer):
url = serializers.SerializerMethodField()
friends = serializers.SerializerMethodField()
class Meta:
model = Author
fields = ('id','host','displayName', 'url', 'github', 'friends')
def get_url(self, obj):
url = obj.host+"service/author/"+str(obj.id)
return url
def get_friends(self, obj):
friends = Author.objects.filter(id=obj.id)
serializer = AuthorSerializer(friends, many=True)
return serializer.data
| 38.923077 | 187 | 0.668831 |
acefd2441a63f9721e04ad59d2d370c4c837be76 | 35,157 | py | Python | cli/tests/commands/job/test_verify.py | AndersonReyes/klio | 758c80daa2c537a42a72e5ba061e8686b68de111 | [
"Apache-2.0"
] | 705 | 2020-10-02T17:25:31.000Z | 2022-03-24T15:26:53.000Z | cli/tests/commands/job/test_verify.py | AndersonReyes/klio | 758c80daa2c537a42a72e5ba061e8686b68de111 | [
"Apache-2.0"
] | 63 | 2020-10-02T17:53:47.000Z | 2022-03-23T21:36:40.000Z | cli/tests/commands/job/test_verify.py | isabella232/klio | 4b8b96b03948235c0b28af96fc85de17cb679e8c | [
"Apache-2.0"
] | 49 | 2020-10-13T18:44:34.000Z | 2022-03-18T08:38:15.000Z | # Copyright 2019-2020 Spotify AB
#
# 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 logging
import httplib2
import pytest
from google.api_core import exceptions as api_ex
from google.api_core import page_iterator
from google.cloud import exceptions
from googleapiclient import errors as google_errors
from klio_core import config as kconfig
from klio_cli.commands.job import verify
from klio_cli.utils import stackdriver_utils as sd_utils
@pytest.fixture
def mock_publisher(mocker):
return mocker.patch.object(verify.pubsub_v1, "PublisherClient")
@pytest.fixture
def mock_sub(mocker):
return mocker.patch.object(verify.pubsub_v1, "SubscriberClient")
@pytest.fixture
def mock_storage(mocker):
return mocker.patch.object(verify.storage, "Client")
@pytest.fixture
def mock_bucket(mocker):
return mocker.patch.object(verify.storage.Client, "bucket")
@pytest.fixture
def mock_blob(mocker):
return mocker.patch.object(verify.storage, "blob")
@pytest.fixture
def mock_discovery_client(mocker, monkeypatch):
mock = mocker.MagicMock()
monkeypatch.setattr(verify.discovery, "build", lambda x, y: mock)
return mock
@pytest.fixture
def mock_iterator(mocker):
return mocker.patch.object(page_iterator, "HTTPIterator")
@pytest.fixture
def config():
return {
"job_name": "klio-job-name",
"job_config": {
"inputs": [
{
"topic": "test-in-topic",
"subscription": "foo",
"data_location": "gs://test-in-data",
}
],
"outputs": [
{
"topic": "test-out-topic",
"data_location": "gs://test-out-data",
}
],
},
"pipeline_options": {
"streaming": True,
"worker_harness_container_image": "a-worker-image",
"experiments": ["beam_fn_api"],
"project": "test-gcp-project",
"zone": "europe-west1-c",
"region": "europe-west1",
"staging_location": "gs://test-gcp-project-dataflow-tmp/staging",
"temp_location": "gs://test-gcp-project-dataflow-tmp/temp",
"max_num_workers": 2,
"autoscaling_algorithm": "NONE",
"disk_size_gb": 32,
"worker_machine_type": "n1-standard-2",
"runner": "DataflowRunner",
},
}
@pytest.fixture
def klio_config(config):
return kconfig.KlioConfig(config)
@pytest.fixture
def mock_get_sd_group_url(mocker):
return mocker.patch.object(sd_utils, "get_stackdriver_group_url")
@pytest.fixture
def mock_create_sd_group(mocker):
return mocker.patch.object(sd_utils, "create_stackdriver_group")
@pytest.mark.parametrize(
"expected,bindings,create_resources",
[
(
True,
[
{
"role": "roles/monitoring.metricWriter",
"members": ["serviceAccount:the-default-svc-account"],
},
{
"role": "roles/pubsub.publisher",
"members": ["serviceAccount:the-default-svc-account"],
},
{
"role": "roles/pubsub.subscriber",
"members": ["serviceAccount:the-default-svc-account"],
},
{
"role": "roles/storage.objectCreator",
"members": ["serviceAccount:the-default-svc-account"],
},
{
"role": "roles/storage.objectViewer",
"members": ["serviceAccount:the-default-svc-account"],
},
],
False,
),
(
False,
[
{
"role": "roles/monitoring.metricWriter",
"members": ["serviceAccount:some-other-account"],
}
],
False,
),
(
False,
[
{
"role": "roles/monitoring.metricWriter",
"members": ["serviceAccount:some-other-account"],
}
],
True,
),
(
False,
[{"role": "roles/monitoring.metricWriter", "members": []}],
False,
),
(False, [], False),
],
)
def test_verify_iam_roles(
caplog,
expected,
bindings,
create_resources,
mock_discovery_client,
klio_config,
):
compute_client = mock_discovery_client.build("compute")
compute_client.projects().get().execute.return_value = {
"defaultServiceAccount": "the-default-svc-account"
}
iam_client = mock_discovery_client.build("cloudresourcemanager")
job = verify.VerifyJob(klio_config, create_resources)
job._compute_client = compute_client
job._iam_client = iam_client
gcp_project = job.klio_config.pipeline_options.project
iam_client.projects().getIamPolicy(
resource=gcp_project, body={}
).execute.return_value = {"bindings": bindings}
result = job._verify_iam_roles()
if create_resources:
assert (
"Klio is unable to add the required role(s)"
in caplog.records[-1].msg
)
compute_client.projects().get(
project=gcp_project
).execute.assert_called_once_with()
iam_client.projects().getIamPolicy(
resource=gcp_project, body={}
).execute.assert_called_once_with()
assert result is expected
def test_verify_iam_roles_editor(caplog, klio_config, mock_discovery_client):
bindings = [
{
"role": "roles/monitoring.metricWriter",
"members": ["serviceAccount:the-default-svc-account"],
},
{
"role": "roles/pubsub.publisher",
"members": ["serviceAccount:the-default-svc-account"],
},
{
"role": "roles/pubsub.subscriber",
"members": ["serviceAccount:the-default-svc-account"],
},
{
"role": "roles/storage.objectCreator",
"members": ["serviceAccount:the-default-svc-account"],
},
{
"role": "roles/storage.objectViewer",
"members": ["serviceAccount:the-default-svc-account"],
},
{
"role": "roles/editor",
"members": ["serviceAccount:the-default-svc-account"],
},
]
gcp_project = klio_config.pipeline_options.project
compute_client = mock_discovery_client.build("compute")
compute_client.projects().get().execute.return_value = {
"defaultServiceAccount": "the-default-svc-account"
}
iam_client = mock_discovery_client.build("cloudresourcemanager")
iam_client.projects().getIamPolicy(
resource=gcp_project, body={}
).execute.return_value = {"bindings": bindings}
job = verify.VerifyJob(klio_config, False)
job._compute_client = compute_client
job._iam_client = iam_client
result = job._verify_iam_roles()
compute_client.projects().get(
project=gcp_project
).execute.assert_called_once_with()
iam_client.projects().getIamPolicy(
resource=gcp_project, body={}
).execute.assert_called_once_with()
assert result is True
with caplog.at_level(logging.WARNING):
assert len(caplog.records) == 3
msg = caplog.records[1].msg
assert "unsafe project editor or owner permissions" in msg
def test_verify_iam_roles_with_svc_account(klio_config, mock_discovery_client):
"If the user configures a SA, verify it instead of the default compute SA"
job = verify.VerifyJob(klio_config, False)
job.klio_config.pipeline_options.service_account_email = (
"my.sa@something.com"
)
bindings = [
{
"role": "roles/monitoring.metricWriter",
"members": ["serviceAccount:my.sa@something.com"],
},
{
"role": "roles/pubsub.publisher",
"members": ["serviceAccount:my.sa@something.com"],
},
{
"role": "roles/pubsub.subscriber",
"members": ["serviceAccount:my.sa@something.com"],
},
{
"role": "roles/storage.objectCreator",
"members": ["serviceAccount:my.sa@something.com"],
},
{
"role": "roles/storage.objectViewer",
"members": ["serviceAccount:my.sa@something.com"],
},
{
"role": "roles/editor",
"members": ["serviceAccount:the-default-svc-account"],
},
]
gcp_project = job.klio_config.pipeline_options.project
compute_client = mock_discovery_client.build("compute")
compute_client.projects().get().execute.return_value = {
"defaultServiceAccount": "the-default-svc-account"
}
iam_client = mock_discovery_client.build("cloudresourcemanager")
iam_client.projects().getIamPolicy(
resource=gcp_project, body={}
).execute.return_value = {"bindings": bindings}
job._compute_client = compute_client
job._iam_client = iam_client
result = job._verify_iam_roles()
# Assert that we don't fetch the default SA since we don't need it
compute_client.projects().get(
project=gcp_project
).execute.assert_not_called()
iam_client.projects().getIamPolicy(
resource=gcp_project, body={}
).execute.assert_called_once_with()
assert result is True
def test_verify_iam_roles_http_error(klio_config, mock_discovery_client):
compute_client = mock_discovery_client.build("compute")
err = google_errors.HttpError
resp = httplib2.Response({})
resp.reason = "some resp"
compute_client.projects().get().execute.side_effect = err(
resp, "some content".encode()
)
iam_client = mock_discovery_client.build("cloudresourcemanager")
job = verify.VerifyJob(klio_config, False)
job._compute_client = compute_client
job._iam_client = iam_client
result = job._verify_iam_roles()
assert result is False
compute_client = mock_discovery_client.build("compute")
compute_client.projects().get().execute.side_effect = None
compute_client.projects().get().execute.return_value = {
"defaultServiceAccount": "the-default-svc-account"
}
iam_client = mock_discovery_client.build("cloudresourcemanager")
iam_client.projects().getIamPolicy(
resource=job.klio_config.pipeline_options.project, body={}
).execute.side_effect = google_errors.HttpError(
resp, "some content".encode()
)
job._compute_client = compute_client
job._iam_client = iam_client
result = job._verify_iam_roles()
assert result is False
@pytest.mark.parametrize(
"create_resources,dashboard_url",
((True, None), (False, None), (False, "dashboard/url")),
)
def test_verify_stackdriver_dashboard(
klio_config,
mock_get_sd_group_url,
mock_create_sd_group,
create_resources,
dashboard_url,
):
mock_get_sd_group_url.return_value = dashboard_url
job = verify.VerifyJob(klio_config, create_resources)
actual = job._verify_stackdriver_dashboard()
mock_get_sd_group_url.assert_called_once_with(
"test-gcp-project", "klio-job-name", "europe-west1"
)
if create_resources:
mock_create_sd_group.assert_called_once_with(
"test-gcp-project", "klio-job-name", "europe-west1"
)
assert actual is True
elif dashboard_url:
assert actual is True
else:
assert actual is False
def test_verify_stackdriver_dashboard_raises(
klio_config, mock_get_sd_group_url, caplog
):
mock_get_sd_group_url.side_effect = Exception("error")
with pytest.raises(Exception, match="error"):
job = verify.VerifyJob(klio_config, False)
job._verify_stackdriver_dashboard()
assert 2 == len(caplog.records)
def test_verify_stackdriver_dashboard_errors(
klio_config, mock_get_sd_group_url, mock_create_sd_group, caplog
):
mock_get_sd_group_url.return_value = None
mock_create_sd_group.return_value = None
job = verify.VerifyJob(klio_config, True)
actual = job._verify_stackdriver_dashboard()
assert actual is False
assert 3 == len(caplog.records)
@pytest.mark.parametrize("create_resources", (True, False))
def test_verify_gcs_bucket(klio_config, mock_storage, create_resources):
test_path = "gs://bucket/blob"
job = verify.VerifyJob(klio_config, create_resources)
job._storage_client = mock_storage
actual = job._verify_gcs_bucket(test_path)
if create_resources:
mock_storage.create_bucket.assert_called_once_with("bucket")
else:
mock_storage.get_bucket.assert_called_once_with("bucket")
assert actual is True
def test_verify_gcs_bucket_invalid_name(klio_config, mock_storage, caplog):
job = verify.VerifyJob(klio_config, True)
job._storage_client = mock_storage
assert not job._verify_gcs_bucket("a/b/c")
assert 2 == len(caplog.records)
def test_verify_gcs_bucket_exists(klio_config, mock_storage):
test_path = "gs://bucket/blob"
mock_storage.create_bucket.side_effect = api_ex.Conflict("test")
job = verify.VerifyJob(klio_config, True)
job._storage_client = mock_storage
actual = job._verify_gcs_bucket(test_path)
assert actual is True
@pytest.mark.parametrize("not_found", (True, False))
def test_verify_gcs_bucket_exceptions(klio_config, mock_storage, not_found):
test_path = "gs://bucket/blob"
if not_found:
mock_storage.get_bucket.side_effect = exceptions.NotFound("test")
else:
mock_storage.get_bucket.side_effect = Exception
job = verify.VerifyJob(klio_config, False)
job._storage_client = mock_storage
actual = job._verify_gcs_bucket(test_path)
assert actual is False
@pytest.mark.parametrize("create_resources", (True, False))
def test_verify_pub_topic(klio_config, mock_publisher, create_resources):
test_topic = "test"
job = verify.VerifyJob(klio_config, create_resources)
job._publisher_client = mock_publisher
actual = job._verify_pub_topic(test_topic, input)
if create_resources:
mock_publisher.create_topic.assert_called_once_with(
request={"name": test_topic}
)
else:
mock_publisher.get_topic.assert_called_once_with(
request={"topic": test_topic}
)
assert actual is True
def test_verify_pub_topic_exists(
klio_config, mock_publisher,
):
test_topic = "test"
mock_publisher.create_topic.side_effect = api_ex.AlreadyExists("test")
job = verify.VerifyJob(klio_config, True)
job._publisher_client = mock_publisher
actual = job._verify_pub_topic(test_topic, input)
assert actual is True
@pytest.mark.parametrize("not_found", (True, False))
def test_verify_pub_topic_exceptions(klio_config, mock_publisher, not_found):
test_topic = "test"
if not_found:
mock_publisher.get_topic.side_effect = exceptions.NotFound("test")
else:
mock_publisher.get_topic.side_effect = Exception
job = verify.VerifyJob(klio_config, False)
job._publisher_client = mock_publisher
actual = job._verify_pub_topic(test_topic, input)
assert actual is False
@pytest.mark.parametrize("create_resources", (True, False))
def test_verify_subscription_and_topic(
klio_config, mock_publisher, mock_sub, create_resources
):
test_sub = "test"
upstream_topic = "Some"
job = verify.VerifyJob(klio_config, create_resources)
job._publisher_client = mock_publisher
job._subscriber_client = mock_sub
if create_resources:
actual = job._verify_subscription_and_topic(test_sub, upstream_topic,)
mock_sub.create_subscription.assert_called_once_with(
request={"name": test_sub, "topic": upstream_topic}
)
else:
actual = job._verify_subscription_and_topic(test_sub, upstream_topic,)
mock_sub.get_subscription.assert_called_once_with(
request={"subscription": test_sub}
)
expected = True, True
assert expected == actual
def test_verify_subscription_and_topic_exists(
klio_config, mock_publisher, mock_sub
):
test_sub = "test"
upstream_topic = "Some"
job = verify.VerifyJob(klio_config, True)
job._publisher_client = mock_publisher
job._subscriber_client = mock_sub
mock_sub.create_subscription.side_effect = api_ex.AlreadyExists("test")
actual = job._verify_subscription_and_topic(test_sub, upstream_topic)
expected = True, True
assert expected == actual
@pytest.mark.parametrize(
"not_found, no_topic", ((True, False), (False, False), (False, True))
)
def test_verify_subscription_and_topic_exceptions(
klio_config, mock_publisher, mock_sub, not_found, no_topic
):
test_sub = "test"
if no_topic:
upstream_topic = None
expected = False, True
else:
upstream_topic = "Some"
expected = True, False
if not_found:
mock_sub.get_subscription.side_effect = exceptions.NotFound("test")
else:
mock_sub.get_subscription.side_effect = Exception
job = verify.VerifyJob(klio_config, False)
job._publisher_client = mock_publisher
job._subscriber_client = mock_sub
actual = job._verify_subscription_and_topic(test_sub, upstream_topic)
assert expected == actual
mock_gcs_event_config = {
"type": "gcs",
"location": "gs://some/events.txt",
"io_type": kconfig._io.KlioIOType.EVENT,
"io_direction": kconfig._io.KlioIODirection.INPUT,
}
mock_gcs_event = kconfig._io.KlioReadFileConfig.from_dict(
mock_gcs_event_config
)
mock_bq_event_config = {
"type": "bq",
"project": "sigint",
"dataset": "test-data",
"table": "test-table",
"io_type": kconfig._io.KlioIOType.EVENT,
"io_direction": kconfig._io.KlioIODirection.INPUT,
}
mock_bq_event = kconfig._io.KlioBigQueryEventInput.from_dict(
mock_bq_event_config
)
mock_avro_event_config = {
"type": "avro",
"io_type": kconfig._io.KlioIOType.EVENT,
"io_direction": kconfig._io.KlioIODirection.INPUT,
}
mock_avro_event = kconfig._io.KlioReadAvroEventConfig.from_dict(
mock_avro_event_config
)
@pytest.mark.parametrize(
"mock_event_input", ((mock_gcs_event), (mock_bq_event), (mock_avro_event),)
)
def test_unverified_event_inputs(
mocker,
caplog,
mock_storage,
mock_publisher,
mock_sub,
klio_config,
mock_event_input,
):
mock_verify_gcs_bucket = mocker.patch.object(
verify.VerifyJob, "_verify_gcs_bucket"
)
mock_verify_sub = mocker.patch.object(
verify.VerifyJob, "_verify_subscription_and_topic"
)
job = verify.VerifyJob(klio_config, False)
job._publisher_client = mock_publisher
job._storage_client = mock_storage
job._subscriber_client = mock_sub
job.klio_config.pipeline_options.project = "sigint"
job.klio_config.job_config.events.inputs = [mock_event_input]
data_config = {
"type": "gcs",
"location": "test",
"io_type": kconfig._io.KlioIOType.DATA,
"io_direction": kconfig._io.KlioIODirection.INPUT,
}
job.klio_config.job_config.data.inputs = [
kconfig._io.KlioGCSInputDataConfig.from_dict(data_config)
]
mock_verify_gcs_bucket.return_value = True
actual = job._verify_inputs()
mock_verify_sub.assert_not_called()
mock_verify_gcs_bucket.assert_called_with("test")
assert actual
assert 3 == len(caplog.records)
@pytest.mark.parametrize(
"unverified_bucket, unverified_topic, unverified_sub",
(
(False, False, False),
(True, False, False),
(True, True, True),
(False, True, True),
(False, False, True),
(False, True, False),
(False, False, False),
),
)
def test_verify_inputs(
mocker,
unverified_bucket,
unverified_topic,
unverified_sub,
klio_config,
mock_storage,
mock_publisher,
mock_sub,
):
mock_verify_gcs_bucket = mocker.patch.object(
verify.VerifyJob, "_verify_gcs_bucket"
)
mock_verify_sub = mocker.patch.object(
verify.VerifyJob, "_verify_subscription_and_topic"
)
job = verify.VerifyJob(klio_config, False)
job._publisher_client = mock_publisher
job._storage_client = mock_storage
job._subscriber_client = mock_sub
job.klio_config.pipeline_options.project = "sigint"
event_config = {
"type": "pubsub",
"topic": "test",
"subscription": "test",
"io_type": kconfig._io.KlioIOType.EVENT,
"io_direction": kconfig._io.KlioIODirection.INPUT,
}
job.klio_config.job_config.events.inputs = [
kconfig._io.KlioPubSubEventInput.from_dict(event_config)
]
data_config = {
"type": "gcs",
"location": "test",
"io_type": kconfig._io.KlioIOType.DATA,
"io_direction": kconfig._io.KlioIODirection.INPUT,
}
job.klio_config.job_config.data.inputs = [
kconfig._io.KlioGCSInputDataConfig.from_dict(data_config)
]
if unverified_topic and unverified_sub and unverified_bucket:
mock_verify_gcs_bucket.return_value = False
mock_verify_sub.return_value = False, False
actual = job._verify_inputs()
expected = False
assert expected == actual
elif unverified_topic and unverified_sub:
mock_verify_sub.return_value = False, False
actual = job._verify_inputs()
expected = False
assert expected == actual
elif unverified_topic:
mock_verify_sub.return_value = False, True
actual = job._verify_inputs()
expected = False
assert expected == actual
elif unverified_sub:
mock_verify_sub.return_value = True, False
actual = job._verify_inputs()
expected = False
assert expected == actual
elif unverified_bucket:
mock_verify_gcs_bucket.return_value = False
mock_verify_sub.return_value = True, True
actual = job._verify_inputs()
expected = False
assert expected == actual
else:
mock_verify_gcs_bucket.return_value = True
mock_verify_sub.return_value = True, True
actual = job._verify_inputs()
expected = True
assert expected == actual
mock_verify_gcs_bucket.assert_called_with("test")
mock_verify_sub.assert_called_with("test", "test")
@pytest.mark.parametrize(
"data_dict, event_dict, expected_log_count",
(
({"location": "test"}, {"topic": "test", "subscription": "test"}, 3),
({"location": None}, {"topic": "test", "subscription": "test"}, 4),
({"location": "test"}, {"topic": "test", "subscription": None}, 4),
({"location": None}, {"topic": "test", "subscription": None}, 5),
(None, None, 5),
),
)
def test_verify_inputs_logs(
data_dict,
event_dict,
expected_log_count,
klio_config,
mock_storage,
mock_publisher,
mock_sub,
mocker,
caplog,
):
mocker.patch.object(verify.VerifyJob, "_verify_gcs_bucket")
mock_verify_sub = mocker.patch.object(
verify.VerifyJob, "_verify_subscription_and_topic"
)
mock_verify_sub.return_value = (False, False)
job = verify.VerifyJob(klio_config, False)
job._publisher_client = mock_publisher
job._storage_client = mock_storage
job._subscriber_client = mock_sub
job.klio_config.pipeline_options.project = "sigint"
if event_dict:
event_dict["type"] = "pubsub"
event_dict["io_type"] = kconfig._io.KlioIOType.EVENT
event_dict["io_direction"] = kconfig._io.KlioIODirection.OUTPUT
job.klio_config.job_config.events.inputs = [
kconfig._io.KlioPubSubEventInput.from_dict(event_dict)
]
else:
job.klio_config.job_config.events.inputs = []
if data_dict:
data_dict["type"] = "gcs"
data_dict["io_type"] = kconfig._io.KlioIOType.DATA
data_dict["io_direction"] = kconfig._io.KlioIODirection.OUTPUT
job.klio_config.job_config.data.inputs = [
kconfig._io.KlioGCSOutputDataConfig.from_dict(data_dict)
]
else:
job.klio_config.job_config.data.inputs = []
job._verify_inputs()
assert expected_log_count == len(caplog.records)
mock_gcs_output_event_config = {
"type": "gcs",
"location": "gs://some/events.txt",
"io_type": kconfig._io.KlioIOType.EVENT,
"io_direction": kconfig._io.KlioIODirection.OUTPUT,
}
mock_gcs_output_event = kconfig._io.KlioWriteFileConfig.from_dict(
mock_gcs_event_config
)
mock_bq_output_event_config = {
"type": "bq",
"project": "sigint",
"dataset": "test-data",
"table": "test-table",
"schema": {"fields": [{"name": "n", "type": "t", "mode": "m"}]},
"io_type": kconfig._io.KlioIOType.EVENT,
"io_direction": kconfig._io.KlioIODirection.OUTPUT,
}
mock_bq_output_event = kconfig._io.KlioBigQueryEventOutput.from_dict(
mock_bq_output_event_config
)
@pytest.mark.parametrize(
"mock_event_output", ((mock_gcs_output_event), (mock_bq_output_event),)
)
def test_unverified_event_outputs(
mocker,
caplog,
klio_config,
mock_event_output,
mock_storage,
mock_publisher,
):
mock_verify_gcs_bucket = mocker.patch.object(
verify.VerifyJob, "_verify_gcs_bucket"
)
mock_verify_pub_topic = mocker.patch.object(
verify.VerifyJob, "_verify_pub_topic"
)
job = verify.VerifyJob(klio_config, False)
job._publisher_client = mock_publisher
job._storage_client = mock_storage
job.klio_config.job_config.events.outputs = [mock_event_output]
data_config = {
"type": "gcs",
"location": "test",
"io_type": kconfig._io.KlioIOType.DATA,
"io_direction": kconfig._io.KlioIODirection.OUTPUT,
}
job.klio_config.job_config.data.outputs = [
kconfig._io.KlioGCSOutputDataConfig.from_dict(data_config)
]
mock_verify_gcs_bucket.return_value = True
actual = job._verify_outputs()
assert actual
mock_verify_pub_topic.assert_not_called()
mock_verify_gcs_bucket.assert_called_with("test")
assert 3 == len(caplog.records)
@pytest.mark.parametrize(
"unverified_gcs, unverified_topic",
((False, False), (True, False), (True, True), (False, True)),
)
def test_verify_outputs(
mocker,
klio_config,
unverified_gcs,
unverified_topic,
mock_storage,
mock_publisher,
):
mock_verify_gcs_bucket = mocker.patch.object(
verify.VerifyJob, "_verify_gcs_bucket"
)
mock_verify_pub_topic = mocker.patch.object(
verify.VerifyJob, "_verify_pub_topic"
)
job = verify.VerifyJob(klio_config, False)
job._publisher_client = mock_publisher
job._storage_client = mock_storage
event_config = {
"type": "pubsub",
"topic": "test",
"io_type": kconfig._io.KlioIOType.EVENT,
"io_direction": kconfig._io.KlioIODirection.OUTPUT,
}
job.klio_config.job_config.events.outputs = [
kconfig._io.KlioPubSubEventOutput.from_dict(event_config)
]
data_config = {
"type": "gcs",
"location": "test",
"io_type": kconfig._io.KlioIOType.DATA,
"io_direction": kconfig._io.KlioIODirection.OUTPUT,
}
job.klio_config.job_config.data.outputs = [
kconfig._io.KlioGCSOutputDataConfig.from_dict(data_config)
]
if unverified_gcs and unverified_topic:
mock_verify_gcs_bucket.return_value = False
mock_verify_pub_topic.return_value = False
actual = job._verify_outputs()
expected = False
assert expected == actual
elif unverified_topic:
mock_verify_gcs_bucket.return_value = True
mock_verify_pub_topic.return_value = False
actual = job._verify_outputs()
expected = False
assert expected == actual
elif unverified_gcs:
mock_verify_gcs_bucket.return_value = False
mock_verify_pub_topic.return_value = True
actual = job._verify_outputs()
expected = False
assert expected == actual
else:
mock_verify_gcs_bucket.return_value = True
mock_verify_pub_topic.return_value = True
actual = job._verify_outputs()
expected = True
assert expected == actual
mock_verify_gcs_bucket.assert_called_with("test")
mock_verify_pub_topic.assert_called_with("test", "output")
@pytest.mark.parametrize(
"event_topic, data_location, expected_log_count",
(
("test", "test", 3),
(None, "test", 4),
("test", None, 4),
(None, None, 5),
),
)
def test_verify_outputs_logs(
event_topic,
data_location,
expected_log_count,
mocker,
klio_config,
mock_storage,
mock_publisher,
caplog,
):
mock_verify_gcs = mocker.patch.object(
verify.VerifyJob, "_verify_gcs_bucket"
)
mock_verify_pub = mocker.patch.object(
verify.VerifyJob, "_verify_pub_topic"
)
job = verify.VerifyJob(klio_config, False)
job._publisher_client = mock_publisher
job._storage_client = mock_storage
event_config = {
"type": "pubsub",
"topic": event_topic,
"io_type": kconfig._io.KlioIOType.EVENT,
"io_direction": kconfig._io.KlioIODirection.OUTPUT,
}
job.klio_config.job_config.events.outputs = [
kconfig._io.KlioPubSubEventOutput.from_dict(event_config)
]
data_config = {
"type": "gcs",
"location": data_location,
"io_type": kconfig._io.KlioIOType.DATA,
"io_direction": kconfig._io.KlioIODirection.OUTPUT,
}
job.klio_config.job_config.data.outputs = [
kconfig._io.KlioGCSOutputDataConfig.from_dict(data_config)
]
job._verify_outputs()
assert expected_log_count == len(caplog.records)
if data_location is not None:
mock_verify_gcs.assert_called_with(data_location)
if event_topic is not None:
mock_verify_pub.assert_called_with(event_topic, "output")
@pytest.mark.parametrize(
"unverified_staging, unverified_temp",
((False, False), (True, True), (True, False), (False, True)),
)
def test_verify_tmp_files(
mocker, mock_storage, klio_config, unverified_staging, unverified_temp
):
job = verify.VerifyJob(klio_config, True)
job._storage_client = mock_storage
job.klio_config.pipeline_options.staging_location = "test"
job.klio_config.pipeline_options.temp_location = "test2"
mock_verify_gcs = mocker.patch.object(
verify.VerifyJob, "_verify_gcs_bucket"
)
if unverified_staging and unverified_temp:
mock_verify_gcs.side_effect = [False, False]
actual = job._verify_tmp_files()
assert actual is False
elif unverified_staging:
mock_verify_gcs.side_effect = [False, True]
actual = job._verify_tmp_files()
assert actual is False
elif unverified_temp:
mock_verify_gcs.side_effect = [True, False]
actual = job._verify_tmp_files()
assert actual is False
else:
mock_verify_gcs.side_effect = [True, True]
actual = job._verify_tmp_files()
assert actual is True
mock_verify_gcs.assert_any_call("test")
mock_verify_gcs.assert_any_call("test2")
assert 2 == mock_verify_gcs.call_count
def test_verify(
mocker, klio_config, mock_storage, mock_publisher, mock_sub, caplog
):
caplog.set_level(logging.INFO)
job = verify.VerifyJob(klio_config, False)
job._publisher_client = mock_publisher
job._storage_client = mock_storage
job._subscriber_client = mock_sub
mock_verify_inputs = mocker.patch.object(job, "_verify_inputs")
mock_verify_outputs = mocker.patch.object(job, "_verify_outputs")
mock_verify_tmp = mocker.patch.object(job, "_verify_tmp_files")
mock_verify_iam_roles = mocker.patch.object(job, "_verify_iam_roles")
mock_verify_dashboard = mocker.patch.object(
job, "_verify_stackdriver_dashboard"
)
mocker.patch.object(verify, "discovery")
mock_verify_config = mocker.patch.object(kconfig, "KlioConfig")
mock_verify_config.return_value = klio_config
mock_storage.return_value = mock_storage
mock_publisher.return_value = mock_publisher
mock_sub.return_value = mock_sub
mock_verify_inputs.return_value = True
mock_verify_outputs.return_value = True
mock_verify_tmp.return_value = True
mock_verify_iam_roles.return_value = True
job.verify_job()
mock_verify_inputs.assert_called_once_with()
mock_verify_outputs.assert_called_once_with()
mock_verify_tmp.assert_called_once_with()
assert mock_verify_iam_roles.called
mock_verify_dashboard.assert_called_once_with()
assert 1 == len(caplog.records)
def test_verify_raises_exception_raises_system_exit(mocker, klio_config):
job = verify.VerifyJob(klio_config, False)
mock_verify_all = mocker.patch.object(job, "_verify_all")
mock_verify_all.return_value = False
mock_verify_all.side_effect = Exception
with pytest.raises(SystemExit):
job.verify_job()
def test_verify_raises_system_exit(
mocker, klio_config, mock_storage, mock_publisher, mock_sub, caplog
):
caplog.set_level(logging.INFO)
job = verify.VerifyJob(klio_config, False)
job._publisher_client = mock_publisher
job._storage_client = mock_storage
job._subscriber_client = mock_sub
mock_verify_inputs = mocker.patch.object(job, "_verify_inputs")
mock_verify_outputs = mocker.patch.object(job, "_verify_outputs")
mock_verify_tmp = mocker.patch.object(job, "_verify_tmp_files")
mock_verify_iam_roles = mocker.patch.object(job, "_verify_iam_roles")
mock_verify_dashboard = mocker.patch.object(
job, "_verify_stackdriver_dashboard"
)
mocker.patch.object(verify, "discovery")
mock_verify_config = mocker.patch.object(kconfig, "KlioConfig")
mock_verify_config.return_value = klio_config
mock_storage.return_value = mock_storage
mock_publisher.return_value = mock_publisher
mock_sub.return_value = mock_sub
mock_verify_inputs.return_value = True
mock_verify_outputs.return_value = False
mock_verify_iam_roles.return_value = True
mock_verify_tmp.return_value = True
with pytest.raises(SystemExit):
job.verify_job()
mock_verify_inputs.assert_called_once_with()
mock_verify_outputs.assert_called_once_with()
mock_verify_tmp.assert_called_once_with()
mock_verify_dashboard.assert_called_once_with()
| 30.920844 | 79 | 0.673607 |
acefd307a6ff54b9be057e03a1f9dcfc3064090a | 6,132 | py | Python | ophyd/areadetector/detectors.py | DominicOram/ophyd | df60483867e521dcda83648756cab8fc7b80dd17 | [
"BSD-3-Clause"
] | 15 | 2019-06-17T20:08:50.000Z | 2021-10-29T20:31:03.000Z | ophyd/areadetector/detectors.py | DominicOram/ophyd | df60483867e521dcda83648756cab8fc7b80dd17 | [
"BSD-3-Clause"
] | 274 | 2019-05-10T16:57:05.000Z | 2022-02-17T19:56:05.000Z | ophyd/areadetector/detectors.py | DominicOram/ophyd | df60483867e521dcda83648756cab8fc7b80dd17 | [
"BSD-3-Clause"
] | 37 | 2019-07-06T18:17:07.000Z | 2022-03-09T22:26:18.000Z | # vi: ts=4 sw=4
'''AreaDetector Devices
`areaDetector`_ detector abstractions
.. _areaDetector: https://areadetector.github.io/master/index.html
'''
from .base import (ADBase, ADComponent as C)
from . import cam
__all__ = ['DetectorBase',
'AreaDetector',
'AdscDetector',
'Andor3Detector',
'AndorDetector',
'BrukerDetector',
'DexelaDetector',
'EmergentVisionDetector',
'EigerDetector',
'FirewireLinDetector',
'FirewireWinDetector',
'GreatEyesDetector',
'LightFieldDetector',
'Mar345Detector',
'MarCCDDetector',
'PSLDetector',
'PerkinElmerDetector',
'PICamDetector',
'PilatusDetector',
'PixiradDetector',
'PointGreyDetector',
'ProsilicaDetector',
'PvcamDetector',
'RoperDetector',
'SimDetector',
'URLDetector',
'UVCDetector',
'Xspress3Detector'
]
class DetectorBase(ADBase):
"""
The base class for the hardware-specific classes that follow.
Note that Plugin also inherits from ADBase.
This adds some AD-specific methods that are not shared by the plugins.
"""
_default_configuration_attrs = (ADBase._default_configuration_attrs +
('cam', ))
def dispatch(self, key, timestamp):
"""Notify plugins of acquisition being complete.
When a new acquisition is started, this method is called with a
key which is a label like 'light', 'dark', or 'gain8'.
It in turn calls ``generate_datum`` on all of the plugins that have
that method.
File plugins are identified by searching for a
:meth:`~ophyd.areadetector.filestore_mixins.FileStoreBase.generate_datum`
method that must have the signature ::
def generate_datum(key: str, timestamp: float, datum_kwargs: dict):
...
"""
file_plugins = [s for s in self._signals.values() if
hasattr(s, 'generate_datum')]
for p in file_plugins:
if p.enable.get():
p.generate_datum(key, timestamp, {})
def make_data_key(self):
source = 'PV:{}'.format(self.prefix)
# This shape is expected to match arr.shape for the array.
shape = (self.cam.num_images.get(),
self.cam.array_size.array_size_y.get(),
self.cam.array_size.array_size_x.get())
return dict(shape=shape, source=source, dtype='array',
external='FILESTORE:')
def collect_asset_docs(self):
file_plugins = [s for s in self._signals.values() if
hasattr(s, 'collect_asset_docs')]
for p in file_plugins:
yield from p.collect_asset_docs()
class AreaDetector(DetectorBase):
cam = C(cam.AreaDetectorCam, 'cam1:')
class SimDetector(DetectorBase):
_html_docs = ['simDetectorDoc.html']
cam = C(cam.SimDetectorCam, 'cam1:')
class AdscDetector(DetectorBase):
_html_docs = ['adscDoc.html']
cam = C(cam.AdscDetectorCam, 'cam1:')
class AndorDetector(DetectorBase):
_html_docs = ['andorDoc.html']
cam = C(cam.AndorDetectorCam, 'cam1:')
class Andor3Detector(DetectorBase):
_html_docs = ['andor3Doc.html']
cam = C(cam.Andor3DetectorCam, 'cam1:')
class BrukerDetector(DetectorBase):
_html_docs = ['BrukerDoc.html']
cam = C(cam.BrukerDetectorCam, 'cam1:')
class DexelaDetector(DetectorBase):
_html_docs = ['DexelaDoc.html']
cam = C(cam.DexelaDetectorCam, 'cam1:')
class EmergentVisionDetector(DetectorBase):
_html_docs = ['EVTDoc.html']
cam = C(cam.EmergentVisionDetectorCam, 'cam1:')
class EigerDetector(DetectorBase):
_html_docs = ['EigerDoc.html']
cam = C(cam.EigerDetectorCam, 'cam1:')
class FirewireLinDetector(DetectorBase):
_html_docs = ['FirewireWinDoc.html']
cam = C(cam.FirewireLinDetectorCam, 'cam1:')
class FirewireWinDetector(DetectorBase):
_html_docs = ['FirewireWinDoc.html']
cam = C(cam.FirewireWinDetectorCam, 'cam1:')
class GreatEyesDetector(DetectorBase):
_html_docs = [] # the documentation is not public
cam = C(cam.GreatEyesDetectorCam, 'cam1:')
class LightFieldDetector(DetectorBase):
_html_docs = ['LightFieldDoc.html']
cam = C(cam.LightFieldDetectorCam, 'cam1:')
class Mar345Detector(DetectorBase):
_html_docs = ['Mar345Doc.html']
cam = C(cam.Mar345DetectorCam, 'cam1:')
class MarCCDDetector(DetectorBase):
_html_docs = ['MarCCDDoc.html']
cam = C(cam.MarCCDDetectorCam, 'cam1:')
class PerkinElmerDetector(DetectorBase):
_html_docs = ['PerkinElmerDoc.html']
cam = C(cam.PerkinElmerDetectorCam, 'cam1:')
class PSLDetector(DetectorBase):
_html_docs = ['PSLDoc.html']
cam = C(cam.PSLDetectorCam, 'cam1:')
class PICamDetector(DetectorBase):
_html_docs = ['PICamDoc.html']
cam = C(cam.PICamDetectorCam, 'cam1:')
class PilatusDetector(DetectorBase):
_html_docs = ['pilatusDoc.html']
cam = C(cam.PilatusDetectorCam, 'cam1:')
class PixiradDetector(DetectorBase):
_html_docs = ['PixiradDoc.html']
cam = C(cam.PixiradDetectorCam, 'cam1:')
class PointGreyDetector(DetectorBase):
_html_docs = ['PointGreyDoc.html']
cam = C(cam.PointGreyDetectorCam, 'cam1:')
class ProsilicaDetector(DetectorBase):
_html_docs = ['prosilicaDoc.html']
cam = C(cam.ProsilicaDetectorCam, 'cam1:')
class PvcamDetector(DetectorBase):
_html_docs = ['pvcamDoc.html']
cam = C(cam.PvcamDetectorCam, 'cam1:')
class RoperDetector(DetectorBase):
_html_docs = ['RoperDoc.html']
cam = C(cam.RoperDetectorCam, 'cam1:')
class URLDetector(DetectorBase):
_html_docs = ['URLDoc.html']
cam = C(cam.URLDetectorCam, 'cam1:')
class UVCDetector(DetectorBase):
_html_docs = ['UVCDoc.html']
cam = C(cam.UVCDetectorCam, 'cam1:')
class Xspress3Detector(DetectorBase):
_html_docs = ['Xspress3Doc.html']
cam = C(cam.Xspress3DetectorCam, 'det1:')
| 27.253333 | 81 | 0.645466 |
acefd4f2dcfe6b354a3c18967839a060d2a443ba | 303 | py | Python | 2015/day01_part1/model/floor.py | j-peralva/AdventOfCode | dc9e6af6e4afd4328f58e0ed0e5f1d2a245e4991 | [
"MIT"
] | null | null | null | 2015/day01_part1/model/floor.py | j-peralva/AdventOfCode | dc9e6af6e4afd4328f58e0ed0e5f1d2a245e4991 | [
"MIT"
] | null | null | null | 2015/day01_part1/model/floor.py | j-peralva/AdventOfCode | dc9e6af6e4afd4328f58e0ed0e5f1d2a245e4991 | [
"MIT"
] | null | null | null | # noinspection DuplicatedCode
"""Jefferson Peralva Machiqueira"""
class Floor:
def __init__(self):
self.__floor = 0
def move_up(self):
self.__floor += 1
def move_down(self):
self.__floor -= 1
@property
def floor(self) -> int:
return self.__floor
| 16.833333 | 35 | 0.607261 |
acefd6242a4cd6d722be86121270eef244d8f521 | 14,002 | py | Python | cloudify_rest_sdk/utility.py | cloudify-incubator/cloudify-utilities-plugins-sdk | f5cfe0381a13a85d89b905c06c79ad8ada5319bc | [
"Apache-2.0"
] | 1 | 2019-04-23T03:06:52.000Z | 2019-04-23T03:06:52.000Z | cloudify_rest_sdk/utility.py | cloudify-incubator/cloudify-utilities-plugins-sdk | f5cfe0381a13a85d89b905c06c79ad8ada5319bc | [
"Apache-2.0"
] | 9 | 2018-12-17T14:08:29.000Z | 2022-01-16T17:52:54.000Z | cloudify_rest_sdk/utility.py | cloudify-incubator/cloudify-utilities-plugins-sdk | f5cfe0381a13a85d89b905c06c79ad8ada5319bc | [
"Apache-2.0"
] | 3 | 2021-12-13T20:53:37.000Z | 2022-01-20T09:01:47.000Z | ########
# Copyright (c) 2014-2020 Cloudify Platform Ltd. All rights reserved
#
# 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
import re
import ast
import yaml
import logging
import requests
import tempfile
import xmltodict
from six import StringIO, string_types
from cloudify_rest_sdk import LOGGER_NAME
from cloudify_common_sdk.filters import (
translate_and_save,
shorted_text,
render_template,
obfuscate_passwords,
)
from cloudify_common_sdk.exceptions import (
RecoverableStatusCodeCodeException,
ExpectationException,
WrongTemplateDataException,
NonRecoverableResponseException,
RecoverableResponseException)
logger = logging.getLogger(LOGGER_NAME)
TEMPLATE_PROPERTY_RETRY_ON_CONNECTION_ERROR = 'retry_on_connection_error'
# request_props (port, ssl, verify, hosts )
def process(params, template, request_props, prerender=False,
resource_callback=False):
logger.info(
'Template:\n{}'.format(shorted_text(obfuscate_passwords(template))))
if prerender:
rendered_call = render_template(template, params)
template_yaml = yaml.load(rendered_call)
else:
template_yaml = yaml.load(template)
result_properties = {}
calls = []
if not template_yaml or not template_yaml.get('rest_calls'):
logger.debug('Empty call list')
return {}
for call in template_yaml['rest_calls']:
call_with_request_props = request_props.copy()
logger.debug(
'Call: {}'.format(shorted_text(obfuscate_passwords(call))))
# enrich params with items stored in runtime props by prev calls
params.update(result_properties)
if not prerender:
call = "{0}".format(call)
# Remove quotation marks before and after jinja blocks
call = re.sub(r'\'\{\%', '{%', call)
call = re.sub(r'\%\}\'', '%}', call)
rendered_call = render_template(call, params)
call = ast.literal_eval(rendered_call)
calls.append(call)
logger.debug('Rendered call: {}'.format(
shorted_text(obfuscate_passwords(call))))
call_with_request_props.update(call)
# client/server side certification check
file_to_remove = []
for field in ['verify', 'cert']:
if isinstance(call_with_request_props.get(field), string_types):
if not os.path.isfile(call_with_request_props.get(field)):
fd, destination = tempfile.mkstemp()
os.write(fd, call_with_request_props.get(field))
os.close(fd)
# replace to path to content
call_with_request_props[field] = destination
file_to_remove.append(destination)
# run requests
try:
response = _send_request(call_with_request_props,
resource_callback=resource_callback)
finally:
for path in file_to_remove:
try:
os.remove(path)
except Exception as e:
logger.debug(
'Cant remove temporary file {path}: {error}'
.format(path=path, error=repr(e))
)
_process_response(response, call, result_properties)
result_properties = {'result_properties': result_properties,
'calls': calls}
return result_properties
def _send_request(call, resource_callback=None):
logger.debug(
'Request props: {}'.format(shorted_text(obfuscate_passwords(call))))
port = call['port']
ssl = call['ssl']
if port == -1:
port = 443 if ssl else 80
if not call.get('hosts', None):
call['hosts'] = [call['host']]
for i, host in enumerate(call['hosts']):
full_url = '{}://{}:{}{}'.format('https' if ssl else 'http', host,
port,
call['path'])
logger.debug('Full url: {}'.format(repr(full_url)))
# check if payload can be used as json
payload_format = call.get('payload_format', 'json')
payload_data = call.get('payload', None)
# check that we have some raw payload
payload_raw = call.get('payload_raw', call.get('raw_payload'))
if resource_callback and payload_raw:
payload_data = resource_callback(payload_raw)
# url params
params = call.get('params', {})
# files magic
files_merged = {}
files = {}
files_raw = call.get("files_raw", call.get("raw_files", {}))
# add all raw files
for name in files_raw:
files_merged[name] = resource_callback(files_raw[name])
# add inline files
files_merged.update(call.get("files", {}))
logger.debug('Files merged: {files_merged}'
.format(files_merged=shorted_text(files_merged)))
# convert files strcut to correct type
for name in files_merged:
if isinstance(files_merged[name], list):
# convert to correct struct
files[name] = tuple(files_merged[name])
elif isinstance(files_merged[name], string_types):
# send string as file
files[name] = StringIO(files_merged[name])
else:
# let's request decide about format
files[name] = files_merged[name]
logger.debug('Files: {files}'
.format(files=shorted_text(files)))
# combine payloads and params
if payload_format == 'json':
json_payload = payload_data
data = None
elif payload_format == 'urlencoded' and isinstance(payload_data, dict):
json_payload = None
params.update(payload_data)
data = None
else:
json_payload = None
data = payload_data
# auth
if 'auth' not in call:
auth = None
else:
auth = (call['auth'].get('user'), call['auth'].get('password'))
# run request
try:
response = requests.request(call['method'], full_url,
auth=auth,
headers=call.get('headers', None),
verify=call.get('verify', True),
cert=call.get('cert', None),
proxies=call.get('proxies', None),
timeout=call.get('timeout', None),
json=json_payload,
params=params,
files=files if files else None,
data=data)
except requests.exceptions.ConnectionError as e:
logger.debug('ConnectionError for host: {}'.format(repr(host)))
if TEMPLATE_PROPERTY_RETRY_ON_CONNECTION_ERROR in call and \
call[TEMPLATE_PROPERTY_RETRY_ON_CONNECTION_ERROR]:
raise RecoverableResponseException(
'ConnectionError {0} has occurred, but flag {1} is set. '
'Retrying...'
.format(
repr(e),
TEMPLATE_PROPERTY_RETRY_ON_CONNECTION_ERROR
)
)
if i == len(call['hosts']) - 1:
logger.error('No host from list available')
raise
logger.info('Response content: \n{}...'
.format(shorted_text(response.content)))
logger.info('Status code: {}'.format(repr(response.status_code)))
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
logger.debug(repr(e))
if response.status_code in call.get('recoverable_codes', []):
raise RecoverableStatusCodeCodeException(
'Response code {} defined as recoverable'.format(
response.status_code))
if response.status_code not in call.get('successful_codes', []):
# code is not marked as successful
raise
# success?
logger.debug(
'Response code {} defined as successful.'.format(
response.status_code))
return response
def _process_response(response, call, store_props):
logger.debug('Process Response: {}'.format(shorted_text(response)))
logger.debug(
'Call: {}'.format(shorted_text(obfuscate_passwords(call))))
logger.debug('Store props: {}'.format(shorted_text(store_props)))
logger.debug('Store headers: {}'.format(shorted_text(response.headers)))
translation_version = call.get('translation_format', 'auto')
# process headers
if response.headers:
translate_and_save(logger, response.headers,
call.get('header_translation', None),
store_props, translation_version)
# process cookies
if response.cookies:
translate_and_save(logger, response.cookies.get_dict(),
call.get('cookies_translation', None),
store_props, translation_version)
# process body
response_format = call.get('response_format', 'auto').lower()
if response_format == 'auto':
if response.headers.get('Content-Type'):
response_content_type = response.headers['Content-Type'].lower()
if (
response_content_type.startswith("application/json") or
response_content_type.startswith("text/json")
):
response_format = 'json'
elif (
response_content_type.startswith('text/xml') or
response_content_type.startswith('application/xml')
):
response_format = 'xml'
logger.debug('Detected type is {}'.format(repr(response_format)))
# for backward compatibility set json for unknown types
if response_format == 'auto':
response_format = 'json'
logger.debug('Response format is {}'.format(repr(response_format)))
if response_format == 'json' or response_format == 'xml':
if response_format == 'json':
json = response.json()
else: # XML
json = xmltodict.parse(response.text)
logger.debug('XML transformed to dict: {}'
.format(shorted_text(obfuscate_passwords(json))))
_check_response(json, call.get('nonrecoverable_response'), False)
_check_response(json, call.get('response_expectation'), True)
translate_and_save(logger, json,
call.get('response_translation', None),
store_props, translation_version)
elif response_format == 'text':
store_props['text'] = response.text
elif response_format == 'raw':
logger.debug('No action for raw response_format')
else:
raise WrongTemplateDataException(
"Response_format {} is not supported. "
"Only json/xml or raw response_format is supported".format(
repr(response_format)))
def _check_response(json, response, is_recoverable):
if not is_recoverable:
logger.debug('Check response (nonrecoverable) in json: {} by {}'
.format(shorted_text(obfuscate_passwords(json)),
repr(response)))
else:
logger.debug('Check response (recoverable) in json: {} by {}'
.format(shorted_text(obfuscate_passwords(json)),
repr(response)))
if not response:
return
if not isinstance(response, list) and not is_recoverable:
raise WrongTemplateDataException(
"Response (nonrecoverable) had to be list. "
"Type {} not supported. ".format(
type(response)))
if not isinstance(response, list) and is_recoverable:
raise WrongTemplateDataException(
"Response (recoverable) had to be list. "
"Type {} not supported. ".format(
type(response)))
if isinstance(response[0], list):
for item in response:
_check_response(json, item, is_recoverable)
else:
pattern = response.pop(-1)
for key in response:
try:
json = json[key]
except (TypeError, IndexError, KeyError) as e:
logger.debug(repr(e))
raise ExpectationException(
'No key or index "{}" in json {}'.format(key, json))
if (
re.match(pattern, "{0}".format(json)) and
not is_recoverable
):
raise NonRecoverableResponseException(
"Giving up... \n"
"Response value: "
"{} matches regexp:{} from nonrecoverable_response. ".format(
json, pattern))
if (
not re.match(pattern, "{0}".format(json)) and
is_recoverable
):
raise RecoverableResponseException(
"Trying one more time...\n"
"Response value:{} does not match regexp: {} "
"from response_expectation".format(
json, pattern))
| 39.891738 | 79 | 0.575775 |
acefd65b56b94e6b0862d8e2676bc9cb8826981b | 1,947 | py | Python | python/paddle/fluid/tests/unittests/test_dist_fleet_ctr.py | wopeizl/Paddle | 9e5948230edfcb67083c8f5f48af25f41d02dab7 | [
"Apache-2.0"
] | 1 | 2018-06-23T10:46:40.000Z | 2018-06-23T10:46:40.000Z | python/paddle/fluid/tests/unittests/test_dist_fleet_ctr.py | wopeizl/Paddle | 9e5948230edfcb67083c8f5f48af25f41d02dab7 | [
"Apache-2.0"
] | null | null | null | python/paddle/fluid/tests/unittests/test_dist_fleet_ctr.py | wopeizl/Paddle | 9e5948230edfcb67083c8f5f48af25f41d02dab7 | [
"Apache-2.0"
] | 4 | 2019-09-30T02:15:34.000Z | 2019-09-30T02:41:30.000Z | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# 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 __future__ import print_function
import os
import unittest
from test_dist_fleet_base import TestFleetBase
def skip_ci(func):
on_ci = bool(int(os.environ.get("SKIP_UNSTABLE_CI", '0')))
def __func__(*args, **kwargs):
if on_ci:
return
return func(*args, **kwargs)
return __func__
class TestDistMnist2x2(TestFleetBase):
def _setup_config(self):
self._sync_mode = False
def check_with_place(self,
model_file,
delta=1e-3,
check_error_log=False,
need_envs={}):
required_envs = {
"PATH": os.getenv("PATH", ""),
"PYTHONPATH": os.getenv("PYTHONPATH", ""),
"LD_LIBRARY_PATH": os.getenv("LD_LIBRARY_PATH", ""),
"FLAGS_rpc_deadline": "5000", # 5sec to fail fast
"http_proxy": ""
}
required_envs.update(need_envs)
if check_error_log:
required_envs["GLOG_v"] = "3"
required_envs["GLOG_logtostderr"] = "1"
tr0_losses, tr1_losses = self._run_cluster(model_file, required_envs)
def test_dist_train(self):
self.check_with_place(
"dist_fleet_ctr.py", delta=1e-5, check_error_log=True)
if __name__ == "__main__":
unittest.main()
| 29.953846 | 77 | 0.637391 |
acefd6bc773ede99cd074874f6f0e0d61448d79e | 9,643 | py | Python | pyssp/noise_estimation/minimum_statistics.py | imoted/pyssp | 3f0ea8340cfdd663b1fbcaf43ea0e31914d98549 | [
"MIT"
] | 19 | 2017-03-08T23:22:27.000Z | 2021-01-26T02:00:54.000Z | pyssp/noise_estimation/minimum_statistics.py | imoted/pyssp | 3f0ea8340cfdd663b1fbcaf43ea0e31914d98549 | [
"MIT"
] | 2 | 2017-03-14T16:35:38.000Z | 2019-06-26T02:55:35.000Z | pyssp/noise_estimation/minimum_statistics.py | imoted/pyssp | 3f0ea8340cfdd663b1fbcaf43ea0e31914d98549 | [
"MIT"
] | 7 | 2017-02-24T21:11:33.000Z | 2020-08-25T15:19:48.000Z | # -*- coding: utf-8 -*-
import scipy as sp
import numpy as np
# compute smoothing parameter
def M_H(D):
if(D == 1):
M = 0
H = 0
elif(D == 2):
M = 0.26
H = 0.15
elif(D == 4):
# nodata
M = 0.40
H = 0.30
elif(D == 5):
M = 0.48
H = 0.48
elif(D == 6):
# nodata
M = 0.50
H = 0.65
elif(D == 8):
M = 0.58
H = 0.78
elif(D == 10):
M = 0.61
H = 0.98
elif(D == 12):
M = 0.64
H = 1.25
elif(D == 15):
M = 0.668
H = 1.55
elif(D == 18):
# nodata
M = 0.68
H = 1.7
elif(D == 20):
M = 0.705
H = 2.0
elif(D == 24):
# no data
M = 0.730
H = 2.15
elif(D == 30):
M = 0.762
H = 2.3
elif(D == 40):
M = 0.8
H = 2.52
elif(D == 60):
M = 0.841
H = 2.52
elif(D == 80):
M = 0.865
H = 3.25
elif(D == 96):
M = 0.87
H = 3.5
elif(D == 120):
M = 0.89
H = 4.0
elif(D == 140):
M = 0.9
H = 4.1
elif(D == 160):
M = 0.91
H = 4.1
elif(D == 192):
# nodata
M = 0.92
H = 4.2
else:
M = -1
H = -1
print("D value:", D)
raise ValueError('D out of range')
return M, H
class MinimumStatistics():
def __init__(self, winsize, window, samp_rate):
self._window = window
self._winsize = winsize
# initial values
frametime = (self._winsize / 2.0) / samp_rate # frame incremental time [sec]
self._snrexp = (-1.0) * frametime / 0.064
self._av = 2.12
self._alpha_c_lambda = 0.7
# U subwindows
self._U = 8
# V samples
self._V = 12
# D window (96 samples)
self._D = self._U * self._V
self._subwc = self._V - 1
self._ibuf = 0
self._lmin_flag_lambda = np.zeros(self._winsize)
self._alpha_max = 0.96
self._beta_max = 0.8
qeqmax = 14.0 # max value of Qeq per frame
self._qeqimin = 1 / qeqmax
self._clear_max = 65535 * 65535
self._actmin_lambda = np.ones(self._winsize)
self._actmin_lambda = self._actmin_lambda * self._clear_max
self._actmin_lambda_sub = self._actmin_lambda
self._Pmin_u_lambda = self._actmin_lambda
self._actbuf = np.ones((self._U, self._winsize))
self._actbuf = self._actbuf * self._clear_max
# for graph
self._x_data = []
self._y_data = []
self._p_data = []
self._x_data_all = []
self._y_data_all = []
self._p_data_all = []
pass
def init_noise_profile(self, NP_lambda):
self._P_lambda = NP_lambda
self._sn2_lambda = self._P_lambda
self._eP_lambda = self._P_lambda
self._eP2_lambda = self._eP_lambda ** 2
self._Pmin_u_lambda = self._P_lambda
def compute(self, frame, lamda):
Y_lambda = np.fft.fftpack.fft(frame * self._window)
power = np.absolute(Y_lambda) ** 2
return self.compute_with_power_spectrum(power, lamda)
def compute_with_power_spectrum(self, power_spectrum, lamda):
# eq9
alpha_c_lambda_tilde = 1.0 / (1.0 + (np.sum(self._P_lambda) / np.sum(power_spectrum) - 1.0) ** 2)
# eq10
self._alpha_c_lambda = 0.7 * self._alpha_c_lambda + 0.3 * np.maximum(alpha_c_lambda_tilde, 0.7)
# eq11
alpha_lambda_hat = (self._alpha_max * self._alpha_c_lambda) / (1 + (self._P_lambda / self._sn2_lambda - 1) ** 2)
# eq12
snr = np.sum(self._P_lambda) / np.sum(self._sn2_lambda)
alpha_lambda_hat = np.maximum(alpha_lambda_hat, np.minimum(0.3, snr ** self._snrexp))
# eq4 smoothed periodgram
self._P_lambda = alpha_lambda_hat * self._P_lambda + (1.0 - alpha_lambda_hat) * power_spectrum
# eq20
beta_lambda = np.minimum(alpha_lambda_hat ** 2, self._beta_max)
self._eP_lambda = beta_lambda * self._eP_lambda + (1.0 - beta_lambda) * self._P_lambda
self._eP2_lambda = beta_lambda * self._eP2_lambda + (1.0 - beta_lambda) * (self._P_lambda ** 2)
# eq22
vP_lambda = self._eP2_lambda - (self._eP_lambda ** 2)
# eq23 modification
Qeq_lambda_inverse = np.maximum(np.minimum(vP_lambda / (2 * (self._sn2_lambda ** 2)), 0.5),
self._qeqimin / (lamda + 1))
# eq23 + 12 lines
eQ_lambda = np.sum(Qeq_lambda_inverse) / self._winsize
# eq23 + 11 lines
Bc_lambda = 1.0 + self._av * np.sqrt(eQ_lambda)
# ----------------------------------------------------------------------------------------
# for overall window of length D
# ----------------------------------------------------------------------------------------
# eq16
M, H = M_H(self._D)
Qeq_lambda_tilde = (1.0 / Qeq_lambda_inverse - 2 * M) / (1 - M)
# eq17
Bmin_lambda = 1.0 + (self._D - 1) * 2.0 / Qeq_lambda_tilde
# ----------------------------------------------------------------------------------------
# for subwindow U of length V
# ----------------------------------------------------------------------------------------
# eq16
M, H = M_H(self._V)
Qeq_lambda_tilde_sub = (1.0 / Qeq_lambda_inverse - 2 * M) / (1 - M)
# eq17
Bmin_lambda_sub = 1.0 + (self._V - 1) * 2.0 / Qeq_lambda_tilde_sub
# ----------------------------------------------------------------------------------------
# set k_mod(k) = 0 for all frequency bin k
k_mod = np.zeros(self._winsize)
# calc actmin
actmin_lambda_current = self._P_lambda * Bmin_lambda * Bc_lambda
# if(P*Bmin*Bc < actmin)
k_mod = np.less(actmin_lambda_current, self._actmin_lambda)
if(k_mod.any()):
# update new minimum of D
self._actmin_lambda[k_mod] = actmin_lambda_current[k_mod]
# update new minimum of V
actmin_lambda_current_sub = self._P_lambda * Bmin_lambda_sub * Bc_lambda
self._actmin_lambda_sub[k_mod] = actmin_lambda_current_sub[k_mod]
if(0 < self._subwc and self._subwc < self._V - 1):
# sample is NOT the fisrt or the last; middle of buffer allows a local minimum
self._lmin_flag_lambda = np.minimum(self._lmin_flag_lambda + k_mod, 1)
# calc Pmin_u_lamda == sigma_n_lamda_hat**2
self._Pmin_u_lambda = np.minimum(self._actmin_lambda_sub, self._Pmin_u_lambda)
# store sn2 for later use
self._sn2_lambda = self._Pmin_u_lambda
self._subwc = self._subwc + 1
elif(self._subwc >= self._V - 1):
# sample IS the last; end of buffer lets finishing subwindow process and a buffer switch
self._lmin_flag_lambda = np.maximum(self._lmin_flag_lambda - k_mod, 0)
# store actmin_lamnda, note actbuf is NOT cyclic!
self._ibuf = np.mod(self._ibuf, self._U)
self._actbuf[self._ibuf] = self._actmin_lambda
self._ibuf = self._ibuf + 1
# find Pmin_u, the minimum of the last U stored value of actmin
self._Pmin_u_lambda = self._actbuf.min(axis=0)
# calc noise_slope_max
if(eQ_lambda < 0.03):
noise_slope_max = 8.0
elif(eQ_lambda < 0.05):
noise_slope_max = 4.0
elif(eQ_lambda < 0.06):
noise_slope_max = 2.0
else:
noise_slope_max = 1.2
# replace all previously stored values of actmin by actminsub
lmin = self._lmin_flag_lambda * np.less(self._actmin_lambda_sub,
noise_slope_max * self._Pmin_u_lambda) *\
np.less(self._Pmin_u_lambda, self._actmin_lambda_sub)
lmin = np.int16(lmin)
if(lmin.any()):
self._Pmin_u_lambda[lmin] = self._actmin_lambda_sub[lmin]
r = np.ones((self._U, self._winsize))
rp = r * self._Pmin_u_lambda
self._actbuf[:, lmin] = rp[:, lmin]
# update flags
self._lmin_flag_lambda = np.zeros(self._winsize)
self._actmin_lambda = np.ones(self._winsize) * self._clear_max
self._subwc = 0
else:
self._subwc = self._subwc + 1
x = self._sn2_lambda
# stderror; paper [2], Fig 15; not use
# qisq = np.sqrt(Qeq_lambda_inverse)
# xs = x*np.sqrt(0.266*(self._D+100*qisq)*qisq/\
# (1+0.005*self._D+6.0/self._D)/(0.5*(1.0/Qeq_lambda_inverse)+self._D-1))
self._x_data.append(x)
self._x_data_all.append(10 * np.log10(np.sum(np.absolute(x)) / self._winsize))
self._p_data_all.append(10 * np.log10(np.sum(self._P_lambda) / self._winsize))
self._y_data.append(power_spectrum)
self._y_data_all.append(10 * np.log10(np.sum(power_spectrum) / self._winsize))
return x
def show_debug_result(self):
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid('on', 'major', color='#666666', linestyle='-')
ax.plot(self._y_data_all)
ax.plot(self._p_data_all, linewidth=3.0)
ax.plot(self._x_data_all, linewidth=3.0)
ax.legend(("Periodgram", "Smoothed Periodgram", "Estimated Noise")) # ,"True Noise"))
plt.show()
| 35.193431 | 120 | 0.522866 |
acefd928c401151694cd5b9c8cd0a0ea305c68c0 | 2,222 | gyp | Python | src/data_manager/testing/mock_data_manager_base.gyp | dancerj/mozc | a5a4927c1f709d2ff0c681585c746f73a434e4c9 | [
"BSD-3-Clause"
] | null | null | null | src/data_manager/testing/mock_data_manager_base.gyp | dancerj/mozc | a5a4927c1f709d2ff0c681585c746f73a434e4c9 | [
"BSD-3-Clause"
] | 1 | 2021-06-30T14:59:51.000Z | 2021-06-30T15:31:56.000Z | src/data_manager/testing/mock_data_manager_base.gyp | dancerj/mozc | a5a4927c1f709d2ff0c681585c746f73a434e4c9 | [
"BSD-3-Clause"
] | 1 | 2022-03-25T09:01:39.000Z | 2022-03-25T09:01:39.000Z | # Copyright 2010-2020, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
{
'variables': {
'relative_dir': 'data_manager/testing',
'relative_mozc_dir': '',
'gen_out_dir': '<(SHARED_INTERMEDIATE_DIR)/<(relative_dir)',
'gen_out_mozc_dir': '<(SHARED_INTERMEDIATE_DIR)/<(relative_mozc_dir)',
# The following variables are passed to ../data_manager.gypi.
'current_dir': '.',
'mozc_dir': '../..',
'common_data_dir': '<(mozc_dir)/data',
'platform_data_dir': '<(mozc_dir)/data/test/dictionary',
'dataset_tag': 'mock',
},
# This 'includes' defines the following targets:
# - mock_user_pos_manager (type: static_library)
# - gen_mock_embedded_data_light (type: none)
'includes': [ '../data_manager_base.gypi' ],
}
| 46.291667 | 74 | 0.743924 |
acefd9cf626a31c51249a09e3eb965e235f1474a | 1,938 | py | Python | Blocks/UpdateVertexBlock.py | Terranlee/Grail | d0197d9bf8e25c125742be2517fc2f6659ef02e7 | [
"Apache-2.0"
] | 7 | 2016-06-29T21:52:15.000Z | 2021-08-08T18:48:15.000Z | Blocks/UpdateVertexBlock.py | Terranlee/Grail | d0197d9bf8e25c125742be2517fc2f6659ef02e7 | [
"Apache-2.0"
] | 3 | 2016-03-30T15:04:52.000Z | 2016-05-24T19:03:06.000Z | Blocks/UpdateVertexBlock.py | UWQuickstep/Grail | d0197d9bf8e25c125742be2517fc2f6659ef02e7 | [
"Apache-2.0"
] | 4 | 2016-03-14T22:02:33.000Z | 2018-10-07T15:47:33.000Z | from Block import Block
class UpdateVertexBlock(Block):
'''
generates sql statements to update the value of the vertices
'''
otherTable=""
valueExpression=""
def getValueExpression(self):
'''
returns the scalar function/value expression
'''
return self.valueExpression
def getOtherTable(self):
'''
returns the name of the other table
'''
return self.otherTable
def __init__(self,stage,indent,col_dict,from_lst,pred=""):
'''
constructor
@param stage: stage of the block
@type stage: string
@param indent: indent level
@type indent: int
@param otherTable: name of the other table from which new values are retrieved
@type otherTable: string
@param valueExpression: expression or scalar function of the attribute in the other table
@type valueExpression: string
'''
super(UpdateVertexBlock,self).__init__(stage,indent)
'''
self.otherTable = otherTable;
self.valueExpression = valueExpression;
self.append("UPDATE next SET val = " + valueExpression);
self.append("FROM "+otherTable);
self.append("WHERE next.id = " + otherTable + ".id" + ";");
self.sql = self.sb
self.update_next(col_dict,from_lst)
'''
self.append("UPDATE next SET ")
keys = col_dict.keys()
for i in range(0,len(keys)-1):
self.append(keys[i]+"="+col_dict[keys[i]]+",")
self.append(keys[len(keys)-1]+"="+col_dict[keys[len(keys)-1]])
self.append("FROM ")
for i in range(0,len(from_lst)-1):
self.append(from_lst[i]+",")
self.append(from_lst[len(from_lst)-1])
self.append("WHERE ")
for i in range(0,len(from_lst)-1):
self.append("next.id="+from_lst[i]+".id and ")
self.append("next.id="+from_lst[len(from_lst)-1]+".id")
if(pred != ""):
self.append("and "+pred)
self.append(";")
self.sql = self.sb
| 30.28125 | 97 | 0.624871 |
acefd9d3eeb9bedda04a488b06bc7271ecb3f8c0 | 541 | py | Python | apps/tasks/models.py | dayvidemerson/django-rest-example | 85eabb1e154cfd8ebc0019080b37cd3f1302c206 | [
"MIT"
] | null | null | null | apps/tasks/models.py | dayvidemerson/django-rest-example | 85eabb1e154cfd8ebc0019080b37cd3f1302c206 | [
"MIT"
] | null | null | null | apps/tasks/models.py | dayvidemerson/django-rest-example | 85eabb1e154cfd8ebc0019080b37cd3f1302c206 | [
"MIT"
] | null | null | null | from django.db import models
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Task(BaseModel):
date = models.DateField('data')
name = models.CharField('nome', max_length=255)
description = models.TextField('descrição')
class Meta:
verbose_name = 'tarefa'
verbose_name_plural = 'tarefas'
ordering = ['-date']
def __str__(self):
return self.name
| 22.541667 | 56 | 0.667283 |
acefda9ddb5e5ec850469971e12aefda8e8c944b | 11,384 | py | Python | nova/virt/netutils.py | jeffrey4l/nova | 35375133398d862a61334783c1e7a90b95f34cdb | [
"Apache-2.0"
] | null | null | null | nova/virt/netutils.py | jeffrey4l/nova | 35375133398d862a61334783c1e7a90b95f34cdb | [
"Apache-2.0"
] | 1 | 2019-01-02T01:30:35.000Z | 2019-01-02T01:38:02.000Z | nova/virt/netutils.py | jeffrey4l/nova | 35375133398d862a61334783c1e7a90b95f34cdb | [
"Apache-2.0"
] | null | null | null | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright 2013 IBM Corp.
#
# 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.
"""Network-related utilities for supporting libvirt connection code."""
import os
import jinja2
import netaddr
from oslo_config import cfg
from nova.network import model
from nova import paths
CONF = cfg.CONF
netutils_opts = [
cfg.StrOpt('injected_network_template',
default=paths.basedir_def('nova/virt/interfaces.template'),
help='Template file for injected network'),
]
CONF.register_opts(netutils_opts)
CONF.import_opt('use_ipv6', 'nova.netconf')
def get_net_and_mask(cidr):
net = netaddr.IPNetwork(cidr)
return str(net.ip), str(net.netmask)
def get_net_and_prefixlen(cidr):
net = netaddr.IPNetwork(cidr)
return str(net.ip), str(net._prefixlen)
def get_ip_version(cidr):
net = netaddr.IPNetwork(cidr)
return int(net.version)
def _get_first_network(network, version):
# Using a generator expression with a next() call for the first element
# of a list since we don't want to evaluate the whole list as we can
# have a lot of subnets
try:
return next(i for i in network['subnets']
if i['version'] == version)
except StopIteration:
pass
def get_injected_network_template(network_info, use_ipv6=None, template=None,
libvirt_virt_type=None):
"""Returns a rendered network template for the given network_info.
:param network_info:
:py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
:param use_ipv6: If False, do not return IPv6 template information
even if an IPv6 subnet is present in network_info.
:param template: Path to the interfaces template file.
:param libvirt_virt_type: The Libvirt `virt_type`, will be `None` for
other hypervisors..
"""
if use_ipv6 is None:
use_ipv6 = CONF.use_ipv6
if not template:
template = CONF.injected_network_template
if not (network_info and template):
return
nets = []
ifc_num = -1
ipv6_is_available = False
for vif in network_info:
if not vif['network'] or not vif['network']['subnets']:
continue
network = vif['network']
# NOTE(bnemec): The template only supports a single subnet per
# interface and I'm not sure how/if that can be fixed, so this
# code only takes the first subnet of the appropriate type.
subnet_v4 = _get_first_network(network, 4)
subnet_v6 = _get_first_network(network, 6)
ifc_num += 1
if not network.get_meta('injected'):
continue
hwaddress = vif.get('address')
address = None
netmask = None
gateway = ''
broadcast = None
dns = None
routes = []
if subnet_v4:
if subnet_v4.get_meta('dhcp_server') is not None:
continue
if subnet_v4['ips']:
ip = subnet_v4['ips'][0]
address = ip['address']
netmask = model.get_netmask(ip, subnet_v4)
if subnet_v4['gateway']:
gateway = subnet_v4['gateway']['address']
broadcast = str(subnet_v4.as_netaddr().broadcast)
dns = ' '.join([i['address'] for i in subnet_v4['dns']])
for route_ref in subnet_v4['routes']:
(net, mask) = get_net_and_mask(route_ref['cidr'])
route = {'gateway': str(route_ref['gateway']['address']),
'cidr': str(route_ref['cidr']),
'network': net,
'netmask': mask}
routes.append(route)
address_v6 = None
gateway_v6 = ''
netmask_v6 = None
dns_v6 = None
have_ipv6 = (use_ipv6 and subnet_v6)
if have_ipv6:
if subnet_v6.get_meta('dhcp_server') is not None:
continue
if subnet_v6['ips']:
ipv6_is_available = True
ip_v6 = subnet_v6['ips'][0]
address_v6 = ip_v6['address']
netmask_v6 = model.get_netmask(ip_v6, subnet_v6)
if subnet_v6['gateway']:
gateway_v6 = subnet_v6['gateway']['address']
dns_v6 = ' '.join([i['address'] for i in subnet_v6['dns']])
net_info = {'name': 'eth%d' % ifc_num,
'hwaddress': hwaddress,
'address': address,
'netmask': netmask,
'gateway': gateway,
'broadcast': broadcast,
'dns': dns,
'routes': routes,
'address_v6': address_v6,
'gateway_v6': gateway_v6,
'netmask_v6': netmask_v6,
'dns_v6': dns_v6,
}
nets.append(net_info)
if not nets:
return
tmpl_path, tmpl_file = os.path.split(template)
env = jinja2.Environment(loader=jinja2.FileSystemLoader(tmpl_path),
trim_blocks=True)
template = env.get_template(tmpl_file)
return template.render({'interfaces': nets,
'use_ipv6': ipv6_is_available,
'libvirt_virt_type': libvirt_virt_type})
def get_network_metadata(network_info, use_ipv6=None):
"""Gets a more complete representation of the instance network information.
This data is exposed as network_data.json in the metadata service and
the config drive.
:param network_info: `nova.network.models.NetworkInfo` object describing
the network metadata.
:param use_ipv6: If False, do not return IPv6 template information
even if an IPv6 subnet is present in network_info. Defaults to
nova.netconf.use_ipv6.
"""
if not network_info:
return
if use_ipv6 is None:
use_ipv6 = CONF.use_ipv6
# IPv4 or IPv6 networks
nets = []
# VIFs, physical NICs, or VLANs. Physical NICs will have type 'phy'.
links = []
# Non-network bound services, such as DNS
services = []
ifc_num = -1
net_num = -1
for vif in network_info:
if not vif.get('network') or not vif['network'].get('subnets'):
continue
network = vif['network']
# NOTE(JoshNang) currently, only supports the first IPv4 and first
# IPv6 subnet on network, a limitation that also exists in the
# network template.
subnet_v4 = _get_first_network(network, 4)
subnet_v6 = _get_first_network(network, 6)
ifc_num += 1
link = None
# Get the VIF or physical NIC data
if subnet_v4 or subnet_v6:
link = _get_eth_link(vif, ifc_num)
links.append(link)
# Add IPv4 and IPv6 networks if they exist
if subnet_v4.get('ips'):
net_num += 1
nets.append(_get_nets(vif, subnet_v4, 4, net_num, link['id']))
services += [dns for dns in _get_dns_services(subnet_v4)
if dns not in services]
if (use_ipv6 and subnet_v6) and subnet_v6.get('ips'):
net_num += 1
nets.append(_get_nets(vif, subnet_v6, 6, net_num, link['id']))
services += [dns for dns in _get_dns_services(subnet_v6)
if dns not in services]
return {
"links": links,
"networks": nets,
"services": services
}
def _get_eth_link(vif, ifc_num):
"""Get a VIF or physical NIC representation.
:param vif: Neutron VIF
:param ifc_num: Interface index for generating name if the VIF's
'devname' isn't defined.
:return:
"""
link_id = vif.get('devname')
if not link_id:
link_id = 'interface%d' % ifc_num
# Use 'phy' for physical links. Ethernet can be confusing
if vif.get('type') == 'ethernet':
nic_type = 'phy'
else:
nic_type = vif.get('type')
link = {
'id': link_id,
'vif_id': vif['id'],
'type': nic_type,
'mtu': vif['network'].get('mtu'),
'ethernet_mac_address': vif.get('address'),
}
return link
def _get_nets(vif, subnet, version, net_num, link_id):
"""Get networks for the given VIF and subnet
:param vif: Neutron VIF
:param subnet: Neutron subnet
:param version: IP version as an int, either '4' or '6'
:param net_num: Network index for generating name of each network
:param link_id: Arbitrary identifier for the link the networks are
attached to
"""
if subnet.get_meta('dhcp_server') is not None:
net_info = {
'id': 'network%d' % net_num,
'type': 'ipv%d_dhcp' % version,
'link': link_id,
'network_id': vif['network']['id']
}
return net_info
ip = subnet['ips'][0]
address = ip['address']
if version == 4:
netmask = model.get_netmask(ip, subnet)
elif version == 6:
netmask = str(subnet.as_netaddr().netmask)
net_info = {
'id': 'network%d' % net_num,
'type': 'ipv%d' % version,
'link': link_id,
'ip_address': address,
'netmask': netmask,
'routes': _get_default_route(version, subnet),
'network_id': vif['network']['id']
}
# Add any additional routes beyond the default route
for route in subnet['routes']:
route_addr = netaddr.IPNetwork(route['cidr'])
new_route = {
'network': str(route_addr.network),
'netmask': str(route_addr.netmask),
'gateway': route['gateway']['address']
}
net_info['routes'].append(new_route)
return net_info
def _get_default_route(version, subnet):
"""Get a default route for a network
:param version: IP version as an int, either '4' or '6'
:param subnet: Neutron subnet
"""
if subnet.get('gateway') and subnet['gateway'].get('address'):
gateway = subnet['gateway']['address']
else:
return []
if version == 4:
return [{
'network': '0.0.0.0',
'netmask': '0.0.0.0',
'gateway': gateway
}]
elif version == 6:
return [{
'network': '::',
'netmask': '::',
'gateway': gateway
}]
def _get_dns_services(subnet):
"""Get the DNS servers for the subnet."""
services = []
if not subnet.get('dns'):
return services
return [{'type': 'dns', 'address': ip.get('address')}
for ip in subnet['dns']]
| 31.977528 | 79 | 0.586701 |
acefdac91d04c343545c7183b3464a7f0aaaa890 | 74,889 | py | Python | clients/oathkeeper/python/ory_oathkeeper_client/model_utils.py | simoneromano96/sdk | a6113d0daefbbb803790297e4b242d4c7cbbcb22 | [
"Apache-2.0"
] | null | null | null | clients/oathkeeper/python/ory_oathkeeper_client/model_utils.py | simoneromano96/sdk | a6113d0daefbbb803790297e4b242d4c7cbbcb22 | [
"Apache-2.0"
] | null | null | null | clients/oathkeeper/python/ory_oathkeeper_client/model_utils.py | simoneromano96/sdk | a6113d0daefbbb803790297e4b242d4c7cbbcb22 | [
"Apache-2.0"
] | null | null | null | """
ORY Oathkeeper
ORY Oathkeeper is a reverse proxy that checks the HTTP Authorization for validity against a set of rules. This service uses Hydra to validate access tokens and policies. # noqa: E501
The version of the OpenAPI document: v0.38.11-beta.1
Contact: hi@ory.am
Generated by: https://openapi-generator.tech
"""
from datetime import date, datetime # noqa: F401
import inspect
import io
import os
import pprint
import re
import tempfile
from dateutil.parser import parse
from ory_oathkeeper_client.exceptions import (
ApiKeyError,
ApiAttributeError,
ApiTypeError,
ApiValueError,
)
none_type = type(None)
file_type = io.IOBase
class cached_property(object):
# this caches the result of the function call for fn with no inputs
# use this as a decorator on fuction methods that you want converted
# into cached properties
result_key = '_results'
def __init__(self, fn):
self._fn = fn
def __get__(self, instance, cls=None):
if self.result_key in vars(self):
return vars(self)[self.result_key]
else:
result = self._fn()
setattr(self, self.result_key, result)
return result
PRIMITIVE_TYPES = (list, float, int, bool, datetime, date, str, file_type)
def allows_single_value_input(cls):
"""
This function returns True if the input composed schema model or any
descendant model allows a value only input
This is true for cases where oneOf contains items like:
oneOf:
- float
- NumberWithValidation
- StringEnum
- ArrayModel
- null
TODO: lru_cache this
"""
if (
issubclass(cls, ModelSimple) or
cls in PRIMITIVE_TYPES
):
return True
elif issubclass(cls, ModelComposed):
if not cls._composed_schemas['oneOf']:
return False
return any(allows_single_value_input(c) for c in cls._composed_schemas['oneOf'])
return False
def composed_model_input_classes(cls):
"""
This function returns a list of the possible models that can be accepted as
inputs.
TODO: lru_cache this
"""
if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES:
return [cls]
elif issubclass(cls, ModelNormal):
if cls.discriminator is None:
return [cls]
else:
return get_discriminated_classes(cls)
elif issubclass(cls, ModelComposed):
if not cls._composed_schemas['oneOf']:
return []
if cls.discriminator is None:
input_classes = []
for c in cls._composed_schemas['oneOf']:
input_classes.extend(composed_model_input_classes(c))
return input_classes
else:
return get_discriminated_classes(cls)
return []
class OpenApiModel(object):
"""The base class for all OpenAPIModels"""
def set_attribute(self, name, value):
# this is only used to set properties on self
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiAttributeError(
"{0} has no attribute '{1}'".format(
type(self).__name__, name),
path_to_item
)
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._spec_property_naming,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value,
self._configuration
)
self.__dict__['_data_store'][name] = value
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
def __setattr__(self, attr, value):
"""set the value of an attribute using dot notation: `instance.attr = val`"""
self[attr] = value
def __getattr__(self, attr):
"""get the value of an attribute using dot notation: `instance.attr`"""
return self.__getitem__(attr)
def __new__(cls, *args, **kwargs):
# this function uses the discriminator to
# pick a new schema/class to instantiate because a discriminator
# propertyName value was passed in
if len(args) == 1:
arg = args[0]
if arg is None and is_type_nullable(cls):
# The input data is the 'null' value and the type is nullable.
return None
if issubclass(cls, ModelComposed) and allows_single_value_input(cls):
model_kwargs = {}
oneof_instance = get_oneof_instance(cls, model_kwargs, kwargs, model_arg=arg)
return oneof_instance
visited_composed_classes = kwargs.get('_visited_composed_classes', ())
if (
cls.discriminator is None or
cls in visited_composed_classes
):
# Use case 1: this openapi schema (cls) does not have a discriminator
# Use case 2: we have already visited this class before and are sure that we
# want to instantiate it this time. We have visited this class deserializing
# a payload with a discriminator. During that process we traveled through
# this class but did not make an instance of it. Now we are making an
# instance of a composed class which contains cls in it, so this time make an instance of cls.
#
# Here's an example of use case 2: If Animal has a discriminator
# petType and we pass in "Dog", and the class Dog
# allOf includes Animal, we move through Animal
# once using the discriminator, and pick Dog.
# Then in the composed schema dog Dog, we will make an instance of the
# Animal class (because Dal has allOf: Animal) but this time we won't travel
# through Animal's discriminator because we passed in
# _visited_composed_classes = (Animal,)
return super(OpenApiModel, cls).__new__(cls)
# Get the name and value of the discriminator property.
# The discriminator name is obtained from the discriminator meta-data
# and the discriminator value is obtained from the input data.
discr_propertyname_py = list(cls.discriminator.keys())[0]
discr_propertyname_js = cls.attribute_map[discr_propertyname_py]
if discr_propertyname_js in kwargs:
discr_value = kwargs[discr_propertyname_js]
elif discr_propertyname_py in kwargs:
discr_value = kwargs[discr_propertyname_py]
else:
# The input data does not contain the discriminator property.
path_to_item = kwargs.get('_path_to_item', ())
raise ApiValueError(
"Cannot deserialize input data due to missing discriminator. "
"The discriminator property '%s' is missing at path: %s" %
(discr_propertyname_js, path_to_item)
)
# Implementation note: the last argument to get_discriminator_class
# is a list of visited classes. get_discriminator_class may recursively
# call itself and update the list of visited classes, and the initial
# value must be an empty list. Hence not using 'visited_composed_classes'
new_cls = get_discriminator_class(
cls, discr_propertyname_py, discr_value, [])
if new_cls is None:
path_to_item = kwargs.get('_path_to_item', ())
disc_prop_value = kwargs.get(
discr_propertyname_js, kwargs.get(discr_propertyname_py))
raise ApiValueError(
"Cannot deserialize input data due to invalid discriminator "
"value. The OpenAPI document has no mapping for discriminator "
"property '%s'='%s' at path: %s" %
(discr_propertyname_js, disc_prop_value, path_to_item)
)
if new_cls in visited_composed_classes:
# if we are making an instance of a composed schema Descendent
# which allOf includes Ancestor, then Ancestor contains
# a discriminator that includes Descendent.
# So if we make an instance of Descendent, we have to make an
# instance of Ancestor to hold the allOf properties.
# This code detects that use case and makes the instance of Ancestor
# For example:
# When making an instance of Dog, _visited_composed_classes = (Dog,)
# then we make an instance of Animal to include in dog._composed_instances
# so when we are here, cls is Animal
# cls.discriminator != None
# cls not in _visited_composed_classes
# new_cls = Dog
# but we know we know that we already have Dog
# because it is in visited_composed_classes
# so make Animal here
return super(OpenApiModel, cls).__new__(cls)
# Build a list containing all oneOf and anyOf descendants.
oneof_anyof_classes = None
if cls._composed_schemas is not None:
oneof_anyof_classes = (
cls._composed_schemas.get('oneOf', ()) +
cls._composed_schemas.get('anyOf', ()))
oneof_anyof_child = new_cls in oneof_anyof_classes
kwargs['_visited_composed_classes'] = visited_composed_classes + (cls,)
if cls._composed_schemas.get('allOf') and oneof_anyof_child:
# Validate that we can make self because when we make the
# new_cls it will not include the allOf validations in self
self_inst = super(OpenApiModel, cls).__new__(cls)
self_inst.__init__(*args, **kwargs)
new_inst = new_cls.__new__(new_cls, *args, **kwargs)
new_inst.__init__(*args, **kwargs)
return new_inst
class ModelSimple(OpenApiModel):
"""the parent class of models whose type != object in their
swagger/openapi"""
def __setitem__(self, name, value):
"""set the value of an attribute using square-bracket notation: `instance[attr] = val`"""
if name in self.required_properties:
self.__dict__[name] = value
return
self.set_attribute(name, value)
def get(self, name, default=None):
"""returns the value of an attribute or some default value if the attribute was not set"""
if name in self.required_properties:
return self.__dict__[name]
return self.__dict__['_data_store'].get(name, default)
def __getitem__(self, name):
"""get the value of an attribute using square-bracket notation: `instance[attr]`"""
if name in self:
return self.get(name)
raise ApiAttributeError(
"{0} has no attribute '{1}'".format(
type(self).__name__, name),
[e for e in [self._path_to_item, name] if e]
)
def __contains__(self, name):
"""used by `in` operator to check if an attrbute value was set in an instance: `'attr' in instance`"""
if name in self.required_properties:
return name in self.__dict__
return name in self.__dict__['_data_store']
def to_str(self):
"""Returns the string representation of the model"""
return str(self.value)
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, self.__class__):
return False
this_val = self._data_store['value']
that_val = other._data_store['value']
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
return vals_equal
class ModelNormal(OpenApiModel):
"""the parent class of models whose type == object in their
swagger/openapi"""
def __setitem__(self, name, value):
"""set the value of an attribute using square-bracket notation: `instance[attr] = val`"""
if name in self.required_properties:
self.__dict__[name] = value
return
self.set_attribute(name, value)
def get(self, name, default=None):
"""returns the value of an attribute or some default value if the attribute was not set"""
if name in self.required_properties:
return self.__dict__[name]
return self.__dict__['_data_store'].get(name, default)
def __getitem__(self, name):
"""get the value of an attribute using square-bracket notation: `instance[attr]`"""
if name in self:
return self.get(name)
raise ApiAttributeError(
"{0} has no attribute '{1}'".format(
type(self).__name__, name),
[e for e in [self._path_to_item, name] if e]
)
def __contains__(self, name):
"""used by `in` operator to check if an attrbute value was set in an instance: `'attr' in instance`"""
if name in self.required_properties:
return name in self.__dict__
return name in self.__dict__['_data_store']
def to_dict(self):
"""Returns the model properties as a dict"""
return model_to_dict(self, serialize=False)
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, self.__class__):
return False
if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in self._data_store.items():
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if not vals_equal:
return False
return True
class ModelComposed(OpenApiModel):
"""the parent class of models whose type == object in their
swagger/openapi and have oneOf/allOf/anyOf
When one sets a property we use var_name_to_model_instances to store the value in
the correct class instances + run any type checking + validation code.
When one gets a property we use var_name_to_model_instances to get the value
from the correct class instances.
This allows multiple composed schemas to contain the same property with additive
constraints on the value.
_composed_schemas (dict) stores the anyOf/allOf/oneOf classes
key (str): allOf/oneOf/anyOf
value (list): the classes in the XOf definition.
Note: none_type can be included when the openapi document version >= 3.1.0
_composed_instances (list): stores a list of instances of the composed schemas
defined in _composed_schemas. When properties are accessed in the self instance,
they are returned from the self._data_store or the data stores in the instances
in self._composed_schemas
_var_name_to_model_instances (dict): maps between a variable name on self and
the composed instances (self included) which contain that data
key (str): property name
value (list): list of class instances, self or instances in _composed_instances
which contain the value that the key is referring to.
"""
def __setitem__(self, name, value):
"""set the value of an attribute using square-bracket notation: `instance[attr] = val`"""
if name in self.required_properties:
self.__dict__[name] = value
return
# set the attribute on the correct instance
model_instances = self._var_name_to_model_instances.get(
name, self._additional_properties_model_instances)
if model_instances:
for model_instance in model_instances:
if model_instance == self:
self.set_attribute(name, value)
else:
setattr(model_instance, name, value)
if name not in self._var_name_to_model_instances:
# we assigned an additional property
self.__dict__['_var_name_to_model_instances'][name] = (
model_instance
)
return None
raise ApiAttributeError(
"{0} has no attribute '{1}'".format(
type(self).__name__, name),
[e for e in [self._path_to_item, name] if e]
)
__unset_attribute_value__ = object()
def get(self, name, default=None):
"""returns the value of an attribute or some default value if the attribute was not set"""
if name in self.required_properties:
return self.__dict__[name]
# get the attribute from the correct instance
model_instances = self._var_name_to_model_instances.get(
name, self._additional_properties_model_instances)
values = []
# A composed model stores child (oneof/anyOf/allOf) models under
# self._var_name_to_model_instances. A named property can exist in
# multiple child models. If the property is present in more than one
# child model, the value must be the same across all the child models.
if model_instances:
for model_instance in model_instances:
if name in model_instance._data_store:
v = model_instance._data_store[name]
if v not in values:
values.append(v)
len_values = len(values)
if len_values == 0:
return default
elif len_values == 1:
return values[0]
elif len_values > 1:
raise ApiValueError(
"Values stored for property {0} in {1} differ when looking "
"at self and self's composed instances. All values must be "
"the same".format(name, type(self).__name__),
[e for e in [self._path_to_item, name] if e]
)
def __getitem__(self, name):
"""get the value of an attribute using square-bracket notation: `instance[attr]`"""
value = self.get(name, self.__unset_attribute_value__)
if value is self.__unset_attribute_value__:
raise ApiAttributeError(
"{0} has no attribute '{1}'".format(
type(self).__name__, name),
[e for e in [self._path_to_item, name] if e]
)
return value
def __contains__(self, name):
"""used by `in` operator to check if an attrbute value was set in an instance: `'attr' in instance`"""
if name in self.required_properties:
return name in self.__dict__
model_instances = self._var_name_to_model_instances.get(
name, self._additional_properties_model_instances)
if model_instances:
for model_instance in model_instances:
if name in model_instance._data_store:
return True
return False
def to_dict(self):
"""Returns the model properties as a dict"""
return model_to_dict(self, serialize=False)
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, self.__class__):
return False
if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in self._data_store.items():
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if not vals_equal:
return False
return True
COERCION_INDEX_BY_TYPE = {
ModelComposed: 0,
ModelNormal: 1,
ModelSimple: 2,
none_type: 3, # The type of 'None'.
list: 4,
dict: 5,
float: 6,
int: 7,
bool: 8,
datetime: 9,
date: 10,
str: 11,
file_type: 12, # 'file_type' is an alias for the built-in 'file' or 'io.IOBase' type.
}
# these are used to limit what type conversions we try to do
# when we have a valid type already and we want to try converting
# to another type
UPCONVERSION_TYPE_PAIRS = (
(str, datetime),
(str, date),
(int, float), # A float may be serialized as an integer, e.g. '3' is a valid serialized float.
(list, ModelComposed),
(dict, ModelComposed),
(str, ModelComposed),
(int, ModelComposed),
(float, ModelComposed),
(list, ModelComposed),
(list, ModelNormal),
(dict, ModelNormal),
(str, ModelSimple),
(int, ModelSimple),
(float, ModelSimple),
(list, ModelSimple),
)
COERCIBLE_TYPE_PAIRS = {
False: ( # client instantiation of a model with client data
# (dict, ModelComposed),
# (list, ModelComposed),
# (dict, ModelNormal),
# (list, ModelNormal),
# (str, ModelSimple),
# (int, ModelSimple),
# (float, ModelSimple),
# (list, ModelSimple),
# (str, int),
# (str, float),
# (str, datetime),
# (str, date),
# (int, str),
# (float, str),
),
True: ( # server -> client data
(dict, ModelComposed),
(list, ModelComposed),
(dict, ModelNormal),
(list, ModelNormal),
(str, ModelSimple),
(int, ModelSimple),
(float, ModelSimple),
(list, ModelSimple),
# (str, int),
# (str, float),
(str, datetime),
(str, date),
# (int, str),
# (float, str),
(str, file_type)
),
}
def get_simple_class(input_value):
"""Returns an input_value's simple class that we will use for type checking
Python2:
float and int will return int, where int is the python3 int backport
str and unicode will return str, where str is the python3 str backport
Note: float and int ARE both instances of int backport
Note: str_py2 and unicode_py2 are NOT both instances of str backport
Args:
input_value (class/class_instance): the item for which we will return
the simple class
"""
if isinstance(input_value, type):
# input_value is a class
return input_value
elif isinstance(input_value, tuple):
return tuple
elif isinstance(input_value, list):
return list
elif isinstance(input_value, dict):
return dict
elif isinstance(input_value, none_type):
return none_type
elif isinstance(input_value, file_type):
return file_type
elif isinstance(input_value, bool):
# this must be higher than the int check because
# isinstance(True, int) == True
return bool
elif isinstance(input_value, int):
return int
elif isinstance(input_value, datetime):
# this must be higher than the date check because
# isinstance(datetime_instance, date) == True
return datetime
elif isinstance(input_value, date):
return date
elif isinstance(input_value, str):
return str
return type(input_value)
def check_allowed_values(allowed_values, input_variable_path, input_values):
"""Raises an exception if the input_values are not allowed
Args:
allowed_values (dict): the allowed_values dict
input_variable_path (tuple): the path to the input variable
input_values (list/str/int/float/date/datetime): the values that we
are checking to see if they are in allowed_values
"""
these_allowed_values = list(allowed_values[input_variable_path].values())
if (isinstance(input_values, list)
and not set(input_values).issubset(
set(these_allowed_values))):
invalid_values = ", ".join(
map(str, set(input_values) - set(these_allowed_values))),
raise ApiValueError(
"Invalid values for `%s` [%s], must be a subset of [%s]" %
(
input_variable_path[0],
invalid_values,
", ".join(map(str, these_allowed_values))
)
)
elif (isinstance(input_values, dict)
and not set(
input_values.keys()).issubset(set(these_allowed_values))):
invalid_values = ", ".join(
map(str, set(input_values.keys()) - set(these_allowed_values)))
raise ApiValueError(
"Invalid keys in `%s` [%s], must be a subset of [%s]" %
(
input_variable_path[0],
invalid_values,
", ".join(map(str, these_allowed_values))
)
)
elif (not isinstance(input_values, (list, dict))
and input_values not in these_allowed_values):
raise ApiValueError(
"Invalid value for `%s` (%s), must be one of %s" %
(
input_variable_path[0],
input_values,
these_allowed_values
)
)
def is_json_validation_enabled(schema_keyword, configuration=None):
"""Returns true if JSON schema validation is enabled for the specified
validation keyword. This can be used to skip JSON schema structural validation
as requested in the configuration.
Args:
schema_keyword (string): the name of a JSON schema validation keyword.
configuration (Configuration): the configuration class.
"""
return (configuration is None or
not hasattr(configuration, '_disabled_client_side_validations') or
schema_keyword not in configuration._disabled_client_side_validations)
def check_validations(
validations, input_variable_path, input_values,
configuration=None):
"""Raises an exception if the input_values are invalid
Args:
validations (dict): the validation dictionary.
input_variable_path (tuple): the path to the input variable.
input_values (list/str/int/float/date/datetime): the values that we
are checking.
configuration (Configuration): the configuration class.
"""
if input_values is None:
return
current_validations = validations[input_variable_path]
if (is_json_validation_enabled('multipleOf', configuration) and
'multiple_of' in current_validations and
isinstance(input_values, (int, float)) and
not (float(input_values) / current_validations['multiple_of']).is_integer()):
# Note 'multipleOf' will be as good as the floating point arithmetic.
raise ApiValueError(
"Invalid value for `%s`, value must be a multiple of "
"`%s`" % (
input_variable_path[0],
current_validations['multiple_of']
)
)
if (is_json_validation_enabled('maxLength', configuration) and
'max_length' in current_validations and
len(input_values) > current_validations['max_length']):
raise ApiValueError(
"Invalid value for `%s`, length must be less than or equal to "
"`%s`" % (
input_variable_path[0],
current_validations['max_length']
)
)
if (is_json_validation_enabled('minLength', configuration) and
'min_length' in current_validations and
len(input_values) < current_validations['min_length']):
raise ApiValueError(
"Invalid value for `%s`, length must be greater than or equal to "
"`%s`" % (
input_variable_path[0],
current_validations['min_length']
)
)
if (is_json_validation_enabled('maxItems', configuration) and
'max_items' in current_validations and
len(input_values) > current_validations['max_items']):
raise ApiValueError(
"Invalid value for `%s`, number of items must be less than or "
"equal to `%s`" % (
input_variable_path[0],
current_validations['max_items']
)
)
if (is_json_validation_enabled('minItems', configuration) and
'min_items' in current_validations and
len(input_values) < current_validations['min_items']):
raise ValueError(
"Invalid value for `%s`, number of items must be greater than or "
"equal to `%s`" % (
input_variable_path[0],
current_validations['min_items']
)
)
items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum',
'inclusive_minimum')
if (any(item in current_validations for item in items)):
if isinstance(input_values, list):
max_val = max(input_values)
min_val = min(input_values)
elif isinstance(input_values, dict):
max_val = max(input_values.values())
min_val = min(input_values.values())
else:
max_val = input_values
min_val = input_values
if (is_json_validation_enabled('exclusiveMaximum', configuration) and
'exclusive_maximum' in current_validations and
max_val >= current_validations['exclusive_maximum']):
raise ApiValueError(
"Invalid value for `%s`, must be a value less than `%s`" % (
input_variable_path[0],
current_validations['exclusive_maximum']
)
)
if (is_json_validation_enabled('maximum', configuration) and
'inclusive_maximum' in current_validations and
max_val > current_validations['inclusive_maximum']):
raise ApiValueError(
"Invalid value for `%s`, must be a value less than or equal to "
"`%s`" % (
input_variable_path[0],
current_validations['inclusive_maximum']
)
)
if (is_json_validation_enabled('exclusiveMinimum', configuration) and
'exclusive_minimum' in current_validations and
min_val <= current_validations['exclusive_minimum']):
raise ApiValueError(
"Invalid value for `%s`, must be a value greater than `%s`" %
(
input_variable_path[0],
current_validations['exclusive_maximum']
)
)
if (is_json_validation_enabled('minimum', configuration) and
'inclusive_minimum' in current_validations and
min_val < current_validations['inclusive_minimum']):
raise ApiValueError(
"Invalid value for `%s`, must be a value greater than or equal "
"to `%s`" % (
input_variable_path[0],
current_validations['inclusive_minimum']
)
)
flags = current_validations.get('regex', {}).get('flags', 0)
if (is_json_validation_enabled('pattern', configuration) and
'regex' in current_validations and
not re.search(current_validations['regex']['pattern'],
input_values, flags=flags)):
err_msg = r"Invalid value for `%s`, must match regular expression `%s`" % (
input_variable_path[0],
current_validations['regex']['pattern']
)
if flags != 0:
# Don't print the regex flags if the flags are not
# specified in the OAS document.
err_msg = r"%s with flags=`%s`" % (err_msg, flags)
raise ApiValueError(err_msg)
def order_response_types(required_types):
"""Returns the required types sorted in coercion order
Args:
required_types (list/tuple): collection of classes or instance of
list or dict with class information inside it.
Returns:
(list): coercion order sorted collection of classes or instance
of list or dict with class information inside it.
"""
def index_getter(class_or_instance):
if isinstance(class_or_instance, list):
return COERCION_INDEX_BY_TYPE[list]
elif isinstance(class_or_instance, dict):
return COERCION_INDEX_BY_TYPE[dict]
elif (inspect.isclass(class_or_instance)
and issubclass(class_or_instance, ModelComposed)):
return COERCION_INDEX_BY_TYPE[ModelComposed]
elif (inspect.isclass(class_or_instance)
and issubclass(class_or_instance, ModelNormal)):
return COERCION_INDEX_BY_TYPE[ModelNormal]
elif (inspect.isclass(class_or_instance)
and issubclass(class_or_instance, ModelSimple)):
return COERCION_INDEX_BY_TYPE[ModelSimple]
elif class_or_instance in COERCION_INDEX_BY_TYPE:
return COERCION_INDEX_BY_TYPE[class_or_instance]
raise ApiValueError("Unsupported type: %s" % class_or_instance)
sorted_types = sorted(
required_types,
key=lambda class_or_instance: index_getter(class_or_instance)
)
return sorted_types
def remove_uncoercible(required_types_classes, current_item, spec_property_naming,
must_convert=True):
"""Only keeps the type conversions that are possible
Args:
required_types_classes (tuple): tuple of classes that are required
these should be ordered by COERCION_INDEX_BY_TYPE
spec_property_naming (bool): True if the variable names in the input
data are serialized names as specified in the OpenAPI document.
False if the variables names in the input data are python
variable names in PEP-8 snake case.
current_item (any): the current item (input data) to be converted
Keyword Args:
must_convert (bool): if True the item to convert is of the wrong
type and we want a big list of coercibles
if False, we want a limited list of coercibles
Returns:
(list): the remaining coercible required types, classes only
"""
current_type_simple = get_simple_class(current_item)
results_classes = []
for required_type_class in required_types_classes:
# convert our models to OpenApiModel
required_type_class_simplified = required_type_class
if isinstance(required_type_class_simplified, type):
if issubclass(required_type_class_simplified, ModelComposed):
required_type_class_simplified = ModelComposed
elif issubclass(required_type_class_simplified, ModelNormal):
required_type_class_simplified = ModelNormal
elif issubclass(required_type_class_simplified, ModelSimple):
required_type_class_simplified = ModelSimple
if required_type_class_simplified == current_type_simple:
# don't consider converting to one's own class
continue
class_pair = (current_type_simple, required_type_class_simplified)
if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[spec_property_naming]:
results_classes.append(required_type_class)
elif class_pair in UPCONVERSION_TYPE_PAIRS:
results_classes.append(required_type_class)
return results_classes
def get_discriminated_classes(cls):
"""
Returns all the classes that a discriminator converts to
TODO: lru_cache this
"""
possible_classes = []
key = list(cls.discriminator.keys())[0]
if is_type_nullable(cls):
possible_classes.append(cls)
for discr_cls in cls.discriminator[key].values():
if hasattr(discr_cls, 'discriminator') and discr_cls.discriminator is not None:
possible_classes.extend(get_discriminated_classes(discr_cls))
else:
possible_classes.append(discr_cls)
return possible_classes
def get_possible_classes(cls, from_server_context):
# TODO: lru_cache this
possible_classes = [cls]
if from_server_context:
return possible_classes
if hasattr(cls, 'discriminator') and cls.discriminator is not None:
possible_classes = []
possible_classes.extend(get_discriminated_classes(cls))
elif issubclass(cls, ModelComposed):
possible_classes.extend(composed_model_input_classes(cls))
return possible_classes
def get_required_type_classes(required_types_mixed, spec_property_naming):
"""Converts the tuple required_types into a tuple and a dict described
below
Args:
required_types_mixed (tuple/list): will contain either classes or
instance of list or dict
spec_property_naming (bool): if True these values came from the
server, and we use the data types in our endpoints.
If False, we are client side and we need to include
oneOf and discriminator classes inside the data types in our endpoints
Returns:
(valid_classes, dict_valid_class_to_child_types_mixed):
valid_classes (tuple): the valid classes that the current item
should be
dict_valid_class_to_child_types_mixed (dict):
valid_class (class): this is the key
child_types_mixed (list/dict/tuple): describes the valid child
types
"""
valid_classes = []
child_req_types_by_current_type = {}
for required_type in required_types_mixed:
if isinstance(required_type, list):
valid_classes.append(list)
child_req_types_by_current_type[list] = required_type
elif isinstance(required_type, tuple):
valid_classes.append(tuple)
child_req_types_by_current_type[tuple] = required_type
elif isinstance(required_type, dict):
valid_classes.append(dict)
child_req_types_by_current_type[dict] = required_type[str]
else:
valid_classes.extend(get_possible_classes(required_type, spec_property_naming))
return tuple(valid_classes), child_req_types_by_current_type
def change_keys_js_to_python(input_dict, model_class):
"""
Converts from javascript_key keys in the input_dict to python_keys in
the output dict using the mapping in model_class.
If the input_dict contains a key which does not declared in the model_class,
the key is added to the output dict as is. The assumption is the model_class
may have undeclared properties (additionalProperties attribute in the OAS
document).
"""
if getattr(model_class, 'attribute_map', None) is None:
return input_dict
output_dict = {}
reversed_attr_map = {value: key for key, value in
model_class.attribute_map.items()}
for javascript_key, value in input_dict.items():
python_key = reversed_attr_map.get(javascript_key)
if python_key is None:
# if the key is unknown, it is in error or it is an
# additionalProperties variable
python_key = javascript_key
output_dict[python_key] = value
return output_dict
def get_type_error(var_value, path_to_item, valid_classes, key_type=False):
error_msg = type_error_message(
var_name=path_to_item[-1],
var_value=var_value,
valid_classes=valid_classes,
key_type=key_type
)
return ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=valid_classes,
key_type=key_type
)
def deserialize_primitive(data, klass, path_to_item):
"""Deserializes string to primitive type.
:param data: str/int/float
:param klass: str/class the class to convert to
:return: int, float, str, bool, date, datetime
"""
additional_message = ""
try:
if klass in {datetime, date}:
additional_message = (
"If you need your parameter to have a fallback "
"string value, please set its type as `type: {}` in your "
"spec. That allows the value to be any type. "
)
if klass == datetime:
if len(data) < 8:
raise ValueError("This is not a datetime")
# The string should be in iso8601 datetime format.
parsed_datetime = parse(data)
date_only = (
parsed_datetime.hour == 0 and
parsed_datetime.minute == 0 and
parsed_datetime.second == 0 and
parsed_datetime.tzinfo is None and
8 <= len(data) <= 10
)
if date_only:
raise ValueError("This is a date, not a datetime")
return parsed_datetime
elif klass == date:
if len(data) < 8:
raise ValueError("This is not a date")
return parse(data).date()
else:
converted_value = klass(data)
if isinstance(data, str) and klass == float:
if str(converted_value) != data:
# '7' -> 7.0 -> '7.0' != '7'
raise ValueError('This is not a float')
return converted_value
except (OverflowError, ValueError) as ex:
# parse can raise OverflowError
raise ApiValueError(
"{0}Failed to parse {1} as {2}".format(
additional_message, repr(data), klass.__name__
),
path_to_item=path_to_item
) from ex
def get_discriminator_class(model_class,
discr_name,
discr_value, cls_visited):
"""Returns the child class specified by the discriminator.
Args:
model_class (OpenApiModel): the model class.
discr_name (string): the name of the discriminator property.
discr_value (any): the discriminator value.
cls_visited (list): list of model classes that have been visited.
Used to determine the discriminator class without
visiting circular references indefinitely.
Returns:
used_model_class (class/None): the chosen child class that will be used
to deserialize the data, for example dog.Dog.
If a class is not found, None is returned.
"""
if model_class in cls_visited:
# The class has already been visited and no suitable class was found.
return None
cls_visited.append(model_class)
used_model_class = None
if discr_name in model_class.discriminator:
class_name_to_discr_class = model_class.discriminator[discr_name]
used_model_class = class_name_to_discr_class.get(discr_value)
if used_model_class is None:
# We didn't find a discriminated class in class_name_to_discr_class.
# So look in the ancestor or descendant discriminators
# The discriminator mapping may exist in a descendant (anyOf, oneOf)
# or ancestor (allOf).
# Ancestor example: in the GrandparentAnimal -> ParentPet -> ChildCat
# hierarchy, the discriminator mappings may be defined at any level
# in the hierarchy.
# Descendant example: mammal -> whale/zebra/Pig -> BasquePig/DanishPig
# if we try to make BasquePig from mammal, we need to travel through
# the oneOf descendant discriminators to find BasquePig
descendant_classes = model_class._composed_schemas.get('oneOf', ()) + \
model_class._composed_schemas.get('anyOf', ())
ancestor_classes = model_class._composed_schemas.get('allOf', ())
possible_classes = descendant_classes + ancestor_classes
for cls in possible_classes:
# Check if the schema has inherited discriminators.
if hasattr(cls, 'discriminator') and cls.discriminator is not None:
used_model_class = get_discriminator_class(
cls, discr_name, discr_value, cls_visited)
if used_model_class is not None:
return used_model_class
return used_model_class
def deserialize_model(model_data, model_class, path_to_item, check_type,
configuration, spec_property_naming):
"""Deserializes model_data to model instance.
Args:
model_data (int/str/float/bool/none_type/list/dict): data to instantiate the model
model_class (OpenApiModel): the model class
path_to_item (list): path to the model in the received data
check_type (bool): whether to check the data tupe for the values in
the model
configuration (Configuration): the instance to use to convert files
spec_property_naming (bool): True if the variable names in the input
data are serialized names as specified in the OpenAPI document.
False if the variables names in the input data are python
variable names in PEP-8 snake case.
Returns:
model instance
Raise:
ApiTypeError
ApiValueError
ApiKeyError
"""
kw_args = dict(_check_type=check_type,
_path_to_item=path_to_item,
_configuration=configuration,
_spec_property_naming=spec_property_naming)
if issubclass(model_class, ModelSimple):
return model_class(model_data, **kw_args)
elif isinstance(model_data, list):
return model_class(*model_data, **kw_args)
if isinstance(model_data, dict):
kw_args.update(model_data)
return model_class(**kw_args)
elif isinstance(model_data, PRIMITIVE_TYPES):
return model_class(model_data, **kw_args)
def deserialize_file(response_data, configuration, content_disposition=None):
"""Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
Args:
param response_data (str): the file data to write
configuration (Configuration): the instance to use to convert files
Keyword Args:
content_disposition (str): the value of the Content-Disposition
header
Returns:
(file_type): the deserialized file which is open
The user is responsible for closing and reading the file
"""
fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path)
os.close(fd)
os.remove(path)
if content_disposition:
filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
content_disposition).group(1)
path = os.path.join(os.path.dirname(path), filename)
with open(path, "wb") as f:
if isinstance(response_data, str):
# change str to bytes so we can write it
response_data = response_data.encode('utf-8')
f.write(response_data)
f = open(path, "rb")
return f
def attempt_convert_item(input_value, valid_classes, path_to_item,
configuration, spec_property_naming, key_type=False,
must_convert=False, check_type=True):
"""
Args:
input_value (any): the data to convert
valid_classes (any): the classes that are valid
path_to_item (list): the path to the item to convert
configuration (Configuration): the instance to use to convert files
spec_property_naming (bool): True if the variable names in the input
data are serialized names as specified in the OpenAPI document.
False if the variables names in the input data are python
variable names in PEP-8 snake case.
key_type (bool): if True we need to convert a key type (not supported)
must_convert (bool): if True we must convert
check_type (bool): if True we check the type or the returned data in
ModelComposed/ModelNormal/ModelSimple instances
Returns:
instance (any) the fixed item
Raises:
ApiTypeError
ApiValueError
ApiKeyError
"""
valid_classes_ordered = order_response_types(valid_classes)
valid_classes_coercible = remove_uncoercible(
valid_classes_ordered, input_value, spec_property_naming)
if not valid_classes_coercible or key_type:
# we do not handle keytype errors, json will take care
# of this for us
if configuration is None or not configuration.discard_unknown_keys:
raise get_type_error(input_value, path_to_item, valid_classes,
key_type=key_type)
for valid_class in valid_classes_coercible:
try:
if issubclass(valid_class, OpenApiModel):
return deserialize_model(input_value, valid_class,
path_to_item, check_type,
configuration, spec_property_naming)
elif valid_class == file_type:
return deserialize_file(input_value, configuration)
return deserialize_primitive(input_value, valid_class,
path_to_item)
except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc:
if must_convert:
raise conversion_exc
# if we have conversion errors when must_convert == False
# we ignore the exception and move on to the next class
continue
# we were unable to convert, must_convert == False
return input_value
def is_type_nullable(input_type):
"""
Returns true if None is an allowed value for the specified input_type.
A type is nullable if at least one of the following conditions is true:
1. The OAS 'nullable' attribute has been specified,
1. The type is the 'null' type,
1. The type is a anyOf/oneOf composed schema, and a child schema is
the 'null' type.
Args:
input_type (type): the class of the input_value that we are
checking
Returns:
bool
"""
if input_type is none_type:
return True
if issubclass(input_type, OpenApiModel) and input_type._nullable:
return True
if issubclass(input_type, ModelComposed):
# If oneOf/anyOf, check if the 'null' type is one of the allowed types.
for t in input_type._composed_schemas.get('oneOf', ()):
if is_type_nullable(t): return True
for t in input_type._composed_schemas.get('anyOf', ()):
if is_type_nullable(t): return True
return False
def is_valid_type(input_class_simple, valid_classes):
"""
Args:
input_class_simple (class): the class of the input_value that we are
checking
valid_classes (tuple): the valid classes that the current item
should be
Returns:
bool
"""
valid_type = input_class_simple in valid_classes
if not valid_type and (
issubclass(input_class_simple, OpenApiModel) or
input_class_simple is none_type):
for valid_class in valid_classes:
if input_class_simple is none_type and is_type_nullable(valid_class):
# Schema is oneOf/anyOf and the 'null' type is one of the allowed types.
return True
if not (issubclass(valid_class, OpenApiModel) and valid_class.discriminator):
continue
discr_propertyname_py = list(valid_class.discriminator.keys())[0]
discriminator_classes = (
valid_class.discriminator[discr_propertyname_py].values()
)
valid_type = is_valid_type(input_class_simple, discriminator_classes)
if valid_type:
return True
return valid_type
def validate_and_convert_types(input_value, required_types_mixed, path_to_item,
spec_property_naming, _check_type, configuration=None):
"""Raises a TypeError is there is a problem, otherwise returns value
Args:
input_value (any): the data to validate/convert
required_types_mixed (list/dict/tuple): A list of
valid classes, or a list tuples of valid classes, or a dict where
the value is a tuple of value classes
path_to_item: (list) the path to the data being validated
this stores a list of keys or indices to get to the data being
validated
spec_property_naming (bool): True if the variable names in the input
data are serialized names as specified in the OpenAPI document.
False if the variables names in the input data are python
variable names in PEP-8 snake case.
_check_type: (boolean) if true, type will be checked and conversion
will be attempted.
configuration: (Configuration): the configuration class to use
when converting file_type items.
If passed, conversion will be attempted when possible
If not passed, no conversions will be attempted and
exceptions will be raised
Returns:
the correctly typed value
Raises:
ApiTypeError
"""
results = get_required_type_classes(required_types_mixed, spec_property_naming)
valid_classes, child_req_types_by_current_type = results
input_class_simple = get_simple_class(input_value)
valid_type = is_valid_type(input_class_simple, valid_classes)
if not valid_type:
if configuration:
# if input_value is not valid_type try to convert it
converted_instance = attempt_convert_item(
input_value,
valid_classes,
path_to_item,
configuration,
spec_property_naming,
key_type=False,
must_convert=True,
check_type=_check_type
)
return converted_instance
else:
raise get_type_error(input_value, path_to_item, valid_classes,
key_type=False)
# input_value's type is in valid_classes
if len(valid_classes) > 1 and configuration:
# there are valid classes which are not the current class
valid_classes_coercible = remove_uncoercible(
valid_classes, input_value, spec_property_naming, must_convert=False)
if valid_classes_coercible:
converted_instance = attempt_convert_item(
input_value,
valid_classes_coercible,
path_to_item,
configuration,
spec_property_naming,
key_type=False,
must_convert=False,
check_type=_check_type
)
return converted_instance
if child_req_types_by_current_type == {}:
# all types are of the required types and there are no more inner
# variables left to look at
return input_value
inner_required_types = child_req_types_by_current_type.get(
type(input_value)
)
if inner_required_types is None:
# for this type, there are not more inner variables left to look at
return input_value
if isinstance(input_value, list):
if input_value == []:
# allow an empty list
return input_value
for index, inner_value in enumerate(input_value):
inner_path = list(path_to_item)
inner_path.append(index)
input_value[index] = validate_and_convert_types(
inner_value,
inner_required_types,
inner_path,
spec_property_naming,
_check_type,
configuration=configuration
)
elif isinstance(input_value, dict):
if input_value == {}:
# allow an empty dict
return input_value
for inner_key, inner_val in input_value.items():
inner_path = list(path_to_item)
inner_path.append(inner_key)
if get_simple_class(inner_key) != str:
raise get_type_error(inner_key, inner_path, valid_classes,
key_type=True)
input_value[inner_key] = validate_and_convert_types(
inner_val,
inner_required_types,
inner_path,
spec_property_naming,
_check_type,
configuration=configuration
)
return input_value
def model_to_dict(model_instance, serialize=True):
"""Returns the model properties as a dict
Args:
model_instance (one of your model instances): the model instance that
will be converted to a dict.
Keyword Args:
serialize (bool): if True, the keys in the dict will be values from
attribute_map
"""
result = {}
model_instances = [model_instance]
if model_instance._composed_schemas:
model_instances.extend(model_instance._composed_instances)
for model_instance in model_instances:
for attr, value in model_instance._data_store.items():
if serialize:
# we use get here because additional property key names do not
# exist in attribute_map
attr = model_instance.attribute_map.get(attr, attr)
if isinstance(value, list):
if not value:
# empty list or None
result[attr] = value
else:
res = []
for v in value:
if isinstance(v, PRIMITIVE_TYPES) or v is None:
res.append(v)
elif isinstance(v, ModelSimple):
res.append(v.value)
else:
res.append(model_to_dict(v, serialize=serialize))
result[attr] = res
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0],
model_to_dict(item[1], serialize=serialize))
if hasattr(item[1], '_data_store') else item,
value.items()
))
elif isinstance(value, ModelSimple):
result[attr] = value.value
elif hasattr(value, '_data_store'):
result[attr] = model_to_dict(value, serialize=serialize)
else:
result[attr] = value
return result
def type_error_message(var_value=None, var_name=None, valid_classes=None,
key_type=None):
"""
Keyword Args:
var_value (any): the variable which has the type_error
var_name (str): the name of the variable which has the typ error
valid_classes (tuple): the accepted classes for current_item's
value
key_type (bool): False if our value is a value in a dict
True if it is a key in a dict
False if our item is an item in a list
"""
key_or_value = 'value'
if key_type:
key_or_value = 'key'
valid_classes_phrase = get_valid_classes_phrase(valid_classes)
msg = (
"Invalid type for variable '{0}'. Required {1} type {2} and "
"passed type was {3}".format(
var_name,
key_or_value,
valid_classes_phrase,
type(var_value).__name__,
)
)
return msg
def get_valid_classes_phrase(input_classes):
"""Returns a string phrase describing what types are allowed
"""
all_classes = list(input_classes)
all_classes = sorted(all_classes, key=lambda cls: cls.__name__)
all_class_names = [cls.__name__ for cls in all_classes]
if len(all_class_names) == 1:
return 'is {0}'.format(all_class_names[0])
return "is one of [{0}]".format(", ".join(all_class_names))
def convert_js_args_to_python_args(fn):
from functools import wraps
@wraps(fn)
def wrapped_init(_self, *args, **kwargs):
"""
An attribute named `self` received from the api will conflicts with the reserved `self`
parameter of a class method. During generation, `self` attributes are mapped
to `_self` in models. Here, we name `_self` instead of `self` to avoid conflicts.
"""
spec_property_naming = kwargs.get('_spec_property_naming', False)
if spec_property_naming:
kwargs = change_keys_js_to_python(kwargs, _self.__class__)
return fn(_self, *args, **kwargs)
return wrapped_init
def get_allof_instances(self, model_args, constant_args):
"""
Args:
self: the class we are handling
model_args (dict): var_name to var_value
used to make instances
constant_args (dict): var_name to var_value
used to make instances
Returns
composed_instances (list)
"""
composed_instances = []
for allof_class in self._composed_schemas['allOf']:
# no need to handle changing js keys to python because
# for composed schemas, allof parameters are included in the
# composed schema and were changed to python keys in __new__
# extract a dict of only required keys from fixed_model_args
kwargs = {}
var_names = set(allof_class.openapi_types.keys())
for var_name in var_names:
if var_name in model_args:
kwargs[var_name] = model_args[var_name]
# and use it to make the instance
kwargs.update(constant_args)
try:
allof_instance = allof_class(**kwargs)
composed_instances.append(allof_instance)
except Exception as ex:
raise ApiValueError(
"Invalid inputs given to generate an instance of '%s'. The "
"input data was invalid for the allOf schema '%s' in the composed "
"schema '%s'. Error=%s" % (
allof_class.__name__,
allof_class.__name__,
self.__class__.__name__,
str(ex)
)
) from ex
return composed_instances
def get_oneof_instance(cls, model_kwargs, constant_kwargs, model_arg=None):
"""
Find the oneOf schema that matches the input data (e.g. payload).
If exactly one schema matches the input data, an instance of that schema
is returned.
If zero or more than one schema match the input data, an exception is raised.
In OAS 3.x, the payload MUST, by validation, match exactly one of the
schemas described by oneOf.
Args:
cls: the class we are handling
model_kwargs (dict): var_name to var_value
The input data, e.g. the payload that must match a oneOf schema
in the OpenAPI document.
constant_kwargs (dict): var_name to var_value
args that every model requires, including configuration, server
and path to item.
Kwargs:
model_arg: (int, float, bool, str, date, datetime, ModelSimple, None):
the value to assign to a primitive class or ModelSimple class
Notes:
- this is only passed in when oneOf includes types which are not object
- None is used to suppress handling of model_arg, nullable models are handled in __new__
Returns
oneof_instance (instance)
"""
if len(cls._composed_schemas['oneOf']) == 0:
return None
oneof_instances = []
# Iterate over each oneOf schema and determine if the input data
# matches the oneOf schemas.
for oneof_class in cls._composed_schemas['oneOf']:
# The composed oneOf schema allows the 'null' type and the input data
# is the null value. This is a OAS >= 3.1 feature.
if oneof_class is none_type:
# skip none_types because we are deserializing dict data.
# none_type deserialization is handled in the __new__ method
continue
single_value_input = allows_single_value_input(oneof_class)
if not single_value_input:
# transform js keys from input data to python keys in fixed_model_args
fixed_model_args = change_keys_js_to_python(
model_kwargs, oneof_class)
# Extract a dict with the properties that are declared in the oneOf schema.
# Undeclared properties (e.g. properties that are allowed because of the
# additionalProperties attribute in the OAS document) are not added to
# the dict.
kwargs = {}
var_names = set(oneof_class.openapi_types.keys())
for var_name in var_names:
if var_name in fixed_model_args:
kwargs[var_name] = fixed_model_args[var_name]
# do not try to make a model with no input args
if len(kwargs) == 0:
continue
# and use it to make the instance
kwargs.update(constant_kwargs)
try:
if not single_value_input:
oneof_instance = oneof_class(**kwargs)
else:
if issubclass(oneof_class, ModelSimple):
oneof_instance = oneof_class(model_arg, **constant_kwargs)
elif oneof_class in PRIMITIVE_TYPES:
oneof_instance = validate_and_convert_types(
model_arg,
(oneof_class,),
constant_kwargs['_path_to_item'],
constant_kwargs['_spec_property_naming'],
constant_kwargs['_check_type'],
configuration=constant_kwargs['_configuration']
)
oneof_instances.append(oneof_instance)
except Exception:
pass
if len(oneof_instances) == 0:
raise ApiValueError(
"Invalid inputs given to generate an instance of %s. None "
"of the oneOf schemas matched the input data." %
cls.__name__
)
elif len(oneof_instances) > 1:
raise ApiValueError(
"Invalid inputs given to generate an instance of %s. Multiple "
"oneOf schemas matched the inputs, but a max of one is allowed." %
cls.__name__
)
return oneof_instances[0]
def get_anyof_instances(self, model_args, constant_args):
"""
Args:
self: the class we are handling
model_args (dict): var_name to var_value
The input data, e.g. the payload that must match at least one
anyOf child schema in the OpenAPI document.
constant_args (dict): var_name to var_value
args that every model requires, including configuration, server
and path to item.
Returns
anyof_instances (list)
"""
anyof_instances = []
if len(self._composed_schemas['anyOf']) == 0:
return anyof_instances
for anyof_class in self._composed_schemas['anyOf']:
# The composed oneOf schema allows the 'null' type and the input data
# is the null value. This is a OAS >= 3.1 feature.
if anyof_class is none_type:
# skip none_types because we are deserializing dict data.
# none_type deserialization is handled in the __new__ method
continue
# transform js keys to python keys in fixed_model_args
fixed_model_args = change_keys_js_to_python(model_args, anyof_class)
# extract a dict of only required keys from these_model_vars
kwargs = {}
var_names = set(anyof_class.openapi_types.keys())
for var_name in var_names:
if var_name in fixed_model_args:
kwargs[var_name] = fixed_model_args[var_name]
# do not try to make a model with no input args
if len(kwargs) == 0:
continue
# and use it to make the instance
kwargs.update(constant_args)
try:
anyof_instance = anyof_class(**kwargs)
anyof_instances.append(anyof_instance)
except Exception:
pass
if len(anyof_instances) == 0:
raise ApiValueError(
"Invalid inputs given to generate an instance of %s. None of the "
"anyOf schemas matched the inputs." %
self.__class__.__name__
)
return anyof_instances
def get_additional_properties_model_instances(
composed_instances, self):
additional_properties_model_instances = []
all_instances = [self]
all_instances.extend(composed_instances)
for instance in all_instances:
if instance.additional_properties_type is not None:
additional_properties_model_instances.append(instance)
return additional_properties_model_instances
def get_var_name_to_model_instances(self, composed_instances):
var_name_to_model_instances = {}
all_instances = [self]
all_instances.extend(composed_instances)
for instance in all_instances:
for var_name in instance.openapi_types:
if var_name not in var_name_to_model_instances:
var_name_to_model_instances[var_name] = [instance]
else:
var_name_to_model_instances[var_name].append(instance)
return var_name_to_model_instances
def get_unused_args(self, composed_instances, model_args):
unused_args = dict(model_args)
# arguments apssed to self were already converted to python names
# before __init__ was called
for var_name_py in self.attribute_map:
if var_name_py in unused_args:
del unused_args[var_name_py]
for instance in composed_instances:
if instance.__class__ in self._composed_schemas['allOf']:
for var_name_py in instance.attribute_map:
if var_name_py in unused_args:
del unused_args[var_name_py]
else:
for var_name_js in instance.attribute_map.values():
if var_name_js in unused_args:
del unused_args[var_name_js]
return unused_args
def validate_get_composed_info(constant_args, model_args, self):
"""
For composed schemas, generate schema instances for
all schemas in the oneOf/anyOf/allOf definition. If additional
properties are allowed, also assign those properties on
all matched schemas that contain additionalProperties.
Openapi schemas are python classes.
Exceptions are raised if:
- 0 or > 1 oneOf schema matches the model_args input data
- no anyOf schema matches the model_args input data
- any of the allOf schemas do not match the model_args input data
Args:
constant_args (dict): these are the args that every model requires
model_args (dict): these are the required and optional spec args that
were passed in to make this model
self (class): the class that we are instantiating
This class contains self._composed_schemas
Returns:
composed_info (list): length three
composed_instances (list): the composed instances which are not
self
var_name_to_model_instances (dict): a dict going from var_name
to the model_instance which holds that var_name
the model_instance may be self or an instance of one of the
classes in self.composed_instances()
additional_properties_model_instances (list): a list of the
model instances which have the property
additional_properties_type. This list can include self
"""
# create composed_instances
composed_instances = []
allof_instances = get_allof_instances(self, model_args, constant_args)
composed_instances.extend(allof_instances)
oneof_instance = get_oneof_instance(self.__class__, model_args, constant_args)
if oneof_instance is not None:
composed_instances.append(oneof_instance)
anyof_instances = get_anyof_instances(self, model_args, constant_args)
composed_instances.extend(anyof_instances)
# map variable names to composed_instances
var_name_to_model_instances = get_var_name_to_model_instances(
self, composed_instances)
# set additional_properties_model_instances
additional_properties_model_instances = (
get_additional_properties_model_instances(composed_instances, self)
)
# set any remaining values
unused_args = get_unused_args(self, composed_instances, model_args)
if len(unused_args) > 0 and \
len(additional_properties_model_instances) == 0 and \
(self._configuration is None or
not self._configuration.discard_unknown_keys):
raise ApiValueError(
"Invalid input arguments input when making an instance of "
"class %s. Not all inputs were used. The unused input data "
"is %s" % (self.__class__.__name__, unused_args)
)
# no need to add additional_properties to var_name_to_model_instances here
# because additional_properties_model_instances will direct us to that
# instance when we use getattr or setattr
# and we update var_name_to_model_instances in setattr
return [
composed_instances,
var_name_to_model_instances,
additional_properties_model_instances,
unused_args
]
| 39.456797 | 187 | 0.628891 |
acefdb01db067099980d335d4b1ba729d1545819 | 11,456 | py | Python | ridt/analysis/resultswriter.py | riskaware-ltd/ridt | c0288a2f814b2749bdf73de7157f7477ca271aff | [
"MIT"
] | null | null | null | ridt/analysis/resultswriter.py | riskaware-ltd/ridt | c0288a2f814b2749bdf73de7157f7477ca271aff | [
"MIT"
] | 9 | 2020-09-18T08:22:39.000Z | 2021-07-20T09:39:59.000Z | ridt/analysis/resultswriter.py | riskaware-ltd/ridt | c0288a2f814b2749bdf73de7157f7477ca271aff | [
"MIT"
] | 1 | 2021-06-22T21:53:20.000Z | 2021-06-22T21:53:20.000Z | import csv
from io import TextIOWrapper
from os.path import join
from typing import List
from typing import Iterable
from typing import Type
from ridt.base import RIDTOSError
from ridt.config import RIDTConfig
from ridt.config import Units
from ridt.config import summary
from ridt.container import Domain
from ridt.equation import EddyDiffusion
from ridt.data import DirectoryAgent
from .datastoreanalyser import DataStoreAnalyser
from .resultcontainers import ResultContainer
StringList = List[str]
class ResultsWriter:
"""The Results Writer class.
Iterates through all selected geometries and writes all quantities to disk.
Attributes
----------
setting : :class:`~.RIDTConfig`
The settings for the run in question.
domain : :class:`~.Domain`
The instance of :class:`~.Domain` corresponding to :attr:`setting`.
analysis : :class:`~.DataStoreAnalyser`
:class:`~.DataStoreAnalyser` instance to be written.
quantity: :obj:`str`
The string id for the quantity stored in the data store.
thresholds : :obj:`list` [:obj:`float`]
The threshold values corresponding to :attr:`quantity` defined in
:attr:`setting`.
units : :class:`~.Units`
The instance of :class:`~.Units` corresponding to :attr:`setting`.
dir_agent: :class:`~.DirectoryAgent`
The directory agent for run.
"""
def __init__(self,
setting: RIDTConfig,
analysis: DataStoreAnalyser,
dir_agent: DirectoryAgent,
quantity: str):
"""The :class`~.ResultsWriter` class initialiser.
Parameters
----------
setting : :class:`~.RIDTConfig`
The settings for the run in question.
analysis : :class:`~.DataStoreAnalyser`
:class:`~.DataStoreAnalyser` instance to be written.
dir_agent: :class:`~.DirectoryAgent`
The directory agent for run.
quantity : :obj:`str`
The string id for the quantity stored in the data store.
"""
self.setting = setting
self.units = Units(setting)
self.quantity = quantity
self.thresholds = self.threshold_converter()
self.analysis = analysis
self.dir_agent = dir_agent
self.domain = Domain(setting)
if quantity == "concentration":
self.summary()
self.maximum()
self.exceedance_analysis()
self.extrema()
@property
def geometries(self):
""":obj:`list` [:obj:`str`] : the list of geometries selected for
evaluation in :attr:`setting`.
"""
locations = self.setting.models.eddy_diffusion.monitor_locations
return [g for g, e in locations.evaluate.items() if e]
def threshold_converter(self):
"""Converts the threshold into SI units.
Converts the thresholds in :attr:`setting` corresponding to
:attr:`quantity` into SI units.
Returns
-------
:obj:`list` [:obj:`float`]
The list of threshold values in SI units.
"""
tld = [t.value for t in getattr(self.setting.thresholds, self.quantity)]
return getattr(self.units, f"{self.quantity}_converter")(tld)
def write(self, file_path: str, header: StringList, lines: Iterable) -> None:
"""Write array of values to csv file.
Parameters
----------
file_path : :obj:`str`
The path to save the data to.
header : :obj:`list` [:obj:`str`]
The header for the csv file.
lines : Iterable
The array of values to be written to the csv file.
Returns
-------
None
Raises
------
:class:`~.RIDTOSError`
If cannot create file on disk.
"""
try:
f = open(file_path, 'w', newline="")
except OSError as e:
raise RIDTOSError(e)
writer = csv.writer(f, delimiter=",")
writer.writerow(header)
for line in lines:
writer.writerow(line)
f.close()
def get_valid(self, geometry: str, results: List[Type[ResultContainer]]):
"""Filter valid results for a given geometry from list of results.
Parameters
----------
geometry : :obj:`str`
The geometry in to filter for.
results : :obj:`list` [:class:`~.ResultContainer`]
The list of :class:`~.ResultConainer`.
Returns
-------
:obj:`list` [:class:`~.ResultContainer`]
The filtered list of :class:`~.ResultConainer`.
"""
return [i for i in results if i.geometry == geometry and i.valid]
def maximum(self):
"""Write the relevant :class:`~.Maximum` results to file.
Loops through all geometries and writes the Maximum results to
a csv file.
Returns
-------
None
"""
for geometry in self.geometries:
self.dir_agent.create_analysis_dir(geometry, self.quantity)
items = self.get_valid(geometry, self.analysis.maximum)
items.sort(reverse=True)
rows = [item.row for item in items]
if rows:
path = join(self.dir_agent.adir, items[0].fname)
self.write(path, items[0].header, rows)
def exceedance_analysis(self):
"""Write the relevant exceedance results to file.
Loops through all geometries and writes the :class:`~.Exceedance`,
:class:`~.PercentExceedance`, and :class:`~.MaxPercentExceedance`
results to a csv file.
Returns
-------
None
"""
results = [
(self.analysis.exceedance, False),
(self.analysis.percent_exceedance, False),
(self.analysis.max_percent_exceedance, True)
]
for r, reverse in results:
for geometry in self.geometries:
self.dir_agent.create_analysis_dir(geometry, self.quantity)
for t in self.thresholds:
valid = self.get_valid(geometry, r)
items = [i for i in valid if i.threshold == t]
items.sort(reverse=reverse)
rows = [item.row for item in items]
if rows:
path = join(self.dir_agent.adir, items[0].fname)
self.write(path, items[0].header, rows)
def extrema(self):
"""Computes and writes extrema results to disk.
loops through all items in :attr:`analysis` and for each geometry type
writes the following information to the output file:
The maximum value.
The fastest time to all threshold values.
The fastest time to the defined percentage of domain to all threshold
values.
The largest percentage that exceeds all threshold values.
The
Raises
------
:class:`~.RIDTOSError`
If unable to create the output file on disk.
"""
try:
fname = f"{self.quantity}_extrema.txt"
f = open(join(self.dir_agent.outdir, fname), 'w')
except OSError as e:
raise RIDTOSError(e)
self.title(f, self.analysis.maximum[0].title)
for geometry in self.geometries:
items = self.get_valid(geometry, self.analysis.maximum)
if items:
self.subtitle(f, items[0].extreme_title)
item = max(items)
f.write(item.string)
results = [
(self.analysis.exceedance, False),
(self.analysis.percent_exceedance, False),
(self.analysis.max_percent_exceedance, True)
]
for r, reverse in results:
self.title(f, r[0].title)
for t in self.thresholds:
for geometry in self.geometries:
valid = self.get_valid(geometry, r)
items = [i for i in valid if i.threshold == t]
if items:
self.subtitle(f, items[0].extreme_title)
item = min(items) if not reverse else max(items)
f.write(item.string)
f.close()
def title(self, file: TextIOWrapper, title: str):
"""Writes a formatted title string to a file object.
Parameters
----------
file : :obj:`TextIOWrapper`
The file object to write to.
title : :obj:`str`
The title string.
Returns
-------
None
"""
file.write("\n")
file.write("".join("=" for i in range(len(title))) + "\n")
file.write(title + "\n")
file.write("".join("=" for i in range(len(title))) + "\n")
def subtitle(self, file: TextIOWrapper, subtitle: str):
"""Writes a formatted subtitle string to a file object.
Parameters
----------
file : :obj:`TextIOWrapper`
The file object to write to.
subtitle : :obj:`str`
The subtitle string.
Returns
-------
None
"""
file.write("\n")
file.write("".join("-" for i in range(len(subtitle))) + "\n")
file.write(subtitle + "\n")
file.write("".join("-" for i in range(len(subtitle))) + "\n")
def summary(self):
"""Saves a run summary to a text file in the run output directory.
Raises
------
:class:`~.RIDTOSError`
If unable to create the output file on disk.
"""
try:
f = open(join(self.dir_agent.outdir, "run_summary.txt"), 'w')
except OSError as e:
raise RIDTOSError(e)
char_diff = self.characteristic_diffusion_time
f.write("Characteristic diffusion times:\n")
f.write(f"\tx: {char_diff['x']:.2f}{self.setting.time_units}\n")
f.write(f"\ty: {char_diff['y']:.2f}{self.setting.time_units}\n")
f.write(f"\tz: {char_diff['z']:.2f}{self.setting.time_units}\n")
f.write(f"\tV^(1/3): {char_diff['v']:.2f}{self.setting.time_units}\n")
f.write("\n")
if self.setting.models.eddy_diffusion.monitor_locations.evaluate["domain"]:
ttwm = self.analysis.time_to_well_mixed
if ttwm:
value = f"{ttwm:.2f}{self.setting.time_units}\n"
else:
value = "not within lifetime of simulation\n"
else:
value = "domain data not available\n"
f.write(f"Time to well mixed: {value}")
f.write("\n")
f.write(summary(self.setting))
f.close()
@property
def characteristic_diffusion_time(self):
""":obj:`dict` [:obj:`str`, :obj:`float`] : the characteristic
diffusion times for all dimensions.
"""
solver = EddyDiffusion(self.setting)
dim = self.setting.dimensions
l = pow(dim.x * dim.y * dim.z, 1.0 / 3.0)
return {
"x": dim.x * dim.x / solver.diff_coeff,
"y": dim.y * dim.y / solver.diff_coeff,
"z": dim.z * dim.z / solver.diff_coeff,
"v": l * l / solver.diff_coeff
}
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
| 31.04607 | 83 | 0.559707 |
acefdb2c2c8ecc845d4427d580824b4abb651cdc | 1,001 | py | Python | day2/python/main.py | mjkoo/aoc2019 | 89e0090688dad2ccd8bdd94f657c6f08320e125a | [
"MIT"
] | null | null | null | day2/python/main.py | mjkoo/aoc2019 | 89e0090688dad2ccd8bdd94f657c6f08320e125a | [
"MIT"
] | null | null | null | day2/python/main.py | mjkoo/aoc2019 | 89e0090688dad2ccd8bdd94f657c6f08320e125a | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import operator
import sys
TARGET = 19690720
def intcode(mem):
def alu(pc, op):
mem[mem[pc + 3]] = op(mem[mem[pc + 1]], mem[mem[pc + 2]])
return 4
opcodes = {
1: lambda pc: alu(pc, operator.add),
2: lambda pc: alu(pc, operator.mul),
99: lambda pc: -1,
}
pc = 0
while True:
op = opcodes[mem[pc]]
off = op(pc)
if off < 0:
break
pc += off
return mem[0]
def init_and_run(mem, noun, verb):
mem[1] = noun
mem[2] = verb
return intcode(mem)
def main(argv):
with open(argv[1], "r") as f:
mem = [int(n) for n in f.read().split(",")]
print(init_and_run(mem.copy(), 12, 2))
for noun in range(100):
for verb in range(100):
if init_and_run(mem.copy(), noun, verb) == TARGET:
print(100 * noun + verb)
return
print("No solutions found")
if __name__ == "__main__":
main(sys.argv)
| 18.886792 | 65 | 0.515485 |
acefdc59364e855f8dbbf4156c26bbf45061430c | 2,858 | py | Python | env/lib/python3.4/site-packages/django_markdown/pypandoc.py | marto-k/pettify-1 | 6d6ab498b2b53559419fc8b523150ce60d40b081 | [
"MIT"
] | 2 | 2017-02-01T09:57:40.000Z | 2017-06-03T15:26:55.000Z | env/lib/python3.4/site-packages/django_markdown/pypandoc.py | marto-k/pettify-1 | 6d6ab498b2b53559419fc8b523150ce60d40b081 | [
"MIT"
] | 2 | 2018-05-11T20:10:23.000Z | 2019-05-01T21:13:07.000Z | env/lib/python3.4/site-packages/django_markdown/pypandoc.py | marto-k/pettify-1 | 6d6ab498b2b53559419fc8b523150ce60d40b081 | [
"MIT"
] | 3 | 2017-02-11T13:19:28.000Z | 2018-08-31T18:51:18.000Z | # -*- coding: utf-8 -*-
from __future__ import with_statement
__author__ = 'Juho Vepsäläinen'
__version__ = '0.8.2'
__license__ = 'MIT'
__all__ = ['convert', 'get_pandoc_formats']
import subprocess
import os
def convert(source, to, format=None, extra_args=(), encoding='utf-8'):
"""Convert given `source` from `format` `to` another.
`source` may be either a file path or a string to be converted. It's possible to pass
`extra_args` if needed. In case `format` is not provided, it will try to invert the format
based on given `source`.
Raises OSError if pandoc is not found! Make sure it has been installed and is available at
path.
"""
return _convert(_read_file, _process_file, source, to, format, extra_args, encoding=encoding)
def _convert(reader, processor, source, to, format=None, extra_args=(), encoding=None):
source, format = reader(source, format, encoding=encoding)
formats = {
'dbk': 'docbook',
'md': 'markdown',
'rest': 'rst',
'tex': 'latex',
}
format = formats.get(format, format)
to = formats.get(to, to)
if not format:
raise RuntimeError('Missing format!')
from_formats, to_formats = get_pandoc_formats()
if format not in from_formats:
raise RuntimeError(
'Invalid input format! Expected one of these: ' +
', '.join(from_formats))
if to not in to_formats:
raise RuntimeError('Invalid to format! Expected one of these: ' + ', '.join(to_formats))
return processor(source, to, format, extra_args)
def _read_file(source, format, encoding='utf-8'):
if os.path.exists(source):
import codecs
with codecs.open(source, encoding=encoding) as f:
format = format or os.path.splitext(source)[1].strip('.')
source = f.read()
return source, format
def _process_file(source, to, format, extra_args):
args = ['pandoc', '--from=' + format, '--to=' + to]
args.extend(extra_args)
p = subprocess.Popen(
args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
return p.communicate(source.encode('utf-8'))[0].decode('utf-8')
def get_pandoc_formats():
""" Dynamic preprocessor for Pandoc formats.
Return 2 lists. "from_formats" and "to_formats".
"""
try:
p = subprocess.Popen(
['pandoc', '-h'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
except OSError:
raise OSError("You probably do not have pandoc installed.")
help_text = p.communicate()[0].decode().splitlines(False)
txt = ' '.join(help_text[1:help_text.index('Options:')])
aux = txt.split('Output formats: ')
in_ = aux[0].split('Input formats: ')[1].split(',')
out = aux[1].split(',')
return [f.strip() for f in in_], [f.strip() for f in out]
| 28.58 | 97 | 0.63226 |
acefdcd2a0b51537d5e9300644ae5f3728ec4447 | 3,098 | py | Python | grr/server/grr_response_server/bigquery_test.py | jaegeral/grr | 1f6bcd901fbebf386988a80fc6cb4034cbedfde9 | [
"Apache-2.0"
] | 1 | 2021-01-25T00:55:20.000Z | 2021-01-25T00:55:20.000Z | grr/server/grr_response_server/bigquery_test.py | jkirby2423/grr | e0a5ab89a6a9dce3812fcbe930df34488ed90613 | [
"Apache-2.0"
] | null | null | null | grr/server/grr_response_server/bigquery_test.py | jkirby2423/grr | e0a5ab89a6a9dce3812fcbe930df34488ed90613 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Lint as: python3
"""Tests for grr.lib.bigquery."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import io
import os
import time
from unittest import mock
from absl import app
from googleapiclient import errors
from grr_response_core import config
from grr_response_core.lib import rdfvalue
from grr_response_core.lib.util import temp
from grr_response_core.lib.util.compat import json
from grr_response_server import bigquery
from grr.test_lib import test_lib
class BigQueryClientTest(test_lib.GRRBaseTest):
"""Tests BigQuery client."""
PROJECT_ID = "grr-dummy"
SERVICE_ACCOUNT_JSON = """{"type": "service_account"}"""
@mock.patch.object(bigquery, "ServiceAccountCredentials")
@mock.patch.object(bigquery.discovery, "build")
@mock.patch.object(bigquery.httplib2, "Http")
def testInsertData(self, mock_http, mock_build, mock_creds):
bq_client = bigquery.GetBigQueryClient(
service_account_json=self.SERVICE_ACCOUNT_JSON,
project_id=self.PROJECT_ID)
schema_path = os.path.join(config.CONFIG["Test.data_dir"], "bigquery",
"ExportedFile.schema")
schema_data = json.ReadFromPath(schema_path)
data_fd = open(
os.path.join(config.CONFIG["Test.data_dir"], "bigquery",
"ExportedFile.json.gz"), "rb")
now = rdfvalue.RDFDatetime.Now().AsSecondsSinceEpoch()
job_id = "hunts_HFFE1D044_Results_%s" % now
bq_client.InsertData("ExportedFile", data_fd, schema_data, job_id)
# We should have called insert once
insert = mock_build.return_value.jobs.return_value.insert
self.assertEqual(insert.call_count, 1)
self.assertEqual(
job_id, insert.call_args_list[0][1]["body"]["jobReference"]["jobId"])
def testRetryUpload(self):
bq_client = bigquery.BigQueryClient()
resp = mock.Mock()
resp.status = 503
error = mock.Mock()
error.resp = resp
job = mock.Mock()
# Always raise errors.HttpError on job.execute()
job.configure_mock(
**{"execute.side_effect": errors.HttpError(resp, b"nocontent")})
job_id = "hunts_HFFE1D044_Results_1446056474"
with temp.AutoTempFilePath() as filepath:
with io.open(filepath, "w", encoding="utf-8") as filedesc:
filedesc.write("{data}")
with mock.patch.object(time, "sleep") as mock_sleep:
with self.assertRaises(bigquery.BigQueryJobUploadError):
bq_client.RetryUpload(job, job_id, error)
# Make sure retry sleeps are correct.
max_calls = config.CONFIG["BigQuery.retry_max_attempts"]
retry_interval = config.CONFIG["BigQuery.retry_interval"]
multiplier = config.CONFIG["BigQuery.retry_multiplier"]
self.assertEqual(job.execute.call_count, max_calls)
mock_sleep.assert_has_calls([
mock.call(retry_interval.ToFractional(rdfvalue.SECONDS)),
mock.call(retry_interval.ToFractional(rdfvalue.SECONDS) * multiplier)
])
def main(argv):
del argv # Unused.
test_lib.main()
if __name__ == "__main__":
app.run(main)
| 32.957447 | 77 | 0.719174 |
acefdd19b3f6eb6bd906cfad386c7f04ab65fba4 | 762 | py | Python | Alphabets/Capital Alphabets/R.py | vijayakumarr345/pattern | d857812cea625098a18c9d45ca01b22a379d5fb0 | [
"MIT"
] | null | null | null | Alphabets/Capital Alphabets/R.py | vijayakumarr345/pattern | d857812cea625098a18c9d45ca01b22a379d5fb0 | [
"MIT"
] | 1 | 2021-03-18T12:33:06.000Z | 2021-03-18T12:33:48.000Z | Alphabets/Capital Alphabets/R.py | vijayakumarr345/pattern | d857812cea625098a18c9d45ca01b22a379d5fb0 | [
"MIT"
] | null | null | null | # Capital Alphabet R using Function
def for_R():
""" *'s printed in the Shape of Capital R """
for row in range(9):
for col in range(6):
if col ==0 or row in (0,4) and col != 5 or row in (1,2,3) and col ==5 or row - col ==4:
print('*',end =' ')
else:
print(' ',end=' ')
print()
def while_R():
""" *'s printed in the Shape of Capital R """
row =0
while row <9:
col =0
while col <6:
if col ==0 or row in (0,4) and col != 5 or row in (1,2,3) and col ==5 or row - col ==4:
print('*',end =' ')
else:
print(' ',end=' ')
col+=1
print()
row +=1
| 28.222222 | 100 | 0.408136 |
acefde38615270bdb69565ff892f9a6747a1acdf | 982 | py | Python | tests/test_urls.py | irahorecka/python-craigslist-meta | 069b0b85971b20f8ea20a1e8868b4614c180ebce | [
"MIT"
] | 1 | 2021-04-07T23:40:15.000Z | 2021-04-07T23:40:15.000Z | tests/test_urls.py | irahorecka/python-craigslist-meta | 069b0b85971b20f8ea20a1e8868b4614c180ebce | [
"MIT"
] | 1 | 2021-02-25T21:14:05.000Z | 2021-02-26T08:53:50.000Z | tests/test_urls.py | irahorecka/python-craigslist-meta | 069b0b85971b20f8ea20a1e8868b4614c180ebce | [
"MIT"
] | null | null | null | import concurrent.futures
import requests
from craigslist_meta import Site
def test_urls():
"""Test every url returns success response status code."""
urls = tuple(get_urls())
status_codes = map_threads(lambda url: requests.get(url).status_code, urls)
expected_status = 200
# assert number of responses == number of urls
assert len(list(status_codes)) == len(urls)
assert all(status == expected_status for status in status_codes)
def get_urls():
"""Get every Craigslist url using craigslist_meta API."""
all_urls = []
for site in Site.all():
if site.has_area():
for area in site:
all_urls.append(area.url)
else:
all_urls.append(site.url)
return all_urls
def map_threads(func, iterable):
"""Map function to iterable object using thread pools."""
with concurrent.futures.ThreadPoolExecutor() as executor:
result = executor.map(func, iterable)
return result
| 28.882353 | 79 | 0.675153 |
acefdeacc769484e4c6b831c7934dab8db529c21 | 93 | py | Python | gpapi/__init__.py | ericfourrier/gimmeproxy-api | 2295c5d1275448ac436877013ba0015f9c0fc8f6 | [
"MIT"
] | 11 | 2017-09-25T14:27:03.000Z | 2021-04-03T20:14:43.000Z | gpapi/__init__.py | ericfourrier/gimmeproxy-api | 2295c5d1275448ac436877013ba0015f9c0fc8f6 | [
"MIT"
] | null | null | null | gpapi/__init__.py | ericfourrier/gimmeproxy-api | 2295c5d1275448ac436877013ba0015f9c0fc8f6 | [
"MIT"
] | 6 | 2017-06-13T19:52:17.000Z | 2019-03-25T10:39:09.000Z | # -*- coding: utf-8 -*-
__all__ = ["getproxies"]
from gpapi.getproxies import GimmeProxyApi
| 18.6 | 42 | 0.698925 |
acefdf7a240e7a4f801184225d1d0d9ac35ba737 | 3,342 | py | Python | utlis/rank.py | id0n3x/v2locamaV2V | 8e29c420cd410daa6a5181e6806ecd25ac0f8d66 | [
"MIT"
] | null | null | null | utlis/rank.py | id0n3x/v2locamaV2V | 8e29c420cd410daa6a5181e6806ecd25ac0f8d66 | [
"MIT"
] | null | null | null | utlis/rank.py | id0n3x/v2locamaV2V | 8e29c420cd410daa6a5181e6806ecd25ac0f8d66 | [
"MIT"
] | 1 | 2021-12-22T22:25:52.000Z | 2021-12-22T22:25:52.000Z | from config import *
from utlis.tg import Bot
def setrank(redis,rank,userID,chatID,type):
try:
if type is "array":
get = redis.sismember("{}Nbot:{}:{}".format(BOT_ID,chatID,rank),userID)
if get:
return rank
save = redis.sadd("{}Nbot:{}:{}".format(BOT_ID,chatID,rank),userID)
return save
elif type is "one":
get = redis.get("{}Nbot:{}:{}".format(BOT_ID,chatID,rank))
if get and int(get) == userID:
return rank
save = redis.set("{}Nbot:{}:{}".format(BOT_ID,chatID,rank),userID)
return save
except Exception as e:
return rank
def remrank(redis,rank,userID,chatID,type):
try:
if type is "array":
get = redis.sismember("{}Nbot:{}:{}".format(BOT_ID,chatID,rank),userID)
if not get:
return 0
save = redis.srem("{}Nbot:{}:{}".format(BOT_ID,chatID,rank),userID)
return save
elif type is "one":
get = redis.get("{}Nbot:{}:{}".format(BOT_ID,chatID,rank))
if get and int(get) != userID:
return 0
save = redis.delete("{}Nbot:{}:{}".format(BOT_ID,chatID,rank),userID)
return save
except Exception as e:
return 0
def isrank(redis,userID,chatID):
get = redis.get("{}Nbot:BOTrank".format(BOT_ID))
if get and int(get) == userID:
return "bot"
get = redis.get("{}Nbot:sudo".format(BOT_ID))
if get and int(get) == userID:
return "sudo"
get = redis.sismember("{}Nbot:sudos".format(BOT_ID),userID)
if get:
return "sudos"
get = redis.get("{}Nbot:{}:creator".format(BOT_ID,chatID))
if get and int(get) == userID:
return "creator"
get = redis.sismember("{}Nbot:{}:owner".format(BOT_ID,chatID),userID)
if get:
return "owner"
get = redis.sismember("{}Nbot:{}:admin".format(BOT_ID,chatID),userID)
if get:
return "admin"
get = redis.sismember("{}Nbot:{}:vip".format(BOT_ID,chatID),userID)
if get:
return "vip"
return 0
def setsudos(redis,userID):
try:
get = redis.sismember("{}Nbot:sudos".format(BOT_ID),userID)
print("get",get)
if get:
return "sudos"
save = redis.sadd("{}Nbot:sudos".format(BOT_ID),userID)
return save
except Exception as e:
return 0
def remsudos(redis,userID):
try:
get = redis.sismember("{}Nbot:sudos".format(BOT_ID),userID)
if not get:
return 0
save = redis.srem("{}Nbot:sudos".format(BOT_ID),userID)
return save
except Exception as e:
return 0
def setsudo(redis,userID):
try:
save = redis.set("{}Nbot:sudo".format(BOT_ID),userID)
return save
except Exception as e:
return 0
def GPranks(userID,chatID):
get = Bot("getChatMember",{"chat_id":chatID,"user_id":userID})
if get["ok"]:
status = get["result"]["status"]
else:
status = "NoMember"
return status
def IDrank(redis,userID,chatID,r):
rank = isrank(redis,userID,chatID)
if (rank is False or rank is 0):
T = r.Rmember
if rank == "sudo":
T = r.Rsudo
if rank == "sudos":
T = r.Rsudos
if rank == "creator":
T = r.Rcreator
if rank == "owner":
T = r.Rowner
if rank == "admin":
T = r.Radmin
if rank == "vip":
T = r.Rvip
if rank == "bot":
T = "bot"
return T
def Grank(rank,r):
if rank == "sudo":
T = r.Rsudo
if rank == "sudos":
T = r.Rsudos
if rank == "creator":
T = r.Rcreator
if rank == "owner":
T = r.Rowner
if rank == "admin":
T = r.Radmin
if rank == "administrator":
T = r.Radmin
if rank == "vip":
T = r.Rvip
if rank == "bot":
T = "bot"
return T
| 21.701299 | 74 | 0.634949 |
acefdf828c69b7b8678aa118ae33a6ccbae12340 | 1,776 | py | Python | image/template_match_with_histogram.py | benjaminBoboul/python-snippets | 22f650251209234fede273a245bfce5efd35668b | [
"Unlicense"
] | null | null | null | image/template_match_with_histogram.py | benjaminBoboul/python-snippets | 22f650251209234fede273a245bfce5efd35668b | [
"Unlicense"
] | null | null | null | image/template_match_with_histogram.py | benjaminBoboul/python-snippets | 22f650251209234fede273a245bfce5efd35668b | [
"Unlicense"
] | 3 | 2019-11-27T17:22:32.000Z | 2020-12-12T06:22:41.000Z | #!/usr/bin/env python
import cv2
import numpy as np
import math
import pprint
import random
# Increase value to decrease precision and reduce execution time (min : 1) WARN : a scan_scale_factor too high could affect the algorithm's ability to work properly
scan_scale_factor = 1
# This variables define the minimum value required to mark position as candidate with HISTCMP_CORREL method, TIPS : set -1 to produce glitchy picture (recommended value : 0.9)
correlation_minimum = 0.9
img_rgb = cv2.imread("Data-TP/mon.jpg")
template_rgb = cv2.imread("Data-TP/statue.jpg")
img_size = img_rgb.shape[:2]
tmp_size = template_rgb.shape[:2]
template_hist = cv2.calcHist(
template_rgb, [2], None, [256], [0, 256]
) # get template histogram
hist_cmp = []
for y in range(0, img_size[0] - tmp_size[0], scan_scale_factor):
y_upper, y_lower = (y, y + tmp_size[0])
for x in range(0, img_size[1] - tmp_size[1], scan_scale_factor):
x_upper, x_lower = (x, x + tmp_size[1])
print("scanning from {}x{} to {}x{}".format(x_upper, y_upper, x_lower, y_lower))
a = img_rgb[y_upper:y_lower, x_upper:x_lower]
img_hist = cv2.calcHist(a, [2], None, [256], [0, 256])
compared_hist = cv2.compareHist(template_hist, img_hist, cv2.HISTCMP_CORREL)
hist_cmp.append((compared_hist, (x_upper, y_upper), (x_lower, y_lower)))
pprint.pprint(hist_cmp)
candidates = [
x for x in hist_cmp if x[0] >= correlation_minimum
] # max(hist_cmp, key=lambda x: x[0])
print(candidates)
for scope in candidates:
cv2.rectangle(
img_rgb,
scope[1],
scope[2],
(random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255)),
2,
)
cv2.imshow("result", img_rgb)
cv2.waitKey(0)
cv2.destroyAllWindows()
| 34.823529 | 175 | 0.690315 |
acefe092715899ec84f8db2a0aee6682cdd2fd91 | 411 | py | Python | src/django-nonrel/tests/modeltests/user_commands/management/commands/dance.py | adamjmcgrath/glancydesign | 826ede7c639879d5b79ee730eb5e91422768cb02 | [
"BSD-3-Clause"
] | 790 | 2015-01-03T02:13:39.000Z | 2020-05-10T19:53:57.000Z | tests/modeltests/user_commands/management/commands/dance.py | mradziej/django | 5d38965743a369981c9a738a298f467f854a2919 | [
"BSD-3-Clause"
] | 1,361 | 2015-01-08T23:09:40.000Z | 2020-04-14T00:03:04.000Z | tests/modeltests/user_commands/management/commands/dance.py | mradziej/django | 5d38965743a369981c9a738a298f467f854a2919 | [
"BSD-3-Clause"
] | 155 | 2015-01-08T22:59:31.000Z | 2020-04-08T08:01:53.000Z | from optparse import make_option
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Dance around like a madman."
args = ''
requires_model_validation = True
option_list =[
make_option("-s", "--style", default="Rock'n'Roll")
]
def handle(self, *args, **options):
self.stdout.write("I don't feel like dancing %s." % options["style"])
| 27.4 | 77 | 0.6618 |
acefe1eed840f8b902c263dace890019639b3262 | 1,235 | py | Python | code/tutorials/theano/load_mnist.py | chaowang15/computer-vision-resources | 97f1a3a07fede01ce500406cd5ad1d99dce1b503 | [
"MIT"
] | 27 | 2016-04-17T05:42:51.000Z | 2021-02-11T17:16:32.000Z | code/tutorials/theano/load_mnist.py | milq/computer-vision-resources | cd532869081b879c7b43550bf7a39e3fb1aa9eab | [
"MIT"
] | null | null | null | code/tutorials/theano/load_mnist.py | milq/computer-vision-resources | cd532869081b879c7b43550bf7a39e3fb1aa9eab | [
"MIT"
] | 34 | 2016-06-20T03:03:47.000Z | 2019-05-27T15:11:06.000Z | import numpy as np
import os
data_dir = os.getcwd() + '/mnist/'
def one_hot(x,n):
if type(x) == list:
x = np.array(x)
x = x.flatten()
o_h = np.zeros((len(x),n))
o_h[np.arange(len(x)),x] = 1
return o_h
def mnist(ntrain=60000,ntest=10000,onehot=True):
fd = open(os.path.join(data_dir,'train-images.idx3-ubyte'))
loaded = np.fromfile(file=fd,dtype=np.uint8)
trX = loaded[16:].reshape((60000,28*28)).astype(float)
fd = open(os.path.join(data_dir,'train-labels.idx1-ubyte'))
loaded = np.fromfile(file=fd,dtype=np.uint8)
trY = loaded[8:].reshape((60000))
fd = open(os.path.join(data_dir,'t10k-images.idx3-ubyte'))
loaded = np.fromfile(file=fd,dtype=np.uint8)
teX = loaded[16:].reshape((10000,28*28)).astype(float)
fd = open(os.path.join(data_dir,'t10k-labels.idx1-ubyte'))
loaded = np.fromfile(file=fd,dtype=np.uint8)
teY = loaded[8:].reshape((10000))
trX = trX/255.
teX = teX/255.
trX = trX[:ntrain]
trY = trY[:ntrain]
teX = teX[:ntest]
teY = teY[:ntest]
if onehot:
trY = one_hot(trY, 10)
teY = one_hot(teY, 10)
else:
trY = np.asarray(trY)
teY = np.asarray(teY)
return trX,teX,trY,teY
| 25.729167 | 63 | 0.606478 |
acefe226d307248e008f06ba557a76adc16b8e94 | 3,540 | py | Python | read_EPIC_output/constants.py | ritviksahajpal/EPIC | 47bfd9ecbe130667bd5e22efded95a612ea3fbd2 | [
"MIT"
] | 3 | 2015-11-08T10:34:31.000Z | 2020-07-03T09:48:20.000Z | read_EPIC_output/constants.py | ritviksahajpal/EPIC | 47bfd9ecbe130667bd5e22efded95a612ea3fbd2 | [
"MIT"
] | null | null | null | read_EPIC_output/constants.py | ritviksahajpal/EPIC | 47bfd9ecbe130667bd5e22efded95a612ea3fbd2 | [
"MIT"
] | 4 | 2015-04-24T23:40:05.000Z | 2018-08-16T14:39:10.000Z | import os, sys, logging, errno, ast, psutil
from ConfigParser import SafeConfigParser
# Parse config file
parser = SafeConfigParser()
parser.read('../config_EPIC.txt')
###############################################################################
# Constants
#
#
###############################################################################
SKIP = 10
SKIP_SCN = 14
###############################################################################
# User modifiable values
#
#
###############################################################################
SOIL = 'ssurgo' # Should be same as SSURGO python code
SLLIST = parser.get('PARAMETERS','SLLIST')
PROJECT_NAME = parser.get('PROJECT','project_name')
TAG = parser.get('PROJECT','OUT_TAG')
START_YR = parser.getint('GET_OUTPUT','START_YR')
END_YR = parser.getint('GET_OUTPUT','END_YR')
ACN_PARAMS = ast.literal_eval(parser.get('GET_OUTPUT','ACN_PARAMS'))
ACM_PARAMS = ast.literal_eval(parser.get('GET_OUTPUT','ACM_PARAMS'))
ACY_PARAMS = ast.literal_eval(parser.get('GET_OUTPUT','ACY_PARAMS'))
DGN_PARAMS = ast.literal_eval(parser.get('GET_OUTPUT','DGN_PARAMS'))
ATG_PARAMS = ast.literal_eval(parser.get('GET_OUTPUT','ATG_PARAMS'))
ANN_PARAMS = ast.literal_eval(parser.get('GET_OUTPUT','ANN_PARAMS'))
SCN_PARAMS = ast.literal_eval(parser.get('GET_OUTPUT','SCN_PARAMS'))
GET_PARAMS = ast.literal_eval(parser.get('RUN_EPIC','EPICOUT_FLS'))
EXTR_YRS = ast.literal_eval(parser.get('GET_OUTPUT','EXTR_YRS'))
DO_FOLDER = parser.getboolean('PROJECT','DO_FOLDER')
FOLDER_PATH = parser.get('PROJECT','FOLDER_PATH')
dominant = parser.get('PARAMETERS','dominant')
OUT_TAG = parser.get('PROJECT', 'OUT_TAG')
base_dir = parser.get('PATHS','base_dir') + os.sep
epic_dir = base_dir + os.sep + 'EPIC' + os.sep + PROJECT_NAME + os.sep
sims_dir = epic_dir + os.sep + 'simulations' # Stores simulations
anly_dir = epic_dir + os.sep + 'analysis' + os.sep + TAG + os.sep
db_dir = anly_dir + os.sep + 'databases' # Store sqlite databases
csv_dir = anly_dir + os.sep + 'csvs' # Store EPIC output csvs
gis_dir = anly_dir + os.sep + 'gis' # Store gis analysis
sgo_dir = parser.get('PATHS', 'out_dir') + os.sep + parser.get('PROJECT', 'project_name') + os.sep + 'Data' + os.sep +\
SOIL + os.sep
IPCC_FILE = parser.get('POST_PROCESS', 'GIS_DIR') + os.sep + parser.get('POST_PROCESS', 'IPCC_carbon_2000_path') + os.sep \
+ parser.get('POST_PROCESS', 'IPCC_carbon_2000_file')
zone_data = parser.get('POST_PROCESS', 'GIS_DIR') + os.sep + parser.get('POST_PROCESS', 'zone_data')
# Maximum number of cpus to use at a time
max_threads = psutil.cpu_count() - 1
###############################################################################
#
#
#
###############################################################################
def make_dir_if_missing(d):
try:
os.makedirs(d)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
# Create directories
make_dir_if_missing(epic_dir)
make_dir_if_missing(anly_dir)
make_dir_if_missing(db_dir)
make_dir_if_missing(csv_dir)
make_dir_if_missing(gis_dir)
# Logging
LOG_FILENAME = epic_dir+os.sep+'Log_Read_'+TAG+'.txt'
logging.basicConfig(filename = LOG_FILENAME, level=logging.INFO,\
format='%(asctime)s %(levelname)s %(module)s - %(funcName)s: %(message)s',\
datefmt="%Y-%m-%d %H:%M:%S") # Logging levels are DEBUG, INFO, WARNING, ERROR, and CRITICAL
| 43.703704 | 123 | 0.595763 |
acefe29f0fe91b0e4476b98b6f4eed53ee6581e9 | 10,066 | py | Python | development/migrations/0005_auto_20171006_1700.py | damgambit/james-gattuso-realty | f1ef70a2d4e8d4cbc2d5774f92891560b89ec63b | [
"Apache-2.0"
] | null | null | null | development/migrations/0005_auto_20171006_1700.py | damgambit/james-gattuso-realty | f1ef70a2d4e8d4cbc2d5774f92891560b89ec63b | [
"Apache-2.0"
] | 4 | 2020-02-12T00:07:36.000Z | 2021-12-13T19:46:18.000Z | development/migrations/0005_auto_20171006_1700.py | damgambit/james-gattuso-realty | f1ef70a2d4e8d4cbc2d5774f92891560b89ec63b | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-06 17:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('development', '0004_auto_20171006_1450'),
]
operations = [
migrations.AlterField(
model_name='baystateauction',
name='address',
field=models.TextField(default='NULL'),
),
migrations.AlterField(
model_name='baystateauction',
name='city',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='baystateauction',
name='date',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='baystateauction',
name='day',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='baystateauction',
name='deposit',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='baystateauction',
name='state',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='baystateauction',
name='status',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='baystateauction',
name='time',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='commonwealthauction',
name='address',
field=models.TextField(default='NULL'),
),
migrations.AlterField(
model_name='harkinrealestate',
name='address',
field=models.TextField(default='NULL'),
),
migrations.AlterField(
model_name='harkinrealestate',
name='city',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='harkinrealestate',
name='date',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='harkinrealestate',
name='deposit',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='harkinrealestate',
name='state',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='harkinrealestate',
name='status',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='harkinrealestate',
name='time',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='harkinrealestate',
name='zipcode',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='landmarkauction',
name='auction_date',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='patriotauctioneer',
name='address',
field=models.TextField(default='NULL'),
),
migrations.AlterField(
model_name='patriotauctioneer',
name='city',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='patriotauctioneer',
name='date',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='patriotauctioneer',
name='state',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='patriotauctioneer',
name='status',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='patriotauctioneer',
name='terms',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='patriotauctioneer',
name='time',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='patriotauctioneer',
name='zipcode',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='pesco',
name='address',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='pesco',
name='city',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='pesco',
name='date',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='pesco',
name='state',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='pesco',
name='terms',
field=models.TextField(default='NULL'),
),
migrations.AlterField(
model_name='pesco',
name='time',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='pesco',
name='title',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='pesco',
name='zipcode',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='sullivanauctioneers',
name='address',
field=models.TextField(default='NULL'),
),
migrations.AlterField(
model_name='sullivanauctioneers',
name='date',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='sullivanauctioneers',
name='status',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='sullivanauctioneers',
name='terms',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='sullivanauctioneers',
name='url',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='tacheauctionandsales',
name='address',
field=models.TextField(default='NULL'),
),
migrations.AlterField(
model_name='tacheauctionandsales',
name='auction_date',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='tacheauctionandsales',
name='city',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='tacheauctionandsales',
name='deposit',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='tacheauctionandsales',
name='state',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='tacheauctionandsales',
name='status',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='tacheauctionandsales',
name='time',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='tacheauctionandsales',
name='zipcode',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='townauction',
name='address',
field=models.TextField(default='NULL'),
),
migrations.AlterField(
model_name='townauction',
name='auction_date',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='townauction',
name='city',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='townauction',
name='country',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='townauction',
name='deposit',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='townauction',
name='state',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='townauction',
name='status',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='townauction',
name='time',
field=models.CharField(default='NULL', max_length=100),
),
migrations.AlterField(
model_name='townauction',
name='zipcode',
field=models.IntegerField(default=0),
),
]
| 34.006757 | 67 | 0.55007 |
acefe38146b472091844080b75466b7de9cf750b | 113 | py | Python | exercicio46Contagem regressiva.py | adrianomdantas/Exercicios-Python | ef5025a186615258aec0cf35ed839fe49577d983 | [
"MIT"
] | null | null | null | exercicio46Contagem regressiva.py | adrianomdantas/Exercicios-Python | ef5025a186615258aec0cf35ed839fe49577d983 | [
"MIT"
] | null | null | null | exercicio46Contagem regressiva.py | adrianomdantas/Exercicios-Python | ef5025a186615258aec0cf35ed839fe49577d983 | [
"MIT"
] | null | null | null | from time import sleep
for cont in range(10, 0, -1):
print(cont, end=', ')
sleep(1)
print('0 \nFIM !!!')
| 18.833333 | 29 | 0.575221 |
acefe39440c80f9dc5d8c9a4c0290baf3a641236 | 4,875 | py | Python | sdk/deviceupdate/azure-iot-deviceupdate/samples/contentfactory.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 2,728 | 2015-01-09T10:19:32.000Z | 2022-03-31T14:50:33.000Z | sdk/deviceupdate/azure-iot-deviceupdate/samples/contentfactory.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 17,773 | 2015-01-05T15:57:17.000Z | 2022-03-31T23:50:25.000Z | sdk/deviceupdate/azure-iot-deviceupdate/samples/contentfactory.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 1,916 | 2015-01-19T05:05:41.000Z | 2022-03-31T19:36:44.000Z | from azure.iot.deviceupdate.models import ImportUpdateInput, ImportManifestMetadata, FileImportMetadata
from datetime import datetime, timedelta
from azure.storage.blob import BlobServiceClient, generate_blob_sas, PublicAccess, BlobSasPermissions
from samples.consts import FILE_NAME
import json
import tempfile
import hashlib
import base64
import os
import uuid
class ContentFactory:
def __init__(self, storage_name, storage_key, blob_container):
self._storage_name = storage_name
self._storage_key = storage_key
self._connection_string = \
f"DefaultEndpointsProtocol=https;AccountName={storage_name};AccountKey={storage_key};EndpointSuffix=core.windows.net"
self._blob_container = blob_container
def create_import_update(self, manufacturer, name, version):
payload_file_id = self._generate_storage_id()
payload_local_file = self._create_adu_payload_file(FILE_NAME, payload_file_id)
payload_file_size = self._get_file_size(payload_local_file)
payload_file_hash = self._get_file_hash(payload_local_file)
payload_url = self._upload_file(payload_local_file, payload_file_id)
import_manifest_file_id = self._generate_storage_id()
import_manifest_file = self._create_import_manifest(
manufacturer, name, version,
FILE_NAME, payload_file_size, payload_file_hash,
[{"DeviceManufacturer": manufacturer.lower(), "DeviceModel": name.lower()}],
import_manifest_file_id)
import_manifest_file_size = self._get_file_size(import_manifest_file)
import_manifest_file_hash = self._get_file_hash(import_manifest_file)
import_manifest_url = self._upload_file(import_manifest_file, import_manifest_file_id)
return self._create_import_body(import_manifest_url, import_manifest_file_size, import_manifest_file_hash,
FILE_NAME, payload_url)
def _create_adu_payload_file(self, filename, file_id):
content = {"Scenario": "DeviceUpdateClientSample",
"Timestamp": datetime.utcnow().strftime("%m/%d/%Y, %H:%M:%S")}
file_path = f"{tempfile.gettempdir()}\\{file_id}"
file = open(file_path, "w+")
file.write(json.dumps(content))
file.close()
return file_path
def _create_import_manifest(self, manufacturer, name, version, file_name, file_size, file_hash, compatibility_ids,
file_id):
content = {"UpdateId": {"Provider": manufacturer, "Name": name, "Version": version},
"CreatedDateTime": f"{datetime.utcnow().isoformat()}Z",
"Files": [{"FileName": file_name, "SizeInBytes": file_size, "Hashes": {"SHA256": file_hash}}],
"Compatibility": compatibility_ids, "ManifestVersion": "2.0", "InstalledCriteria": "1.2.3.4",
"UpdateType": "microsoft/swupdate:1"}
file_path = f"{tempfile.gettempdir()}\\{file_id}"
file = open(file_path, "w+")
file.write(json.dumps(content))
file.close()
return file_path
def _create_import_body(self, import_manifest_url, import_manifest_file_size, import_manifest_file_hash,
file_name, payload_url):
return ImportUpdateInput(
import_manifest=ImportManifestMetadata(
url=import_manifest_url,
size_in_bytes=import_manifest_file_size,
hashes={"SHA256": import_manifest_file_hash}),
files=[FileImportMetadata(filename=file_name, url=payload_url)])
def _get_file_size(self, file_path):
return os.path.getsize(file_path)
def _get_file_hash(self, file_path):
with open(file_path, "rb") as f:
bytes = f.read() # read entire file as bytes
return base64.b64encode(hashlib.sha256(bytes).digest()).decode("utf-8")
def _generate_storage_id(self):
return uuid.uuid4().hex
def _upload_file(self, file_path, storage_id):
blob_service_client = BlobServiceClient.from_connection_string(conn_str=self._connection_string)
try:
blob_service_client.create_container(self._blob_container, public_access=PublicAccess.Container)
except:
pass
blob_client = blob_service_client.get_blob_client(container=self._blob_container, blob=storage_id)
with open(file_path, "rb") as data:
blob_client.upload_blob(data)
token = generate_blob_sas(
account_name=self._storage_name,
account_key=self._storage_key,
container_name=self._blob_container,
blob_name=storage_id,
permission=BlobSasPermissions(read=True),
expiry=datetime.utcnow() + timedelta(hours=1))
return f"{blob_client.url}?{token}"
| 46.428571 | 129 | 0.683282 |
acefe49746bd9a2357e2283651cd8ff3eff630b4 | 10,984 | py | Python | tests/behaviour/connection/transaction/transaction_steps.py | jmsfltchr/typedb-client-python | 2007225e8800dc84872c70136f74c4504693359b | [
"Apache-2.0"
] | null | null | null | tests/behaviour/connection/transaction/transaction_steps.py | jmsfltchr/typedb-client-python | 2007225e8800dc84872c70136f74c4504693359b | [
"Apache-2.0"
] | null | null | null | tests/behaviour/connection/transaction/transaction_steps.py | jmsfltchr/typedb-client-python | 2007225e8800dc84872c70136f74c4504693359b | [
"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 concurrent.futures.thread import ThreadPoolExecutor
from functools import partial
from typing import Callable, List
from behave import *
from hamcrest import *
from grakn.common.exception import GraknClientException
from grakn.rpc.transaction import TransactionType, Transaction
from tests.behaviour.config.parameters import parse_transaction_type, parse_list, parse_bool
from tests.behaviour.context import Context
def for_each_session_open_transaction_of_type(context: Context, transaction_types: List[TransactionType]):
for session in context.sessions:
transactions = []
for transaction_type in transaction_types:
transaction = session.transaction(transaction_type)
transactions.append(transaction)
context.sessions_to_transactions[session] = transactions
# TODO: this is implemented as open(s) in some clients - get rid of that, simplify them
@step("session opens transaction of type: {transaction_type}")
@step("for each session, open transaction of type: {transaction_type}")
def step_impl(context: Context, transaction_type: str):
transaction_type = parse_transaction_type(transaction_type)
for_each_session_open_transaction_of_type(context, [transaction_type])
@step("for each session, open transaction of type")
@step("for each session, open transactions of type")
def step_impl(context: Context):
transaction_types = list(map(parse_transaction_type, parse_list(context.table)))
for_each_session_open_transaction_of_type(context, transaction_types)
def open_transactions_of_type_throws_exception(context: Context, transaction_types: List[TransactionType]):
for session in context.sessions:
for transaction_type in transaction_types:
try:
session.transaction(transaction_type)
assert False
except GraknClientException:
pass
@step("session open transaction of type; throws exception: {transaction_type}")
def step_impl(context: Context, transaction_type):
print("Running step: session open transaction of type; throws exception")
transaction_type = parse_transaction_type(transaction_type)
open_transactions_of_type_throws_exception(context, [transaction_type])
# TODO: transaction(s) in other implementations, simplify
@step("for each session, open transactions of type; throws exception")
def step_impl(context: Context):
open_transactions_of_type_throws_exception(context, list(map(lambda raw_type: parse_transaction_type(raw_type), parse_list(context.table))))
def for_each_session_transactions_are(context: Context, assertion: Callable[[Transaction], None]):
for session in context.sessions:
for transaction in context.sessions_to_transactions[session]:
assertion(transaction)
def assert_transaction_null(transaction: Transaction, is_null: bool):
assert_that(transaction is None, is_(is_null))
@step("session transaction is null: {is_null}")
@step("for each session, transaction is null: {is_null}")
@step("for each session, transactions are null: {is_null}")
def step_impl(context: Context, is_null):
is_null = parse_bool(is_null)
for_each_session_transactions_are(context, lambda tx: assert_transaction_null(tx, is_null))
def assert_transaction_open(transaction: Transaction, is_open: bool):
assert_that(transaction.is_open(), is_(is_open))
@step("session transaction is open: {is_open}")
@step("for each session, transaction is open: {is_open}")
@step("for each session, transactions are open: {is_open}")
def step_impl(context: Context, is_open):
is_open = parse_bool(is_open)
for_each_session_transactions_are(context, lambda tx: assert_transaction_open(tx, is_open))
@step("session transaction commits")
@step("transaction commits")
def step_impl(context: Context):
context.tx().commit()
@step("session transaction commits; throws exception")
@step("transaction commits; throws exception")
def step_impl(context: Context):
try:
context.tx().commit()
assert False
except GraknClientException:
pass
@step("transaction commits; throws exception containing \"{exception}\"")
def step_impl(context: Context, exception: str):
assert_that(calling(context.tx().commit), raises(GraknClientException, exception))
@step("for each session, transaction commits")
@step("for each session, transactions commit")
def step_impl(context: Context):
for session in context.sessions:
for transaction in context.sessions_to_transactions[session]:
transaction.commit()
@step("for each session, transaction commits; throws exception")
@step("for each session, transactions commit; throws exception")
def step_impl(context: Context):
for session in context.sessions:
for transaction in context.sessions_to_transactions[session]:
try:
transaction.commit()
assert False
except GraknClientException:
pass
# TODO: close(s) in other implementations - simplify
@step("for each session, transaction closes")
def step_impl(context: Context):
for session in context.sessions:
for transaction in context.sessions_to_transactions[session]:
transaction.close()
def for_each_session_transaction_has_type(context: Context, transaction_types: list):
for session in context.sessions:
transactions = context.sessions_to_transactions[session]
assert_that(transactions, has_length(len(transaction_types)))
transactions_iterator = iter(transactions)
for transaction_type in transaction_types:
assert_that(next(transactions_iterator).transaction_type(), is_(transaction_type))
# NOTE: behave ignores trailing colons in feature files
@step("for each session, transaction has type")
@step("for each session, transactions have type")
def step_impl(context: Context):
transaction_types = list(map(parse_transaction_type, parse_list(context.table)))
for_each_session_transaction_has_type(context, transaction_types)
# TODO: this is overcomplicated in some clients (has/have, transaction(s))
@step("for each session, transaction has type: {transaction_type}")
@step("session transaction has type: {transaction_type}")
def step_impl(context: Context, transaction_type):
transaction_type = parse_transaction_type(transaction_type)
for_each_session_transaction_has_type(context, [transaction_type])
##############################################
# sequential sessions, parallel transactions #
##############################################
# TODO: transaction(s) in other implementations - simplify
@step("for each session, open transactions in parallel of type")
def step_impl(context: Context):
types = list(map(parse_transaction_type, parse_list(context.table)))
assert_that(len(types), is_(less_than_or_equal_to(context.THREAD_POOL_SIZE)))
with ThreadPoolExecutor(max_workers=context.THREAD_POOL_SIZE) as executor:
for session in context.sessions:
context.sessions_to_transactions_parallel[session] = []
for type_ in types:
context.sessions_to_transactions_parallel[session].append(executor.submit(partial(session.transaction, type_)))
def for_each_session_transactions_in_parallel_are(context: Context, assertion: Callable[[Transaction], None]):
for session in context.sessions:
for future_transaction in context.sessions_to_transactions_parallel[session]:
assertion(future_transaction.result())
@step("for each session, transactions in parallel are null: {is_null}")
def step_impl(context: Context, is_null):
is_null = parse_bool(is_null)
for_each_session_transactions_in_parallel_are(context, lambda tx: assert_transaction_null(tx, is_null))
@step("for each session, transactions in parallel are open: {is_open}")
def step_impl(context: Context, is_open):
is_open = parse_bool(is_open)
for_each_session_transactions_in_parallel_are(context, lambda tx: assert_transaction_open(tx, is_open))
@step("for each session, transactions in parallel have type")
def step_impl(context: Context):
types = list(map(parse_transaction_type, parse_list(context.table)))
for session in context.sessions:
future_transactions = context.sessions_to_transactions_parallel[session]
assert_that(future_transactions, has_length(len(types)))
future_transactions_iter = iter(future_transactions)
for type_ in types:
assert_that(next(future_transactions_iter).result().transaction_type(), is_(type_))
############################################
# parallel sessions, parallel transactions #
############################################
def for_each_session_in_parallel_transactions_in_parallel_are(context: Context, assertion):
for future_session in context.sessions_parallel:
for future_transaction in context.sessions_parallel_to_transactions_parallel[future_session]:
assertion(future_transaction.result())
@step("for each session in parallel, transactions in parallel are null: {is_null}")
def step_impl(context: Context, is_null):
is_null = parse_bool(is_null)
for_each_session_in_parallel_transactions_in_parallel_are(context, lambda tx: assert_transaction_null(tx, is_null))
@step("for each session in parallel, transactions in parallel are open: {is_open}")
def step_impl(context: Context, is_open):
is_open = parse_bool(is_open)
for_each_session_in_parallel_transactions_in_parallel_are(context, lambda tx: assert_transaction_open(tx, is_open))
######################################
# transaction behaviour with queries #
######################################
@step("for each transaction, define query; throws exception containing \"{exception}\"")
def step_impl(context: Context, exception: str):
for session in context.sessions:
for transaction in context.sessions_to_transactions[session]:
try:
next(transaction.query().define(context.text), default=None)
assert False
except GraknClientException as e:
assert_that(exception, is_in(str(e)))
| 41.606061 | 144 | 0.742261 |
acefe625aba41bd75f6abedec717f6a0639d36f7 | 46,161 | py | Python | test/ext/test_baked.py | dpgaspar/sqlalchemy | db47859dca999b9d1679b513fe855e408d7d07c4 | [
"MIT"
] | 1 | 2020-07-15T15:00:42.000Z | 2020-07-15T15:00:42.000Z | test/ext/test_baked.py | dpgaspar/sqlalchemy | db47859dca999b9d1679b513fe855e408d7d07c4 | [
"MIT"
] | null | null | null | test/ext/test_baked.py | dpgaspar/sqlalchemy | db47859dca999b9d1679b513fe855e408d7d07c4 | [
"MIT"
] | null | null | null | import contextlib
import itertools
from sqlalchemy import bindparam
from sqlalchemy import event
from sqlalchemy import exc as sa_exc
from sqlalchemy import func
from sqlalchemy import literal_column
from sqlalchemy import testing
from sqlalchemy.ext import baked
from sqlalchemy.orm import aliased
from sqlalchemy.orm import backref
from sqlalchemy.orm import defaultload
from sqlalchemy.orm import exc as orm_exc
from sqlalchemy.orm import lazyload
from sqlalchemy.orm import Load
from sqlalchemy.orm import mapper
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session
from sqlalchemy.orm import subqueryload
from sqlalchemy.orm.query import Query
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import eq_
from sqlalchemy.testing import is_
from sqlalchemy.testing import is_not_
from sqlalchemy.testing import mock
from sqlalchemy.testing.assertsql import CompiledSQL
from test.orm import _fixtures
class BakedTest(_fixtures.FixtureTest):
run_setup_mappers = "once"
run_inserts = "once"
run_deletes = None
def setup(self):
self.bakery = baked.bakery()
class StateChangeTest(BakedTest):
@classmethod
def setup_mappers(cls):
User = cls.classes.User
mapper(User, cls.tables.users)
def _assert_cache_key(self, key, elements):
eq_(key, tuple(elem.__code__ for elem in elements))
def test_initial_key(self):
User = self.classes.User
session = Session()
def l1():
return session.query(User)
q1 = self.bakery(l1)
self._assert_cache_key(q1._cache_key, [l1])
eq_(q1.steps, [l1])
def test_inplace_add(self):
User = self.classes.User
session = Session()
def l1():
return session.query(User)
def l2(q):
return q.filter(User.name == bindparam("name"))
q1 = self.bakery(l1)
self._assert_cache_key(q1._cache_key, [l1])
eq_(q1.steps, [l1])
q2 = q1.add_criteria(l2)
is_(q2, q1)
self._assert_cache_key(q1._cache_key, [l1, l2])
eq_(q1.steps, [l1, l2])
def test_inplace_add_operator(self):
User = self.classes.User
session = Session()
def l1():
return session.query(User)
def l2(q):
return q.filter(User.name == bindparam("name"))
q1 = self.bakery(l1)
self._assert_cache_key(q1._cache_key, [l1])
q1 += l2
self._assert_cache_key(q1._cache_key, [l1, l2])
def test_chained_add(self):
User = self.classes.User
session = Session()
def l1():
return session.query(User)
def l2(q):
return q.filter(User.name == bindparam("name"))
q1 = self.bakery(l1)
q2 = q1.with_criteria(l2)
is_not_(q2, q1)
self._assert_cache_key(q1._cache_key, [l1])
self._assert_cache_key(q2._cache_key, [l1, l2])
def test_chained_add_operator(self):
User = self.classes.User
session = Session()
def l1():
return session.query(User)
def l2(q):
return q.filter(User.name == bindparam("name"))
q1 = self.bakery(l1)
q2 = q1 + l2
is_not_(q2, q1)
self._assert_cache_key(q1._cache_key, [l1])
self._assert_cache_key(q2._cache_key, [l1, l2])
class LikeQueryTest(BakedTest):
@classmethod
def setup_mappers(cls):
User = cls.classes.User
mapper(User, cls.tables.users)
def test_first_no_result(self):
User = self.classes.User
bq = self.bakery(lambda s: s.query(User))
bq += lambda q: q.filter(User.name == "asdf")
eq_(bq(Session()).first(), None)
def test_first_multiple_result(self):
User = self.classes.User
bq = self.bakery(lambda s: s.query(User.id))
bq += lambda q: q.filter(User.name.like("%ed%")).order_by(User.id)
eq_(bq(Session()).first(), (8,))
def test_one_or_none_no_result(self):
User = self.classes.User
bq = self.bakery(lambda s: s.query(User))
bq += lambda q: q.filter(User.name == "asdf")
eq_(bq(Session()).one_or_none(), None)
def test_one_or_none_result(self):
User = self.classes.User
bq = self.bakery(lambda s: s.query(User))
bq += lambda q: q.filter(User.name == "ed")
u1 = bq(Session()).one_or_none()
eq_(u1.name, "ed")
def test_one_or_none_multiple_result(self):
User = self.classes.User
bq = self.bakery(lambda s: s.query(User))
bq += lambda q: q.filter(User.name.like("%ed%"))
assert_raises_message(
orm_exc.MultipleResultsFound,
"Multiple rows were found for one_or_none()",
bq(Session()).one_or_none,
)
def test_one_no_result(self):
User = self.classes.User
bq = self.bakery(lambda s: s.query(User))
bq += lambda q: q.filter(User.name == "asdf")
assert_raises_message(
orm_exc.NoResultFound,
"No row was found for one()",
bq(Session()).one,
)
def test_one_result(self):
User = self.classes.User
bq = self.bakery(lambda s: s.query(User))
bq += lambda q: q.filter(User.name == "ed")
u1 = bq(Session()).one()
eq_(u1.name, "ed")
def test_one_multiple_result(self):
User = self.classes.User
bq = self.bakery(lambda s: s.query(User))
bq += lambda q: q.filter(User.name.like("%ed%"))
assert_raises_message(
orm_exc.MultipleResultsFound,
"Multiple rows were found for one()",
bq(Session()).one,
)
def test_get(self):
User = self.classes.User
bq = self.bakery(lambda s: s.query(User))
sess = Session()
def go():
u1 = bq(sess).get(7)
eq_(u1.name, "jack")
self.assert_sql_count(testing.db, go, 1)
u1 = sess.query(User).get(7) # noqa
def go():
u2 = bq(sess).get(7)
eq_(u2.name, "jack")
self.assert_sql_count(testing.db, go, 0)
def go():
u2 = bq(sess).get(8)
eq_(u2.name, "ed")
self.assert_sql_count(testing.db, go, 1)
def test_scalar(self):
User = self.classes.User
bq = self.bakery(lambda s: s.query(User.id))
sess = Session()
bq += lambda q: q.filter(User.id == 7)
eq_(bq(sess).scalar(), 7)
def test_count(self):
User = self.classes.User
bq = self.bakery(lambda s: s.query(User))
sess = Session()
eq_(bq(sess).count(), 4)
bq += lambda q: q.filter(User.id.in_([8, 9]))
eq_(bq(sess).count(), 2)
# original query still works
eq_(
set([(u.id, u.name) for u in bq(sess).all()]),
set([(8, "ed"), (9, "fred")]),
)
def test_count_with_bindparams(self):
User = self.classes.User
bq = self.bakery(lambda s: s.query(User))
sess = Session()
eq_(bq(sess).count(), 4)
bq += lambda q: q.filter(User.name == bindparam("uname"))
# calling with *args
eq_(bq(sess).params(uname="fred").count(), 1)
# with multiple params, the **kwargs will be used
bq += lambda q: q.filter(User.id == bindparam("anid"))
eq_(bq(sess).params(uname="fred", anid=9).count(), 1)
eq_(
# wrong id, so 0 results:
bq(sess).params(uname="fred", anid=8).count(),
0,
)
def test_get_pk_w_null(self):
"""test the re-implementation of logic to do get with IS NULL."""
class AddressUser(object):
pass
mapper(
AddressUser,
self.tables.users.outerjoin(self.tables.addresses),
properties={
"id": self.tables.users.c.id,
"address_id": self.tables.addresses.c.id,
},
)
bq = self.bakery(lambda s: s.query(AddressUser))
sess = Session()
def go():
u1 = bq(sess).get((10, None))
eq_(u1.name, "chuck")
self.assert_sql_count(testing.db, go, 1)
u1 = sess.query(AddressUser).get((10, None)) # noqa
def go():
u2 = bq(sess).get((10, None))
eq_(u2.name, "chuck")
self.assert_sql_count(testing.db, go, 0)
def test_get_includes_getclause(self):
# test issue #3597
User = self.classes.User
bq = self.bakery(lambda s: s.query(User))
for i in range(5):
sess = Session()
u1 = bq(sess).get(7)
eq_(u1.name, "jack")
sess.close()
eq_(len(bq._bakery), 2)
# simulate race where mapper._get_clause
# may be generated more than once
from sqlalchemy import inspect
del inspect(User).__dict__["_get_clause"]
for i in range(5):
sess = Session()
u1 = bq(sess).get(7)
eq_(u1.name, "jack")
sess.close()
eq_(len(bq._bakery), 4)
class ResultPostCriteriaTest(BakedTest):
@classmethod
def setup_mappers(cls):
User = cls.classes.User
Address = cls.classes.Address
Order = cls.classes.Order
mapper(
User,
cls.tables.users,
properties={
"addresses": relationship(
Address, order_by=cls.tables.addresses.c.id
),
"orders": relationship(Order, order_by=cls.tables.orders.c.id),
},
)
mapper(Address, cls.tables.addresses)
mapper(Order, cls.tables.orders)
@contextlib.contextmanager
def _fixture(self):
from sqlalchemy import event
User = self.classes.User
with testing.db.connect() as conn:
@event.listens_for(conn, "before_execute")
def before_execute(conn, clauseelement, multiparams, params):
assert "yes" in conn._execution_options
bq = self.bakery(lambda s: s.query(User.id).order_by(User.id))
sess = Session(conn)
yield sess, bq
def test_first(self):
with self._fixture() as (sess, bq):
result = bq(sess).with_post_criteria(
lambda q: q.execution_options(yes=True)
)
eq_(result.first(), (7,))
def test_iter(self):
with self._fixture() as (sess, bq):
result = bq(sess).with_post_criteria(
lambda q: q.execution_options(yes=True)
)
eq_(list(result)[0], (7,))
def test_spoiled(self):
with self._fixture() as (sess, bq):
result = bq.spoil()(sess).with_post_criteria(
lambda q: q.execution_options(yes=True)
)
eq_(list(result)[0], (7,))
def test_get(self):
User = self.classes.User
with self._fixture() as (sess, bq):
bq = self.bakery(lambda s: s.query(User))
result = bq(sess).with_post_criteria(
lambda q: q.execution_options(yes=True)
)
eq_(result.get(7), User(id=7))
class ResultTest(BakedTest):
__backend__ = True
@classmethod
def setup_mappers(cls):
User = cls.classes.User
Address = cls.classes.Address
Order = cls.classes.Order
mapper(
User,
cls.tables.users,
properties={
"addresses": relationship(
Address, order_by=cls.tables.addresses.c.id
),
"orders": relationship(Order, order_by=cls.tables.orders.c.id),
},
)
mapper(Address, cls.tables.addresses)
mapper(Order, cls.tables.orders)
def test_cachekeys_on_constructor(self):
User = self.classes.User
queue = [7, 8]
def fn(s):
return s.query(User.id).filter_by(id=queue.pop(0))
bq1 = self.bakery(fn, 7)
bq2 = self.bakery(fn, 8)
for i in range(3):
session = Session(autocommit=True)
eq_(bq1(session).all(), [(7,)])
eq_(bq2(session).all(), [(8,)])
def test_no_steps(self):
User = self.classes.User
bq = self.bakery(
lambda s: s.query(User.id, User.name).order_by(User.id)
)
for i in range(3):
session = Session(autocommit=True)
eq_(
bq(session).all(),
[(7, "jack"), (8, "ed"), (9, "fred"), (10, "chuck")],
)
def test_different_limits(self):
User = self.classes.User
bq = self.bakery(
lambda s: s.query(User.id, User.name).order_by(User.id)
)
bq += lambda q: q.limit(bindparam("limit")).offset(bindparam("offset"))
session = Session(autocommit=True)
for i in range(4):
for limit, offset, exp in [
(2, 1, [(8, "ed"), (9, "fred")]),
(3, 0, [(7, "jack"), (8, "ed"), (9, "fred")]),
(1, 2, [(9, "fred")]),
]:
eq_(bq(session).params(limit=limit, offset=offset).all(), exp)
def test_disable_on_session(self):
User = self.classes.User
canary = mock.Mock()
def fn1(s):
canary.fn1()
return s.query(User.id, User.name).order_by(User.id)
def fn2(q):
canary.fn2()
return q.filter(User.id == bindparam("id"))
def fn3(q):
canary.fn3()
return q
for x in range(3):
bq = self.bakery(fn1)
bq += fn2
sess = Session(autocommit=True, enable_baked_queries=False)
eq_(bq.add_criteria(fn3)(sess).params(id=7).all(), [(7, "jack")])
eq_(
canary.mock_calls,
[
mock.call.fn1(),
mock.call.fn2(),
mock.call.fn3(),
mock.call.fn1(),
mock.call.fn2(),
mock.call.fn3(),
mock.call.fn1(),
mock.call.fn2(),
mock.call.fn3(),
],
)
def test_spoiled_full_w_params(self):
User = self.classes.User
canary = mock.Mock()
def fn1(s):
canary.fn1()
return s.query(User.id, User.name).order_by(User.id)
def fn2(q):
canary.fn2()
return q.filter(User.id == bindparam("id"))
def fn3(q):
canary.fn3()
return q
for x in range(3):
bq = self.bakery(fn1)
bq += fn2
sess = Session(autocommit=True)
eq_(
bq.spoil(full=True).add_criteria(fn3)(sess).params(id=7).all(),
[(7, "jack")],
)
eq_(
canary.mock_calls,
[
mock.call.fn1(),
mock.call.fn2(),
mock.call.fn3(),
mock.call.fn1(),
mock.call.fn2(),
mock.call.fn3(),
mock.call.fn1(),
mock.call.fn2(),
mock.call.fn3(),
],
)
def test_spoiled_half_w_params(self):
User = self.classes.User
canary = mock.Mock()
def fn1(s):
canary.fn1()
return s.query(User.id, User.name).order_by(User.id)
def fn2(q):
canary.fn2()
return q.filter(User.id == bindparam("id"))
def fn3(q):
canary.fn3()
return q
bq = self.bakery(fn1)
bq += fn2
for x in range(3):
bq = self.bakery(fn1)
bq += fn2
sess = Session(autocommit=True)
eq_(
bq.spoil().add_criteria(fn3)(sess).params(id=7).all(),
[(7, "jack")],
)
eq_(
canary.mock_calls,
[
mock.call.fn1(),
mock.call.fn2(),
mock.call.fn3(),
mock.call.fn3(),
mock.call.fn3(),
],
)
def test_w_new_entities(self):
"""Test that the query can have its entities modified in
an arbitrary callable, and that this new entity list is preserved
when the query is invoked.
"""
User = self.classes.User
bq = self.bakery(lambda s: s.query(User.id, User.name))
bq += lambda q: q.from_self().with_entities(func.count(User.id))
for i in range(3):
session = Session(autocommit=True)
eq_(bq(session).all(), [(4,)])
def test_conditional_step(self):
"""Test a large series of conditionals and assert that
results remain correct between all of them within a series
of loops.
"""
User = self.classes.User
base_bq = self.bakery(lambda s: s.query(User.id, User.name))
base_bq += lambda q: q.order_by(User.id)
for i in range(4):
for cond1, cond2, cond3, cond4 in itertools.product(
*[(False, True) for j in range(4)]
):
bq = base_bq._clone()
if cond1:
bq += lambda q: q.filter(User.name != "jack")
if cond2:
bq += lambda q: q.join(User.addresses)
else:
bq += lambda q: q.outerjoin(User.addresses)
elif cond3:
bq += lambda q: q.filter(User.name.like("%ed%"))
else:
bq += lambda q: q.filter(User.name == "jack")
if cond4:
bq += lambda q: q.from_self().with_entities(
func.count(User.id)
)
sess = Session(autocommit=True)
result = bq(sess).all()
if cond4:
if cond1:
if cond2:
eq_(result, [(4,)])
else:
eq_(result, [(5,)])
elif cond3:
eq_(result, [(2,)])
else:
eq_(result, [(1,)])
else:
if cond1:
if cond2:
eq_(
result,
[(8, "ed"), (8, "ed"), (8, "ed"), (9, "fred")],
)
else:
eq_(
result,
[
(8, "ed"),
(8, "ed"),
(8, "ed"),
(9, "fred"),
(10, "chuck"),
],
)
elif cond3:
eq_(result, [(8, "ed"), (9, "fred")])
else:
eq_(result, [(7, "jack")])
sess.close()
def test_conditional_step_oneline(self):
User = self.classes.User
base_bq = self.bakery(lambda s: s.query(User.id, User.name))
base_bq += lambda q: q.order_by(User.id)
for i in range(4):
for cond1 in (False, True):
bq = base_bq._clone()
# we were using (filename, firstlineno) as cache key,
# which fails for this kind of thing!
bq += (
(lambda q: q.filter(User.name != "jack"))
if cond1
else (lambda q: q.filter(User.name == "jack"))
) # noqa
sess = Session(autocommit=True)
result = bq(sess).all()
if cond1:
eq_(result, [(8, u"ed"), (9, u"fred"), (10, u"chuck")])
else:
eq_(result, [(7, "jack")])
sess.close()
def test_to_query_query(self):
User = self.classes.User
Address = self.classes.Address
sub_bq = self.bakery(lambda s: s.query(User.name))
sub_bq += (
lambda q: q.filter(User.id == Address.user_id)
.filter(User.name == "ed")
.correlate(Address)
)
main_bq = self.bakery(lambda s: s.query(Address.id))
main_bq += lambda q: q.filter(sub_bq.to_query(q).exists())
main_bq += lambda q: q.order_by(Address.id)
sess = Session()
result = main_bq(sess).all()
eq_(result, [(2,), (3,), (4,)])
def test_to_query_session(self):
User = self.classes.User
Address = self.classes.Address
sub_bq = self.bakery(lambda s: s.query(User.name))
sub_bq += lambda q: q.filter(User.id == Address.user_id).correlate(
Address
)
main_bq = self.bakery(
lambda s: s.query(Address.id, sub_bq.to_query(s).scalar_subquery())
)
main_bq += lambda q: q.filter(
sub_bq.to_query(q).scalar_subquery() == "ed"
)
main_bq += lambda q: q.order_by(Address.id)
sess = Session()
result = main_bq(sess).all()
eq_(result, [(2, "ed"), (3, "ed"), (4, "ed")])
def test_to_query_args(self):
User = self.classes.User
sub_bq = self.bakery(lambda s: s.query(User.name))
q = Query([], None)
assert_raises_message(
sa_exc.ArgumentError,
"Given Query needs to be associated with a Session",
sub_bq.to_query,
q,
)
assert_raises_message(
TypeError,
"Query or Session object expected, got .*'int'.*",
sub_bq.to_query,
5,
)
def test_subquery_eagerloading(self):
User = self.classes.User
Address = self.classes.Address
Order = self.classes.Order
# Override the default bakery for one with a smaller size. This used to
# trigger a bug when unbaking subqueries.
self.bakery = baked.bakery(size=3)
base_bq = self.bakery(lambda s: s.query(User))
base_bq += lambda q: q.options(
subqueryload(User.addresses), subqueryload(User.orders)
)
base_bq += lambda q: q.order_by(User.id)
assert_result = [
User(
id=7,
addresses=[Address(id=1, email_address="jack@bean.com")],
orders=[Order(id=1), Order(id=3), Order(id=5)],
),
User(
id=8,
addresses=[
Address(id=2, email_address="ed@wood.com"),
Address(id=3, email_address="ed@bettyboop.com"),
Address(id=4, email_address="ed@lala.com"),
],
),
User(
id=9,
addresses=[Address(id=5)],
orders=[Order(id=2), Order(id=4)],
),
User(id=10, addresses=[]),
]
for i in range(4):
for cond1, cond2 in itertools.product(
*[(False, True) for j in range(2)]
):
bq = base_bq._clone()
sess = Session()
if cond1:
bq += lambda q: q.filter(User.name == "jack")
else:
bq += lambda q: q.filter(User.name.like("%ed%"))
if cond2:
ct = func.count(Address.id).label("count")
subq = (
sess.query(ct, Address.user_id)
.group_by(Address.user_id)
.having(ct > 2)
.subquery()
)
bq += lambda q: q.join(subq)
if cond2:
if cond1:
def go():
result = bq(sess).all()
eq_([], result)
self.assert_sql_count(testing.db, go, 1)
else:
def go():
result = bq(sess).all()
eq_(assert_result[1:2], result)
self.assert_sql_count(testing.db, go, 3)
else:
if cond1:
def go():
result = bq(sess).all()
eq_(assert_result[0:1], result)
self.assert_sql_count(testing.db, go, 3)
else:
def go():
result = bq(sess).all()
eq_(assert_result[1:3], result)
self.assert_sql_count(testing.db, go, 3)
sess.close()
def test_subqueryload_post_context(self):
User = self.classes.User
Address = self.classes.Address
assert_result = [
User(
id=7, addresses=[Address(id=1, email_address="jack@bean.com")]
)
]
self.bakery = baked.bakery(size=3)
bq = self.bakery(lambda s: s.query(User))
bq += lambda q: q.options(subqueryload(User.addresses))
bq += lambda q: q.order_by(User.id)
bq += lambda q: q.filter(User.name == bindparam("name"))
sess = Session()
def set_params(q):
return q.params(name="jack")
# test that the changes we make using with_post_criteria()
# are also applied to the subqueryload query.
def go():
result = bq(sess).with_post_criteria(set_params).all()
eq_(assert_result, result)
self.assert_sql_count(testing.db, go, 2)
@testing.fixture()
def before_compile_nobake_fixture(self):
@event.listens_for(Query, "before_compile", retval=True)
def _modify_query(query):
query = query.enable_assertions(False)
return query
yield
event.remove(Query, "before_compile", _modify_query)
def test_subqueryload_post_context_w_cancelling_event(
self, before_compile_nobake_fixture
):
User = self.classes.User
Address = self.classes.Address
assert_result = [
User(
id=7, addresses=[Address(id=1, email_address="jack@bean.com")]
)
]
self.bakery = baked.bakery(size=3)
bq = self.bakery(lambda s: s.query(User))
bq += lambda q: q.options(subqueryload(User.addresses))
bq += lambda q: q.order_by(User.id)
bq += lambda q: q.filter(User.name == bindparam("name"))
sess = Session()
def set_params(q):
return q.params(name="jack")
# test that the changes we make using with_post_criteria()
# are also applied to the subqueryload query.
def go():
result = bq(sess).with_post_criteria(set_params).all()
eq_(assert_result, result)
self.assert_sql_count(testing.db, go, 2)
class LazyLoaderTest(testing.AssertsCompiledSQL, BakedTest):
run_setup_mappers = "each"
@testing.fixture
def modify_query_fixture(self):
def set_event(bake_ok):
event.listen(
Query,
"before_compile",
_modify_query,
retval=True,
bake_ok=bake_ok,
)
return m1
m1 = mock.Mock()
def _modify_query(query):
m1(query.column_descriptions[0]["entity"])
query = query.enable_assertions(False).filter(
literal_column("1") == 1
)
return query
yield set_event
event.remove(Query, "before_compile", _modify_query)
def _o2m_fixture(self, lazy="select", **kw):
User = self.classes.User
Address = self.classes.Address
mapper(
User,
self.tables.users,
properties={
"addresses": relationship(
Address,
order_by=self.tables.addresses.c.id,
lazy=lazy,
**kw
)
},
)
mapper(Address, self.tables.addresses)
return User, Address
def _o2m_twolevel_fixture(self, lazy="select", **kw):
User = self.classes.User
Address = self.classes.Address
Dingaling = self.classes.Dingaling
mapper(
User,
self.tables.users,
properties={
"addresses": relationship(
Address,
order_by=self.tables.addresses.c.id,
lazy=lazy,
**kw
)
},
)
mapper(
Address,
self.tables.addresses,
properties={"dingalings": relationship(Dingaling, lazy=lazy)},
)
mapper(Dingaling, self.tables.dingalings)
return User, Address, Dingaling
def _m2o_fixture(self):
User = self.classes.User
Address = self.classes.Address
mapper(User, self.tables.users)
mapper(
Address,
self.tables.addresses,
properties={"user": relationship(User)},
)
return User, Address
def test_no_cache_for_event(self, modify_query_fixture):
m1 = modify_query_fixture(False)
User, Address = self._o2m_fixture()
sess = Session()
u1 = sess.query(User).filter(User.id == 7).first()
u1.addresses
eq_(m1.mock_calls, [mock.call(User), mock.call(Address)])
sess.expire(u1, ["addresses"])
u1.addresses
eq_(
m1.mock_calls,
[mock.call(User), mock.call(Address), mock.call(Address)],
)
def test_cache_ok_for_event(self, modify_query_fixture):
m1 = modify_query_fixture(True)
User, Address = self._o2m_fixture()
sess = Session()
u1 = sess.query(User).filter(User.id == 7).first()
u1.addresses
eq_(m1.mock_calls, [mock.call(User), mock.call(Address)])
sess.expire(u1, ["addresses"])
u1.addresses
eq_(m1.mock_calls, [mock.call(User), mock.call(Address)])
def test_unsafe_unbound_option_cancels_bake(self):
User, Address, Dingaling = self._o2m_twolevel_fixture(lazy="joined")
class SubDingaling(Dingaling):
pass
mapper(SubDingaling, None, inherits=Dingaling)
lru = Address.dingalings.property._lazy_strategy._bakery(
lambda q: None
)._bakery
l1 = len(lru)
for i in range(5):
sess = Session()
u1 = (
sess.query(User)
.options(
defaultload(User.addresses).lazyload(
Address.dingalings.of_type(aliased(SubDingaling))
)
)
.first()
)
for ad in u1.addresses:
ad.dingalings
l2 = len(lru)
eq_(l1, 0)
eq_(l2, 1)
def test_unsafe_bound_option_cancels_bake(self):
User, Address, Dingaling = self._o2m_twolevel_fixture(lazy="joined")
class SubDingaling(Dingaling):
pass
mapper(SubDingaling, None, inherits=Dingaling)
lru = Address.dingalings.property._lazy_strategy._bakery(
lambda q: None
)._bakery
l1 = len(lru)
for i in range(5):
sess = Session()
u1 = (
sess.query(User)
.options(
Load(User)
.defaultload(User.addresses)
.lazyload(
Address.dingalings.of_type(aliased(SubDingaling))
)
)
.first()
)
for ad in u1.addresses:
ad.dingalings
l2 = len(lru)
eq_(l1, 0)
eq_(l2, 1)
def test_safe_unbound_option_allows_bake(self):
User, Address, Dingaling = self._o2m_twolevel_fixture(lazy="joined")
lru = Address.dingalings.property._lazy_strategy._bakery(
lambda q: None
)._bakery
l1 = len(lru)
for i in range(5):
sess = Session()
u1 = (
sess.query(User)
.options(
defaultload(User.addresses).lazyload(Address.dingalings)
)
.first()
)
for ad in u1.addresses:
ad.dingalings
l2 = len(lru)
eq_(l1, 0)
eq_(l2, 2)
def test_safe_bound_option_allows_bake(self):
User, Address, Dingaling = self._o2m_twolevel_fixture(lazy="joined")
lru = Address.dingalings.property._lazy_strategy._bakery(
lambda q: None
)._bakery
l1 = len(lru)
for i in range(5):
sess = Session()
u1 = (
sess.query(User)
.options(
Load(User)
.defaultload(User.addresses)
.lazyload(Address.dingalings)
)
.first()
)
for ad in u1.addresses:
ad.dingalings
l2 = len(lru)
eq_(l1, 0)
eq_(l2, 2)
def test_baked_lazy_loading_relationship_flag_true(self):
self._test_baked_lazy_loading_relationship_flag(True)
def test_baked_lazy_loading_relationship_flag_false(self):
self._test_baked_lazy_loading_relationship_flag(False)
def _test_baked_lazy_loading_relationship_flag(self, flag):
User, Address = self._o2m_fixture(bake_queries=flag)
sess = Session()
u1 = sess.query(User).first()
from sqlalchemy.orm import Query
canary = mock.Mock()
# I would think Mock can do this but apparently
# it cannot (wrap / autospec don't work together)
real_compile_context = Query._compile_context
def _my_compile_context(*arg, **kw):
if arg[0].column_descriptions[0]["entity"] is Address:
canary()
return real_compile_context(*arg, **kw)
with mock.patch.object(Query, "_compile_context", _my_compile_context):
u1.addresses
sess.expire(u1)
u1.addresses
if flag:
eq_(canary.call_count, 1)
else:
eq_(canary.call_count, 2)
def test_baked_lazy_loading_option_o2m(self):
User, Address = self._o2m_fixture()
self._test_baked_lazy_loading(set_option=True)
def test_baked_lazy_loading_mapped_o2m(self):
User, Address = self._o2m_fixture(lazy="baked_select")
self._test_baked_lazy_loading(set_option=False)
def _test_baked_lazy_loading(self, set_option):
User, Address = self.classes.User, self.classes.Address
base_bq = self.bakery(lambda s: s.query(User))
if set_option:
base_bq += lambda q: q.options(lazyload(User.addresses))
base_bq += lambda q: q.order_by(User.id)
assert_result = self.static.user_address_result
for i in range(4):
for cond1, cond2 in itertools.product(
*[(False, True) for j in range(2)]
):
bq = base_bq._clone()
sess = Session()
if cond1:
bq += lambda q: q.filter(User.name == "jack")
else:
bq += lambda q: q.filter(User.name.like("%ed%"))
if cond2:
ct = func.count(Address.id).label("count")
subq = (
sess.query(ct, Address.user_id)
.group_by(Address.user_id)
.having(ct > 2)
.subquery()
)
bq += lambda q: q.join(subq)
if cond2:
if cond1:
def go():
result = bq(sess).all()
eq_([], result)
self.assert_sql_count(testing.db, go, 1)
else:
def go():
result = bq(sess).all()
eq_(assert_result[1:2], result)
self.assert_sql_count(testing.db, go, 2)
else:
if cond1:
def go():
result = bq(sess).all()
eq_(assert_result[0:1], result)
self.assert_sql_count(testing.db, go, 2)
else:
def go():
result = bq(sess).all()
eq_(assert_result[1:3], result)
self.assert_sql_count(testing.db, go, 3)
sess.close()
def test_baked_lazy_loading_m2o(self):
User, Address = self._m2o_fixture()
base_bq = self.bakery(lambda s: s.query(Address))
base_bq += lambda q: q.options(lazyload(Address.user))
base_bq += lambda q: q.order_by(Address.id)
assert_result = self.static.address_user_result
for i in range(4):
for cond1 in (False, True):
bq = base_bq._clone()
sess = Session()
if cond1:
bq += lambda q: q.filter(
Address.email_address == "jack@bean.com"
)
else:
bq += lambda q: q.filter(
Address.email_address.like("ed@%")
)
if cond1:
def go():
result = bq(sess).all()
eq_(assert_result[0:1], result)
self.assert_sql_count(testing.db, go, 2)
else:
def go():
result = bq(sess).all()
eq_(assert_result[1:4], result)
self.assert_sql_count(testing.db, go, 2)
sess.close()
def test_useget_cancels_eager(self):
"""test that a one to many lazyload cancels the unnecessary
eager many-to-one join on the other side."""
User = self.classes.User
Address = self.classes.Address
mapper(User, self.tables.users)
mapper(
Address,
self.tables.addresses,
properties={
"user": relationship(
User,
lazy="joined",
backref=backref("addresses", lazy="baked_select"),
)
},
)
sess = Session()
u1 = sess.query(User).filter(User.id == 8).one()
def go():
eq_(u1.addresses[0].user, u1)
self.assert_sql_execution(
testing.db,
go,
CompiledSQL(
"SELECT addresses.id AS addresses_id, addresses.user_id AS "
"addresses_user_id, addresses.email_address AS "
"addresses_email_address FROM addresses WHERE :param_1 = "
"addresses.user_id",
{"param_1": 8},
),
)
def test_useget_cancels_eager_propagated_present(self):
"""test that a one to many lazyload cancels the unnecessary
eager many-to-one join on the other side, even when a propagated
option is present."""
User = self.classes.User
Address = self.classes.Address
mapper(User, self.tables.users)
mapper(
Address,
self.tables.addresses,
properties={
"user": relationship(
User,
lazy="joined",
backref=backref("addresses", lazy="baked_select"),
)
},
)
from sqlalchemy.orm.interfaces import MapperOption
class MyBogusOption(MapperOption):
propagate_to_loaders = True
sess = Session()
u1 = (
sess.query(User)
.options(MyBogusOption())
.filter(User.id == 8)
.one()
)
def go():
eq_(u1.addresses[0].user, u1)
self.assert_sql_execution(
testing.db,
go,
CompiledSQL(
"SELECT addresses.id AS addresses_id, addresses.user_id AS "
"addresses_user_id, addresses.email_address AS "
"addresses_email_address FROM addresses WHERE :param_1 = "
"addresses.user_id",
{"param_1": 8},
),
)
def test_simple_lazy_clause_no_race_on_generate(self):
User, Address = self._o2m_fixture()
expr1, paramdict1 = (
User.addresses.property._lazy_strategy._simple_lazy_clause
)
# delete the attr, as though a concurrent thread is also generating it
del User.addresses.property._lazy_strategy._simple_lazy_clause
expr2, paramdict2 = (
User.addresses.property._lazy_strategy._simple_lazy_clause
)
eq_(paramdict1, paramdict2)
# additional tests:
# 1. m2m w lazyload
# 2. o2m lazyload where m2o backrefs have an eager load, test
# that eager load is canceled out
# 3. uselist = False, uselist=False assertion
# assert that the integration style illustrated in the dogpile.cache
# example works w/ baked
class CustomIntegrationTest(testing.AssertsCompiledSQL, BakedTest):
run_setup_mappers = "each"
def _o2m_fixture(self, lazy="select", **kw):
User = self.classes.User
Address = self.classes.Address
mapper(
User,
self.tables.users,
properties={
"addresses": relationship(
Address,
order_by=self.tables.addresses.c.id,
lazy=lazy,
**kw
)
},
)
mapper(Address, self.tables.addresses)
return User, Address
def _query_fixture(self):
from sqlalchemy.orm.query import Query, _generative
class CachingQuery(Query):
cache = {}
@_generative
def set_cache_key(self, key):
self._cache_key = key
def __iter__(self):
super_ = super(CachingQuery, self)
if hasattr(self, "_cache_key"):
return self.get_value(
createfunc=lambda: list(super_.__iter__())
)
else:
return super_.__iter__()
def _execute_and_instances(self, context):
super_ = super(CachingQuery, self)
if context.query is not self and hasattr(self, "_cache_key"):
return self.get_value(
createfunc=lambda: list(
super_._execute_and_instances(context)
)
)
else:
return super_._execute_and_instances(context)
def get_value(self, createfunc):
if self._cache_key in self.cache:
return iter(self.cache[self._cache_key])
else:
self.cache[self._cache_key] = retval = createfunc()
return iter(retval)
return Session(query_cls=CachingQuery)
def _option_fixture(self):
from sqlalchemy.orm.interfaces import MapperOption
class RelationshipCache(MapperOption):
propagate_to_loaders = True
def process_query_conditionally(self, query):
if query._current_path:
query._cache_key = "user7_addresses"
def _generate_cache_key(self, path):
return None
return RelationshipCache()
def test_non_baked(self):
User, Address = self._o2m_fixture()
sess = self._query_fixture()
q = sess._query_cls
eq_(q.cache, {})
q = sess.query(User).filter(User.id == 7).set_cache_key("user7")
eq_(q.all(), [User(id=7, addresses=[Address(id=1)])])
eq_(q.cache, {"user7": [User(id=7, addresses=[Address(id=1)])]})
eq_(q.all(), [User(id=7, addresses=[Address(id=1)])])
def test_use_w_baked(self):
User, Address = self._o2m_fixture()
sess = self._query_fixture()
q = sess._query_cls
eq_(q.cache, {})
base_bq = self.bakery(lambda s: s.query(User))
base_bq += lambda q: q.filter(User.id == 7)
base_bq += lambda q: q.set_cache_key("user7")
eq_(base_bq(sess).all(), [User(id=7, addresses=[Address(id=1)])])
eq_(q.cache, {"user7": [User(id=7, addresses=[Address(id=1)])]})
eq_(base_bq(sess).all(), [User(id=7, addresses=[Address(id=1)])])
def test_plain_w_baked_lazyload(self):
User, Address = self._o2m_fixture()
opt = self._option_fixture()
sess = self._query_fixture()
q = sess._query_cls
eq_(q.cache, {})
q = sess.query(User).filter(User.id == 7).options(opt)
u = q.first()
eq_(u.addresses, [Address(id=1)])
eq_(q.cache, {"user7_addresses": [Address(id=1)]})
sess.close()
# ensure caching logic works after query has been baked
q.cache.clear()
u = q.first()
eq_(u.addresses, [Address(id=1)])
eq_(q.cache, {"user7_addresses": [Address(id=1)]})
| 28.922932 | 79 | 0.50625 |
acefe66f06ddef21df631932dcc339e1329a6f40 | 8,505 | py | Python | matador/crystal/elastic.py | dquigley-warwick/matador | 729e97efb0865c4fff50af87555730ff4b7b6d91 | [
"MIT"
] | 24 | 2020-01-21T21:40:44.000Z | 2022-03-23T13:37:18.000Z | matador/crystal/elastic.py | dquigley-warwick/matador | 729e97efb0865c4fff50af87555730ff4b7b6d91 | [
"MIT"
] | 234 | 2020-02-03T15:56:58.000Z | 2022-03-29T21:36:45.000Z | matador/crystal/elastic.py | dquigley-warwick/matador | 729e97efb0865c4fff50af87555730ff4b7b6d91 | [
"MIT"
] | 15 | 2019-11-29T11:33:32.000Z | 2021-11-02T09:14:08.000Z | # coding: utf-8
# Distributed under the terms of the MIT License.
""" This submodule contains functionality to fit E(V) equations
of state to ab initio data, primarily to calculate bulk moduli.
"""
import re
import numpy as np
from matador.utils.chem_utils import eV_PER_ANGSTROM_CUBED_TO_GPa
from matador.plotting.plotting import plotting_function
def get_equation_of_state(seed, plot=False):
""" Extract E(V) data from CASTEP files and perform
fits for the equation of state and bulk moduli.
Parameters:
seed (str/dict): filename or scraped dictionary to fit.
Keyword arguments:
plot (bool): plot the fitted EoS.
"""
if isinstance(seed, dict):
results = seed
else:
from matador.scrapers import castep2dict
results, success = castep2dict(seed, intermediates=True, db=False)
if not success:
raise RuntimeError(results)
volumes = []
energies = []
for snapshot in results['intermediates']:
volumes.append(snapshot['cell_volume'])
energies.append(snapshot['total_energy'])
volumes.append(results['cell_volume'])
energies.append(results['total_energy'])
volumes = np.asarray(volumes)
energies = np.asarray(energies)
if len(volumes) < 3:
raise RuntimeError('Seed {} does not contain enough energies vs volumes to fit a bulk modulus')
energies = energies[np.argsort(volumes)]
volumes = np.sort(volumes)
E_0 = np.min(energies)
V_0 = volumes[np.argmin(energies)]
types_of_fit = EquationOfState.__subclasses__()
results['eos'] = []
results['summary'] = []
probes_all = []
curves = []
labels = []
for eos_type in types_of_fit:
eos = eos_type(E_0, V_0)
eos.fit(volumes, energies)
results['summary'].append(eos_type.__name__ + '\n')
results['summary'].append('fitting parameters = {d[0]:.6f}, {d[1]:.6f}\n'.format(d=eos.fit_parameters))
results['summary'].append('rrrmsd = {:10.10f} %\n'.format(eos.rrmsd))
results['summary'].append('bulk modulus = {d[0]:.6f} +/- {d[1]:.6f} GPa\n'
.format(d=(eos.bulk_modulus, eos.bulk_modulus_err)))
results['summary'].append(80*'-' + '\n')
probes = np.linspace(min(volumes), max(volumes), num=100)
fitted_curve = eos.evaluate(probes, *eos.popt)
results['eos'].append(eos)
probes_all.append(probes)
curves.append(fitted_curve)
name = eos_type.__name__.replace('EOS', '')
label = '-'.join(re.findall('[A-Z][^A-Z]*', name))
label += " {eos.bulk_modulus:3.1f}±{eos.bulk_modulus_err:3.1f} GPa"
labels.append(label)
if plot:
try:
plot_volume_curve(probes_all, labels, curves, volumes, energies, seed)
except Exception:
print("There was a problem making the bulk modulus plot.")
return results
class EquationOfState:
""" Abstract class for E(V) isothermal equations of state. Used to
perform least squares fitting to arbitrary functional form.
Attributes:
E_0 (float): equilbirium lattice energy.
V_0 (float): equilibrium lattice volume.
popt (:obj:`list` of :obj:`float`): fitting parameters for
particular EOS.
p0 (:obj:`list` of :obj:`float`): initial guess at fitting parameters.
rrmsd (float): relative root mean square deviation of fit, as
defined by [2].
"""
def __init__(self, E_0, V_0):
""" Set up EOS ready for fit.
Parameters:
E_0 (float): equilibrium energy.
V_0 (float): equilibrium volume.
"""
self.E_0 = E_0
self.V_0 = V_0
self.popt = None
self.rrmsd = None
self.p0 = [0.01, 1]
def fit(self, volumes, energies):
""" Perform a least squares fit on the volumes and energies.
Parameters:
volumes (:obj:`list` of :obj:`float`): calculated volumes.
energies (:obj:`list` of :obj:`float`): calculated energies.
"""
from scipy import optimize
self.popt, _ = optimize.leastsq(self.residual, self.p0, args=(volumes, energies))
self.rrmsd = np.sqrt(np.sum(((energies - self.evaluate(volumes, *self.popt)) / energies)**2) / (len(energies) - 1))
def evaluate(self, V, B, C):
""" Evaluate the EOS.
Parameters:
V (:obj:`list` of :obj:`float`): volumes at which to test.
B (float): the first fitting parameter defined in [2].
C (float): the second fitting parameter defined in [2].
"""
raise NotImplementedError
def residual(self, guess, V, E):
""" Calculate the resdiual of the current fit.
Parameters:
guess (:obj:`list` of :obj:`float`): interim fitting parameters.
V (:obj:`list` of :obj:`float`): volumes at which to test.
E (:obj:`list` of :obj:`float`): energies at the volumes V.
"""
return E - self.evaluate(V, *guess)
@property
def bulk_modulus(self):
""" Returns the bulk modulus predicted by the fit. """
bulk_modulus = self.get_bulk_modulus()
return bulk_modulus
@property
def bulk_modulus_err(self):
""" Returns the estimated error on the bulk modulus. """
return self.bulk_modulus * self.rrmsd
@property
def fit_parameters(self):
""" Return list of final fitting parameters. """
return self.popt
class BirchMurnaghanEulerianEOS(EquationOfState):
""" Implements the 3rd order Birch-Murnaghan EOS [1] for given data, as
provided by Ref. [2] in the Eulerian frame.
[1]. Francis Birch, Phys. Rev. 71 809 (1947)
DOI: 10.1103/PhysRev.71.809.
[2]. K. Latimer, S. Dwaraknath, K. Mathew, D. Winston, K. A. Persson,
npj Comput. Mater. 2018 41 2018, 4, 40.
DOI: 10.1038/s41524-018-0091-x.
"""
def evaluate(self, V, B, C):
nu = V / self.V_0
nu = (nu**(-2.0/3.0) - 1)
return self.E_0 + B * self.V_0 * (nu**2 + 0.5 * C * nu**3)
def get_bulk_modulus(self):
""" Return the bulk modulus of this particular fit. """
if self.popt is None:
raise RuntimeError('No fit performed.')
return self.popt[0] * 8.0/9.0 * eV_PER_ANGSTROM_CUBED_TO_GPa
class PoirerTarantolaEOS(EquationOfState):
""" Implements the logarithmic Poirer-Tarantola [3] for given data, as
provided by Ref. [2].
[2]. K. Latimer, S. Dwaraknath, K. Mathew, D. Winston, K. A. Persson,
npj Comput. Mater. 2018 41 2018, 4, 40.
DOI: 10.1038/s41524-018-0091-x.
[3]. J. Poirer, A. Tarantola, Phys. Earth Planet. Inter. 109 1-8 (1998).
"""
def evaluate(self, V, B, C):
nu = V / self.V_0
return self.E_0 + B * self.V_0 * np.log(nu)**2 * (3 - C*np.log(nu))
def get_bulk_modulus(self):
""" Return the bulk modulus of this particular fit. """
if self.popt is None:
raise RuntimeError('No fit performed.')
return self.popt[0] * 6 * eV_PER_ANGSTROM_CUBED_TO_GPa
class TaitEOS(EquationOfState):
""" Implements the exponential Tait EOS [4] for given data, as
provided by Ref. [2].
[2]. K. Latimer, S. Dwaraknath, K. Mathew, D. Winston, K. A. Persson,
npj Comput. Mater. 2018 41 2018, 4, 40.
DOI: 10.1038/s41524-018-0091-x.
[4]. J. H. Dymond, R. Malhotra, Int. J. Thermophys. 9 941-951 (1988).
"""
def evaluate(self, V, B, C):
nu = V / self.V_0
return self.E_0 + (B*self.V_0 / C) * (nu - 1 + (1/C) * (np.exp(C*(1-nu)) - 1))
def get_bulk_modulus(self):
""" Return the bulk modulus of this particular fit. """
if self.popt is None:
raise RuntimeError('No fit performed.')
return self.popt[0] * eV_PER_ANGSTROM_CUBED_TO_GPa
@plotting_function
def plot_volume_curve(probes_all, labels, curves, volumes, energies, seed):
""" Plot all fitted EOS curves for this structure and save as a PDF. """
import matplotlib.pyplot as plt
_, ax = plt.subplots()
ax.set_ylabel('Total energy (eV)')
ax.set_xlabel('Cell volume ($\\AA^3$)')
ls = 2*['--', '-.', ':']
for ind, probe in enumerate(probes_all):
ax.plot(probes_all[ind], curves[ind], label=labels[ind], ls=ls[ind])
ax.plot(volumes, energies, marker='o', label='DFT data')
ax.legend(loc=0)
plt.savefig(seed + '.pdf')
| 33.222656 | 123 | 0.608936 |
acefe6d45489f96318af21601390fd5ec592fd78 | 1,236 | py | Python | futu/common/err.py | szmile2008/py-futu-api | efe4af5deedf7e030dfe3ee78817f89191821753 | [
"Apache-2.0"
] | null | null | null | futu/common/err.py | szmile2008/py-futu-api | efe4af5deedf7e030dfe3ee78817f89191821753 | [
"Apache-2.0"
] | null | null | null | futu/common/err.py | szmile2008/py-futu-api | efe4af5deedf7e030dfe3ee78817f89191821753 | [
"Apache-2.0"
] | 1 | 2022-03-26T08:59:12.000Z | 2022-03-26T08:59:12.000Z | # -*- coding: utf-8 -*-
from collections import namedtuple
_ErrField = namedtuple('_ErrField', ('code', 'text'))
class Err:
"""
0 ~ 999 通用错误
1000 ~ 1999 行情错误
2000 ~ 2999 交易错误
"""
Ok = _ErrField(0, 'Ok')
ConnectionLost = _ErrField(1, 'Connection lost')
Timeout = _ErrField(2, 'Timeout')
NotConnected = _ErrField(3, 'Not connected')
PacketDataErr = _ErrField(4, 'Packet data error')
ConnectionClosed = _ErrField(5, 'Connection closed')
ParamErr = _ErrField(6, 'Parameter error')
NotSetRSAFile = _ErrField(7, 'Conn is encrypted, but no RSA private key file is set. Call SysConfig.set_init_rsa_file.')
RsaErr = _ErrField(8, 'RSA key is invalid')
NoNeedUnlock = _ErrField(2000, 'No need to unlock, because REAL trade is not supported in this market')
def _make_kwargs_str(**kwargs):
msg = ''
if len(kwargs) > 0:
msg = ':'
for k, v in kwargs.items():
msg += ' {0}={1};'.format(k, v)
return msg
def make_msg(err, msg_=None, **kwargs):
msg_ = '' if msg_ is None else ': ' + msg_
if isinstance(err, str):
return err + msg_ + _make_kwargs_str(**kwargs)
else:
return err.text + msg_ + _make_kwargs_str(**kwargs) | 30.9 | 124 | 0.628641 |
acefe6e5b4b9d356e4805b7d86849d993f7743ec | 838 | py | Python | indy_common/test/types/test_claim_def_sub_schema.py | Rob-S/indy-node | 0aefbda62c5a7412d7e03b2fb9795c500ea67e9f | [
"Apache-2.0"
] | 627 | 2017-07-06T12:38:08.000Z | 2022-03-30T13:18:43.000Z | indy_common/test/types/test_claim_def_sub_schema.py | Rob-S/indy-node | 0aefbda62c5a7412d7e03b2fb9795c500ea67e9f | [
"Apache-2.0"
] | 580 | 2017-06-29T17:59:57.000Z | 2022-03-29T21:37:52.000Z | indy_common/test/types/test_claim_def_sub_schema.py | Rob-S/indy-node | 0aefbda62c5a7412d7e03b2fb9795c500ea67e9f | [
"Apache-2.0"
] | 704 | 2017-06-29T17:45:34.000Z | 2022-03-30T07:08:58.000Z | import pytest
from indy_common.types import ClientClaimDefSubmitOperation, ClaimDefField
from collections import OrderedDict
from plenum.common.messages.fields import ConstantField, LimitedLengthStringField, TxnSeqNoField
EXPECTED_ORDERED_FIELDS = OrderedDict([
("type", ConstantField),
("ref", TxnSeqNoField),
("data", ClaimDefField),
('signature_type', LimitedLengthStringField),
('tag', LimitedLengthStringField),
])
def test_has_expected_fields():
actual_field_names = OrderedDict(
ClientClaimDefSubmitOperation.schema).keys()
assert actual_field_names == EXPECTED_ORDERED_FIELDS.keys()
def test_has_expected_validators():
schema = dict(ClientClaimDefSubmitOperation.schema)
for field, validator in EXPECTED_ORDERED_FIELDS.items():
assert isinstance(schema[field], validator)
| 32.230769 | 96 | 0.778043 |
acefe7969a4dd5ab8fc08069bbb08894bcc9b62c | 292 | py | Python | src/utils/generic_utils.py | alilakda/Eva | e3d447f81e1e47172e21758c059ad6f5ee21ffa4 | [
"Apache-2.0"
] | 1 | 2019-11-06T03:30:08.000Z | 2019-11-06T03:30:08.000Z | src/utils/generic_utils.py | alilakda/Eva | e3d447f81e1e47172e21758c059ad6f5ee21ffa4 | [
"Apache-2.0"
] | 1 | 2019-11-18T03:09:56.000Z | 2019-11-18T03:09:56.000Z | src/utils/generic_utils.py | asrayousuf/Eva | f652e5d398556055490c146f37e7a2d7a9d091f3 | [
"Apache-2.0"
] | null | null | null |
def validate_kwargs(kwargs, allowed_kwargs,
error_message='Keyword argument not understood:'):
"""Checks that all keyword arguments are in the set of allowed keys."""
for kwarg in kwargs:
if kwarg not in allowed_kwargs:
raise TypeError(error_message, kwarg) | 41.714286 | 73 | 0.705479 |
acefe85201c7429c39ffbb5ab5dc45381d995a3a | 487 | py | Python | example_d/market/get_taker_buy_sell_vol.py | rmdpadula/Binance_Futures | 1297a0a0be7b396e5a3980c8ae68f18ca492cb9a | [
"MIT"
] | 1 | 2021-04-12T09:15:01.000Z | 2021-04-12T09:15:01.000Z | example_d/market/get_taker_buy_sell_vol.py | rmdpadula/Binance_Futures | 1297a0a0be7b396e5a3980c8ae68f18ca492cb9a | [
"MIT"
] | null | null | null | example_d/market/get_taker_buy_sell_vol.py | rmdpadula/Binance_Futures | 1297a0a0be7b396e5a3980c8ae68f18ca492cb9a | [
"MIT"
] | null | null | null | from binance_d import RequestClient
from binance_d.constant.test import *
from binance_d.base.printobject import *
request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key)
# result = request_client.get_liquidation_orders()
result = request_client.get_taker_buy_sell_vol(pair="BTCUSD", contractType="CURRENT_QUARTER", period='1d')
# print("======= Get Taker Buy/Sell Ratio =======")
# PrintMix.print_data(result)
# print("==========================================")
| 37.461538 | 106 | 0.708419 |
acefe93f606e34f236e5c4cb841503926e31e9f8 | 4,451 | py | Python | src/openalea/container/id_generator.py | revesansparole/oacontainer | 066a15b8b1b22f857bf25ed443c5f39f4cbefb3e | [
"MIT"
] | null | null | null | src/openalea/container/id_generator.py | revesansparole/oacontainer | 066a15b8b1b22f857bf25ed443c5f39f4cbefb3e | [
"MIT"
] | null | null | null | src/openalea/container/id_generator.py | revesansparole/oacontainer | 066a15b8b1b22f857bf25ed443c5f39f4cbefb3e | [
"MIT"
] | null | null | null | # -*- python -*-
# -*- coding: utf-8 -*-
#
# IdGenerator : graph package
#
# Copyright or Copr. 2006 INRIA - CIRAD - INRA
#
# File author(s): Jerome Chopard <jerome.chopard@sophia.inria.fr>
# Fred Theveny <theveny@cirad.fr>
#
# Distributed under the Cecill-C License.
# See accompanying file LICENSE.txt or copy at
# http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html
#
# VPlants WebSite : https://gforge.inria.fr/projects/vplants/
#
""" This module provide a generator for id numbers.
"""
class IdMaxGenerator(object):
"""Simple id generator based on returning an id
always superior to the highest fetched id.
"""
def __init__(self):
self._id_max = None
self.clear()
def clear(self):
""" Reset the generator.
"""
self._id_max = 0
def get_id(self, pid=None):
"""Generate a new id.
args:
- pid (int): potential id to use, if None (default) generate a new id
"""
if pid is None:
ret = self._id_max
self._id_max += 1
return ret
else:
if pid < self._id_max:
raise IndexError("id %d already used" % pid)
self._id_max = max(self._id_max, pid + 1)
return pid
def release_id(self, pid):
"""Mark the given id as available
args:
- pid (int): id to release
"""
del pid
class IdSetGenerator(object):
"""Keep a set of available ids.
"""
def __init__(self):
self._id_max = None
self._available_ids = set()
self.clear()
def clear(self):
""" Reset the generator.
"""
self._id_max = 0
self._available_ids.clear()
def get_id(self, pid=None):
"""Generate a new id.
args:
- pid (int): potential id to use, if None (default) generate a new id
"""
if pid is None:
if len(self._available_ids) == 0:
ret = self._id_max
self._id_max += 1
return ret
else:
return self._available_ids.pop()
else:
if pid >= self._id_max:
self._available_ids.update(xrange(self._id_max, pid))
self._id_max = pid + 1
return pid
else:
try:
self._available_ids.remove(pid)
return pid
except KeyError:
raise IndexError("id %d already used" % pid)
def release_id(self, pid):
"""Mark the given id as available
args:
- pid (int): id to release
"""
if pid > self._id_max:
raise IndexError("id out of range")
elif pid in self._available_ids:
raise IndexError("id currently not in use")
else:
self._available_ids.add(pid)
class IdGenerator(IdSetGenerator):
"""Alias to define a default id generator.
"""
pass
class IdListGenerator(object):
"""Keep a list of unused ids instead of a set.
"""
def __init__(self):
self._id_max = None
self._id_list = []
self.clear()
def clear(self):
""" Reset the generator.
"""
self._id_max = 0
del self._id_list[:]
def get_id(self, pid=None):
if pid is None:
if len(self._id_list) == 0:
ret = self._id_max
self._id_max += 1
return ret
else:
return self._id_list.pop()
else:
if pid >= self._id_max:
self._id_list.extend(range(self._id_max, pid))
self._id_max = pid + 1
return pid
else:
try:
ind = self._id_list.index(pid)
del self._id_list[ind]
return pid
except ValueError:
raise IndexError("id %d already used" % pid)
def release_id(self, pid):
"""Mark the given id as available
args:
- pid (int): id to release
"""
if pid > self._id_max:
raise IndexError("id out of range")
elif pid in self._id_list:
raise IndexError("id currently not in use")
else:
self._id_list.append(pid)
| 26.494048 | 78 | 0.510896 |
acefe9d202647c626680850304746f1aa61de85e | 95 | py | Python | examples/test.py | hyeonukbhin/bootstrap-flask | 42bd57dbd5ac802a13afd6bbd9e5136a4b1e8f5b | [
"BSD-3-Clause"
] | null | null | null | examples/test.py | hyeonukbhin/bootstrap-flask | 42bd57dbd5ac802a13afd6bbd9e5136a4b1e8f5b | [
"BSD-3-Clause"
] | null | null | null | examples/test.py | hyeonukbhin/bootstrap-flask | 42bd57dbd5ac802a13afd6bbd9e5136a4b1e8f5b | [
"BSD-3-Clause"
] | null | null | null | ss = '{0:>30}'.format('전혀 그렇지 않음') + "s"
sss = '{0:>30}'.format('전혀 그렇지 않음') + "sss"
print(sss) | 31.666667 | 43 | 0.515789 |
acefea0a06c4bb051c28e066992f9960b47c947b | 52,158 | py | Python | pythran/tests/test_ndarray.py | lsix/pythran | dc2b0544c49a8f9fc278fc91de32b0cc97a3ef40 | [
"BSD-3-Clause"
] | 1 | 2020-07-21T10:01:20.000Z | 2020-07-21T10:01:20.000Z | pythran/tests/test_ndarray.py | lsix/pythran | dc2b0544c49a8f9fc278fc91de32b0cc97a3ef40 | [
"BSD-3-Clause"
] | null | null | null | pythran/tests/test_ndarray.py | lsix/pythran | dc2b0544c49a8f9fc278fc91de32b0cc97a3ef40 | [
"BSD-3-Clause"
] | null | null | null | from pythran.tests import TestEnv
from pythran.typing import NDArray, Tuple, List
import numpy
import unittest
try:
numpy.float128
has_float128 = True
except AttributeError:
has_float128 = False
@TestEnv.module
class TestNdarray(TestEnv):
def test_ndarray_intc(self):
self.run_test('def ndarray_intc(a): import numpy as np; return np.intc(a), np.array([a, a], dtype=np.intc)',
numpy.intc(5),
ndarray_intc=[numpy.intc])
def test_ndarray_uintc(self):
self.run_test('def ndarray_uintc(a): import numpy as np; return np.uintc(a), np.array([a, a], dtype=np.uintc)',
numpy.uintc(5),
ndarray_uintc=[numpy.uintc])
def test_ndarray_intp(self):
self.run_test('def ndarray_intp(a): import numpy as np; return np.intp(a), np.array([a, a], dtype=np.intp)',
numpy.intp(-5),
ndarray_intp=[numpy.intp])
def test_ndarray_uintp(self):
self.run_test('def ndarray_uintp(a): import numpy as np; return np.uintp(a), np.array([a, a], dtype=np.uintp)',
numpy.uintp(5),
ndarray_uintp=[numpy.uintp])
def test_ndarray_real_attr_read(self):
self.run_test('def ndarray_real_attr_read(a): return a.real + 1',
numpy.arange(100, dtype=numpy.complex128).reshape((10, 10)),
ndarray_real_attr_read=[NDArray[complex, :, :]])
def test_ndarray_imag_attr_read(self):
self.run_test('def ndarray_imag_attr_read(a): return a.imag + 1',
1j * numpy.arange(10, dtype=numpy.complex128),
ndarray_imag_attr_read=[NDArray[complex, :]])
def test_ndarray_real_attr_read_complex64(self):
self.run_test('def ndarray_real_attr_read_complex64(a): return a.real + 1',
numpy.arange(100, dtype=numpy.complex64).reshape((10, 10)),
ndarray_real_attr_read_complex64=[NDArray[numpy.complex64, :, :]])
def test_ndarray_imag_attr_read_complex64(self):
self.run_test('def ndarray_imag_attr_read_complex64(a): return a.imag + 1',
1j * numpy.arange(10, dtype=numpy.complex64),
ndarray_imag_attr_read_complex64=[NDArray[numpy.complex64, :]])
def test_ndarray_real_attr_write(self):
self.run_test('def ndarray_real_attr_write(a): a.real = 1 ; return a',
numpy.arange(100, dtype=numpy.complex128).reshape((10, 10)),
ndarray_real_attr_write=[NDArray[complex, :, :]])
def test_ndarray_imag_attr_write(self):
self.run_test('def ndarray_imag_attr_write(a): a.imag = 1 ; return a',
1j * numpy.arange(10, dtype=numpy.complex128),
ndarray_imag_attr_write=[NDArray[complex, :]])
def test_ndarray_real_fun_read(self):
self.run_test('def ndarray_real_fun_read(a): import numpy as np ; return np.real(a)[1:]',
numpy.arange(100, dtype=numpy.complex128).reshape((10, 10)),
ndarray_real_fun_read=[NDArray[complex, :, :]])
def test_ndarray_imag_fun_read(self):
self.run_test('def ndarray_imag_fun_read(a): import numpy as np ; return - np.imag(a)',
1j * numpy.arange(10, dtype=numpy.complex128),
ndarray_imag_fun_read=[NDArray[complex, :]])
def test_numpy_augassign0(self):
self.run_test('def numpy_augassign0(a): a+=1; return a',
numpy.arange(100).reshape((10, 10)),
numpy_augassign0=[NDArray[int, :, :]])
def test_numpy_augassign1(self):
self.run_test('def numpy_augassign1(a): a*=2; return a',
numpy.arange(100).reshape((10, 10)),
numpy_augassign1=[NDArray[int, :, :]])
def test_numpy_augassign2(self):
self.run_test('def numpy_augassign2(a): a-=2; return a',
numpy.arange(100).reshape((10, 10)),
numpy_augassign2=[NDArray[int, :, :]])
def test_numpy_augassign3(self):
self.run_test('def numpy_augassign3(a): a//=2; return a',
numpy.arange(100).reshape((10, 10)),
numpy_augassign3=[NDArray[int, :, :]])
def test_numpy_augassign4(self):
self.run_test('def numpy_augassign4(a): a|=2; return a',
numpy.arange(100).reshape((10, 10)),
numpy_augassign4=[NDArray[int, :, :]])
def test_numpy_augassign5(self):
self.run_test('def numpy_augassign5(a): a&=2; return a',
numpy.arange(100).reshape((10, 10)),
numpy_augassign5=[NDArray[int, :, :]])
def test_numpy_augassign6(self):
self.run_test('def helper(x): x //= 2; x+=3\ndef numpy_augassign6(a): a&=2; helper(a); return a',
numpy.arange(100).reshape((10, 10)),
numpy_augassign6=[NDArray[int, :, :]])
def test_numpy_faugassign0(self):
self.run_test('def numpy_faugassign0(a): a[a>5]+=1; return a',
numpy.arange(100),
numpy_faugassign0=[NDArray[int, :]])
def test_numpy_faugassign1(self):
self.run_test('def numpy_faugassign1(a): a[a>3]*=2; return a',
numpy.arange(100),
numpy_faugassign1=[NDArray[int, :]])
def test_numpy_faugassign2(self):
self.run_test('def numpy_faugassign2(a): a[a>30]-=2; return a',
numpy.arange(100),
numpy_faugassign2=[NDArray[int, :]])
def test_numpy_faugassign3(self):
self.run_test('def numpy_faugassign3(a): a[a<40]//=2; return a',
numpy.arange(100),
numpy_faugassign3=[NDArray[int, :]])
def test_numpy_faugassign4(self):
self.run_test('def numpy_faugassign4(a): a[a<4]|=2; return a',
numpy.arange(100),
numpy_faugassign4=[NDArray[int, :]])
def test_numpy_faugassign5(self):
self.run_test('def numpy_faugassign5(a): a[a>8]&=2; return a',
numpy.arange(100),
numpy_faugassign5=[NDArray[int, :]])
def test_broadcast0(self):
self.run_test('def numpy_broadcast0(a): a[0] = 1 ; return a',
numpy.arange(100).reshape((10, 10)),
numpy_broadcast0=[NDArray[int, :, :]])
def test_broadcast1(self):
self.run_test('def numpy_broadcast1(a): a[1:-1] = 1 ; return a',
numpy.arange(100).reshape((10, 10)),
numpy_broadcast1=[NDArray[int, :, :]])
def test_broadcast2(self):
self.run_test('def numpy_broadcast2(a): a[1:-1,1:-1] = 1 ; return a',
numpy.arange(100).reshape((10, 10)),
numpy_broadcast2=[NDArray[int, :, :]])
def test_broadcast3(self):
self.run_test('def numpy_broadcast3(a): a[1:-1,1] = 1 ; return a',
numpy.arange(100).reshape((10, 10)),
numpy_broadcast3=[NDArray[int, :, :]])
def test_broadcast4(self):
self.run_test('def numpy_broadcast4(a): a[:,1,1] = 1 ; return a',
numpy.arange(100).reshape((5,5,4)),
numpy_broadcast4=[NDArray[int, :, :, :]])
def test_broadcast5(self):
self.run_test('def numpy_broadcast5(a): import numpy as np ; return a + np.array([1,2,3,4])',
numpy.arange(20).reshape((5,4)),
numpy_broadcast5=[NDArray[int, :, :]])
def test_extended_slicing0(self):
self.run_test("def numpy_extended_slicing0(a): return a[2,1:-1]",
numpy.arange(100).reshape((10, 10)),
numpy_extended_slicing0=[NDArray[int, :, :]])
def test_extended_slicing1(self):
self.run_test("def numpy_extended_slicing1(a): return a[1:-1,2]",
numpy.arange(100).reshape((10, 10)),
numpy_extended_slicing1=[NDArray[int, :, :]])
def test_extended_slicing2(self):
self.run_test("def numpy_extended_slicing2(a): return a[2,1:-1]",
numpy.arange(30).reshape((3,5,2)),
numpy_extended_slicing2=[NDArray[int, :, :, :]])
def test_extended_slicing3(self):
self.run_test("def numpy_extended_slicing3(a): return a[1:-1,2]",
numpy.arange(30).reshape((3,5,2)),
numpy_extended_slicing3=[NDArray[int, :,:,:]])
def test_extended_slicing4(self):
self.run_test("def numpy_extended_slicing4(a): return a[1:-1,2:-2]",
numpy.arange(100).reshape((10, 10)),
numpy_extended_slicing4=[NDArray[int, :, :]])
def test_extended_slicing5(self):
self.run_test("def numpy_extended_slicing5(a): return a[1:-1]",
numpy.arange(100).reshape((10, 10)),
numpy_extended_slicing5=[NDArray[int, :, :]])
def test_extended_slicing6(self):
self.run_test("def numpy_extended_slicing6(a): return a[1:-1,2:-2, 3:-3]",
numpy.arange(5*6*7).reshape((5,6,7)),
numpy_extended_slicing6=[NDArray[int,:,:,:]])
def test_extended_slicing7(self):
self.run_test("def numpy_extended_slicing7(a): return a[1:-1, 2, 1]",
numpy.arange(120).reshape((3,5,4,2)),
numpy_extended_slicing7=[NDArray[int,:,:,:,:]])
def test_extended_slicing8(self):
self.run_test("def numpy_extended_slicing8(a): return a[1:-1,2:-2, 1:2]",
numpy.arange(60).reshape((3,5,4)),
numpy_extended_slicing8=[NDArray[int,:,:,:]])
def test_extended_slicing9(self):
self.run_test("def numpy_extended_slicing9(a): return a[1:-1, 2, 1, 1:2]",
numpy.arange(120).reshape((3,5,2,4)),
numpy_extended_slicing9=[NDArray[int,:,:,:,:]])
def test_extended_slicing10(self):
self.run_test("def numpy_extended_slicing10(a): return a[1, 2, 1:-1]",
numpy.arange(120).reshape((3,5,4,2)),
numpy_extended_slicing10=[NDArray[int,:,:,:,:]])
def test_extended_slicing11(self):
self.run_test("def numpy_extended_slicing11(a): return a[1, 2, 1:-1, 1]",
numpy.arange(120).reshape((3,5,4,2)),
numpy_extended_slicing11=[NDArray[int,:,:,:,:]])
def test_numpy_mask0(self):
self.run_test("def numpy_mask0(n): import numpy ; return n[n>0][ n[n>0] < 1]",
numpy.cos(numpy.arange(10)),
numpy_mask0=[NDArray[float, :]])
def test_numpy_bool(self):
self.run_test("def numpy_bool(n): import numpy ; return numpy.ones(n, bool)",
5,
numpy_bool=[int])
def test_numpy_int(self):
self.run_test("def numpy_int(n): import numpy ; return numpy.ones(n, int)",
5,
numpy_int=[int])
def test_numpy_float(self):
self.run_test("def numpy_float(n): import numpy ; return numpy.ones(n, float)",
5,
numpy_float=[int])
def test_numpy_int16(self):
self.run_test("def numpy_int16(n): import numpy ; return numpy.ones(n, numpy.int16)",
5,
numpy_int16=[int])
def test_numpy_uint16(self):
self.run_test("def numpy_uint16(n): import numpy ; return numpy.ones(n, numpy.uint16)",
5,
numpy_uint16=[int])
def test_numpy_uint64(self):
self.run_test("def numpy_uint64(n): import numpy ; return numpy.ones(n, numpy.uint64)",
5,
numpy_uint64=[int])
def test_numpy_np_float(self):
""" Check dtype == numpy.float for numpy array. """
self.run_test("""
def numpy_np_float(n):
import numpy
return numpy.ones(n, numpy.float)""",
5,
numpy_np_float=[int])
def test_numpy_complex(self):
self.run_test("def numpy_complex(n): import numpy ; return numpy.ones(n, numpy.complex)",
5,
numpy_complex=[int])
def test_numpy_complex64(self):
self.run_test("def numpy_complex64(n): import numpy ; return numpy.ones(n, numpy.complex64)",
5,
numpy_complex64=[int])
def test_numpy_double(self):
self.run_test("def numpy_double(n): import numpy ; return numpy.ones(n, numpy.double)",
5,
numpy_double=[int])
def test_numpy_complex_export(self):
self.run_test("def numpy_complex_export(a): import numpy ; return numpy.sum(a)",
numpy.array([1+1j]),
numpy_complex_export=[NDArray[complex, :]])
def test_assign_gsliced_array(self):
self.run_test("""def assign_gsliced_array():
import numpy as np;
a = np.array([[[1,2],[3,4]],[[5,6],[7,8]]])
b = np.array([[[9,10],[11,12]],[[13,14],[15,16]]])
a[:,:] = b[:,:]
return a,b;""", assign_gsliced_array=[])
def test_assign_sliced_array(self):
self.run_test("""def assign_sliced_array():
import numpy as np;
a = np.array([1,2,3]);
b = np.array([1,2,3]);
c=a[1:]
c=b[1:]
b[2] = -1;
return c;""", assign_sliced_array=[])
def test_index_array_0(self):
self.run_test('''
def index_array_0(n):
import numpy
a = numpy.arange(n)
return a[numpy.array([1, 0])]''',
10,
index_array_0=[int])
def test_index_array_1(self):
self.run_test('''
def index_array_1(n):
import numpy
a = numpy.arange(n * 3).reshape(3, n)
return a[numpy.array([0, 1, 0, 2])]''',
10,
index_array_1=[int])
def test_filter_array_0(self):
self.run_test('def filter_array_0(n): import numpy ; a = numpy.zeros(n) ; return a[a>1]',
10,
filter_array_0=[int])
def test_filter_array_1(self):
self.run_test('def filter_array_1(n): import numpy ; a = numpy.arange(n) ; return a[a>4]',
10,
filter_array_1=[int])
def test_filter_array_2(self):
self.run_test('def filter_array_2(n): import numpy ; a = numpy.arange(n) ; return (a+a)[a>4]',
10,
filter_array_2=[int])
def test_filter_array_3(self):
self.run_test('def filter_array_3(n): import numpy ; a = numpy.arange(n) ; return (-a)[a>4]',
10,
filter_array_3=[int])
@unittest.skip("filtering a slice")
def test_filter_array_4(self):
self.run_test('def filter_array_4(n): import numpy ; a = numpy.arange(n) ; return a[1:-1][a[1:-1]>4]',
10,
filter_array_4=[int])
@unittest.skip("filtering a slice")
def test_filter_array_5(self):
self.run_test('def filter_array_5(n): import numpy ; a = numpy.arange(n) ; return (a[1:-1])[a[1:-1]>4]',
10,
filter_array_5=[int])
def test_assign_ndarray(self):
code = """
def assign_ndarray(t):
import numpy as np;
a = np.array([1,2,3]);
b = np.array([1,2,3]);
if t:
c = a;
else:
c=b;
if t:
c=b;
b[0] = -1;
return c;"""
self.run_test(code,
1,
assign_ndarray=[int])
def test_bitwise_nan_bool(self):
self.run_test("def np_bitwise_nan_bool(a): import numpy as np ; return ~(a<5)", numpy.arange(10), np_bitwise_nan_bool=[NDArray[int, :]])
def test_gslice0(self):
self.run_test("def np_gslice0(a): import numpy as np; return a[1:9,5:7]", numpy.array(range(10*9)).reshape((10,9)), np_gslice0=[NDArray[int, :, :]])
def test_gslice1(self):
self.run_test("def np_gslice1(a): import numpy as np ; return a[1:9,0:1, 3:6]", numpy.array(range(10*9*8)).reshape((10,9,8)), np_gslice1=[NDArray[int, :, :, :]])
def test_gslice2(self):
self.run_test("def np_gslice2(a): import numpy as np ; return a[:,0:1, 3:6]", numpy.array(range(10*9*8)).reshape((10,9,8)), np_gslice2=[NDArray[int, :, :, :]])
def test_gslice3(self):
self.run_test("def np_gslice3(a): import numpy as np ; return a[:-1,0:-1, -3:7]", numpy.array(range(10*9*8)).reshape((10,9,8)), np_gslice3=[NDArray[int, :, :, :]])
def test_gslice4(self):
self.run_test("def np_gslice4(a): import numpy as np ; return a[1,0:-1, -3:7]", numpy.array(range(10*9*8)).reshape((10,9,8)), np_gslice4=[NDArray[int, :, :, :]])
def test_gslice5(self):
self.run_test("def np_gslice5(a): import numpy as np ; return a[1,0:-1, 7]", numpy.array(range(10*9*8)).reshape((10,9,8)), np_gslice5=[NDArray[int, :, :, :]])
def test_gslice6(self):
self.run_test("def np_gslice6(a): import numpy as np ; return a[:-1, :][1:,:]", numpy.array(range(10*9*8)).reshape((10,9,8)), np_gslice6=[NDArray[int, :,:,:]])
def test_iexpr0(self):
self.run_test("def np_iexpr0(a,i): return a[i][0,0]", numpy.array(range(10*9*8)).reshape(10,9,8), 0, np_iexpr0=[NDArray[int, :,:,:], int])
def test_iexpr1(self):
self.run_test("def np_iexpr1(a,i): return a[i,0][0]", numpy.array(range(10*9*8)).reshape(10,9,8), 0, np_iexpr1=[NDArray[int, :,:,:], int])
def test_iexpr2(self):
self.run_test("def np_iexpr2(a,m): a[m==False] = 1; return a", numpy.arange(10).reshape(5,2), numpy.arange(10).reshape(5,2), np_iexpr2=[NDArray[int, :,:], NDArray[int, :,:]])
def test_item0(self):
self.run_test("def np_item0(a): return a.item(3)", numpy.array([[3, 1, 7],[2, 8, 3],[8, 5, 3]]), np_item0=[NDArray[int, :,: ]])
def test_item1(self):
self.run_test("def np_item1(a): return a.item(7)", numpy.array([[3, 1, 7],[2, 8, 3],[8, 5, 3]]), np_item1=[NDArray[int, :,: ]])
def test_item2(self):
self.run_test("def np_item2(a): return a.item((0,1))",numpy.array([[3, 1, 7],[2, 8, 3],[8, 5, 3]]), np_item2=[NDArray[int, :,: ]])
def test_item3(self):
self.run_test("def np_item3(a): return a.item((2,2))", numpy.array([[3, 1, 7],[2, 8, 3],[8, 5, 3]]), np_item3=[NDArray[int, :,: ]])
def test_item4(self):
self.run_test("def np_item4(a): return a.item(-2)", numpy.array([[3, 1, 7],[2, 8, 3],[8, 5, 3]]), np_item4=[NDArray[int, :,: ]])
def test_acces1D_(self):
self.run_test("def np_acces1D_(a): return a[1]", numpy.array([1,2,3]), np_acces1D_=[NDArray[int, :]])
def test_accesSimple_(self):
self.run_test("def np_accesSimple_(a): return a[1]", numpy.array([[1,2],[3,4]]), np_accesSimple_=[NDArray[int, :,: ]])
def test_accesMultiple_(self):
self.run_test("def np_accesMultiple_(a): return a[1,0]", numpy.array([[1,2],[3,4]]), np_accesMultiple_=[NDArray[int, :,: ]])
def test_accesMultipleND_(self):
self.run_test("def np_accesMultipleND_(a): return a[1,0]", numpy.array([[[1,2],[3,4]],[[5,6],[7,8]]]), np_accesMultipleND_=[NDArray[int, :,:,:]])
def test_accesMultipleNDSplit_(self):
self.run_test("def np_accesMultipleNDSplit_(a): return a[1][0]", numpy.array([[[1,2],[3,4]],[[5,6],[7,8]]]), np_accesMultipleNDSplit_=[NDArray[int, :,:,:]])
def test_shape_(self):
self.run_test("def np_shape_(a): return a.shape", numpy.array([[[1,2],[3,4]],[[5,6],[7,8]]]), np_shape_=[NDArray[int, :,:,:]])
def test_change_arrayND_(self):
self.run_test("def np_change_arrayND_(a):\n from numpy import array\n a[0,0] = array([99,99])\n return a", numpy.array([[[1,2],[3,4]],[[5,6],[7,8]]]), np_change_arrayND_=[NDArray[int, :,:,:]])
def test_ndim_(self):
self.run_test("def np_ndim_(a): return a.ndim", numpy.array([[[1,2],[3,4]],[[5,6],[7,8]]]), np_ndim_=[NDArray[int, :,:,:]])
def test_stride_(self):
self.run_test("def np_stride_(a): return a.strides", numpy.array([[[1,2],[3,4]],[[5,6],[7,8]]]), np_stride_=[NDArray[int, :,:,:]])
def test_size_(self):
self.run_test("def np_size_(a): return a.size", numpy.array([[[1,2],[3,4]],[[5,6],[7,8]]]), np_size_=[NDArray[int, :,:,:]])
def test_itemsize_(self):
self.run_test("def np_itemsize_(a): return a.itemsize", numpy.array([[[1,2],[3,4]],[[5,6],[7,8]]]), np_itemsize_=[NDArray[int, :,:,:]])
def test_nbytes_(self):
self.run_test("def np_nbytes_(a): return a.nbytes", numpy.array([[[1,2],[3,4]],[[5,6],[7,8]]]), np_nbytes_=[NDArray[int, :,:,:]])
def test_flat_(self):
self.run_test("def np_flat_(a): return [i for i in a.flat]", numpy.array([[[1,2],[3,4]],[[5,6],[7,8]]]), np_flat_=[NDArray[int, :,:,:]])
def test_sliced0(self):
self.run_test("def np_sliced0(a): return a[2:12]", numpy.ones(20), np_sliced0=[NDArray[float, :]])
def test_sliced1(self):
self.run_test("def np_sliced1(a): return a[2:12:3]", numpy.ones(20), np_sliced1=[NDArray[float, :]])
def test_sliced2(self):
self.run_test("def np_sliced2(a): return -a[2:12:3]", numpy.ones(20), np_sliced2=[NDArray[float, :]])
def test_sliced3(self):
self.run_test("def np_sliced3(a): return a[1:11:3] -a[2:12:3]", numpy.ones(20), np_sliced3=[NDArray[float, :]])
def test_sliced4(self):
self.run_test("def np_sliced4(a): return a[1:11] -a[2:12]", numpy.ones(20), np_sliced4=[NDArray[float, :]])
def test_sliced5(self):
self.run_test("def np_sliced5(a): return (-a[1:11]) + 3*a[2:12]", numpy.ones(20), np_sliced5=[NDArray[float, :]])
def test_sliced6(self):
self.run_test("def np_sliced6(a): return a[3:4]", numpy.arange(12).reshape(6,2), np_sliced6=[NDArray[int, :,: ]])
def test_sliced7(self):
self.run_test("def np_sliced7(a): a[3:4] = 1 ; return a", numpy.arange(12).reshape(6,2), np_sliced7=[NDArray[int, :,: ]])
def test_sliced8(self):
self.run_test("def np_sliced8(a): a[1:2] = 1 ; return a", numpy.arange(12).reshape(3,2,2), np_sliced8=[NDArray[int, :,:,:]])
def test_sliced9(self):
self.run_test("def np_sliced9(a): from numpy import arange ; a[1:2] = arange(4.).reshape((1,2,2)) ; return a", numpy.arange(12.).reshape(3,2,2), np_sliced9=[NDArray[float, :,:,:]])
def test_sliced10(self):
self.run_test("def np_sliced10(a): from numpy import arange ; a[1:-1:2] = arange(4.).reshape((1,2,2)) ; return a", numpy.arange(12.).reshape(3,2,2), np_sliced10=[NDArray[float, :,:,:]])
def test_sliced11(self):
self.run_test("def np_sliced11(a): return a[1::-2]", numpy.arange(12).reshape(3,2,2), np_sliced11=[NDArray[int, :,:,:]])
def test_sliced12(self):
self.run_test("def np_sliced12(a): return a[1::-2]", numpy.arange(12), np_sliced12=[NDArray[int, :]])
def test_sliced13(self):
self.run_test("def np_sliced13(a): return a[3::-3]", numpy.arange(11), np_sliced13=[NDArray[int, :]])
def test_newaxis0(self):
self.run_test("def np_newaxis0(a): return a[None]",
numpy.ones(5), np_newaxis0=[NDArray[float, :]])
def test_newaxis1(self):
self.run_test("def np_newaxis1(a): from numpy import newaxis; return a[newaxis]",
numpy.ones(5), np_newaxis1=[NDArray[float, :]])
def test_newaxis2(self):
self.run_test("def np_newaxis2(a): from numpy import newaxis; return a[newaxis,:,newaxis]",
numpy.ones(5), np_newaxis2=[NDArray[float, :]])
def test_newaxis3(self):
self.run_test("def np_newaxis3(a): from numpy import newaxis; return a[:,newaxis]",
numpy.ones(5), np_newaxis3=[NDArray[float, :]])
def test_newaxis4(self):
self.run_test("def np_newaxis4(a): from numpy import newaxis; return a[newaxis,:,:]",
numpy.ones((2,3)), np_newaxis4=[NDArray[float, :,: ]])
def test_newaxis5(self):
self.run_test("def np_newaxis5(a): from numpy import newaxis; return a[:,newaxis,:]",
numpy.ones((2,3)), np_newaxis5=[NDArray[float, :,: ]])
def test_newaxis6(self):
self.run_test("def np_newaxis6(a): from numpy import newaxis; return a[:,:,newaxis]",
numpy.ones((2,3)), np_newaxis6=[NDArray[float, :,: ]])
def test_newaxis7(self):
self.run_test("def np_newaxis7(a): from numpy import newaxis; return a[newaxis,1:,newaxis,:1,newaxis]",
numpy.ones((2,3)), np_newaxis7=[NDArray[float, :,: ]])
def test_gexpr_composition0(self):
self.run_test("def gexpr_composition0(a): return a[:,:,:][1]",
numpy.arange(16).reshape(2,2,2,2),
gexpr_composition0=[NDArray[int, :,:,:, :]])
def test_gexpr_composition1(self):
self.run_test("def gexpr_composition1(a): return a[:,:,:][1,:]",
numpy.arange(16).reshape(2,2,2,2),
gexpr_composition1=[NDArray[int,:,:,:,:]])
def test_gexpr_composition2(self):
self.run_test("def gexpr_composition2(a): return a[:,:,:][1,:,:]",
numpy.arange(16).reshape(2,2,2,2),
gexpr_composition2=[NDArray[int,:,:,:,:]])
def test_gexpr_composition3(self):
self.run_test("def gexpr_composition3(a): return a[:,1,:][:,:,:]",
numpy.arange(16).reshape(2,2,2,2),
gexpr_composition3=[NDArray[int,:,:,:,:]])
def test_gexpr_composition4(self):
self.run_test("def gexpr_composition4(a): return a[:,:,1][:,:,:]",
numpy.arange(16).reshape(2,2,2,2),
gexpr_composition4=[NDArray[int,:,:,:,:]])
def test_gexpr_composition5(self):
self.run_test("def gexpr_composition5(a): return a[:,1,:][:,1,:]",
numpy.arange(16).reshape(2,2,2,2),
gexpr_composition5=[NDArray[int,:,:,:,:]])
def test_gexpr_composition6(self):
self.run_test("def gexpr_composition6(a): return a[:,:,1][:,1,:]",
numpy.arange(16).reshape(2,2,2,2),
gexpr_composition6=[NDArray[int,:,:,:,:]])
def test_gexpr_composition7(self):
self.run_test("def gexpr_composition7(a): return a[::2][::2]",
numpy.arange(16),
gexpr_composition7=[NDArray[int, :]])
def test_gexpr_composition8(self):
self.run_test("def gexpr_composition8(a): return a[1::2][2::2]",
numpy.arange(16),
gexpr_composition8=[NDArray[int, :]])
def test_gexpr_composition9(self):
self.run_test("def gexpr_composition9(a): return a[:1:2][:2:2]",
numpy.arange(16),
gexpr_composition9=[NDArray[int, :]])
@unittest.skip("Unknown slice combination")
def test_gexpr_composition10(self):
self.run_test("def gexpr_composition10(a): return a[:-1:2][:-2:2]",
numpy.arange(16),
gexpr_composition10=[NDArray[int, :]])
@unittest.skip("Unknown slice combination")
def test_gexpr_composition11(self):
self.run_test("def gexpr_composition11(a): return a[::2][::-2]",
numpy.arange(17),
gexpr_composition11=[NDArray[int, :]])
@unittest.skip("Unknown slice combination")
def test_gexpr_composition12(self):
self.run_test("def gexpr_composition12(a): return a[::-2][::-2]",
numpy.arange(13),
gexpr_composition12=[NDArray[int, :]])
def test_gexpr_composition13(self):
self.run_test("def gexpr_composition13(a): return a[::-3][::2]",
numpy.arange(17),
gexpr_composition13=[NDArray[int, :]])
def test_gexpr_composition14(self):
self.run_test("def gexpr_composition14(a): return a[:,::2][:,1,::-2]",
numpy.arange(16).reshape(1,4,4),
gexpr_composition14=[NDArray[int, :,:,:]])
def test_gexpr_composition15(self):
self.run_test("def gexpr_composition15(a): return a[:,1,1:-1][:,:-1]",
numpy.arange(16).reshape(1,4,4),
gexpr_composition15=[NDArray[int, :,:,:]])
def test_gexpr_composition16(self):
self.run_test("def gexpr_composition16(a): return a[:,None][:,:,None]",
numpy.arange(16).reshape(4,4),
gexpr_composition16=[NDArray[int, :,:]])
def test_gexpr_composition17(self):
self.run_test("def gexpr_composition17(a): return a[:,None][:,None]",
numpy.arange(16).reshape(1,4,4),
gexpr_composition17=[NDArray[int, :,:,:]])
def test_gexpr_composition18(self):
self.run_test("def gexpr_composition18(a): return a[0,:,None][:,None]",
numpy.arange(24).reshape(2,3,4),
gexpr_composition18=[NDArray[int, :,:,:]])
def test_gexpr_copy0(self):
self.run_test("def gexpr_copy0(a,b): a[:,0] = b[:,0]; return a",
numpy.arange(16).reshape(8,2), numpy.arange(16).reshape(8,2),
gexpr_copy0=[NDArray[int, :,: ], NDArray[int, :,: ]])
def test_ndarray_iter0(self):
self.run_test("def ndarray_iter0(a): return list(map(str, a))",
numpy.arange(16),
ndarray_iter0=[NDArray[int, :]])
def test_ndarray_iter1(self):
self.run_test("""
def ndarray_iter1(a):
s = 0
for v in a:
s *= v
return s""",
numpy.arange(16),
ndarray_iter1=[NDArray[int, :]])
def test_ndarray_str_dtype0(self):
self.run_test("def ndarray_str_dtype0(a): return str(a.dtype)",
numpy.arange(16),
ndarray_str_dtype0=[NDArray[int, :]])
def test_ndarray_str_dtype1(self):
self.run_test("def ndarray_str_dtype1(a): return str(a.dtype)",
numpy.arange(16.),
ndarray_str_dtype1=[NDArray[float, :]])
def test_ndarray_fancy_indexing0(self):
self.run_test("def ndarray_fancy_indexing0(a,b): return a[b]",
numpy.arange(8.),
numpy.arange(8),
ndarray_fancy_indexing0=[NDArray[float, :], NDArray[int, :]])
def test_ndarray_fancy_indexing1(self):
self.run_test("def ndarray_fancy_indexing1(a,b): return a[b]",
numpy.arange(8.).reshape(4,2),
numpy.array([0,1], dtype=int),
ndarray_fancy_indexing1=[NDArray[float, :, :], NDArray[int, :]])
def test_ndarray_fancy_indexing2(self):
self.run_test("def ndarray_fancy_indexing2(a,b): return a[b]",
numpy.arange(8.).reshape(4,2),
numpy.array([3,2,1,0, 0], dtype=int),
ndarray_fancy_indexing2=[NDArray[float, :, :], NDArray[int, :]])
def test_ndarray_fancy_indexing3(self):
self.run_test("def ndarray_fancy_indexing3(a,b): return a[b]",
numpy.arange(8.).reshape(4,2),
numpy.array([3,2,1,0], dtype=int),
ndarray_fancy_indexing3=[NDArray[float, :, :], NDArray[int, :]])
def test_ndarray_ubyte(self):
self.run_test("def ndarray_ubyte(n): import numpy; return numpy.arange(0, n, 1, dtype=numpy.ubyte)",
4,
ndarray_ubyte=[int])
def test_ndarray_byte(self):
self.run_test("def ndarray_byte(n): import numpy; return numpy.arange(-n, n, 1, dtype=numpy.byte)",
4,
ndarray_byte=[int])
def test_ndarray_ushort(self):
self.run_test("def ndarray_ushort(n): import numpy; return numpy.arange(0, n, 1, dtype=numpy.ushort)",
4,
ndarray_ushort=[int])
def test_ndarray_short(self):
self.run_test("def ndarray_short(n): import numpy; return numpy.arange(-n, n, 1, dtype=numpy.short)",
4,
ndarray_short=[int])
def test_ndarray_1d_index(self):
self.run_test(
'def ndarray_1d_index(a): return a[1], a[-1]',
numpy.arange(30).reshape((2,3,5)),
ndarray_1d_index=[NDArray[int, :, :,:]])
def test_ndarray_2d_index(self):
self.run_test(
'def ndarray_2d_index(a): return a[0,1], a[0, -1]',
numpy.arange(30).reshape((2,3,5)),
ndarray_2d_index=[NDArray[int, :, :,:]])
def test_ndarray_3d_index(self):
self.run_test(
'def ndarray_3d_index(a): return a[0, 1, 2], a[0, -1, -2]',
numpy.arange(30).reshape((2,3,5)),
ndarray_3d_index=[NDArray[int, :, :,:]])
def test_numpy_iexpr_1d_index(self):
self.run_test(
'def numpy_iexpr_1d_index(A): a = A[0]; return a[1], a[-1]',
numpy.arange(30).reshape((1, 2,3,5)),
numpy_iexpr_1d_index=[NDArray[int, :, :,:, :]])
def test_numpy_iexpr_2d_index(self):
self.run_test(
'def numpy_iexpr_2d_index(A): a = A[0]; return a[0,1], a[0, -1]',
numpy.arange(30).reshape((1, 2,3,5)),
numpy_iexpr_2d_index=[NDArray[int, :, :,:, :]])
def test_numpy_iexpr_3d_index(self):
self.run_test(
'def numpy_iexpr_3d_index(A): a = A[0]; return a[0, 1, 2], a[0, -1, -2]',
numpy.arange(30).reshape((1, 2,3,5)),
numpy_iexpr_3d_index=[NDArray[int, :, :,:, :]])
def test_numpy_indexing_ex0(self):
self.run_test(
'def numpy_indexing_ex0(x, y): return x[y]',
numpy.array([1,2,3,4]),
(0,),
numpy_indexing_ex0=[NDArray[int, :], Tuple[int]])
def test_numpy_indexing_ex1(self):
self.run_test(
'def numpy_indexing_ex1(x, y): return x[y]',
numpy.array([[1,2],[3,4]]),
(0, 1),
numpy_indexing_ex1=[NDArray[int, :, :], Tuple[int, int]])
def test_numpy_indexing_ex2(self):
self.run_test(
'def numpy_indexing_ex2(x, y): return x[y, :]',
numpy.array([[1,2],[3,4]]),
0,
numpy_indexing_ex2=[NDArray[int, :, :], int])
def test_numpy_indexing_ex3(self):
self.run_test(
'def numpy_indexing_ex3(x, y): return x[y]',
numpy.array([[1,2],[3,4]]),
[1],
numpy_indexing_ex3=[NDArray[int, :, :], List[int]])
def test_numpy_indexing_ex4(self):
self.run_test(
'def numpy_indexing_ex4(x, y): return x[:,:][y]',
numpy.array([[1,2],[3,4]]),
[1],
numpy_indexing_ex4=[NDArray[int, :, :], List[int]])
def test_numpy_indexing_ex10(self):
self.run_test(
'def numpy_indexing_ex10(x, y): return (2*x)[y]',
numpy.array([1,2,3,4]),
(0,),
numpy_indexing_ex10=[NDArray[int, :], Tuple[int]])
def test_numpy_indexing_ex11(self):
self.run_test(
'def numpy_indexing_ex11(x, y): return (2*x)[y]',
numpy.array([[1,2],[3,4]]),
(0, 1),
numpy_indexing_ex11=[NDArray[int, :, :], Tuple[int, int]])
def test_numpy_indexing_ex12(self):
self.run_test(
'def numpy_indexing_ex12(x, y): return (2*x)[y, :]',
numpy.array([[1,2],[3,4]]),
0,
numpy_indexing_ex12=[NDArray[int, :, :], int])
def test_numpy_indexing_ex13(self):
self.run_test(
'def numpy_indexing_ex13(x, y): return (2*x)[y]',
numpy.array([[1,2],[3,4]]),
[1],
numpy_indexing_ex13=[NDArray[int, :, :], List[int]])
def test_numpy_indexing_ex14(self):
self.run_test(
'def numpy_indexing_ex14(x, y): return (2*x)[:,:][y]',
numpy.array([[1,2],[3,4]]),
[1],
numpy_indexing_ex14=[NDArray[int, :, :], List[int]])
def test_numpy_expr_combiner(self):
code = '''
import numpy as np
def abcd(x, y):
return np.linspace(0, x, y)
def ops(a, b, o):
return 4.0 * np.pi / a * np.sin(0.5 * np.arctan(o / b))
def efgh(x, y):
a = abcd(x, y)
if x == 2:
c = ops(2.0, 3.0, a * 3.0) # Comment here
#c = a # decoment here
else:
c = a # And here
#c = ops(2.0, 3.0, a * 3.0) # and here
return c[:-1]
def numpy_expr_combiner(x, y):
b = efgh(x, y)
return b'''
self.run_test(code,
10, 10,
numpy_expr_combiner=[int, int])
def test_bool_conversion_0(self):
code = 'def bool_conversion_0(x): return bool(x)'
self.run_test(code,
numpy.array([[1]]),
bool_conversion_0=[NDArray[int, :,:]])
def test_bool_conversion_1(self):
code = 'def bool_conversion_1(x): return bool(x > 1)'
self.run_test(code,
numpy.array([1]),
bool_conversion_1=[NDArray[int, :]])
def test_bool_conversion_2(self):
code = 'def bool_conversion_2(x): return bool(x[1:,1,1:])'
self.run_test(code,
numpy.array([[[1,1],[1,1]],
[[1,0],[1,1]]]
),
bool_conversion_2=[NDArray[int, :,:,:]])
def test_bool_conversion_3(self):
code = 'def bool_conversion_3(x): return bool(x[1])'
self.run_test(code,
numpy.array([[1],[0]]),
bool_conversion_3=[NDArray[int, :,:]])
def test_bool_conversion_4(self):
code = 'def bool_conversion_4(x): return bool(x.T)'
self.run_test(code,
numpy.array([[1]]),
bool_conversion_4=[NDArray[int, :,:]])
def test_numpy_lazy_gexpr(self):
code = '''
import numpy as np
def efgh2(s, m, x, y):
if x == 0: # Without the if it doesn't compile
return np.zeros(10)[:-1]
return np.zeros(10)[:-1]
def numpy_lazy_gexpr(s, m, x, y):
if m == 'a':
b = efgh2(s, m, x, y + 1)
else:
b = efgh2(s, m, x, y)
return b'''
self.run_test(code,
10, "b", 10, 10,
numpy_lazy_gexpr=[int, str, int, int])
def test_numpy_lazy_gexpr2(self):
code = '''
import numpy as np
def numpy_lazy_gexpr2(c, y):
z = [0] * 2
if c:
x = y[1:3]
z[0] = x[0]
z[1] = x[1]
return z'''
self.run_test(code,
1, numpy.array([1,2,3,4]),
numpy_lazy_gexpr2=[int, NDArray[int, :]])
def test_fexpr0(self):
code = '''
import numpy as np
def test_fexpr0(peaks):
peaks = peaks[peaks>30] # <- does not compiles
lastBin = 0
for peak in peaks:
lastBin = peak
return lastBin'''
self.run_test(code, numpy.array([1,32,33,4]), test_fexpr0=[NDArray[int, :]])
def test_fexpr1(self):
code = '''
import numpy as np
def yy(x):
a = np.zeros(x, np.float32)
return a[:-1]
def test_fexpr1(x):
c = yy(x)
d = yy(x)
c[d == 0] = np.nan
return c'''
self.run_test(code, 10, test_fexpr1=[int])
def test_vexpr0(self):
code = '''
import numpy as np
def vexpr0(a, b=None):
if b is None:
assert len(a) > 0
b = np.copy(a[0])
a = a[1:]
else:
b = np.copy(b)
m = b >= 0
for array in a:
b[m] *= array[m]
return b'''
self.run_test(code,
[numpy.arange(10, dtype=numpy.int32).reshape(5,2)],
2 * numpy.arange(10, dtype=numpy.int32).reshape(5,2),
vexpr0=[List[NDArray[numpy.int32,:,:]], NDArray[numpy.int32,:,:]])
def test_array_of_pshape(self):
code = 'def array_of_pshape(x): from numpy import array; return array(x[None].shape)'
self.run_test(code, numpy.arange(10), array_of_pshape=[NDArray[int,:]])
def test_vexpr_of_texpr(self):
code = '''
import numpy as np
def apply_mask(mat, mask):
assert mask.shape == mat.shape
mat[mask == False] = np.nan
return mat
def vexpr_of_texpr(a, b):
return apply_mask(a.T, b), apply_mask(a, b.T), apply_mask(a.T, b.T)'''
self.run_test(code,
numpy.arange(4., dtype=numpy.float32).reshape(2,2),
numpy.array([[False,True],[True, False]]),
vexpr_of_texpr=[NDArray[numpy.float32,:,:], NDArray[numpy.bool,:,:]])
def test_indexing_through_int8(self):
code = '''
def indexing_through_int8(x):
return x[x[0,0],x[0,1]]'''
self.run_test(code,
numpy.arange(10, dtype=numpy.uint8).reshape(5,2),
indexing_through_int8=[NDArray[numpy.uint8,:,:]])
def test_indexing_through_byte(self):
code = '''
def indexing_through_byte(x):
return x[x[0,0],x[0,1]]'''
self.run_test(code,
numpy.arange(10, dtype=numpy.byte).reshape(5,2),
indexing_through_byte=[NDArray[numpy.byte,:,:]])
def test_indexing_through_uint8(self):
code = '''
def indexing_through_uint8(x):
import numpy as np
return x[np.uint8(2), np.uint8(1)]'''
self.run_test(code,
numpy.arange(9).reshape(3,3),
indexing_through_uint8=[NDArray[int,:,:]])
def test_complex_scalar_broadcast(self):
self.run_test('def complex_scalar_broadcast(a): return (a**2 * (1 + a) + 2) / 5.',
numpy.ones((10,10), dtype=complex),
complex_scalar_broadcast=[NDArray[complex, :, :]])
@unittest.skipIf(not has_float128, "not float128")
def test_float128_0(self):
self.run_test('def float128_0(x): return x, x **2',
numpy.float128(numpy.finfo(numpy.float64).max),
float128_0=[numpy.float128])
@unittest.skipIf(not has_float128, "not float128")
def test_float128_1(self):
self.run_test('def float128_1(x): return x, x **2',
numpy.ones((10,10), dtype=numpy.float128),
float128_1=[NDArray[numpy.float128,:, :]])
@unittest.skipIf(not has_float128, "not float128")
def test_float128_2(self):
self.run_test('def float128_2(x): from numpy import ones, float128; return ones(x,dtype=float128)',
3,
float128_2=[int])
def test_texpr_expr_combined(self):
self.run_test("def texpr_expr_combined(x, y):\n if x: return y.T\n else: return y * 2",
1,
numpy.arange(10).reshape(5, 2),
texpr_expr_combined=[int, NDArray[int,:,:]])
def test_built_slice_indexing(self):
self.run_test('''
def built_slice_indexing(x,n,axis,val=0.):
import numpy as np
y = np.roll(x,n,axis)
S = [slice(None,None)]*x.ndim
if n>0: S[axis] = slice(0, n)
elif n<0: S[axis] = slice(n, None)
if n: y[tuple(S)] = val
return y''',
numpy.array([-1.2, 1, 1.2]),
1,
0,
5.,
built_slice_indexing=[NDArray[float, :], int, int, float])
def test_dtype_type(self):
self.run_test('''
def dtype_type(x):
import numpy as np
c = np.complex64(x)
f = np.float32(x)
u = np.uint8(x)
return c.dtype.type(1), f.dtype.type(2), u.dtype.type(3)''',
2,
dtype_type=[int])
def test_transposed_slice_assign0(self):
self.run_test("""def transposed_slice_assign0(shape):
import numpy as np
xx = np.empty(shape, dtype=int)
xx.T[:] = np.arange(0, shape[0], 1, dtype=int)
return xx""",
(3, 5),
transposed_slice_assign0=[Tuple[int, int]])
def test_transposed_slice_assign1(self):
self.run_test("""def transposed_slice_assign1(shape):
import numpy as np
xx = np.ones(shape, dtype=int)
xx.T[:] = 3
return xx""",
(3, 5),
transposed_slice_assign1=[Tuple[int, int]])
def test_transposed_slice_assign2(self):
self.run_test("""def transposed_slice_assign2(shape):
import numpy as np
xx = np.ones(shape, dtype=int)
xx.T[:1] = 3
return xx""",
(10, 20),
transposed_slice_assign2=[Tuple[int, int]])
def test_slice_through_list0(self):
self.run_test("""def slice_through_list0(shape):
import numpy as np
xx = np.ones(shape, dtype=int)
return xx[[1,3,5],1]""",
(10, 20),
slice_through_list0=[Tuple[int, int]])
def test_slice_through_list1(self):
self.run_test("""def slice_through_list1(shape):
import numpy as np
xx = np.ones(shape, dtype=int)
return xx[[1,3,5],1:]""",
(10, 20),
slice_through_list1=[Tuple[int, int]])
def test_slice_through_list2(self):
self.run_test("""def slice_through_list2(arr):
import numpy as np;
return arr[np.array([1,3,5]),1:]""",
numpy.ones((10, 20)),
slice_through_list2=[NDArray[float, :,:]])
def test_slice_through_list3(self):
self.run_test("""def slice_through_list3(arr):
import numpy as np;
return arr[[1,3,5],1:]""",
numpy.ones((10, 20)),
slice_through_list3=[NDArray[float, :,:]])
def test_slice_through_list4(self):
self.run_test("""def slice_through_list4(arr):
import numpy as np;
return arr[(1,3,5),1:]""",
numpy.ones((10, 20)),
slice_through_list4=[NDArray[float, :,:]])
def test_transposed_array(self):
self.run_test("""def transposed_array(shape):
import numpy as np
xx = np.ones(shape, dtype=int)
return xx.T""",
(3, 5),
transposed_array=[Tuple[int, int]])
def assign_transposed(self, last):
params = [numpy.arange(30.).reshape(5,6), 3, 1, 1]
code = '''
def helper(signal, N, A):
return (signal[N:N-A:-1],
signal[N:N+A],
signal[N-A:N+A],)
def assign_transposed(signal, N, A):
return (helper(signal, N, A),
helper(signal[:,:], N, A),
helper(signal.T, N, A),)
'''
self.run_test(code, *params, assign_transposed=[NDArray[float,:,:], int, int, int])
def test_hanning(self):
code = '''
import numpy as np
def helper(M):
if M < 1:
return np.array([])
if M == 1:
return np.ones(1, float)
n = np.arange(0,float(M))
return 0.5 - 0.5*np.cos(2.0*np.pi*n/(M-1))
def hanning(M):
return helper(M * 0), helper(M * 1), helper(M * 4)'''
self.run_test(code, 1, hanning=[int])
def test_ones_on_updated_shape(self):
code = '''
import numpy as np
def ones_on_updated_shape(array,n,axis,padVal):
shape = list(array.shape)
shape[axis]=n
toPad = padVal*np.ones(shape,dtype=array.dtype)
return np.concatenate((np.diff(array, n, axis=axis), toPad), axis=axis)'''
self.run_test(code, numpy.arange(10.).reshape(5, 2), 1, 0, 3., ones_on_updated_shape=[NDArray[float,:,:], int, int, float])
def test_numpy_vexpr_static_shape(self):
code = '''
import numpy as np
def numpy_vexpr_static_shape(A):
x_transFrames = np.array([3,6,20,40,70,245])
x_transScores = A[x_transFrames]
x_transList = np.array([0,2,3,4])
B = x_transScores[x_transList]
return x_transFrames[x_transList].astype(int),B'''
self.run_test(code, numpy.arange(300.), numpy_vexpr_static_shape=[NDArray[float, :]])
def test_subscripting_slice_array_transpose(self):
code = 'def subscripting_slice_array_transpose(x): return x.T[(slice(0,1),slice(0,1))]'
self.run_test(code,
numpy.arange(200.).reshape(10, 20),
subscripting_slice_array_transpose=[NDArray[float, :, :]])
def test_combiner_0(self):
code = '''
import numpy as np
def test_combiner_0(X):
O=test1(X[:,0], False)
P=test1(X[:,0], True) # <- Ask to concatenate
return O,P
def test1(X,A):
N = 20
if A:
X = np.concatenate((np.zeros(N),X))
return X'''
self.run_test(code, numpy.ones((10,10)), test_combiner_0=[NDArray[float,:,:]])
def test_combiner_1(self):
code = '''
import numpy as np
def test_combiner_1(X):
O=test1(X[0], False)
P=test1(X[1], True) # <- Ask to concatenate
return O,P
def test1(X,A):
N = 20
if A:
X = np.concatenate((np.zeros((N)),X))
return X'''
self.run_test(code, numpy.ones((10,10)), test_combiner_1=[NDArray[float,:,:]])
def test_combiner_2(self):
code = '''
import numpy as np
def test_combiner_2(X):
O=test1(X[X==1], False)
P=test1(X[X==1], True) # <- Ask to concatenate
return O,P
def test1(X,A):
N = 20
if A:
X = np.concatenate((np.zeros((N)),X))
return X'''
self.run_test(code, numpy.ones((10)), test_combiner_2=[NDArray[float,:]])
| 42.164915 | 200 | 0.530293 |
acefeb32f6dfcee6b591f77a717755e889afdc28 | 830 | py | Python | Digit.py | samli6479/PythonLearn | 2ad78f62d58612132d3a3759aecec4a52381566f | [
"Apache-2.0"
] | null | null | null | Digit.py | samli6479/PythonLearn | 2ad78f62d58612132d3a3759aecec4a52381566f | [
"Apache-2.0"
] | null | null | null | Digit.py | samli6479/PythonLearn | 2ad78f62d58612132d3a3759aecec4a52381566f | [
"Apache-2.0"
] | null | null | null | # Recursive FUnction
def split(n):
assert n >0, 'n has to be postive'
'''Split postive n into all but its last digit and its last digit'''
return n//10, n%10
def sum_digit(n):
''' Return the sum of the digits of postive integer n.'''
if n<10:
return n
else:
all_but_last,last=split(n)
return sum_digit(all_but_last)+last
# conditional statement check the base case, evaluated without revursive calls
# Recurisive cases are evaluated with recurisive calls
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
### Recursion case only need to track 2 names
### n, fact
def fact_iter(n):
total, k = 1, 1
while k <= n:
total, k = total*k, k+1
return total
### Iteration cases track 4 names
### n, total, k, fact_iter
| 19.302326 | 78 | 0.619277 |
acefebab46d052da052f7ed843ed8c4e0fc93bb6 | 7,773 | py | Python | splintegrate/splintegrate.py | eas342/splintegrate | 24d13460312737f5290ef308c34a41cbec9292d6 | [
"MIT"
] | null | null | null | splintegrate/splintegrate.py | eas342/splintegrate | 24d13460312737f5290ef308c34a41cbec9292d6 | [
"MIT"
] | 1 | 2021-03-29T18:02:28.000Z | 2021-03-29T18:02:28.000Z | splintegrate/splintegrate.py | eas342/splintegrate | 24d13460312737f5290ef308c34a41cbec9292d6 | [
"MIT"
] | null | null | null | """Main module."""
from astropy.io import fits
from astropy.table import Table
import numpy as np
import glob
import os
import tqdm
import warnings
import pdb
from copy import deepcopy
class splint:
"""
Splint is the object for taking a multi-integration file and splitting it up
"""
def __init__(self,inFile=None,outDir=None,overWrite=False,flipToDet=True,
detectorName=None,mirageSeedFile=False):
"""
Initializes the objects
Parameters
----------
inFile: str
A path for the file to split
outDir: str
The path to the output directory
overWrite: bool
Overwrite existing files?
flipToDet: bool
Flip to detector coordinates (provisional)?
detectorName: str or None
Give a detector name for flipping. If None, it is read from the header automatically
mirageSeedFile: bool
Is it a mirage seed file? This requires extra treatment for the differet parts of segments
"""
self.inFile = inFile
self.mirageSeedFile = mirageSeedFile
if os.path.exists(self.inFile) == False:
warnings.warn('No file found. {}'.format(self.inFile))
self.nint = 0
else:
HDUList = fits.open(self.inFile)
self.head = HDUList[0].header
if self.mirageSeedFile == True:
self.int_start_num = self.head['SEGINTST'] + 1 + self.head['PTINTSRT']
elif 'INTSTART' not in self.head:
warnings.warn('INTSTART not found, trying SEGINTST')
self.int_start_num = self.head['SEGINTST'] + 1
else:
self.int_start_num = self.head['INTSTART']
if self.mirageSeedFile == True:
head1 = HDUList[1].header
self.nint = head1['NAXIS4'] ## didn't find a better keyword
self.nint_orig = self.head['EXPINT']
elif 'INTEND' not in self.head:
warnings.warn('INTEND not found, reverting to using NINTS')
if 'NINTS' not in self.head:
warnings.warn('NINTS not found, trying SEGINTED')
self.nint = self.head['SEGINTED'] - self.int_start_num + 2 ## number in this file segment
self.nint_orig = self.head['EXPINT']
else:
self.nint = self.head['NINTS']
self.nint_orig = self.nint
elif self.head['INTEND'] == 0:
warnings.warn('INTEND is 0, reverting to using NINTS')
self.nint = self.head['NINTS']
self.nint_orig = self.nint
else:
self.nint = self.head['INTEND'] - self.int_start_num + 1 ## number in this file segment
self.nint_orig = self.head['NINTS'] ## original number of integrations in exposure
if 'INT_TIMES' in HDUList:
self.times_tab = Table(fits.getdata(self.inFile,extname='INT_TIMES'))#HDUList['INT_TIMES'].data)
else:
self.times_tab = Table()
self.outDir = outDir
if os.path.exists(self.outDir) == False:
os.mkdir(self.outDir)
self.overWrite = overWrite
self.detectorName = detectorName
self.flipToDet = flipToDet
self.baseName = os.path.splitext(os.path.basename(self.inFile))[0]
def split(self):
datCube = fits.getdata(self.inFile,extName='SCI')
for i in tqdm.tqdm(np.arange(self.nint)):
if self.nint == 1:
_thisint = datCube
else:
_thisint = datCube[i]
thisHeader=deepcopy(self.head)
if self.flipToDet == True:
outDat = flip_data(_thisint,self.head,detectorName=self.detectorName)
thisHeader['FLIP2DET'] = (True,'Flipped to detector coordinates?')
else:
outDat = _thisint
thisHeader['FLIP2DET'] = (True,'Flipped to detector coordinates?')
tmpStr="{:05d}".format(i+self.int_start_num-1)
outFile = "{}_I{}.fits".format(self.baseName,tmpStr)
## since we have split the ints, set nints to 1
thisHeader['NINTS'] = 1
thisHeader.insert("NINTS",("ON_NINT",i+self.int_start_num,"This is INT of TOT_NINT"),after=True)
thisHeader.insert("ON_NINT",("TOT_NINT",self.nint_orig,"Total number of NINT in original exposure"),after=True)
## This is the number of ints in the file segment, which could be less than the total
thisHeader.insert("TOT_NINT",("SEGNINT",self.nint,"Total number of NINT in the segment or file"),after=True)
if len(self.times_tab) == self.nint:
thisHeader.insert("TIME-OBS",("BJDMID",self.times_tab[i]['int_mid_BJD_TDB'],"Mid-Exposure time (MBJD_TDB)"),after=True)
thisHeader.insert("BJDMID",("MJDSTART",self.times_tab[i]['int_start_MJD_UTC'],"Exposure start time (MJD_UTC)"),after=True)
thisHeader['NINTS'] = 1 # set nint to 1
thisHeader.insert("NINTS",("NINT",1,"Number of ints"))
thisHeader["COMMENT"] = 'Extracted from a multi-integration file by splintegrate'
#thisheader["COMMENT"] = 'splintegrate version {}'.format(__version__)
outHDU = fits.PrimaryHDU(outDat,header=thisHeader)
outPath = os.path.join(self.outDir,outFile)
if (os.path.exists(outPath) & (self.overWrite == False)):
print("Found {}. Not overwriting".format(outPath))
else:
outHDU.writeto(outPath,overwrite=self.overWrite)
del outHDU
def flip_data(data,head,detectorName=None):
""" This flips the detector coordinates from DMS to the Fitswriter way
Perhaps using this module will make things easier in the future:
https://github.com/spacetelescope/jwst/blob/master/jwst/fits_generator/create_dms_data.py
Parameters
----------
data: numpy array
The input 2D array
head: astropy.io.fits header
Original
Returns
----------
"""
ndim = len(data.shape)
if detectorName is None:
if 'DETECTOR' not in head:
raise Exception("Couldn't find detector name to know how to flip")
else:
detectorName = head['DETECTOR']
if detectorName in ['NRCALONG','NRCA1','NRCA3','NRCB2','NRCB4']:
if ndim == 2:
return data[:,::-1]
elif ndim == 3:
return data[:,:,::-1]
else:
raise Exception("Don't know what to do with {} dimensions".format(ndim))
elif detectorName in ['NRCBLONG','NRCA2','NRCA4','NRCB1','NRCB3']:
if ndim == 2:
return data[::-1,:]
elif ndim == 3:
return data[:,::-1,:]
else:
raise Exception("Don't know what to do with {} dimensions".format(ndim))
else:
raise NotImplementedError("Need to add this detector: {}".format(detectorName))
def get_fileList(inFiles):
"""
Search a file list for a list of files
Parameters
----------
inFiles: str
A search string (can contain * ) for the files to split
"""
#self.nFile = len(self.fileList)
return np.sort(glob.glob(inFiles))
def run_on_multiple(inFiles,**kwargs):
fileList = get_fileList(inFiles)
print("Splitting up {} original file(s)".format(len(fileList)))
for oneFile in fileList:
sp1 = splint(inFile=oneFile,**kwargs)
sp1.split()
| 39.861538 | 138 | 0.575068 |
acefebadc5e1770b6230d6e767e4a6e1145e8b58 | 3,712 | py | Python | google/ads/google_ads/v4/proto/errors/not_empty_error_pb2.py | arammaliachi/google-ads-python | a4fe89567bd43eb784410523a6306b5d1dd9ee67 | [
"Apache-2.0"
] | 1 | 2021-04-09T04:28:47.000Z | 2021-04-09T04:28:47.000Z | google/ads/google_ads/v4/proto/errors/not_empty_error_pb2.py | arammaliachi/google-ads-python | a4fe89567bd43eb784410523a6306b5d1dd9ee67 | [
"Apache-2.0"
] | null | null | null | google/ads/google_ads/v4/proto/errors/not_empty_error_pb2.py | arammaliachi/google-ads-python | a4fe89567bd43eb784410523a6306b5d1dd9ee67 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v4/proto/errors/not_empty_error.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='google/ads/googleads_v4/proto/errors/not_empty_error.proto',
package='google.ads.googleads.v4.errors',
syntax='proto3',
serialized_options=_b('\n\"com.google.ads.googleads.v4.errorsB\022NotEmptyErrorProtoP\001ZDgoogle.golang.org/genproto/googleapis/ads/googleads/v4/errors;errors\242\002\003GAA\252\002\036Google.Ads.GoogleAds.V4.Errors\312\002\036Google\\Ads\\GoogleAds\\V4\\Errors\352\002\"Google::Ads::GoogleAds::V4::Errors'),
serialized_pb=_b('\n:google/ads/googleads_v4/proto/errors/not_empty_error.proto\x12\x1egoogle.ads.googleads.v4.errors\x1a\x1cgoogle/api/annotations.proto\"R\n\x11NotEmptyErrorEnum\"=\n\rNotEmptyError\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0b\n\x07UNKNOWN\x10\x01\x12\x0e\n\nEMPTY_LIST\x10\x02\x42\xed\x01\n\"com.google.ads.googleads.v4.errorsB\x12NotEmptyErrorProtoP\x01ZDgoogle.golang.org/genproto/googleapis/ads/googleads/v4/errors;errors\xa2\x02\x03GAA\xaa\x02\x1eGoogle.Ads.GoogleAds.V4.Errors\xca\x02\x1eGoogle\\Ads\\GoogleAds\\V4\\Errors\xea\x02\"Google::Ads::GoogleAds::V4::Errorsb\x06proto3')
,
dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,])
_NOTEMPTYERRORENUM_NOTEMPTYERROR = _descriptor.EnumDescriptor(
name='NotEmptyError',
full_name='google.ads.googleads.v4.errors.NotEmptyErrorEnum.NotEmptyError',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='UNSPECIFIED', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='UNKNOWN', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='EMPTY_LIST', index=2, number=2,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=145,
serialized_end=206,
)
_sym_db.RegisterEnumDescriptor(_NOTEMPTYERRORENUM_NOTEMPTYERROR)
_NOTEMPTYERRORENUM = _descriptor.Descriptor(
name='NotEmptyErrorEnum',
full_name='google.ads.googleads.v4.errors.NotEmptyErrorEnum',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
],
extensions=[
],
nested_types=[],
enum_types=[
_NOTEMPTYERRORENUM_NOTEMPTYERROR,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=124,
serialized_end=206,
)
_NOTEMPTYERRORENUM_NOTEMPTYERROR.containing_type = _NOTEMPTYERRORENUM
DESCRIPTOR.message_types_by_name['NotEmptyErrorEnum'] = _NOTEMPTYERRORENUM
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
NotEmptyErrorEnum = _reflection.GeneratedProtocolMessageType('NotEmptyErrorEnum', (_message.Message,), dict(
DESCRIPTOR = _NOTEMPTYERRORENUM,
__module__ = 'google.ads.googleads_v4.proto.errors.not_empty_error_pb2'
,
__doc__ = """Container for enum describing possible not empty errors.
""",
# @@protoc_insertion_point(class_scope:google.ads.googleads.v4.errors.NotEmptyErrorEnum)
))
_sym_db.RegisterMessage(NotEmptyErrorEnum)
DESCRIPTOR._options = None
# @@protoc_insertion_point(module_scope)
| 37.877551 | 601 | 0.785022 |
acefebbb3690d84c71d43317ec93ebbcaae45b33 | 208 | py | Python | comments/urls.py | MiracleWong/blogproject | 6c23177a4f6c56a02cbddfe3d4086acfe27bd2b1 | [
"MIT"
] | null | null | null | comments/urls.py | MiracleWong/blogproject | 6c23177a4f6c56a02cbddfe3d4086acfe27bd2b1 | [
"MIT"
] | null | null | null | comments/urls.py | MiracleWong/blogproject | 6c23177a4f6c56a02cbddfe3d4086acfe27bd2b1 | [
"MIT"
] | null | null | null | # -*- coding:utf-8 -*-
from django.conf.urls import url
from . import views
app_name = 'comments'
urlpatterns = [
url(r'^comment/post/(?P<post_pk>[0-9]+)/$', views.post_comment, name='post_comment'),
] | 20.8 | 89 | 0.658654 |
acefec45852f3250cc9d25b75196fe92b3258b4d | 4,120 | py | Python | tests/test_urls.py | bfontaine/jinja2_maps | 9e231a871a1f1884a1cdf870d7fd50de28c74015 | [
"MIT"
] | 1 | 2019-07-11T19:12:11.000Z | 2019-07-11T19:12:11.000Z | tests/test_urls.py | bfontaine/jinja2_maps | 9e231a871a1f1884a1cdf870d7fd50de28c74015 | [
"MIT"
] | 1 | 2021-03-30T06:44:21.000Z | 2021-03-30T06:44:21.000Z | tests/test_urls.py | bfontaine/jinja2_maps | 9e231a871a1f1884a1cdf870d7fd50de28c74015 | [
"MIT"
] | null | null | null | # -*- coding: UTF-8 -*-
from base import TestCase
import jinja2_maps
from jinja2_maps.urls import apple_maps_url, bing_maps_url, gmaps_url, here_url
from jinja2_maps.urls import mappy_url, arcgis_url, wikimapia_url
from jinja2_maps.urls import yandex_maps_url
class TestAppleMaps(TestCase):
def test_url_filter_exists(self):
self.assertIn("apple_maps_url", jinja2_maps.filters())
def test_url_dict(self):
url = "https://maps.apple.com/?ll=12.34,56.78&z=2&t=&q="
self.assertEquals(url,
apple_maps_url(dict(latitude=12.34, longitude=56.78), zoom=2))
def test_url_dict_no_zoom(self):
url = "https://maps.apple.com/?ll=12.34,56.78&z=16&t=&q="
self.assertEquals(url,
apple_maps_url(dict(latitude=12.34, longitude=56.78)))
class TestBingMaps(TestCase):
def test_url_filter_exists(self):
self.assertIn("bing_maps_url", jinja2_maps.filters())
def test_url_dict(self):
url = "https://www.bing.com/mapspreview?&cp=12.34~56.78&lvl=2"
self.assertEquals(url,
bing_maps_url(dict(latitude=12.34, longitude=56.78), zoom=2))
def test_url_dict_no_zoom(self):
url = "https://www.bing.com/mapspreview?&cp=12.34~56.78&lvl=16"
self.assertEquals(url,
bing_maps_url(dict(latitude=12.34, longitude=56.78)))
class TestGmaps(TestCase):
def test_url_filter_exists(self):
self.assertIn("gmaps_url", jinja2_maps.filters())
self.assertIn("google_maps_url", jinja2_maps.filters())
def test_url_dict(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42))
def test_url_dict_no_zoom(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,16z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78)))
class TestMappy(TestCase):
def test_url_filter_exists(self):
self.assertIn("mappy_url", jinja2_maps.filters())
def test_url_dict(self):
url = "http://en.mappy.com/#/M2/THome/N0,0,12.34,56.78/Z2/"
self.assertEquals(url,
mappy_url(dict(latitude=12.34, longitude=56.78), zoom=2))
def test_url_dict_no_zoom(self):
url = "http://en.mappy.com/#/M2/THome/N0,0,12.34,56.78/Z16/"
self.assertEquals(url,
mappy_url(dict(latitude=12.34, longitude=56.78)))
def test_url_dict_locale(self):
url = "http://fr.mappy.com/#/M2/THome/N0,0,12.34,56.78/Z16/"
self.assertEquals(url,
mappy_url(dict(latitude=12.34, longitude=56.78), locale="fr"))
class TestArcgis(TestCase):
def test_url_filter_exists(self):
self.assertIn("arcgis_url", jinja2_maps.filters())
def test_url_dict(self):
url = "https://www.arcgis.com/home/webmap/viewer.html" \
"?center=56.78,12.34&level=2"
self.assertEquals(url,
arcgis_url(dict(latitude=12.34, longitude=56.78), zoom=2))
class TestHere(TestCase):
def test_url_filter_exists(self):
self.assertIn("here_url", jinja2_maps.filters())
def test_url_dict(self):
url = "https://maps.here.com/?map=12.34,56.78,2,normal"
self.assertEquals(url,
here_url(dict(latitude=12.34, longitude=56.78), zoom=2))
class TestWikimapia(TestCase):
def test_url_filter_exists(self):
self.assertIn("wikimapia_url", jinja2_maps.filters())
def test_url_dict(self):
url = "http://wikimapia.org/#lang=en&lat=12.34&lon=56.78&z=2&m=w"
self.assertEquals(url,
wikimapia_url(dict(latitude=12.34, longitude=56.78), zoom=2))
class TestYandexMaps(TestCase):
def test_url_filter_exists(self):
self.assertIn("yandex_maps_url", jinja2_maps.filters())
def test_url_dict(self):
url = "https://yandex.com/maps/105075/place/?ll=12.34,56.78&z=2"
self.assertEquals(url,
yandex_maps_url(dict(latitude=12.34, longitude=56.78), zoom=2))
| 33.495935 | 79 | 0.650728 |
acefed32646fdb44d4c14066c4cd5e9c73eee781 | 145,779 | py | Python | fritzcall/src/plugin.py | FoxyRabbit67/enigma2-plugins | f6b94012726931fdf28e80a26226aec612b350de | [
"Linux-OpenIB"
] | 41 | 2016-01-21T17:54:44.000Z | 2021-06-26T05:54:41.000Z | fritzcall/src/plugin.py | FoxyRabbit67/enigma2-plugins | f6b94012726931fdf28e80a26226aec612b350de | [
"Linux-OpenIB"
] | 22 | 2016-11-16T11:25:26.000Z | 2021-12-13T09:13:06.000Z | fritzcall/src/plugin.py | FoxyRabbit67/enigma2-plugins | f6b94012726931fdf28e80a26226aec612b350de | [
"Linux-OpenIB"
] | 62 | 2016-02-05T22:55:48.000Z | 2022-03-12T21:48:22.000Z | # -*- coding: utf-8 -*-
'''
Update rev
$Author: michael $
$Revision: 1591 $
$Date: 2021-04-29 16:52:10 +0200 (Thu, 29 Apr 2021) $
$Id: plugin.py 1591 2021-04-29 14:52:10Z michael $
'''
# C0111 (Missing docstring)
# C0103 (Invalid name)
# C0301 (line too long)
# W0603 (global statement)
# W0141 (map, filter, etc.)
# W0110 lambda with map,filter
# W0403 Relative import
# W1401 Anomalous backslash in string
# C0302 too-many-lines
# E401 multiple imports on one line
# E501 line too long (85 > 79 characters)
# pylint: disable=C0111,C0103,C0301,W0603,C0302
from __future__ import division, absolute_import
import re, time, os, traceback, json, base64, six, logging, binascii, locale
from itertools import cycle
from logging import NOTSET, DEBUG, INFO, WARNING, ERROR, CRITICAL
from xml.dom.minidom import parse
from six.moves import zip, range
from enigma import getDesktop
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
# from Screens.InputBox import InputBox
from Screens.VirtualKeyBoard import VirtualKeyBoard
from Screens import Standby
from Screens.HelpMenu import HelpableScreen
from Screens.LocationBox import LocationBox
from enigma import eTimer, eSize # @UnresolvedImport # pylint: disable=E0611
from enigma import eDVBVolumecontrol, eConsoleAppContainer # @UnresolvedImport # pylint: disable=E0611
# BgFileEraser = eBackgroundFileEraser.getInstance()
# BgFileEraser.erase("blabla.txt")
from Components.ActionMap import ActionMap
from Components.Label import Label
from Components.Button import Button
from Components.Pixmap import Pixmap
from Components.Sources.List import List
from Components.ConfigList import ConfigListScreen
from Components.config import config, ConfigSubsection, ConfigSelection, ConfigDirectory, \
getConfigListEntry, ConfigText, ConfigInteger, ConfigYesNo, ConfigOnOff, ConfigPassword
from Plugins.Plugin import PluginDescriptor
from Tools import Notifications
from Tools.NumericalTextInput import NumericalTextInput
from Tools.Directories import resolveFilename, SCOPE_PLUGINS, SCOPE_CONFIG, SCOPE_CURRENT_SKIN, \
SCOPE_CURRENT_PLUGIN
from Tools.LoadPixmap import LoadPixmap
from GlobalActions import globalActionMap # for muting
from twisted.internet import reactor # @UnresolvedImport
from twisted.internet.protocol import ReconnectingClientFactory # @UnresolvedImport
from twisted.protocols.basic import LineReceiver # @UnresolvedImport
from .nrzuname import ReverseLookupAndNotifier # @UnresolvedImport
from . import __ # @UnresolvedImport # pylint: disable=W0611,F0401
try:
from enigma import eMediaDatabase # @UnresolvedImport @UnusedImport
except:
from . import _ # @UnresolvedImport
if six.PY3:
import codecs
encode = lambda x : codecs.encode(x, "rot13")
decode = lambda x : codecs.decode(x, "rot13")
else:
def encode(x):
return base64.b64encode(''.join(chr(ord(c) ^ ord(k)) for c, k in zip(x, cycle('secret key')))).strip()
def decode(x):
return ''.join(chr(ord(c) ^ ord(k)) for c, k in zip(base64.b64decode(x), cycle('secret key')))
DESKTOP_WIDTH = getDesktop(0).size().width()
DESKTOP_HEIGHT = getDesktop(0).size().height()
#
# this is pure magic.
# It returns the first value, if HD (1280x720),
# the second if SD (720x576),
# else something scaled accordingly
# if one of the parameters is -1, scale proportionally
#
def scaleH(y2, y1):
if y2 == -1:
y2 = y1 * 1280 // 720
elif y1 == -1:
y1 = y2 * 720 // 1280
return scale(y2, y1, 1280, 720, DESKTOP_WIDTH)
def scaleV(y2, y1):
if y2 == -1:
y2 = y1 * 720 // 576
elif y1 == -1:
y1 = y2 * 576 // 720
return scale(y2, y1, 720, 576, DESKTOP_HEIGHT)
def scale(y2, y1, x2, x1, x):
return (y2 - y1) * (x - x1) // (x2 - x1) + y1
my_global_session = None
config.plugins.FritzCall = ConfigSubsection()
config.plugins.FritzCall.fwVersion = ConfigSelection(choices = [(None, _("not configured")), ("old", _("before 05.27")), ("05.27", "05.27, 05.28"), ("05.50", _("05.29 until below 6.35")), ("06.35", _("06.35 and newer"))], default = None)
# config.plugins.FritzCall.fwVersion = ConfigSelection(choices = [(None, _("not configured")), ("old", _("before 05.27")), ("05.27", "05.27, 05.28"), ("05.50", _("05.29 until below 6.35")), ("06.35", _("06.35 and newer")), ("upnp", "Experimental")], default = None)
# config.plugins.FritzCall.fwVersion = ConfigSelection(choices=[(None, _("not configured")), ("old", _("before 05.27")), ("05.27", "05.27, 05.28"), ("05.50", _("05.29 and newer"))], default=None)
config.plugins.FritzCall.debug = ConfigSelection(choices = [
(str(NOTSET), _("nothing")),
(str(DEBUG), "DEBUG"),
(str(INFO), "INFO"),
(str(WARNING), "WARNING"),
(str(ERROR), "ERROR"),
(str(CRITICAL), "CRITICAL")],
default = str(ERROR))
# config.plugins.FritzCall.muteOnCall = ConfigSelection(choices=[(None, _("no")), ("ring", _("on ring")), ("connect", _("on connect"))])
# config.plugins.FritzCall.muteOnCall = ConfigSelection(choices=[(None, _("no")), ("ring", _("on ring"))])
config.plugins.FritzCall.muteOnCall = ConfigYesNo(default = False)
config.plugins.FritzCall.muteOnOutgoingCall = ConfigYesNo(default = False)
config.plugins.FritzCall.hostname = ConfigText(default = "fritz.box", fixed_size = False)
config.plugins.FritzCall.afterStandby = ConfigSelection(choices = [("none", _("show nothing")), ("inList", _("show as list")), ("each", _("show each call"))])
config.plugins.FritzCall.filter = ConfigYesNo(default = False)
config.plugins.FritzCall.filtermsn = ConfigText(default = "", fixed_size = False)
config.plugins.FritzCall.filtermsn.setUseableChars('0123456789,')
config.plugins.FritzCall.filterCallList = ConfigYesNo(default = True)
config.plugins.FritzCall.showBlacklistedCalls = ConfigYesNo(default = False)
config.plugins.FritzCall.showOutgoingCalls = ConfigYesNo(default = False)
config.plugins.FritzCall.timeout = ConfigInteger(default = 15, limits = (0, 65535))
config.plugins.FritzCall.lookup = ConfigYesNo(default = False)
config.plugins.FritzCall.internal = ConfigYesNo(default = False)
config.plugins.FritzCall.fritzphonebook = ConfigYesNo(default = False)
config.plugins.FritzCall.fritzphonebookName = ConfigText(default = _('Phonebook'), fixed_size = False)
config.plugins.FritzCall.fritzphonebookShowInternal = ConfigYesNo(default = True)
config.plugins.FritzCall.phonebook = ConfigYesNo(default = False)
config.plugins.FritzCall.addcallers = ConfigYesNo(default = False)
config.plugins.FritzCall.enable = ConfigOnOff(default = False)
config.plugins.FritzCall.username = ConfigText(default = 'BoxAdmin', fixed_size = False)
config.plugins.FritzCall.password = ConfigPassword(default = "", fixed_size = False)
config.plugins.FritzCall.extension = ConfigText(default = '1', fixed_size = False)
config.plugins.FritzCall.extension.setUseableChars('0123456789')
config.plugins.FritzCall.showType = ConfigYesNo(default = True)
config.plugins.FritzCall.showShortcut = ConfigYesNo(default = False)
config.plugins.FritzCall.showVanity = ConfigYesNo(default = False)
config.plugins.FritzCall.prefix = ConfigText(default = "", fixed_size = False)
config.plugins.FritzCall.prefix.setUseableChars('0123456789')
config.plugins.FritzCall.connectionVerbose = ConfigSelection(choices = [("on", _("on")), ("failed", _("only failed")), ("off", _("off"))])
config.plugins.FritzCall.ignoreUnknown = ConfigYesNo(default = False)
config.plugins.FritzCall.reloadPhonebookTime = ConfigInteger(default = 8, limits = (0, 99))
config.plugins.FritzCall.FritzExtendedSearchFaces = ConfigYesNo(default = False)
config.plugins.FritzCall.FritzExtendedSearchNames = ConfigYesNo(default = False)
config.plugins.FritzCall.phonebookLocation = ConfigDirectory(default = resolveFilename(SCOPE_CONFIG))
config.plugins.FritzCall.guestSSID = ConfigText(default = "FRITZ!Box Gastzugang", fixed_size = False)
config.plugins.FritzCall.guestSecure = ConfigYesNo(default = True)
config.plugins.FritzCall.guestPassword = ConfigPassword(default = encode("guestguest!!!"), fixed_size = False)
config.plugins.FritzCall.useHttps = ConfigYesNo(default = False)
guestWLANUptime = [(None, _('Not deactivating after time')), "15", "30", "45", "60", "90", "120", "180", "240", "300", "360", "480", "600", "720", "900", "1080", "1260"]
config.plugins.FritzCall.guestUptime = ConfigSelection(choices = guestWLANUptime, default = "30")
countryCodes = [
("0049", _("Germany")),
("0031", _("The Netherlands")),
("0033", _("France")),
("0039", _("Italy")),
("0041", _("Switzerland")),
("0043", _("Austria")),
("", _("Others"))
]
config.plugins.FritzCall.country = ConfigSelection(choices = countryCodes)
config.plugins.FritzCall.countrycode = ConfigText(default = "0049", fixed_size = False)
config.plugins.FritzCall.countrycode.setUseableChars('0123456789')
FBF_ALL_CALLS = "."
FBF_IN_CALLS = "1"
FBF_MISSED_CALLS = "2"
FBF_OUT_CALLS = "3"
FBF_BLOCKED_CALLS = "4"
fbfCallsChoices = {
FBF_ALL_CALLS: _("All calls"),
FBF_IN_CALLS: _("Incoming calls"),
FBF_MISSED_CALLS: _("Missed calls"),
FBF_OUT_CALLS: _("Outgoing calls")
}
config.plugins.FritzCall.fbfCalls = ConfigSelection(choices = fbfCallsChoices)
config.plugins.FritzCall.name = ConfigText(default = "", fixed_size = False)
config.plugins.FritzCall.number = ConfigText(default = "", fixed_size = False)
config.plugins.FritzCall.number.setUseableChars('0123456789')
logger = logging.getLogger("FritzCall")
logger.setLevel(int(config.plugins.FritzCall.debug.value))
fileHandler = logging.FileHandler('/tmp/FritzDebug.log', mode = 'w')
fileHandler.setFormatter(logging.Formatter('%(asctime)s %(levelname)-8s %(name)-26s %(funcName)s %(message)-15s', '%Y-%m-%d %H:%M:%S'))
logger.addHandler(fileHandler)
debug = logger.debug
info = logger.info
warning = logger.warning
error = logger.error
exception = logger.exception
phonebook = None
fritzbox = None
avon = {}
def initAvon():
avonFileName = resolveFilename(SCOPE_PLUGINS, "Extensions/FritzCall/avon.dat")
if os.path.exists(avonFileName):
for line in open(avonFileName):
try:
line = six.ensure_text(line)
except UnicodeDecodeError:
line = six.ensure_text(line, "iso-8859-1") # to deal with old avon.dat
if line[0] == '#':
continue
parts = line.split(':')
if len(parts) == 2:
avon[parts[0].replace('-', '').replace('*', '').replace('/', '')] = parts[1]
def resolveNumberWithAvon(number, countrycode):
if not countrycode or not number or number[0] != '0':
return ""
countrycode = countrycode.replace('00', '+')
if number[:2] == '00':
normNumber = '+' + number[2:]
elif number[:1] == '0':
normNumber = countrycode + number[1:]
else: # this should can not happen, but safety first
return ""
# debug('normNumer: ' + normNumber)
for i in reversed(list(range(min(10, len(number))))):
if normNumber[:i] in avon:
return '[' + avon[normNumber[:i]].strip() + ']'
return ""
def handleReverseLookupResult(name):
name = six.ensure_text(name)
found = re.match("NA: ([^;]*);VN: ([^;]*);STR: ([^;]*);HNR: ([^;]*);PLZ: ([^;]*);ORT: ([^;]*)", name)
if found:
(name, firstname, street, streetno, zipcode, city) = (found.group(1),
found.group(2),
found.group(3),
found.group(4),
found.group(5),
found.group(6)
)
if firstname:
name += ' ' + firstname
if street or streetno or zipcode or city:
name += ', '
if street:
name += street
if streetno:
name += ' ' + streetno
if (street or streetno) and (zipcode or city):
name += ', '
if zipcode and city:
name += zipcode + ' ' + city
elif zipcode:
name += zipcode
elif city:
name += city
return name
cbcInfos = {}
def initCbC():
callbycallFileName = resolveFilename(SCOPE_PLUGINS, "Extensions/FritzCall/callbycall_world.xml")
if os.path.exists(callbycallFileName):
dom = parse(callbycallFileName)
for top in dom.getElementsByTagName("callbycalls"):
for cbc in top.getElementsByTagName("country"):
code = cbc.getAttribute("code").replace("+", "00")
cbcInfos[code] = cbc.getElementsByTagName("callbycall")
else:
error("[FritzCall] initCbC: callbycallFileName does not exist?!?!")
def stripCbCPrefix(number, countrycode):
if not countrycode:
return number
if number and number[:2] != "00" and countrycode in cbcInfos:
for cbc in cbcInfos[countrycode]:
if len(cbc.getElementsByTagName("length")) < 1 or len(cbc.getElementsByTagName("prefix")) < 1:
warning("[FritzCall] stripCbCPrefix: entries for %s invalid", countrycode)
return number
length = int(cbc.getElementsByTagName("length")[0].childNodes[0].data)
prefix = cbc.getElementsByTagName("prefix")[0].childNodes[0].data
# if re.match('^'+prefix, number):
if number[:len(prefix)] == prefix:
return number[length:]
return number
from . import FritzCallFBF # @UnresolvedImport # wrong-import-position # pylint: disable=
class FritzAbout(Screen):
def __init__(self, session):
if DESKTOP_WIDTH <= 720:
self.skin = """
<!-- SD screen -->
<screen name="FritzAbout" position="center,center" size="580,240" title=" ">
<ePixmap alphatest="blend" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/fritz.png" position="5,50" size="150,110" />
<widget font="Regular;18" name="text" position="175,10" size="210,160" />
<ePixmap alphatest="blend" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/website.png" position="400,10" size="175,175" />
<widget font="Regular;18" foregroundColor="#bab329" halign="center" name="url" position="10,205" size="560,25" />
</screen>"""
elif DESKTOP_WIDTH <= 1280:
self.skin = """
<!-- HD screen -->
<screen name="FritzAbout" position="center,center" size="780,240" title=" ">
<ePixmap alphatest="blend" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/fritz.png" position="10,50" size="150,110" />
<widget font="Regular;22" name="text" position="200,10" size="350,160" />
<ePixmap alphatest="blend" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/website.png" position="580,10" size="175,175" />
<widget font="Regular;22" foregroundColor="#bab329" halign="center" name="url" position="10,200" size="760,40" />
</screen>"""
elif DESKTOP_WIDTH <= 1920:
self.skin = """
<!-- Fullhd screen -->
<screen name="FritzAbout" position="center,center" size="880,300" title=" ">
<ePixmap alphatest="blend" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/fritz.png" position="10,50" size="150,110" />
<widget font="Regular;30" name="text" position="200,10" size="450,220" />
<ePixmap alphatest="blend" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/website.png" position="680,30" size="175,175" />
<widget font="Regular;30" foregroundColor="#bab329" halign="center" name="url" position="10,250" size="860,40" />
</screen>
"""
else:
self.skin = """
<!-- UHD screen -->
<screen name="FritzAbout" position="center,center" size="1880,460" title=" ">
<ePixmap alphatest="blend" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/fritz.png" position="10,60" size="300,220" />
<widget font="Regular;60" name="text" position="350,10" size="1100,360" />
<ePixmap alphatest="blend" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/website.png" position="1570,20" size="300,300" />
<widget font="Regular;58" foregroundColor="#bab329" halign="center" name="url" position="10,380" size="1860,65" />
</screen>"""
Screen.__init__(self, session)
self["aboutActions"] = ActionMap(["OkCancelActions"],
{
"cancel": self.exit,
"ok": self.exit,
}, -2)
self["text"] = Label(
"FritzCall Plugin" + "\n\n" +
"$Author: michael $"[1:-2] + "\n" +
"$Revision: 1591 $"[1:-2] + "\n" +
"$Date: 2021-04-29 16:52:10 +0200 (Thu, 29 Apr 2021) $"[1:23] + "\n"
)
self["url"] = Label("http://wiki.blue-panel.com/index.php/FritzCall")
self.onLayoutFinish.append(self.setWindowTitle)
def setWindowTitle(self):
# TRANSLATORS: this is a window title.
self.setTitle(_("About FritzCall"))
def exit(self):
self.close()
from .FritzCallFBF import FBF_dectActive, FBF_faxActive, FBF_rufumlActive, FBF_tamActive, FBF_wlanState # @UnresolvedImport # wrong-import-position # pylint: disable=
class FritzMenu(Screen, HelpableScreen):
def __init__(self, session):
if not fritzbox or not fritzbox.information:
return
if config.plugins.FritzCall.fwVersion.value == "old" or config.plugins.FritzCall.fwVersion.value == "05.27":
fontSize = scaleV(24, 21) # indeed this is font size +2
noButtons = 2 # reset, wlan
if fritzbox.information[FBF_tamActive]:
noButtons += 1 # toggle mailboxes
width = max(DESKTOP_WIDTH - scaleH(500, 250), noButtons * 140 + (noButtons + 1) * 10)
# boxInfo 2 lines, gap, internet 2 lines, gap, dsl/wlan each 1 line, gap, buttons
height = 5 + 2 * fontSize + 10 + 2 * fontSize + 10 + 2 * fontSize + 10 + 40 + 5
if fritzbox.information[FBF_tamActive] is not None:
height += fontSize
if fritzbox.information[FBF_dectActive] is not None:
height += fontSize
if fritzbox.information[FBF_faxActive] is not None:
height += fontSize
if fritzbox.information[FBF_rufumlActive] is not None:
height += fontSize
buttonsGap = (width - noButtons * 140) // (noButtons + 1)
buttonsVPos = height - 40 - 5
varLinePos = 4
if fritzbox.information[FBF_tamActive] is not None:
mailboxLine = """
<widget name="FBFMailbox" position="%d,%d" size="%d,%d" font="Regular;%d" />
<widget name="mailbox_inactive" pixmap="%s" position="%d,%d" size="15,16" transparent="1" alphatest="blend"/>
<widget name="mailbox_active" pixmap="%s" position="%d,%d" size="15,16" transparent="1" alphatest="blend"/>
<ePixmap position="%d,%d" zPosition="4" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="blend" />
<widget name="key_yellow" position="%d,%d" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
""" % (
40, 5 + 2 * fontSize + 10 + varLinePos * fontSize + 10, # position mailbox
width - 40 - 20, fontSize, # size mailbox
fontSize - 2,
"skin_default/buttons/button_green_off.png",
20, 5 + 2 * fontSize + 10 + varLinePos * fontSize + 10 + (fontSize - 16) // 2, # position button mailbox
"skin_default/buttons/button_green.png",
20, 5 + 2 * fontSize + 10 + varLinePos * fontSize + 10 + (fontSize - 16) // 2, # position button mailbox
noButtons * buttonsGap + (noButtons - 1) * 140, buttonsVPos,
noButtons * buttonsGap + (noButtons - 1) * 140, buttonsVPos,
)
varLinePos += 1
else:
mailboxLine = ""
if fritzbox.information[FBF_dectActive] is not None:
dectLine = """
<widget name="FBFDect" position="%d,%d" size="%d,%d" font="Regular;%d" />
<widget name="dect_inactive" pixmap="%s" position="%d,%d" size="15,16" transparent="1" alphatest="blend"/>
<widget name="dect_active" pixmap="%s" position="%d,%d" size="15,16" transparent="1" alphatest="blend"/>
""" % (
40, 5 + 2 * fontSize + 10 + varLinePos * fontSize + 10, # position dect
width - 40 - 20, fontSize, # size dect
fontSize - 2,
"skin_default/buttons/button_green_off.png",
20, 5 + 2 * fontSize + 10 + varLinePos * fontSize + 10 + (fontSize - 16) // 2, # position button dect
"skin_default/buttons/button_green.png",
20, 5 + 2 * fontSize + 10 + varLinePos * fontSize + 10 + (fontSize - 16) // 2, # position button dect
)
varLinePos += 1
else:
dectLine = ""
if fritzbox.information[FBF_faxActive] is not None:
faxLine = """
<widget name="FBFFax" position="%d,%d" size="%d,%d" font="Regular;%d" />
<widget name="fax_inactive" pixmap="%s" position="%d,%d" size="15,16" transparent="1" alphatest="blend"/>
<widget name="fax_active" pixmap="%s" position="%d,%d" size="15,16" transparent="1" alphatest="blend"/>
""" % (
40, 5 + 2 * fontSize + 10 + varLinePos * fontSize + 10, # position dect
width - 40 - 20, fontSize, # size dect
fontSize - 2,
"skin_default/buttons/button_green_off.png",
20, 5 + 2 * fontSize + 10 + varLinePos * fontSize + 10 + (fontSize - 16) // 2, # position button dect
"skin_default/buttons/button_green.png",
20, 5 + 2 * fontSize + 10 + varLinePos * fontSize + 10 + (fontSize - 16) // 2, # position button dect
)
varLinePos += 1
else:
faxLine = ""
if fritzbox.information[FBF_rufumlActive] is not None:
rufumlLine = """
<widget name="FBFRufuml" position="%d,%d" size="%d,%d" font="Regular;%d" />
<widget name="rufuml_inactive" pixmap="%s" position="%d,%d" size="15,16" transparent="1" alphatest="blend"/>
<widget name="rufuml_active" pixmap="%s" position="%d,%d" size="15,16" transparent="1" alphatest="blend"/>
""" % (
40, 5 + 2 * fontSize + 10 + varLinePos * fontSize + 10, # position dect
width - 40 - 20, fontSize, # size dect
fontSize - 2,
"skin_default/buttons/button_green_off.png",
20, 5 + 2 * fontSize + 10 + varLinePos * fontSize + 10 + (fontSize - 16) // 2, # position button dect
"skin_default/buttons/button_green.png",
20, 5 + 2 * fontSize + 10 + varLinePos * fontSize + 10 + (fontSize - 16) // 2, # position button dect
)
varLinePos += 1
else:
rufumlLine = ""
self.skin = """
<screen name="FritzMenu" position="center,center" size="%d,%d" title="FRITZ!Box Fon Status" >
<widget name="FBFInfo" position="%d,%d" size="%d,%d" font="Regular;%d" />
<widget name="FBFInternet" position="%d,%d" size="%d,%d" font="Regular;%d" />
<widget name="internet_inactive" pixmap="%s" position="%d,%d" size="15,16" transparent="1" alphatest="blend"/>
<widget name="internet_active" pixmap="%s" position="%d,%d" size="15,16" transparent="1" alphatest="blend"/>
<widget name="FBFDsl" position="%d,%d" size="%d,%d" font="Regular;%d" />
<widget name="dsl_inactive" pixmap="%s" position="%d,%d" size="15,16" transparent="1" alphatest="blend"/>
<widget name="dsl_active" pixmap="%s" position="%d,%d" size="15,16" transparent="1" alphatest="blend"/>
<widget name="FBFWlan" position="%d,%d" size="%d,%d" font="Regular;%d" />
<widget name="wlan_inactive" pixmap="%s" position="%d,%d" size="15,16" transparent="1" alphatest="blend"/>
<widget name="wlan_active" pixmap="%s" position="%d,%d" size="15,16" transparent="1" alphatest="blend"/>
%s
%s
%s
%s
<ePixmap position="%d,%d" zPosition="4" size="140,40" pixmap="%s" transparent="1" alphatest="blend" />
<widget name="key_red" position="%d,%d" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
<ePixmap position="%d,%d" zPosition="4" size="140,40" pixmap="%s" transparent="1" alphatest="blend" />
<widget name="key_green" position="%d,%d" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
</screen>""" % (
width, height, # size
40, 5, # position information
width - 2 * 40, 2 * fontSize, # size information
fontSize - 2,
40, 5 + 2 * fontSize + 10, # position internet
width - 40, 2 * fontSize, # size internet
fontSize - 2,
"skin_default/buttons/button_green_off.png",
20, 5 + 2 * fontSize + 10 + (fontSize - 16) // 2, # position button internet
"skin_default/buttons/button_green.png",
20, 5 + 2 * fontSize + 10 + (fontSize - 16) // 2, # position button internet
40, 5 + 2 * fontSize + 10 + 2 * fontSize + 10, # position dsl
width - 40 - 20, fontSize, # size dsl
fontSize - 2,
"skin_default/buttons/button_green_off.png",
20, 5 + 2 * fontSize + 10 + 2 * fontSize + 10 + (fontSize - 16) // 2, # position button dsl
"skin_default/buttons/button_green.png",
20, 5 + 2 * fontSize + 10 + 2 * fontSize + 10 + (fontSize - 16) // 2, # position button dsl
40, 5 + 2 * fontSize + 10 + 3 * fontSize + 10, # position wlan
width - 40 - 20, fontSize, # size wlan
fontSize - 2,
"skin_default/buttons/button_green_off.png",
20, 5 + 2 * fontSize + 10 + 3 * fontSize + 10 + (fontSize - 16) // 2, # position button wlan
"skin_default/buttons/button_green.png",
20, 5 + 2 * fontSize + 10 + 3 * fontSize + 10 + (fontSize - 16) // 2, # position button wlan
mailboxLine,
dectLine,
faxLine,
rufumlLine,
buttonsGap, buttonsVPos, "skin_default/buttons/red.png", buttonsGap, buttonsVPos,
buttonsGap + 140 + buttonsGap, buttonsVPos, "skin_default/buttons/green.png", buttonsGap + 140 + buttonsGap, buttonsVPos,
)
Screen.__init__(self, session)
HelpableScreen.__init__(self)
# TRANSLATORS: keep it short, this is a button
self["key_red"] = Button(_("Reset"))
# TRANSLATORS: keep it short, this is a button
self["key_green"] = Button(_("Toggle WLAN"))
self._mailboxActive = False
if fritzbox.information[FBF_tamActive] is not None:
# TRANSLATORS: keep it short, this is a button
self["key_yellow"] = Button(_("Toggle Mailbox"))
self["menuActions"] = ActionMap(["OkCancelActions", "ColorActions", "NumberActions", "EPGSelectActions"],
{
"cancel": self._exit,
"ok": self._exit,
"red": self._reset,
"green": self._toggleWlan,
"yellow": (lambda: self._toggleMailbox(-1)),
"0": (lambda: self._toggleMailbox(0)),
"1": (lambda: self._toggleMailbox(1)),
"2": (lambda: self._toggleMailbox(2)),
"3": (lambda: self._toggleMailbox(3)),
"4": (lambda: self._toggleMailbox(4)),
"info": self._getInfo,
}, -2)
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "ColorActions", [("yellow", _("Toggle all mailboxes"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "NumberActions", [("0", _("Toggle 1. mailbox"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "NumberActions", [("1", _("Toggle 2. mailbox"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "NumberActions", [("2", _("Toggle 3. mailbox"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "NumberActions", [("3", _("Toggle 4. mailbox"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "NumberActions", [("4", _("Toggle 5. mailbox"))]))
self["FBFMailbox"] = Label(_('Mailbox'))
self["mailbox_inactive"] = Pixmap()
self["mailbox_active"] = Pixmap()
self["mailbox_active"].hide()
else:
self["menuActions"] = ActionMap(["OkCancelActions", "ColorActions", "EPGSelectActions"],
{
"cancel": self._exit,
"ok": self._exit,
"green": self._toggleWlan,
"red": self._reset,
"info": self._getInfo,
}, -2)
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "OkCancelActions", [("cancel", _("Quit"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "OkCancelActions", [("ok", _("Quit"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "ColorActions", [("green", _("Toggle WLAN"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "ColorActions", [("red", _("Reset"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "EPGSelectActions", [("info", _("Refresh status"))]))
self["FBFInfo"] = Label(_('Getting status from FRITZ!Box Fon...'))
self["FBFInternet"] = Label('Internet')
self["internet_inactive"] = Pixmap()
self["internet_active"] = Pixmap()
self["internet_active"].hide()
self["FBFDsl"] = Label('DSL')
self["dsl_inactive"] = Pixmap()
self["dsl_inactive"].hide()
self["dsl_active"] = Pixmap()
self["dsl_active"].hide()
self["FBFWlan"] = Label('WLAN ')
self["wlan_inactive"] = Pixmap()
self["wlan_inactive"].hide()
self["wlan_active"] = Pixmap()
self["wlan_active"].hide()
self._wlanActive = False
if fritzbox.information[FBF_dectActive] is not None:
self["FBFDect"] = Label('DECT')
self["dect_inactive"] = Pixmap()
self["dect_active"] = Pixmap()
self["dect_active"].hide()
if fritzbox.information[FBF_faxActive] is not None:
self["FBFFax"] = Label('Fax')
self["fax_inactive"] = Pixmap()
self["fax_active"] = Pixmap()
self["fax_active"].hide()
if fritzbox.information[FBF_rufumlActive] is not None:
self["FBFRufuml"] = Label(_('Call diversion'))
self["rufuml_inactive"] = Pixmap()
self["rufuml_active"] = Pixmap()
self["rufuml_active"].hide()
else: # not (config.plugins.FritzCall.fwVersion.value == "old" or config.plugins.FritzCall.fwVersion.value == "05.27")
if DESKTOP_WIDTH <= 720:
self.skin = """
<!-- SD screen -->
<screen name="FritzMenuNew" position="center,center" size="600,370" title="FRITZ!Box Fon Status">
<widget name="FBFInfo" position="40,10" size="550,50" font="Regular;20" />
<widget name="FBFInternet" position="40,70" size="550,45" font="Regular;18" />
<widget name="internet_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,72" size="8,20" alphatest="blend"/>
<widget name="internet_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,72" size="8,20" alphatest="blend"/>
<widget name="FBFDsl" position="40,144" size="550,25" font="Regular;18" />
<widget name="dsl_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,140" size="8,20" alphatest="blend"/>
<widget name="dsl_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,140" size="8,20" alphatest="blend"/>
<widget name="FBFWlan" position="40,169" size="550,25" font="Regular;18" />
<widget name="wlan_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,165" size="8,20" alphatest="blend"/>
<widget name="wlan_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,165" size="8,20" alphatest="blend"/>
<widget name="FBFDect" position="40,194" size="550,25" font="Regular;18" />
<widget name="dect_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,190" size="8,20" alphatest="blend"/>
<widget name="dect_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,190" size="8,20" alphatest="blend"/>
<widget name="FBFFax" position="40,219" size="550,25" font="Regular;18" />
<widget name="fax_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,215" size="8,20" alphatest="blend"/>
<widget name="fax_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,215" size="8,20" alphatest="blend"/>
<widget name="FBFRufuml" position="40,244" size="550,25" font="Regular;18" />
<widget name="rufuml_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,240" size="8,20" alphatest="blend"/>
<widget name="rufuml_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,240" size="8,20" alphatest="blend"/>
<widget name="FBFGast" position="40,269" size="550,25" font="Regular;18" />
<widget name="gast_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,265" size="8,20" alphatest="blend"/>
<widget name="gast_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,265" size="8,20" alphatest="blend"/>
<widget font="Regular;18" halign="center" name="key_red" position="10,330" size="160,22" />
<widget font="Regular;18" halign="center" name="key_green" position="180,330" size="160,22" />
<widget font="Regular;18" halign="center" name="key_yellow" position="350,330" size="240,22" />
<eLabel position="10,355" size="160,10" backgroundColor="#9f1313" />
<eLabel position="180,355" size="160,10" backgroundColor="#1f771f" />
<eLabel position="350,355" size="240,10" backgroundColor="#a08500" />
</screen>"""
elif DESKTOP_WIDTH <= 1280:
self.skin = """
<!-- HD screen -->
<screen name="FritzMenuNew" position="center,center" size="800,430" title="FRITZ!Box Fon Status">
<widget name="FBFInfo" position="60,10" size="730,60" font="Regular;20" />
<widget name="FBFInternet" position="60,80" size="730,50" font="Regular;20" />
<widget name="internet_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,82" size="8,25" alphatest="blend"/>
<widget name="internet_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,82" size="8,25" alphatest="blend"/>
<widget name="FBFDsl" position="60,154" size="730,30" font="Regular;20" />
<widget name="dsl_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,152" size="8,25" alphatest="blend"/>
<widget name="dsl_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,152" size="8,25" alphatest="blend"/>
<widget name="FBFWlan" position="60,184" size="730,30" font="Regular;20" />
<widget name="wlan_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,182" size="8,25" alphatest="blend"/>
<widget name="wlan_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,182" size="8,25" alphatest="blend"/>
<widget name="FBFDect" position="60,214" size="730,30" font="Regular;20" />
<widget name="dect_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,212" size="8,25" alphatest="blend"/>
<widget name="dect_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,212" size="8,25" alphatest="blend"/>
<widget name="FBFFax" position="60,244" size="730,30" font="Regular;20" />
<widget name="fax_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,242" size="8,25" alphatest="blend"/>
<widget name="fax_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,242" size="8,25" alphatest="blend"/>
<widget name="FBFRufuml" position="60,274" size="730,30" font="Regular;20" />
<widget name="rufuml_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,272" size="8,25" alphatest="blend"/>
<widget name="rufuml_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,272" size="8,25" alphatest="blend"/>
<widget name="FBFGast" position="60,304" size="730,30" font="Regular;20" />
<widget name="gast_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,302" size="8,25" alphatest="blend"/>
<widget name="gast_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,302" size="8,25" alphatest="blend"/>
<widget font="Regular;20" halign="center" name="key_red" position="10,375" size="220,30" />
<widget font="Regular;20" halign="center" name="key_green" position="240,375" size="220,30" />
<widget font="Regular;20" halign="center" name="key_yellow" position="470,375" size="320,30" />
<eLabel position="10,410" size="220,10" backgroundColor="#9f1313" />
<eLabel position="240,410" size="220,10" backgroundColor="#1f771f" />
<eLabel position="470,410" size="320,10" backgroundColor="#a08500" />
</screen> """
elif DESKTOP_WIDTH <= 1920:
self.skin = """
<!-- Fullhd screen -->
<screen name="FritzMenuNew" position="center,center" size="1100,660" title="FRITZ!Box Fon Status">
<widget name="FBFInfo" position="60,10" size="980,105" font="Regular;30" />
<widget name="FBFInternet" position="60,122" size="980,80" font="Regular;28" />
<widget name="internet_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,125" size="10,35" alphatest="blend"/>
<widget name="internet_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,125" size="10,35" alphatest="blend"/>
<widget name="FBFDsl" position="60,233" size="980,40" font="Regular;28" />
<widget name="dsl_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,230" size="10,35" alphatest="blend"/>
<widget name="dsl_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,230" size="10,35" alphatest="blend"/>
<widget name="FBFWlan" position="60,283" size="980,40" font="Regular;28" />
<widget name="wlan_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,280" size="10,35" alphatest="blend"/>
<widget name="wlan_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,280" size="10,35" alphatest="blend"/>
<widget name="FBFDect" position="60,333" size="980,40" font="Regular;28" />
<widget name="dect_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,330" size="10,35" alphatest="blend"/>
<widget name="dect_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,330" size="10,35" alphatest="blend"/>
<widget name="FBFFax" position="60,383" size="980,40" font="Regular;28" />
<widget name="fax_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,380" size="10,35" alphatest="blend"/>
<widget name="fax_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,380" size="10,35" alphatest="blend"/>
<widget name="FBFRufuml" position="60,433" size="980,40" font="Regular;28" />
<widget name="rufuml_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,430" size="10,35" alphatest="blend"/>
<widget name="rufuml_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,430" size="10,35" alphatest="blend"/>
<widget name="FBFGast" position="60,483" size="980,80" font="Regular;28" />
<widget name="gast_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,480" size="10,35" alphatest="blend"/>
<widget name="gast_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,480" size="10,35" alphatest="blend"/>
<widget font="Regular;30" halign="center" name="key_red" position="10,590" size="300,40" />
<widget font="Regular;30" halign="center" name="key_green" position="330,590" size="300,40" />
<widget font="Regular;30" halign="center" name="key_yellow" position="650,590" size="440,40" />
<eLabel position="10,640" size="300,8" backgroundColor="#9f1313"/>
<eLabel position="330,640" size="300,8" backgroundColor="#1f771f" />
<eLabel position="650,640" size="440,8" backgroundColor="#a08500" />
</screen>"""
else:
self.skin = """
<!-- UHD screen -->
<screen name="FritzMenuNew" position="center,center" size="2400,1270" title="FRITZ!Box Fon Status">
<widget name="FBFInfo" position="80,10" size="2300,150" font="Regular;65" />
<widget name="FBFInternet" position="80,200" size="2100,130" font="Regular;60" />
<widget name="internet_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,205" size="20,70" alphatest="blend"/>
<widget name="internet_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,205" size="20,70" alphatest="blend"/>
<widget name="FBFDsl" position="80,397" size="2300,70" font="Regular;60" />
<widget name="dsl_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,395" size="20,70" alphatest="blend"/>
<widget name="dsl_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,395" size="20,70" alphatest="blend"/>
<widget name="FBFWlan" position="80,517" size="2300,70" font="Regular;60" />
<widget name="wlan_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,515" size="20,70" alphatest="blend"/>
<widget name="wlan_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,515" size="20,70" alphatest="blend"/>
<widget name="FBFDect" position="80,617" size="2300,70" font="Regular;60" />
<widget name="dect_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,615" size="20,70" alphatest="blend"/>
<widget name="dect_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,615" size="20,70" alphatest="blend"/>
<widget name="FBFFax" position="80,727" size="2300,70" font="Regular;60" />
<widget name="fax_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,725" size="20,70" alphatest="blend"/>
<widget name="fax_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,725" size="20,70" alphatest="blend"/>
<widget name="FBFRufuml" position="80,837" size="2300,70" font="Regular;60" />
<widget name="rufuml_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,835" size="20,70" alphatest="blend"/>
<widget name="rufuml_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,785" size="20,70" alphatest="blend"/>
<widget name="FBFGast" position="80,947" size="2300,70" font="Regular;60" />
<widget name="gast_inactive" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/inaktiv.png" position="20,945" size="20,70" alphatest="blend"/>
<widget name="gast_active" pixmap="/usr/lib/enigma2/python/Plugins/Extensions/FritzCall/images/aktiv.png" position="20,945" size="20,70" alphatest="blend"/>
<widget font="Regular;60" halign="center" name="key_red" position="20,1140" size="650,70" />
<widget font="Regular;60" halign="center" name="key_green" position="700,1140" size="650,70" />
<widget font="Regular;60" halign="center" name="key_yellow" position="1380,1140" size="1000,70" />
<eLabel position="20,1230" size="650,20" backgroundColor="#9f1313" />
<eLabel position="700,1230" size="650,20" backgroundColor="#1f771f" />
<eLabel position="1380,1230" size="1000,20" backgroundColor="#a08500" />
</screen>"""
Screen.__init__(self, session)
HelpableScreen.__init__(self)
# TRANSLATORS: keep it short, this is a button
self["menuActions"] = ActionMap(["OkCancelActions", "ColorActions", "EPGSelectActions"],
{
"cancel": self._exit,
"ok": self._exit,
"green": self._toggleWlan,
"yellow": self._toggleGast,
"red": self._reset, # no button, does not work
"info": self._getInfo,
}, -2)
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "OkCancelActions", [("cancel", _("Quit"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "OkCancelActions", [("ok", _("Quit"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "ColorActions", [("green", _("Toggle WLAN"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "ColorActions", [("yellow", _("Toggle WLAN guest access"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "ColorActions", [("red", _("Reset"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["menuActions"], "EPGSelectActions", [("info", _("Refresh status"))]))
# TRANSLATORS: keep it short, this is a button
self["key_red"] = Button(_("Reset"))
# TRANSLATORS: keep it short, this is a button
self["key_green"] = Button(_("Toggle WLAN"))
# TRANSLATORS: keep it short, this is a button
self["key_yellow"] = Button(_("Activate WLAN guest access"))
self["FBFInfo"] = Label(_('Getting status from FRITZ!Box Fon...'))
self["FBFInternet"] = Label('Internet')
self["internet_inactive"] = Pixmap()
self["internet_inactive"].hide()
self["internet_active"] = Pixmap()
self["internet_active"].hide()
self["FBFDsl"] = Label('DSL')
self["dsl_inactive"] = Pixmap()
self["dsl_inactive"].hide()
self["dsl_active"] = Pixmap()
self["dsl_active"].hide()
self["FBFWlan"] = Label('WLAN ')
self["wlan_inactive"] = Pixmap()
self["wlan_inactive"].hide()
self["wlan_active"] = Pixmap()
self["wlan_active"].hide()
self._wlanActive = False
self["FBFDect"] = Label('DECT')
self["dect_inactive"] = Pixmap()
self["dect_inactive"].hide()
self["dect_active"] = Pixmap()
self["dect_active"].hide()
self["FBFFax"] = Label('Fax')
self["fax_inactive"] = Pixmap()
self["fax_inactive"].hide()
self["fax_active"] = Pixmap()
self["fax_active"].hide()
self["FBFRufuml"] = Label(_('Call redirection'))
self["rufuml_inactive"] = Pixmap()
self["rufuml_inactive"].hide()
self["rufuml_active"] = Pixmap()
self["rufuml_active"].hide()
self["FBFGast"] = Label(_('Guest access'))
self["gast_inactive"] = Pixmap()
self["gast_inactive"].hide()
self["gast_active"] = Pixmap()
self["gast_active"].hide()
self._guestActive = ""
self._getInfo()
self.onLayoutFinish.append(self.setWindowTitle)
def setWindowTitle(self):
# TRANSLATORS: this is a window title.
self.setTitle(_("FRITZ!Box Fon Status"))
def _getInfo(self):
if fritzbox:
fritzbox.getInfo(self._fillMenu)
self._fillMenu(fritzbox.information, True)
def _fillMenu(self, status, refreshing = False):
(boxInfo, upTime, ipAddress, wlanState, dslState, tamActive, dectActive, faxActive, rufumlActive, guestAccess) = status
if wlanState:
self._wlanActive = (wlanState[0] == '1')
self._guestActive = guestAccess
self._mailboxActive = False
try:
if "FBFInfo" not in self: # screen is closed already
return
if refreshing:
self["FBFInfo"].setText(_("Refreshing..."))
else:
if boxInfo:
self["FBFInfo"].setText(six.ensure_str(boxInfo))
else:
self["FBFInfo"].setText('BoxInfo ' + _('Status not available'))
if ipAddress:
if upTime:
self["FBFInternet"].setText('Internet ' + _('IP Address:') + ' ' + ipAddress + '\n' + _('Connected since') + ' ' + six.ensure_str(upTime))
else:
self["FBFInternet"].setText('Internet ' + _('IP Address:') + ' ' + ipAddress)
self["internet_inactive"].hide()
self["internet_active"].show()
elif upTime:
self["FBFInternet"].setText(_('Connected since') + ' ' + six.ensure_str(upTime))
self["internet_inactive"].hide()
self["internet_active"].show()
else:
self["internet_active"].hide()
self["internet_inactive"].show()
if dslState:
if dslState[0] == '5':
self["dsl_inactive"].hide()
self["dsl_active"].show()
if dslState[2]:
message = dslState[2]
else:
message = "DSL"
if dslState[1]:
message = message + ' ' + dslState[1]
self["FBFDsl"].setText(six.ensure_str(message))
else:
self["dsl_active"].hide()
self["dsl_inactive"].show()
else:
self["FBFDsl"].setText('DSL ' + _('Status not available'))
self["dsl_active"].hide()
self["dsl_inactive"].hide()
if wlanState:
if wlanState[0] == '1':
self["wlan_inactive"].hide()
self["wlan_active"].show()
message = 'WLAN'
if wlanState[1] == '0':
message += ' ' + _('not encrypted')
elif wlanState[1] == '1':
message += ' ' + _('encrypted')
if wlanState[2]:
if wlanState[2] == '0':
message = message + ', ' + _('no device active')
elif wlanState[2] == '1' or wlanState[2] == 'ein':
message = message + ', ' + _('one device active')
else:
message = message + ', ' + wlanState[2] + ' ' + _('devices active')
if len(wlanState) == 4:
message = message + ", " + wlanState[3]
self["FBFWlan"].setText(six.ensure_str(message))
else:
self["wlan_active"].hide()
self["wlan_inactive"].show()
self["FBFWlan"].setText('WLAN')
else:
self["FBFWlan"].setText('WLAN ' + _('Status not available'))
self["wlan_active"].hide()
self["wlan_inactive"].hide()
if fritzbox.information[FBF_tamActive] and "mailbox_active" in self:
if not tamActive or tamActive[0] == 0:
self._mailboxActive = False
self["mailbox_active"].hide()
self["mailbox_inactive"].show()
self["FBFMailbox"].setText(_('No mailbox active'))
else:
self._mailboxActive = True
message = ''
for i in range(min(len(tamActive) - 1, 5)):
if tamActive[i + 1]:
message = message + str(i) + ','
if message:
message = '(' + message[:-1] + ')'
self["mailbox_inactive"].hide()
self["mailbox_active"].show()
if tamActive[0] == 1:
self["FBFMailbox"].setText(_('One mailbox active') + ' ' + message)
else:
self["FBFMailbox"].setText(str(tamActive[0]) + ' ' + _('mailboxes active') + ' ' + message)
if dectActive and "dect_inactive" in self:
self["dect_inactive"].hide()
self["dect_active"].show()
if dectActive == 0:
self["FBFDect"].setText(_('No DECT phone registered'))
else:
if dectActive == "ein" or dectActive == "1" or dectActive == 1:
self["FBFDect"].setText(_('One DECT phone registered'))
else:
self["FBFDect"].setText(str(dectActive) + ' ' + _('DECT phones registered'))
else:
self["dect_active"].hide()
self["dect_inactive"].show()
self["FBFDect"].setText(_('DECT inactive'))
if faxActive:
self["fax_inactive"].hide()
self["fax_active"].show()
self["FBFFax"].setText(_('Software fax active'))
else:
self["fax_active"].hide()
self["fax_inactive"].show()
self["FBFFax"].setText(_('Software fax inactive'))
if rufumlActive:
self["rufuml_inactive"].hide()
self["rufuml_active"].show()
if rufumlActive == -1: # means no number available
self["FBFRufuml"].setText(_('Call diversion active'))
elif rufumlActive == 1:
self["FBFRufuml"].setText(_('One call diversion active'))
else:
self["FBFRufuml"].setText(str(rufumlActive) + ' ' + _('call diversions active'))
else:
self["rufuml_active"].hide()
self["rufuml_inactive"].show()
self["FBFRufuml"].setText(_('No call diversion active'))
if guestAccess:
self["gast_inactive"].hide()
self["gast_active"].show()
self["FBFGast"].setText(_('Guest access on ') + guestAccess)
else:
self["gast_active"].hide()
self["gast_inactive"].show()
self["FBFGast"].setText(_('Guest access not active'))
if guestAccess and (guestAccess.find('WLAN') != -1 or guestAccess.find('WIFI') != -1):
# TRANSLATORS: keep it short, this is a button
self["key_yellow"].setText(_("Deactivate WLAN guest access"))
else:
# TRANSLATORS: keep it short, this is a button
self["key_yellow"].setText(_("Activate WLAN guest access"))
except KeyError:
error("[FritzCallFBF] _fillMenu: %s", traceback.format_exc())
def _toggleWlan(self, callback=None):
self["FBFInfo"].setText(_("Setting...") + " WLAN")
if self._wlanActive:
info("[FritzMenu] toggleWlan off")
if callback:
fritzbox.changeWLAN('0', callback)
else:
fritzbox.changeWLAN('0', self._getInfo)
else:
info("[FritzMenu] toggleWlan on")
if callback:
fritzbox.changeWLAN('1', callback)
else:
fritzbox.changeWLAN('1', self._getInfo)
def _toggleMailbox(self, which):
debug("[FritzMenu]")
if fritzbox.information[FBF_tamActive]:
info("[FritzMenu] toggleMailbox off")
fritzbox.changeMailbox(which, self._getInfo)
def _toggleGast(self):
self["FBFInfo"].setText(_("Setting...") + ' ' + _("Guest access"))
if not self._wlanActive:
self["FBFInfo"].setText(_("WLAN not active"))
# self._toggleWlan(self._toggleGast)
return
fritzbox.changeGuestAccess(self._guestActive, self._getInfo)
def _reset(self):
fritzbox.reset()
self._exit()
def _exit(self):
self.close()
class FritzDisplayCalls(Screen, HelpableScreen):
def __init__(self, session, text = ""): # @UnusedVariable # pylint: disable=W0613
if DESKTOP_WIDTH <= 720:
self.skin = """
<!-- SD screen -->
<screen name="FritzDisplayCalls" position="center,center" size="620,460" title="Phone calls" >
<widget name="statusbar" position="10,10" halign="center" foregroundColor="#bab329" size="590,25" font="Regular;18"/>
<eLabel position="10,35" size="590,2" backgroundColor="#aaaaaa" />
<widget source="entries" render="Listbox" position="10,45" size="600,360" enableWrapAround="1" scrollbarMode="showOnDemand">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (50,24), size = (150,21), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 1), # index 0 is the number, index 1 is date
MultiContentEntryPixmapAlphaBlend(pos = (5,5), size = (35,35), png = 2), # index 1 i direction pixmap
MultiContentEntryText(pos = (50,0), size = (530,24), font=0, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 3), # index 2 is remote name/number
MultiContentEntryText(pos = (220,24), size = (80,21), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 4), # index 3 is length of call
MultiContentEntryText(pos = (320,24), size = (240,21), font=1, flags = RT_HALIGN_RIGHT|RT_VALIGN_CENTER, text = 5), # index 4 is my number/name for number
],
"fonts": [gFont("Regular", 18), gFont("Regular", 16)],
"itemHeight": 45
}
</convert>
</widget>
<widget name="key_red" position="10,415" size="140,20" halign="center" font="Regular;18" />
<widget name="key_green" position="160,415" size="140,20" halign="center" font="Regular;18" />
<widget name="key_yellow" position="310,415" size="140,20" halign="center" font="Regular;18" />
<widget name="key_blue" position="460,415" size="140,20" halign="center" font="Regular;18" />
<eLabel position="10,440" size="140,10" backgroundColor="#9f1313"/>
<eLabel position="160,440" size="140,10" backgroundColor="#1f771f" />
<eLabel position="310,440" size="140,10" backgroundColor="#a08500" />
<eLabel position="460,440" size="140,10" backgroundColor="#0039f0"/>
</screen>"""
elif DESKTOP_WIDTH <= 1280:
self.skin = """
<!-- HD screen -->
<screen name="FritzDisplayCalls" position="center,center" size="850,560" title="Phone calls" >
<widget name="statusbar" position="10,8" halign="center" foregroundColor="#bab329" size="830,30" font="Regular;20"/>
<eLabel position="10,40" size="830,2" backgroundColor="#aaaaaa" />
<widget source="entries" render="Listbox" position="10,50" size="830,440" enableWrapAround="1" scrollbarMode="showOnDemand">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (55,30), size = (200,25), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 1), # index 0 is the number, index 1 is date
MultiContentEntryPixmapAlphaBlend(pos = (5,10), size = (35,35), png = 2), # index 1 i direction pixmap
MultiContentEntryText(pos = (55,0), size = (760,30), font=0, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 3), # index 2 is remote name/number
MultiContentEntryText(pos = (270,30), size = (100,25), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 4), # index 3 is length of call
MultiContentEntryText(pos = (390,30), size = (400,25), font=1, flags = RT_HALIGN_RIGHT|RT_VALIGN_CENTER, text = 5), # index 4 is my number/name for number
],
"fonts": [gFont("Regular", 20), gFont("Regular", 18)],
"itemHeight": 55
}
</convert>
</widget>
<widget name="key_red" position="10,510" size="200,25" halign="center" font="Regular;20" />
<widget name="key_green" position="220,510" size="200,25" halign="center" font="Regular;20" />
<widget name="key_yellow" position="430,510" size="200,25" halign="center" font="Regular;20" />
<widget name="key_blue" position="640,510" size="200,25" halign="center" font="Regular;20" />
<eLabel position="10,540" size="200,10" backgroundColor="#9f1313"/>
<eLabel position="220,540" size="200,10" backgroundColor="#1f771f" />
<eLabel position="430,540" size="200,10" backgroundColor="#a08500" />
<eLabel position="640,540" size="200,10" backgroundColor="#0039f0"/>
</screen>"""
elif DESKTOP_WIDTH <= 1920:
self.skin = """
<!-- Fullhd screen -->
<screen name="FritzDisplayCalls" position="center,center" size="1450,850" title="Phone calls" >
<widget name="statusbar" position="10,10" halign="center" foregroundColor="#bab329" size="1430,40" font="Regular;30"/>
<eLabel position="10,55" size="1430,2" backgroundColor="#aaaaaa" />
<widget source="entries" render="Listbox" position="10,65" size="1430,680" enableWrapAround="1" scrollbarMode="showOnDemand">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (5,0), size = (180,40), flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 1), # index 0 is the number, index 1 is date
MultiContentEntryPixmapAlphaBlend(pos = (190,2), size = (35,35), png = 2), # index 1 i direction pixmap
MultiContentEntryText(pos = (245,2), size = (600,40), flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 3), # index 2 is remote name/number
MultiContentEntryText(pos = (860,0), size = (120,40), flags = RT_HALIGN_CENTER|RT_VALIGN_CENTER, text = 4), # index 3 is length of call
MultiContentEntryText(pos = (1000,0), size = (390,40), flags = RT_HALIGN_RIGHT|RT_VALIGN_CENTER, text = 5), # index 4 is my number/name for number
],
"fonts": [gFont("Regular", 28)],
"itemHeight": 40
}
</convert>
</widget>
<widget name="key_red" position="10,780" size="350,40" halign="center" font="Regular;30" />
<widget name="key_green" position="370,780" size="350,40" halign="center" font="Regular;30" />
<widget name="key_yellow" position="730,780" size="350,40" halign="center" font="Regular;30" />
<widget name="key_blue" position="1090,780" size="350,40" halign="center" font="Regular;30" />
<eLabel position="10,830" size="350,8" backgroundColor="#9f1313"/>
<eLabel position="370,830" size="350,8" backgroundColor="#1f771f" />
<eLabel position="730,830" size="350,8" backgroundColor="#a08500" />
<eLabel position="1090,830" size="350,8" backgroundColor="#0039f0"/>
</screen>"""
else:
self.skin = """
<!-- UHD screen -->
<screen name="FritzDisplayCalls" position="center,center" size="2560,1540" title="Phone calls" >
<widget name="statusbar" position="10,10" halign="center" foregroundColor="#bab329" size="2540,80" font="Regular;65"/>
<eLabel position="10,100" size="2540,4" backgroundColor="#aaaaaa" />
<widget source="entries" render="Listbox" position="10,110" size="2540,1260" enableWrapAround="1" scrollbarMode="showOnDemand">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (1100,0), size = (420,70), flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 1), # index 0 is the number, index 1 is date
MultiContentEntryPixmapAlphaBlend(pos = (5,10), size = (50,50), png = 2), # index 1 i direction pixmap
MultiContentEntryText(pos = (80,0), size = (1000,70), flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 3), # index 2 is remote name/number
MultiContentEntryText(pos = (1540,0), size = (200,70), flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 4), # index 3 is length of call
MultiContentEntryText(pos = (1760,0), size = (740,70), flags = RT_HALIGN_RIGHT|RT_VALIGN_CENTER, text = 5), # index 4 is my number/name for number
],
"fonts": [gFont("Regular", 58)],
"itemHeight": 70
}
</convert>
</widget>
<widget name="key_red" position="10,1420" size="600,70" halign="center" font="Regular;60" />
<widget name="key_green" position="660,1420" size="600,70" halign="center" font="Regular;60" />
<widget name="key_yellow" position="1310,1420" size="600,70" halign="center" font="Regular;60" />
<widget name="key_blue" position="1950,1420" size="600,70" halign="center" font="Regular;60" />
<eLabel position="10,1510" size="600,20" backgroundColor="#9f1313"/>
<eLabel position="660,1510" size="600,20" backgroundColor="#1f771f" />
<eLabel position="1310,1510" size="600,20" backgroundColor="#a08500" />
<eLabel position="1950,1510" size="600,20" backgroundColor="#0039f0"/>
</screen>"""
# debug("[FritzDisplayCalls] skin: " + self.skin)
Screen.__init__(self, session)
HelpableScreen.__init__(self)
# TRANSLATORS: keep it short, this is a button
self["key_yellow"] = Button(_("All"))
# TRANSLATORS: keep it short, this is a button
self["key_red"] = Button(_("Missed"))
# TRANSLATORS: keep it short, this is a button
self["key_blue"] = Button(_("Incoming"))
# TRANSLATORS: keep it short, this is a button
self["key_green"] = Button(_("Outgoing"))
self["setupActions"] = ActionMap(["OkCancelActions", "ColorActions"],
{
"yellow": (lambda: self.display(FBF_ALL_CALLS)),
"red": (lambda: self.display(FBF_MISSED_CALLS)),
"blue": (lambda: self.display(FBF_IN_CALLS)),
"green": (lambda: self.display(FBF_OUT_CALLS)),
"cancel": self.ok,
"ok": self.showEntry, }, -2)
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "OkCancelActions", [("ok", _("Show details of entry"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "OkCancelActions", [("cancel", _("Quit"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "ColorActions", [("yellow", _("Display all calls"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "ColorActions", [("red", _("Display missed calls"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "ColorActions", [("blue", _("Display incoming calls"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "ColorActions", [("green", _("Display outgoing calls"))]))
self["statusbar"] = Label(_("Getting calls from FRITZ!Box..."))
self.list = []
self["entries"] = List(self.list)
#=======================================================================
# fontSize = scaleV(22, 18)
# fontHeight = scaleV(24, 20)
# self["entries"].l.setFont(0, gFont("Regular", fontSize))
# self["entries"].l.setItemHeight(fontHeight)
#=======================================================================
debug("[FritzDisplayCalls] '''%s'''", config.plugins.FritzCall.fbfCalls.value)
self.display(config.plugins.FritzCall.fbfCalls.value)
self.onLayoutFinish.append(self.setWindowTitle)
def setWindowTitle(self):
# TRANSLATORS: this is a window title.
self.setTitle(_("Phone calls"))
def ok(self):
self.close()
def display(self, which = None):
debug("[FritzDisplayCalls]")
if which:
config.plugins.FritzCall.fbfCalls.value = which
config.plugins.FritzCall.fbfCalls.save()
else:
which = config.plugins.FritzCall.fbfCalls.value
fritzbox.getCalls(self, lambda x: self.gotCalls(x, which), which)
def gotCalls(self, listOfCalls, which):
debug("[FritzDisplayCalls]")
self.updateStatus(fbfCallsChoices[which] + " (" + str(len(listOfCalls)) + ")")
callPngPath = "Extensions/FritzCall/images/MODERN"
debug("[FritzDisplayCalls] callPngPath: %s", callPngPath)
directout = LoadPixmap(resolveFilename(SCOPE_CURRENT_PLUGIN, callPngPath + "/callout.png"))
directin = LoadPixmap(resolveFilename(SCOPE_CURRENT_PLUGIN, callPngPath + "/callin.png"))
directfailed = LoadPixmap(resolveFilename(SCOPE_CURRENT_PLUGIN, callPngPath + "/callinfailed.png"))
directrejected = LoadPixmap(resolveFilename(SCOPE_CURRENT_PLUGIN, callPngPath + "/callrejected.png"))
def pixDir(param):
if param == FBF_OUT_CALLS:
direct = directout
elif param == FBF_IN_CALLS:
direct = directin
elif param == FBF_MISSED_CALLS:
direct = directfailed
else:
direct = directrejected
return direct
# debug("[FritzDisplayCalls] %s" %repr(listOfCalls))
self.list = [(number, date[:6] + ' ' + date[9:14], pixDir(direct), six.ensure_str(remote), length, six.ensure_str(here)) for (number, date, direct, remote, length, here) in listOfCalls]
# debug("[FritzDisplayCalls] %s" %repr(self.list))
self["entries"].setList(self.list)
#=======================================================================
# if len(self.list) > 1:
# self["entries"].setIndex(1)
#=======================================================================
def updateStatus(self, text):
if "statusbar" in self:
self["statusbar"].setText(_("Getting calls from FRITZ!Box...") + ' ' + text)
def showEntry(self):
debug("[FritzDisplayCalls]")
cur = self["entries"].getCurrent()
if cur:
if cur[0]:
# debug("[FritzDisplayCalls] %s" % (cur[0]))
number = cur[0]
fullname = phonebook.search(cur[0])
if fullname:
# we have a name for this number
name = six.ensure_str(fullname)
self.session.open(FritzOfferAction, self, number, name)
elif cur[3]:
name = cur[3]
self.session.open(FritzOfferAction, self, number, name)
else:
# we don't
fullname = resolveNumberWithAvon(number, config.plugins.FritzCall.countrycode.value)
if fullname:
name = six.ensure_str(fullname)
self.session.open(FritzOfferAction, self, number, name)
else:
self.session.open(FritzOfferAction, self, number)
else:
# we do not even have a number...
self.session.open(MessageBox,
_("UNKNOWN"),
type = MessageBox.TYPE_INFO)
class FritzOfferAction(Screen):
def __init__(self, session, parent, number, name = ""):
if DESKTOP_WIDTH <= 720:
self.skin = """
<!-- SD screen -->
<screen name="FritzOfferAction" position="center,center" size="490,230" title=" ">
<widget name="FacePixmap" position="10,10" size="160,160" alphatest="blend" />
<widget name="text" position="220,40" size="260,120" font="Regular;18"/>
<widget font="Regular;18" halign="center" name="key_red" position="10,190" size="150,22" />
<widget font="Regular;18" halign="center" name="key_green" position="170,190" size="150,22" />
<widget font="Regular;18" halign="center" name="key_yellow" position="330,190" size="150,22" />
<eLabel position="10,215" size="150,10" backgroundColor="#9f1313"/>
<eLabel position="170,215" size="150,10" backgroundColor="#1f771f" />
<eLabel position="330,215" size="150,10" backgroundColor="#a08500" />
</screen>
"""
elif DESKTOP_WIDTH <= 1280:
self.skin = """
<!-- HD screen -->
<screen name="FritzOfferAction" position="center,center" size="700,320" title=" ">
<widget name="FacePixmap" position="10,10" size="230,230" alphatest="blend" />
<widget name="text" position="290,80" size="400,150" font="Regular;20"/>
<widget font="Regular;20" halign="center" name="key_red" position="10,270" size="200,25" />
<widget font="Regular;20" halign="center" name="key_green" position="250,270" size="200,25" />
<widget font="Regular;20" halign="center" name="key_yellow" position="490,270" size="200,25" />
<eLabel position="10,300" size="200,10" backgroundColor="#9f1313"/>
<eLabel position="250,300" size="200,10" backgroundColor="#1f771f" />
<eLabel position="490,300" size="200,10" backgroundColor="#a08500" />
</screen>
"""
elif DESKTOP_WIDTH <= 1920:
self.skin = """
<!-- Fullhd screen -->
<screen name="FritzOfferAction" position="center,center" size="1160,480" title=" ">
<widget name="FacePixmap" position="10,10" size="400,400" alphatest="blend" />
<widget name="text" position="470,110" size="680,280" font="Regular;30"/>
<widget font="Regular;30" halign="center" name="key_red" position="10,420" size="300,40" />
<widget font="Regular;30" halign="center" name="key_green" position="430,420" size="300,40" />
<widget font="Regular;30" halign="center" name="key_yellow" position="850,420" size="300,40" />
<eLabel position="10,460" size="300,8" backgroundColor="#9f1313"/>
<eLabel position="430,460" size="300,8" backgroundColor="#1f771f" />
<eLabel position="850,460" size="300,8" backgroundColor="#a08500" />
</screen>
"""
else:
self.skin = """
<!-- UHD screen -->
<screen name="FritzOfferAction" position="center,center" size="2080,940" title=" ">
<widget name="FacePixmap" position="10,10" size="800,800" alphatest="blend" />
<widget name="text" position="900,300" size="1150,500" font="Regular;60"/>
<widget font="Regular;60" halign="center" name="key_red" position="10,830" size="600,70" />
<widget font="Regular;60" halign="center" name="key_green" position="740,830" size="600,70" />
<widget font="Regular;60" halign="center" name="key_yellow" position="1470,830" size="600,70" />
<eLabel position="10,910" size="600,20" backgroundColor="#9f1313"/>
<eLabel position="740,910" size="600,20" backgroundColor="#1f771f" />
<eLabel position="1470,910" size="600,20" backgroundColor="#a08500" />
</screen>
"""
debug("[FritzOfferAction] %s, %s", __(number), __(name))
Screen.__init__(self, session)
# TRANSLATORS: keep it short, this is a button
self["key_red"] = Button(_("Lookup"))
# TRANSLATORS: keep it short, this is a button
self["key_green"] = Button(_("Call"))
# TRANSLATORS: keep it short, this is a button
self["key_yellow"] = Button(_("Save"))
# TRANSLATORS: keep it short, this is a button
# self["key_blue"] = Button(_("Search"))
self["FritzOfferActions"] = ActionMap(["OkCancelActions", "ColorActions"],
{
"red": self._lookup,
"green": self._call,
"yellow": self._add,
"cancel": self._exit,
"ok": self._exit, }, -2)
self._session = session
if config.plugins.FritzCall.internal.value and len(number) > 3 and number[0] == "0":
number = number[1:]
self._number = number
self._name = name.replace("\n", ", ")
self["text"] = Label(number + "\n\n" + name.replace(", ", "\n"))
self._parent = parent
self["key_red_p"] = Pixmap()
self["key_green_p"] = Pixmap()
self["key_yellow_p"] = Pixmap()
self["FacePixmap"] = Pixmap()
self.onLayoutFinish.append(self._finishLayout)
self.onLayoutFinish.append(self.setWindowTitle)
def setWindowTitle(self):
# TRANSLATORS: this is a window title.
self.setTitle(_("Do what?"))
def _finishLayout(self):
debug("[FritzOfferAction] number: %s/%s", __(self._number), __(self._name))
faceFile = findFace(self._number, self._name)
picPixmap = LoadPixmap(faceFile)
if not picPixmap: # that means most probably, that the picture is not 8 bit...
Notifications.AddNotification(MessageBox, _("Found picture\n\n%s\n\nBut did not load. Probably not PNG, 8-bit") % faceFile, type = MessageBox.TYPE_ERROR)
if DESKTOP_WIDTH <= 720:
picPixmap = LoadPixmap(resolveFilename(SCOPE_CURRENT_PLUGIN, "Extensions/FritzCall/images/no-face-error-sd.png"))
elif DESKTOP_WIDTH <= 1280:
picPixmap = LoadPixmap(resolveFilename(SCOPE_CURRENT_PLUGIN, "Extensions/FritzCall/images/no-face-error-hd.png"))
elif DESKTOP_WIDTH <= 1920:
picPixmap = LoadPixmap(resolveFilename(SCOPE_CURRENT_PLUGIN, "Extensions/FritzCall/images/no-face-error-fhd.png"))
else:
picPixmap = LoadPixmap(resolveFilename(SCOPE_CURRENT_PLUGIN, "Extensions/FritzCall/images/no-face-error-uhd.png"))
self["FacePixmap"].instance.setPixmap(picPixmap)
def _setTextAndResize(self, message):
self["text"].instance.resize(eSize(*(DESKTOP_WIDTH, DESKTOP_HEIGHT)))
self["text"].setText(self._number + "\n\n" + message)
self._finishLayout()
def _lookup(self):
self._setTextAndResize(_("Reverse searching..."))
ReverseLookupAndNotifier(self._number, self._lookedUp, "UTF-8", config.plugins.FritzCall.countrycode.value)
def _lookedUp(self, number, name):
name = handleReverseLookupResult(name)
if not name:
name = _("No result from reverse lookup")
self._name = name
self._number = number
info("[FritzOfferAction]\n%s", str(name.replace(", ", "\n")))
self._setTextAndResize(str(name.replace(", ", "\n")))
def _call(self):
if fritzbox:
debug("[FritzOfferAction] %s", self._number)
self.session.open(MessageBox, _("Calling %s") % self._number, type = MessageBox.TYPE_INFO)
fritzbox.dial(self._number)
else:
error("[FritzOfferAction] no fritzbox object?!?!")
self.session.open(MessageBox, _("FRITZ!Box not available for calling"), type = MessageBox.TYPE_INFO)
def _add(self):
debug("[FritzOfferAction] %s, %s", self._number, self._name)
phonebook.FritzDisplayPhonebook(self._session).add(self._parent, self._number, self._name)
self._exit()
def _exit(self):
self.close()
OneHour = 60 * 60 * 1000
# OneHour = 1000
class FritzCallPhonebook(object):
def __init__(self):
debug("[FritzCallPhonebook]")
# Beware: strings in phonebook.phonebook have to be in utf-8!
self.phonebook = {}
if config.plugins.FritzCall.reloadPhonebookTime.value > 0:
debug("[FritzCallPhonebook] start timer with %s", repr(config.plugins.FritzCall.reloadPhonebookTime.value))
self.loop = eTimer()
# newer OE versions don't have the callback
try:
self.loop_conn = self.loop.timeout.connect(self.reload)
except AttributeError:
self.loop.callback.append(self.reload)
self.loop.start(config.plugins.FritzCall.reloadPhonebookTime.value * OneHour, False)
self.reload()
def reload(self):
debug("[FritzCallPhonebook] %s", time.ctime())
# Beware: strings in phonebook.phonebook have to be in utf-8!
self.phonebook = {}
if not config.plugins.FritzCall.enable.value:
return
phonebookFilenameOld = os.path.join(config.plugins.FritzCall.phonebookLocation.value, "PhoneBook.txt")
phonebookFilename = os.path.join(config.plugins.FritzCall.phonebookLocation.value, "PhoneBook.json")
if config.plugins.FritzCall.phonebook.value:
if os.path.exists(phonebookFilename):
# read json
debug("[FritzCallPhonebook] read %s", phonebookFilename)
try:
for k, v in json.loads(six.ensure_text(open(phonebookFilename).read())).items():
# TODO if we change the value to a list of lines, we have to adapt this here
self.phonebook[k] = v
except (ValueError, UnicodeError, IOError) as e:
error("[FritzCallPhonebook] Could not load %s: %s", phonebookFilename, str(e))
Notifications.AddNotification(MessageBox, _("Could not load phonebook: %s") % (phonebookFilename + ": " + str(e)), type = MessageBox.TYPE_ERROR)
# debug(repr(self.phonebook))
if fritzbox:
if config.plugins.FritzCall.fritzphonebook.value:
debug("[FritzCallPhonebook] config.plugins.FritzCall.fritzphonebook.value %s", repr(config.plugins.FritzCall.fritzphonebook.value))
fritzbox.loadFritzBoxPhonebook(self)
else:
debug("[FritzCallPhonebook] config.plugins.FritzCall.fritzphonebook.value %s", repr(config.plugins.FritzCall.fritzphonebook.value))
fritzbox.phonebook = self
def search(self, number, default = None, extended = True):
# debug("[FritzCallPhonebook] Searching for %s" %number)
name = ""
if not self.phonebook or not number:
return name
if config.plugins.FritzCall.prefix.value:
prefix = config.plugins.FritzCall.prefix.value
if number[0] != '0':
number = prefix + number
# debug("[FritzCallPhonebook] added prefix: %s" %number)
elif number[:len(prefix)] == prefix and number[len(prefix):] in self.phonebook:
# debug("[FritzCallPhonebook] same prefix")
name = self.phonebook[number[len(prefix):]]
# debug("[FritzCallPhonebook] result: %s" %name)
else:
prefix = ""
if not name and number in self.phonebook:
name = self.phonebook[number]
if not name and default:
name = default
if not name and extended and config.plugins.FritzCall.FritzExtendedSearchNames.value:
for k in range(len(number) - 1, 0, -1):
# debug("[FritzCallPhonebook] extended search: check: %s" %number[:k])
name = self.search(number[:k], default, False)
if name:
# debug("[FritzCallPhonebook] search result for shortened number: %s" % name)
break
return name.replace(", ", "\n").strip()
def add(self, number, name):
'''
@param number: number of entry
@param name: name of entry, has to be in utf-8
'''
debug("[FritzCallPhonebook]")
name = name.replace("\n", ", ") # this is just for safety reasons. add should only be called with newlines converted into commas
self.remove(number)
self.phonebook[number] = name
if number and number != 0:
if config.plugins.FritzCall.phonebook.value:
try:
# name = name.strip() + "\n"
# string = "%s#%s" % (number, name)
# # Beware: strings in Phonebook.json have to be in utf-8!
# f = open(os.path.join(config.plugins.FritzCall.phonebookLocation.value, "PhoneBook.txt"), 'a')
# f.write(string)
# f.close()
phonebookFilename = os.path.join(config.plugins.FritzCall.phonebookLocation.value, "PhoneBook.json")
# check whether PhoneBook.json exists, if not drop empty JSOn file
if not os.path.isfile(phonebookFilename):
json.dump({}, open(phonebookFilename, "w"), ensure_ascii=False, indent=0, separators=(',', ': '), sort_keys=True)
info("[FritzCallPhonebook] empty Phonebook.json created")
phonebookTmp = {}
for k, v in json.loads(six.ensure_text(open(phonebookFilename).read())).items():
phonebookTmp[k] = v
phonebookTmp[number] = name
json.dump(phonebookTmp, open(phonebookFilename, "w"), ensure_ascii=False, indent=0, separators=(',', ': '), sort_keys=True)
info("[FritzCallPhonebook] added %s with %s to Phonebook.json", number, name.strip())
return True
except IOError:
return False
def remove(self, number):
if number in self.phonebook:
debug("[FritzCallPhonebook]")
del self.phonebook[number]
if config.plugins.FritzCall.phonebook.value:
try:
# phonebookFilename = os.path.join(config.plugins.FritzCall.phonebookLocation.value, "PhoneBook.json")
# debug("[FritzCallPhonebook] remove entry in Phonebook.json")
# fOld = open(phonebookFilename, 'r')
# fNew = open(phonebookFilename + str(os.getpid()), 'w')
# line = fOld.readline()
# while line:
# elems = line.split('#')
# if len(elems) == 2 and elems[0] != number:
# fNew.write(line)
# line = fOld.readline()
# fOld.close()
# fNew.close()
# # os.remove(phonebookFilename)
# eBackgroundFileEraser.getInstance().erase(phonebookFilename)
# os.rename(phonebookFilename + str(os.getpid()), phonebookFilename)
phonebookFilename = os.path.join(config.plugins.FritzCall.phonebookLocation.value, "PhoneBook.json")
# check whether PhoneBook.json exists, if not drop empty JSOn file
if not os.path.isfile(phonebookFilename):
json.dump({}, open(phonebookFilename, "w"), ensure_ascii=False, indent=0, separators=(',', ': '), sort_keys=True)
info("[FritzCallPhonebook] empty Phonebook.json created")
return True
phonebookTmp = {}
for k, v in json.loads(six.ensure_text(open(phonebookFilename).read())).items():
phonebookTmp[k] = v
if number in phonebookTmp:
del phonebookTmp[number]
json.dump(phonebookTmp, open(phonebookFilename, "w"), ensure_ascii=False, indent=0, separators=(',', ': '), sort_keys=True)
info("[FritzCallPhonebook] removed %s from Phonebook.json", number)
return True
except (IOError, OSError):
error("[FritzCallPhonebook] error removing %s from %s", number, phonebookFilename)
return False
class FritzDisplayPhonebook(Screen, HelpableScreen, NumericalTextInput):
def __init__(self, session):
if DESKTOP_WIDTH <= 720:
self.skin = """
<!-- SD screen -->
<screen name="FritzDisplayPhonebook" position="center,center" size="620,460" title="Phonebook" >
<widget source="entries" render="Listbox" position="10,5" size="600,400" enableWrapAround="1" scrollbarMode="showOnDemand">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (5,0), size = (400,25), font=0, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 1), # index 0 is the name, index 1 is shortname
MultiContentEntryText(pos = (415,0), size = (145,25), font=0, flags = RT_HALIGN_RIGHT|RT_VALIGN_CENTER, text = 2), # index 2 is number
],
"fonts": [gFont("Regular", 18)],
"itemHeight": 25
}
</convert>
</widget>
<widget name="key_red" position="10,415" size="140,20" halign="center" font="Regular;18" />
<widget name="key_green" position="160,415" size="140,20" halign="center" font="Regular;18" />
<widget name="key_yellow" position="310,415" size="140,20" halign="center" font="Regular;18" />
<widget name="key_blue" position="460,415" size="140,20" halign="center" font="Regular;18" />
<eLabel position="10,440" size="140,10" backgroundColor="#9f1313"/>
<eLabel position="160,440" size="140,10" backgroundColor="#1f771f" />
<eLabel position="310,440" size="140,10" backgroundColor="#a08500" />
<eLabel position="460,440" size="140,10" backgroundColor="#0039f0"/>
</screen>
"""
elif DESKTOP_WIDTH <= 1280:
self.skin = """
<!-- HD screen -->
<screen name="FritzDisplayPhonebook" position="center,center" size="850,560" title="Phonebook" >
<widget source="entries" render="Listbox" position="10,10" size="830,480" enableWrapAround="1" scrollbarMode="showOnDemand">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (5,0), size = (500,30), font=0, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 1), # index 0 is the name, index 1 is shortname
MultiContentEntryText(pos = (520,0), size = (270,30), font=0, flags = RT_HALIGN_RIGHT|RT_VALIGN_CENTER, text = 2), # index 2 is number
],
"fonts": [gFont("Regular", 20)],
"itemHeight": 30
}
</convert>
</widget>
<widget name="key_red" position="10,510" size="200,25" halign="center" font="Regular;20" />
<widget name="key_green" position="220,510" size="200,25" halign="center" font="Regular;20" />
<widget name="key_yellow" position="430,510" size="200,25" halign="center" font="Regular;20" />
<widget name="key_blue" position="640,510" size="200,25" halign="center" font="Regular;20" />
<eLabel position="10,540" size="200,10" backgroundColor="#9f1313"/>
<eLabel position="220,540" size="200,10" backgroundColor="#1f771f" />
<eLabel position="430,540" size="200,10" backgroundColor="#a08500" />
<eLabel position="640,540" size="200,10" backgroundColor="#0039f0"/>
</screen>
"""
elif DESKTOP_WIDTH <= 1920:
self.skin = """
<!-- Fullhd screen -->
<screen name="FritzDisplayPhonebook" position="center,center" size="1450,850" title="Phonebook" >
<widget source="entries" render="Listbox" position="10,10" size="1430,640" enableWrapAround="1" scrollbarMode="showOnDemand">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (5,0), size = (980,40), font=0, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 1), # index 0 is the name, index 1 is shortname
MultiContentEntryText(pos = (1000,0), size = (390,40), font=0, flags = RT_HALIGN_RIGHT|RT_VALIGN_CENTER, text = 2), # index 2 is number
],
"fonts": [gFont("Regular", 28)],
"itemHeight": 40
}
</convert>
</widget>
<widget name="key_red" position="10,780" size="350,40" halign="center" font="Regular;30" />
<widget name="key_green" position="370,780" size="350,40" halign="center" font="Regular;30" />
<widget name="key_yellow" position="730,780" size="350,40" halign="center" font="Regular;30" />
<widget name="key_blue" position="1090,780" size="350,40" halign="center" font="Regular;30" />
<eLabel position="10,830" size="350,8" backgroundColor="#9f1313"/>
<eLabel position="370,830" size="350,8" backgroundColor="#1f771f" />
<eLabel position="730,830" size="350,8" backgroundColor="#a08500" />
<eLabel position="1090,830" size="350,8" backgroundColor="#0039f0"/>
</screen>
"""
else:
self.skin = """
<!-- UHD screen -->
<screen name="FritzDisplayPhonebook" position="center,center" size="2560,1540" title="Phonebook" >
<widget source="entries" render="Listbox" position="10,10" size="2540,1330" enableWrapAround="1" scrollbarMode="showOnDemand">
<convert type="TemplatedMultiContent">
{"template": [
MultiContentEntryText(pos = (20,0), size = (1900,70), font=0, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 1), # index 0 is the name, index 1 is shortname
MultiContentEntryText(pos = (1950,0), size = (550,70), font=0, flags = RT_HALIGN_RIGHT|RT_VALIGN_CENTER, text = 2), # index 2 is number
],
"fonts": [gFont("Regular", 58)],
"itemHeight": 70
}
</convert>
</widget>
<widget name="key_red" position="10,1420" size="600,70" halign="center" font="Regular;60" />
<widget name="key_green" position="660,1420" size="600,70" halign="center" font="Regular;60" />
<widget name="key_yellow" position="1310,1420" size="600,70" halign="center" font="Regular;60" />
<widget name="key_blue" position="1950,1420" size="600,70" halign="center" font="Regular;60" />
<eLabel position="10,1510" size="600,20" backgroundColor="#9f1313"/>
<eLabel position="660,1510" size="600,20" backgroundColor="#1f771f" />
<eLabel position="1310,1510" size="600,20" backgroundColor="#a08500" />
<eLabel position="1950,1510" size="600,20" backgroundColor="#0039f0"/>
</screen>
"""
# debug("[FritzDisplayCalls] skin: %s", self.skin)
Screen.__init__(self, session)
NumericalTextInput.__init__(self)
HelpableScreen.__init__(self)
# TRANSLATORS: keep it short, this is a button
self["key_red"] = Button(_("Delete"))
# TRANSLATORS: keep it short, this is a button
self["key_green"] = Button(_("New"))
# TRANSLATORS: keep it short, this is a button
self["key_yellow"] = Button(_("Edit"))
# TRANSLATORS: keep it short, this is a button
self["key_blue"] = Button(_("Search"))
self["setupActions"] = ActionMap(["OkCancelActions", "ColorActions"],
{
"red": self.delete,
"green": self.add,
"yellow": self.edit,
"blue": self.mySearch,
"cancel": self.exit,
"ok": self.showEntry, }, -2)
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "OkCancelActions", [("ok", _("Show details of entry"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "OkCancelActions", [("cancel", _("Quit"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "ColorActions", [("red", _("Delete entry"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "ColorActions", [("green", _("Add entry to phonebook"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "ColorActions", [("yellow", _("Edit selected entry"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "ColorActions", [("blue", _("Search (case insensitive)"))]))
self["entries"] = List([])
debug("[FritzDisplayPhonebook]")
self.help_window = None
self.sortlist = []
self.onLayoutFinish.append(self.setWindowTitle)
self.display()
def setWindowTitle(self):
# TRANSLATORS: this is a window title.
self.setTitle(_("Phonebook"))
def display(self, filterNumber = ""):
debug("[FritzDisplayPhonebook]")
self.sortlist = []
# Beware: strings in phonebook.phonebook are utf-8!
sortlistHelp = sorted(((name.lower(), name, number) for (number, name) in six.iteritems(phonebook.phonebook)), key=lambda x: locale.strxfrm(x[0]))
for (low, name, number) in sortlistHelp:
if number == "01234567890":
continue
low = six.ensure_str(low)
name = six.ensure_str(name).strip()
number = six.ensure_str(number).strip()
if filterNumber:
filterNumber = filterNumber.lower()
if low.find(filterNumber) == -1:
continue
comma = name.find(',')
if comma != -1:
shortname = name[:comma]
else:
shortname = name
# number = number.encode("utf-8", "replace")
# name = name.encode("utf-8", "replace")
# shortname = shortname.encode('utf-8', 'replace')
self.sortlist.append((name, shortname, number))
self["entries"].setList(self.sortlist)
def showEntry(self):
cur = self["entries"].getCurrent()
if cur:
debug("[FritzDisplayPhonebook] %s", repr(cur))
number = cur[2]
name = cur[0]
self.session.open(FritzOfferAction, self, number, name)
def delete(self):
cur = self["entries"].getCurrent()
if cur:
debug("[FritzDisplayPhonebook] %s", repr(cur))
self.session.openWithCallback(
self.deleteConfirmed,
MessageBox,
_("Do you really want to delete entry for\n\n%(number)s\n\n%(name)s?")
% {'number':str(cur[2]), 'name':str(cur[0]).replace(", ", "\n")}
)
else:
self.session.open(MessageBox, _("No entry selected"), MessageBox.TYPE_INFO)
def deleteConfirmed(self, ret):
debug("[FritzDisplayPhonebook]")
#
# if ret: delete number from sortlist, delete number from phonebook.phonebook and write it to disk
#
cur = self["entries"].getCurrent()
if cur:
if ret:
# delete number from sortlist, delete number from phonebook.phonebook and write it to disk
debug("[FritzDisplayPhonebook] %s", repr(cur))
phonebook.remove(cur[2])
self.display()
# else:
# self.session.open(MessageBox, _("Not deleted."), MessageBox.TYPE_INFO)
else:
self.session.open(MessageBox, _("No entry selected"), MessageBox.TYPE_INFO)
def add(self, parent = None, number = "", name = ""):
class AddScreen(Screen, ConfigListScreen):
'''ConfiglistScreen with two ConfigTexts for Name and Number'''
def __init__(self, session, parent, number = "", name = ""):
if DESKTOP_WIDTH <= 720:
self.skin = """
<!-- SD screen -->
<screen name="AddScreen" position="center,center" size="590,140" title="Add entry to phonebook" >
<widget name="config" position="10,10" size="570,75" itemHeight="25" enableWrapAround="1" scrollbarMode="showOnDemand"/>
<widget name="key_red" position="10,95" size="150,22" halign="center" font="Regular;18" />
<widget name="key_green" position="430,95" size="150,22" halign="center" font="Regular;18" />
<eLabel position="10,120" size="150,10" backgroundColor="#9f1313" />
<eLabel position="430,120" size="150,10" backgroundColor="#1f771f" />
</screen>
"""
elif DESKTOP_WIDTH <= 1280:
self.skin = """
<!-- HD screen -->
<screen name="AddScreen" position="center,center" size="850,160" title="Add entry to phonebook" >
<widget name="config" position="10,10" size="830,90" itemHeight="30" enableWrapAround="1" scrollbarMode="showOnDemand"/>
<widget name="key_red" position="10,110" size="200,25" halign="center" font="Regular;20" />
<widget name="key_green" position="640,110" size="200,25" halign="center" font="Regular;20" />
<eLabel position="10,140" size="200,10" backgroundColor="#9f1313" />
<eLabel position="640,140" size="200,10" backgroundColor="#1f771f" />
</screen>
"""
elif DESKTOP_WIDTH <= 1920:
self.skin = """
<!-- Fullhd screen -->
<screen name="AddScreen" position="center,center" size="1250,210" title="Add entry to phonebook" >
<widget name="config" position="10,10" size="1230,120" itemHeight="40" enableWrapAround="1" scrollbarMode="showOnDemand"/>
<widget name="key_red" position="10,140" size="300,40" halign="center" font="Regular;30" />
<widget name="key_green" position="940,140" size="300,40" halign="center" font="Regular;30" />
<eLabel position="10,190" size="300,8" backgroundColor="#9f1313"/>
<eLabel position="940,190" size="300,8" backgroundColor="#1f771f"/>
</screen>
"""
else:
self.skin = """
<!-- UHD screen -->
<screen name="AddScreen" position="center,center" size="2250,350" title="Add entry to phonebook" >
<widget name="config" position="10,10" size="2230,210" itemHeight="70" enableWrapAround="1" scrollbarMode="showOnDemand"/>
<widget name="key_red" position="10,240" size="600,70" halign="center" font="Regular;60" />
<widget name="key_green" position="1640,240" size="600,70" halign="center" font="Regular;60" />
<eLabel position="10,320" size="600,20" backgroundColor="#9f1313"/>
<eLabel position="1640,320" size="600,20" backgroundColor="#1f771f"/>
</screen>
"""
Screen.__init__(self, session)
self.session = session
self.parent = parent
# TRANSLATORS: keep it short, this is a button
self["key_red"] = Button(_("Cancel"))
# TRANSLATORS: keep it short, this is a button
self["key_green"] = Button(_("OK"))
self["setupActions"] = ActionMap(["SetupActions", "ColorActions"],
{
"cancel": self.cancel,
"red": self.cancel,
"green": self.add,
"ok": self.add,
}, -2)
self.list = []
ConfigListScreen.__init__(self, self.list, session = session)
self.name = name
self.number = number
config.plugins.FritzCall.name.value = name
config.plugins.FritzCall.number.value = number
self.list.append(getConfigListEntry(_("Name"), config.plugins.FritzCall.name))
self.list.append(getConfigListEntry(_("Number"), config.plugins.FritzCall.number))
self["config"].list = self.list
self["config"].l.setList(self.list)
self.onLayoutFinish.append(self.setWindowTitle)
def setWindowTitle(self):
if self.number != "":
# TRANSLATORS: this is a window title.
self.setTitle(_("Edit selected entry"))
else:
# TRANSLATORS: this is a window title.
self.setTitle(_("Add entry to phonebook"))
def add(self):
# get texts from Screen
# add (number,name) to sortlist and phonebook.phonebook and disk
self.name = config.plugins.FritzCall.name.value
self.number = config.plugins.FritzCall.number.value
if not self.number or not self.name:
self.session.open(MessageBox, _("Entry incomplete."), type = MessageBox.TYPE_ERROR)
return
# add (number,name) to sortlist and phonebook.phonebook and disk
# oldname = phonebook.search(self.number)
# if oldname:
# self.session.openWithCallback(
# self.overwriteConfirmed,
# MessageBox,
# _("Do you really want to overwrite entry for %(number)s\n\n%(name)s\n\nwith\n\n%(newname)s?")
# % {
# 'number':self.number,
# 'name': oldname,
# 'newname':self.name.replace(", ","\n")
# }
# )
# self.close()
# return
phonebook.add(self.number, self.name)
self.close()
self.parent.display()
def overwriteConfirmed(self, ret):
if ret:
phonebook.remove(self.number)
phonebook.add(self.number, self.name)
self.parent.display()
def cancel(self):
self.close()
debug("[FritzDisplayPhonebook]")
if not parent:
parent = self
self.session.open(AddScreen, parent, number, name)
def edit(self):
debug("[FritzDisplayPhonebook]")
cur = self["entries"].getCurrent()
if cur is None:
self.session.open(MessageBox, _("No entry selected"), MessageBox.TYPE_INFO)
else:
self.add(self, cur[2], cur[0])
def mySearch(self):
debug("[FritzDisplayPhonebook]")
# self.help_window = self.session.instantiateDialog(NumericalTextInputHelpDialog, self)
# self.help_window.show()
# VirtualKeyboard instead of InputBox?
self.session.openWithCallback(self.doSearch, VirtualKeyBoard, title = _("Search phonebook"))
def doSearch(self, searchTerms):
if not searchTerms:
searchTerms = ""
debug("[FritzDisplayPhonebook]: %s", searchTerms)
if self.help_window:
self.session.deleteDialog(self.help_window)
self.help_window = None
self.display(searchTerms)
def exit(self):
self.close()
phonebook = FritzCallPhonebook()
class FritzCallSetup(Screen, ConfigListScreen, HelpableScreen):
def __init__(self, session, args = None): # @UnusedVariable # pylint: disable=W0613
if DESKTOP_WIDTH <= 720:
self.skin = """
<!-- SD screen -->
<screen name="FritzCallSetup" position="center,center" size="660,460" title="FritzCall Setup" >
<widget name="consideration" position="10,10" halign="center" foregroundColor="#bab329" size="640,25" font="Regular;18"/>
<eLabel position="10,35" size="640,2" backgroundColor="#aaaaaa" />
<widget name="config" position="10,50" size="640,350" itemHeight="25" enableWrapAround="1" scrollbarMode="showOnDemand"/>
<widget name="key_red" position="10,415" size="130,20" halign="center" font="Regular;18" />
<widget name="key_green" position="150,415" size="130,20" halign="center" font="Regular;18" />
<widget name="key_yellow" position="290,415" size="130,20" halign="center" font="Regular;18" />
<widget name="key_blue" position="430,415" size="130,20" halign="center" font="Regular;18" />
<eLabel position="10,440" size="130,10" backgroundColor="#9f1313"/>
<eLabel position="150,440" size="130,10" backgroundColor="#1f771f" />
<eLabel position="290,440" size="130,10" backgroundColor="#a08500" />
<eLabel position="430,440" size="130,10" backgroundColor="#0039f0"/>
<eLabel font="Regular;17" foregroundColor="#aaaaaa" position="570,435" size="50,20" text="Menu" />
<eLabel font="Regular;17" foregroundColor="#aaaaaa" position="630,435" size="30,20" text="Info" />
</screen>
"""
elif DESKTOP_WIDTH <= 1280:
self.skin = """
<!-- HD screen -->
<screen name="FritzCallSetup" position="center,center" size="1020,560" title="FritzCall Setup" >
<widget name="consideration" position="10,8" halign="center" foregroundColor="#bab329" size="1000,30" font="Regular;20"/>
<eLabel position="10,40" size="1000,2" backgroundColor="#aaaaaa" />
<widget name="config" position="10,50" size="1000,450" itemHeight="30" enableWrapAround="1" scrollbarMode="showOnDemand"/>
<widget name="key_red" position="10,510" size="200,25" halign="center" font="Regular;20" />
<widget name="key_green" position="220,510" size="200,25" halign="center" font="Regular;20" />
<widget name="key_yellow" position="430,510" size="200,25" halign="center" font="Regular;20" />
<widget name="key_blue" position="640,510" size="200,25" halign="center" font="Regular;20" />
<eLabel position="10,540" size="200,10" backgroundColor="#9f1313"/>
<eLabel position="220,540" size="200,10" backgroundColor="#1f771f" />
<eLabel position="430,540" size="200,10" backgroundColor="#a08500" />
<eLabel position="640,540" size="200,10" backgroundColor="#0039f0"/>
<eLabel font="Regular;20" foregroundColor="#aaaaaa" position="880,530" size="70,25" text="Menu" />
<eLabel font="Regular;20" foregroundColor="#aaaaaa" position="960,530" size="60,25" text="Info" />
</screen>
"""
elif DESKTOP_WIDTH <= 1920:
self.skin = """
<!-- Fullhd screen -->
<screen name="FritzCallSetup" position="center,center" size="1550,850" title="FritzCall Setup" >
<widget name="consideration" position="10,10" halign="center" foregroundColor="#bab329" size="1530,40" font="Regular;30"/>
<eLabel position="10,55" size="1530,2" backgroundColor="#aaaaaa" />
<widget name="config" position="10,65" size="1530,680" itemHeight="40" enableWrapAround="1" scrollbarMode="showOnDemand"/>
<widget name="key_red" position="10,780" size="320,40" halign="center" font="Regular;30" />
<widget name="key_green" position="340,780" size="320,40" halign="center" font="Regular;30" />
<widget name="key_yellow" position="670,780" size="320,40" halign="center" font="Regular;30" />
<widget name="key_blue" position="1000,780" size="320,40" halign="center" font="Regular;30" />
<eLabel position="10,830" size="320,8" backgroundColor="#9f1313"/>
<eLabel position="340,830" size="320,8" backgroundColor="#1f771f" />
<eLabel position="670,830" size="320,8" backgroundColor="#a08500" />
<eLabel position="1000,830" size="320,8" backgroundColor="#0039f0"/>
<eLabel font="Regular;30" foregroundColor="#aaaaaa" position="1350,810" size="90,35" text="Menu" />
<eLabel font="Regular;30" foregroundColor="#aaaaaa" position="1470,810" size="80,35" text="Info" />
</screen>
"""
else:
self.skin = """
<!-- UHD screen -->
<screen name="FritzCallSetup" position="center,center" size="3180,1540" title="FritzCall Setup" >
<widget name="consideration" position="10,10" halign="center" foregroundColor="#bab329" size="3160,80" font="Regular;65"/>
<eLabel position="10,100" size="3160,4" backgroundColor="#aaaaaa" />
<widget name="config" position="10,110" size="3160,1260" itemHeight="70" enableWrapAround="1" scrollbarMode="showOnDemand"/>
<widget name="key_red" position="10,1420" size="600,70" halign="center" font="Regular;60" />
<widget name="key_green" position="660,1420" size="600,70" halign="center" font="Regular;60" />
<widget name="key_yellow" position="1310,1420" size="600,70" halign="center" font="Regular;60" />
<widget name="key_blue" position="1950,1420" size="600,70" halign="center" font="Regular;60" />
<eLabel position="10,1510" size="600,20" backgroundColor="#9f1313"/>
<eLabel position="660,1510" size="600,20" backgroundColor="#1f771f" />
<eLabel position="1310,1510" size="600,20" backgroundColor="#a08500" />
<eLabel position="1950,1510" size="600,20" backgroundColor="#0039f0"/>
<eLabel font="Regular;65" foregroundColor="#aaaaaa" position="2700,1445" size="280,75" text="Menu" />
<eLabel font="Regular;65" foregroundColor="#aaaaaa" position="3000,1445" size="160,75" text="Info" />
</screen>
"""
Screen.__init__(self, session)
HelpableScreen.__init__(self)
self.session = session
self["consideration"] = Label(_("You need to enable the monitoring on your FRITZ!Box by dialing #96*5*!"))
self.list = []
# Initialize Buttons
# TRANSLATORS: keep it short, this is a button
self["key_red"] = Button(_("Cancel"))
# TRANSLATORS: keep it short, this is a button
self["key_green"] = Button(_("OK"))
# TRANSLATORS: keep it short, this is a button
self["key_yellow"] = Button(_("Phone calls"))
# TRANSLATORS: keep it short, this is a button
self["key_blue"] = Button(_("Phonebook"))
# TRANSLATORS: keep it short, this is a button
self["key_info"] = Button(_("About FritzCall"))
# TRANSLATORS: keep it short, this is a button
self["key_menu"] = Button(_("FRITZ!Box Fon Status"))
self["setupActions"] = ActionMap(["ColorActions", "OkCancelActions", "MenuActions", "EPGSelectActions"],
{
"red": self.cancel,
"green": self.save,
"yellow": self.displayCalls,
"blue": self.displayPhonebook,
"cancel": self.cancel,
"ok": self.save,
"menu": self.menu,
"info": self.about,
}, -2)
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "ColorActions", [("red", _("quit"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "ColorActions", [("green", _("save and quit"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "ColorActions", [("yellow", _("display calls"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "ColorActions", [("blue", _("display phonebook"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "OkCancelActions", [("ok", _("save and quit"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "OkCancelActions", [("cancel", _("quit"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "MenuActions", [("menu", _("FRITZ!Box Fon Status"))]))
# TRANSLATORS: keep it short, this is a help text
self.helpList.append((self["setupActions"], "EPGSelectActions", [("info", _("About FritzCall"))]))
ConfigListScreen.__init__(self, self.list, session = session)
try:
config.plugins.FritzCall.guestPassword.value = decode(config.plugins.FritzCall.guestPassword.value)
except binascii.Error:
config.plugins.FritzCall.guestPassword.value = ""
try:
config.plugins.FritzCall.password.value = decode(config.plugins.FritzCall.password.value)
except binascii.Error:
config.plugins.FritzCall.password.value = ""
# get new list of locations for Phonebook.json
self.createSetup()
self.onLayoutFinish.append(self.setWindowTitle)
def setWindowTitle(self):
# TRANSLATORS: this is a window title.
self.setTitle(_("FritzCall Setup") + " (" + "$Revision: 1591 $"[1:-1] + "$Date: 2021-04-29 16:52:10 +0200 (Thu, 29 Apr 2021) $"[7:23] + ")")
def keyLeft(self):
ConfigListScreen.keyLeft(self)
self.createSetup()
def keyRight(self):
ConfigListScreen.keyRight(self)
self.createSetup()
def createSetup(self):
self.list = []
self.list.append(getConfigListEntry(_("Call monitoring"), config.plugins.FritzCall.enable))
if config.plugins.FritzCall.enable.value:
self.list.append(getConfigListEntry(_("FRITZ!Box FON address (Name or IP)"), config.plugins.FritzCall.hostname))
self.list.append(getConfigListEntry(_("FRITZ!Box FON firmware version"), config.plugins.FritzCall.fwVersion))
self.list.append(getConfigListEntry(_("Show after Standby"), config.plugins.FritzCall.afterStandby))
self.list.append(getConfigListEntry(_("Show only calls for specific MSN"), config.plugins.FritzCall.filter))
if config.plugins.FritzCall.filter.value:
self.list.append(getConfigListEntry(_("MSN to show (separated by ,)"), config.plugins.FritzCall.filtermsn))
self.list.append(getConfigListEntry(_("Filter also list of calls"), config.plugins.FritzCall.filterCallList))
self.list.append(getConfigListEntry(_("Mute on incoming call"), config.plugins.FritzCall.muteOnCall))
self.list.append(getConfigListEntry(_("Mute on outgoing calls"), config.plugins.FritzCall.muteOnOutgoingCall))
self.list.append(getConfigListEntry(_("Show Blocked Calls"), config.plugins.FritzCall.showBlacklistedCalls))
self.list.append(getConfigListEntry(_("Show Outgoing Calls"), config.plugins.FritzCall.showOutgoingCalls))
# not only for outgoing: config.plugins.FritzCall.showOutgoingCalls.value:
self.list.append(getConfigListEntry(_("Areacode to add to calls without one (if necessary)"), config.plugins.FritzCall.prefix))
self.list.append(getConfigListEntry(_("Timeout for Call Notifications (seconds)"), config.plugins.FritzCall.timeout))
self.list.append(getConfigListEntry(_("Country"), config.plugins.FritzCall.country))
if config.plugins.FritzCall.country.value:
self.list.append(getConfigListEntry(_("Reverse Lookup Caller ID"), config.plugins.FritzCall.lookup))
config.plugins.FritzCall.countrycode.value = config.plugins.FritzCall.country.value
# else:
self.list.append(getConfigListEntry(_("Countrycode (e.g. 0044 for UK, 0034 for Spain, etc.)"), config.plugins.FritzCall.countrycode))
if config.plugins.FritzCall.fwVersion.value is not None:
if config.plugins.FritzCall.fwVersion.value == "05.50" or config.plugins.FritzCall.fwVersion.value == "06.35"or config.plugins.FritzCall.fwVersion.value == "upnp":
self.list.append(getConfigListEntry(_("User name Accessing FRITZ!Box"), config.plugins.FritzCall.username))
self.list.append(getConfigListEntry(_("Password Accessing FRITZ!Box"), config.plugins.FritzCall.password))
self.list.append(getConfigListEntry(_("Extension number to initiate call on"), config.plugins.FritzCall.extension))
# if config.plugins.FritzCall.fwVersion.value == "05.50" or config.plugins.FritzCall.fwVersion.value == "06.35":
# self.list.append(getConfigListEntry(_("Name of WLAN guest network"), config.plugins.FritzCall.guestSSID))
# self.list.append(getConfigListEntry(_("Secure WLAN guest network"), config.plugins.FritzCall.guestSecure))
# self.list.append(getConfigListEntry(_("Password of WLAN guest network"), config.plugins.FritzCall.guestPassword))
# self.list.append(getConfigListEntry(_("Minutes of uptime of WLAN guest network"), config.plugins.FritzCall.guestUptime))
self.list.append(getConfigListEntry(_("Read PhoneBook from FRITZ!Box"), config.plugins.FritzCall.fritzphonebook))
if config.plugins.FritzCall.fritzphonebook.value:
self.list.append(getConfigListEntry(_("FRITZ!Box PhoneBook to read"), config.plugins.FritzCall.fritzphonebookName))
if config.plugins.FritzCall.fwVersion.value == "06.35":
self.list.append(getConfigListEntry(_("Show also internal numbers"), config.plugins.FritzCall.fritzphonebookShowInternal))
self.list.append(getConfigListEntry(_("Append type of number"), config.plugins.FritzCall.showType))
self.list.append(getConfigListEntry(_("Append shortcut number"), config.plugins.FritzCall.showShortcut))
self.list.append(getConfigListEntry(_("Append vanity name"), config.plugins.FritzCall.showVanity))
else:
config.plugins.FritzCall.fritzphonebook.value = False
self.list.append(getConfigListEntry(_("Use internal PhoneBook"), config.plugins.FritzCall.phonebook))
if config.plugins.FritzCall.phonebook.value:
if config.plugins.FritzCall.lookup.value:
self.list.append(getConfigListEntry(_("Automatically add new Caller to PhoneBook"), config.plugins.FritzCall.addcallers))
self.list.append(getConfigListEntry(_("PhoneBook and Faces Location"), config.plugins.FritzCall.phonebookLocation))
if config.plugins.FritzCall.phonebook.value or config.plugins.FritzCall.fritzphonebook.value:
self.list.append(getConfigListEntry(_("Reload interval for phonebooks (hours)"), config.plugins.FritzCall.reloadPhonebookTime))
if config.plugins.FritzCall.phonebook.value or config.plugins.FritzCall.fritzphonebook.value:
self.list.append(getConfigListEntry(_("Extended Search for names"), config.plugins.FritzCall.FritzExtendedSearchNames))
self.list.append(getConfigListEntry(_("Extended Search for faces"), config.plugins.FritzCall.FritzExtendedSearchFaces))
self.list.append(getConfigListEntry(_("Strip Leading 0"), config.plugins.FritzCall.internal))
# self.list.append(getConfigListEntry(_("Default display mode for FRITZ!Box calls"), config.plugins.FritzCall.fbfCalls))
self.list.append(getConfigListEntry(_("Display connection infos"), config.plugins.FritzCall.connectionVerbose))
self.list.append(getConfigListEntry(_("Ignore callers with no phone number"), config.plugins.FritzCall.ignoreUnknown))
self.list.append(getConfigListEntry(_("Log level"), config.plugins.FritzCall.debug))
self.list.append(getConfigListEntry(_("Use HTTPS to communicate with FRITZ!Box"), config.plugins.FritzCall.useHttps))
self["config"].list = self.list
self["config"].l.setList(self.list)
def save(self):
# debug("[FritzCallSetup]"
global fritzbox
if self["config"].getCurrent()[1] == config.plugins.FritzCall.phonebookLocation:
self.session.openWithCallback(self.LocationBoxClosed, LocationBox, _("PhoneBook and Faces Location"), currDir = config.plugins.FritzCall.phonebookLocation.value)
if fritzbox and config.plugins.FritzCall.password.isChanged():
fritzbox.password = config.plugins.FritzCall.password.value
config.plugins.FritzCall.password.value = encode(config.plugins.FritzCall.password.value)
if fritzbox and config.plugins.FritzCall.guestPassword.isChanged():
fritzbox.guestPassword = config.plugins.FritzCall.guestPassword.value
config.plugins.FritzCall.guestPassword.value = encode(config.plugins.FritzCall.guestPassword.value)
for x in self["config"].list:
# debug("Save %s", repr(x[1].value))
x[1].save()
if not config.plugins.FritzCall.fwVersion.value:
Notifications.AddNotification(MessageBox, _("To enjoy more functionalities of your FRITZ!Box, configure the firmware version!"), type = MessageBox.TYPE_INFO, timeout = 4)
fritzbox = FritzCallFBF.FritzCallFBF_dummy()
config.plugins.FritzCall.fritzphonebook.value = False
elif config.plugins.FritzCall.fwVersion.value == "old":
fritzbox = FritzCallFBF.FritzCallFBF()
elif config.plugins.FritzCall.fwVersion.value == "05.27":
fritzbox = FritzCallFBF.FritzCallFBF_05_27()
elif config.plugins.FritzCall.fwVersion.value == "05.50":
fritzbox = FritzCallFBF.FritzCallFBF_05_50()
elif config.plugins.FritzCall.fwVersion.value == "06.35":
# fritzbox = FritzCallFBF.FritzCallFBF_06_35()
# elif config.plugins.FritzCall.fwVersion.value == "upnp":
fritzbox = FritzCallFBF.FritzCallFBF_upnp()
else:
Notifications.AddNotification(MessageBox, _("FRITZ!Box firmware version not configured! Please set it in the configuration."), type = MessageBox.TYPE_INFO, timeout = 0)
phonebook.reload()
logger.setLevel(int(config.plugins.FritzCall.debug.value))
if fritz_call:
if config.plugins.FritzCall.enable.value:
fritz_call.connect()
else:
fritz_call.shutdown()
self.close()
def LocationBoxClosed(self, path):
if path is not None:
config.plugins.FritzCall.phonebookLocation.setValue(path)
def cancel(self):
# debug("[FritzCallSetup]"
config.plugins.FritzCall.password.value = encode(config.plugins.FritzCall.password.value)
config.plugins.FritzCall.guestPassword.value = encode(config.plugins.FritzCall.guestPassword.value)
for x in self["config"].list:
x[1].cancel()
self.close()
def displayCalls(self):
if config.plugins.FritzCall.enable.value:
if fritzbox and config.plugins.FritzCall.fwVersion.value:
self.session.open(FritzDisplayCalls)
else:
self.session.open(MessageBox, _("Cannot get calls from FRITZ!Box"), type = MessageBox.TYPE_INFO)
else:
self.session.open(MessageBox, _("Plugin not enabled"), type = MessageBox.TYPE_INFO)
def displayPhonebook(self):
if phonebook:
if config.plugins.FritzCall.enable.value:
self.session.open(phonebook.FritzDisplayPhonebook)
else:
self.session.open(MessageBox, _("Plugin not enabled"), type = MessageBox.TYPE_INFO)
else:
self.session.open(MessageBox, _("No phonebook"), type = MessageBox.TYPE_INFO)
def about(self):
self.session.open(FritzAbout)
def menu(self):
if config.plugins.FritzCall.enable.value:
if fritzbox and fritzbox.information:
self.session.open(FritzMenu)
else:
self.session.open(MessageBox, _("Cannot get infos from FRITZ!Box yet\nStill initialising or wrong firmware version"), type = MessageBox.TYPE_INFO)
else:
self.session.open(MessageBox, _("Plugin not enabled"), type = MessageBox.TYPE_INFO)
standbyMode = False
class FritzCallList(object):
def __init__(self):
self.callList = []
def add(self, event, date, number, caller, phone):
debug("[FritzCallList] %s %s", number, caller)
if len(self.callList) > 10:
if self.callList[0] != "Start":
self.callList[0] = "Start"
del self.callList[1]
self.callList.append((event, number, date, caller, phone))
def display(self):
debug("[FritzCallList]")
global standbyMode
standbyMode = False
# Standby.inStandby.onClose.remove(self.display) object does not exist anymore...
# build screen from call list
text = "\n"
if not self.callList: # why is this happening at all?!?!
text = _("no calls")
debug("[FritzCallList] %s", text)
return
else:
if self.callList[0] == "Start":
text = text + _("Last 10 calls:\n")
del self.callList[0]
for call in self.callList:
(event, number, date, caller, phone) = call
if event == "RING":
direction = "->"
else:
direction = "<-"
# shorten the date information
date = date[:6] + date[9:14]
# our phone could be of the form "0123456789 (home)", then we only take "home"
oBrack = phone.find('(')
cBrack = phone.find(')')
if oBrack != -1 and cBrack != -1:
phone = phone[oBrack + 1:cBrack]
# should not happen, for safety reasons
if not caller:
caller = _("UNKNOWN")
# if we have an unknown number, show the number
if caller == _("UNKNOWN") and number != "":
caller = number
else:
# strip off the address part of the remote caller/callee, if there is any
nl = caller.find('\n')
if nl != -1:
caller = caller[:nl]
elif caller[0] == '[' and caller[-1] == ']':
# that means, we've got an unknown number with a city added from avon.dat
if (len(number) + 1 + len(caller) + len(phone)) <= 40:
caller = number + ' ' + caller
else:
caller = number
while (len(caller) + len(phone)) > 40:
if len(caller) > len(phone):
caller = caller[:-1]
else:
phone = phone[:-1]
text = text + "%s %s %s %s\n" % (date, caller, direction, phone)
debug("[FritzCallList] '%s %s %s %s'", date, caller, direction, phone)
# display screen
Notifications.AddNotification(MessageBox, text, type = MessageBox.TYPE_INFO)
self.callList = []
callList = FritzCallList()
def findFace(number, name):
# debug("[FritzCall] number/name: %s/%s" % (number, name))
if name:
sep = name.find(',')
if sep != -1:
name = name[:sep]
sep = name.find('\n')
if sep != -1:
name = name[:sep]
else:
name = _("UNKNOWN")
# debug("[FritzCall] looking for: %s" %name)
facesDir = os.path.join(config.plugins.FritzCall.phonebookLocation.value, "FritzCallFaces")
# debug("[FritzCall] looking in: %s" %facesDir)
facesFile = None
if not os.path.isdir(facesDir):
info("[FritzCall] findFace facesdir does not exist: %s", facesDir)
else:
files = os.listdir(facesDir)
# debug("[FritzCall] listdir: %s" %repr(files))
myFiles = [f for f in files if re.match(re.escape(number) + r"\.[png|PNG]", f)]
if not myFiles:
myFiles = [f for f in files if re.match(re.escape(name) + r"\.[png|PNG]", f)]
if not myFiles:
sep = name.find(' (')
if sep != -1:
name = name[:sep]
myFiles = [f for f in files if re.match(re.escape(name) + r"\.[png|PNG]", f)]
if myFiles:
# debug("[FritzCall] found: %s" %repr(myFiles))
facesFile = os.path.join(facesDir, myFiles[0])
if not facesFile and config.plugins.FritzCall.FritzExtendedSearchFaces.value:
for k in range(len(number) - 1, 0, -1):
# debug("[FritzCall] extended search: %s" %number[:k])
myFiles = [f for f in files if re.match(re.escape(number[:k]) + r"\.[png|PNG]", f)]
if myFiles:
facesFile = os.path.join(facesDir, myFiles[0])
break
if not facesFile:
if DESKTOP_WIDTH <= 720:
facesFile = resolveFilename(SCOPE_CURRENT_PLUGIN, "Extensions/FritzCall/images/no-face-sd.png")
elif DESKTOP_WIDTH <= 1280:
facesFile = resolveFilename(SCOPE_CURRENT_PLUGIN, "Extensions/FritzCall/images/no-face-hd.png")
elif DESKTOP_WIDTH <= 1920:
facesFile = resolveFilename(SCOPE_CURRENT_PLUGIN, "Extensions/FritzCall/images/no-face-fhd.png")
else:
facesFile = resolveFilename(SCOPE_CURRENT_PLUGIN, "Extensions/FritzCall/images/no-face-uhd.png")
info("[FritzCall] result: %s", __(facesFile))
return facesFile
class MessageBoxPixmap(Screen):
def __init__(self, session, text, number = "", name = "", timeout = -1):
if DESKTOP_WIDTH <= 720:
self.skin = """
<!-- SD screen -->
<screen name="MessageBoxPixmap" position="center,center" size="490,200" title="New Call">
<widget name="InfoPixmap" position="10,10" size="160,160" alphatest="blend" />
<widget name="text" halign="left" valign="center" position="220,10" size="260,180" font="Regular;18"/>
</screen>
"""
elif DESKTOP_WIDTH <= 1280:
self.skin = """
<!-- HD screen -->
<screen name="MessageBoxPixmap" position="center,center" size="700,270" title="New Call">
<widget name="InfoPixmap" position="10,10" size="230,230" alphatest="blend" />
<widget name="text" halign="left" valign="center" position="290,10" size="400,250" font="Regular;20"/>
</screen>
"""
elif DESKTOP_WIDTH <= 1920:
self.skin = """
<!-- Fullhd screen -->
<screen name="MessageBoxPixmap" position="center,center" size="1150,420" title="New Call">
<widget name="InfoPixmap" position="10,10" size="400,400" alphatest="blend" />
<widget name="text" halign="left" valign="center" position="470,10" size="670,400" font="Regular;30"/>
</screen>
"""
else:
self.skin = """
<!-- UHD screen -->
<screen name="MessageBoxPixmap" position="center,center" size="2080,820" title="New Call">
<widget name="InfoPixmap" position="10,10" size="800,800" alphatest="blend" />
<widget name="text" halign="left" valign="center" position="900,10" size="1150,800" font="Regular;60"/>
</screen>
"""
Screen.__init__(self, session)
# MessageBox.__init__(self, session, text, type=MessageBox.TYPE_INFO, timeout=timeout)
self["text"] = Label(text)
self["InfoPixmap"] = Pixmap()
self._session = session
self._number = number
self._name = name
self._timerRunning = False
self._timer = None
self._timeout = timeout
self._origTitle = None
self._initTimeout()
self.onLayoutFinish.append(self._finishLayout)
self["actions"] = ActionMap(["OkCancelActions"],
{
"cancel": self._exit,
"ok": self._exit, }, -2)
def _finishLayout(self):
debug("[FritzCall] MessageBoxPixmap/setInfoPixmap number: %s/%s", self._number, self._name)
self.setTitle(_("New call"))
faceFile = findFace(self._number, self._name)
picPixmap = LoadPixmap(faceFile)
if not picPixmap: # that means most probably, that the picture is not 8 bit...
Notifications.AddNotification(MessageBox, _("Found picture\n\n%s\n\nBut did not load. Probably not PNG, 8-bit") % faceFile, type = MessageBox.TYPE_ERROR)
if DESKTOP_WIDTH <= 720:
picPixmap = LoadPixmap(resolveFilename(SCOPE_CURRENT_PLUGIN, "Extensions/FritzCall/images/no-face-error-sd.png"))
elif DESKTOP_WIDTH <= 1280:
picPixmap = LoadPixmap(resolveFilename(SCOPE_CURRENT_PLUGIN, "Extensions/FritzCall/images/no-face-error-hd.png"))
elif DESKTOP_WIDTH <= 1920:
picPixmap = LoadPixmap(resolveFilename(SCOPE_CURRENT_PLUGIN, "Extensions/FritzCall/images/no-face-error-fhd.png"))
else:
picPixmap = LoadPixmap(resolveFilename(SCOPE_CURRENT_PLUGIN, "Extensions/FritzCall/images/no-face-error-uhd.png"))
self["InfoPixmap"].instance.setPixmap(picPixmap)
def _initTimeout(self):
if self._timeout > 0:
self._timer = eTimer()
# newer OE versions don't have the callback
try:
self._timer_conn = self._timer.timeout.connect(self._timerTick)
except AttributeError:
self._timer.callback.append(self._timerTick)
self.onExecBegin.append(self._startTimer)
self._origTitle = None
if self.execing:
self._timerTick()
else:
self.onShown.append(self.__onShown)
self._timerRunning = True
else:
self._timerRunning = False
def __onShown(self):
self.onShown.remove(self.__onShown)
self._timerTick()
def _startTimer(self):
self._timer.start(1000)
#===============================================================================
# def stopTimer(self):
# if self._timerRunning:
# del self._timer
# self.setTitle(self._origTitle)
# self._timerRunning = False
#===============================================================================
def _timerTick(self):
if self.execing:
self._timeout -= 1
if self._origTitle is None:
self._origTitle = self.instance.getTitle()
self.setTitle(self._origTitle + " (" + str(self._timeout) + ")")
if self._timeout == 0:
self._timer.stop()
self._timerRunning = False
self._exit()
def _exit(self):
self.close()
def runUserActionScript(event, date, number, caller, phone):
# user exit
# call FritzCallserAction.sh in the same dir as Phonebook.json with the following parameters:
# event: "RING" (incomning) or "CALL" (outgoing)
# date of event, format: "dd.mm.yy hh.mm.ss"
# telephone number which is calling/is called
# caller's name and address, format Name\n Street\n ZIP City
# line/number which is called/which is used for calling
userActionScript = os.path.join(config.plugins.FritzCall.phonebookLocation.value, "FritzCallUserAction.sh")
if os.path.exists(userActionScript) and os.access(userActionScript, os.X_OK):
cmd = userActionScript + ' "' + event + '" "' + date + '" "' + number + '" "' + caller + '" "' + phone + '"'
info("[FritzCall] calling: %s", cmd)
eConsoleAppContainer().execute(cmd)
userActionList = [runUserActionScript]
def registerUserAction(fun):
#===========================================================================
# other plugins can register a function, which is then called for each displayed call
# it must take the arguments event,date,number,caller,phone
#
# example:
# def FritzCallEvent(event,date,number,caller,phone):
# ......
#
# try:
# from Plugins.Extensions.FritzCall.plugin import registerUserAction as FritzCallRegisterUserAction
# FritzCallRegisterUserAction(FritzCallEvent)
# except:
# print "import of FritzCall failed"
#===========================================================================
info("[FritzCall] register: %s", fun.__name__)
userActionList.append(fun)
mutedOnConnID = None
def notifyCall(event, date, number, caller, phone, connID): # @UnusedVariable # pylint: disable=W0613
event = six.ensure_str(event)
date = six.ensure_str(date)
number = six.ensure_str(number)
caller = six.ensure_str(caller)
phone = six.ensure_str(phone)
connID = six.ensure_str(connID)
if Standby.inStandby is None or config.plugins.FritzCall.afterStandby.value == "each":
if event == "RING":
text = _("Incoming Call on %(date)s at %(time)s from\n---------------------------------------------\n%(number)s\n%(caller)s\n---------------------------------------------\nto: %(phone)s") % {'date':date[:8], 'time':date[9:], 'number':number, 'caller':caller, 'phone':phone}
else:
text = _("Outgoing Call on %(date)s at %(time)s to\n---------------------------------------------\n%(number)s\n%(caller)s\n---------------------------------------------\nfrom: %(phone)s") % {'date':date[:8], 'time':date[9:], 'number':number, 'caller':caller, 'phone':phone}
info("[FritzCall]\n%s", text)
# Notifications.AddNotification(MessageBox, text, type=MessageBox.TYPE_INFO, timeout=config.plugins.FritzCall.timeout.value)
Notifications.AddNotification(MessageBoxPixmap, text, number = number, name = caller, timeout = config.plugins.FritzCall.timeout.value)
elif config.plugins.FritzCall.afterStandby.value == "inList":
#
# if not yet done, register function to show call list
global standbyMode
if not standbyMode:
standbyMode = True
Standby.inStandby.onHide.append(callList.display) # @UndefinedVariable
# add text/timeout to call list
callList.add(event, date, number, caller, phone)
info("[FritzCall] added to callList")
else: # this is the "None" case
info("[FritzCall] standby and no show")
for fun in userActionList:
info("[FritzCall] call user action: %s", fun.__name__)
fun(event, date, number, caller, phone)
#===============================================================================
# We need a separate class for each invocation of reverseLookup to retain
# the necessary data for the notification
#===============================================================================
countries = {}
reverselookupMtime = 0
class FritzReverseLookupAndNotifier(object):
def __init__(self, event, number, caller, phone, date, connID):
'''
Initiate a reverse lookup for the given number in the configured country
@param event: CALL or RING
@param number: number to be looked up
@param caller: caller including name and address
@param phone: Number (and name) of or own phone
@param date: date of call
'''
info("[FritzReverseLookupAndNotifier] reverse Lookup for %s!", number)
self.event = event
self.number = number
self.caller = caller
self.phone = phone
self.date = date
self.connID = connID
if number[0] != "0":
self.notifyAndReset(number, caller)
return
ReverseLookupAndNotifier(number, self.notifyAndReset, "UTF-8", config.plugins.FritzCall.countrycode.value)
def notifyAndReset(self, number, caller):
'''
this gets called with the result of the reverse lookup
@param number: number
@param caller: name and address of remote. it comes in with name, address and city separated by commas
'''
info("[FritzReverseLookupAndNotifier] got: %s", caller)
self.number = number
name = handleReverseLookupResult(caller)
if name:
self.caller = name.replace(", ", "\n")
if self.number != 0 and config.plugins.FritzCall.addcallers.value:
info("[FritzReverseLookupAndNotifier] add to phonebook")
phonebook.add(self.number, self.caller)
else:
name = resolveNumberWithAvon(self.number, config.plugins.FritzCall.countrycode.value)
if not name:
self.caller = _("UNKNOWN")
else:
self.caller = name
notifyCall(self.event, self.date, self.number, self.caller, self.phone, self.connID)
# kill that object...
class FritzProtocol(LineReceiver): # pylint: disable=W0223
def __init__(self):
info("[FritzProtocol] %s%s starting", "$Revision: 1591 $"[1:-1], "$Date: 2021-04-29 16:52:10 +0200 (Thu, 29 Apr 2021) $"[7:23])
global mutedOnConnID
mutedOnConnID = None
self.number = '0'
self.caller = None
self.phone = None
self.date = '0'
self.event = None
self.connID = None
def resetValues(self):
debug("[FritzProtocol]")
self.number = '0'
self.caller = None
self.phone = None
self.date = '0'
self.event = None
self.connID = None
def notifyAndReset(self):
notifyCall(self.event, self.date, self.number, self.caller, self.phone, self.connID)
self.resetValues()
# def pauseEnigma2(self):
# debug("")
# getPage("http://127.0.0.1/web/remotecontrol?command=164").addCallback(self.pauseEnigma2_cb).addErrback(self.pauseEnigma2_eb)
#
# def pauseEnigma2_cb(self, result):
# debug(repr(result))
#
# def pauseEnigma2_eb(self, result):
# debug(repr(result))
def lineReceived(self, line):
debug("[FritzProtocol] %s", line)
# 15.07.06 00:38:54;CALL;1;4;<from/our msn>;<to/extern>;
# 15.07.06 00:38:58;DISCONNECT;1;0;
# 15.07.06 00:39:22;RING;0;<from/extern>;<to/our msn>;
# 15.07.06 00:39:27;DISCONNECT;0;0;
anEvent = six.ensure_str(line).split(';')
(self.date, self.event) = anEvent[0:2]
self.connID = anEvent[2]
filtermsns = config.plugins.FritzCall.filtermsn.value.split(",")
filtermsns = [i.strip() for i in filtermsns]
debug("Filtermsns: %s", filtermsns)
if config.plugins.FritzCall.ignoreUnknown.value:
if self.event == "RING":
if not anEvent[3]:
debug("[FritzProtocol] call from unknown phone; skipping")
return
elif not anEvent[5]:
debug("[FritzProtocol] call to unknown phone; skipping")
return
# debug("[FritzProtocol] Volcontrol dir: %s" % dir(eDVBVolumecontrol.getInstance()))
# debug("[FritzCall] unmute on connID: %s?" %self.connID)
global mutedOnConnID
phone = anEvent[4]
debug("Phone: %s", phone)
if Standby.inStandby is None and not mutedOnConnID:
if not (config.plugins.FritzCall.filter.value and phone not in filtermsns):
info("[FritzCall] check mute")
if (self.event == "RING" and config.plugins.FritzCall.muteOnCall.value) or (self.event == "CALL" and config.plugins.FritzCall.muteOnOutgoingCall.value):
info("[FritzCall] mute on connID: %s", self.connID)
mutedOnConnID = self.connID
# eDVBVolumecontrol.getInstance().volumeMute() # with this, we get no mute icon...
if not eDVBVolumecontrol.getInstance().isMuted():
globalActionMap.actions["volumeMute"]()
# self.pauseEnigma2()
if self.event == "DISCONNECT"and (config.plugins.FritzCall.muteOnCall.value or config.plugins.FritzCall.muteOnOutgoingCall.value) and mutedOnConnID == self.connID:
debug("[FritzCall] unmute on connID: %s!", self.connID)
mutedOnConnID = None
# eDVBVolumecontrol.getInstance().volumeUnMute()
if eDVBVolumecontrol.getInstance().isMuted():
globalActionMap.actions["volumeMute"]()
# self.pauseEnigma2()
# not supported so far, because, taht would mean muting on EVERY connect, regardless of RING or CALL or filter active
#=======================================================================
# elif self.event == "CONNECT" and config.plugins.FritzCall.muteOnCall.value == "connect":
# debug("[FritzCall] mute on connID: %s" % self.connID)
# mutedOnConnID = self.connID
# # eDVBVolumecontrol.getInstance().volumeMute() # with this, we get no mute icon...
# if not eDVBVolumecontrol.getInstance().isMuted():
# globalActionMap.actions["volumeMute"]()
#=======================================================================
elif self.event == "RING" or (self.event == "CALL" and config.plugins.FritzCall.showOutgoingCalls.value):
if self.event == "RING":
number = anEvent[3]
else:
number = anEvent[5]
if fritzbox and fritzbox.blacklist and not config.plugins.FritzCall.showBlacklistedCalls.value:
if self.event == "RING":
if number in fritzbox.blacklist[0]:
info("[FritzProtocol] phone: '''%s''' blacklisted number: '''%s'''", phone, number)
return
else:
if number in fritzbox.blacklist[1]:
info("[FritzProtocol] phone: '''%s''' blacklisted number: '''%s'''", phone, number)
return
info("[FritzProtocol] phone: '''%s''' number: '''%s'''", phone, number)
if not (config.plugins.FritzCall.filter.value and phone not in filtermsns):
debug("[FritzProtocol] no filter hit")
if phone:
phonename = phonebook.search(phone) # do we have a name for the number of our side?
if phonename:
self.phone = "%s (%s)" % (phone, phonename)
else:
self.phone = phone
else:
self.phone = _("UNKNOWN")
if not number:
debug("[FritzProtocol] no number")
self.number = _("number suppressed")
self.caller = _("UNKNOWN")
else:
if config.plugins.FritzCall.internal.value and len(number) > 3 and number[0] == "0":
debug("[FritzProtocol] strip leading 0")
self.number = number[1:]
else:
self.number = number
if self.event == "CALL" and self.number[0] != '0': # should only happen for outgoing
debug("[FritzProtocol] add local prefix")
self.number = config.plugins.FritzCall.prefix.value + self.number
# strip trailing #
if self.number[-1] == "#":
self.number = self.number[:-1]
# strip CbC prefixes
if self.event == "CALL":
self.number = stripCbCPrefix(self.number, config.plugins.FritzCall.countrycode.value)
info("[FritzProtocol] phonebook.search: %s", self.number)
self.caller = phonebook.search(self.number)
info("[FritzProtocol] phonebook.search result: %s", self.caller)
if not self.caller:
if config.plugins.FritzCall.lookup.value:
FritzReverseLookupAndNotifier(self.event, self.number, self.caller, self.phone, self.date, self.connID)
return # reverselookup is supposed to handle the message itself
else:
self.caller = _("UNKNOWN")
self.notifyAndReset()
class FritzClientFactory(ReconnectingClientFactory):
def __init__(self):
self.hangup_ok = False
# self.initialDelay = 20
# self.maxDelay = 30
self.maxRetries = 5
def startedConnecting(self, connector): # @UnusedVariable # pylint: disable=W0613
#=======================================================================
# if not config.plugins.FritzCall.fwVersion.value:
# Notifications.AddNotification(MessageBox, _("FRITZ!Box firmware version not configured! Please set it in the configuration."), type=MessageBox.TYPE_INFO, timeout=0)
#=======================================================================
if config.plugins.FritzCall.connectionVerbose.value == "on":
info("[FRITZ!FritzClientFactory]")
Notifications.AddNotification(MessageBox, _("Connecting to FRITZ!Box..."), type = MessageBox.TYPE_INFO, timeout = 2)
def buildProtocol(self, addr): # @UnusedVariable # pylint: disable=W0613
global fritzbox
if config.plugins.FritzCall.connectionVerbose.value == "on":
info("[FRITZ!FritzClientFactory]")
Notifications.AddNotification(MessageBox, _("Connected to FRITZ!Box!"), type = MessageBox.TYPE_INFO, timeout = 4)
self.resetDelay()
# initDebug()
initCbC()
initAvon()
try:
decode(config.plugins.FritzCall.password.value)
except binascii.Error:
Notifications.AddNotification(MessageBox, _("There might be a problem with your FritzCall %spassword.\nCheck in the configuration.") % "", type = MessageBox.TYPE_WARNING)
config.plugins.FritzCall.password.value = encode(config.plugins.FritzCall.password.value)
config.plugins.FritzCall.password.save()
try:
decode(config.plugins.FritzCall.guestPassword.value)
except binascii.Error:
Notifications.AddNotification(MessageBox, _("There might be a problem with your FritzCall %spassword.\nCheck in the configuration.") % _("guest "), type = MessageBox.TYPE_WARNING)
config.plugins.FritzCall.guestPassword.value = encode(config.plugins.FritzCall.guestPassword.value)
config.plugins.FritzCall.guestPassword.save()
if not config.plugins.FritzCall.fwVersion.value:
Notifications.AddNotification(MessageBox, _("To enjoy more functionalities of your FRITZ!Box, configure the firmware version!"), type = MessageBox.TYPE_INFO, timeout = 4)
fritzbox = FritzCallFBF.FritzCallFBF_dummy()
config.plugins.FritzCall.fritzphonebook.value = False
elif config.plugins.FritzCall.fwVersion.value == "old":
fritzbox = FritzCallFBF.FritzCallFBF()
elif config.plugins.FritzCall.fwVersion.value == "05.27":
fritzbox = FritzCallFBF.FritzCallFBF_05_27()
elif config.plugins.FritzCall.fwVersion.value == "05.50":
fritzbox = FritzCallFBF.FritzCallFBF_05_50()
elif config.plugins.FritzCall.fwVersion.value == "06.35":
# fritzbox = FritzCallFBF.FritzCallFBF_06_35()
# elif config.plugins.FritzCall.fwVersion.value == "upnp":
fritzbox = FritzCallFBF.FritzCallFBF_upnp()
else:
fritzbox = None
Notifications.AddNotification(MessageBox, _("FRITZ!Box firmware version not configured! Please set it in the configuration."), type = MessageBox.TYPE_INFO, timeout = 0)
phonebook.reload()
return FritzProtocol()
def clientConnectionLost(self, connector, reason):
global fritzbox
if not self.hangup_ok and config.plugins.FritzCall.connectionVerbose.value != "off":
warning("[FRITZ!FritzClientFactory] - clientConnectionLost")
Notifications.AddNotification(MessageBox, _("Connection to FRITZ!Box! lost\n (%s)\nretrying...") % reason.getErrorMessage(), type = MessageBox.TYPE_INFO, timeout = config.plugins.FritzCall.timeout.value)
ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
fritzbox = None
def clientConnectionFailed(self, connector, reason):
global fritzbox
if config.plugins.FritzCall.connectionVerbose.value != "off":
Notifications.AddNotification(MessageBox, _("Connecting to FRITZ!Box failed\n (%s)\nretrying...") % reason.getErrorMessage(), type = MessageBox.TYPE_INFO, timeout = config.plugins.FritzCall.timeout.value)
ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
fritzbox = None
class FritzCall(object):
def __init__(self):
self.dialog = None
self.desc = None
if config.plugins.FritzCall.enable.value:
self.connect()
def connect(self):
self.abort()
if config.plugins.FritzCall.enable.value:
fact = FritzClientFactory()
self.desc = (fact, reactor.connectTCP(config.plugins.FritzCall.hostname.value, 1012, fact)) # @UndefinedVariable # pylint: disable=E1101
def shutdown(self):
self.abort()
def abort(self):
if self.desc is not None:
self.desc[0].hangup_ok = True
self.desc[0].stopTrying()
self.desc[1].disconnect()
self.desc = None
def displayCalls(session, servicelist = None): # @UnusedVariable # pylint: disable=W0613
if config.plugins.FritzCall.enable.value:
if fritzbox and config.plugins.FritzCall.fwVersion.value:
session.open(FritzDisplayCalls)
else:
Notifications.AddNotification(MessageBox, _("Cannot get calls from FRITZ!Box"), type = MessageBox.TYPE_INFO)
else:
Notifications.AddNotification(MessageBox, _("Plugin not enabled"), type = MessageBox.TYPE_INFO)
def displayPhonebook(session, servicelist = None): # @UnusedVariable # pylint: disable=W0613
if phonebook:
if config.plugins.FritzCall.enable.value:
session.open(phonebook.FritzDisplayPhonebook)
else:
Notifications.AddNotification(MessageBox, _("Plugin not enabled"), type = MessageBox.TYPE_INFO)
else:
Notifications.AddNotification(MessageBox, _("No phonebook"), type = MessageBox.TYPE_INFO)
def displayFBFStatus(session, servicelist = None): # @UnusedVariable # pylint: disable=W0613
if config.plugins.FritzCall.enable.value:
if fritzbox and fritzbox.information:
session.open(FritzMenu)
else:
Notifications.AddNotification(MessageBox, _("Cannot get infos from FRITZ!Box yet\nStill initialising or wrong firmware version"), type = MessageBox.TYPE_INFO)
else:
Notifications.AddNotification(MessageBox, _("Plugin not enabled"), type = MessageBox.TYPE_INFO)
def main(session, **kwargs): # @UnusedVariable pylint: disable=W0613
session.open(FritzCallSetup)
fritz_call = None
def autostart(reason, **kwargs):
global fritz_call
# ouch, this is a hack
if "session" in kwargs:
global my_global_session
my_global_session = kwargs["session"]
return
info("[FRITZ!Call]")
if reason == 0:
if not fritz_call:
fritz_call = FritzCall()
elif reason == 1:
fritz_call.shutdown()
fritz_call = None
def Plugins(**kwargs): # @UnusedVariable # pylint: disable=W0613,C0103
what = _("Display FRITZ!box-Fon calls on screen")
what_calls = _("Phone calls")
what_phonebook = _("Phonebook")
what_status = _("FRITZ!Box Fon Status")
return [PluginDescriptor(name = "FritzCall", description = what, where = PluginDescriptor.WHERE_PLUGINMENU, icon = "plugin.png", fnc = main),
PluginDescriptor(name = what_calls, description = what_calls, where = PluginDescriptor.WHERE_EXTENSIONSMENU, fnc = displayCalls),
PluginDescriptor(name = what_phonebook, description = what_phonebook, where = PluginDescriptor.WHERE_EXTENSIONSMENU, fnc = displayPhonebook),
PluginDescriptor(name = what_status, description = what_status, where = PluginDescriptor.WHERE_EXTENSIONSMENU, fnc = displayFBFStatus),
PluginDescriptor(where = [PluginDescriptor.WHERE_SESSIONSTART, PluginDescriptor.WHERE_AUTOSTART], fnc = autostart)]
| 48.690381 | 276 | 0.676538 |
acefed6462b029e5c5a7bfa4178ad2df87271771 | 6,125 | py | Python | pkgs/prompt_toolkit-1.0.3-py27_0/lib/python2.7/site-packages/prompt_toolkit/filters/base.py | wangyum/anaconda | 6e5a0dbead3327661d73a61e85414cf92aa52be6 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2017-11-29T18:52:27.000Z | 2017-11-29T18:52:27.000Z | pkgs/prompt_toolkit-1.0.3-py27_0/lib/python2.7/site-packages/prompt_toolkit/filters/base.py | wangyum/anaconda | 6e5a0dbead3327661d73a61e85414cf92aa52be6 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | pkgs/prompt_toolkit-1.0.3-py27_0/lib/python2.7/site-packages/prompt_toolkit/filters/base.py | wangyum/anaconda | 6e5a0dbead3327661d73a61e85414cf92aa52be6 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2020-07-25T12:09:01.000Z | 2020-07-25T12:09:01.000Z | from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
from six import with_metaclass
from .types import test_callable_args
__all__ = (
'Filter',
'Never',
'Always',
'Condition',
)
class Filter(with_metaclass(ABCMeta, object)):
"""
Filter to activate/deactivate a feature, depending on a condition.
The return value of ``__call__`` will tell if the feature should be active.
"""
@abstractmethod
def __call__(self, *a, **kw):
"""
The actual call to evaluate the filter.
"""
return True
def __and__(self, other):
"""
Chaining of filters using the & operator.
"""
if isinstance(other, Always) or isinstance(self, Never):
return self
elif isinstance(other, Never) or isinstance(self, Always):
return other
else:
assert isinstance(other, Filter), 'Expecting filter, got %r' % other
return _and(self, other)
def __or__(self, other):
"""
Chaining of filters using the | operator.
"""
if isinstance(other, Always) or isinstance(self, Never):
return other
elif isinstance(other, Never) or isinstance(self, Always):
return self
else:
assert isinstance(other, Filter), 'Expecting filter, got %r' % other
return _or(self, other)
def __invert__(self):
"""
Inverting of filters using the ~ operator.
"""
return _Invert(self)
def __bool__(self):
"""
By purpose, we don't allow bool(...) operations directly on a filter,
because because the meaning is ambigue.
Executing a filter has to be done always by calling it. Providing
defaults for `None` values should be done through an `is None` check
instead of for instance ``filter1 or Always()``.
"""
raise TypeError
__nonzero__ = __bool__ # For Python 2.
def test_args(self, *args):
"""
Test whether this filter can be called with the following argument list.
"""
return test_callable_args(self.__call__, args)
class _AndCache(dict):
"""
Cache for And operation between filters.
(Filter classes are stateless, so we can reuse them.)
Note: This could be a memory leak if we keep creating filters at runtime.
If that is True, the filters should be weakreffed (not the tuple of
filters), and tuples should be removed when one of these filters is
removed. In practise however, there is a finite amount of filters.
"""
def __missing__(self, filters):
result = _AndList(filters)
self[filters] = result
return result
class _OrCache(dict):
""" Cache for Or operation between filters. """
def __missing__(self, filters):
result = _OrList(filters)
self[filters] = result
return result
_and_cache = _AndCache()
_or_cache = _OrCache()
def _and(filter1, filter2):
"""
And operation between two filters.
"""
return _and_cache[filter1, filter2]
def _or(filter1, filter2):
"""
Or operation between two filters.
"""
return _or_cache[filter1, filter2]
class _AndList(Filter):
"""
Result of &-operation between several filters.
"""
def __init__(self, filters):
all_filters = []
for f in filters:
if isinstance(f, _AndList): # Turn nested _AndLists into one.
all_filters.extend(f.filters)
else:
all_filters.append(f)
self.filters = all_filters
def test_args(self, *args):
return all(f.test_args(*args) for f in self.filters)
def __call__(self, *a, **kw):
return all(f(*a, **kw) for f in self.filters)
def __repr__(self):
return '&'.join(repr(f) for f in self.filters)
class _OrList(Filter):
"""
Result of |-operation between several filters.
"""
def __init__(self, filters):
all_filters = []
for f in filters:
if isinstance(f, _OrList): # Turn nested _OrLists into one.
all_filters.extend(f.filters)
else:
all_filters.append(f)
self.filters = all_filters
def test_args(self, *args):
return all(f.test_args(*args) for f in self.filters)
def __call__(self, *a, **kw):
return any(f(*a, **kw) for f in self.filters)
def __repr__(self):
return '|'.join(repr(f) for f in self.filters)
class _Invert(Filter):
"""
Negation of another filter.
"""
def __init__(self, filter):
self.filter = filter
def __call__(self, *a, **kw):
return not self.filter(*a, **kw)
def __repr__(self):
return '~%r' % self.filter
def test_args(self, *args):
return self.filter.test_args(*args)
class Always(Filter):
"""
Always enable feature.
"""
def __call__(self, *a, **kw):
return True
def __invert__(self):
return Never()
class Never(Filter):
"""
Never enable feature.
"""
def __call__(self, *a, **kw):
return False
def __invert__(self):
return Always()
class Condition(Filter):
"""
Turn any callable (which takes a cli and returns a boolean) into a Filter.
This can be used as a decorator::
@Condition
def feature_is_active(cli): # `feature_is_active` becomes a Filter.
return True
:param func: Callable which takes either a
:class:`~prompt_toolkit.interface.CommandLineInterface` or nothing and
returns a boolean. (Depending on what it takes, this will become a
:class:`.Filter` or :class:`~prompt_toolkit.filters.CLIFilter`.)
"""
def __init__(self, func):
assert callable(func)
self.func = func
def __call__(self, *a, **kw):
return self.func(*a, **kw)
def __repr__(self):
return 'Condition(%r)' % self.func
def test_args(self, *a):
return test_callable_args(self.func, a)
| 25.95339 | 80 | 0.604898 |
acefed93e3b0cd44c94d5fccd1f3a594daef3229 | 65,795 | py | Python | fairseq/trainer.py | SeunghyunSEO/seosh_fairseq | 443b2a8effb6b8fba5758989076cf992470ccb62 | [
"MIT"
] | null | null | null | fairseq/trainer.py | SeunghyunSEO/seosh_fairseq | 443b2a8effb6b8fba5758989076cf992470ccb62 | [
"MIT"
] | 2 | 2022-02-22T08:28:06.000Z | 2022-02-22T09:26:26.000Z | fairseq/trainer.py | SeunghyunSEO/seosh_fairseq | 443b2a8effb6b8fba5758989076cf992470ccb62 | [
"MIT"
] | null | null | null | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Train a network across multiple GPUs.
"""
import contextlib
import logging
import os
import sys
import time
from argparse import Namespace
from itertools import chain
from typing import Any, Dict, List
import torch
from omegaconf import OmegaConf
from fairseq import checkpoint_utils, models, optim, utils
from fairseq.dataclass.configs import FairseqConfig
from fairseq.dataclass.utils import convert_namespace_to_omegaconf
from fairseq.distributed import utils as distributed_utils
from fairseq.file_io import PathManager
from fairseq.logging import meters, metrics
from fairseq.models.ema import build_ema
from fairseq.nan_detector import NanDetector
from fairseq.optim import lr_scheduler
from fairseq.utils import safe_hasattr
logger = logging.getLogger(__name__)
class Trainer(object):
"""Main class for data parallel training.
This class supports synchronous distributed data parallel training,
where multiple workers each have a full model replica and gradients
are accumulated across workers before each update. We use
:class:`~torch.nn.parallel.DistributedDataParallel` to handle
communication of the gradients across workers.
"""
def __init__(self, cfg: FairseqConfig, task, model, criterion, quantizer=None):
if isinstance(cfg, Namespace):
logger.warning(
"argparse.Namespace configuration is deprecated! Automatically converting to OmegaConf"
)
cfg = convert_namespace_to_omegaconf(cfg)
self.cfg = cfg
self.task = task
# catalog shared parameters
shared_params = _catalog_shared_params(model)
self.tpu = cfg.common.tpu
self.cuda = torch.cuda.is_available() and not cfg.common.cpu and not self.tpu
if self.cuda:
self.device = torch.device("cuda")
elif self.tpu:
self.device = utils.get_tpu_device()
else:
self.device = torch.device("cpu")
if self.is_fsdp:
import fairscale
if self.cfg.common.bf16:
raise ValueError(
"FullyShardedDataParallel is not compatible with --bf16 or "
"--memory-efficient-bf16"
)
if self.cfg.distributed_training.zero_sharding != "none":
raise ValueError(
"FullyShardedDataParallel is not compatible with --zero-sharding "
"option (it's already built in)"
)
if (
max(self.cfg.optimization.update_freq) > 1
and fairscale.__version__ < "0.4.0"
):
raise RuntimeError(
"Please update to fairscale 0.4.0 or newer when combining "
"--update-freq with FullyShardedDataParallel"
)
else:
if (
hasattr(self.cfg.distributed_training, "cpu_offload")
and self.cfg.distributed_training.cpu_offload
):
raise ValueError("--cpu-offload requires --ddp-backend=fully_sharded")
# copy model and criterion to current device/dtype
self._criterion = criterion
self._model = model
if not self.is_fsdp:
if cfg.common.fp16:
assert not cfg.common.amp, "Cannot use fp16 and AMP together"
self._criterion = self._criterion.half()
self._model = self._model.half()
elif cfg.common.bf16:
self._criterion = self._criterion.to(dtype=torch.bfloat16)
self._model = self._model.to(dtype=torch.bfloat16)
elif cfg.common.amp:
self._amp_retries = 0
if (
not cfg.distributed_training.pipeline_model_parallel
# the DistributedFairseqModel wrapper will handle moving to device,
# so only handle cases which don't use the wrapper
and not self.use_distributed_wrapper
):
self._criterion = self._criterion.to(device=self.device)
self._model = self._model.to(device=self.device)
self.pipeline_model_parallel = cfg.distributed_training.pipeline_model_parallel
self.last_device = None
if self.cuda and self.pipeline_model_parallel:
self.last_device = torch.device(
cfg.distributed_training.pipeline_devices[-1]
)
# check that shared parameters are preserved after device transfer
for shared_param in shared_params:
ref = _get_module_by_path(self._model, shared_param[0])
for path in shared_param[1:]:
logger.info(
"detected shared parameter: {} <- {}".format(shared_param[0], path)
)
_set_module_by_path(self._model, path, ref)
self._dummy_batch = None # indicates we don't have a dummy batch at first
self._lr_scheduler = None
self._num_updates = 0
self._num_xla_compiles = 0 # for TPUs
self._optim_history = None
self._optimizer = None
self._warn_once = set()
self._wrapped_criterion = None
self._wrapped_model = None
self._ema = None
# TODO(myleott): support tpu
if self.cuda and self.data_parallel_world_size > 1:
self._grad_norm_buf = torch.cuda.DoubleTensor(self.data_parallel_world_size)
else:
self._grad_norm_buf = None
self.quantizer = quantizer
if self.quantizer is not None:
self.quantizer.set_trainer(self)
# get detailed cuda environment
if self.cuda:
self.cuda_env = utils.CudaEnvironment()
if self.data_parallel_world_size > 1:
self.cuda_env_arr = distributed_utils.all_gather_list(
self.cuda_env, group=distributed_utils.get_global_group()
)
else:
self.cuda_env_arr = [self.cuda_env]
if self.data_parallel_rank == 0:
utils.CudaEnvironment.pretty_print_cuda_env_list(self.cuda_env_arr)
else:
self.cuda_env = None
self.cuda_env_arr = None
metrics.log_start_time("wall", priority=790, round=0)
self._start_time = time.time()
self._previous_training_time = 0
self._cumulative_training_time = None
def reinitialize(self):
"""Reinitialize the Trainer, typically after model params change."""
self._lr_scheduler = None
self._optimizer = None
self._wrapped_criterion = None
self._wrapped_model = None
@property
def data_parallel_world_size(self):
if self.cfg.distributed_training.distributed_world_size == 1:
return 1
return distributed_utils.get_data_parallel_world_size()
@property
def data_parallel_process_group(self):
return distributed_utils.get_data_parallel_group()
@property
def data_parallel_rank(self):
if self.cfg.distributed_training.distributed_world_size == 1:
return 0
return distributed_utils.get_data_parallel_rank()
@property
def is_data_parallel_master(self):
# NOTE: this returns true for all model parallel replicas with data
# parallel rank 0
return self.data_parallel_rank == 0
@property
def use_distributed_wrapper(self) -> bool:
return (
self.data_parallel_world_size > 1 and not self.cfg.optimization.use_bmuf
) or (self.is_fsdp and self.cfg.distributed_training.cpu_offload)
@property
def should_save_checkpoint_on_current_rank(self) -> bool:
"""Indicates whether to save checkpoints on the current DDP rank."""
if (
self.is_fsdp and self.cfg.distributed_training.use_sharded_state
) or getattr(self.cfg.model, "base_layers", 0) > 0:
return True
else:
return self.is_data_parallel_master
@property
def always_call_state_dict_during_save_checkpoint(self) -> bool:
if self.is_fsdp and not self.cfg.distributed_training.use_sharded_state:
# FSDP calls communication collective when consolidating checkpoints
return True
else:
return False
@property
def checkpoint_suffix(self) -> str:
"""Suffix to add to the checkpoint file name."""
if self.is_fsdp and self.cfg.distributed_training.use_sharded_state:
return self.cfg.checkpoint.checkpoint_suffix + "-shard{0}".format(
self.data_parallel_rank
)
else:
return self.cfg.checkpoint.checkpoint_suffix or ""
@property
def criterion(self):
if self._wrapped_criterion is None:
if utils.has_parameters(self._criterion) and self.use_distributed_wrapper:
self._wrapped_criterion = models.DistributedFairseqModel(
self.cfg.distributed_training,
self._criterion,
process_group=self.data_parallel_process_group,
device=self.device,
)
else:
self._wrapped_criterion = self._criterion
return self._wrapped_criterion
@property
def model(self):
if self._wrapped_model is None:
if self.use_distributed_wrapper:
self._wrapped_model = models.DistributedFairseqModel(
self.cfg.distributed_training,
self._model,
process_group=self.data_parallel_process_group,
device=self.device,
)
else:
self._wrapped_model = self._model
return self._wrapped_model
@property
def ema(self):
if self._ema is None:
self._build_ema()
return self._ema
def _build_ema(self):
if self.cfg.ema.store_ema:
self._ema = build_ema(self._model, self.cfg.ema, self.device)
logger.info("Exponential Moving Average Shadow Model is initialized.")
@property
def optimizer(self):
if self._optimizer is None:
self._build_optimizer()
return self._optimizer
@property
def lr_scheduler(self):
if self._lr_scheduler is None:
self._build_optimizer() # this will initialize self._lr_scheduler
return self._lr_scheduler
def _build_optimizer(self):
params = list(
filter(
lambda p: p.requires_grad,
chain(self.model.parameters(), self.criterion.parameters()),
)
)
if self.is_fsdp and self.cfg.common.fp16:
# FullyShardedDataParallel always uses MemoryEfficientFP16 wrapper,
# mostly for the grad scaling. But if we don't have the
# --memory-efficient-fp16 flag set, then we're effectively doing
# regular --fp16 and can allow the use of optimizers that would
# otherwise be unsupported by MemoryEfficientFP16Optimizer.
allow_unsupported = not self.cfg.common.memory_efficient_fp16
self._optimizer = optim.MemoryEfficientFP16Optimizer.build_optimizer(
self.cfg, params, allow_unsupported=allow_unsupported
)
elif self.cfg.common.fp16 or self.cfg.common.bf16 or self.cfg.common.amp:
if self.cuda and torch.cuda.get_device_capability(0)[0] < 7:
logger.info(
"NOTE: your device does NOT support faster training with --fp16 or --amp, "
"please switch to FP32 which is likely to be faster"
)
if (
self.cfg.common.memory_efficient_fp16
or self.cfg.common.memory_efficient_bf16
):
self._optimizer = optim.MemoryEfficientFP16Optimizer.build_optimizer(
self.cfg, params
)
elif self.cfg.common.amp:
self._optimizer = optim.AMPOptimizer.build_optimizer(self.cfg, params)
else:
self._optimizer = optim.FP16Optimizer.build_optimizer(self.cfg, params)
else:
if self.cuda and torch.cuda.get_device_capability(0)[0] >= 7:
logger.info(
"NOTE: your device may support faster training with --fp16 or --amp"
)
self._optimizer = optim.build_optimizer(self.cfg.optimizer, params)
if self.is_fsdp:
assert (
not self.cfg.optimization.use_bmuf
), "--ddp-backend=fully_sharded is not compatible with BMUF"
assert self._optimizer.supports_flat_params, (
"--ddp-backend=fully_sharded is only compatible with pointwise "
"optimizers (e.g., Adam, AdamW, Adadelta, Adamax, SGD, etc.). "
"However, the sharding will result in slightly different results when "
"using non-pointwise optimizers (e.g., Adagrad, Adafactor, LAMB)"
)
if self.cfg.optimization.use_bmuf:
self._optimizer = optim.FairseqBMUF(
self.cfg.bmuf,
self._optimizer,
)
if self.cfg.distributed_training.zero_sharding == "os":
if (
self.cfg.common.fp16
and not self.cfg.common.memory_efficient_fp16
and not self.cfg.common.memory_efficient_bf16
) and not self.cfg.common.fp16_no_flatten_grads:
raise ValueError(
"ZeRO is incomptabile with fp16 and flattened grads. "
"Please use --fp16-no-flatten-grads"
)
else:
optim.shard_(self._optimizer, self.data_parallel_process_group)
# We should initialize the learning rate scheduler immediately after
# building the optimizer, so that the initial learning rate is set.
self._lr_scheduler = lr_scheduler.build_lr_scheduler(
self.cfg.lr_scheduler,
self.optimizer,
)
self._lr_scheduler.step_update(0)
@property
def is_fsdp(self):
return self.cfg.distributed_training.ddp_backend == "fully_sharded"
def consolidate_optimizer(self):
"""For OSS, we need to consolidate the state dict."""
if self.cfg.checkpoint.no_save_optimizer_state:
return
self._gathered_optim_state = None
if hasattr(self.optimizer.optimizer, "consolidate_state_dict"):
self.optimizer.optimizer.consolidate_state_dict()
elif self.is_fsdp and not self.model.use_sharded_state:
st = self.model.gather_full_optim_state_dict(
self.optimizer
) # only returns on rank 0
self._gathered_optim_state = st
def state_dict(self):
state_dict = {
"args": None, # legacy
"cfg": (
OmegaConf.to_container(self.cfg, resolve=True, enum_to_str=True)
if OmegaConf.is_config(self.cfg)
else self.cfg
),
"model": self.model.state_dict(),
"criterion": (
self.criterion.state_dict()
if utils.has_parameters(self.criterion)
else None
),
"optimizer_history": (self._optim_history or [])
+ [
{
"criterion_name": self.get_criterion().__class__.__name__,
"optimizer_name": self.optimizer.__class__.__name__,
"lr_scheduler_state": self.lr_scheduler.state_dict(),
"num_updates": self.get_num_updates(),
}
],
"task_state": self.task.state_dict() if self.task is not None else {},
"extra_state": {
"metrics": metrics.state_dict(),
"previous_training_time": self.cumulative_training_time(),
},
}
if self.cfg.ema.store_ema:
# Save EMA model state as extra state
state_dict["extra_state"]["ema"] = self.ema.get_model().state_dict()
if self.cfg.ema.ema_fp32:
# Save EMA params in fp32
state_dict["extra_state"]["ema_fp32_params"] = self.ema.fp32_params
if not self.cfg.checkpoint.no_save_optimizer_state:
if self._gathered_optim_state is not None:
state_dict["last_optimizer_state"] = self._gathered_optim_state
self._gathered_optim_state = None
else:
state_dict["last_optimizer_state"] = self.optimizer.state_dict()
if self.is_fsdp:
# save meta data for recombining checkpoint upon loading
state_dict["fsdp_metadata"] = self.model.local_metadata_dict()
return state_dict
def save_checkpoint(self, filename, extra_state):
"""Save all training state in a checkpoint file."""
logger.info(f"Saving checkpoint to {os.path.abspath(filename)}")
# call state_dict on all ranks in case it needs internal communication
state_dict = utils.move_to_cpu(self.state_dict())
state_dict["extra_state"].update(extra_state)
if self.should_save_checkpoint_on_current_rank:
checkpoint_utils.torch_persistent_save(
state_dict,
filename,
async_write=self.cfg.checkpoint.write_checkpoints_asynchronously,
)
logger.info(f"Finished saving checkpoint to {os.path.abspath(filename)}")
def load_checkpoint(
self,
filename,
reset_optimizer=False,
reset_lr_scheduler=False,
optimizer_overrides=None,
reset_meters=False,
):
"""
Load all training state from a checkpoint file.
rank = 0 will load the checkpoint, and then broadcast it to all
other ranks.
"""
extra_state, self._optim_history, last_optim_state = None, [], None
logger.info(f"Preparing to load checkpoint {filename}")
is_distributed = self.data_parallel_world_size > 1
bexists = PathManager.isfile(filename)
if bexists:
load_on_all_ranks = (
self.cfg.checkpoint.load_checkpoint_on_all_dp_ranks
# TPUs don't support broadcast yet, so load checkpoints
# on every worker for now
or self.tpu
# FSDP requires loading checkpoint shards on all ranks
or (self.is_fsdp and self.cfg.distributed_training.use_sharded_state)
or getattr(self.cfg.model, "base_layers", 0) > 0
)
if load_on_all_ranks or self.data_parallel_rank == 0:
state = checkpoint_utils.load_checkpoint_to_cpu(
filename, load_on_all_ranks=load_on_all_ranks
)
last_optim_state = state.get("last_optimizer_state", None)
# If doing zero_sharding, do not broadcast global optimizer
# state. Later we will broadcast sharded states to each rank
# to avoid memory from exploding.
if (
not load_on_all_ranks
and self.cfg.distributed_training.zero_sharding == "os"
and "last_optimizer_state" in state
and is_distributed
):
state["last_optimizer_state"] = "SHARDED"
else:
last_optim_state = None
state = None
if is_distributed and not load_on_all_ranks:
state = distributed_utils.broadcast_object(
state,
src_rank=0,
group=self.data_parallel_process_group,
dist_device=self.device,
)
if self.data_parallel_rank > 0:
last_optim_state = state.get("last_optimizer_state", None)
# load model parameters
try:
if (
"optimizer_history" in state
and len(state["optimizer_history"]) > 0
and "num_updates" in state["optimizer_history"][-1]
):
self.model.set_num_updates(
state["optimizer_history"][-1]["num_updates"]
)
# this is the code related to AdaPrune
# In short, it removes redundant heads in multi-head attention module based on heads importance provided
# For more info, please refer to the paper: https://openreview.net/forum?id=_CMSV7FTzGI
# The idea of prune in mha can be summarized as
# Fine tune model (e.g. roberta encoder) on a certain datasets with regularization
# After the model is trained. User could use get_reserve_head_index and _adaptive_prune_heads functions to get the top X heads with most importance.
# Then user uses the rank to prune a new roberta encoder and save the pruned ckpt manually.
# User will fine tune the the new roberta encoder via the ckpt saved above
# To get rid of registering different pruned version of Roberta, I use the argument --mha-heads-to-keep to prune the Roberta model into a pruned version which matches the pruned ckpt.
if (
safe_hasattr(self.model, "args")
and safe_hasattr(self.model.args, "mha_heads_to_keep")
and self.model.args.mha_heads_to_keep != -1
):
logger.info(
f"Prune model: keep {self.model.args.mha_heads_to_keep} heads for each multihead attention module"
)
for layer in self.model.encoder.sentence_encoder.layers:
reserve_head_index = layer.self_attn._get_reserve_head_index(
num_heads_to_keep=self.model.args.mha_heads_to_keep
)
layer.self_attn._adaptive_prune_heads(
reserve_head_index=reserve_head_index
)
layer.self_attn._set_skip_embed_dim_check()
logger.info(self.model)
# this is the code related to AdaPrune
# In short, it removes redundant units in feedforward layer in each transformer layer based on importance
# For more info, please refer to the paper: https://openreview.net/forum?id=_CMSV7FTzGI
# The idea of prune in ffn can be summarized as
# Fine tune model (e.g. roberta encoder) on a certain datasets with regularization
# After the model is trained. User could use _get_fc_rank and _prune_fc_layer functions to get the top X units with most importance.
# Then user uses the rank to prune a new roberta encoder and save the pruned ckpt manually.
# User will fine tune the the new roberta encoder via the ckpt saved above
# To get rid of registering different pruned version of Roberta, I use the argument --ffn-blocks-to-remove to prune the Roberta model into a pruned version which matches the pruned ckpt.
if (
safe_hasattr(self.model, "args")
and safe_hasattr(self.model.args, "ffn_blocks_to_remove")
and self.model.args.ffn_blocks_to_remove != -1
):
logger.info(
f"Prune model: remove {self.model.args.ffn_blocks_to_remove} ffn blocks for each transformer layer"
)
for layer in self.model.encoder.sentence_encoder.layers:
remove_index = layer._get_fc_rank(
remove_num=self.model.args.ffn_blocks_to_remove
)
layer._prune_fc_layer(remove_index=remove_index)
logger.info(self.model)
self.model.load_state_dict(
state["model"], strict=True, model_cfg=self.cfg.model
)
# save memory for later steps
del state["model"]
if utils.has_parameters(self.get_criterion()):
self.get_criterion().load_state_dict(
state["criterion"], strict=True
)
del state["criterion"]
except Exception:
raise Exception(
"Cannot load model parameters from checkpoint {}; "
"please ensure that the architectures match.".format(filename)
)
extra_state = state["extra_state"]
self._optim_history = state["optimizer_history"]
if last_optim_state is not None and not reset_optimizer:
# rebuild optimizer after loading model, since params may have changed
self._build_optimizer()
# only reload optimizer and lr_scheduler if they match
last_optim = self._optim_history[-1]
assert (
last_optim["criterion_name"] == self.get_criterion().__class__.__name__
), f"Criterion does not match; please reset the optimizer (--reset-optimizer). {last_optim['criterion_name']} vs {self.get_criterion().__class__.__name__}"
assert (
last_optim["optimizer_name"] == self.optimizer.__class__.__name__
), f"Optimizer does not match; please reset the optimizer (--reset-optimizer). {last_optim['optimizer_name']} vs {self.optimizer.__class__.__name__}"
if not reset_lr_scheduler:
self.lr_scheduler.load_state_dict(last_optim["lr_scheduler_state"])
if self.is_fsdp and not self.model.use_sharded_state:
# if use_sharded_state, the last_optim_state is already sharded, skip this
last_optim_state = self.model.get_shard_from_optim_state_dict(
last_optim_state
)
elif not load_on_all_ranks and is_distributed:
last_optim_state = self.optimizer.broadcast_global_state_dict(
last_optim_state
)
self.optimizer.load_state_dict(last_optim_state, optimizer_overrides)
self.set_num_updates(last_optim["num_updates"])
if extra_state is not None:
itr_state = extra_state["train_iterator"]
epoch = itr_state["epoch"]
if "previous_training_time" in extra_state:
self._previous_training_time = extra_state["previous_training_time"]
self._start_time = time.time()
self.lr_step(epoch)
if (
itr_state.get("version", 1) >= 2
and itr_state["iterations_in_epoch"] == 0
):
# reset meters at start of epoch
reset_meters = True
if "metrics" in extra_state and not reset_meters:
metrics.load_state_dict(extra_state["metrics"])
# reset TimeMeters, since their start times don't make sense anymore
for meter in metrics.get_meters("default"):
if isinstance(meter, meters.TimeMeter):
meter.reset()
if self.cfg.ema.store_ema:
if "ema" not in extra_state:
logger.warn(
"EMA not found in checkpoint. But store_ema is True. "
"EMA is re-initialized from checkpoint."
)
self.ema.restore(
state["model"], build_fp32_params=self.cfg.ema.ema_fp32
)
else:
logger.info("Loading EMA from checkpoint")
self.ema.restore(extra_state["ema"], build_fp32_params=False)
if self.cfg.ema.ema_fp32:
if "ema_fp32_params" in extra_state:
logger.info("Loading EMA fp32 params from checkpoint")
self.ema.build_fp32_params(extra_state["ema_fp32_params"])
else:
logger.info(
"Building EMA fp32 params from EMA model in checkpoint"
)
self.ema.build_fp32_params()
logger.info(
"Loaded checkpoint {} (epoch {} @ {} updates)".format(
filename, epoch, self.get_num_updates()
)
)
else:
logger.info("No existing checkpoint found {}".format(filename))
return extra_state
def get_train_iterator(
self,
epoch,
combine=True,
load_dataset=True,
data_selector=None,
shard_batch_itr=True,
disable_iterator_cache=False,
):
"""Return an EpochBatchIterator over the training set for a given epoch."""
if load_dataset:
logger.info("loading train data for epoch {}".format(epoch))
self.task.load_dataset(
self.cfg.dataset.train_subset,
epoch=epoch,
combine=combine,
data_selector=data_selector,
tpu=self.tpu,
)
# import pdb
# pdb.set_trace()
batch_iterator = self.task.get_batch_iterator(
dataset=self.task.dataset(self.cfg.dataset.train_subset),
max_tokens=self.cfg.dataset.max_tokens,
max_sentences=self.cfg.dataset.batch_size,
max_positions=utils.resolve_max_positions(
self.task.max_positions(),
self.model.max_positions(),
self.cfg.dataset.max_tokens,
),
ignore_invalid_inputs=True,
required_batch_size_multiple=self.cfg.dataset.required_batch_size_multiple,
seed=(self.cfg.common.seed + epoch)
if self.cfg.dataset.update_ordered_indices_seed
else self.cfg.common.seed,
num_shards=self.data_parallel_world_size if shard_batch_itr else 1,
shard_id=self.data_parallel_rank if shard_batch_itr else 0,
num_workers=self.cfg.dataset.num_workers,
epoch=epoch,
data_buffer_size=self.cfg.dataset.data_buffer_size,
disable_iterator_cache=disable_iterator_cache,
skip_remainder_batch=self.cfg.optimization.skip_remainder_batch,
grouped_shuffling=self.cfg.dataset.grouped_shuffling,
update_epoch_batch_itr=self.cfg.dataset.update_epoch_batch_itr,
)
self.reset_dummy_batch(batch_iterator.first_batch)
return batch_iterator
def get_valid_iterator(
self,
subset,
disable_iterator_cache=False,
):
"""Return an EpochBatchIterator over given validation subset for a given epoch."""
batch_iterator = self.task.get_batch_iterator(
dataset=self.task.dataset(subset),
max_tokens=self.cfg.dataset.max_tokens_valid,
max_sentences=self.cfg.dataset.batch_size_valid,
max_positions=utils.resolve_max_positions(
self.task.max_positions(),
self.model.max_positions(),
),
ignore_invalid_inputs=self.cfg.dataset.skip_invalid_size_inputs_valid_test,
required_batch_size_multiple=self.cfg.dataset.required_batch_size_multiple,
seed=self.cfg.common.seed,
num_shards=self.data_parallel_world_size,
shard_id=self.data_parallel_rank,
num_workers=self.cfg.dataset.num_workers,
# always pass a fixed "epoch" to keep validation data consistent
# across training epochs
epoch=1,
data_buffer_size=self.cfg.dataset.data_buffer_size,
disable_iterator_cache=disable_iterator_cache,
skip_remainder_batch=False,
)
self.reset_dummy_batch(batch_iterator.first_batch)
return batch_iterator
def begin_epoch(self, epoch):
"""Called at the beginning of each epoch."""
logger.info("begin training epoch {}".format(epoch))
self.lr_step_begin_epoch(epoch)
if self.quantizer is not None:
self.quantizer.begin_epoch(epoch)
# task specific setup per epoch
self.task.begin_epoch(epoch, self.get_model())
if self.tpu:
import torch_xla.core.xla_model as xm
xm.rendezvous("begin_epoch") # wait for all workers
xm.mark_step()
def begin_valid_epoch(self, epoch):
"""Called at the beginning of each validation epoch."""
# task specific setup per validation epoch
self.task.begin_valid_epoch(epoch, self.get_model())
def reset_dummy_batch(self, batch):
self._dummy_batch = batch
@metrics.aggregate("train")
def train_step(self, samples, raise_oom=False):
"""Do forward, backward and parameter update."""
self._set_seed()
self.model.train()
self.criterion.train()
self.zero_grad()
metrics.log_start_time("train_wall", priority=800, round=0)
# If EMA is enabled through store_ema=True
# and task.uses_ema is True, pass the EMA model as a keyword
# argument to the task.
extra_kwargs = {}
if self.cfg.ema.store_ema and getattr(self.task, "uses_ema", False):
extra_kwargs["ema_model"] = self.ema.get_model()
# forward and backward pass
logging_outputs, sample_size, ooms = [], 0, 0
for i, sample in enumerate(samples): # delayed update loop
sample, is_dummy_batch = self._prepare_sample(sample)
def maybe_no_sync():
"""
Whenever *samples* contains more than one mini-batch, we
want to accumulate gradients locally and only call
all-reduce in the last backwards pass.
"""
if (
self.data_parallel_world_size > 1
and hasattr(self.model, "no_sync")
and i < len(samples) - 1
# The no_sync context manager results in increased memory
# usage with FSDP, since full-size gradients will be
# accumulated on each GPU. It's typically a better tradeoff
# to do the extra communication with FSDP.
and not self.is_fsdp
):
return self.model.no_sync()
else:
return contextlib.ExitStack() # dummy contextmanager
try:
with maybe_no_sync():
# forward and backward
loss, sample_size_i, logging_output = self.task.train_step(
sample=sample,
model=self.model,
criterion=self.criterion,
optimizer=self.optimizer,
update_num=self.get_num_updates(),
ignore_grad=is_dummy_batch,
**extra_kwargs,
)
del loss
logging_outputs.append(logging_output)
sample_size += sample_size_i
# emptying the CUDA cache after the first step can
# reduce the chance of OOM
if self.cuda and self.get_num_updates() == 0:
torch.cuda.empty_cache()
except RuntimeError as e:
if "out of memory" in str(e):
self._log_oom(e)
if raise_oom:
raise e
logger.warning(
"attempting to recover from OOM in forward/backward pass"
)
ooms += 1
self.zero_grad()
if self.cuda:
torch.cuda.empty_cache()
if self.cfg.distributed_training.distributed_world_size == 1:
return None
else:
raise e
except Exception:
self.consolidate_optimizer()
self.save_checkpoint(
os.path.join(self.cfg.checkpoint.save_dir, "crash.pt"), {}
)
raise
if self.tpu and i < len(samples) - 1:
# tpu-comment: every XLA operation before marking step is
# appended to the IR graph, and processing too many batches
# before marking step can lead to OOM errors.
# To handle gradient accumulation use case, we explicitly
# mark step here for every forward pass without a backward pass
self._xla_markstep_and_send_to_cpu()
if is_dummy_batch:
if torch.is_tensor(sample_size):
sample_size.zero_()
else:
sample_size *= 0.0
if torch.is_tensor(sample_size):
sample_size = sample_size.float()
else:
sample_size = float(sample_size)
# gather logging outputs from all replicas
if self._sync_stats():
train_time = self._local_cumulative_training_time()
(
logging_outputs,
(
sample_size,
ooms,
total_train_time,
),
) = self._aggregate_logging_outputs(
logging_outputs, sample_size, ooms, train_time, ignore=is_dummy_batch
)
self._cumulative_training_time = (
total_train_time / self.data_parallel_world_size
)
overflow = False
try:
with torch.autograd.profiler.record_function("reduce-grads"):
# reduce gradients across workers
self.optimizer.all_reduce_grads(self.model)
if utils.has_parameters(self.criterion):
self.optimizer.all_reduce_grads(self.criterion)
with torch.autograd.profiler.record_function("multiply-grads"):
# multiply gradients by (data_parallel_size / sample_size) since
# DDP normalizes by the number of data parallel workers for
# improved fp16 precision.
# Thus we get (sum_of_gradients / sample_size) at the end.
# In case of fp16, this step also undoes loss scaling.
# (Debugging note: Some optimizers perform this scaling on the
# fly, so inspecting model.parameters() or optimizer.params may
# still show the original, unscaled gradients.)
numer = (
self.data_parallel_world_size
if not self.cfg.optimization.use_bmuf or self._sync_stats()
else 1
)
self.optimizer.multiply_grads(numer / (sample_size or 1.0))
# Note: (sample_size or 1.0) handles the case of a zero gradient, in a
# way that avoids CPU/device transfers in case sample_size is a GPU or
# TPU object. The assumption is that the gradient itself is also 0.
with torch.autograd.profiler.record_function("clip-grads"):
# clip grads
grad_norm = self.clip_grad_norm(self.cfg.optimization.clip_norm)
# check that grad norms are consistent across workers
# on tpu check tensor is slow
if not self.tpu:
if (
not self.cfg.optimization.use_bmuf
and self.cfg.distributed_training.ddp_backend != "slowmo"
):
self._check_grad_norms(grad_norm)
if not torch.isfinite(grad_norm).all():
# in case of AMP, if gradients are Nan/Inf then
# optimizer step is still required
if self.cfg.common.amp:
overflow = True
else:
# check local gradnorm single GPU case, trigger NanDetector
raise FloatingPointError("gradients are Nan/Inf")
with torch.autograd.profiler.record_function("optimizer"):
# take an optimization step
self.task.optimizer_step(
self.optimizer, model=self.model, update_num=self.get_num_updates()
)
if self.cfg.common.amp and overflow:
if self._amp_retries == self.cfg.common.amp_batch_retries:
logger.info("AMP: skipping this batch.")
self._amp_retries = 0
else:
self._amp_retries += 1
return self.train_step(
samples, raise_oom
) # recursion to feed in same batch
except FloatingPointError:
self.consolidate_optimizer()
self.save_checkpoint(
os.path.join(self.cfg.checkpoint.save_dir, "crash.pt"), {}
)
# re-run the forward and backward pass with hooks attached to print
# out where it fails
self.zero_grad()
with NanDetector(self.get_model()):
for _, sample in enumerate(samples):
sample, _ = self._prepare_sample(sample)
self.task.train_step(
sample,
self.model,
self.criterion,
self.optimizer,
self.get_num_updates(),
ignore_grad=False,
**extra_kwargs,
)
raise
except OverflowError as e:
overflow = True
logger.info(
f"NOTE: gradient overflow detected, ignoring gradient, {str(e)}"
)
grad_norm = torch.tensor(0.0).cuda()
self.zero_grad()
except RuntimeError as e:
if "out of memory" in str(e):
self._log_oom(e)
logger.error("OOM during optimization, irrecoverable")
raise e
# Some distributed wrappers (e.g., SlowMo) need access to the optimizer
# after the step
if hasattr(self.model, "perform_slowmo"):
self.model.perform_slowmo(
self.optimizer.optimizer, getattr(self.optimizer, "fp32_params", None)
)
logging_output = None
if not overflow or self.cfg.distributed_training.ddp_backend == "slowmo":
self.set_num_updates(self.get_num_updates() + 1)
if self.cfg.ema.store_ema:
# Step EMA forward with new model.
self.ema.step(
self.get_model(),
self.get_num_updates(),
)
metrics.log_scalar(
"ema_decay",
self.ema.get_decay(),
priority=10000,
round=5,
weight=0,
)
if self.tpu:
import torch_xla.core.xla_model as xm
# mark step on TPUs
self._xla_markstep_and_send_to_cpu()
# only log stats every log_interval steps
# this causes wps to be misreported when log_interval > 1
logging_output = {}
if self.get_num_updates() % self.cfg.common.log_interval == 0:
# log memory usage
mem_info = xm.get_memory_info(self.device)
gb_free = mem_info["kb_free"] / 1024 / 1024
gb_total = mem_info["kb_total"] / 1024 / 1024
metrics.log_scalar(
"gb_free", gb_free, priority=1500, round=1, weight=0
)
metrics.log_scalar(
"gb_total", gb_total, priority=1600, round=1, weight=0
)
logging_outputs = self._xla_markstep_and_send_to_cpu(
logging_outputs
)
logging_output = self._reduce_and_log_stats(
logging_outputs, sample_size, grad_norm
)
# log whenever there's an XLA compilation, since these
# slow down training and may indicate opportunities for
# optimization
self._check_xla_compilation()
else:
if self.cuda and self.cuda_env is not None:
# log minimum free memory over the iteration
gb_used = torch.cuda.max_memory_allocated() / 1024 / 1024 / 1024
torch.cuda.reset_peak_memory_stats()
gb_free = self.cuda_env.total_memory_in_GB - gb_used
metrics.log_scalar(
"gb_free", gb_free, priority=1500, round=1, weight=0
)
# log stats
logging_output = self._reduce_and_log_stats(
logging_outputs, sample_size, grad_norm
)
# clear CUDA cache to reduce memory fragmentation
if (
self.cuda
and self.cfg.common.empty_cache_freq > 0
and (
(self.get_num_updates() + self.cfg.common.empty_cache_freq - 1)
% self.cfg.common.empty_cache_freq
)
== 0
):
torch.cuda.empty_cache()
if self.cfg.common.fp16 or self.cfg.common.amp:
metrics.log_scalar(
"loss_scale",
(
self.optimizer.scaler.loss_scale
if self.cfg.common.fp16
else self.optimizer.scaler.get_scale()
),
priority=700,
round=4,
weight=0,
)
metrics.log_stop_time("train_wall")
return logging_output
@metrics.aggregate("valid")
def valid_step(self, sample, raise_oom=False):
"""Do forward pass in evaluation mode."""
if self.tpu:
import torch_xla.core.xla_model as xm
xm.rendezvous("valid_step") # wait for all workers
# If EMA is enabled through store_ema=True
# and task.uses_ema is True, pass the EMA model as a keyword
# argument to the task.
extra_kwargs = {}
if self.cfg.ema.store_ema and getattr(self.task, "uses_ema", False):
extra_kwargs["ema_model"] = self.ema.get_model()
with torch.no_grad():
self.model.eval()
self.criterion.eval()
sample, is_dummy_batch = self._prepare_sample(sample)
try:
_loss, sample_size, logging_output = self.task.valid_step(
sample, self.model, self.criterion, **extra_kwargs
)
except RuntimeError as e:
if "out of memory" in str(e):
self._log_oom(e)
if not raise_oom:
logger.warning(
"ran out of memory in validation step, retrying batch"
)
for p in self.model.parameters():
if p.grad is not None:
p.grad = None # free some memory
if self.cuda:
torch.cuda.empty_cache()
return self.valid_step(sample, raise_oom=True)
raise e
logging_outputs = [logging_output]
if is_dummy_batch:
if torch.is_tensor(sample_size):
sample_size.zero_()
else:
sample_size *= 0.0
# gather logging outputs from all replicas
if self.data_parallel_world_size > 1:
logging_outputs, (sample_size,) = self._aggregate_logging_outputs(
logging_outputs,
sample_size,
ignore=is_dummy_batch,
)
# log validation stats
if self.tpu:
logging_outputs = self._xla_markstep_and_send_to_cpu(logging_outputs)
logging_output = self._reduce_and_log_stats(logging_outputs, sample_size)
return logging_output
def zero_grad(self):
self.optimizer.zero_grad()
def lr_step_begin_epoch(self, epoch):
"""Adjust the learning rate at the beginning of the epoch."""
self.lr_scheduler.step_begin_epoch(epoch)
# prefer updating the LR based on the number of steps
return self.lr_step_update()
def lr_step(self, epoch, val_loss=None):
"""Adjust the learning rate at the end of the epoch."""
self.lr_scheduler.step(epoch, val_loss)
# prefer updating the LR based on the number of steps
return self.lr_step_update()
def lr_step_update(self):
"""Update the learning rate after each update."""
new_lr = self.lr_scheduler.step_update(self.get_num_updates())
if isinstance(new_lr, dict):
for k, v in new_lr.items():
metrics.log_scalar(f"lr_{k}", v, weight=0, priority=300)
new_lr = new_lr.get("default", next(iter(new_lr.values())))
else:
metrics.log_scalar("lr", new_lr, weight=0, priority=300)
return new_lr
def get_lr(self):
"""Get the current learning rate."""
return self.optimizer.get_lr()
def get_model(self):
"""Get the (non-wrapped) model instance."""
return self._model
def get_criterion(self):
"""Get the (non-wrapped) criterion instance."""
return self._criterion
def get_meter(self, name):
"""[deprecated] Get a specific meter by name."""
from fairseq import meters
if "get_meter" not in self._warn_once:
self._warn_once.add("get_meter")
utils.deprecation_warning(
"Trainer.get_meter is deprecated. Please use fairseq.metrics instead."
)
train_meters = metrics.get_meters("train")
if train_meters is None:
train_meters = {}
if name == "train_loss" and "loss" in train_meters:
return train_meters["loss"]
elif name == "train_nll_loss":
# support for legacy train.py, which assumed this meter is
# always initialized
m = train_meters.get("nll_loss", None)
return m or meters.AverageMeter()
elif name == "wall":
# support for legacy train.py, which assumed this meter is
# always initialized
m = metrics.get_meter("default", "wall")
return m or meters.TimeMeter()
elif name == "wps":
m = metrics.get_meter("train", "wps")
return m or meters.TimeMeter()
elif name in {"valid_loss", "valid_nll_loss"}:
# support for legacy train.py, which assumed these meters
# are always initialized
k = name[len("valid_") :]
m = metrics.get_meter("valid", k)
return m or meters.AverageMeter()
elif name == "oom":
return meters.AverageMeter()
elif name in train_meters:
return train_meters[name]
return None
def get_num_updates(self):
"""Get the number of parameters updates."""
return self._num_updates
def set_num_updates(self, num_updates):
"""Set the number of parameters updates."""
self._num_updates = num_updates
self.lr_step_update()
if self.quantizer:
self.quantizer.step_update(self._num_updates)
metrics.log_scalar("num_updates", self._num_updates, weight=0, priority=200)
def clip_grad_norm(self, clip_norm):
def agg_norm_fn(total_norm):
total_norm = total_norm.cuda().float() ** 2
total_norm = distributed_utils.all_reduce(
total_norm, group=self.data_parallel_process_group
)
return total_norm**0.5
should_agg_norm = self.is_fsdp and (
self.data_parallel_process_group is not None
or torch.distributed.is_initialized()
)
return self.optimizer.clip_grad_norm(
clip_norm, aggregate_norm_fn=agg_norm_fn if should_agg_norm else None
)
def cumulative_training_time(self):
if self._cumulative_training_time is None:
# single GPU
return self._local_cumulative_training_time()
else:
return self._cumulative_training_time
def _local_cumulative_training_time(self):
"""Aggregate training time in seconds."""
return time.time() - self._start_time + self._previous_training_time
def _fp_convert_sample(self, sample):
def apply_half(t):
if t.dtype is torch.float32:
return t.to(dtype=torch.half)
return t
def apply_bfloat16(t):
if t.dtype is torch.float32:
return t.to(dtype=torch.bfloat16)
return t
if self.cfg.common.fp16:
sample = utils.apply_to_sample(apply_half, sample)
if self.cfg.common.bf16:
sample = utils.apply_to_sample(apply_bfloat16, sample)
return sample
def _prepare_sample(self, sample, is_dummy=False):
if sample == "DUMMY":
raise Exception(
"Trying to use an uninitialized 'dummy' batch. This usually indicates "
"that the total number of batches is smaller than the number of "
"participating GPUs. Try reducing the batch size or using fewer GPUs."
)
if sample is None or len(sample) == 0:
assert (
self._dummy_batch is not None and len(self._dummy_batch) > 0
), "Invalid dummy batch: {}".format(self._dummy_batch)
sample, _ = self._prepare_sample(self._dummy_batch, is_dummy=True)
return sample, True
# Given that PCIe/NVLink bandwidth is significantly smaller than DRAM bandwidth
# it makes sense to do the format conversion on the CPU and then transfer
# a smaller buffer to the device. This also saves GPU memory capacity.
if self.cfg.common.on_cpu_convert_precision:
sample = self._fp_convert_sample(sample)
if self.cuda:
if self.pipeline_model_parallel:
if "target" in sample:
sample["target"] = utils.move_to_cuda(
sample["target"], device=self.last_device
)
else:
sample = utils.move_to_cuda(sample)
elif self.tpu and is_dummy:
# the dummy batch may not be on the appropriate device
sample = utils.move_to_cuda(sample, device=self.device)
if not self.cfg.common.on_cpu_convert_precision:
sample = self._fp_convert_sample(sample)
if self._dummy_batch == "DUMMY":
self._dummy_batch = sample
return sample, False
def _set_seed(self):
# Set seed based on args.seed and the update number so that we get
# reproducible results when resuming from checkpoints
seed = self.cfg.common.seed + self.get_num_updates()
utils.set_torch_seed(seed)
def _sync_stats(self):
# Return True if it's using multiple GPUs and DDP or multiple GPUs with
# BMUF and it's a bmuf sync with warmup iterations completed before.
if self.data_parallel_world_size == 1:
return False
elif self.cfg.optimization.use_bmuf:
return (
self.get_num_updates() + 1
) % self.cfg.bmuf.global_sync_iter == 0 and (
self.get_num_updates() + 1
) > self.cfg.bmuf.warmup_iterations
else:
return True
def _log_oom(self, exc):
msg = "OOM: Ran out of memory with exception: {}".format(exc)
logger.warning(msg)
if torch.cuda.is_available() and hasattr(torch.cuda, "memory_summary"):
for device_idx in range(torch.cuda.device_count()):
logger.warning(torch.cuda.memory_summary(device=device_idx))
sys.stderr.flush()
def _aggregate_logging_outputs(
self,
logging_outputs: List[Dict[str, Any]],
*extra_stats_to_sum,
ignore=False,
):
if self.task.__class__.logging_outputs_can_be_summed(self.get_criterion()):
return self._fast_stat_sync_sum(
logging_outputs, *extra_stats_to_sum, ignore=ignore
)
else:
return self._all_gather_list_sync(
logging_outputs, *extra_stats_to_sum, ignore=ignore
)
def _all_gather_list_sync(
self,
logging_outputs: List[Dict[str, Any]],
*extra_stats_to_sum,
ignore=False,
):
"""
Sync logging outputs across workers. all_gather_list_sync is
suitable when logging outputs are complex types.
"""
if self.tpu:
raise NotImplementedError
if ignore:
logging_outputs = []
results = list(
zip(
*distributed_utils.all_gather_list(
[logging_outputs] + list(extra_stats_to_sum),
max_size=getattr(self.cfg.common, "all_gather_list_size", 16384),
group=self.data_parallel_process_group,
)
)
)
logging_outputs, extra_stats_to_sum = results[0], results[1:]
logging_outputs = list(chain.from_iterable(logging_outputs))
extra_stats_to_sum = [sum(s) for s in extra_stats_to_sum]
return logging_outputs, extra_stats_to_sum
def _fast_stat_sync_sum(
self,
logging_outputs: List[Dict[str, Any]],
*extra_stats_to_sum,
ignore=False,
):
"""
Sync logging outputs across workers. fast_stat_sync_sum is
faster than all_gather_list_sync, but is only suitable when
logging outputs are scalars and can be summed. Note that
*logging_outputs* cannot contain any nested dicts/lists.
"""
data = {}
for i, stat in enumerate(extra_stats_to_sum):
data["extra_stats_" + str(i)] = stat
if len(logging_outputs) > 0:
log_keys = list(logging_outputs[0].keys())
for k in log_keys:
if not ignore:
v = sum(log[k] for log in logging_outputs if k in log)
else:
v = logging_outputs[0][k]
v = torch.zeros_like(v) if torch.is_tensor(v) else 0
data["logging_outputs_" + k] = v
else:
log_keys = None
data = distributed_utils.all_reduce_dict(
data, device=self.device, group=self.data_parallel_process_group
)
extra_stats_to_sum = [
data["extra_stats_" + str(i)] for i in range(len(extra_stats_to_sum))
]
if log_keys is not None:
logging_outputs = [{k: data["logging_outputs_" + k] for k in log_keys}]
else:
logging_outputs = []
return logging_outputs, extra_stats_to_sum
def _check_grad_norms(self, grad_norm):
"""Check that grad norms are consistent across workers."""
if self._grad_norm_buf is not None:
self._grad_norm_buf.zero_()
self._grad_norm_buf[self.data_parallel_rank] = grad_norm
distributed_utils.all_reduce(
self._grad_norm_buf, group=self.data_parallel_process_group
)
def is_consistent(tensor):
max_abs_diff = torch.max(torch.abs(tensor - tensor[0]))
return (
(
torch.isfinite(tensor).all()
and (max_abs_diff / (tensor[0] + 1e-6) < 1e-6).all()
)
or (self.cfg.common.amp and not torch.isfinite(tensor).all())
# in case of amp non-finite grads are fine
)
if not is_consistent(self._grad_norm_buf):
pretty_detail = "\n".join(
"rank {:3d} = {:.8f}".format(r, n)
for r, n in enumerate(self._grad_norm_buf.tolist())
)
error_detail = "grad_norm across the workers:\n{}\n".format(
pretty_detail
)
# use FloatingPointError to trigger NanDetector
raise FloatingPointError(
"Fatal error: gradients are inconsistent between workers. "
"Try --ddp-backend=legacy_ddp. "
"Or are you mixing up different generation of GPUs in training?"
+ "\n"
+ "-" * 80
+ "\n{}\n".format(error_detail)
+ "-" * 80
)
def _reduce_and_log_stats(self, logging_outputs, sample_size, grad_norm=None):
if grad_norm is not None and (
not torch.is_tensor(grad_norm) or torch.isfinite(grad_norm)
):
metrics.log_speed("ups", 1.0, priority=100, round=2)
metrics.log_scalar("gnorm", grad_norm, priority=400, round=3)
if self.cfg.optimization.clip_norm > 0:
metrics.log_scalar(
"clip",
torch.where(
grad_norm > self.cfg.optimization.clip_norm,
grad_norm.new_tensor(100),
grad_norm.new_tensor(0),
),
priority=500,
round=1,
)
with metrics.aggregate() as agg:
if logging_outputs is not None:
self.task.reduce_metrics(logging_outputs, self.get_criterion())
del logging_outputs
# extra warning for criterions that don't properly log a loss value
if "loss" not in agg:
if "loss" not in self._warn_once:
self._warn_once.add("loss")
logger.warning(
"Criterion.reduce_metrics did not log a 'loss' value, "
"which may break some functionality"
)
metrics.log_scalar("loss", -1)
# support legacy interface
if self.tpu:
logging_output = {}
else:
logging_output = agg.get_smoothed_values()
logging_output["sample_size"] = sample_size
for key_to_delete in ["ppl", "wps", "wpb", "bsz"]:
if key_to_delete in logging_output:
del logging_output[key_to_delete]
return logging_output
def _check_xla_compilation(self):
import torch_xla.debug.metrics as met
compile_stats = met.metric_data("CompileTime")
if compile_stats is None:
return
num_xla_compiles = compile_stats[0]
if num_xla_compiles > self._num_xla_compiles:
logger.warning(
"XLA compilation detected on device #{}; too many of these can lead "
"to slow training, but we expect a few in the beginning".format(
self.cfg.distributed_training.distributed_rank
)
)
self._num_xla_compiles = num_xla_compiles
def _xla_markstep_and_send_to_cpu(self, data=None):
import torch_xla.core.xla_model as xm
xm.mark_step()
if data is not None:
from fairseq.utils import xla_device_to_cpu
return xla_device_to_cpu(data)
def _catalog_shared_params(module, memo=None, prefix=""):
if memo is None:
first_call = True
memo = {}
else:
first_call = False
for name, param in module._parameters.items():
param_prefix = prefix + ("." if prefix else "") + name
if param not in memo:
memo[param] = []
memo[param].append(param_prefix)
for name, m in module._modules.items():
if m is None:
continue
submodule_prefix = prefix + ("." if prefix else "") + name
_catalog_shared_params(m, memo, submodule_prefix)
if first_call:
return [x for x in memo.values() if len(x) > 1]
def _get_module_by_path(module, path):
path = path.split(".")
for name in path:
module = getattr(module, name)
return module
def _set_module_by_path(module, path, value):
path = path.split(".")
for name in path[:-1]:
module = getattr(module, name)
setattr(module, path[-1], value)
| 41.250784 | 202 | 0.572901 |
acefeffc617ba4d3d905d85aa38b15d431ffdcdc | 448 | py | Python | leadmanager/leads/api.py | epoyepoy/lead-manager | db9bd76c3549a5f794af63b5583659d3d6e0e510 | [
"MIT"
] | null | null | null | leadmanager/leads/api.py | epoyepoy/lead-manager | db9bd76c3549a5f794af63b5583659d3d6e0e510 | [
"MIT"
] | null | null | null | leadmanager/leads/api.py | epoyepoy/lead-manager | db9bd76c3549a5f794af63b5583659d3d6e0e510 | [
"MIT"
] | null | null | null | from .models import Lead
from rest_framework import viewsets, permissions
from .serializers import LeadSerializer
# Lead Viewset
class LeadViewset(viewsets.ModelViewSet):
permission_classes = [
permissions.IsAuthenticated
]
serializer_class = LeadSerializer
def get_queryset(self):
return self.request.user.leads.all()
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
| 22.4 | 48 | 0.741071 |
aceff1bd9329396cb40f7218c945582ef6e551cc | 5,997 | py | Python | test/synthetic_test_continuous_2.py | saeyoung/tslb | 5f52646260e14f44c61a670cfc75509951e5e794 | [
"MIT"
] | null | null | null | test/synthetic_test_continuous_2.py | saeyoung/tslb | 5f52646260e14f44c61a670cfc75509951e5e794 | [
"MIT"
] | 3 | 2020-03-24T18:18:21.000Z | 2021-08-23T20:37:09.000Z | test/synthetic_test_continuous_2.py | saeyoung/tslb | 5f52646260e14f44c61a670cfc75509951e5e794 | [
"MIT"
] | null | null | null | #############################################################
#
# Test 2-2. Continuous distribution, Gaussian Linear Model
#
#############################################################
import sys, os
sys.path.append("../..")
sys.path.append("..")
sys.path.append(os.getcwd())
import numpy as np
import pandas as pd
import copy
import pickle
from math import log, e
from sklearn.linear_model import LinearRegression
from numpy.linalg import eig
from utils import *
from continuous import *
from pykalman import KalmanFilter
def KalmanSequence(size, a):
# a = transition matrix's (0,0) and (1,1) coordinate
##########
# specify parameters
random_state = np.random.RandomState(0)
transition_matrix = [[a, 0], [0, a]]
transition_offset = [0, 0]
observation_matrix = np.eye(2) #+ random_state.randn(2, 2) * 0.1
observation_offset = [0, 0]
transition_covariance = np.eye(2)
observation_covariance = np.eye(2) #+ random_state.randn(2, 2) * 0.1
initial_state_mean = [5, -5]
initial_state_covariance = [[1, 0], [0, 1]]
# sample from model
kf = KalmanFilter(
transition_matrix, observation_matrix, transition_covariance,
observation_covariance, transition_offset, observation_offset,
initial_state_mean, initial_state_covariance,
random_state=random_state
)
states, observations = kf.sample(n_timesteps=size, initial_state=initial_state_mean)
# estimate state with filtering and smoothing
filtered_state_estimates = kf.filter(observations)[0]
# smoothed_state_estimates = kf.smooth(observations)[0]
return states, observations, filtered_state_estimates
def test(seq, est, n, k, name, plot=False, verbose=True):
# discretize the sequence
discretized_seq, categories = discretize(seq, n)
discretized_est, categories2 = pd.cut(est, categories, labels=np.arange(0, n), retbins=True)
# print(categories == categories2)
prediction_error = np.mean(discretized_seq[:-1] != discretized_est[:-1])
# convert format and get p_tilda
uncomp_numbers = list(discretized_seq)
p_tilda = get_p_tilda(uncomp_numbers, n)
# print(uncomp_numbers)
# plt.hist(uncomp_numbers)
# plt.show()
# make dictionary
dictionary = {i : chr(i) for i in range(n)}
# convert number list to string
uncompressed = str()
for i in uncomp_numbers:
uncompressed = uncompressed + dictionary[i]
# compression
compressed = compress(uncompressed)
compression_ratio = len(compressed)/len(uncompressed)
# entropy
estimated_ent = get_entropy(n, len(uncomp_numbers), compression_ratio, name=name, plot=plot)
# lower bound
lb = h_inverse(estimated_ent,n, a=0.005)
if verbose:
print("p_tilda : ", np.round(p_tilda,3))
print("Compression ratio : ", compression_ratio)
print("Error lower bound : ", lb)
print("[sanity chk] Est.ent~", h(lb,n))
print("Estimated entropy : ", estimated_ent)
print("Kalman filter error: ", prediction_error)
return compression_ratio, estimated_ent, lb, prediction_error
def experiment(a):
#### edit here ####
size = 1024
verbose = True
plot = False
# title = "Gaussian Linear Model, a={}".format(a)
title = "Gaussian Linear Model, a={}".format(a)
path = "result/continuous/dependent_seq"
####################
if not os.path.isdir(path):
os.makedirs(path)
# produce a sequence
# seq = glm(init=0, a=a, length=size)
states, observations, filtered_state_estimates = KalmanSequence(size, a)
# draw estimates
plt.clf()
plt.title("Gaussian Linear Model, a={}".format(a))
plt.plot(observations, color="pink", label= 'obs')
plt.plot(states, color='b', label="true")
plt.plot(filtered_state_estimates, color='r', label="filter")
# plt.plot(smoothed_state_estimates, color='g', label="smooth")
plt.legend()
plt.savefig("{}/glm_{}_{}_sequence.eps".format(path, a, size), format='eps')
# plt.show()
plt.clf()
seq = states[:,0]
est = filtered_state_estimates[:,0]
numbin=[]
binsize=[]
y=[]
z=[]
for k in range(1,9):
print(k)
# dict size
n = 2**k
name = "a discretized r.v. into {} buckets".format(n)
compression_ratio, estimated_ent, lb, prediction_error = test(seq, est, n, k, name, plot, verbose)
binsize.append(2**(-k))
numbin.append(n)
y.append(lb)
z.append(prediction_error)
print()
plt.title(title)
plt.hist(seq, density=True)
plt.savefig("{}/glm_{}_{}_hist.png".format(path, a, size), format='eps')
# plt.show()
plt.clf()
plt.title(title)
plt.plot(numbin,y, marker='.', label="error lower bound")
plt.plot(numbin,z, marker='.', label="kalman filter error")
plt.xlabel("# bins (=2^k)")
plt.ylabel("Misclassification error")
plt.ylim(0,1)
plt.legend()
plt.savefig("{}/glm_{}_{}_error-numbin.eps".format(path, a, size), format='eps')
# plt.show()
plt.clf()
plt.title(title)
plt.plot(binsize,y, marker='.', label="error lower bound")
plt.plot(binsize,z, marker='.', label="kalman filter error")
plt.xlabel("Bin size (=1/2^k)")
plt.ylabel("Misclassification error")
plt.ylim(0,1)
plt.legend()
plt.savefig("{}/glm_{}_{}_error-binsize.eps".format(path, a, size), format='eps')
# plt.show()
plt.clf()
def main():
print("*******************************************************")
print("*******************************************************")
print("********** Running the Testing Scripts. ***************")
for a in [0.1,0.5,1]:
experiment(a)
print("********** Testing Scripts Done. **********************")
print("*******************************************************")
print("*******************************************************")
if __name__ == "__main__":
main()
| 31.898936 | 106 | 0.597465 |
aceff3cfca1000aa2916f9a4851c3ecd413cafea | 597 | py | Python | tests/test_pandas_dtype.py | interpretml/ebm2onnx | e484814e93bb0a479c412e413a63a17935e9d15e | [
"MIT"
] | 7 | 2021-05-20T19:51:32.000Z | 2021-12-14T04:21:41.000Z | tests/test_pandas_dtype.py | SoftAtHome/ebm2onnx | e484814e93bb0a479c412e413a63a17935e9d15e | [
"MIT"
] | 2 | 2021-10-06T13:59:33.000Z | 2021-10-08T09:13:38.000Z | tests/test_pandas_dtype.py | SoftAtHome/ebm2onnx | e484814e93bb0a479c412e413a63a17935e9d15e | [
"MIT"
] | 2 | 2021-05-24T21:45:36.000Z | 2021-09-29T17:23:51.000Z | import os
import pandas as pd
import ebm2onnx
def test_titanic_types():
df = pd.read_csv(os.path.join('examples','titanic_train.csv'))
df['Survived'] = df['Survived'].astype(bool)
df['Fare'] = df['Fare'].astype('float32')
assert ebm2onnx.get_dtype_from_pandas(df) == {
'PassengerId': 'int',
'Survived': 'bool',
'Pclass': 'int',
'Name': 'str',
'Sex': 'str',
'Age': 'double',
'SibSp': 'int',
'Parch': 'int',
'Ticket': 'str',
'Fare': 'float',
'Cabin': 'str',
'Embarked': 'str',
}
| 22.961538 | 66 | 0.514238 |
aceff54c2efd105dec712f2c87d388865823647a | 2,079 | py | Python | accounts/models.py | NickMcGettigan/Autama-Backend | 82e15b045bd4f1302df51bf830b3bfc869990f88 | [
"MIT"
] | null | null | null | accounts/models.py | NickMcGettigan/Autama-Backend | 82e15b045bd4f1302df51bf830b3bfc869990f88 | [
"MIT"
] | null | null | null | accounts/models.py | NickMcGettigan/Autama-Backend | 82e15b045bd4f1302df51bf830b3bfc869990f88 | [
"MIT"
] | null | null | null | from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
sex = models.IntegerField(verbose_name="gender", choices=((0, 'male'), (1, 'female'), (2, 'non-binary')), default=0)
image = models.ImageField(max_length=1000, upload_to='avatar', verbose_name=u'picture', null=True, blank=True)
interests1 = models.TextField()
interests2 = models.TextField()
interests3 = models.TextField()
interests4 = models.TextField()
interests5 = models.TextField()
interests6 = models.TextField()
currentAutama = models.IntegerField(default=1) # Used for find matches stack tracing.
nextAutama = models.IntegerField(default=2)
my_Autama = models.IntegerField(default=0) # Use for tracking the amount of Autamas the user created
last_page = models.CharField(max_length=100, default='/MyMatches/') # Tracks the page used to get to chat page
class Claims(models.Model):
autamaID = models.OneToOneField('AutamaProfiles.AutamaProfile', on_delete=models.CASCADE)
userID = models.ForeignKey('User', on_delete=models.CASCADE)
timeStamp = models.DateTimeField(auto_now_add=True)
class Messages(models.Model):
# Constants used for enum in sender
USER = 'User'
AUTAMA = 'Autama'
SENDER_CHOICES = [
(USER, 'User'),
(AUTAMA, 'Autama'),
]
message = models.TextField()
timeStamp = models.DateTimeField(auto_now_add=True)
userID = models.ForeignKey('User', on_delete=models.CASCADE)
autamaID = models.ForeignKey('AutamaProfiles.AutamaProfile', on_delete=models.CASCADE)
sender = models.CharField(max_length=6, choices=SENDER_CHOICES)
def __str__(self):
return '{userID} {autamaID}'.format(userID=self.userID, autamaID=self.autamaID)
class Matches(models.Model):
timeStamp = models.DateTimeField(auto_now_add=True)
userID = models.ForeignKey('User', on_delete=models.CASCADE)
autamaID = models.ForeignKey('AutamaProfiles.AutamaProfile', on_delete=models.CASCADE)
| 42.428571 | 121 | 0.708995 |
aceff64b623b8f4c3859a682efe2e38c006a232b | 2,393 | py | Python | run_pms7003.py | chipgarner/yourair | 22415389256cfa283e817970d6c79c187cbded4c | [
"MIT"
] | null | null | null | run_pms7003.py | chipgarner/yourair | 22415389256cfa283e817970d6c79c187cbded4c | [
"MIT"
] | null | null | null | run_pms7003.py | chipgarner/yourair | 22415389256cfa283e817970d6c79c187cbded4c | [
"MIT"
] | null | null | null | import logging
import logging.handlers
import os
from publish.publisher import Publisher
from Secrets import SECRET # Credential string for MQTT on Thingsboard - don't put credentials in Git
from sense.sensors import PmsSensor
try:
from display.display import Display
display = True
except ModuleNotFoundError:
display = False # Assuming this means no display is installed
from publish.publish import Publish
class RunMePms7003:
def __init__(self):
log_format = '%(asctime)s %(name)s %(message)s'
logging.basicConfig(format=log_format,
datefmt='%m/%d/%Y %I:%M:%S %p',
level=logging.DEBUG)
self.logger = logging.getLogger()
directory_path = os.path.dirname(__file__)
formatter = logging.Formatter(log_format, datefmt='%m/%d/%Y %I:%M:%S %p')
file_path = directory_path + '/warning.log'
warning_log_handler = logging.handlers.TimedRotatingFileHandler(file_path, when='D', interval=1,
backupCount=5, utc=True)
warning_log_handler.setLevel(logging.WARNING)
warning_log_handler.setFormatter(formatter)
self.logger.addHandler(warning_log_handler)
file_path = directory_path + '/debug.log'
debug_log_handler = logging.handlers.TimedRotatingFileHandler(file_path, when='D', interval=1,
backupCount=5, utc=True)
debug_log_handler.setLevel(logging.DEBUG)
debug_log_handler.setFormatter(formatter)
self.logger.addHandler(debug_log_handler)
self.sensors = PmsSensor()
if display:
self.display = Display()
else:
self.logger.warning('Could not import display, assuming there is none.')
self.display = None
self.publish = Publish(Publisher(SECRET))
self.running = True
def loop(self):
self.logger.info('Starting loop')
while self.running:
latest = self.sensors.get_latest()
if self.display is not None:
self.display.display(latest)
self.publish.publish(latest)
self.logger.error('Exited main loop')
self.sensors.stop()
if __name__ == '__main__':
runner = RunMePms7003()
runner.loop()
| 33.704225 | 104 | 0.619724 |
aceff656e4e87cf2a1dd8484bb454dc232010722 | 4,408 | py | Python | test/test_session.py | chavit/fast-acl-plugin | 3ecac10d386edbb7d30ce8ae1facd003391b828f | [
"Apache-2.0"
] | 3 | 2019-11-22T13:24:26.000Z | 2021-02-22T12:33:10.000Z | test/test_session.py | ayourtch/vpp | 9e9ba6bd72d3c57d32d2100e4249549ba1295798 | [
"Apache-2.0"
] | null | null | null | test/test_session.py | ayourtch/vpp | 9e9ba6bd72d3c57d32d2100e4249549ba1295798 | [
"Apache-2.0"
] | 1 | 2019-12-06T14:29:39.000Z | 2019-12-06T14:29:39.000Z | #!/usr/bin/env python
import unittest
from framework import VppTestCase, VppTestRunner
from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath
class TestSession(VppTestCase):
""" Session Test Case """
@classmethod
def setUpClass(cls):
super(TestSession, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestSession, cls).tearDownClass()
def setUp(self):
super(TestSession, self).setUp()
self.vapi.session_enable_disable(is_enabled=1)
self.create_loopback_interfaces(2)
table_id = 0
for i in self.lo_interfaces:
i.admin_up()
if table_id != 0:
tbl = VppIpTable(self, table_id)
tbl.add_vpp_config()
i.set_table_ip4(table_id)
i.config_ip4()
table_id += 1
# Configure namespaces
self.vapi.app_namespace_add_del(namespace_id=b"0",
sw_if_index=self.loop0.sw_if_index)
self.vapi.app_namespace_add_del(namespace_id=b"1",
sw_if_index=self.loop1.sw_if_index)
def tearDown(self):
for i in self.lo_interfaces:
i.unconfig_ip4()
i.set_table_ip4(0)
i.admin_down()
super(TestSession, self).tearDown()
self.vapi.session_enable_disable(is_enabled=1)
def test_segment_manager_alloc(self):
""" Session Segment Manager Multiple Segment Allocation """
# Add inter-table routes
ip_t01 = VppIpRoute(self, self.loop1.local_ip4, 32,
[VppRoutePath("0.0.0.0",
0xffffffff,
nh_table_id=1)])
ip_t10 = VppIpRoute(self, self.loop0.local_ip4, 32,
[VppRoutePath("0.0.0.0",
0xffffffff,
nh_table_id=0)], table_id=1)
ip_t01.add_vpp_config()
ip_t10.add_vpp_config()
# Start builtin server and client with small private segments
uri = "tcp://" + self.loop0.local_ip4 + "/1234"
error = self.vapi.cli("test echo server appns 0 fifo-size 64 " +
"private-segment-size 1m uri " + uri)
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
error = self.vapi.cli("test echo client nclients 100 appns 1 " +
"no-output fifo-size 64 syn-timeout 2 " +
"private-segment-size 1m uri " + uri)
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
if self.vpp_dead:
self.assert_equal(0)
# Delete inter-table routes
ip_t01.remove_vpp_config()
ip_t10.remove_vpp_config()
class TestSessionUnitTests(VppTestCase):
""" Session Unit Tests Case """
@classmethod
def setUpClass(cls):
super(TestSessionUnitTests, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestSessionUnitTests, cls).tearDownClass()
def setUp(self):
super(TestSessionUnitTests, self).setUp()
self.vapi.session_enable_disable(is_enabled=1)
def test_session(self):
""" Session Unit Tests """
error = self.vapi.cli("test session all")
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
def tearDown(self):
super(TestSessionUnitTests, self).tearDown()
self.vapi.session_enable_disable(is_enabled=0)
class TestSvmFifoUnitTests(VppTestCase):
""" SVM Fifo Unit Tests Case """
@classmethod
def setUpClass(cls):
super(TestSvmFifoUnitTests, cls).setUpClass()
@classmethod
def tearDownClass(cls):
super(TestSvmFifoUnitTests, cls).tearDownClass()
def setUp(self):
super(TestSvmFifoUnitTests, self).setUp()
def test_svm_fifo(self):
""" SVM Fifo Unit Tests """
error = self.vapi.cli("test svm fifo all")
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
def tearDown(self):
super(TestSvmFifoUnitTests, self).tearDown()
if __name__ == '__main__':
unittest.main(testRunner=VppTestRunner)
| 29.986395 | 75 | 0.582804 |
aceff8715c3f1d12423ffa1cb0c09546c032c4d2 | 5,843 | py | Python | tools/tcpdrop.py | teroz/bcc | fbb42c77ac15937dacac80ef212197a58739df4b | [
"Apache-2.0"
] | 2 | 2020-08-14T16:41:10.000Z | 2021-07-07T15:10:33.000Z | tools/tcpdrop.py | teroz/bcc | fbb42c77ac15937dacac80ef212197a58739df4b | [
"Apache-2.0"
] | 1 | 2020-07-01T20:08:46.000Z | 2020-07-01T20:08:46.000Z | tools/tcpdrop.py | teroz/bcc | fbb42c77ac15937dacac80ef212197a58739df4b | [
"Apache-2.0"
] | 1 | 2021-05-24T04:35:40.000Z | 2021-05-24T04:35:40.000Z | #!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
# tcpdrop Trace TCP kernel-dropped packets/segments.
# For Linux, uses BCC, eBPF. Embedded C.
#
# This provides information such as packet details, socket state, and kernel
# stack trace for packets/segments that were dropped via tcp_drop().
#
# USAGE: tcpdrop [-h]
#
# This uses dynamic tracing of kernel functions, and will need to be updated
# to match kernel changes.
#
# Copyright 2018 Netflix, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# 30-May-2018 Brendan Gregg Created this.
from __future__ import print_function
from bcc import BPF
import argparse
from time import strftime
from socket import inet_ntop, AF_INET, AF_INET6
from struct import pack
from time import sleep
from bcc import tcp
# arguments
examples = """examples:
./tcpdrop # trace kernel TCP drops
"""
parser = argparse.ArgumentParser(
description="Trace TCP drops by the kernel",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=examples)
parser.add_argument("--ebpf", action="store_true",
help=argparse.SUPPRESS)
args = parser.parse_args()
debug = 0
# define BPF program
bpf_text = """
#include <uapi/linux/ptrace.h>
#include <uapi/linux/tcp.h>
#include <uapi/linux/ip.h>
#include <net/sock.h>
#include <bcc/proto.h>
BPF_STACK_TRACE(stack_traces, 1024);
// separate data structs for ipv4 and ipv6
struct ipv4_data_t {
u32 pid;
u64 ip;
u32 saddr;
u32 daddr;
u16 sport;
u16 dport;
u8 state;
u8 tcpflags;
u32 stack_id;
};
BPF_PERF_OUTPUT(ipv4_events);
struct ipv6_data_t {
u32 pid;
u64 ip;
unsigned __int128 saddr;
unsigned __int128 daddr;
u16 sport;
u16 dport;
u8 state;
u8 tcpflags;
u32 stack_id;
};
BPF_PERF_OUTPUT(ipv6_events);
static struct tcphdr *skb_to_tcphdr(const struct sk_buff *skb)
{
// unstable API. verify logic in tcp_hdr() -> skb_transport_header().
return (struct tcphdr *)(skb->head + skb->transport_header);
}
static inline struct iphdr *skb_to_iphdr(const struct sk_buff *skb)
{
// unstable API. verify logic in ip_hdr() -> skb_network_header().
return (struct iphdr *)(skb->head + skb->network_header);
}
// from include/net/tcp.h:
#ifndef tcp_flag_byte
#define tcp_flag_byte(th) (((u_int8_t *)th)[13])
#endif
int trace_tcp_drop(struct pt_regs *ctx, struct sock *sk, struct sk_buff *skb)
{
if (sk == NULL)
return 0;
u32 pid = bpf_get_current_pid_tgid();
// pull in details from the packet headers and the sock struct
u16 family = sk->__sk_common.skc_family;
char state = sk->__sk_common.skc_state;
u16 sport = 0, dport = 0;
struct tcphdr *tcp = skb_to_tcphdr(skb);
struct iphdr *ip = skb_to_iphdr(skb);
u8 tcpflags = ((u_int8_t *)tcp)[13];
sport = tcp->source;
dport = tcp->dest;
sport = ntohs(sport);
dport = ntohs(dport);
if (family == AF_INET) {
struct ipv4_data_t data4 = {};
data4.pid = pid;
data4.ip = 4;
data4.saddr = ip->saddr;
data4.daddr = ip->daddr;
data4.dport = dport;
data4.sport = sport;
data4.state = state;
data4.tcpflags = tcpflags;
data4.stack_id = stack_traces.get_stackid(ctx, 0);
ipv4_events.perf_submit(ctx, &data4, sizeof(data4));
} else if (family == AF_INET6) {
struct ipv6_data_t data6 = {};
data6.pid = pid;
data6.ip = 6;
bpf_probe_read_kernel(&data6.saddr, sizeof(data6.saddr),
sk->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32);
bpf_probe_read_kernel(&data6.daddr, sizeof(data6.daddr),
sk->__sk_common.skc_v6_daddr.in6_u.u6_addr32);
data6.dport = dport;
data6.sport = sport;
data6.state = state;
data6.tcpflags = tcpflags;
data6.stack_id = stack_traces.get_stackid(ctx, 0);
ipv6_events.perf_submit(ctx, &data6, sizeof(data6));
}
// else drop
return 0;
}
"""
if debug or args.ebpf:
print(bpf_text)
if args.ebpf:
exit()
# process event
def print_ipv4_event(cpu, data, size):
event = b["ipv4_events"].event(data)
print("%-8s %-6d %-2d %-20s > %-20s %s (%s)" % (
strftime("%H:%M:%S"), event.pid, event.ip,
"%s:%d" % (inet_ntop(AF_INET, pack('I', event.saddr)), event.sport),
"%s:%s" % (inet_ntop(AF_INET, pack('I', event.daddr)), event.dport),
tcp.tcpstate[event.state], tcp.flags2str(event.tcpflags)))
for addr in stack_traces.walk(event.stack_id):
sym = b.ksym(addr, show_offset=True)
print("\t%s" % sym)
print("")
def print_ipv6_event(cpu, data, size):
event = b["ipv6_events"].event(data)
print("%-8s %-6d %-2d %-20s > %-20s %s (%s)" % (
strftime("%H:%M:%S"), event.pid, event.ip,
"%s:%d" % (inet_ntop(AF_INET6, event.saddr), event.sport),
"%s:%d" % (inet_ntop(AF_INET6, event.daddr), event.dport),
tcp.tcpstate[event.state], tcp.flags2str(event.tcpflags)))
for addr in stack_traces.walk(event.stack_id):
sym = b.ksym(addr, show_offset=True)
print("\t%s" % sym)
print("")
# initialize BPF
b = BPF(text=bpf_text)
if b.get_kprobe_functions(b"tcp_drop"):
b.attach_kprobe(event="tcp_drop", fn_name="trace_tcp_drop")
else:
print("ERROR: tcp_drop() kernel function not found or traceable. "
"Older kernel versions not supported.")
exit()
stack_traces = b.get_table("stack_traces")
# header
print("%-8s %-6s %-2s %-20s > %-20s %s (%s)" % ("TIME", "PID", "IP",
"SADDR:SPORT", "DADDR:DPORT", "STATE", "FLAGS"))
# read events
b["ipv4_events"].open_perf_buffer(print_ipv4_event)
b["ipv6_events"].open_perf_buffer(print_ipv6_event)
while 1:
try:
b.perf_buffer_poll()
except KeyboardInterrupt:
exit()
| 29.215 | 77 | 0.651378 |
aceff8803c0d8028efe9feb5485abf88e29ef747 | 411 | py | Python | dit_helpdesk/rules_of_origin/migrations/0007_auto_20201117_1626.py | uktrade/dit-helpdesk | f5127daa46e920d33ec3f0b982136b65bba0353a | [
"MIT"
] | 3 | 2019-10-24T10:39:38.000Z | 2021-07-13T11:46:18.000Z | dit_helpdesk/rules_of_origin/migrations/0007_auto_20201117_1626.py | uktrade/dit-helpdesk | f5127daa46e920d33ec3f0b982136b65bba0353a | [
"MIT"
] | 20 | 2020-01-22T11:16:24.000Z | 2022-02-02T10:38:54.000Z | dit_helpdesk/rules_of_origin/migrations/0007_auto_20201117_1626.py | uktrade/dit-helpdesk | f5127daa46e920d33ec3f0b982136b65bba0353a | [
"MIT"
] | null | null | null | # Generated by Django 2.2.13 on 2020-11-17 16:26
import django_migration_linter as linter
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("rules_of_origin", "0006_auto_20201117_1233")]
operations = [
linter.IgnoreMigration(),
migrations.RenameField(
model_name="rule", old_name="rule_id", new_name="description"
),
]
| 24.176471 | 73 | 0.688564 |
aceff8b090b779db8f9fccb709d0b99ca330346f | 1,465 | py | Python | docs/source/conf.py | Tensor46/TensorMONK | 67617d3fdf8fde072ba9cab42de7d67c79b17494 | [
"MIT"
] | 29 | 2018-07-06T23:57:23.000Z | 2022-03-08T20:38:57.000Z | docs/source/conf.py | sparupat/TensorMONK | 7a2699a28299a89b186e0eb17ed6e9feaea5429e | [
"MIT"
] | 3 | 2018-12-14T22:21:26.000Z | 2020-06-19T02:13:34.000Z | docs/source/conf.py | sparupat/TensorMONK | 7a2699a28299a89b186e0eb17ed6e9feaea5429e | [
"MIT"
] | 8 | 2018-07-06T23:58:03.000Z | 2021-04-12T01:35:54.000Z |
import datetime
import sphinx_rtd_theme
import doctest
import sys
import os
sys.path.insert(0, os.path.abspath("../"))
sys.path.insert(0, os.path.abspath("../.."))
sys.path.insert(0, os.path.abspath("../../tensormonk"))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.mathjax',
'sphinx.ext.napoleon',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
]
source_suffix = '.rst'
master_doc = 'index'
author = 'Vikas Gottemukkula, Sashi Saripalle'
project = 'TensorMONK'
copyright = '{}, {}'.format(datetime.datetime.now().year, author)
version = '0.5.0'
release = '0.5.0'
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
doctest_default_flags = doctest.NORMALIZE_WHITESPACE
intersphinx_mapping = {'python': ('https://docs.python.org/', None)}
html_theme_options = {
'collapse_navigation': False,
'display_version': True,
'logo_only': True,
}
html_logo = '_static/img/tensormonk-transparent.png'
html_static_path = ['_static']
html_context = {'css_files': ['_static/css/custom.css']}
add_module_names = False
def setup(app):
def skip(app, what, name, obj, skip, options):
members = [
'__init__',
'__repr__',
'__weakref__',
'__dict__',
'__module__',
]
return True if name in members else skip
app.connect('autodoc-skip-member', skip)
| 23.253968 | 68 | 0.661433 |
aceff8fb0143d34882416d0a7cfd8fed7bc9b5c3 | 6,020 | py | Python | test/functional/rpc_part_mnemonic.py | dmuralov/particl | d56f81eda29ba9967000148d53afed38877b8f7e | [
"MIT"
] | 2 | 2021-12-07T13:52:29.000Z | 2022-01-08T08:56:05.000Z | test/functional/rpc_part_mnemonic.py | dmuralov/particl | d56f81eda29ba9967000148d53afed38877b8f7e | [
"MIT"
] | null | null | null | test/functional/rpc_part_mnemonic.py | dmuralov/particl | d56f81eda29ba9967000148d53afed38877b8f7e | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2017 The Particl Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_particl import ParticlTestFramework
from test_framework.authproxy import JSONRPCException
class MnemonicTest(ParticlTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
self.extra_args = [ ['-debug',] for i in range(self.num_nodes)]
def setup_network(self, split=False):
self.add_nodes(self.num_nodes, extra_args=self.extra_args)
self.start_nodes()
self.sync_all()
def run_test(self):
node = self.nodes[0]
# mnemonic new [password] [language] [nBytesEntropy] [bip44]
# check default key is bip44
json_obj = node.mnemonic('new')
key = json_obj['master']
assert(key.startswith('tprv')), 'Key is not bip44.'
# check bip32 key is made
json_obj = node.mnemonic('new', '', 'english', '32', 'false')
key = json_obj['master']
assert(key.startswith('xpar')), 'Key is not bip32.'
checkLangs = ['english', 'french', 'japanese', 'spanish', 'chinese_s', 'chinese_t', 'italian', 'korean']
for i in range(8):
for l in checkLangs:
json_obj = node.mnemonic('new', '', l)
keyBip44 = json_obj['master']
words = json_obj['mnemonic']
assert(keyBip44.startswith('tprv')), 'Key is not bip44.'
json_obj = node.mnemonic('decode', '', words)
assert json_obj['master'] == keyBip44, 'Decoded bip44 key does not match.'
# bip32
json_obj = node.mnemonic('new', '', l, '32', 'false')
keyBip32 = json_obj['master']
words = json_obj['mnemonic']
assert(keyBip32.startswith('xpar')), 'Key is not bip32.'
json_obj = node.mnemonic('decode', '', words, 'false')
assert json_obj['master'] == keyBip32, 'Decoded bip32 key does not match.'
# with pwd
json_obj = node.mnemonic('new', 'qwerty123', l)
keyBip44Pass = json_obj['master']
words = json_obj['mnemonic']
assert(keyBip44Pass.startswith('tprv')), 'Key is not bip44.'
json_obj = node.mnemonic('decode', 'qwerty123', words)
assert json_obj['master'] == keyBip44Pass, 'Decoded bip44 key with password does not match.'
json_obj = node.mnemonic('decode', 'wrongpass', words)
assert json_obj['master'] != keyBip44Pass, 'Decoded bip44 key with wrong password should not match.'
try:
ro = node.mnemonic('new', '', 'english', '15')
assert(False), 'Generated mnemonic from < 16bytes entropy.'
except JSONRPCException as e:
assert('Num bytes entropy out of range [16,64]' in e.error['message'])
for i in range(16, 65):
ro = node.mnemonic('new', '', 'english', str(i))
try:
ro = node.mnemonic('new', '', 'english', '65')
assert(False), 'Generated mnemonic from > 64bytes entropy .'
except JSONRPCException as e:
assert('Num bytes entropy out of range [16,64]' in e.error['message'])
ro = node.mnemonic('new', '', 'english', '64')
assert(len(ro['mnemonic'].split(' ')) == 48)
try:
ro = node.mnemonic('new', '', 'abcdefgh', '15')
assert(False), 'Generated mnemonic from unknown language.'
except JSONRPCException as e:
assert('Unknown language' in e.error['message'])
ro = node.mnemonic('dumpwords')
assert(ro['num_words'] == 2048)
for l in checkLangs:
ro = node.mnemonic('dumpwords', l)
assert(ro['num_words'] == 2048)
ro = node.mnemonic('listlanguages')
assert(len(ro) == 8)
# Test incorrect parameter order: mnemonic,password vs password,mnemonic
try:
ro = node.mnemonic('decode', 'abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb', '')
assert(False), 'Decoded empty word string.'
except JSONRPCException as e:
print(e.error['message'])
assert("Mnemonic can't be blank" in e.error['message'])
# Normalise 'alléger'
ro = node.mnemonic('decode', '', 'sortir hygiène boueux détourer doyen émission prospère tunnel cerveau miracle brioche feuille arbitre terne alléger prison connoter diable méconnu fraise pelle carbone erreur admettre')
assert(ro['master'] == 'tprv8ZgxMBicQKsPdsKV1vzsQkRQp5TobgyfXsBLcU49jmnC2zBT4Cd5LTCtdoWe5gg7EPjjQnAsxbMG1qyoCn1bHn6n4c1ZEdFLKg1TJAwTriQ')
# Leading and trailing spaces
ro = node.mnemonic('decode', '', ' sortir hygiène boueux détourer doyen émission prospère tunnel cerveau miracle brioche feuille arbitre terne alléger prison connoter diable méconnu fraise pelle carbone erreur admettre ')
assert(ro['master'] == 'tprv8ZgxMBicQKsPdsKV1vzsQkRQp5TobgyfXsBLcU49jmnC2zBT4Cd5LTCtdoWe5gg7EPjjQnAsxbMG1qyoCn1bHn6n4c1ZEdFLKg1TJAwTriQ')
# Multiple spaces between words
try:
ro = node.mnemonic('decode', '', 'abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb')
assert(False), 'Decoded with multiple spaces.'
except JSONRPCException as e:
assert("Multiple spaces between words" in e.error['message'])
try:
ro = node.mnemonic('decode', '', 'abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb')
assert(False), 'Decoded with multiple spaces.'
except JSONRPCException as e:
assert("Multiple spaces between words" in e.error['message'])
if __name__ == '__main__':
MnemonicTest().main()
| 43 | 235 | 0.614286 |
aceff9d5560d28b1bbefe51a1386f1a42f111f76 | 25,880 | py | Python | rman_ui/rman_ui_txmanager.py | N500/RenderManForBlender | 76de176322a130b657a898fef7123168677f67eb | [
"MIT"
] | 5 | 2018-01-13T09:37:35.000Z | 2021-07-19T08:55:28.000Z | rman_ui/rman_ui_txmanager.py | N500/RenderManForBlender | 76de176322a130b657a898fef7123168677f67eb | [
"MIT"
] | 3 | 2018-01-17T22:32:24.000Z | 2018-01-22T13:36:31.000Z | rman_ui/rman_ui_txmanager.py | N500/RenderManForBlender | 76de176322a130b657a898fef7123168677f67eb | [
"MIT"
] | 2 | 2020-02-01T15:37:09.000Z | 2020-06-16T16:40:17.000Z | import bpy
from bpy.props import StringProperty, IntProperty, CollectionProperty, EnumProperty, BoolProperty, FloatProperty
from bpy.types import PropertyGroup, UIList, Operator, Panel
from bpy_extras.io_utils import ImportHelper
from .rman_ui_base import _RManPanelHeader
from ..rfb_utils import texture_utils
from ..rfb_utils import shadergraph_utils
from ..rfb_utils import scene_utils
from ..rfb_utils import object_utils
from ..rman_config import __RFB_CONFIG_DICT__ as rfb_config
from .. import rman_render
from rman_utils.txmanager import txparams
from rman_utils import txmanager as txmngr
from .. import rfb_icons
import os
import uuid
class TxFileItem(PropertyGroup):
"""UIList item representing a TxFile"""
name: StringProperty(
name="Name",
description="Image name",
default="")
tooltip: StringProperty(
name="tooltip",
description="Tool Tip",
default="")
nodeID: StringProperty(
name="nodeID",
description="Node ID (hidden)",
default="")
state: IntProperty(
name="state",
description="",
default=0
)
enable: BoolProperty(
name="enable",
description="Enable or disable this TxFileItem",
default=True
)
def colorspace_names(self, context):
items = []
items.append(('0', '', ''))
try:
mdict = texture_utils.get_txmanager().txmanager.color_manager.colorspace_names()
for nm in mdict:
items.append((nm, nm, ""))
except AttributeError:
pass
return items
ocioconvert: EnumProperty(
name="Color Space",
description="colorspace",
items=colorspace_names
)
txsettings = ['texture_type',
's_mode',
't_mode',
'texture_format',
'data_type',
'resize',
'ocioconvert']
items = []
for item in txparams.TX_TYPES:
items.append((item, item, ''))
texture_type: EnumProperty(
name="Texture Type",
items=items,
description="Texture Type",
default=txparams.TX_TYPE_REGULAR)
items = []
for item in txparams.TX_WRAP_MODES:
items.append((item, item, ''))
s_mode: EnumProperty(
name="S Wrap",
items=items,
default=txparams.TX_WRAP_MODE_PERIODIC)
t_mode: EnumProperty(
name="T Wrap",
items=items,
default=txparams.TX_WRAP_MODE_PERIODIC)
items = []
for item in txparams.TX_FORMATS:
items.append((item, item, ''))
texture_format: EnumProperty(
name="Format",
default=txparams.TX_FORMAT_PIXAR,
items=items,
description="Texture format")
items = []
items.append(('default', 'default', ''))
for item in txparams.TX_DATATYPES:
items.append((item, item, ''))
data_type: EnumProperty(
name="Data Type",
default=txparams.TX_DATATYPE_FLOAT,
items=items,
description="The data storage txmake uses")
items = []
for item in txparams.TX_RESIZES:
items.append((item, item, ''))
resize: EnumProperty(
name="Resize",
default=txparams.TX_RESIZE_UP_DASH,
items=items,
description="The type of resizing flag to pass to txmake")
bumpRough: EnumProperty(
name="Bump Rough",
default="-1",
items=(
("-1", "Off", ""),
("0", "Bump Map", ""),
("1", "Normal Map", "")
)
)
bumpRough_factor: FloatProperty(
name="Scale",
default=2.0
)
bumpRough_invert: BoolProperty(
name="Invert",
default=False
)
bumpRough_invertU: BoolProperty(
name="InvertU",
default=False
)
bumpRough_invertV: BoolProperty(
name="InvertV",
default=False
)
bumpRough_refit: BoolProperty(
name="Refit",
default=False
)
class PRMAN_UL_Renderman_txmanager_list(UIList):
"""RenderMan TxManager UIList."""
def draw_item(self, context, layout, data, item, icon, active_data,
active_propname, index):
icons_map = {txmngr.STATE_MISSING: 'ERROR',
txmngr.STATE_EXISTS: 'CHECKBOX_HLT',
txmngr.STATE_IS_TEX: 'TEXTURE',
txmngr.STATE_IN_QUEUE: 'PLUS',
txmngr.STATE_PROCESSING: 'TIME',
txmngr.STATE_ERROR: 'CANCEL',
txmngr.STATE_REPROCESS: 'TIME',
txmngr.STATE_UNKNOWN: 'CANCEL',
txmngr.STATE_INPUT_MISSING: 'ERROR'}
txfile = None
if item.nodeID != "":
txfile = texture_utils.get_txmanager().txmanager.get_txfile_from_id(item.nodeID)
else:
txfile = texture_utils.get_txmanager().txmanager.get_txfile_from_path(item.name)
if txfile:
custom_icon = icons_map[txfile.state]
else:
custom_icon = 'CANCEL'
if self.layout_type in {'DEFAULT', 'COMPACT'}:
layout.label(text=item.name, icon = custom_icon)
elif self.layout_type in {'GRID'}:
layout.alignment = 'CENTER'
layout.label(text="", icon = custom_icon)
class PRMAN_OT_Renderman_txmanager_parse_scene(Operator):
"""Parse scene for textures to add to to the txmanager"""
bl_idname = "rman_txmgr_list.parse_scene"
bl_label = "Parse Scene"
bl_description = "Parse the scene and look for textures that need converting."
def execute(self, context):
rman_txmgr_list = context.scene.rman_txmgr_list
texture_utils.parse_for_textures(context.scene)
texture_utils.get_txmanager().txmake_all(blocking=False)
bpy.ops.rman_txmgr_list.refresh('EXEC_DEFAULT')
return{'FINISHED'}
class PRMAN_OT_Renderman_txmanager_reset_state(Operator):
"""Reset State"""
bl_idname = "rman_txmgr_list.reset_state"
bl_label = "Reset State"
bl_description = "All texture settings will be erased and the scene will be re-parsed. All manual edits will be lost."
def execute(self, context):
rman_txmgr_list = context.scene.rman_txmgr_list
rman_txmgr_list.clear()
texture_utils.get_txmanager().txmanager.reset()
texture_utils.parse_for_textures(context.scene)
texture_utils.get_txmanager().txmake_all(blocking=False)
texture_utils.get_txmanager().txmanager.reset_state()
return{'FINISHED'}
class PRMAN_OT_Renderman_txmanager_pick_images(Operator, ImportHelper):
"""Pick images from a directory."""
bl_idname = "rman_txmgr_list.pick_images"
bl_label = "Pick Images"
bl_description = "Manually choose images on disk to convert."
filename: StringProperty(maxlen=1024)
directory: StringProperty(maxlen=1024)
files: CollectionProperty(type=bpy.types.PropertyGroup)
def execute(self, context):
rman_txmgr_list = context.scene.rman_txmgr_list
if len(self.files) > 0:
for f in self.files:
img = os.path.join(self.directory, f.name)
nodeID = str(uuid.uuid1())
texture_utils.get_txmanager().txmanager.add_texture(nodeID, img)
bpy.ops.rman_txmgr_list.add_texture('EXEC_DEFAULT', filepath=img, nodeID=nodeID)
texture_utils.get_txmanager().txmake_all(blocking=False)
texture_utils.get_txmanager().txmanager.save_state()
PRMAN_PT_Renderman_txmanager_list.refresh_panel(context)
return{'FINISHED'}
class PRMAN_OT_Renderman_txmanager_clear_all_cache(Operator):
"""Clear RenderMan Texture cache"""
bl_idname = "rman_txmgr_list.clear_all_cache"
bl_label = "Flush Texture Cache"
bl_description = "Tell the core RenderMan to flush its texture cache."
def execute(self, context):
rr = rman_render.RmanRender.get_rman_render()
if rr.rman_interactive_running and rr.sg_scene:
texture_list = list()
for item in context.scene.rman_txmgr_list:
if item.nodeID != "":
output_texture = texture_utils.get_txmanager().get_output_tex_from_id(item.nodeID)
texture_list.append(output_texture)
if texture_list:
rr.rman_scene_sync.flush_texture_cache(texture_list)
return{'FINISHED'}
class PRMAN_OT_Renderman_txmanager_reconvert_all(Operator):
"""Clear all .tex files and re-convert."""
bl_idname = "rman_txmgr_list.reconvert_all"
bl_label = "RE-Convert All"
bl_description = "Clear all .tex files for all input images and re-convert."
def execute(self, context):
texture_utils.get_txmanager().txmanager.delete_texture_files()
texture_utils.get_txmanager().txmake_all(blocking=False)
return{'FINISHED'}
class PRMAN_OT_Renderman_txmanager_reconvert_selected(Operator):
"""Clear all .tex files and re-convert selected."""
bl_idname = "rman_txmgr_list.reconvert_selected"
bl_label = "RE-Convert Selected"
bl_description = "Clear all .tex files for selected image and re-convert"
def execute(self, context):
idx = context.scene.rman_txmgr_list_index
item = context.scene.rman_txmgr_list[idx]
txfile = None
if item.nodeID != "":
txfile = texture_utils.get_txmanager().txmanager.get_txfile_from_id(item.nodeID)
else:
txfile = texture_utils.get_txmanager().txmanager.get_txfile_from_path(item.name)
if txfile:
rr = rman_render.RmanRender.get_rman_render()
txfile.delete_texture_files()
if item.nodeID:
rr.rman_scene_sync.texture_updated(item.nodeID)
texture_utils.get_txmanager().txmake_all(blocking=False)
return{'FINISHED'}
class PRMAN_OT_Renderman_txmanager_apply_preset(Operator):
"""Apply current settings to the selected texture."""
bl_idname = "rman_txmgr_list.apply_preset"
bl_label = "Apply preset"
bl_description = "Apply the current settings for this input image and re-convert."
def execute(self, context):
idx = context.scene.rman_txmgr_list_index
item = context.scene.rman_txmgr_list[idx]
txsettings = dict()
for attr in item.txsettings:
val = getattr(item, attr)
if attr == 'data_type' and val == 'default':
val = None
txsettings[attr] = val
# b2r
bumprough = dict()
if item.bumpRough != "-1":
bumprough['normalmap'] = int(item.bumpRough)
bumprough['factor'] = item.bumpRough_factor
bumprough['invert'] = item.bumpRough_invert
bumprough['invertU'] = item.bumpRough_invertU
bumprough['invertV'] = item.bumpRough_invertV
bumprough['refit'] = item.bumpRough_refit
else:
bumprough = list()
txsettings['bumprough'] = bumprough
if txsettings:
txfile = None
if item.nodeID != "":
txfile = texture_utils.get_txmanager().txmanager.get_txfile_from_id(item.nodeID)
else:
txfile = texture_utils.get_txmanager().txmanager.get_txfile_from_path(item.name)
if txfile:
txfile.params.from_dict(txsettings)
txfile.delete_texture_files()
texture_utils.get_txmanager().txmake_all(blocking=False)
texture_utils.get_txmanager().txmanager.save_state()
# update any nodes with colorspace in it
tokens = item.nodeID.split('|')
if len(tokens) < 3:
return
node_name,prop_name,ob_name = tokens
prop_colorspace_name = '%s_colorspace' % prop_name
try:
mdict = texture_utils.get_txmanager().txmanager.color_manager.colorspace_names()
val = 0
for i, nm in enumerate(mdict):
if nm == item.ocioconvert:
val = i+1
break
node, ob = scene_utils.find_node_by_name(node_name, ob_name)
if node:
node[prop_colorspace_name] = val
except AttributeError:
pass
return {'FINISHED'}
class PRMAN_OT_Renderman_txmanager_add_texture(Operator):
"""Add texture."""
bl_idname = "rman_txmgr_list.add_texture"
bl_label = "add_texture"
filepath: StringProperty()
nodeID: StringProperty()
def execute(self, context):
txfile = texture_utils.get_txmanager().txmanager.get_txfile_from_path(self.filepath)
if not txfile:
return{'FINISHED'}
item = None
# check if nodeID already exists in the list
for idx, i in enumerate(context.scene.rman_txmgr_list):
if i.nodeID == self.nodeID:
item = i
break
if not item:
item = context.scene.rman_txmgr_list.add()
item.nodeID = self.nodeID
item.name = txfile.input_image
params = txfile.params
item.texture_type = params.texture_type
item.s_mode = params.s_mode
item.t_mode = params.t_mode
item.texture_format = params.texture_format
if params.data_type is not None:
item.data_type = params.data_type
item.resize = params.resize
item.state = txfile.state
if txfile.state == txmngr.STATE_IS_TEX:
item.enable = False
else:
item.enable = True
if params.ocioconvert:
item.ocioconvert = params.ocioconvert
if params.bumprough:
bumprough = params.bumprough_as_dict()
item.bumpRough = str(bumprough['normalmap'])
item.bumpRough_factor = float(bumprough['factor'])
item.bumpRough_invert = bool(bumprough['invert'])
item.bumpRough_invertU = bool(bumprough['invertU'])
item.bumpRough_invertV = bool(bumprough['invertV'])
item.bumpRough_refit = bool(bumprough['refit'])
else:
params.bumpRough = "-1"
item.tooltip = '\nNode ID: ' + item.nodeID + "\n" + str(txfile)
# FIXME: should also add the nodes that this texture is referenced in
return{'FINISHED'}
class PRMAN_OT_Renderman_txmanager_refresh(Operator):
"""Refresh Texture Manager"""
bl_idname = "rman_txmgr_list.refresh"
bl_label = "refresh"
filepath: StringProperty()
nodeID: StringProperty()
def execute(self, context):
for item in context.scene.rman_txmgr_list:
txfile = texture_utils.get_txmanager().txmanager.get_txfile_from_id(item.nodeID)
if not txfile:
continue
item.name = txfile.input_image
params = txfile.params
item.texture_type = params.texture_type
item.s_mode = params.s_mode
item.t_mode = params.t_mode
item.texture_type = params.texture_type
if params.data_type is not None:
item.data_type = params.data_type
item.resize = params.resize
item.state = txfile.state
if txfile.state == txmngr.STATE_IS_TEX:
item.enable = False
else:
item.enable = True
if params.ocioconvert:
item.ocioconvert = params.ocioconvert
if params.bumprough:
bumprough = params.bumprough_as_dict()
item.bumpRough = str(bumprough['normalmap'])
item.bumpRough_factor = float(bumprough['factor'])
item.bumpRough_invert = bool(bumprough['invert'])
item.bumpRough_invertU = bool(bumprough['invertU'])
item.bumpRough_invertV = bool(bumprough['invertV'])
item.bumpRough_refit = bool(bumprough['refit'])
else:
params.bumpRough = "-1"
item.tooltip = '\n' + item.nodeID + "\n" + str(txfile)
PRMAN_PT_Renderman_txmanager_list.refresh_panel(context)
return {'FINISHED'}
class PRMAN_OT_Renderman_txmanager_remove_texture(Operator):
bl_idname = "rman_txmgr_list.remove_texture"
bl_label = "remove texture"
nodeID: StringProperty()
def execute(self, context):
for i, item in enumerate(context.scene.rman_txmgr_list):
if item.nodeID == self.properties.nodeID:
context.scene.rman_txmgr_list.remove(i)
break
return{'FINISHED'}
class PRMAN_PT_Renderman_txmanager_list(_RManPanelHeader, Panel):
"""RenderMan Texture Manager Panel."""
bl_label = "RenderMan Texture Manager"
bl_idname = "PRMAN_PT_Renderman_txmanager_list"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "scene"
nodeID: StringProperty()
@classmethod
def refresh_panel(cls, context):
for window in context.window_manager.windows:
for area in window.screen.areas:
for space in area.spaces:
if space.type == 'PROPERTIES':
for region in area.regions:
if region.type == 'WINDOW':
region.tag_redraw()
@classmethod
def draw_txmanager_layout(cls, context, layout):
scene = context.scene
row = layout.row()
txmanager = texture_utils.get_txmanager().txmanager
row.operator('rman_txmgr_list.parse_scene', text='Parse Scene')
row.operator('rman_txmgr_list.reset_state', text='Reset', icon='FILE_REFRESH')
row.operator('rman_txmgr_list.pick_images', text='Pick Images', icon='FILE_FOLDER')
row.operator('rman_txmgr_list.reconvert_all', text='Reconvert All')
if scene.rman_txmgr_list_index >= 0 and scene.rman_txmgr_list:
row = layout.row()
row.template_list("PRMAN_UL_Renderman_txmanager_list", "The_List", scene,
"rman_txmgr_list", scene, "rman_txmgr_list_index", item_dyntip_propname="tooltip")
if scene.rman_txmgr_list_index < len(scene.rman_txmgr_list):
item = scene.rman_txmgr_list[scene.rman_txmgr_list_index]
row = layout.row()
row.label(text='Texture Settings')
row = layout.row()
row.enabled = item.enable
row.prop(item, "texture_type")
row = layout.row()
row.enabled = item.enable
row.prop(item, "s_mode")
row.prop(item, "t_mode")
row = layout.row()
row.enabled = item.enable
row.prop(item, "texture_format")
row = layout.row()
row.enabled = item.enable
row.prop(item, "data_type")
row = layout.row()
row.enabled = item.enable
row.prop(item, "resize")
if item.ocioconvert != '0':
row = layout.row()
row.enabled = item.enable
row.prop(item, "ocioconvert")
dst = txmanager.color_manager.scene_colorspace_name
row.label(text='%s' % dst if dst else txmngr.NO_COLORSPACE)
# b2r
row = layout.row()
row.enabled = item.enable
row.prop(item, "bumpRough")
if item.bumpRough != "-1":
row = layout.row()
row.enabled = item.enable
row.alignment = "RIGHT"
row.label(text="")
row.prop(item, "bumpRough_factor")
row.prop(item, "bumpRough_invert")
row.prop(item, "bumpRough_invertU")
row.prop(item, "bumpRough_invertV")
row.prop(item, "bumpRough_refit")
row = layout.row()
row.enabled = item.enable
row.alignment = 'RIGHT'
row.operator('rman_txmgr_list.reconvert_selected', text='Reconvert')
row.operator('rman_txmgr_list.apply_preset', text='Apply')
row = layout.row()
row.alignment='CENTER'
in_list = len(context.scene.rman_txmgr_list)
progress = 'All Converted'
qsize = txmanager.work_queue.qsize()
if qsize != 0:
progress = 'Converting... %d left to convert' % (qsize)
else:
t_size = txmanager.file_size()
# t_size in bytes
t_size /= 1024.0 * 1024.0
unit = 'MB'
if t_size > 1024:
t_size /= 1024.0
unit = 'GB'
progress = 'All Converted (Texture Disk Space: %.2f %s)' % (t_size, unit)
row.label(text=progress)
def draw(self, context):
layout = self.layout
PRMAN_PT_Renderman_txmanager_list.draw_txmanager_layout(context, layout)
class PRMAN_OT_Renderman_open_txmanager(Operator):
bl_idname = "rman_txmgr_list.open_txmanager"
bl_label = "Open TxManager"
nodeID: StringProperty(default='')
def execute(self, context):
return{'FINISHED'}
def draw(self, context):
layout = self.layout
PRMAN_PT_Renderman_txmanager_list.draw_txmanager_layout(context, layout)
def cancel(self, context):
if self.event and self.event.type == 'LEFTMOUSE':
bpy.ops.rman_txmgr_list.open_txmanager('INVOKE_DEFAULT')
def __init__(self):
self.event = None
def invoke(self, context, event):
if self.properties.nodeID != '':
for i, item in enumerate(context.scene.rman_txmgr_list):
if item.nodeID == self.properties.nodeID:
context.scene.rman_txmgr_list_index = i
break
wm = context.window_manager
width = rfb_config['editor_preferences']['texture_manager']['width']
self.event = event
return wm.invoke_props_dialog(self, width=width)
def index_updated(self, context):
'''
When the index updates, make sure the texture settings
are in sync with the txmanager.
'''
idx = context.scene.rman_txmgr_list_index
if idx < 0:
return
item = context.scene.rman_txmgr_list[idx]
txfile = None
if item.nodeID != "":
txfile = texture_utils.get_txmanager().txmanager.get_txfile_from_id(item.nodeID)
else:
txfile = texture_utils.get_txmanager().txmanager.get_txfile_from_path(item.name)
if txfile:
params = txfile.params
item.texture_type = params.texture_type
item.s_mode = params.s_mode
item.t_mode = params.t_mode
item.texture_format = params.texture_format
item.texture_type = params.texture_type
if params.data_type is not None:
item.data_type = params.data_type
item.resize = params.resize
if txfile.state == txmngr.STATE_IS_TEX:
item.enable = False
else:
item.enable = True
if params.ocioconvert:
item.ocioconvert = params.ocioconvert
if params.bumprough:
bumprough = params.bumprough_as_dict()
item.bumpRough = str(bumprough['normalmap'])
item.bumpRough_factor = float(bumprough['factor'])
item.bumpRough_invert = bool(bumprough['invert'])
item.bumpRough_invertU = bool(bumprough['invertU'])
item.bumpRough_invertV = bool(bumprough['invertV'])
item.bumpRough_refit = bool(bumprough['refit'])
else:
params.bumpRough = "-1"
item.tooltip = '\nNode ID: ' + item.nodeID + "\n" + str(txfile)
classes = [
TxFileItem,
PRMAN_UL_Renderman_txmanager_list,
PRMAN_OT_Renderman_txmanager_parse_scene,
PRMAN_OT_Renderman_txmanager_reset_state,
PRMAN_OT_Renderman_txmanager_pick_images,
PRMAN_OT_Renderman_txmanager_clear_all_cache,
PRMAN_OT_Renderman_txmanager_reconvert_all,
PRMAN_OT_Renderman_txmanager_reconvert_selected,
PRMAN_OT_Renderman_txmanager_apply_preset,
PRMAN_OT_Renderman_txmanager_add_texture,
PRMAN_OT_Renderman_txmanager_refresh,
PRMAN_PT_Renderman_txmanager_list,
PRMAN_OT_Renderman_open_txmanager,
PRMAN_OT_Renderman_txmanager_remove_texture
]
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.Scene.rman_txmgr_list = CollectionProperty(type = TxFileItem)
bpy.types.Scene.rman_txmgr_list_index = IntProperty(name = "RenderMan Texture Manager",
default = 0, update=index_updated)
def unregister():
del bpy.types.Scene.rman_txmgr_list
del bpy.types.Scene.rman_txmgr_list_index
for cls in classes:
try:
bpy.utils.unregister_class(cls)
except RuntimeError:
rfb_log().debug('Could not unregister class: %s' % str(cls))
pass | 35.598349 | 122 | 0.596909 |
aceffa49309a70f38c855ca62ca91f2324813f03 | 1,143 | py | Python | pychron/geochron/tasks/node.py | ael-noblegas/pychron | 6ebbbb1f66a614972b62b7a9be4c784ae61b5d62 | [
"Apache-2.0"
] | 1 | 2019-02-27T21:57:44.000Z | 2019-02-27T21:57:44.000Z | pychron/geochron/tasks/node.py | ael-noblegas/pychron | 6ebbbb1f66a614972b62b7a9be4c784ae61b5d62 | [
"Apache-2.0"
] | 80 | 2018-07-17T20:10:20.000Z | 2021-08-17T15:38:24.000Z | pychron/geochron/tasks/node.py | AGESLDEO/pychron | 1a81e05d9fba43b797f335ceff6837c016633bcf | [
"Apache-2.0"
] | null | null | null | # ===============================================================================
# Copyright 2016 ross
#
# 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 __future__ import absolute_import
from traits.api import Instance
from pychron.pipeline.nodes.base import BaseNode
class GeochronNode(BaseNode):
service = Instance('pychron.geochron.geochron_service.GeochronService')
def configure(self):
return True
def run(self, state):
if state.unknowns:
pass
# ============= EOF =============================================
| 32.657143 | 81 | 0.600175 |
aceffaa3a168fe90c347a457c5e0f589483992d5 | 3,719 | py | Python | contrib/macdeploy/custom_dsstore.py | Shawno0/GlobalSalaryCoin | 8926c8419b3089e826d99116ec71368bc2e46d6c | [
"MIT"
] | null | null | null | contrib/macdeploy/custom_dsstore.py | Shawno0/GlobalSalaryCoin | 8926c8419b3089e826d99116ec71368bc2e46d6c | [
"MIT"
] | null | null | null | contrib/macdeploy/custom_dsstore.py | Shawno0/GlobalSalaryCoin | 8926c8419b3089e826d99116ec71368bc2e46d6c | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2013-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.
import biplist
from ds_store import DSStore
from mac_alias import Alias
import sys
output_file = sys.argv[1]
package_name_ns = sys.argv[2]
ds = DSStore.open(output_file, 'w+')
ds['.']['bwsp'] = {
'ShowStatusBar': False,
'WindowBounds': '{{300, 280}, {500, 343}}',
'ContainerShowSidebar': False,
'SidebarWidth': 0,
'ShowTabView': False,
'PreviewPaneVisibility': False,
'ShowToolbar': False,
'ShowSidebar': False,
'ShowPathbar': True
}
icvp = {
'gridOffsetX': 0.0,
'textSize': 12.0,
'viewOptionsVersion': 1,
'backgroundImageAlias': b'\x00\x00\x00\x00\x02\x1e\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd1\x94\\\xb0H+\x00\x05\x00\x00\x00\x98\x0fbackground.tiff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x99\xd19\xb0\xf8\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\x00\x00\r\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b.background\x00\x00\x10\x00\x08\x00\x00\xd1\x94\\\xb0\x00\x00\x00\x11\x00\x08\x00\x00\xd19\xb0\xf8\x00\x00\x00\x01\x00\x04\x00\x00\x00\x98\x00\x0e\x00 \x00\x0f\x00b\x00a\x00c\x00k\x00g\x00r\x00o\x00u\x00n\x00d\x00.\x00t\x00i\x00f\x00f\x00\x0f\x00\x02\x00\x00\x00\x12\x00\x1c/.background/background.tiff\x00\x14\x01\x06\x00\x00\x00\x00\x01\x06\x00\x02\x00\x00\x0cMacintosh HD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xce\x97\xab\xc3H+\x00\x00\x01\x88[\x88\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02u\xab\x8d\xd1\x94\\\xb0devrddsk\xff\xff\xff\xff\x00\x00\t \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07bitcoin\x00\x00\x10\x00\x08\x00\x00\xce\x97\xab\xc3\x00\x00\x00\x11\x00\x08\x00\x00\xd1\x94\\\xb0\x00\x00\x00\x01\x00\x14\x01\x88[\x88\x00\x16\xa9\t\x00\x08\xfaR\x00\x08\xfaQ\x00\x02d\x8e\x00\x0e\x00\x02\x00\x00\x00\x0f\x00\x1a\x00\x0c\x00M\x00a\x00c\x00i\x00n\x00t\x00o\x00s\x00h\x00 \x00H\x00D\x00\x13\x00\x01/\x00\x00\x15\x00\x02\x00\x14\xff\xff\x00\x00\xff\xff\x00\x00',
'backgroundColorBlue': 1.0,
'iconSize': 96.0,
'backgroundColorGreen': 1.0,
'arrangeBy': 'none',
'showIconPreview': True,
'gridSpacing': 100.0,
'gridOffsetY': 0.0,
'showItemInfo': False,
'labelOnBottom': True,
'backgroundType': 2,
'backgroundColorRed': 1.0
}
alias = Alias.from_bytes(icvp['backgroundImageAlias'])
alias.volume.name = package_name_ns
alias.volume.posix_path = '/Volumes/' + package_name_ns
alias.volume.disk_image_alias.target.filename = package_name_ns + '.temp.dmg'
alias.volume.disk_image_alias.target.carbon_path = 'Macintosh HD:Users:\x00bitcoinuser:\x00Documents:\x00bitcoin:\x00bitcoin:\x00' + package_name_ns + '.temp.dmg'
alias.volume.disk_image_alias.target.posix_path = 'Users/bitcoinuser/Documents/bitcoin/bitcoin/' + package_name_ns + '.temp.dmg'
alias.target.carbon_path = package_name_ns + ':.background:\x00background.tiff'
icvp['backgroundImageAlias'] = biplist.Data(alias.to_bytes())
ds['.']['icvp'] = icvp
ds['.']['vSrn'] = ('long', 1)
ds['Applications']['Iloc'] = (370, 156)
ds['GlobalSalaryCoin-Qt.app']['Iloc'] = (128, 156)
ds.flush()
ds.close()
| 61.983333 | 1,817 | 0.724926 |
aceffad2d0329f22c281b0855d23901ba0388f3f | 26,034 | py | Python | example_cycles/CFM56.py | swryan/pyCycleOld | fbab35b74d0e5487abe686ae0823ff52e75afb3b | [
"Apache-2.0"
] | null | null | null | example_cycles/CFM56.py | swryan/pyCycleOld | fbab35b74d0e5487abe686ae0823ff52e75afb3b | [
"Apache-2.0"
] | null | null | null | example_cycles/CFM56.py | swryan/pyCycleOld | fbab35b74d0e5487abe686ae0823ff52e75afb3b | [
"Apache-2.0"
] | null | null | null | from __future__ import print_function
import sys
import numpy as np
from openmdao.api import ImplicitComponent, Group, IndepVarComp, BalanceComp
from openmdao.api import DirectSolver, BoundsEnforceLS, NewtonSolver, ArmijoGoldsteinLS
from pycycle.constants import AIR_MIX, AIR_FUEL_MIX
from pycycle.connect_flow import connect_flow
from pycycle.cea import species_data
from pycycle.elements.api import FlightConditions, Inlet, Compressor, Splitter, \
Combustor, Turbine, Nozzle, Shaft, Duct, Performance, BleedOut
from pycycle.viewers import print_bleed, print_burner, print_compressor, print_flow_station, \
print_mixer, print_nozzle, print_shaft, print_turbine
from pycycle.maps.CFM56_Fan_map import FanMap
from pycycle.maps.CFM56_LPC_map import LPCmap
from pycycle.maps.CFM56_HPC_map import HPCmap
from pycycle.maps.CFM56_HPT_map import HPTmap
from pycycle.maps.CFM56_LPT_map import LPTmap
class CFM56(Group):
def initialize(self):
self.options.declare('design', default=True,
desc='Switch between on-design and off-design calculation.')
self.options.declare('statics', default=True,
desc='If True, calculate static properties.')
def setup(self):
thermo_spec = species_data.janaf
design = self.options['design']
statics = self.options['statics']
self.add_subsystem('fc', FlightConditions(thermo_data=thermo_spec, elements=AIR_MIX))
self.add_subsystem('inlet', Inlet(design=design, thermo_data=thermo_spec, elements=AIR_MIX))
self.add_subsystem('fan', Compressor(map_data=FanMap, design=design, thermo_data=thermo_spec, elements=AIR_MIX,
bleed_names=[], statics=statics, map_extrap=True), promotes_inputs=[('Nmech','LP_Nmech')])
self.add_subsystem('splitter', Splitter(design=design, thermo_data=thermo_spec, elements=AIR_MIX, statics=statics))
self.add_subsystem('duct4', Duct(design=design, thermo_data=thermo_spec, elements=AIR_MIX, statics=statics))
self.add_subsystem('lpc', Compressor(map_data=LPCmap, design=design, thermo_data=thermo_spec, elements=AIR_MIX,
statics=statics, map_extrap=True),promotes_inputs=[('Nmech','LP_Nmech')])
self.add_subsystem('duct6', Duct(design=design, thermo_data=thermo_spec, elements=AIR_MIX, statics=statics))
self.add_subsystem('hpc', Compressor(map_data=HPCmap, design=design, thermo_data=thermo_spec, elements=AIR_MIX,
bleed_names=['cool1','cool2','cust'], statics=statics, map_extrap=True),promotes_inputs=[('Nmech','HP_Nmech')])
self.add_subsystem('bld3', BleedOut(design=design, statics=statics, bleed_names=['cool3','cool4']))
self.add_subsystem('burner', Combustor(design=design,thermo_data=thermo_spec,
inflow_elements=AIR_MIX,
air_fuel_elements=AIR_FUEL_MIX,
fuel_type='Jet-A(g)', statics=statics))
self.add_subsystem('hpt', Turbine(map_data=HPTmap, design=design, thermo_data=thermo_spec, elements=AIR_FUEL_MIX,
bleed_names=['cool3','cool4'], statics=statics, map_extrap=True),promotes_inputs=[('Nmech','HP_Nmech')])
self.add_subsystem('duct11', Duct(design=design, thermo_data=thermo_spec, elements=AIR_FUEL_MIX, statics=statics))
self.add_subsystem('lpt', Turbine(map_data=LPTmap, design=design, thermo_data=thermo_spec, elements=AIR_FUEL_MIX,
bleed_names=['cool1','cool2'], statics=statics, map_extrap=True),promotes_inputs=[('Nmech','LP_Nmech')])
self.add_subsystem('duct13', Duct(design=design, thermo_data=thermo_spec, elements=AIR_FUEL_MIX, statics=statics))
self.add_subsystem('core_nozz', Nozzle(nozzType='CV', lossCoef='Cv', thermo_data=thermo_spec, elements=AIR_FUEL_MIX))
self.add_subsystem('byp_bld', BleedOut(design=design, statics=statics, bleed_names=['bypBld']))
self.add_subsystem('duct15', Duct(design=design, thermo_data=thermo_spec, elements=AIR_MIX, statics=statics))
self.add_subsystem('byp_nozz', Nozzle(nozzType='CV', lossCoef='Cv', thermo_data=thermo_spec, elements=AIR_MIX))
self.add_subsystem('lp_shaft', Shaft(num_ports=3),promotes_inputs=[('Nmech','LP_Nmech')])
self.add_subsystem('hp_shaft', Shaft(num_ports=2),promotes_inputs=[('Nmech','HP_Nmech')])
self.add_subsystem('perf', Performance(num_nozzles=2, num_burners=1))
self.connect('inlet.Fl_O:tot:P', 'perf.Pt2')
self.connect('hpc.Fl_O:tot:P', 'perf.Pt3')
self.connect('burner.Wfuel', 'perf.Wfuel_0')
self.connect('inlet.F_ram', 'perf.ram_drag')
self.connect('core_nozz.Fg', 'perf.Fg_0')
self.connect('byp_nozz.Fg', 'perf.Fg_1')
self.connect('fan.trq', 'lp_shaft.trq_0')
self.connect('lpc.trq', 'lp_shaft.trq_1')
self.connect('lpt.trq', 'lp_shaft.trq_2')
self.connect('hpc.trq', 'hp_shaft.trq_0')
self.connect('hpt.trq', 'hp_shaft.trq_1')
self.connect('fc.Fl_O:stat:P', 'core_nozz.Ps_exhaust')
self.connect('fc.Fl_O:stat:P', 'byp_nozz.Ps_exhaust')
balance = self.add_subsystem('balance', BalanceComp())
if design:
balance.add_balance('W', units='lbm/s', eq_units='lbf')
self.connect('balance.W', 'inlet.Fl_I:stat:W')
self.connect('perf.Fn', 'balance.lhs:W')
balance.add_balance('FAR', eq_units='degR', lower=1e-4, val=.017)
self.connect('balance.FAR', 'burner.Fl_I:FAR')
self.connect('burner.Fl_O:tot:T', 'balance.lhs:FAR')
balance.add_balance('lpt_PR', val=1.5, lower=1.001, upper=8,
eq_units='hp', use_mult=True, mult_val=-1)
self.connect('balance.lpt_PR', 'lpt.PR')
self.connect('lp_shaft.pwr_in_real', 'balance.lhs:lpt_PR')
self.connect('lp_shaft.pwr_out_real', 'balance.rhs:lpt_PR')
balance.add_balance('hpt_PR', val=1.5, lower=1.001, upper=8,
eq_units='hp', use_mult=True, mult_val=-1)
self.connect('balance.hpt_PR', 'hpt.PR')
self.connect('hp_shaft.pwr_in_real', 'balance.lhs:hpt_PR')
self.connect('hp_shaft.pwr_out_real', 'balance.rhs:hpt_PR')
else:
balance.add_balance('FAR', val=0.017, lower=1e-4, eq_units='lbf')
self.connect('balance.FAR', 'burner.Fl_I:FAR')
self.connect('perf.Fn', 'balance.lhs:FAR')
balance.add_balance('W', units='lbm/s', lower=10., upper=1000., eq_units='inch**2')
self.connect('balance.W', 'inlet.Fl_I:stat:W')
self.connect('core_nozz.Throat:stat:area', 'balance.lhs:W')
balance.add_balance('BPR', lower=2., upper=10., eq_units='inch**2')
self.connect('balance.BPR', 'splitter.BPR')
self.connect('byp_nozz.Throat:stat:area', 'balance.lhs:BPR')
balance.add_balance('lp_Nmech', val=1.5, units='rpm', lower=500., eq_units='hp', use_mult=True, mult_val=-1)
self.connect('balance.lp_Nmech', 'LP_Nmech')
self.connect('lp_shaft.pwr_in_real', 'balance.lhs:lp_Nmech')
self.connect('lp_shaft.pwr_out_real', 'balance.rhs:lp_Nmech')
balance.add_balance('hp_Nmech', val=1.5, units='rpm', lower=500., eq_units='hp', use_mult=True, mult_val=-1)
self.connect('balance.hp_Nmech', 'HP_Nmech')
self.connect('hp_shaft.pwr_in_real', 'balance.lhs:hp_Nmech')
self.connect('hp_shaft.pwr_out_real', 'balance.rhs:hp_Nmech')
self.set_order(['balance', 'fc', 'inlet', 'fan', 'splitter', 'duct4', 'lpc', 'duct6', 'hpc', 'bld3', 'burner', 'hpt', 'duct11',
'lpt', 'duct13', 'core_nozz', 'byp_bld', 'duct15', 'byp_nozz', 'lp_shaft', 'hp_shaft', 'perf'])
connect_flow(self, 'fc.Fl_O', 'inlet.Fl_I', connect_w=False)
connect_flow(self, 'inlet.Fl_O', 'fan.Fl_I')
connect_flow(self, 'fan.Fl_O', 'splitter.Fl_I')
connect_flow(self, 'splitter.Fl_O1', 'duct4.Fl_I')
connect_flow(self, 'duct4.Fl_O', 'lpc.Fl_I')
connect_flow(self, 'lpc.Fl_O', 'duct6.Fl_I')
connect_flow(self, 'duct6.Fl_O', 'hpc.Fl_I')
connect_flow(self, 'hpc.Fl_O', 'bld3.Fl_I')
connect_flow(self, 'bld3.Fl_O', 'burner.Fl_I')
connect_flow(self, 'burner.Fl_O', 'hpt.Fl_I')
connect_flow(self, 'hpt.Fl_O', 'duct11.Fl_I')
connect_flow(self, 'duct11.Fl_O', 'lpt.Fl_I')
connect_flow(self, 'lpt.Fl_O', 'duct13.Fl_I')
connect_flow(self, 'duct13.Fl_O','core_nozz.Fl_I')
connect_flow(self, 'splitter.Fl_O2', 'byp_bld.Fl_I')
connect_flow(self, 'byp_bld.Fl_O', 'duct15.Fl_I')
connect_flow(self, 'duct15.Fl_O', 'byp_nozz.Fl_I')
connect_flow(self, 'hpc.cool1', 'lpt.cool1', connect_stat=False)
connect_flow(self, 'hpc.cool2', 'lpt.cool2', connect_stat=False)
connect_flow(self, 'bld3.cool3', 'hpt.cool3', connect_stat=False)
connect_flow(self, 'bld3.cool4', 'hpt.cool4', connect_stat=False)
newton = self.nonlinear_solver = NewtonSolver()
newton.options['atol'] = 1e-8
newton.options['rtol'] = 1e-8
newton.options['iprint'] = 2
newton.options['maxiter'] = 50
newton.options['solve_subsystems'] = True
newton.options['max_sub_solves'] = 100
# ls = newton.linesearch = BoundsEnforceLS()
ls = newton.linesearch = ArmijoGoldsteinLS()
ls.options['maxiter'] = 3
ls.options['bound_enforcement'] = 'scalar'
# ls.options['print_bound_enforce'] = True
self.linear_solver = DirectSolver(assemble_jac=True)
def viewer(prob, pt, file=sys.stdout):
"""
print a report of all the relevant cycle properties
"""
if pt == 'DESIGN':
MN = prob['DESIGN.fc.Fl_O:stat:MN']
LPT_PR = prob['DESIGN.balance.lpt_PR']
HPT_PR = prob['DESIGN.balance.hpt_PR']
FAR = prob['DESIGN.balance.FAR']
else:
MN = prob[pt+'.fc.Fl_O:stat:MN']
LPT_PR = prob[pt+'.lpt.PR']
HPT_PR = prob[pt+'.hpt.PR']
FAR = prob[pt+'.balance.FAR']
print(file=file, flush=True)
print(file=file, flush=True)
print(file=file, flush=True)
print("----------------------------------------------------------------------------", file=file, flush=True)
print(" POINT:", pt, file=file, flush=True)
print("----------------------------------------------------------------------------", file=file, flush=True)
print(" PERFORMANCE CHARACTERISTICS", file=file, flush=True)
print(" Mach Alt W Fn Fg Fram OPR TSFC BPR ", file=file, flush=True)
print(" %7.5f %7.1f %7.3f %7.1f %7.1f %7.1f %7.3f %7.5f %7.3f" %(MN, prob[pt+'.fc.alt'],prob[pt+'.inlet.Fl_O:stat:W'],prob[pt+'.perf.Fn'],prob[pt+'.perf.Fg'],prob[pt+'.inlet.F_ram'],prob[pt+'.perf.OPR'],prob[pt+'.perf.TSFC'], prob[pt+'.splitter.BPR']), file=file, flush=True)
fs_names = ['fc.Fl_O', 'inlet.Fl_O', 'fan.Fl_O', 'splitter.Fl_O1', 'splitter.Fl_O2',
'duct4.Fl_O', 'lpc.Fl_O', 'duct6.Fl_O', 'hpc.Fl_O', 'bld3.Fl_O', 'burner.Fl_O',
'hpt.Fl_O', 'duct11.Fl_O', 'lpt.Fl_O', 'duct13.Fl_O', 'core_nozz.Fl_O', 'byp_bld.Fl_O',
'duct15.Fl_O', 'byp_nozz.Fl_O']
fs_full_names = [f'{pt}.{fs}' for fs in fs_names]
print_flow_station(prob, fs_full_names, file=file)
comp_names = ['fan', 'lpc', 'hpc']
comp_full_names = [f'{pt}.{c}' for c in comp_names]
print_compressor(prob, comp_full_names, file=file)
print_burner(prob, [f'{pt}.burner'])
turb_names = ['hpt', 'lpt']
turb_full_names = [f'{pt}.{t}' for t in turb_names]
print_turbine(prob, turb_full_names, file=file)
noz_names = ['core_nozz', 'byp_nozz']
noz_full_names = [f'{pt}.{n}' for n in noz_names]
print_nozzle(prob, noz_full_names, file=file)
shaft_names = ['hp_shaft', 'lp_shaft']
shaft_full_names = [f'{pt}.{s}' for s in shaft_names]
print_shaft(prob, shaft_full_names, file=file)
bleed_names = ['hpc.cool1', 'hpc.cool2', 'bld3.cool3', 'bld3.cool4', 'hpc.cust', 'byp_bld.bypBld']
bleed_full_names = [f'{pt}.{b}' for b in bleed_names]
print_bleed(prob, bleed_full_names, file=file)
if __name__ == "__main__":
import time
from openmdao.api import Problem
from openmdao.utils.units import convert_units as cu
prob = Problem()
des_vars = prob.model.add_subsystem('des_vars', IndepVarComp(), promotes=["*"])
# FOR DESIGN
des_vars.add_output('alt', 35000., units='ft'),
des_vars.add_output('MN', 0.8),
des_vars.add_output('T4max', 2857.0, units='degR'),
des_vars.add_output('Fn_des', 5500.0, units='lbf'),
des_vars.add_output('inlet:ram_recovery', 0.9990),
des_vars.add_output('inlet:MN_out', 0.751),
des_vars.add_output('fan:PRdes', 1.685),
des_vars.add_output('fan:effDes', 0.8948),
des_vars.add_output('fan:MN_out', 0.4578)
des_vars.add_output('splitter:BPR', 5.105),
des_vars.add_output('splitter:MN_out1', 0.3104)
des_vars.add_output('splitter:MN_out2', 0.4518)
des_vars.add_output('duct4:dPqP', 0.0048),
des_vars.add_output('duct4:MN_out', 0.3121),
des_vars.add_output('lpc:PRdes', 1.935),
des_vars.add_output('lpc:effDes', 0.9243),
des_vars.add_output('lpc:MN_out', 0.3059),
des_vars.add_output('duct6:dPqP', 0.0101),
des_vars.add_output('duct6:MN_out', 0.3563),
des_vars.add_output('hpc:PRdes', 9.369),
des_vars.add_output('hpc:effDes', 0.8707),
des_vars.add_output('hpc:MN_out', 0.2442),
des_vars.add_output('bld3:MN_out', 0.3000)
des_vars.add_output('burner:dPqP', 0.0540),
des_vars.add_output('burner:MN_out', 0.1025),
des_vars.add_output('hpt:effDes', 0.8888),
des_vars.add_output('hpt:MN_out', 0.3650),
des_vars.add_output('duct11:dPqP', 0.0051),
des_vars.add_output('duct11:MN_out', 0.3063),
des_vars.add_output('lpt:effDes', 0.8996),
des_vars.add_output('lpt:MN_out', 0.4127),
des_vars.add_output('duct13:dPqP', 0.0107),
des_vars.add_output('duct13:MN_out', 0.4463),
des_vars.add_output('core_nozz:Cv', 0.9933),
des_vars.add_output('bypBld:frac_W', 0.005),
des_vars.add_output('bypBld:MN_out', 0.4489),
des_vars.add_output('duct15:dPqP', 0.0149),
des_vars.add_output('duct15:MN_out', 0.4589),
des_vars.add_output('byp_nozz:Cv', 0.9939),
des_vars.add_output('lp_shaft:Nmech', 4666.1, units='rpm'),
des_vars.add_output('hp_shaft:Nmech', 14705.7, units='rpm'),
des_vars.add_output('hp_shaft:HPX', 250.0, units='hp'),
des_vars.add_output('hpc:cool1:frac_W', 0.050708),
des_vars.add_output('hpc:cool1:frac_P', 0.5),
des_vars.add_output('hpc:cool1:frac_work', 0.5),
des_vars.add_output('hpc:cool2:frac_W', 0.020274),
des_vars.add_output('hpc:cool2:frac_P', 0.55),
des_vars.add_output('hpc:cool2:frac_work', 0.5),
des_vars.add_output('bld3:cool3:frac_W', 0.067214),
des_vars.add_output('bld3:cool4:frac_W', 0.101256),
des_vars.add_output('hpc:cust:frac_W', 0.0445),
des_vars.add_output('hpc:cust:frac_P', 0.5),
des_vars.add_output('hpc:cust:frac_work', 0.5),
des_vars.add_output('hpt:cool3:frac_P', 1.0),
des_vars.add_output('hpt:cool4:frac_P', 0.0),
des_vars.add_output('lpt:cool1:frac_P', 1.0),
des_vars.add_output('lpt:cool2:frac_P', 0.0),
# OFF DESIGN
des_vars.add_output('OD_MN', [0.8, 0.8, 0.25, 0.00001]),
des_vars.add_output('OD_alt', [35000.0, 35000.0, 0.0, 0.0], units='ft'),
des_vars.add_output('OD_Fn_target', [5500.0, 5970.0, 22590.0, 27113.0], units='lbf'), #8950.0
des_vars.add_output('OD_dTs', [0.0, 0.0, 27.0, 27.0], units='degR')
des_vars.add_output('OD_cust_fracW', [0.0445, 0.0422, 0.0177, 0.0185])
# DESIGN CASE
prob.model.add_subsystem('DESIGN', CFM56(statics=True))
prob.model.connect('alt', 'DESIGN.fc.alt')
prob.model.connect('MN', 'DESIGN.fc.MN')
prob.model.connect('Fn_des', 'DESIGN.balance.rhs:W')
prob.model.connect('T4max', 'DESIGN.balance.rhs:FAR')
prob.model.connect('inlet:ram_recovery', 'DESIGN.inlet.ram_recovery')
prob.model.connect('inlet:MN_out', 'DESIGN.inlet.MN')
prob.model.connect('fan:PRdes', 'DESIGN.fan.PR')
prob.model.connect('fan:effDes', 'DESIGN.fan.eff')
prob.model.connect('fan:MN_out', 'DESIGN.fan.MN')
prob.model.connect('splitter:BPR', 'DESIGN.splitter.BPR')
prob.model.connect('splitter:MN_out1', 'DESIGN.splitter.MN1')
prob.model.connect('splitter:MN_out2', 'DESIGN.splitter.MN2')
prob.model.connect('duct4:dPqP', 'DESIGN.duct4.dPqP')
prob.model.connect('duct4:MN_out', 'DESIGN.duct4.MN')
prob.model.connect('lpc:PRdes', 'DESIGN.lpc.PR')
prob.model.connect('lpc:effDes', 'DESIGN.lpc.eff')
prob.model.connect('lpc:MN_out', 'DESIGN.lpc.MN')
prob.model.connect('duct6:dPqP', 'DESIGN.duct6.dPqP')
prob.model.connect('duct6:MN_out', 'DESIGN.duct6.MN')
prob.model.connect('hpc:PRdes', 'DESIGN.hpc.PR')
prob.model.connect('hpc:effDes', 'DESIGN.hpc.eff')
prob.model.connect('hpc:MN_out', 'DESIGN.hpc.MN')
prob.model.connect('bld3:MN_out', 'DESIGN.bld3.MN')
prob.model.connect('burner:dPqP', 'DESIGN.burner.dPqP')
prob.model.connect('burner:MN_out', 'DESIGN.burner.MN')
prob.model.connect('hpt:effDes', 'DESIGN.hpt.eff')
prob.model.connect('hpt:MN_out', 'DESIGN.hpt.MN')
prob.model.connect('duct11:dPqP', 'DESIGN.duct11.dPqP')
prob.model.connect('duct11:MN_out', 'DESIGN.duct11.MN')
prob.model.connect('lpt:effDes', 'DESIGN.lpt.eff')
prob.model.connect('lpt:MN_out', 'DESIGN.lpt.MN')
prob.model.connect('duct13:dPqP', 'DESIGN.duct13.dPqP')
prob.model.connect('duct13:MN_out', 'DESIGN.duct13.MN')
prob.model.connect('core_nozz:Cv', 'DESIGN.core_nozz.Cv')
prob.model.connect('bypBld:MN_out', 'DESIGN.byp_bld.MN')
prob.model.connect('duct15:dPqP', 'DESIGN.duct15.dPqP')
prob.model.connect('duct15:MN_out', 'DESIGN.duct15.MN')
prob.model.connect('byp_nozz:Cv', 'DESIGN.byp_nozz.Cv')
prob.model.connect('lp_shaft:Nmech', 'DESIGN.LP_Nmech')
prob.model.connect('hp_shaft:Nmech', 'DESIGN.HP_Nmech')
prob.model.connect('hp_shaft:HPX', 'DESIGN.hp_shaft.HPX')
prob.model.connect('hpc:cool1:frac_W', 'DESIGN.hpc.cool1:frac_W')
prob.model.connect('hpc:cool1:frac_P', 'DESIGN.hpc.cool1:frac_P')
prob.model.connect('hpc:cool1:frac_work', 'DESIGN.hpc.cool1:frac_work')
prob.model.connect('hpc:cool2:frac_W', 'DESIGN.hpc.cool2:frac_W')
prob.model.connect('hpc:cool2:frac_P', 'DESIGN.hpc.cool2:frac_P')
prob.model.connect('hpc:cool2:frac_work', 'DESIGN.hpc.cool2:frac_work')
prob.model.connect('bld3:cool3:frac_W', 'DESIGN.bld3.cool3:frac_W')
prob.model.connect('bld3:cool4:frac_W', 'DESIGN.bld3.cool4:frac_W')
prob.model.connect('hpc:cust:frac_W', 'DESIGN.hpc.cust:frac_W')
prob.model.connect('hpc:cust:frac_P', 'DESIGN.hpc.cust:frac_P')
prob.model.connect('hpc:cust:frac_work', 'DESIGN.hpc.cust:frac_work')
prob.model.connect('hpt:cool3:frac_P', 'DESIGN.hpt.cool3:frac_P')
prob.model.connect('hpt:cool4:frac_P', 'DESIGN.hpt.cool4:frac_P')
prob.model.connect('lpt:cool1:frac_P', 'DESIGN.lpt.cool1:frac_P')
prob.model.connect('lpt:cool2:frac_P', 'DESIGN.lpt.cool2:frac_P')
prob.model.connect('bypBld:frac_W', 'DESIGN.byp_bld.bypBld:frac_W')
# OFF DESIGN CASES
# pts = []
pts = ['OD1','OD2','OD3','OD4']
for i_OD, pt in enumerate(pts):
ODpt = prob.model.add_subsystem(pt, CFM56(design=False))
prob.model.connect('OD_alt', pt+'.fc.alt', src_indices=i_OD)
prob.model.connect('OD_MN', pt+'.fc.MN', src_indices=i_OD)
prob.model.connect('OD_Fn_target', pt+'.balance.rhs:FAR', src_indices=i_OD)
prob.model.connect('OD_dTs', pt+'.fc.dTs', src_indices=i_OD)
prob.model.connect('OD_cust_fracW', pt+'.hpc.cust:frac_W', src_indices=i_OD)
prob.model.connect('inlet:ram_recovery', pt+'.inlet.ram_recovery')
# prob.model.connect('splitter:BPR', pt+'.splitter.BPR')
prob.model.connect('duct4:dPqP', pt+'.duct4.dPqP')
prob.model.connect('duct6:dPqP', pt+'.duct6.dPqP')
prob.model.connect('burner:dPqP', pt+'.burner.dPqP')
prob.model.connect('duct11:dPqP', pt+'.duct11.dPqP')
prob.model.connect('duct13:dPqP', pt+'.duct13.dPqP')
prob.model.connect('core_nozz:Cv', pt+'.core_nozz.Cv')
prob.model.connect('duct15:dPqP', pt+'.duct15.dPqP')
prob.model.connect('byp_nozz:Cv', pt+'.byp_nozz.Cv')
prob.model.connect('hp_shaft:HPX', pt+'.hp_shaft.HPX')
prob.model.connect('hpc:cool1:frac_W', pt+'.hpc.cool1:frac_W')
prob.model.connect('hpc:cool1:frac_P', pt+'.hpc.cool1:frac_P')
prob.model.connect('hpc:cool1:frac_work', pt+'.hpc.cool1:frac_work')
prob.model.connect('hpc:cool2:frac_W', pt+'.hpc.cool2:frac_W')
prob.model.connect('hpc:cool2:frac_P', pt+'.hpc.cool2:frac_P')
prob.model.connect('hpc:cool2:frac_work', pt+'.hpc.cool2:frac_work')
prob.model.connect('bld3:cool3:frac_W', pt+'.bld3.cool3:frac_W')
prob.model.connect('bld3:cool4:frac_W', pt+'.bld3.cool4:frac_W')
# prob.model.connect('hpc:cust:frac_W', pt+'.hpc.cust:frac_W')
prob.model.connect('hpc:cust:frac_P', pt+'.hpc.cust:frac_P')
prob.model.connect('hpc:cust:frac_work', pt+'.hpc.cust:frac_work')
prob.model.connect('hpt:cool3:frac_P', pt+'.hpt.cool3:frac_P')
prob.model.connect('hpt:cool4:frac_P', pt+'.hpt.cool4:frac_P')
prob.model.connect('lpt:cool1:frac_P', pt+'.lpt.cool1:frac_P')
prob.model.connect('lpt:cool2:frac_P', pt+'.lpt.cool2:frac_P')
prob.model.connect('bypBld:frac_W', pt+'.byp_bld.bypBld:frac_W')
prob.model.connect('DESIGN.fan.s_PR', pt+'.fan.s_PR')
prob.model.connect('DESIGN.fan.s_Wc', pt+'.fan.s_Wc')
prob.model.connect('DESIGN.fan.s_eff', pt+'.fan.s_eff')
prob.model.connect('DESIGN.fan.s_Nc', pt+'.fan.s_Nc')
prob.model.connect('DESIGN.lpc.s_PR', pt+'.lpc.s_PR')
prob.model.connect('DESIGN.lpc.s_Wc', pt+'.lpc.s_Wc')
prob.model.connect('DESIGN.lpc.s_eff', pt+'.lpc.s_eff')
prob.model.connect('DESIGN.lpc.s_Nc', pt+'.lpc.s_Nc')
prob.model.connect('DESIGN.hpc.s_PR', pt+'.hpc.s_PR')
prob.model.connect('DESIGN.hpc.s_Wc', pt+'.hpc.s_Wc')
prob.model.connect('DESIGN.hpc.s_eff', pt+'.hpc.s_eff')
prob.model.connect('DESIGN.hpc.s_Nc', pt+'.hpc.s_Nc')
prob.model.connect('DESIGN.hpt.s_PR', pt+'.hpt.s_PR')
prob.model.connect('DESIGN.hpt.s_Wp', pt+'.hpt.s_Wp')
prob.model.connect('DESIGN.hpt.s_eff', pt+'.hpt.s_eff')
prob.model.connect('DESIGN.hpt.s_Np', pt+'.hpt.s_Np')
prob.model.connect('DESIGN.lpt.s_PR', pt+'.lpt.s_PR')
prob.model.connect('DESIGN.lpt.s_Wp', pt+'.lpt.s_Wp')
prob.model.connect('DESIGN.lpt.s_eff', pt+'.lpt.s_eff')
prob.model.connect('DESIGN.lpt.s_Np', pt+'.lpt.s_Np')
prob.model.connect('DESIGN.core_nozz.Throat:stat:area',pt+'.balance.rhs:W')
prob.model.connect('DESIGN.byp_nozz.Throat:stat:area',pt+'.balance.rhs:BPR')
prob.model.connect('DESIGN.inlet.Fl_O:stat:area', pt+'.inlet.area')
prob.model.connect('DESIGN.fan.Fl_O:stat:area', pt+'.fan.area')
prob.model.connect('DESIGN.splitter.Fl_O1:stat:area', pt+'.splitter.area1')
prob.model.connect('DESIGN.splitter.Fl_O2:stat:area', pt+'.splitter.area2')
prob.model.connect('DESIGN.duct4.Fl_O:stat:area', pt+'.duct4.area')
prob.model.connect('DESIGN.lpc.Fl_O:stat:area', pt+'.lpc.area')
prob.model.connect('DESIGN.duct6.Fl_O:stat:area', pt+'.duct6.area')
prob.model.connect('DESIGN.hpc.Fl_O:stat:area', pt+'.hpc.area')
prob.model.connect('DESIGN.bld3.Fl_O:stat:area', pt+'.bld3.area')
prob.model.connect('DESIGN.burner.Fl_O:stat:area', pt+'.burner.area')
prob.model.connect('DESIGN.hpt.Fl_O:stat:area', pt+'.hpt.area')
prob.model.connect('DESIGN.duct11.Fl_O:stat:area', pt+'.duct11.area')
prob.model.connect('DESIGN.lpt.Fl_O:stat:area', pt+'.lpt.area')
prob.model.connect('DESIGN.duct13.Fl_O:stat:area', pt+'.duct13.area')
prob.model.connect('DESIGN.byp_bld.Fl_O:stat:area', pt+'.byp_bld.area')
prob.model.connect('DESIGN.duct15.Fl_O:stat:area', pt+'.duct15.area')
prob.setup(check=False)
# initial guesses
prob['DESIGN.balance.FAR'] = 0.025
prob['DESIGN.balance.W'] = 100.
prob['DESIGN.balance.lpt_PR'] = 4.0
prob['DESIGN.balance.hpt_PR'] = 3.0
prob['DESIGN.fc.balance.Pt'] = 5.2
prob['DESIGN.fc.balance.Tt'] = 440.0
W_guesses = [300, 300, 700, 700]
for i, pt in enumerate(pts):
# ADP and TOC guesses
prob[pt+'.balance.FAR'] = 0.02467
prob[pt+'.balance.W'] = W_guesses[i]
prob[pt+'.balance.BPR'] = 5.105
prob[pt+'.balance.lp_Nmech'] = 5000 # 4666.1
prob[pt+'.balance.hp_Nmech'] = 15000 # 14705.7
# prob[pt+'.fc.balance.Pt'] = 5.2
# prob[pt+'.fc.balance.Tt'] = 440.0
prob[pt+'.hpt.PR'] = 3.
prob[pt+'.lpt.PR'] = 4.
prob[pt+'.fan.map.RlineMap'] = 2.0
prob[pt+'.lpc.map.RlineMap'] = 2.0
prob[pt+'.hpc.map.RlineMap'] = 2.0
st = time.time()
prob.set_solver_print(level=-1)
prob.set_solver_print(level=2, depth=1)
prob.run_model()
prob.model.DESIGN.list_outputs(residuals=True, residuals_tol=1e-2)
for pt in ['DESIGN']+pts:
viewer(prob, pt)
print()
print("time", time.time() - st)
| 51.860558 | 282 | 0.641661 |
aceffad5e4cea43f4ca4d6930bf519477686fb55 | 2,459 | py | Python | laminar/configurations/hooks.py | rchui/laminar | 63bcc813484bd8510bcfa93456e46118b7093b5e | [
"MIT"
] | null | null | null | laminar/configurations/hooks.py | rchui/laminar | 63bcc813484bd8510bcfa93456e46118b7093b5e | [
"MIT"
] | 1 | 2022-02-04T00:50:26.000Z | 2022-02-04T00:50:26.000Z | laminar/configurations/hooks.py | rchui/laminar | 83e03aa97a11943218fc792b0f33017200cb10be | [
"MIT"
] | null | null | null | """Configurations for laminar hooks."""
from contextlib import ExitStack, contextmanager
from enum import Enum
from typing import TYPE_CHECKING, Any, Callable, Generator, Optional, TypeVar
from laminar.types import annotations
if TYPE_CHECKING:
from laminar import Layer
else:
Layer = "Layer"
T = TypeVar("T", bound=Any)
ATTRIBUTE = "annotation"
class Annotation(str, Enum):
execution = "hook::execution"
retry = "hook::retry"
submission = "hook::submission"
@staticmethod
def annotate(hook: T, annotation: "Annotation") -> T:
setattr(hook, ATTRIBUTE, annotation)
return hook
@staticmethod
def get(hook: Callable[..., Generator[None, None, None]]) -> Optional[str]:
return getattr(hook, ATTRIBUTE, None)
def execution(hook: T) -> T:
"""Configure an execution hook.
Usage::
from laminar.configurations import hooks
@hooks.execution
def configure() -> Generator[None, None, None]:
...
"""
return Annotation.annotate(hook, Annotation.execution)
def retry(hook: T) -> T:
"""Configure a retry hook.
Usage::
from laminar.configurations import hooks
@hooks.retry
def configure() -> Generator[None, None, None]:
...
"""
return Annotation.annotate(hook, Annotation.retry)
def submission(hook: T) -> T:
"""Configure a submission hook.
Usage::
from laminar.configurations import hooks
@hooks.submission
def configure() -> Generator[None, None, None]:
...
"""
return Annotation.annotate(hook, Annotation.submission)
def context(*, layer: Layer, annotation: Annotation) -> ExitStack:
"""Get a context manager for all hooks of the annotated type.
Args:
layer: Layer the hooks are for.
annotation: Annotation to get hooks for.
Returns:
A context manager with all annotated hooks activated.
"""
stack = ExitStack()
for hook in list(vars(type(layer.flow)).values()) + list(vars(type(layer)).values()):
if Annotation.get(hook) == annotation:
# Gather any layer dependencies the hook may have
parameters = annotations(layer.flow, hook)
# Create a context for each hook and register it with the exit stack
hook_context = contextmanager(hook)
stack.enter_context(hook_context(layer, *parameters))
return stack
| 24.346535 | 89 | 0.642131 |
aceffb1998ff9a6c4cfacc3aa055c55cf006a3a9 | 1,702 | py | Python | old-server/compute/test/test_all.py | Aakriti28/tapestry-server | fab99091bc61dec4855604d491bb2f7cd14fd517 | [
"MIT"
] | null | null | null | old-server/compute/test/test_all.py | Aakriti28/tapestry-server | fab99091bc61dec4855604d491bb2f7cd14fd517 | [
"MIT"
] | null | null | null | old-server/compute/test/test_all.py | Aakriti28/tapestry-server | fab99091bc61dec4855604d491bb2f7cd14fd517 | [
"MIT"
] | null | null | null | # vim: tabstop=2 expandtab shiftwidth=2 softtabstop=8
import sys
sys.path.append(".")
from core.get_test_results import at_deployment, mat_codenames
from core.cs_expts import run_many_parallel_expts_internal, do_many_expts
from core.matrices import MDict, validate_kirkman
def test_get_test_results():
at_deployment()
def test_kirkman_matrices():
validate_kirkman()
def test_all_matrices_and_algos():
algos = []
algos.extend(['COMP'])
algos.append('precise_SBL_COMP')
algos.append('precise_SBL_combined_COMP_SBL')
algos.append('precise_SBL_combined_COMP_NNOMP_random_cv')
algos.append('SBL_clustered')
algos.append('combined_COMP_SBL_clustered')
algos.append('NNOMP')
algos.append('combined_COMP_NNOMP')
algos.append('NNOMP_random_cv')
algos.extend(['combined_COMP_NNOMP_random_cv'])
algos.append('SBL')
algos.append('combined_COMP_SBL')
algos.append('l1ls')
algos.append('combined_COMP_l1ls')
#algos.append('l1ls_cv')
#algos.append('combined_COMP_l1ls_cv')
# List of all deployed matrices past and present is in mat_codenames
for mlabel in mat_codenames:
print("Running algos for matrix ", mlabel)
M = MDict[mlabel]
n = M.shape[1]
t = M.shape[0]
num_expts=1
add_noise = True
d_range = list(range(0,11))
#d_range = [0]
n_jobs = 1 #len(d_range)
run_many_parallel_expts_internal(num_expts, n, t, add_noise, M, algos,
d_range, n_jobs, xslist=[None for d in d_range], mlabel=mlabel)
#for d in d_range:
# do_many_expts(n, d, t, num_expts=num_expts, M=M, add_noise=add_noise, algo=algos)
if __name__ == '__main__':
test_kirkman_matrices()
test_get_test_results()
test_all_matrices_and_algos()
| 31.518519 | 88 | 0.742068 |
aceffb97a5ea783ea1c5a376f97c81ecb78ca4d4 | 124,963 | py | Python | kinemparse/models/models_backup.py | jd-jones/kinemparse | 279a9989981aa2a0eef1e46e5d02833f51ae352d | [
"MIT"
] | null | null | null | kinemparse/models/models_backup.py | jd-jones/kinemparse | 279a9989981aa2a0eef1e46e5d02833f51ae352d | [
"MIT"
] | null | null | null | kinemparse/models/models_backup.py | jd-jones/kinemparse | 279a9989981aa2a0eef1e46e5d02833f51ae352d | [
"MIT"
] | null | null | null | import sys
import functools
import itertools
import os
import logging
import warnings
import collections
import numpy as np
import scipy
from matplotlib import pyplot as plt
from sklearn.mixture import GaussianMixture
from sklearn.cluster import KMeans, MiniBatchKMeans
from sklearn import preprocessing
from skimage import img_as_float
# from LCTM import models as lctm_models
from blocks.core import utils, geometry, labels
from blocks.core.mixins import LoggerMixin
from blocks.estimation import imageprocessing, render
this_module = sys.modules[__name__]
logger = logging.getLogger(__name__)
# -=( PROBABILITY MODEL HELPER FUNCTIONS )=------------------------------------
def makeHistogram(
num_classes, samples, normalize=False, ignore_empty=True, backoff_counts=0):
""" Make a histogram representing the empirical distribution of the input.
Parameters
----------
num_classes : int
The length of the histogram.
samples : numpy array of int, shape (num_samples,)
Array of outcome indices.
normalize : bool, optional
If True, the histogram is normalized to it sums to one (ie this
method returns a probability distribution). If False, this method
returns the class counts. Default is False.
ignore_empty : bool, optional
Can be useful when ``normalize == False`` and ``backoff_counts == 0``.
If True, this function doesn't try to normalize the histogram of an
empty input. Trying to normalize that histogram would lead to a
divide-by-zero error and an output of all ``NaN``.
backoff_counts : int or float, optional
This amount is added to all bins in the histogram before normalization
(if `normalize` is True). Non-integer backoff counts are allowed.
Returns
-------
class_histogram : numpy array of float, shape (num_clusters,)
Histogram representing the input data. If `normalize` is True, this is
a probability distribution (possibly smoothed via backoff). If not,
this is the number of times each cluster was encountered in the input,
plus any additional backoff counts.
"""
hist = np.zeros(num_classes)
# Convert input to array, to be safe
samples = np.array(samples)
# Sometimes the input can be empty. We would rather return a vector of
# zeros than trying to normalize and get NaN.
if ignore_empty and not np.any(samples):
return hist
# Count occurrences of each class in the histogram
for index in range(num_classes):
class_count = np.sum(samples == index)
hist[index] = class_count
# Add in the backoff counts
hist += backoff_counts
if normalize:
hist /= hist.sum()
return hist
def assignToModes(probs, mode_subset=None, log_domain=False):
""" Hard-assign distributions to their modes.
Parameters
----------
probs : numpy array of float, shape (num_samples, num_outcomes)
A distribution over possible outcomes for a sample of data. This is
usually the probability score of some latent class.
mode_subset : iterable(int), optional
If a value is passed for this argument, distributions are only hard-assigned
if their modes are in this set. Otherwise, this function returns the
input distribution.
log_domain : bool, optional
If True, the input is treated as log-probabilities. Default is False.
Returns
-------
assigned_probs : numpy array of float, shape (num_samples, num_outcomes)
A copy of the input with new distributions along the rows. Each row is
a delta distribution with probability 1 at the mode of the corresponding
row of the input.
"""
if log_domain:
unit = 0
zero = -np.inf
else:
unit = 1
zero = 0
modes = probs.argmax(axis=1)
assigned_probs = np.full(probs.shape, zero)
assigned_probs[range(assigned_probs.shape[0]), modes] = unit
if mode_subset is not None:
mode_in_subset = utils.arrayMatchesAny(modes, mode_subset)
assigned_probs[~mode_in_subset, :] = probs[~mode_in_subset, :]
return assigned_probs
def gaussianSample(mean=0, std=1):
return mean + float(np.random.randn(1)) * std
def viterbiForward(self, unary_scores, pairwise_scores, minimize=False):
""" Forward pass of Viterbi search.
Parameters
----------
unary_scores : iterable( np.array of float, shape (num_states_t,) )
pairwise_scores : iterable( np.array of float, shape (num_states_t, num_states_tprev) )
minimize : bool, optional
If True, Viterbi minimizes the score instead of maximizing.
Returns
-------
final_scores : np.array of float, shape (num_states_final,)
best_state_idxs : iterable( np.array of int, shape (num_states_t,) )
"""
if minimize:
unary_scores = -unary_scores
pairwise_scores = -pairwise_scores
# Initialize scores with zero cost
best_state_idxs = []
prev_max_scores = 0
# Forward pass (max-sum)
scores = zip(unary_scores, pairwise_scores)
for t, scores_t in enumerate(scores):
def totalScore(unary_score, pairwise_scores):
return prev_max_scores + pairwise_scores + unary_score
# Compute scores for each of the current states
total_scores = utils.batchProcess(totalScore, zip(*scores_t))
# For each of the current states, find the best previous state
best_state_idxs.append(utils.batchProcess(np.argmax, total_scores))
# Save the total score so far for each of the current states
prev_max_scores = utils.batchProcess(np.max, total_scores)
final_scores = prev_max_scores
return final_scores, best_state_idxs
def viterbiBackward(final_scores, best_state_idxs):
""" Viterbi backward pass (backtrace).
Parameters
----------
final_scores :
best_state_idxs :
Returns
-------
pred_idxs :
"""
# Find the best final state
pred_idxs = [final_scores.argmax()]
# Trace back the best path from the final state
for best_idxs in reversed(best_state_idxs):
prev_best_idx = pred_idxs[-1]
pred_idxs.append(best_idxs[prev_best_idx])
# Reverse the output because we constructed it right-to-left
pred_idxs = reversed(pred_idxs)
return pred_idxs
def sparsifyApprox(probs, err_thresh):
""" Sparsify a probability vector. """
# FIXME
# sorted_indices = None
return probs
def sparsifyThresh(log_vec, log_thresh):
""" Threshold-based beam pruning. """
# num_elem = len(log_vec)
# non_inf_entries = log_vec[~np.isinf(log_vec)]
# Prune state space using beam search
# Keep in mind that G is in the range [-inf, 0]
dynamic_thresh = log_vec.max() + log_thresh
in_beam_support = log_vec >= dynamic_thresh
return in_beam_support
def sparsifyBest(vec, K):
num_elem = len(vec)
k_best_indices = np.argpartition(vec, -K)[-K:]
in_beam_support = np.zeros(num_elem, dtype=bool)
in_beam_support[k_best_indices] = True
return in_beam_support
def estimateGaussianParams(X, cov_structure=None):
""" Estimate the parameters of a normal distribution, ignoring NaN values.
Parameters
----------
X : numpy array of float, shape (num_samples, num_dims)
cov_structure : {'diag'}, optional
Returns
-------
mean : numpy array of float, shape (num_dims,)
cov : numpy array of float, shape (num_dims,)
Raises
------
ValueError
When the return values contain NaN entries
"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "Mean of empty slice")
mean = np.nanmean(X, axis=0)
if cov_structure == 'diag':
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "Degrees of freedom")
cov = np.nanstd(X, axis=0) ** 2
if np.isnan(mean).any():
err_str = f"NaN-valued entries in mean vector: {mean}"
logger.warning(err_str)
# mean[np.isnan(mean)] = 0
if np.isnan(cov).any():
err_str = f"NaN-valued entries in cov vector: {cov}"
logger.warning(err_str)
# cov[np.isnan(cov)] = 0
return mean, cov
def gaussianScore(x, mean, cov):
standardized = (x - mean) / cov
score = np.sum(standardized ** 2, axis=1)
return score
def computeErrorCovariance(
model_error_seqs, true_state_idx_seqs, is_log_likelihood=False,
max_error_thresh=2e4):
"""
Compute the mean model error.
Parameters
----------
model_error_seqs : iterable( numpy array of float, shape (num_samples, num_states) )
true_state_idx_seqs : iterable( numpy array of int, shape (num_samples) )
is_log_likelihood : bool, optional
If True, each entry in `model_error_seqs` is actually the *negative*
model error. This is useful if you have Gaussian log-likelihoods.
Default is False.
max_error_thresh : float, optional
Model errors above this value are considered outliers and ignored.
Default is 20,000.
Returns
-------
error_covariance : float
"""
def computeErrorCovarianceSeq(
error_seq, true_state_idx_seq, max_error_thresh=None):
"""
Parameters
----------
error_seq : numpy array of float, shape (num_states, num_samples)
true_state_idx_seq : numpy array of int, shape (num_samples,)
max_error_thresh : float
Returns
-------
numerator : float
denominator : float
"""
true_error_seq = error_seq[true_state_idx_seq, range(error_seq.shape[1])]
is_finite = np.isfinite(true_error_seq)
is_below_max_thresh = np.abs(true_error_seq) <= max_error_thresh
is_inlier = np.logical_and(is_finite, is_below_max_thresh)
true_error_seq = true_error_seq[is_inlier]
numerator = true_error_seq.sum()
denominator = true_error_seq.shape[0]
return numerator, denominator
sum_errors, num_items = utils.batchProcess(
computeErrorCovarianceSeq,
model_error_seqs, true_state_idx_seqs,
static_kwargs={'max_error_thresh': max_error_thresh},
unzip=True
)
error_covariance = sum(sum_errors) / sum(num_items)
if is_log_likelihood:
error_covariance *= -1
return error_covariance
# -=( PROBABILITY MODEL MIXINS )=----------------------------------------------
class ExponentialDist(object):
def __init__(self):
self.beta = None
self.log_beta = None
def fit(self, x):
self.beta = x.mean()
self.log_beta = np.log(self.beta)
def logl(self, x):
return np.sum(-self.log_beta - x / self.beta)
def likelihood(self, x):
return np.exp(self.logl(x))
class FrameScorer(object):
""" Mixture model for scoring video frames.
This model is meant to extend a base mixture model like k-means or GMM
using multiple inheritance (see `models.KMeansFrameScorer` for an example).
This model assumes there are multiple high-level classes with different
distributions over the same set of low-level classes. Concretely, it is used
to distinguish between hand and blocks pixels in a distantly-supervised way.
In this application, the base mixture model first segments the color space
into a set of `k` distinct regions. Then, the 'hands' and 'blocks' classes
each have their own prior distribution over the same `k` regions in color
space.
"""
def __init__(
self,
n_clusters=32, sat_thresh=0.1, ignore_low_sat=True,
one_indexed=False, **super_kwargs):
"""
Parameters
----------
n_clusters : int, optional
Number of shared clusters (i.e., segments in color space).
Default is 32.
sat_thresh : float, optional
Minimum saturation threshold. If the average saturation of a
color-space segment is below this value, that segment is assigned
to a special low-saturation (background) class. Default is 0.2.
ignore_low_sat : bool, optional
If True, this model discards clusters with mean saturation below
`sat_thresh` in ``self.fit`` and ``self.is_bad_cluster``.
one_indexed : bool, optional
If True, the color-space segments are one-indexed. Default is False.
**super_kwargs : optional
Any extra keyword arguments get passed to ``super().__init()__``.
"""
if n_clusters % 2:
err_str = 'n_clusters must be an even number!'
raise ValueError(err_str)
self.class_histograms = None
self.n_clusters = n_clusters
self.one_indexed = one_indexed
self.sat_thresh = sat_thresh
self.ignore_low_sat = ignore_low_sat
super().__init__(n_clusters=n_clusters, **super_kwargs)
def fit(self, X, Y, backoff_counts=0):
""" Fit this model to a collection of (data, label) pairs.
This model fits itself in two stages:
1. (Unsupervised) Segment the colorspace by fitting a mixture model to `X`.
2. (Supervised) For each class in `Y`, fit a categorical distribution
:math:`P(segment | class)`.
Parameters
----------
X : numpy array of float, shape (num_pixels, 3) )
Each row is a pixel from an image in the training dataset,
represented in the HSV colorspace.
Y : iterable(int)
Category labels in the training dataset. The i-th element in Y is
the label for the i-th element in X. If a pixel came from the child
dataset its label is 0, and if it came from the controlled dataset
its labels is 1.
backoff_counts : int or float, optional
Each class in `Y` has its own distribution over the colorspace
segments. Passing a nonzero value for this argument allows you to
smooth each of those distributions by adding that amount to all bins
in the histogram before normalizing. Non-integer backoff counts are
allowed.
"""
# Quantize color space into clusters
super().fit(X)
# Identify low-saturation clusters. These probably belong to the
# background, which is white.
cluster_center_sats = self.cluster_centers_[:,1]
self.is_low_sat_cluster = cluster_center_sats < self.sat_thresh
self.low_sat_clusters = self.is_low_sat_cluster.nonzero()[0]
# Set class attributes
Y = Y.astype(int)
self.class_indices = np.unique(Y)
self.num_classes = len(self.class_indices)
if self.num_classes != 2:
err_str = (
'FrameScorer only supports 2 classes! '
f'({self.num_classes} classes were passed)'
)
raise ValueError(err_str)
# Fit class histograms---ie, each class's prior distribution over the
# color space clusters.
self.class_histograms = np.zeros((self.n_clusters, self.num_classes))
for class_index in self.class_indices:
in_class = Y == class_index
class_samples = X[in_class, :]
sample_clusters = self.predict(class_samples)
if self.ignore_low_sat:
if self.one_indexed:
is_low_sat = utils.arrayMatchesAny(sample_clusters - 1, self.low_sat_clusters)
else:
is_low_sat = utils.arrayMatchesAny(sample_clusters, self.low_sat_clusters)
sample_clusters = sample_clusters[~is_low_sat]
class_histogram = self.constructHist(
sample_clusters, normalize=True, backoff_counts=backoff_counts
)
self.class_histograms[:, class_index] = class_histogram
# Infer cluster labels. Each cluster is assigned to the class with
# highest prior probability.
noise = self.class_histograms[:, 0]
clean = self.class_histograms[:, 1]
diff_hist = noise - clean
self.is_noise_cluster = np.zeros(self.n_clusters, dtype=bool)
self.is_noise_cluster[diff_hist > 0] = 1
# Compute a signal-to-noise ratio for each class
self.class_snrs = []
for class_index in self.class_indices:
class_histogram = self.class_histograms[:, class_index]
class_snr = self.computeClassSnr(class_histogram)
self.class_snrs.append(class_snr)
# Set hsv and rgb means for convenience
self.hsv_means = self.cluster_centers_
hsv_mean_img = self.hsv_means.reshape(2, self.n_clusters // 2, 3)
rgb_mean_img = imageprocessing.color.hsv2rgb(hsv_mean_img)
self.rgb_means = rgb_mean_img.reshape(self.n_clusters, 3)
def pixelwiseSnr(self, sample, log_domain=False, hard_assign_clusters=False):
""" Compute a signal-to-noise ratio (SNR) for each element in the input.
This SNR is really a likelihood ratio. If :math:`C_s` is the set of
signal classes and :math:`C_n` is the set of noise classes,
..math:
SNR(x) = \frac{
\sum_{c \in C_s} P(x | c)
}{
\sum_{c' \in C_n} P(x | c')
}
Parameters
----------
sample : numpy array of float, shape (num_pixels, 3) )
Each row is a pixel from an image in the training dataset,
represented in the HSV colorspace.
log_domain : bool, optional
If True, :math:`\log(SNR)` is returned instead of the actual SNR.
Default is False.
hard_assign_clusters : bool, optional
If True, each pixel is hard-assigned to its nearest cluster instead
of marginalizing over cluster assignments. This means the pixel
likelihood :math:`P(x | c)` is really class-conditional prior
:math:`P(cluster | c)`.
Returns
-------
snr : numpy array of float, shape (num_samples,)
The sample's elementwise signal-to-noise ratio. If `log_domain` is
True, the log of this value is returned.
"""
if not sample.any():
return np.array([])
signal_class = 1
noise_class = 0
log_probs = self.logLikelihood(
(noise_class, signal_class), sample,
hard_assign_clusters=hard_assign_clusters
)
with warnings.catch_warnings():
# If a pixel has probability zero under both classes, log_snr
# tries to do infinity - infinity (= NaN) and throws a warning
warnings.filterwarnings("ignore", "invalid value encountered")
log_snr = np.diff(log_probs).squeeze()
if log_domain:
return log_snr
return np.exp(log_snr)
def averageSnr(self, sample, **snr_kwargs):
""" Compute the average signal-to-noise ratio of the input.
For documentation on the type of SNR used, see ``self.pixelwiseSnr``.
This method ignores any pixels whose SNR is NaN, which can happen if
they have zero probability under both models.
Parameters
----------
sample : numpy array of float, shape (num_pixels, 3) )
Each row is a pixel from an image in the training dataset,
represented in the HSV colorspace.
**snr_kwargs : optional
Any extra keyword arguments get passed to ``self.pixelwiseSnr``.
Returns
-------
avg_snr : float
The average pixelwise SNR, ignoring NaN values.
"""
px_snrs = self.pixelwiseSnr(sample, **snr_kwargs)
with warnings.catch_warnings():
# It's ok if the input is empty; don't display the warning
warnings.filterwarnings("ignore", "Mean of empty slice")
avg_snr = np.nanmean(px_snrs)
return avg_snr
def clusterPrior(self, class_index):
""" Return a class's prior distribution over color-space segments.
Parameters
----------
class_index : int or iterable(int)
Returns
-------
cluster_prior : numpt array of float, shape (num_clusters, len(class_index))
"""
return self.class_histograms[:, class_index]
def quantize(self, X, colorspace='rgb'):
""" Quantize the input pixels.
Parameters
----------
X : numpy array of float, shape (num_pixels, 3)
Each row is a pixel from an image in the training dataset,
represented in the HSV colorspace.
colorspace : {'rgb', 'hsv'}, optional
Colorspace representation of the return value. Default is ``'rgb'``.
Returns
-------
quantized : numpy array of float, shape (num_pixels, 3)
The i-th row is this this model's closest match to the i-th row of
the input.
"""
if not X.any():
return np.zeros(X.shape, dtype=int)
clusters = super().predict(X)
if colorspace == 'rgb':
quantized = self.rgb_means[clusters, :]
elif colorspace == 'hsv':
quantized = self.hsv_means[clusters, :]
else:
err_str = (
f"Received bad argument colorspace={colorspace} "
"(must be one of {'rgb', 'hsv'})"
)
raise ValueError(err_str)
return quantized
def predict(self, X):
""" Map each pixel in the given input to its closest colorspace segment.
Parameters
----------
X : numpy array of float, shape (num_pixels, 3)
Each row is a pixel from an image in the training dataset,
represented in the HSV colorspace.
Returns
-------
predicted : numpy array of int, shape (num_pixels,)
The i-th element is this model's best guess about the category
label of the i-th row in `X`.
"""
if not X.any():
return np.zeros(X.shape, dtype=int)
predicted = super().predict(X)
if self.one_indexed:
predicted += 1
return predicted
def predictClassFromCluster(self):
""" Map each colorspace segment to the higher-level class it belongs to.
Returns
-------
mapping : numpy array of int, shape (num_clusters,)
Each entry in this array contains the higher-level class of the
corresponding segment in colorspace. Classes are enumerated as
follows:
0 -- background
1 -- skin
2 -- low-saturation (specular or white background)
3 -- blocks
"""
class_idxs = {
'background': 0,
'skin': 1,
'losat': 2,
'blocks': 3
}
mapping = np.zeros_like(self.is_low_sat_cluster, dtype=int)
mapping[self.is_low_sat_cluster] = class_idxs['losat']
mapping[self.is_noise_cluster] = class_idxs['skin']
is_signal_cluster = ~self.is_low_sat_cluster * ~self.is_noise_cluster
mapping[is_signal_cluster] = class_idxs['blocks']
return mapping
def predictClass(self, X):
""" Predict the class of each pixel in the given input.
Parameters
----------
X : numpy array of float, shape (num_pixels, 3)
Each row is a pixel from an image in the training dataset,
represented in the HSV colorspace.
Returns
-------
class_preds : numpy.array of int, shape (img_height, img_width)
Each pixel contains its class label. Classes are enumerated as
follows:
0 -- background
1 -- skin
2 -- low-saturation (specular or white background)
3 -- blocks
"""
if not X.any():
return np.zeros(X.shape, dtype=int)
# First, assign each pixel to the closest segment
cluster_preds = super().predict(X)
# Then, assign to the best class based on the segment prediction
cluster_to_class_map = self.predictClassFromCluster()
class_preds = cluster_to_class_map[cluster_preds]
return class_preds
def logLikelihood(self, class_index, sample, hard_assign_clusters=None):
""" Return the log probability that a sample belongs to a particular class.
..math:
P(sample | class) = \sum_{cluster} P( sample | cluster ) P(cluster | class)
Parameters
----------
class_index : int or iterable(int)
Class or classes for which the log likelihood will be computed. The
input can be a single integer or a collection of integers.
sample : numpy array of float, shape (num_pixels, 3) )
Each row is a pixel from an image in the training dataset,
represented in the HSV colorspace.
hard_assign_clusters : {'all', 'losat'}, optional
If ``'all'``, each pixel is hard-assigned to its nearest cluster
instead of marginalizing over cluster assignments. This means the
pixel likelihood :math:`P(x | c)` is really class-conditional prior
:math:`P(cluster | c)`. If ``'losat'``, pixels are only hard-assigned
if their nearest cluster is in ``self.low_sat_clusters`` (ie their
mean saturation is below a set threshold).
Returns
-------
class_logprobs : numpy array of float, shape (num_samples, num_classes)
The i-th column of `class_logprobs` is the probability that `sample`
belongs to the class in ``class_index[i]``.
"""
arg_set = ('all', 'losat')
if hard_assign_clusters is not None and hard_assign_clusters not in arg_set:
err_str = (
f"Keyword argument hard_assign_clusters={hard_assign_clusters} "
f"not recognized---must be one of {arg_set}"
)
raise ValueError(err_str)
if type(class_index) is int:
class_index = (class_index,)
# We can compute probs more efficiently if all clusters are hard-assigned
if hard_assign_clusters == 'all':
cluster_assignments = super().predict(sample)
with warnings.catch_warnings():
# If there are any structural zeros in the cluster prior, log
# will automatically throw a warning we don't want to see
warnings.filterwarnings("ignore", "divide by zero")
cluster_logprobs = np.log(self.clusterPrior(class_index))
class_logprobs = cluster_logprobs[cluster_assignments, :]
return class_logprobs
cluster_logprobs = self.clusterLogProbs(sample)
if hard_assign_clusters == 'losat':
cluster_logprobs = assignToModes(
cluster_logprobs, mode_subset=self.low_sat_clusters,
log_domain=True
)
class_logprobs = tuple(
scipy.special.logsumexp(cluster_logprobs, axis=1, b=self.clusterPrior(i))
for i in class_index
)
return np.column_stack(class_logprobs)
def clusterScores(self, sample):
""" Computer the parent model's score for each item in the input.
Parameters
----------
sample : numpy array of float, shape (num_pixels, 3) )
Each row is a pixel from an image in the training dataset,
represented in the HSV colorspace.
Returns
-------
cluster_scores :
"""
return super().transform(sample)
def clusterProbsUnnormalized(self, sample):
return np.exp(-self.clusterScores(sample))
@property
def cluster_normalizer(self):
return (2 * np.pi) ** 0.5
@property
def cluster_log_normalizer(self):
return 0.5 * np.log(2 * np.pi)
def clusterLogProbs(self, sample):
return -self.clusterScores(sample) - self.cluster_log_normalizer
def clusterProbs(self, sample):
"""
Parameters
----------
sample :
Returns
-------
cluster_probs :
"""
return self.clusterProbsUnnormalized(sample) / self.cluster_normalizer
@property
def is_bad_cluster(self):
ret_val = self.is_noise_cluster
if self.ignore_low_sat:
ret_val = np.logical_or(ret_val, self.is_low_sat_cluster)
return ret_val
def constructHist(self, pixel_labels, **hist_kwargs):
""" Make a histogram representing the empirical distribution of the input.
Parameters
----------
pixel_labels : numpy array of int, shape (num_samples,)
Array of indices identifying the closest segments in colorspace for
a set of pixels.
**hist_kwargs : optional
Any extra keyword arguments are passed to `models.makeHistogram`.
Returns
-------
class_histogram : numpy array of float, shape (num_clusters,)
Cluster histogram. If `normalize` is True, this is a distribution
over clusters. If not, this is the number of times each cluster
was encountered in the input.
"""
if self.one_indexed:
# FIXME: This could be modifying the argument in-place
pixel_labels -= 1
class_histogram = makeHistogram(self.n_clusters, pixel_labels, **hist_kwargs)
return class_histogram
def computeClassSnr(self, class_histogram):
""" Compute a signal-to-noise ratio (SNR) for a particular class.
This SNR is really a probability ratio. If :math:`C_s` is the set of
colorspace clusters assigned to the signal class and :math:`C_n` is the
set of colorspace clusters assigned to the noise class,
..math:
SNR = \frac{
\sum_{c \in C_s} P(c)
}{
\sum_{c' \in C_n} P(c')
}
So this SNR compares the proportion of this class's probability mass
that is distributed among "signal" classes vs. "noise" classes.
Parameters
----------
class_histogram : numpy array of float, shape (num_clusters,)
A class's prior distribution over colorspace segments, ie
:math:`P(cluster | class)`.
Returns
-------
class_snr : float
The signal-to-noise ratio of this class.
"""
num_signal_samples = class_histogram[~self.is_bad_cluster].sum()
num_noise_samples = class_histogram[self.is_bad_cluster].sum()
class_snr = num_signal_samples / num_noise_samples
return class_snr
def predictSeq(self, pixel_seq):
pixel_label_seq = utils.iterate(self.predict, pixel_seq, obj=tuple)
return pixel_label_seq
def constructHistSeq(self, pixel_seq):
hist_tup = utils.iterate(self.constructHist, pixel_seq, obj=tuple)
if not hist_tup:
return np.array([])
return np.row_stack(hist_tup)
def computeClassSnrSeq(self, pixel_seq):
hist_arr = self.constructHistSeq(pixel_seq)
snr_arr = np.array([self.computeClassSnr(hist) for hist in hist_arr])
return snr_arr
def bestFrame(self, pixel_seq):
snr_arr = self.computeClassSnrSeq(pixel_seq)
best_idx = snr_arr.argmax()
return best_idx
class EmpiricalLatentVariables(object):
""" Variable and potential function names follow Murphy """
def __init__(self):
self.states = None
self.state_index_map = None
def getStateIndex(self, state):
""" []
Parameters
----------
state : integer-valued symmetric numpy array
Returns
-------
index : int
Label index of the provided argument
"""
state_str = ''.join([str(elem) for elem in state.astype(int)])
index = self.state_index_map.get(state_str, None)
if index is None:
index = len(self.states)
self.state_index_map[state_str] = index
self.states.append(state)
return index
def getState(self, index):
return self.states[index]
def toFlattenedLabelIndexArray(self, label_seqs):
labels = [self.getStateIndex(l) for ls in label_seqs for l in ls]
return np.array(labels)
def toFlattenedLabelArray(self, label_seqs):
raise NotImplementedError
def toLabelIndexArray(self, label_seq):
labels = [self.getStateIndex(l) for l in label_seq]
return np.array(labels)
def toLabelIndexArrays(self, label_seqs):
return utils.iterate(self.toLabelIndexArray, label_seqs)
@property
def num_states(self):
return len(self.states)
@property
def state_indices(self):
return tuple(range(self.num_states))
@property
def num_vertex_vals(self):
return 1
@property
def num_vertices(self):
return len(self.states)
def fit(self, state_seqs, *feat_seqs, model_segments=False, memory_len=1):
""" Identify the support of the input's empirical distribution.
Parameters
----------
state_seqs : iterable( iterable( object ) )
Each element is a sequence of 'state' objects. These objects can be
almost anything---the only requirement is that they must implement
``__eq__()``.
*feat_seqs : iterable(numpy array of float, shape (num_samples, num_features))
Ignored---Exists for API compatibility.
memory_len : int, optional
The length of n-gram samples to record.
For example:
If 1, this function records all states encountered in the input.
If 2, it records all state pairs encountered.
Don't try anything more than two though, because it isn't
implemented.
"""
self.states = []
self.state_index_map = {}
if memory_len > 1:
self.transitions = set()
# Populate the state list & index map so we can deal with labels that
# aren't naturally integer-valued (such as graph-like objects)
for seq in state_seqs:
if model_segments:
seq, segment_len_seq = labels.computeSegments(seq)
prev_state_index = -1
for state in seq:
state_index = self.getStateIndex(state)
if memory_len > 1 and prev_state_index >= 0:
transition = (prev_state_index, state_index)
self.transitions.add(transition)
prev_state_index = state_index
class EmpiricalStateVariable(EmpiricalLatentVariables):
def getStateIndex(self, state):
""" Override inherited method """
try:
state_index = self.states.index(state)
except ValueError:
self.states.append(state)
state_index = self.num_states - 1
return state_index
class DummyLikelihood(object):
"""
Likelihood model that ignores the input.
This is useful for creating baseline models that only use the prior to
decode.
"""
def __init__(self):
super().__init__()
def fit(self, state_seqs, data_seqs):
super().fit(state_seqs, data_seqs)
def computeStateLogLikelihood(self, state_idx, *data):
return 0, None
class ImuLikelihood(object):
""" Compute the likelihood of an IMU sample. """
def __init__(self, num_imu_vars=1):
super().__init__()
self.num_imu_vars = num_imu_vars
self.lms = tuple(
(ExponentialDist(), ExponentialDist())
for i in range(self.num_imu_vars))
def fit(self, state_seqs, *all_corr_seqs):
super().fit(state_seqs, *all_corr_seqs)
for i, corr_seqs in enumerate(all_corr_seqs):
data = countMagCorrSeqs(corr_seqs, state_seqs)
for dist, sample in zip(self.lms[i], data):
dist.fit(sample)
def computeStateLogLikelihood(
self, state_idx, *all_corr_samples):
state = self.states[state_idx]
logl = 0
for i, corr_sample in enumerate(all_corr_samples):
data = countMagCorrs(corr_sample, state)
if len(data) != len(self.lms[i]):
err_str = 'Number of data categories does not match number of models'
raise ValueError(err_str)
for samples, lm in zip(data, self.lms[i]):
logl += lm.logl(samples)
return logl, None
class ImageLikelihood(object):
""" Compute the likelihood of an image. """
def __init__(self, structured=True, pixel_classifier=None):
"""
Parameters
----------
structured : bool, optional
This flag selects between two image likelihood models.
If ``structured == True``, the image model incorporates global image
structure using template rendering and registration.
If ``structured == False``, the image model assumes image pixels are
independent and uses a Gaussian mixture model.
The default value is False.
pixel_classifier : ???, optional
This is an optional model that detects (and scores) nuisance pixels.
"""
super().__init__()
self.debug = False
self.pixel_classifier = pixel_classifier
self.num_seqs = None
self.cur_seq_idx = None
self.structured = structured
if self.structured:
self.computeStateLogLikelihood = self.structuredStateLogl
else:
self.base_gmm = initBaseGmm(self.block_colors)
self.template_priors = {}
self.computeStateLogLikelihood = self.unstructuredStateLogl
self.templates = {}
def fit(self, label_seqs, *feat_seqs, model_responses=None, err_cov=None, model_segments=False):
""" Estimate the parameters of an `ImageLikelihood` model from data.
Parameters
----------
label_seqs : iterable( numpy array of int, shape (n_samples,) )
Each item in `label_seqs` is a sequence of labels for each of the
corresponding items in `feat_seqs`.
*feat_seqs : iterable( iterable( numpy array of float, shape (n_samples, n_dim) ) )
Feature sequences. Each item in `feat_seqs` is a separate set of
feature sequences.
model_responses : iterable( numpy array of float, shape (n_samples, n_states) ), optional
This model's responses to `feat_seqs`, cached from a previous run.
If this argument is provided, `fit` skips evaluating `feat_seqs`
estimates its parameters using `model_responses` instead.
err_cov : float, optional
The model's error covariance, :math:`sigma^2`.
"""
super().fit(label_seqs, *feat_seqs)
"""
if err_cov is None:
# Compute model responses for the correct labels
if model_responses is None:
feat_seqs = zip(*feat_seqs)
model_responses = tuple(
utils.batchProcess(
self.computeLogLikelihoods,
*feat_seq_tup,
state_idx=label_seq
)
for feat_seq_tup, label_seq in zip(feat_seqs, label_seqs)
)
err_cov = computeErrorCovariance(
model_responses, label_seqs,
is_log_likelihood=True,
max_error_thresh=2e4
)
self.error_covariance = err_cov
"""
def structuredStateLogl(
self, rgb_image, depth_image, segment_image,
background_plane, state_idx=None, state=None,
# include_hand_pixel_logprob=False,
**fitscene_kwargs):
"""
Score an observed image against a hypothesis state.
Parameters
----------
rgb_foreground_image : numpy array of float, shape (img_height, img_width, 3)
depth_foreground_image : numpy array of float, shape (img_height, img_width)
label_img : numpy array of int, shape (img_height, img_width)
DEPRECATED FOR NOW
This array gives a class assignment for each pixel in `observed`.
Classes are from the following set:
0 -- Hands
1 -- Blocks
2 -- Specularity
segment_img : numpy array of int, shape (img_height, img_width)
This array gives a segment assignment for each pixel in `observed`.
Segments are (mostly) contiguous regions of the image.
background_plane : geometry.Plane
state_idx : int, optional
Index of the hypothesis state to score. One of `state_idx` and `state`
must be passed to this method. If `state_idx` is not passed, this
method will retrieve the index of `state`.
state : blockassembly.BlockAssembly, optional
The hypothesis state to score. One of `state_idx` and `state` must
be passed to this method. If `state` is not passed, this method will
retrieve the state corresponding to `state_idx`.
include_hand_pixel_logprob : bool, optional
DEPRECATED FOR NOW
If True, add in the log-probability score from this object's pixel
classifier. Default is False.
**fitscene_kwargs : optional
Any extra keyword arguments get passed to `models.fitScene`.
Returns
-------
log_likelihoods : numpy array of float, shape (len(state_idxs),)
(Proportional to ) log likelihood score for each hypothesis in `state_idxs`
argmaxima : iterable( ??? )
DEPRECATED FOR NOW
arg-maximizers of any sub-models that were optimized to produce
`log_likelihoods`. The i-th element if `argmaxima` corresponds to
the i-th element of `log_likelihoods`.
component_poses : tuple( (np array of float, shape (3, 3), np array of float, shape(3,)) )
Collection of (R, t) pairs specifying the orientation and position
of each sub-part in the spatial assembly.
"""
if state is None:
state = self.getState(state_idx)
if state_idx is None:
state_idx = self.getStateIndex(state)
error, component_poses, rendered_images = fitScene(
rgb_image, depth_image, segment_image,
state, background_plane,
camera_params=render.intrinsic_matrix,
camera_pose=render.camera_pose,
block_colors=render.object_colors,
**fitscene_kwargs
)
# is_hand = label_img == 1
# if include_hand_pixel_logprob and is_hand.any():
# sample = rgb_foreground_image[is_hand]
# logprobs = self.pixel_classifier.logLikelihood(0, sample)
# state_ll += np.sum(logprobs)
# state_ll /= self.err_cov
# return state_ll, argmaxima
return -error, component_poses
def unstructuredStateLogl(
self, observed, pixel_classes, segment_labels, background_model,
state_idx=None, state=None, viz_pose=False, is_depth=False,
obsv_std=1, greedy_assignment=False, **optim_kwargs):
"""
Score an observed image against a hypothesis state.
Parameters
----------
observed : numpy array of float, shape (img_height, img_width)
pixel_classes : numpy array of int, shape (img_height, img_width)
This array gives a class assignment for each pixel in `observed`.
Classes are from the following set:
0 -- Hands
1 -- Blocks
2 -- Specularity
segment_labels : numpy array of int, shape (img_height, img_width)
This array gives a segment assignment for each pixel in `observed`.
Segments are (mostly) contiguous regions of the image.
background_model :
state_idx : int, optional
Index of the hypothesis state to score. One of `state_idx` and `state`
must be passed to this method. If `state_idx` is not passed, this
method will retrieve the index of `state`.
state : blockassembly.BlockAssembly, optional
The hypothesis state to score. One of `state_idx` and `state` must
be passed to this method. If `state` is not passed, this method will
retrieve the state corresponding to `state_idx`.
viz_pose : bool, optional
is_depth : bool, optional
obsv_std : bool, optional
greedy_assignment : bool, optional
**optim_kwargs : optional
Additional keyword arguments that get passed to
`self.computeStateLogLikelihood`.
Returns
-------
log_likelihoods : numpy array of float, shape (len(state_idxs),)
Log likelihood score for each hypothesis in `state_idxs`
argmaxima : iterable( ??? )
arg-maximizers of any sub-models that were optimized to produce
`log_likelihoods`. The i-th element if `argmaxima` corresponds to
the i-th element of `log_likelihoods`.
"""
if state is None:
state = self.states[state_idx]
if state_idx is None:
state_idx = self.getStateIndex(state)
if not state.connected_components:
state.connected_components[0] = set()
background_plane_img = None
if is_depth:
background_plane_img = render.renderPlane(background_model, observed.shape)
background_plane_img /= obsv_std
observed = observed.astype(float) / obsv_std
observed[segment_labels == 0] = background_plane_img[segment_labels == 0]
bboxes = imageprocessing.segmentBoundingBoxes(observed, segment_labels)
num_segments = segment_labels.max()
if viz_pose:
obsv_bboxes = observed.copy()
num_components = len(state.connected_components)
nll_upper_bound = 1e14
OBJECTIVES = np.full((num_components, num_segments), nll_upper_bound)
NEG_LOGLS = np.full((num_components, num_segments), nll_upper_bound)
visibility_ratio_lower_bound = 0.35
TS = []
THETAS = []
TEMPLATES = []
for comp_arr_idx, comp_idx in enumerate(state.connected_components.keys()):
template_model = self.makeTemplateGmm(state_idx, comp_idx)
if viz_pose:
plt.figure()
plt.stem(template_model.weights_)
plt.title(f'GMM prior, state {state_idx} component {comp_idx}')
plt.ylabel('p(color)')
plt.xlabel('color')
plt.show()
# TEMPLATES.append(rendered)
if viz_pose:
rgb_rendered = self.getCanonicalTemplate(state_idx, comp_idx, img_type='rgb')
TEMPLATES.append(rgb_rendered)
TS.append([])
THETAS.append([])
for seg_idx in range(1, num_segments + 1):
bbox = bboxes[seg_idx - 1]
t, __ = geometry.extremePoints(*bbox)
TS[-1].append(t)
THETAS[-1].append(0)
in_seg = segment_labels == seg_idx
is_blocks = pixel_classes == 3
is_blocks_in_seg = in_seg & is_blocks
visibility_ratio = is_blocks_in_seg.sum() / in_seg.sum()
prune_segment = visibility_ratio < visibility_ratio_lower_bound
# logger.info(f'visibility ratio: {visibility_ratio:.2f}')
if not prune_segment:
seg_pixels = observed[in_seg, :]
avg_log_prob = template_model.score(seg_pixels)
log_prob = template_model.score_samples(seg_pixels).sum()
OBJECTIVES[comp_arr_idx, seg_idx - 1] = -avg_log_prob
NEG_LOGLS[comp_arr_idx, seg_idx - 1] = -log_prob
if viz_pose:
perimeter = imageprocessing.rectangle_perimeter(*bbox)
obsv_bboxes[perimeter] = 1
if prune_segment:
obsv_bboxes[in_seg] = 1
final_obj, argmaxima = matchComponentsToSegments(
OBJECTIVES, TS, THETAS,
# downstream_objectives=NEG_LOGLS,
greedy_assignment=greedy_assignment
)
if viz_pose:
final_render = render.makeFinalRender(
TEMPLATES, observed, argmaxima[0], argmaxima[1],
copy_observed=True)
imageprocessing.displayImages(obsv_bboxes, final_render, pixel_classes, segment_labels)
if is_depth:
f, axes = plt.subplots(2, 1, figsize=(16, 8))
# axes[0].hist(residual_img.ravel(), bins=100)
axes[1].hist(final_render.ravel(), bins=100)
plt.show()
return -final_obj, argmaxima
def computeLogLikelihoods(
self, rgb_image, depth_image, segment_image, background_plane,
state_idxs=None, viz_logls=False, **fitscene_kwargs):
"""
Score an observed image against a set of hypothesis states.
Parameters
----------
rgb_image : numpy array of float, shape (img_height, img_width, 3)
depth_image : numpy array of float, shape (img_height, img_width)
segment_image : numpy array of int, shape (img_height, img_width)
This array gives a segment assignment for each pixel in `observed`.
Segments are (mostly) contiguous regions of the image.
background_plane : geometry.Plane
state_idxs : iterable(int), optional
Indices of the hypothesis states to score. By default this method
will score all the states in the model's vocabulary.
viz_logls : bool, optional
**fitscene_kwargs : optional
Additional keyword arguments that get passed to `models.fitScene`.
Returns
-------
log_likelihoods : numpy array of float, shape (len(state_idxs),)
Log likelihood score for each hypothesis in `state_idxs`
argmaxima : iterable( ??? )
arg-maximizers of any sub-models that were optimized to produce
`log_likelihoods`. The i-th element if `argmaxima` corresponds to
the i-th element of `log_likelihoods`.
"""
if state_idxs is None:
state_idxs = range(self.num_states)
logls, argmaxima = utils.batchProcess(
self.computeStateLogLikelihood,
state_idxs,
static_args=(rgb_image, depth_image, segment_image, background_plane),
static_kwargs=fitscene_kwargs,
unzip=True
)
if viz_logls:
plt.figure()
plt.stem(state_idxs, logls)
plt.xlabel('State indices')
plt.ylabel('Log probability')
plt.title('Frame log likelihoods')
plt.show()
return np.array(logls), argmaxima
def computeLikelihoods(self, *feat_seqs, **kwargs):
""" Calls `self.computeLogLikelihoods` and exponentiates to produce likelihoods.
See `self.computeLogLikelihoods`.
"""
logl, argmaxima = self.computeLogLikelihoods(*feat_seqs, **kwargs)
likelihood = np.exp(logl)
return likelihood, argmaxima
def getCanonicalTemplate(self, state_idx, comp_idx, img_type='label'):
"""
Retrieve an image of a spatial assembly component in a canonical pose.
If the template is already cached in ``self.templates``, return it.
If not, render the template, cache it, and return it.
Parameters
----------
state_idx : int
Index of the spatial assembly state.
comp_idx : int
The componenent's index in its spatial assembly.
img_type : str, optional
Type of template to retrieve. Can be one of `label`, `rgb`, or
`depth`. Default is `label`.
Returns
-------
template : numpy array of float, shape (template_height, template_width)
"""
rendered = self.templates.get((state_idx, comp_idx, img_type), None)
if rendered is not None:
return rendered
state = self.getState(state_idx)
template = self.renderCanonicalTemplate(state, comp_idx, img_type=img_type)
self.templates[(state_idx, comp_idx, img_type)] = template
return template
def makeTemplateGmm(self, state_idx, comp_idx):
"""
Create an appearance model for a component of an assembly state.
The appearance model is a Gaussian mixture model, and assumes pixels
are independent (so it is unstructured). Each Gaussian component in the
GMM corresponds to an object in the connected component of the spatial
assembly. This method renders a label image and computes a histogram
to estimate each object's prior probability in the GMM.
Parameters
----------
state_idx : int
Index of the spatial assembly state.
comp_idx : int
The componenent's index in its spatial assembly.
Returns
-------
gmm : sklearn.mixture.GaussianMixture
GMM ppearance model. It has `num_objects + 1` components, whose
means are the colors of the background and each object in the
spatial assembly. Covariances are all the identity matrix.
Component priors are histograms computed from a template image
rendered by this object.
"""
key = (state_idx, comp_idx)
prior = self.template_priors.get(key, None)
if prior is None:
num_components = self.base_gmm.means_.shape[0]
rendered = self.getCanonicalTemplate(state_idx, comp_idx, img_type='label')
prior = makeHistogram(
num_components, rendered,
ignore_empty=False, normalize=True
)
# FIXME: return a copy (GaussianMixture doesn't have a copy method)
gmm = self.base_gmm
gmm.weights_ = prior
return gmm
def predictSample(self, state_logls, state_idxs=None):
"""
Return the assembly state (and its state index) corresponding to the
arg-max of `state_logls`.
Parameters
----------
state_logls : numpy array, shape (num_states)
state_idxs : iterable(int), optional
Returns
-------
best_state : blockassembly.BlockAssembly
best_state_idx : int
"""
if state_idxs is None:
state_idxs = tuple(range(self.num_states))
best_idx = state_logls.argmax()
best_state_idx = state_idxs[best_idx]
best_state = self.getState(best_state_idx)
return best_state, best_state_idx
def visualize(self, base_path):
"""
Vizualize this model's state space.
This method saves visualizations of each state in the model's state
space in a directory named ``states``.
Parameters
----------
base_path : str
Path to the directory that visualizations should be saved in.
``states`` will be created in this directory.
"""
fig_path = os.path.join(base_path, 'states')
os.makedirs(fig_path)
for i, state in enumerate(self.states):
state.draw(fig_path, i)
def visualizePredictionInfo(self, rgb_seq, state_index_seq, pred_args):
"""
Visualize model predictions using matplotlib.
Parameters
----------
rgb_seq : iterable( numpy array, shape (img_height, img_width) )
Observed image from which the predictions were made
state_index_seq : iterable( int )
Predicted assembly state indices.
pred_args : iterable( ??? )
Values of any nuisance arguments that were maximized along with the
assembly state values. Right now this means the pose of each
component in the assembly state.
"""
# observed_eq = len(rgb_seq) == len(depth_seq)
cross_eq = len(rgb_seq) == len(state_index_seq)
if not cross_eq:
err_str = 'Arg sequences are not all of equal length'
raise ValueError(err_str)
N = len(rgb_seq)
for i in range(N):
rgb_image = img_as_float(rgb_seq[i])
# depth_image = depth_seq[i]
state_index = state_index_seq[i]
predicted_arg = pred_args[i][state_index]
# displayImages(rgb_image, depth_image)
resid_img = rgb_image - predicted_arg
imageprocessing.displayImages(predicted_arg, np.abs(resid_img))
class MultimodalLikelihood(ImuLikelihood, ImageLikelihood):
""" Container class wrapping IMU and Image likelihood models. """
def __init__(self, **imu_kwargs):
ImuLikelihood.__init__(self, **imu_kwargs)
ImageLikelihood.__init__(self)
def fit(self, state_seqs, *feat_seqs):
imu_seqs = feat_seqs[:self.num_imu_vars]
image_seqs = feat_seqs[self.num_imu_vars:]
ImuLikelihood.fit(self, state_seqs, *imu_seqs)
ImageLikelihood.fit(self, state_seqs, *image_seqs)
def computeStateLogLikelihood(
self, state_idx, *samples, imu_weight=1, image_weight=1,
**optim_kwargs):
imu_samples = samples[:self.num_imu_vars]
image_samples = samples[self.num_imu_vars:]
imu_ll, __ = ImuLikelihood.computeStateLogLikelihood(self, state_idx, *imu_samples)
# self.logger.info(f'IMU LOGL: {imu_ll}')
image_ll, argmaxima = ImageLikelihood.computeStateLogLikelihood(
self, state_idx, *image_samples, **optim_kwargs)
# self.logger.info(f'IMAGE LOGL: {image_ll}')
logl = imu_weight * imu_ll + image_weight * image_ll
return logl, argmaxima
class Hmm(object):
""" Timeseries model with a discrete, Markov-distributed latent state """
def __init__(self, **likelihood_kwargs):
super().__init__(**likelihood_kwargs)
self.psi = None
self.log_psi = None
self.sparse_uniform_transitions_ = None
self.uniform_transitions_ = None
self.cur_seq_idx = None
@property
def sparse_uniform_transitions(self):
if self.sparse_uniform_transitions_ is None:
self.sparse_uniform_transitions_ = self.makeUniformTransitions(sparse=True)
return self.sparse_uniform_transitions_
@property
def uniform_transitions(self):
if self.uniform_transitions_ is None:
self.uniform_transitions_ = self.makeUniformTransitions(sparse=False)
return self.uniform_transitions_
def makeUniformTransitions(self, sparse=False):
transition_probs = np.ones_like(self.psi)
if sparse:
transition_probs[self.psi == 0] = 0
transition_probs /= transition_probs.sum(axis=1)
return transition_probs
def fit(self, label_seqs, *feat_seqs,
uniform_regularizer=0, diag_regularizer=0, empty_regularizer=0,
zero_transition_regularizer=0, model_segments=False,
estimate_final_state_scores=False,
override_transitions=False,
**super_kwargs):
""" Fit this model to observed data-label pairs.
This method estimates the state-to-state transition parameters.
Parameters
----------
label_seqs : list(np array), shape [n_samples, n_edges]
Observed labels.
*feat_seqs : list(np array), shape [n_samples, n_dim]
Observed data.
uniform_regularizer : float, optional
Number of extra counts added to all entries of transition matrix.
diag_regularizer : float, optional
Number of extra counts added to diagonal entries of transition
matrix (ie self-transitions).
empty_regularizer : float, optional
Number of extra counts added to the self-transition of the 0
(presumed empty) state.
zero_transition_regularizer : float, optional
Number of extra counts added to all transitions that lead to the
0 (presumed empty) state.
override_transitions : bool, optional
If True, set the state transition parameters to a constant array of
ones instead of the observed relative frequencies.
NOTE: state_seqs can actually contain anything iterable over the
number of samples. If it contains 2D numpy arrays, the array rows
must represent samples because numpy iterates over rows by default.
"""
super().fit(label_seqs, *feat_seqs, model_segments=model_segments, **super_kwargs)
psi = np.zeros((self.num_states, self.num_states))
psi += uniform_regularizer
for i in range(self.num_states):
psi[i, i] += diag_regularizer
psi[0, 0] += empty_regularizer
psi[:, 0] += zero_transition_regularizer
psi[0, :] += zero_transition_regularizer
unigram_counts = np.zeros(self.num_states)
if model_segments:
segment_lens = collections.defaultdict(list)
else:
segment_lens = None
for l in label_seqs:
seq_bigram_counts, seq_unigram_counts = self.fitSeq(l, segment_lens=segment_lens)
psi += seq_bigram_counts
unigram_counts += seq_unigram_counts
if estimate_final_state_scores:
final_states = np.array([self.getStateIndex(label_seq[-1]) for label_seq in label_seqs])
self.final_state_probs = makeHistogram(self.num_states, final_states, normalize=True)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "divide by zero encountered")
self.final_state_scores = np.log(self.final_state_probs)
if np.any(np.isnan(self.final_state_scores)):
raise ValueError()
else:
self.final_state_probs = np.ones(self.num_states)
self.final_state_scores = np.zeros(self.num_states)
plt.figure()
plt.stem(self.final_state_probs)
if segment_lens is not None:
self.max_duration = max(itertools.chain(*segment_lens.values()))
self.durations = np.arange(self.max_duration)
self.duration_probs = np.array(
tuple(
makeHistogram(self.max_duration, segment_lens[state_idx], normalize=True)
for state_idx in range(self.num_states)
)
)
plt.matshow(self.duration_probs)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "divide by zero encountered")
self.duration_scores = np.log(self.duration_probs)
state_has_no_counts = ~self.duration_probs.any(axis=1)
if state_has_no_counts.any():
err_str = (
f"States {state_has_no_counts.nonzero()[0]} "
"have zero counts for every duration!"
)
raise ValueError(err_str)
if override_transitions:
logger.info('Overriding pairwise counts with array of all ones')
psi = np.ones_like(psi)
# Normalize rows of transition matrix
for index in range(self.num_states):
# Define 0 / 0 as 0
if not psi[index, :].any(): # and not unigram_counts[index]:
continue
# psi[index,:] /= unigram_counts[index]
psi[index, :] /= psi[index, :].sum()
self.psi = psi
plt.matshow(self.psi)
plt.show()
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "divide by zero")
self.log_psi = np.log(psi)
def fitSeq(self, label_seq, segment_lens=None):
""" Count max-likelihood transition parameters for a single sequence.
Parameters
----------
label_seq : iterable( object )
Sequence of label states---not state integer IDs.
segment_lens : collections.defaultdict(list), optional
If provided, this dictionary is updated with the duration of each
segment in the label sequence.
Returns
-------
pairwise_counts : numpy array of int, shape (self.num_states, self.num_states)
unigram_counts : numpy array of int, shape (self.num_states,)
"""
label_idx_seq = self.toLabelIndexArray(label_seq)
# Convert sample labels to segment labels and compute segment duration
# counts if segment_lens was passed.
if segment_lens is not None:
label_idx_seq, segment_len_seq = labels.computeSegments(label_idx_seq)
for state_id, segment_len in zip(label_idx_seq, segment_len_seq):
segment_lens[state_id].append(segment_len)
# Compute unigram counts
unigram_counts = np.zeros(self.num_states)
for index in label_idx_seq:
unigram_counts[index] += 1
# Compute bigram counts
pairwise_counts = np.zeros((self.num_states, self.num_states))
for prev_index, cur_index in zip(label_idx_seq[:-1], label_idx_seq[1:]):
pairwise_counts[prev_index, cur_index] += 1
return pairwise_counts, unigram_counts
def forward(self, local_evidence):
"""
HMM forward algorithm for computing data likelihood.
NOTE: This implementation follows the pseudocode in Murphy Ch. 17.4.2
(Algorithm 17.1)
Parameters
----------
local_evidence :
Returns
-------
alpha :
Z :
"""
def normalize(u):
u_sum = u.sum()
if u.any():
u /= u_sum
return u, u_sum
# initialization
num_states, num_samples = local_evidence.shape
alpha = np.zeros_like(local_evidence)
Z = np.zeros(num_samples)
# We always start in state 0, so pi is the standard basis vector e_0
# NOTE: pi is the marginal distribution on the state at time t = 1,
# p(z_1 = j)
pi = np.zeros(num_states)
pi[0] = 1
alpha[:, 0], Z[0] = normalize(local_evidence[:, 0] * pi)
for t in range(1, num_samples):
alpha[:, t], Z[t] = normalize(
local_evidence[:, t] * (self.psi.T @ alpha[:, t - 1]))
return alpha, Z.sum()
def backward(self, local_evidence):
"""
HMM backward algorithm for computing data likelihood.
NOTE: This implementation follows the pseudocode in Murphy Ch. 17.4.2
(Algorithm 17.1)
Parameters
----------
local_evidence :
Returns
-------
beta :
"""
num_states, num_samples = local_evidence.shape
beta = np.zeros_like(local_evidence)
beta[:, -1] = 1
for t in reversed(range(1, num_samples)):
beta[:, t - 1] = self.psi @ (local_evidence[:, t] * beta[:, t])
return beta
def prune(
self, prev_max_lps, transition_probs,
greed_coeff=None, sparsity_level=None,
transition_thresh=0, verbose=0):
"""
Produces a set of predictions (hypotheses) for time t, given a set of
scores for the model's predictions at time t-1 and a transition model.
Parameters
----------
prev_max_lps : numpy.ndarray, shape (NUM_STATES,)
Scores for the model's predictions at time t-1.
transition_probs : numpy.ndarray, shape (NUM_STATES, NUM_STATES)
Pairwise scores. Usually interpreted as state-to-state transition
probabilities.
greed_coeff : float, optional
Controls the "greediness" of the pruner by thresholding against the
highest-scoring hypothesis. Must be in the range [0, infinity].
If 0, nothing is pruned. If infinity, everything but the one-best
hypothesis is pruned.
sparsity_level : int, optional
Controls the "greediness" of the pruner by keeping a k-best list.
Let `sparsity_level = k`. Everything but the k highest-scoring
hypotheses is pruned.
transition_thresh : float, optional
Threshold for sparsifying pairwise scores. Any state transition with
score less than `transition_thresh` is pruned.
verbose : bool, optional
If True, sends a message summarizing the pruning operation to
logger.info.
Returns
-------
beam_image : list(int)
New predictions (hypothesis set). Each element is the index of a
hypothesized state.
"""
if greed_coeff is not None and sparsity_level is not None:
err_str = 'Only one of (greed_coeff, sparsity_level) may be passed!'
raise ValueError(err_str)
transition_prob_nonzero = transition_probs > transition_thresh
if greed_coeff is not None:
in_beam_support = sparsifyThresh(prev_max_lps, greed_coeff)
elif sparsity_level is not None:
in_beam_support = sparsifyBest(prev_max_lps, sparsity_level)
else:
in_beam_support = np.ones(self.num_states, dtype=bool)
in_beam_image = transition_prob_nonzero.T @ in_beam_support
# in_beam_image = in_beam_support
if not in_beam_image.any():
err_str = 'Viterbi beam is empty!'
raise ValueError(err_str)
beam_image = np.where(in_beam_image)[0]
if verbose:
support_size = in_beam_support.sum()
image_size = in_beam_image.sum()
debug_str = f'Beam size {support_size:2} -> {image_size:2}'
self.logger.info(debug_str)
return beam_image
def transitionProbs(self, ml_decode=None, sparse_ml_decode=None):
""" Return pairwise scores for a decode run.
By default, this method returns the model's pairwise parameters.
Parameters:
-----------
ml_decode : bool, optional
If True, this method emulates a maximum-likelihood decode by
ignoring the prior distribution over states. In other words, it
returns uniform score arrays instead of the model parameters.
sparse_ml_decode: bool, optional
If True, this method returns score arrays that are uniform over the
domain of the model's pairwise parameters (ie any state transition
that has zero probability in the model's parameters also has zero
probability in these scores).
Returns
-------
transition_probs : numpy.ndarray, shape (NUM_STATES, NUM_STATES)
Pairwise potentials (probabities) for states.
log_transition_probs : numpy.ndarray, shape (NUM_STATES, NUM_STATES)
Pairwise scores (log probabilities) for states.
"""
if ml_decode:
transition_probs = self.uniform_transitions
log_transition_probs = np.log(transition_probs)
elif sparse_ml_decode:
transition_probs = self.sparse_uniform_transitions
log_transition_probs = np.log(transition_probs)
else:
transition_probs = self.psi
log_transition_probs = self.log_psi
return transition_probs, log_transition_probs
def viterbi(
self, *samples, prior=None,
greed_coeff=None, sparsity_level=None, verbose_level=False,
transition_thresh=0, ml_decode=False, sparse_ml_decode=False,
state_log_likelihoods=None, edge_logls=None,
score_samples_as_batch=False, no_state_logl=False,
**ll_kwargs):
""" Viterbi search with threshold and sparsity-based beam pruning.
Parameters
----------
samples :
prior :
greed_coeff :
sparsity_level :
verbose_level :
transition_thresh :
ml_decode :
sparse_ml_decode :
log_likelihoods :
edge_logls :
ll_kwargs :
Returns
-------
pred_idxs :
max_log_probs :
log-likelihoods :
final_argmaxima :
"""
transition_probs, log_transition_probs = self.transitionProbs(
ml_decode=ml_decode,
sparse_ml_decode=sparse_ml_decode
)
if prior is None:
prior = np.zeros(self.num_states)
prior[0] = 1
# You need to call this before unzipping samples below
if score_samples_as_batch:
edge_logls = self.computeLogLikelihoods(*samples, as_array=True)
# Convert tuple of sequences to sequence of tuples for easier
# iteration
samples = tuple(zip(*samples))
# Initialization---you need to call this AFTER unzipping samples above
all_argmaxima = {}
num_samples = len(samples)
array_dims = (self.num_states, num_samples)
max_log_probs = np.full(array_dims, -np.inf)
best_state_idxs = np.full(array_dims, np.nan, dtype=int)
# Forward pass (max-sum)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "divide by zero")
prev_max_lps = np.log(prior)
for sample_idx, sample in enumerate(samples):
if sample_idx == 0:
state_lps = prev_max_lps
max_log_probs[:, sample_idx] = state_lps
prev_max_lps = max_log_probs[:, sample_idx]
all_argmaxima[0, sample_idx] = tuple()
continue
# Prune hypotheses
beam_image = self.prune(
prev_max_lps, transition_probs,
greed_coeff=greed_coeff, sparsity_level=sparsity_level,
transition_thresh=transition_thresh,
verbose=verbose_level
)
# Compute likelihoods / data scores
if no_state_logl:
state_logls = None
elif state_log_likelihoods is None:
state_logls, argmaxima = self.computeLogLikelihoods(
*sample, **ll_kwargs, state_idxs=beam_image
)
state_log_likelihoods = np.full(array_dims, -np.inf)
else:
state_logls = state_log_likelihoods[beam_image, sample_idx]
argmaxima = [None] * len(beam_image)
# Add in state transition scores
for i, state_idx in enumerate(beam_image):
state_lps = (prev_max_lps + log_transition_probs[:, state_idx])
if state_logls is not None:
state_logl = state_logls[i]
argm = argmaxima[i]
state_lps += state_logl
state_log_likelihoods[state_idx, sample_idx] = state_logl
if edge_logls is not None:
state_lps += edge_logls[sample_idx, :, state_idx]
argm = None
max_log_probs[state_idx, sample_idx] = state_lps.max()
best_state_idxs[state_idx, sample_idx] = state_lps.argmax()
all_argmaxima[state_idx, sample_idx] = argm
prev_max_lps = max_log_probs[:, sample_idx]
plt.stem(state_logls)
plt.matshow(max_log_probs)
plt.show()
# Backward pass (backtrace)
pred_idxs = np.zeros(num_samples, dtype=int)
pred_idxs[-1] = max_log_probs[:, -1].argmax()
for sample_idx in reversed(range(1, num_samples)):
prev_best_state = pred_idxs[sample_idx]
best_state_idx = best_state_idxs[prev_best_state, sample_idx]
pred_idxs[sample_idx - 1] = best_state_idx
final_argmaxima = tuple(
all_argmaxima[state_idx, sample_idx]
for sample_idx, state_idx in enumerate(pred_idxs)
)
return pred_idxs, max_log_probs, state_log_likelihoods, final_argmaxima
def viterbiSegmental(
self, *samples, prior=None,
greed_coeff=None, sparsity_level=None, verbose_level=False,
transition_thresh=0, ml_decode=False, sparse_ml_decode=False,
state_log_likelihoods=None, edge_logls=None,
score_samples_as_batch=False, no_state_logl=False,
**ll_kwargs):
""" Viterbi search with threshold and sparsity-based beam pruning.
Parameters
----------
samples :
prior :
greed_coeff :
sparsity_level :
verbose_level :
transition_thresh :
ml_decode :
sparse_ml_decode :
log_likelihoods :
edge_logls :
ll_kwargs :
Returns
-------
pred_idxs :
max_log_probs :
log-likelihoods :
final_argmaxima :
"""
transition_probs, log_transition_probs = self.transitionProbs(
ml_decode=ml_decode,
sparse_ml_decode=sparse_ml_decode
)
if prior is None:
prior = np.zeros(self.num_states)
prior[0] = 1
# You need to call this before unzipping samples below
if score_samples_as_batch:
edge_logls = self.computeLogLikelihoods(*samples, as_array=True)
for sample in edge_logls:
plt.matshow(sample)
plt.show()
# Convert tuple of sequences to sequence of tuples for easier
# iteration
samples = tuple(zip(*samples))
# Initialization---you need to call this AFTER unzipping samples above
all_argmaxima = {}
num_samples = len(samples)
array_dims = (self.num_states, num_samples)
best_scores = np.full(array_dims, -np.inf)
# Seed packpointers so we can decode the first segment when backtracing
backpointers = {} # (0, 0): (0, -1)}
if state_log_likelihoods is None and not no_state_logl:
state_log_likelihoods = np.full(array_dims, -np.inf)
# Forward pass (max-sum)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "divide by zero")
log_prior = np.log(prior)
prev_best_scores = log_prior
for sample_idx, sample in enumerate(samples):
# if sample_idx == 0:
# state_lps = prev_best_scores
# best_scores[:, sample_idx] = state_lps
# prev_best_scores = best_scores[:, sample_idx]
# all_argmaxima[0, sample_idx] = tuple()
# continue
# Prune hypotheses
beam_image = self.prune(
prev_best_scores, transition_probs,
greed_coeff=greed_coeff, sparsity_level=sparsity_level,
transition_thresh=transition_thresh,
verbose=verbose_level
)
# logger.info(f"Sample {sample_idx}: {beam_image}")
# Compute likelihoods / data scores
if no_state_logl:
state_logls = None
elif state_logls is None:
state_logls, argmaxima = self.computeLogLikelihoods(
*sample, **ll_kwargs, state_idxs=beam_image
)
else:
state_logls = state_log_likelihoods[beam_image, sample_idx]
argmaxima = [None] * len(beam_image)
for i, seg_idx in enumerate(beam_image):
score_table = np.full(
(self.duration_scores.shape[0], self.duration_scores.shape[1]),
-np.inf
)
for j, prev_seg_idx in enumerate(self.state_indices):
duration_prob_is_pos = self.duration_probs[seg_idx, :] > 0
segment_begins_in_seq = (sample_idx - self.durations) + 1 >= 0
duration_candidate_idxs = np.nonzero(
duration_prob_is_pos * segment_begins_in_seq
)[0]
duration_candidates = self.durations[duration_candidate_idxs]
# logger.info(f"duration candidates: {duration_candidates}")
duration_scores = self.duration_scores[seg_idx, duration_candidates]
# if not duration_candidates.any():
# raise ValueError()
# for duration, dur_score in enumerate(self.duration_scores[prev_seg_idx,:])
for duration, dur_score in zip(duration_candidates, duration_scores):
prev_seg_end_idx = sample_idx - duration
seg_start_idx = prev_seg_end_idx + 1
if seg_start_idx < 0:
raise ValueError()
if sample_idx == -1:
prev_seg_prior = log_prior[seg_idx]
seg_score = prev_seg_prior
else:
prev_seg_prior = best_scores[prev_seg_idx, prev_seg_end_idx]
seg_transition_score = log_transition_probs[prev_seg_idx, seg_idx]
seg_score = prev_seg_prior + seg_transition_score
seg_score += dur_score
# Compute data score for this segment
seg = slice(seg_start_idx, sample_idx + 1)
# FIXME: hasn't been properly converted to segmental decode
if state_logls is not None:
state_logl = state_logls[seg]
argm = argmaxima[i]
# state_lps += state_logl
state_log_likelihoods[seg_idx, sample_idx] = state_logl
if edge_logls is not None and prev_seg_idx >= 0:
seg_score += edge_logls[seg, prev_seg_idx, seg_idx].sum()
argm = None
score_table[j, duration] = seg_score
# if sample_idx == 1:
# plt.matshow(score_table.T)
# plt.show()
# assert(True == False)
j, best_duration = utils.argmaxNd(score_table)
prev_best_seg = self.state_indices[j]
prev_best_seg_end_idx = sample_idx - best_duration
backpointers[seg_idx, sample_idx] = (prev_best_seg, prev_best_seg_end_idx)
best_scores[seg_idx, sample_idx] = score_table[j, best_duration]
all_argmaxima[seg_idx, sample_idx] = argm
prev_best_scores = best_scores[:, sample_idx]
plt.matshow(best_scores.T)
plt.show()
# Add in final state scores to eliminate sequences that aren't accepted
# by this machine
best_scores[:, -1] += self.final_state_scores
# Backward pass (backtrace)
best_seg = best_scores[:, -1].argmax()
best_seg_end_idx = num_samples - 1
pred_idxs = np.full(num_samples, -1, dtype=int)
sample_idx = best_seg_end_idx
# logger.info(f"backpointer: {best_seg}, @ {best_seg_end_idx}")
while sample_idx > -1:
prev_best_seg, prev_best_seg_end_idx = backpointers[best_seg, sample_idx]
best_seg_start_idx = prev_best_seg_end_idx + 1
pred_idxs[best_seg_start_idx:best_seg_end_idx + 1] = best_seg
best_seg = prev_best_seg
best_seg_end_idx = prev_best_seg_end_idx
sample_idx = best_seg_end_idx
# logger.info(f"backpointer: {best_seg}, @ {best_seg_end_idx}")
sample_was_skipped = pred_idxs < 0
if np.any(sample_was_skipped):
err_str = f"skipped {sample_was_skipped.sum()} samples when backtracing"
raise ValueError(err_str)
final_argmaxima = tuple(
all_argmaxima[state_idx, sample_idx]
for sample_idx, state_idx in enumerate(pred_idxs)
)
return pred_idxs, best_scores, state_log_likelihoods, final_argmaxima
def mpeDecode(self, logl, **kwargs):
"""
Marginal posterior estimation using the forward-backward algorithm.
Parameters
----------
logl :
kwargs :
Returns
-------
predicted_idxs :
"""
local_evidence = np.exp(logl)
# Forward, backward passes
alpha, __ = self.forward(local_evidence)
beta = self.backward(local_evidence)
# Compute gamma, proportional to the marginal posterior up to a
# dividing term which is constant in z (so we can just argmax over
# gamma)
gamma = alpha * beta
predicted_idxs = gamma.argmax(axis=0)
return predicted_idxs
def predict(self, *feat_seqs, **predict_kwargs):
self.num_seqs = len(feat_seqs[0])
self.cur_seq_idx = 0
f = functools.partial(self.predictSeq, **predict_kwargs)
prediction_tups = utils.iterate(f, *feat_seqs)
pred_state_seqs, pred_idx_seqs, unary_info = tuple(zip(*prediction_tups))
return pred_state_seqs, pred_idx_seqs, unary_info
def predictSeq(
self, *feat_seqs, decode_method='MAP', viz_predictions=False,
**kwargs):
if decode_method == 'MPE':
decode = self.mpeDecode
elif decode_method == 'MAP':
decode = self.viterbi
elif decode_method == 'ML':
decode = functools.partial(self.viterbi, ml_decode=True)
elif decode_method == 'MLSPARSE':
decode = functools.partial(self.viterbi, sparse_ml_decode=True)
elif decode_method == 'segmental':
decode = self.viterbiSegmental
else:
err_str = (
'Invalid argument "decode_method={}" '
'decode_method must be one of: '
'MPE (marginal posterior decoding) '
'MAP (viterbi decoding) '
'ML (maximum likelihood decoding)'
)
raise ValueError(err_str.format(decode_method))
if self.cur_seq_idx is not None:
fmt_str = 'Decoding sequence {} / {}'
self.logger.info(fmt_str.format(self.cur_seq_idx + 1, self.num_seqs))
# logl, argmaxima = self.computeLogUnaryPotential(
# *feat_seqs, **kwargs)
# pred_states, pred_idxs = self.predictSeqFromUnary(
# *feat_seqs, decode_method=decode_method)
# if viz_predictions:
# self.visualizePredictionInfo(*feat_seqs, pred_idxs, argmaxima)
# unary_info = (logl, argmaxima)
pred_idxs, log_probs, log_likelihoods, argmaxima = decode(*feat_seqs, **kwargs)
pred_states = [self.getState(i) for i in pred_idxs]
if self.cur_seq_idx is not None:
self.cur_seq_idx += 1
return pred_states, pred_idxs, log_probs, log_likelihoods, argmaxima
def predictSeqFromUnary(self, logl, decode_method='MAP'):
if decode_method == 'MPE':
decode = self.mpeDecode
elif decode_method == 'MAP':
decode = self.mapDecode
elif decode_method == 'ML':
decode = self.mlDecode
else:
err_str = (
'Invalid argument "decode_method={}" '
'decode_method must be one of: '
'MPE (marginal posterior decoding) '
'MAP (viterbi decoding) '
'ML (maximum likelihood decoding)')
raise ValueError(err_str.format(decode_method))
pred_idxs = decode(logl)
pred_states = [self.getState(i) for i in pred_idxs]
return pred_states, pred_idxs
def predictFromUnary(self, logl_seqs, **predict_kwargs):
f = functools.partial(self.predictSeqFromUnary, **predict_kwargs)
prediction_tups = utils.iterate(f, logl_seqs)
pred_state_seqs, pred_idx_seqs = tuple(zip(*prediction_tups))
return pred_state_seqs, pred_idx_seqs
def visualize(self, base_path):
super().visualize(base_path)
fn = os.path.join(base_path, 'transition-probs.png')
label = 'Transition probabilities'
utils.plotArray(self.psi, fn, label)
class Crf(object):
"""
Straightforward application of some models in Lea et al.
(ECCV, ICRA)
"""
def __init__(self, base_model='ChainModel', **base_kwargs):
super().__init__()
# self.model = getattr(lctm_models, base_model)(**base_kwargs)
def visualize(self, base_path):
if not os.path.exists(base_path):
os.makedirs(base_path)
def plotLoss(model, base_path):
fn = os.path.join(base_path, 'objective.png')
iterate_idxs = np.array(list(model.logger.objectives.keys()))
iterate_vals = np.array(list(model.logger.objectives.values()))
plt.figure()
plt.plot(iterate_idxs, iterate_vals)
plt.title('Objective function')
plt.ylabel('f(i)')
plt.xlabel('i')
plt.savefig(fn)
plt.close()
def plotWeights(model, base_path):
for name, weights in model.ws.items():
fn = os.path.join(base_path, 'weights-{}.png'.format(name))
plt.matshow(weights)
plt.colorbar(orientation='horizontal', pad=0.1)
plt.title(name)
plt.savefig(fn)
plt.close()
plotLoss(self.model, base_path)
plotWeights(self.model, base_path)
def fit(self, label_seqs, *feat_seqs, **kwargs):
super().fit(label_seqs, *feat_seqs)
labels = self.toLabelIndexArrays(label_seqs)
self.preprocessor = preprocessing.StandardScaler()
self.preprocessor.fit(utils.toFlattenedFeatureArray(*feat_seqs))
features = utils.toFeatureArrays(*feat_seqs)
features = [self.preprocessor.transform(f) for f in features]
self.model.fit(utils.transposeSeq(features), labels, **kwargs)
def predictSeq(self, *feat_seqs):
features = utils.toFeatureArray(*feat_seqs)
features = self.preprocessor.transform(features)
predicted_idxs = self.model.predict(features.T)
predicted_seq = [self.getState(index) for index in predicted_idxs]
return predicted_seq
def computeUnaryPotential(self, *feat_seqs):
raise NotImplementedError
def computeLogUnaryPotential(self, *feat_seqs):
features = utils.toFeatureArray(*feat_seqs)
features = self.preprocessor.transform(features)
num_samples = features.shape[0]
score = np.zeros([self.num_states, num_samples], np.float64)
score = self.model.potentials['unary'].compute(
self.model, features.T, score)
return score
class BaseModel(object):
""" [] """
def localEvidence(self, *feat_seqs):
return utils.iterate(self.computeLogUnaryPotential, *feat_seqs)
def predict(self, *feat_seqs, **predict_kwargs):
f = functools.partial(self.predictSeq, **predict_kwargs)
return utils.iterate(f, *feat_seqs)
def fit(self, label_seqs, *feat_seqs, **kwargs):
raise NotImplementedError
def visualize(self, base_path):
raise NotImplementedError
# -=( COMPOSITE PROBABILITIC MODELS )=-----------------------------------------
class KMeansFrameScorer(FrameScorer, KMeans, LoggerMixin):
pass
class MiniBatchKMeansFrameScorer(FrameScorer, MiniBatchKMeans, LoggerMixin):
pass
class EmpiricalImageLikelihood(ImageLikelihood, EmpiricalStateVariable, LoggerMixin):
pass
class EmpiricalImageHmm(Hmm, ImageLikelihood, EmpiricalStateVariable, LoggerMixin):
pass
class EmpiricalImuHmm(Hmm, ImuLikelihood, EmpiricalStateVariable, LoggerMixin):
pass
class EmpiricalMultimodalHmm(Hmm, MultimodalLikelihood, EmpiricalStateVariable, LoggerMixin):
pass
class EmpiricalDummyHmm(Hmm, DummyLikelihood, EmpiricalStateVariable, LoggerMixin):
pass
class HandDetectionHmm(Hmm, HandDetectionLikelihood, EmpiricalStateVariable, LoggerMixin):
pass
class EmpiricalCrf(Crf, EmpiricalLatentVariables, LoggerMixin):
pass
# -=( VISUALIZATION )----------------------------------------------------------
def plotModel(model, base_path, label):
path = os.path.join(base_path, 'models')
if not os.path.exists(path):
os.makedirs(path)
model_path = os.path.join(path, label)
model.visualize(model_path)
def plotLocalEvidenceSeqs(le_seqs, trial_ids, base_path, label):
f = functools.partial(plotLocalEvidenceSeq, base_path=base_path, label=label)
utils.evaluate(f, le_seqs, trial_ids)
def plotLocalEvidenceSeq(le_seq, trial_id, base_path, label):
path = os.path.join(base_path, '{}'.format(trial_id))
if not os.path.exists(path):
os.makedirs(path)
fn = os.path.join(path, '{}_trial-{:03d}.png'.format(label, trial_id))
utils.plotArray(le_seq, fn, label)
def visualizeKeyframeModel(model):
""" Draw a figure visualizing a keyframe model.
Parameters
----------
model : FrameScorer
"""
noise_hist = model.class_histograms[:,0]
clean_hist = model.class_histograms[:,1]
indices = np.arange(model.n_clusters)
snrs = model.class_snrs
is_noise_cluster = model.is_bad_cluster
rgb_means = model.rgb_means
f, axes = plt.subplots(2, figsize=(10, 10))
axes[0].bar(
indices[~is_noise_cluster],
clean_hist[~is_noise_cluster],
color=rgb_means[~is_noise_cluster,:],
edgecolor='k'
)
axes[0].set_title('Clean data')
axes[0].bar(
indices[is_noise_cluster],
clean_hist[is_noise_cluster],
color=rgb_means[is_noise_cluster,:],
alpha=0.5
)
axes[1].bar(
indices[~is_noise_cluster],
noise_hist[~is_noise_cluster],
color=rgb_means[~is_noise_cluster,:],
alpha=0.5
)
axes[1].bar(
indices[is_noise_cluster],
noise_hist[is_noise_cluster],
color=rgb_means[is_noise_cluster,:],
edgecolor='k'
)
axes[1].set_title('Noisy data')
plt.tight_layout()
plt.show()
logger.info(f'Noise SNR: {snrs[0]:.2f}')
logger.info(f'Clean SNR: {snrs[1]:.2f}')
# -=( IMAGE MODEL HELPER FUNCTIONS )-------------------------------------------
def initBaseGmm(block_colors):
"""
Partially-initialize a GMM appearance model.
Parameters
----------
block_colors : shape (1 + num_objects, 3)
Numpy array whose rows represent the colors of each object in a scene.
The first row (i.e. row index zero) corresponds to the background. Each
subsequent row corresponds to an object in the spatial assembly.
These block colors serve as a rudimentary appearance model.
Returns
-------
gmm : sklearn.mixture.GaussianMixture
Partially-initialized Gaussian mixture model. It has `num_objects + 1`
components, whose means are the corresponding rows of `block_colors`
and whose covariances are all the identity matrix. The component priors
are all zero, and must be initialized later.
"""
# class_means = block_colors
# num_nonzero_components, num_dims = block_colors.shape
# zero = np.zeros(num_dims)
# class_means = np.vstack((zero, block_colors))
class_means = block_colors
num_components, num_dims = class_means.shape
cov = np.eye(num_dims)
prec = np.linalg.inv(cov)
gmm = GaussianMixture(
n_components=num_components,
# weights_init=class_priors,
means_init=class_means,
precisions_init=prec,
covariance_type='tied'
)
gmm._initialize(np.zeros((0, num_dims)), np.zeros((0, num_components)))
gmm.covariances_ = cov
return gmm
def registerTemplateToSegment(
observed, rendered, seg_bounding_box, rendered_center, Tr, Tc,
background_img=None, **optim_kwargs):
"""
Parameters
----------
Returns
-------
"""
V = geometry.sampleInteriorUniform(*seg_bounding_box)
max_min = geometry.extremePoints(*seg_bounding_box)
residual = functools.partial(
templateMatchingResidual, observed, rendered, V,
background_img=background_img
)
jacobian = functools.partial(templateMatchingJacobian, observed, rendered, Tr, Tc, V)
bound = functools.partial(translationBoundConstraints, rendered_center, *max_min)
t, theta, __ = optimizePose(residual, jacobian, bound, **optim_kwargs)
return t, theta
def residual(x_true, x_est, true_mask=None, est_mask=None):
if true_mask is not None:
x_true[true_mask] = 0
if est_mask is not None:
x_est[est_mask] = 0
resid = x_true - x_est
return resid
def standardize(x, bias=0, scale=1):
x_standardized = (x - bias) / scale
return x_standardized
def mse(x_true, x_est, true_mask=None, est_mask=None, bias=None, scale=None):
x_true = standardize(x_true, bias=bias, scale=scale)
x_est = standardize(x_est, bias=bias, scale=scale)
resid = residual(x_true, x_est, true_mask=true_mask, est_mask=est_mask)
mse = np.mean(resid ** 2)
return mse
def sse(x_true, x_est, true_mask=None, est_mask=None, bias=None, scale=None):
x_true = standardize(x_true, bias=bias, scale=scale)
x_est = standardize(x_est, bias=bias, scale=scale)
resid = residual(x_true, x_est, true_mask=true_mask, est_mask=est_mask)
sse = np.sum(resid ** 2)
return sse
def refineComponentPose(
rgb_image, depth_image, segment_image, assembly,
rgb_background=None, depth_background=None, label_background=None,
component_index=None, init_pose=None, theta_samples=None,
camera_params=None, camera_pose=None, block_colors=None,
object_mask=None, W=None, error_func=None, bias=None, scale=None):
""" Refine a component's initial pose estimate using a simple registration routine.
Parameters
----------
Returns
-------
best_error : float
best_pose : (R, t)
"""
if error_func is None:
error_func = sse
if W is None:
W = np.ones(2)
if theta_samples is None:
theta_samples = range(0, 360, 90)
R_init, t_init = init_pose
pose_candidates = tuple(
(geometry.rotationMatrix(z_angle=theta, x_angle=0) @ R_init, t_init)
for theta in theta_samples
)
rgb_renders, depth_renders, label_renders = utils.batchProcess(
render.renderComponent, pose_candidates,
static_args=(assembly, component_index),
static_kwargs={
'camera_pose': camera_pose,
'camera_params': camera_params,
'block_colors': block_colors,
'rgb_image': rgb_background,
'range_image': depth_background,
'label_image': label_background,
'in_place': False
},
unzip=True
)
# Subtract background from all depth images. This gives distances relative
# to the background plane instead of the camera, so RGB and depth models
# are closer to the same scale.
depth_renders = tuple(d - depth_background for d in depth_renders)
depth_image = depth_image - depth_background
# imageprocessing.displayImages(*rgb_renders, *depth_renders, *label_renders, num_rows=3)
object_background_mask = ~object_mask
label_background_masks = tuple(label_render == 0 for label_render in label_renders)
rgb_errors = np.array([
error_func(
rgb_image, rgb_render,
true_mask=object_background_mask, est_mask=label_mask,
bias=bias[0], scale=scale[0]
)
for rgb_render, label_mask in zip(rgb_renders, label_background_masks)
])
depth_errors = np.array([
error_func(
depth_image, depth_render,
true_mask=object_background_mask, est_mask=label_mask,
bias=bias[1], scale=scale[1]
)
for depth_render, label_mask in zip(depth_renders, label_background_masks)
])
errors = np.column_stack((rgb_errors, depth_errors)) @ W
best_idx = errors.argmin()
best_error = errors[best_idx]
best_pose = pose_candidates[best_idx]
return best_error, best_pose
def fitScene(
rgb_image, depth_image, segment_image,
assembly, background_plane,
camera_params=None, camera_pose=None, block_colors=None,
W=None, error_func=None, bias=None, scale=None,
ignore_background=False):
""" Fit a spatial assembly and a background plane to an RGBD image.
Parameters
----------
Returns
-------
"""
# Make copies so we don't accidentally modify the input
rgb_image = rgb_image.copy()
segment_image = segment_image.copy()
depth_image = depth_image.copy()
if error_func is None:
error_func = sse
if W is None:
W = np.ones(2)
rgb_background, depth_background, label_background = render.renderPlane(
background_plane, camera_pose, camera_params,
plane_appearance=block_colors[0, :],
)
# Estimate initial poses from each detected image segment
segment_labels = np.unique(segment_image[segment_image != 0])
object_masks = tuple(segment_image == i for i in segment_labels)
object_poses_est = utils.batchProcess(
imageprocessing.estimateSegmentPose,
object_masks,
static_args=(camera_params, camera_pose, depth_image),
static_kwargs={'estimate_orientation': False}
)
num_components = len(assembly.connected_components)
num_segments = len(segment_labels)
# Find the best pose for each component of the spatial assembly, assuming
# we try to match it to a particular segment.
errors = np.zeros((num_components, num_segments))
poses = {}
for component_index, component_key in enumerate(assembly.connected_components.keys()):
for segment_index in range(num_segments):
object_mask = object_masks[segment_index]
init_pose = object_poses_est[segment_index]
error, pose = refineComponentPose(
rgb_image, depth_image, segment_image, assembly,
rgb_background=rgb_background,
depth_background=depth_background,
label_background=label_background,
component_index=component_key, init_pose=init_pose,
camera_params=camera_params, camera_pose=camera_pose,
block_colors=block_colors,
object_mask=object_mask, W=W, error_func=error_func,
bias=bias, scale=scale
)
errors[component_index, segment_index] = error
poses[component_index, segment_index] = pose
# Match components to segments by solving the linear sum assignment problem
# (ie data association)
_, component_poses, _ = matchComponentsToSegments(
errors, poses, downstream_objectives=None, greedy_assignment=False
)
# Render the complete final scene
rgb_render, depth_render, label_render = render.renderScene(
background_plane, assembly, component_poses,
camera_pose=camera_pose,
camera_params=camera_params,
object_appearances=block_colors
)
# Subtract background from all depth images. This gives distances relative
# to the background plane instead of the camera, so RGB and depth models
# are closer to the same scale.
depth_render = depth_render - depth_background
depth_image = depth_image - depth_background
# f, axes = plt.subplots(2, figsize=(10, 6), sharex=True)
# axes[0].hist(depth_image[depth_image != 0], bins=100)
# axes[0].set_ylabel('observed')
# axes[1].hist(depth_render[depth_render != 0], bins=100)
# axes[1].set_ylabel('rendered')
# plt.tight_layout()
# plt.show()
# Compute the total error of the final scene
image_background = segment_image == 0
render_background = label_render == 0
rgb_error = error_func(
rgb_image, rgb_render,
bias=bias[0], scale=scale[0],
true_mask=image_background, est_mask=render_background
)
depth_error = error_func(
depth_image, depth_render,
bias=bias[1], scale=scale[1],
true_mask=image_background, est_mask=render_background
)
error = np.array([rgb_error, depth_error]) @ W
# imageprocessing.displayImages(
# rgb_image, depth_image, segment_image,
# rgb_render, depth_render, label_render,
# num_rows=2
# )
return error, component_poses, (rgb_render, depth_render, label_render)
def matchComponentsToSegments(
objectives, poses, downstream_objectives=None, greedy_assignment=False):
"""
Parameters
----------
objectives : numpy array of float, shape (num_components, num_segments)
poses :
downstream_objectives : optional
greedy_assignment : bool, optional
Returns
-------
final_obj :
best_poses :
best_seg_idxs :
"""
if not objectives.any():
return None, (tuple(), tuple(), tuple()), tuple()
# linear_sum_assignment can't take an infinty-valued matrix, so set those
# greater than the max. That way they'll never be chosen by the routine.
non_inf_max = objectives[~np.isinf(objectives)].max()
objectives[np.isinf(objectives)] = non_inf_max + 1
num_components, num_segments = objectives.shape
if greedy_assignment:
row_ind = np.arange(num_components)
col_ind = objectives.argmin(axis=1)
else:
row_ind, col_ind = scipy.optimize.linear_sum_assignment(objectives)
if downstream_objectives is None:
final_obj = objectives[row_ind, col_ind].sum()
else:
final_obj = downstream_objectives[row_ind, col_ind].sum()
best_poses = [poses[r, c] for r, c in zip(row_ind, col_ind)]
best_seg_idxs = [c + 1 for c in col_ind]
num_unassigned_components = num_components - num_segments
for i in range(num_unassigned_components):
R = geometry.rotationMatrix(z_angle=0, x_angle=0)
t = np.zeros(3) + i * np.array([75, 0, 0])
best_poses.append((R, t))
best_seg_idxs.append(-1)
# argmaxima = (theta_best, t_best, seg_best)
if downstream_objectives is None:
return final_obj, best_poses, best_seg_idxs
# -=( PROBABLY GOING TO BE DEPRECATED )=---------------------------------------
def initModel(model_name, **model_kwargs):
model = getattr(this_module, model_name)
return model(**model_kwargs)
def train(model, labels, *feat_seqs, to_array=False, **train_kwargs):
"""
"""
# feat_seqs = tuple(utils.transposeSeq(fs)
# for fs in feat_seqs if fs is not None)
if to_array:
if labels is not None:
err_str = 'Not yet implemented for supervised models!'
raise ValueError(err_str)
feat_array = utils.toFlattenedFeatureArray(*feat_seqs)
model.fit(feat_array, **train_kwargs)
return model
model.fit(labels, *feat_seqs, **train_kwargs)
return model
def predict(model, *feat_seqs, to_array=False, **decode_kwargs):
"""
"""
# feat_seqs = tuple(
# utils.transposeSeq(fs) for fs in feat_seqs if fs is not None)
if to_array:
feat_array = utils.toFlattenedFeatureArray(*feat_seqs)
pred_seqs = model.predict(feat_array, **decode_kwargs)
return pred_seqs, None
pred_seqs, pred_idxs, unary_info = model.predict(
*feat_seqs, **decode_kwargs)
return pred_seqs, unary_info
class CliqueLatentVariables(object):
""" [] """
def __init__(self):
self.num_vertices = None
self.num_edges = None
def getStateIndex(self, state):
""" []
Parameters
----------
state : binary-valued numpy vector
[]
Returns
-------
index : int
Label index of the provided argument
"""
return utils.boolarray2int(state)
def getState(self, index):
return utils.int2boolarray(index, self.num_vertices)
def toFlattenedLabelIndexArray(self, label_seqs):
labels = [self.getStateIndex(l) for ls in label_seqs for l in ls]
return np.array(labels)
def toFlattenedLabelArray(self, label_seqs):
"""
Returns
-------
labels : np array, size [n_features, n_classes]
[]
"""
labels = tuple(np.squeeze(l) for ls in label_seqs for l in ls)
return np.row_stack(labels)
def toLabelIndexArray(self, label_seq):
labels = [self.getStateIndex(l) for l in label_seq]
return np.array(labels)
def toLabelIndexArrays(self, label_seqs):
return utils.iterate(self.toLabelIndexArray, label_seqs)
@property
def num_states(self):
return self.num_vertex_vals ** self.num_vertices
@property
def num_vertex_vals(self):
return 2
@property
def num_edge_vals(self):
return 2
def fit(self, state_seqs, *feat_seqs):
""" []
Parameters
----------
state_seqs : list of list of numpy array of shape [n_edges, n_edges]
[]
*feat_seqs : list of numpy array of shape [n_samples, n_dim]
[]
NOTE: state_seqs can actually contain anything iterable over the
number of samples. If it contains 2D numpy arrays, the array rows
must represent samples because numpy iterates over rows by default.
"""
self.num_vertices = state_seqs[0][0].shape[0]
self.num_edges = self.num_vertices * (self.num_vertices - 1) // 2
def countMagCorrs(corr, state, on=None, off=None):
if on is None:
on = []
if off is None:
off = []
edges = state.symmetrized_connections
idx_tups = itertools.combinations(range(8), 2)
for idx, (i, j) in enumerate(idx_tups):
if edges[i,j]:
on.append(corr[idx])
else:
off.append(corr[idx])
return off, on
def countMagCorrSeqs(corr_seqs, state_seqs):
on = []
off = []
for cseq, sseq in zip(corr_seqs, state_seqs):
for c, s in zip(cseq, sseq):
_ = countMagCorrs(c, s, on=on, off=off)
return np.array(off), np.array(on)
def stateLogLikelihood(
camera_params, camera_pose, block_colors,
observed, pixel_classes, segment_labels, state,
background_model,
viz_pose=False, hue_only=False,
mask_left_side=False, mask_bottom=False,
depth_image=None,
is_depth=False,
obsv_std=1,
greedy_assignment=False,
normalize_logl=False,
render_segment_template=False,
**optim_kwargs):
"""
Compute the best pose and its corresponding score.
Specifically,
best_pose = argmax_{pose} P( observed, pose | state )
best_score = log P( observed, best_pose | state )
Parameters
----------
camera_params :
camera_pose :
block_colors :
observed :
pixel_classes :
segment_labels :
state :
background_model :
viz_pose :
hue_only :
mask_left_side :
mask_bottom :
is_depth :
obsv_std :
greedy_assignment :
normalize_logl :
render_segment_template : bool, optional
If True, a template is rendered individually for each segment in
`segment_labels`. If False, a single template is used for all segments.
Default is False.
Returns
-------
final_logprob :
argmaxima :
"""
# Make copies so we don't modify the input
observed = observed.copy()
pixel_classes = pixel_classes.copy()
segment_labels = segment_labels.copy()
if depth_image is not None:
depth_image = depth_image.copy()
if hue_only:
# Colorspace conversion transforms can throw a divide-by-zero warning
# for images with zero-valued pixels, but we don't want to see them.
with warnings.catch_warnings():
warnings.filterwarnings("ignore", "divide by zero")
observed_hsv = imageprocessing.color.rgb2hsv(observed)
observed = imageprocessing.hueImgAsRgb(observed_hsv)
observed[segment_labels == 0] = 0
if mask_left_side or mask_bottom:
mask = np.zeros(pixel_classes.shape, dtype=bool)
mask = imageprocessing.maskOutsideBuildArea(
mask, mask_left_side=mask_left_side, mask_bottom=mask_bottom
)
observed[mask] = 0
pixel_classes[mask] = 0
segment_labels[mask] = 0
background_plane_img = None
if is_depth:
background_plane_img = render.renderPlane(background_model, observed.shape)
background_plane_img /= obsv_std
observed = observed.astype(float) / obsv_std
observed[segment_labels == 0] = background_plane_img[segment_labels == 0]
bboxes = imageprocessing.segmentBoundingBoxes(observed, segment_labels)
seg_arr_idxs = tuple(range(1, segment_labels.max() + 1))
if viz_pose:
obsv_bboxes = observed.copy()
num_components = len(state.connected_components)
num_segments = len(bboxes)
OBJECTIVES = np.zeros((num_components, num_segments))
unoccluded_pixels = pixel_classes != 1
TS = []
THETAS = []
TEMPLATES = []
if is_depth:
final_render = background_plane_img.copy()
img_type = 'depth'
else:
final_render = np.zeros_like(observed)
img_type = 'rgb'
for comp_arr_idx, comp_idx in enumerate(state.connected_components.keys()):
# Render a template
if not render_segment_template:
rendered = render.renderComponent(
state, comp_idx, img_type=img_type,
camera_pose=camera_pose, camera_params=camera_params,
block_colors=block_colors, obsv_std=obsv_std
)
TEMPLATES.append(rendered)
# Compute the template's gradient and center
rendered_grad_rows, rendered_grad_cols = imageprocessing.imgGradient(
rendered, sigma=1
)
rendered_center = imageprocessing.imageMidpoint(rendered.shape[0:2])
TS.append([])
THETAS.append([])
TEMPLATES.append([])
# Register the component template to each object proposal
for seg_arr_idx, seg_bounding_box in zip(seg_arr_idxs, bboxes):
if np.sum(segment_labels == seg_arr_idx) < 2:
TEMPLATES[-1].append(None)
TS[-1].append(None)
THETAS[-1].append(None)
OBJECTIVES[comp_arr_idx, seg_arr_idx - 1] = np.inf
continue
if render_segment_template:
pose_est = imageprocessing.estimateSegmentPose(
camera_params, camera_pose, depth_image, segment_labels == seg_arr_idx
)
rendered = render.renderComponent(
state, comp_idx, img_type=img_type,
component_pose=pose_est,
camera_pose=camera_pose, camera_params=camera_params,
block_colors=block_colors, obsv_std=obsv_std
)
# Compute the template's gradient and center
rendered_grad_rows, rendered_grad_cols = imageprocessing.imgGradient(
rendered, sigma=1
)
rendered_center = imageprocessing.imageMidpoint(rendered.shape[0:2])
if not rendered.any():
TEMPLATES[-1].append(None)
TS[-1].append(None)
THETAS[-1].append(None)
OBJECTIVES[comp_arr_idx, seg_arr_idx - 1] = np.inf
continue
TEMPLATES[-1].append(rendered)
t, theta = registerTemplateToSegment(
observed, rendered, seg_bounding_box, rendered_center,
rendered_grad_rows, rendered_grad_cols,
background_img=background_plane_img, **optim_kwargs
)
TS[-1].append(t)
THETAS[-1].append(theta)
obj = sse(
observed, rendered, theta, t, background_plane_img=None,
is_depth=False, unoccluded_pixels=None
)
OBJECTIVES[comp_arr_idx, seg_arr_idx - 1] = obj
if viz_pose:
perimeter = imageprocessing.rectangle_perimeter(*seg_bounding_box)
obsv_bboxes[perimeter] = 1
final_obj, argmaxima, TEMPLATES = matchComponentsToSegments(
OBJECTIVES, TS, THETAS, TEMPLATES,
greedy_assignment=greedy_assignment
)
final_render = render.makeFinalRender(
TEMPLATES, observed, argmaxima[0], argmaxima[1],
is_depth=is_depth, background_plane_img=background_plane_img
)
# FIXME: Turn this into a function call
residual_img = observed - final_render
final_obj = np.sum(residual_img[unoccluded_pixels] ** 2)
if normalize_logl:
num_samples = unoccluded_pixels.sum()
final_obj /= num_samples
if viz_pose:
imageprocessing.displayImages(obsv_bboxes, np.abs(residual_img), final_render)
if is_depth:
f, axes = plt.subplots(2, 1, figsize=(16, 8))
axes[0].hist(residual_img.ravel(), bins=100)
axes[1].hist(final_render.ravel(), bins=100)
plt.show()
return -final_obj, argmaxima
def templateMatchingResidual(observed, rendered, V, x, theta=None, background_img=None):
"""
Parameters
----------
Returns
-------
"""
if theta is None:
theta = int(x[:1])
t = x[1:]
else:
t = x
R = geometry.rotationMatrix(theta)
U = geometry.computePreimage(V, R, t)
U = imageprocessing.projectIntoImage(U, rendered.shape[0:2])
residue = residueVector(observed, rendered, V, U, background_image=background_img)
return residue.ravel()
def residueVector(
observed, rendered, pixel_coords_observed, pixel_coords_rendered,
background_image=None):
"""
Parameters
----------
observed :
rendered :
pixel_coords_observed :
pixel_coords_rendered :
Returns
-------
residue_vector :
"""
o_rows, o_cols = utils.splitColumns(pixel_coords_observed)
r_rows, r_cols = utils.splitColumns(pixel_coords_rendered)
observed_pixels = observed[o_rows, o_cols].copy()
rendered_pixels = rendered[r_rows, r_cols].copy()
if background_image is not None:
rendered_pixels += background_image[o_rows, o_cols]
residue_vector = observed_pixels.squeeze(axis=1) - rendered_pixels.squeeze(axis=1)
return residue_vector
def templateMatchingJacobian(I, T, grad_rendered_rows, grad_rendered_cols, V, x, theta=None):
"""
Parameters
----------
Returns
-------
"""
if theta is None:
theta = int(x[:1])
t = x[1:]
else:
t = x
R = geometry.rotationMatrix(theta)
U = geometry.computePreimage(V, R, t)
U = imageprocessing.projectIntoImage(U, T.shape[0:2])
Ur, Uc = utils.splitColumns(U)
dT_dtr = np.squeeze(grad_rendered_rows[Ur, Uc], axis=1)
dT_dtc = np.squeeze(grad_rendered_cols[Ur, Uc], axis=1)
if theta is not None:
return np.column_stack((dT_dtr.ravel(), dT_dtc.ravel()))
Ux, Uy = geometry.rc2xy(Ur, Uc, T.shape)
# Ttheta = -Uy * dT_dtc - Ux * dT_dtr
dR_dtheta = geometry.rDot(theta)
# Uxy = np.column_stack((Ux, Uy))
dT_dt = np.column_stack((grad_rendered_rows[Ur, Uc], grad_rendered_cols[Ur, Uc]))
stacked = np.stack((dT_dtr, dT_dtc), axis=2)
dT_dt = np.swapaxes(stacked, 1, 2)
dT_dtheta = np.zeros_like(dT_dtr)
for i in range(dT_dt.shape[2]):
dT_dtheta[:,i] = np.sum(dT_dt[:,:,i] * (V @ dR_dtheta.T), axis=1)
jacobian = np.column_stack((dT_dtheta.ravel(), dT_dtr.ravel(), dT_dtc.ravel()))
return jacobian
def optimizePose(
resid_func, jacobian_func, bound_func,
max_iters=25, min_theta=0, max_theta=360,
**lsq_kwargs):
""" Find the best pose (R, t) using a nonlinear least-squares objective.
Parameters
----------
resid_func : function
Residual function inside the least-square objective.
jacobian_func : function
Jacobian of the residual.
bound_func : function
Function that produces bound constraints for the translation parameter.
max_iters: int, optional
Number of samples to test when optimizing `theta`. Default is 25.
min_theta : float, optional
Minimum value of `theta` samples. Default is 0.
max_theta : float, optional
Maximum value of `theta` samples. Default is 360.
**lsq_kwargs : optional
Any extra arguments get passed through optimizeTranslation to
`scipy.optimize.least_squares`
Returns
-------
t_best :
theta_best :
obj_best :
"""
obj_best = np.inf
t_best = np.zeros(2)
theta_best = 0
obj_evals = 0
for theta in np.linspace(min_theta, max_theta, max_iters):
resid_func = functools.partial(resid_func, theta=theta)
jacobian_func = functools.partial(jacobian_func, theta=theta)
R = geometry.rotationMatrix(theta)
t_intervals = bound_func(R)
t_init = geometry.midpoint(*t_intervals)
t, obj, obj_evals = optimizeTranslation(
resid_func, jacobian_func, t_init, obj_evals,
**lsq_kwargs
)
t_in_bounds = geometry.sampleLiesInVolume(t, *t_intervals)
obj_decreased = obj < obj_best
if obj_decreased and t_in_bounds:
obj_best = obj
t_best = t
theta_best = theta
return t_best, theta_best, obj_best
def optimizeTranslation(resid_func, jacobian_func, t_init, obj_evals, **lsq_kwargs):
""" Find the best translation `t` using a nonlinear least-squares objective.
Parameters
----------
resid_func : function
Residual function inside the least-square objective.
jacobian_func : function
Jacobian of the residual.
t_init : numpy array of float, shape (3,)
Initial guess for the translation vector.
obj_evals : int
Number of objective evaluations made before calling this function.
**lsq_kwargs : optional
Any extra arguments get passed to `scipy.optimize.least_squares`.
Returns
-------
t_new :
obj_new :
obj_evals :
"""
result = scipy.optimize.least_squares(resid_func, t_init, jac=jacobian_func, **lsq_kwargs)
t_new = result.x
obj_new = result.cost
obj_evals += result.nfev
return t_new, obj_new, obj_evals
def makeInterval(bound1, bound2):
dim_min = min(bound1, bound2)
dim_max = max(bound1, bound2)
return (dim_min, dim_max)
def translationBoundConstraints(rendered_center, obs_ul, obs_lr, R):
""" Compute bound constraints for the translation vector.
This function is used while registering a template to an observed image
segment. While optimizing we want to add a constraint on the translation so
that, when the template is transformed, its center is guaranteed to fall
within the bounding box of the image segment. Otherwise the routine could
translate the template completely outsize the observed image, and end up at
a degenerate solution.
This function computes bound constraints that define the set of translations
which keep the template center within the segment's bounding box.
Parameters
----------
rendered_center :
obs_ul :
obs_lr :
R :
Returns
-------
dim_bounds :
"""
if obs_ul.shape != obs_lr.shape:
err_str = 'obs_ul shape {} != obs_lr shape {}'
raise ValueError(err_str.format(obs_ul.shape, obs_lr.shape))
t_min = obs_ul - R @ rendered_center
t_max = obs_lr - R @ rendered_center
num_dims = len(t_min)
dim_bounds = tuple(makeInterval(t_min[i], t_max[i]) for i in range(num_dims))
return dim_bounds
| 34.87664 | 100 | 0.621224 |
aceffbe7bd7cc39a9ac640588df23016dde6080d | 3,614 | py | Python | postgres/setup.py | michael-go/integrations-core | b094befc63a479e6496ad0d0c7bb340be63699fc | [
"BSD-3-Clause"
] | null | null | null | postgres/setup.py | michael-go/integrations-core | b094befc63a479e6496ad0d0c7bb340be63699fc | [
"BSD-3-Clause"
] | null | null | null | postgres/setup.py | michael-go/integrations-core | b094befc63a479e6496ad0d0c7bb340be63699fc | [
"BSD-3-Clause"
] | null | null | null | # Always prefer setuptools over distutils
from setuptools import setup
# To use a consistent encoding
from codecs import open
from os import path
import json
import re
here = path.abspath(path.dirname(__file__))
def parse_req_line(line):
line = line.strip()
if not line or line.startswith('--hash') or line[0] == '#':
return None
req = line.rpartition('#')
if len(req[1]) == 0:
line = req[2].strip()
else:
line = req[1].strip()
if '--hash=' in line:
line = line[:line.find('--hash=')].strip()
if ';' in line:
line = line[:line.find(';')].strip()
if '\\' in line:
line = line[:line.find('\\')].strip()
return line
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
# Parse requirements
runtime_reqs = ['datadog-checks-base']
with open(path.join(here, 'requirements.txt'), encoding='utf-8') as f:
for line in f.readlines():
req = parse_req_line(line)
if req:
runtime_reqs.append(req)
def read(*parts):
with open(path.join(here, *parts), 'r') as fp:
return fp.read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
# https://packaging.python.org/guides/single-sourcing-package-version/
version = find_version("datadog_checks", "postgres", "__init__.py")
manifest_version = None
with open(path.join(here, 'manifest.json'), encoding='utf-8') as f:
manifest = json.load(f)
manifest_version = manifest.get('version')
if version != manifest_version:
raise Exception("Inconsistent versioning in module and manifest - aborting wheel build")
setup(
name='datadog-postgres',
version=version,
description='The Postgres check',
long_description=long_description,
keywords='datadog agent postgres check',
# The project's main homepage.
url='https://github.com/DataDog/integrations-core',
# Author details
author='Datadog',
author_email='packages@datadoghq.com',
# License
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Topic :: System :: Monitoring',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
# The package we're going to ship
packages=['datadog_checks.postgres'],
# Run-time dependencies
install_requires=list(set(runtime_reqs)),
# Development dependencies, run with:
# $ pip install -e .[dev]
extras_require={
'dev': [
'check-manifest',
'datadog_agent_tk>=5.15',
],
},
# Testing setup and dependencies
tests_require=[
'nose',
'coverage',
'datadog_agent_tk>=5.15',
],
test_suite='nose.collector',
# Extra files to ship with the wheel package
package_data={b'datadog_checks.postgres': ['conf.yaml.example']},
include_package_data=True,
# The entrypoint to run the check manually without an agent
entry_points={
'console_scripts': [
'postgres=datadog_checks.postgres:main',
],
},
)
| 28.234375 | 92 | 0.63005 |
aceffd3264b22f0603249ebfdbcfc63df75dcfe9 | 10,550 | py | Python | src/ebay_rest/api/buy_order/models/pricing_summary_v2.py | matecsaj/ebay_rest | dd23236f39e05636eff222f99df1e3699ce47d4a | [
"MIT"
] | 3 | 2021-12-12T04:28:03.000Z | 2022-03-10T03:29:18.000Z | src/ebay_rest/api/buy_order/models/pricing_summary_v2.py | jdavv/ebay_rest | 20fc88c6aefdae9ab90f9c1330e79abddcd750cd | [
"MIT"
] | 33 | 2021-06-16T20:44:36.000Z | 2022-03-30T14:55:06.000Z | src/ebay_rest/api/buy_order/models/pricing_summary_v2.py | jdavv/ebay_rest | 20fc88c6aefdae9ab90f9c1330e79abddcd750cd | [
"MIT"
] | 7 | 2021-06-03T09:30:23.000Z | 2022-03-08T19:51:33.000Z | # coding: utf-8
"""
Order API
<span class=\"tablenote\"><b>Note:</b> This version of the Order API (v2) currently only supports the guest payment flow for eBay managed payments. To view the v1_beta version of the Order API, which includes both member and guest checkout payment flows, refer to the <a href=\"/api-docs/buy/order_v1/resources/methods\">Order_v1 API</a> documentation.</span><br /><br /><span class=\"tablenote\"><b>Note:</b> This is a <a href=\"https://developer.ebay.com/api-docs/static/versioning.html#limited\" target=\"_blank\"><img src=\"/cms/img/docs/partners-api.svg\" class=\"legend-icon partners-icon\" alt=\"Limited Release\" title=\"Limited Release\" />(Limited Release)</a> API available only to select developers approved by business units.</span><br /><br />The Order API provides interfaces that let shoppers pay for items. It also returns payment and shipping status of the order. # noqa: E501
OpenAPI spec version: v2.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class PricingSummaryV2(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'additional_savings': 'Amount',
'adjustment': 'Adjustment',
'delivery_cost': 'Amount',
'fee': 'Amount',
'import_charges': 'Amount',
'import_tax': 'ImportTax',
'price_discount': 'Amount',
'price_subtotal': 'Amount',
'tax': 'Amount',
'total': 'Amount'
}
attribute_map = {
'additional_savings': 'additionalSavings',
'adjustment': 'adjustment',
'delivery_cost': 'deliveryCost',
'fee': 'fee',
'import_charges': 'importCharges',
'import_tax': 'importTax',
'price_discount': 'priceDiscount',
'price_subtotal': 'priceSubtotal',
'tax': 'tax',
'total': 'total'
}
def __init__(self, additional_savings=None, adjustment=None, delivery_cost=None, fee=None, import_charges=None, import_tax=None, price_discount=None, price_subtotal=None, tax=None, total=None): # noqa: E501
"""PricingSummaryV2 - a model defined in Swagger""" # noqa: E501
self._additional_savings = None
self._adjustment = None
self._delivery_cost = None
self._fee = None
self._import_charges = None
self._import_tax = None
self._price_discount = None
self._price_subtotal = None
self._tax = None
self._total = None
self.discriminator = None
if additional_savings is not None:
self.additional_savings = additional_savings
if adjustment is not None:
self.adjustment = adjustment
if delivery_cost is not None:
self.delivery_cost = delivery_cost
if fee is not None:
self.fee = fee
if import_charges is not None:
self.import_charges = import_charges
if import_tax is not None:
self.import_tax = import_tax
if price_discount is not None:
self.price_discount = price_discount
if price_subtotal is not None:
self.price_subtotal = price_subtotal
if tax is not None:
self.tax = tax
if total is not None:
self.total = total
@property
def additional_savings(self):
"""Gets the additional_savings of this PricingSummaryV2. # noqa: E501
:return: The additional_savings of this PricingSummaryV2. # noqa: E501
:rtype: Amount
"""
return self._additional_savings
@additional_savings.setter
def additional_savings(self, additional_savings):
"""Sets the additional_savings of this PricingSummaryV2.
:param additional_savings: The additional_savings of this PricingSummaryV2. # noqa: E501
:type: Amount
"""
self._additional_savings = additional_savings
@property
def adjustment(self):
"""Gets the adjustment of this PricingSummaryV2. # noqa: E501
:return: The adjustment of this PricingSummaryV2. # noqa: E501
:rtype: Adjustment
"""
return self._adjustment
@adjustment.setter
def adjustment(self, adjustment):
"""Sets the adjustment of this PricingSummaryV2.
:param adjustment: The adjustment of this PricingSummaryV2. # noqa: E501
:type: Adjustment
"""
self._adjustment = adjustment
@property
def delivery_cost(self):
"""Gets the delivery_cost of this PricingSummaryV2. # noqa: E501
:return: The delivery_cost of this PricingSummaryV2. # noqa: E501
:rtype: Amount
"""
return self._delivery_cost
@delivery_cost.setter
def delivery_cost(self, delivery_cost):
"""Sets the delivery_cost of this PricingSummaryV2.
:param delivery_cost: The delivery_cost of this PricingSummaryV2. # noqa: E501
:type: Amount
"""
self._delivery_cost = delivery_cost
@property
def fee(self):
"""Gets the fee of this PricingSummaryV2. # noqa: E501
:return: The fee of this PricingSummaryV2. # noqa: E501
:rtype: Amount
"""
return self._fee
@fee.setter
def fee(self, fee):
"""Sets the fee of this PricingSummaryV2.
:param fee: The fee of this PricingSummaryV2. # noqa: E501
:type: Amount
"""
self._fee = fee
@property
def import_charges(self):
"""Gets the import_charges of this PricingSummaryV2. # noqa: E501
:return: The import_charges of this PricingSummaryV2. # noqa: E501
:rtype: Amount
"""
return self._import_charges
@import_charges.setter
def import_charges(self, import_charges):
"""Sets the import_charges of this PricingSummaryV2.
:param import_charges: The import_charges of this PricingSummaryV2. # noqa: E501
:type: Amount
"""
self._import_charges = import_charges
@property
def import_tax(self):
"""Gets the import_tax of this PricingSummaryV2. # noqa: E501
:return: The import_tax of this PricingSummaryV2. # noqa: E501
:rtype: ImportTax
"""
return self._import_tax
@import_tax.setter
def import_tax(self, import_tax):
"""Sets the import_tax of this PricingSummaryV2.
:param import_tax: The import_tax of this PricingSummaryV2. # noqa: E501
:type: ImportTax
"""
self._import_tax = import_tax
@property
def price_discount(self):
"""Gets the price_discount of this PricingSummaryV2. # noqa: E501
:return: The price_discount of this PricingSummaryV2. # noqa: E501
:rtype: Amount
"""
return self._price_discount
@price_discount.setter
def price_discount(self, price_discount):
"""Sets the price_discount of this PricingSummaryV2.
:param price_discount: The price_discount of this PricingSummaryV2. # noqa: E501
:type: Amount
"""
self._price_discount = price_discount
@property
def price_subtotal(self):
"""Gets the price_subtotal of this PricingSummaryV2. # noqa: E501
:return: The price_subtotal of this PricingSummaryV2. # noqa: E501
:rtype: Amount
"""
return self._price_subtotal
@price_subtotal.setter
def price_subtotal(self, price_subtotal):
"""Sets the price_subtotal of this PricingSummaryV2.
:param price_subtotal: The price_subtotal of this PricingSummaryV2. # noqa: E501
:type: Amount
"""
self._price_subtotal = price_subtotal
@property
def tax(self):
"""Gets the tax of this PricingSummaryV2. # noqa: E501
:return: The tax of this PricingSummaryV2. # noqa: E501
:rtype: Amount
"""
return self._tax
@tax.setter
def tax(self, tax):
"""Sets the tax of this PricingSummaryV2.
:param tax: The tax of this PricingSummaryV2. # noqa: E501
:type: Amount
"""
self._tax = tax
@property
def total(self):
"""Gets the total of this PricingSummaryV2. # noqa: E501
:return: The total of this PricingSummaryV2. # noqa: E501
:rtype: Amount
"""
return self._total
@total.setter
def total(self, total):
"""Sets the total of this PricingSummaryV2.
:param total: The total of this PricingSummaryV2. # noqa: E501
:type: Amount
"""
self._total = total
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(PricingSummaryV2, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PricingSummaryV2):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 30.57971 | 900 | 0.611754 |
aceffd373af18ee55d4c3f3ecb44c5307a99fc0c | 70,897 | py | Python | tensorflow/python/ops/variable_scope.py | salonirk11/tensorflow | 7fda1bb1177c69fa7bf80d20d5c5e7aaa25816e7 | [
"Apache-2.0"
] | 5 | 2019-01-17T08:47:31.000Z | 2020-05-06T06:10:56.000Z | tensorflow/python/ops/variable_scope.py | salonirk11/tensorflow | 7fda1bb1177c69fa7bf80d20d5c5e7aaa25816e7 | [
"Apache-2.0"
] | null | null | null | tensorflow/python/ops/variable_scope.py | salonirk11/tensorflow | 7fda1bb1177c69fa7bf80d20d5c5e7aaa25816e7 | [
"Apache-2.0"
] | 3 | 2017-06-09T10:39:33.000Z | 2021-04-08T16:13:30.000Z | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""A class to store named variables and a scope operator to manage sharing."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections as collections_lib
import copy
import functools
import traceback
import six
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import tf_contextlib
__all__ = ["VariableScope", "get_variable_scope",
"get_variable", "get_local_variable", "variable_scope",
"variable_op_scope", "no_regularizer"]
class _PartitionInfo(object):
"""Holds partition info used by initializer functions.
"""
def __init__(self, full_shape, var_offset):
"""Constructor.
Args:
full_shape: Tuple or list of `int` indicating the full combined shape
of the partitioned variables.
var_offset: Tuple or list of `int` specifying offset of this partition
with respect to the full variable for each dimension.
Raises:
TypeError: If `full_shape` or `var_offset` is not a sequence.
ValueError: If `full_shape` or `var_offset` differ in length. If
`var_offset` exceeds `full_shape` in any dimension.
"""
if not isinstance(full_shape, collections_lib.Sequence) or isinstance(
full_shape, six.string_types):
raise TypeError(
"`full_shape` must be a sequence (like tuple or list) instead of " +
type(full_shape).__name__)
if not isinstance(var_offset, collections_lib.Sequence) or isinstance(
var_offset, six.string_types):
raise TypeError(
"`var_offset` must be a sequence (like tuple or list) instead of " +
type(var_offset).__name__)
if len(var_offset) != len(full_shape):
raise ValueError(
"Expected equal length, but `var_offset` is of length {} while "
"full_shape is of length {}.".format(
len(var_offset), len(full_shape)))
for i in xrange(len(full_shape)):
offset = var_offset[i]
shape = full_shape[i]
if offset < 0 or offset >= shape:
raise ValueError(
"Expected 0 <= offset < shape but found offset={}, shape={} for "
"var_offset={}, full_shape={}".format(offset, shape, var_offset,
full_shape))
self._full_shape = full_shape
self._var_offset = var_offset
@property
def full_shape(self):
return self._full_shape
@property
def var_offset(self):
return self._var_offset
def single_offset(self, shape):
"""Returns the offset when the variable is partitioned in at most one dim.
Args:
shape: Tuple or list of `int` indicating the shape of one specific
variable partition.
Returns:
`int` representing the offset in the dimension along which the variable is
partitioned. Returns 0 if the variable is not being partitioned.
Raises:
ValueError: Depending on self.single_slice_dim().
"""
single_slice_dim = self.single_slice_dim(shape)
# If this variable is not being partitioned at all, single_slice_dim() could
# return None.
if single_slice_dim is None:
return 0
return self.var_offset[single_slice_dim]
def single_slice_dim(self, shape):
"""Returns the slice dim when the variable is partitioned only in one dim.
Args:
shape: Tuple or list of `int` indicating the shape of one specific
variable partition.
Returns:
`int` representing the dimension that the variable is partitioned in, or
`None` if the variable doesn't seem to be partitioned at all.
Raises:
TypeError: If `shape` is not a sequence.
ValueError: If `shape` is not the same length as `self.full_shape`. If
the variable is partitioned in more than one dimension.
"""
if not isinstance(shape, collections_lib.Sequence) or isinstance(
shape, six.string_types):
raise TypeError(
"`shape` must be a sequence (like tuple or list) instead of " +
type(shape).__name__)
if len(shape) != len(self.full_shape):
raise ValueError(
"Expected equal length, but received shape={} of length {} while "
"self.full_shape={} is of length {}.".format(shape, len(
shape), self.full_shape, len(self.full_shape)))
for i in xrange(len(shape)):
if self.var_offset[i] + shape[i] > self.full_shape[i]:
raise ValueError(
"With self.var_offset={}, a partition of shape={} would exceed "
"self.full_shape={} in dimension {}.".format(
self.var_offset, shape, self.full_shape, i))
slice_dim = None
for i in xrange(len(shape)):
if shape[i] == self.full_shape[i]:
continue
if slice_dim is not None:
raise ValueError(
"Cannot use single_slice_dim() with shape={} and "
"self.full_shape={} since slice dim could be either dimension {} "
"or {}.".format(shape, self.full_shape, i, slice_dim))
slice_dim = i
return slice_dim
class _VariableStore(object):
"""Variable store that carries a number of named Variables.
New variable names and new variables can be created; all stored
variables are initialized with the initializer passed to __init__.
Attributes:
vars: a dictionary with string names (same as passed in GetVar) as keys
and the corresponding TensorFlow Variables as values.
"""
def __init__(self):
"""Create a variable store."""
self._vars = {} # A dictionary of the stored TensorFlow variables.
self._partitioned_vars = {} # A dict of the stored PartitionedVariables.
self.variable_scopes_count = {} # Count re-used variable scopes.
def open_variable_scope(self, scope_name):
if scope_name in self.variable_scopes_count:
self.variable_scopes_count[scope_name] += 1
else:
self.variable_scopes_count[scope_name] = 1
def close_variable_subscopes(self, scope_name):
for k in self.variable_scopes_count:
if not scope_name or k.startswith(scope_name + "/"):
self.variable_scopes_count[k] = 0
def variable_scope_count(self, scope_name):
return self.variable_scopes_count.get(scope_name, 0)
def get_variable(self, name, shape=None, dtype=dtypes.float32,
initializer=None, regularizer=None, reuse=None,
trainable=True, collections=None, caching_device=None,
partitioner=None, validate_shape=True, use_resource=None,
custom_getter=None):
"""Gets an existing variable with these parameters or create a new one.
If a variable with the given name is already stored, we return the stored
variable. Otherwise, we create a new one.
Set `reuse` to `True` when you only want to reuse existing Variables.
Set `reuse` to `False` when you only want to create new Variables.
If `reuse` is `None` (the default), both new and existing variables are
returned.
If initializer is `None` (the default), the default initializer passed in
the constructor is used. If that one is `None` too, we use a new
`glorot_uniform_initializer`. If initializer is a Tensor, we use
it as a value and derive the shape from the initializer.
If a partitioner is provided, a `PartitionedVariable` is returned.
Accessing this object as a `Tensor` returns the shards concatenated along
the partition axis.
Some useful partitioners are available. See, e.g.,
`variable_axis_size_partitioner` and `min_max_variable_partitioner`.
Args:
name: The name of the new or existing variable.
shape: Shape of the new or existing variable.
dtype: Type of the new or existing variable (defaults to `DT_FLOAT`).
initializer: Initializer for the variable.
regularizer: A (Tensor -> Tensor or None) function; the result of
applying it on a newly created variable will be added to the collection
GraphKeys.REGULARIZATION_LOSSES and can be used for regularization.
reuse: a Boolean or `None`. Controls reuse or creation of variables.
trainable: If `True` also add the variable to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).
collections: List of graph collections keys to add the `Variable` to.
Defaults to `[GraphKeys.GLOBAL_VARIABLES]` (see `tf.Variable`).
caching_device: Optional device string or function describing where the
Variable should be cached for reading. Defaults to the Variable's
device. If not `None`, caches on another device. Typical use is to
cache on the device where the Ops using the `Variable` reside, to
deduplicate copying through `Switch` and other conditional statements.
partitioner: Optional callable that accepts a fully defined `TensorShape`
and dtype of the `Variable` to be created, and returns a list of
partitions for each axis (currently only one axis can be partitioned).
validate_shape: If False, allows the variable to be initialized with a
value of unknown shape. If True, the default, the shape of initial_value
must be known.
use_resource: If False, creates a regular Variable. If True, creates
instead an experimental ResourceVariable which has well-defined
semantics. Defaults to False (will later change to True).
custom_getter: Callable that takes as a first argument the true getter,
and allows overwriting the internal get_variable method.
The signature of `custom_getter` should match that of this method,
but the most future-proof version will allow for changes:
`def custom_getter(getter, *args, **kwargs)`. Direct access to
all `get_variable` parameters is also allowed:
`def custom_getter(getter, name, *args, **kwargs)`. A simple identity
custom getter that simply creates variables with modified names is:
```python
def custom_getter(getter, name, *args, **kwargs):
return getter(name + '_suffix', *args, **kwargs)
```
Returns:
The created or existing `Variable` (or `PartitionedVariable`, if a
partitioner was used).
Raises:
ValueError: when creating a new variable and shape is not declared,
when reusing a variable and specifying a conflicting shape,
or when violating reuse during variable creation.
"""
if custom_getter is not None and not callable(custom_getter):
raise ValueError(
"Passed a custom_getter which is not callable: %s" % custom_getter)
# If a *_ref type is passed in an error would be triggered further down the
# stack. We prevent this using base_dtype to get a non-ref version of the
# type, before doing anything else. When _ref types are removed in favor of
# resources, this line can be removed.
try:
dtype = dtype.base_dtype
except AttributeError:
# .base_dtype not existing means that we will try and use the raw dtype
# which was passed in - this might be a NumPy type which is valid.
pass
# This is the main logic of get_variable. However, custom_getter
# may override this logic. So we save it as a callable and pass
# it to custom_getter.
# Note: the parameters of _true_getter, and their documentation, match
# *exactly* item-for-item with the docstring of this method.
def _true_getter(name, shape=None, dtype=dtypes.float32, # pylint: disable=missing-docstring
initializer=None, regularizer=None, reuse=None,
trainable=True, collections=None, caching_device=None,
partitioner=None, validate_shape=True, use_resource=None):
is_scalar = shape is not None and not shape
# Partitioned variable case
if partitioner is not None and not is_scalar:
if not callable(partitioner):
raise ValueError(
"Partitioner must be callable, but received: %s" % partitioner)
with ops.name_scope(None):
return self._get_partitioned_variable(name=name,
shape=shape,
dtype=dtype,
initializer=initializer,
regularizer=regularizer,
reuse=reuse,
trainable=trainable,
collections=collections,
caching_device=caching_device,
partitioner=partitioner,
validate_shape=validate_shape,
use_resource=use_resource)
# Special case for partitioned variable to allow reuse without having to
# specify partitioner.
if (reuse is True and partitioner is None
and name in self._partitioned_vars):
return self._get_partitioned_variable(name=name,
shape=shape,
dtype=dtype,
initializer=initializer,
regularizer=regularizer,
reuse=reuse,
trainable=trainable,
collections=collections,
caching_device=caching_device,
partitioner=None,
validate_shape=validate_shape,
use_resource=use_resource)
# Single variable case
if "%s/part_0" % name in self._vars:
raise ValueError(
"No partitioner was provided, but a partitioned version of the "
"variable was found: %s/part_0. Perhaps a variable of the same "
"name was already created with partitioning?" % name)
return self._get_single_variable(
name=name, shape=shape, dtype=dtype,
initializer=initializer, regularizer=regularizer, reuse=reuse,
trainable=trainable, collections=collections,
caching_device=caching_device, validate_shape=validate_shape,
use_resource=use_resource)
if custom_getter is not None:
return custom_getter(
getter=_true_getter, name=name, shape=shape, dtype=dtype,
initializer=initializer, regularizer=regularizer,
reuse=reuse, trainable=trainable, collections=collections,
caching_device=caching_device, partitioner=partitioner,
validate_shape=validate_shape, use_resource=use_resource)
else:
return _true_getter(
name, shape=shape, dtype=dtype,
initializer=initializer, regularizer=regularizer,
reuse=reuse, trainable=trainable, collections=collections,
caching_device=caching_device, partitioner=partitioner,
validate_shape=validate_shape, use_resource=use_resource)
def _get_partitioned_variable(
self, name, partitioner, shape=None, dtype=dtypes.float32,
initializer=None, regularizer=None, reuse=None,
trainable=True, collections=None, caching_device=None,
validate_shape=True, use_resource=None):
"""Gets or creates a sharded variable list with these parameters.
The `partitioner` must be a callable that accepts a fully defined
`TensorShape` and returns a sequence of integers (the `partitions`).
These integers describe how to partition the given sharded `Variable`
along the given dimension. That is, `partitions[1] = 3` means split
the `Variable` into 3 shards along dimension 1. Currently, sharding along
only one axis is supported.
If the list of variables with the given name (prefix) is already stored,
we return the stored variables. Otherwise, we create a new one.
Set `reuse` to `True` when you only want to reuse existing Variables.
Set `reuse` to `False` when you only want to create new Variables.
If `reuse` is `None` (the default), both new and existing variables are
returned.
If initializer is `None` (the default), the default initializer passed in
the constructor is used. If that one is `None` too, we use a new
`glorot_uniform_initializer`. If initializer is a Tensor, we use
it as a value and derive the shape from the initializer.
If the initializer is a callable, then it will be called for each
shard. Otherwise the initializer should match the shape of the entire
sharded Variable, and it will be sliced accordingly for each shard.
Some useful partitioners are available. See, e.g.,
`variable_axis_size_partitioner` and `min_max_variable_partitioner`.
Args:
name: the name of the new or existing sharded variable.
partitioner: Optional callable that accepts a fully defined `TensorShape`
and `dtype` of the Variable to be created, and returns a list of
partitions for each axis (currently only one axis can be partitioned).
shape: shape of the new or existing sharded variable.
dtype: type of the new or existing sharded variable
(defaults to `DT_FLOAT`).
initializer: initializer for the sharded variable.
regularizer: a (Tensor -> Tensor or None) function; the result of
applying it on a newly created variable will be added to the collection
GraphKeys.REGULARIZATION_LOSSES and can be used for regularization.
reuse: a Boolean or `None`. Controls reuse or creation of variables.
trainable: If `True` also add the variable to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).
collections: List of graph collections keys to add the Variable to.
Defaults to `[GraphKeys.GLOBAL_VARIABLES]` (see `tf.Variable`).
caching_device: Optional device string or function describing where the
Variable should be cached for reading. Defaults to the Variable's
device. If not `None`, caches on another device. Typical use is to
cache on the device where the Ops using the Variable reside, to
deduplicate copying through `Switch` and other conditional statements.
validate_shape: If False, allows the variable to be initialized with a
value of unknown shape. If True, the default, the shape of initial_value
must be known.
use_resource: If False, creates a regular Variable. If True, creates an
experimental ResourceVariable which has well-defined semantics. Defaults
to False (will later change to True).
Returns:
A `PartitionedVariable` object.
Raises:
ValueError: when creating a new variable and shape is not declared,
when reusing a variable and specifying a conflicting shape,
when violating reuse during variable creation, or if an existing
sharded variable exists for the given name but with different sharding.
"""
initializing_from_value = initializer is not None and isinstance(
initializer, ops.Tensor)
reuse_without_partition = reuse is True and partitioner is None
if name in self._vars:
raise ValueError(
"A partitioner was provided, but an unpartitioned version of the "
"variable was found: %s. Perhaps a variable of the same name was "
"already created without partitioning?" % name)
shape = tensor_shape.as_shape(shape)
if initializing_from_value:
shape = shape.merge_with(initializer.get_shape())
if not reuse_without_partition:
if not shape.is_fully_defined():
raise ValueError("Shape of a new partitioned variable (%s) must be "
"fully defined, but instead was %s." % (name, shape))
if shape.ndims < 1:
raise ValueError("A partitioned Variable must have rank at least 1, "
"shape: %s" % shape)
partitions = partitioner(shape=shape, dtype=dtype)
if not isinstance(partitions, collections_lib.Sequence):
raise ValueError("Partitioner must return a sequence, but saw: %s"
% partitions)
if len(partitions) != shape.ndims:
raise ValueError(
"Partitioner returned a partition list that does not match the "
"Variable's rank: %s vs. %s" % (partitions, shape))
if any([p < 1 for p in partitions]):
raise ValueError(
"Partitioner returned zero partitions for some axes: %s" %
partitions)
should_check = reuse is not None
if name in self._partitioned_vars:
if should_check and not reuse:
raise ValueError(
"Partitioned variable with name %s already exists. Did you mean to "
"set reuse=True in VarScope?"
% name)
existing_var = self._partitioned_vars[name]
if not shape.is_compatible_with(existing_var.get_shape()):
raise ValueError(
"Trying to reuse partitioned variable %s, but specified shape %s "
"and found shape %s."
% (name, shape, existing_var.get_shape()))
if not dtype.is_compatible_with(existing_var.dtype):
raise ValueError(
"Trying to reuse partitioned variable %s, but specified dtype %s "
"and found dtype %s."
% (name, dtype.name, existing_var.dtype.name))
# pylint: disable=protected-access
if (not reuse_without_partition and
existing_var._get_partitions() != partitions):
raise ValueError(
"Trying to reuse partitioned variable %s, but specified partitions "
"%s and found partitions %s." %
(name, partitions, existing_var._get_partitions()))
# pylint: enable=protected-access
return existing_var
if should_check and reuse:
raise ValueError("PartitionedVariable %s does not exist, or was not "
"created with tf.get_variable(). Did you mean to set "
"reuse=None in VarScope?" % name)
slice_dim, slice_shape = _compute_slice_dim_and_shape(
shape.as_list(), partitions)
vs = []
num_slices = partitions[slice_dim]
num_slices_with_excess = shape[slice_dim].value % num_slices
slice_offset = [0] * shape.ndims
if "%s/part_0" % name in self._vars:
if "%s/part_%d" % (name, num_slices - 1) not in self._vars:
raise ValueError(
"Partitioner returned a different partitioning than what was "
"already found. Partitioner returned %d shards, and shard "
"%s/part_0 was found, but %s/part_%d was not."
% (num_slices, name, name, num_slices - 1))
if "%s/part_%d" % (name, num_slices) in self._vars:
raise ValueError(
"Partitioner returned a different partitioning than what was "
"already found. Partitioner returned %d shards, and shard "
"%s/part_0 was found, but so was the extra shard %s/part_%d."
% (num_slices, name, name, num_slices))
for i in xrange(num_slices):
var_shape = slice_shape[:]
var_offset = slice_offset[:]
partition_info = _PartitionInfo(
full_shape=shape.as_list(), var_offset=var_offset)
if i < num_slices_with_excess:
var_shape[slice_dim] += 1
slice_offset[slice_dim] += var_shape[slice_dim]
var_full_name = "%s/part_%d" % (name, i)
with ops.name_scope(var_full_name + "/PartitionedInitializer"):
# Create the tensor to initialize the variable with default value.
if initializer is None:
init, initializing_from_value = self._get_default_initializer(
name=name, shape=shape, dtype=dtype)
if initializing_from_value:
init_shape = None
else:
init_shape = var_shape
elif callable(initializer):
init = initializer
init_shape = var_shape
elif isinstance(initializer, ops.Tensor):
init = array_ops.slice(initializer, var_offset, var_shape)
# Use the dtype of the given tensor.
dtype = init.dtype.base_dtype
init_shape = None
else:
init = ops.convert_to_tensor(initializer, dtype=dtype)
init = array_ops.slice(init, var_offset, var_shape)
init_shape = None
with ops.name_scope(None):
var = self._get_single_variable(
name=var_full_name,
shape=init_shape,
dtype=dtype,
initializer=init,
partition_info=partition_info,
regularizer=regularizer,
reuse=reuse,
trainable=trainable,
collections=collections,
caching_device=caching_device,
validate_shape=validate_shape,
use_resource=use_resource)
# pylint: disable=protected-access
var._set_save_slice_info(variables.Variable.SaveSliceInfo(
name, shape.as_list(), var_offset, var_shape))
vs.append(var)
# pylint: enable=protected-access
# pylint: disable=protected-access
partitioned_var = variables.PartitionedVariable(name=name,
shape=shape,
dtype=dtype,
variable_list=vs,
partitions=partitions)
# pylint: enable=protected-access
self._partitioned_vars[name] = partitioned_var
return partitioned_var
def _get_single_variable(self,
name,
shape=None,
dtype=dtypes.float32,
initializer=None,
regularizer=None,
partition_info=None,
reuse=None,
trainable=True,
collections=None,
caching_device=None,
validate_shape=True,
use_resource=None,):
"""Get or create a single Variable (e.g. a shard or entire variable).
See the documentation of get_variable above (ignore partitioning components)
for details.
Args:
name: see get_variable.
shape: see get_variable.
dtype: see get_variable.
initializer: see get_variable.
regularizer: see get_variable.
partition_info: _PartitionInfo object.
reuse: see get_variable.
trainable: see get_variable.
collections: see get_variable.
caching_device: see get_variable.
validate_shape: see get_variable.
use_resource: see get_variable.
Returns:
A Variable. See documentation of get_variable above.
Raises:
ValueError: See documentation of get_variable above.
"""
# Set to true if initializer is a constant.
initializing_from_value = False
if initializer is not None and not callable(initializer):
initializing_from_value = True
if shape is not None and initializing_from_value:
raise ValueError("If initializer is a constant, do not specify shape.")
should_check = reuse is not None
dtype = dtypes.as_dtype(dtype)
shape = tensor_shape.as_shape(shape)
if name in self._vars:
# Here we handle the case when returning an existing variable.
if should_check and not reuse:
tb = self._vars[name].op.traceback[::-1]
# Throw away internal tf entries and only take a few lines.
tb = [x for x in tb if "tensorflow/python" not in x[0]][:3]
raise ValueError("Variable %s already exists, disallowed."
" Did you mean to set reuse=True in VarScope? "
"Originally defined at:\n\n%s" % (
name, "".join(traceback.format_list(tb))))
found_var = self._vars[name]
if not shape.is_compatible_with(found_var.get_shape()):
raise ValueError("Trying to share variable %s, but specified shape %s"
" and found shape %s." % (name, shape,
found_var.get_shape()))
if not dtype.is_compatible_with(found_var.dtype):
dtype_str = dtype.name
found_type_str = found_var.dtype.name
raise ValueError("Trying to share variable %s, but specified dtype %s"
" and found dtype %s." % (name, dtype_str,
found_type_str))
return found_var
# The code below handles only the case of creating a new variable.
if should_check and reuse:
raise ValueError("Variable %s does not exist, or was not created with "
"tf.get_variable(). Did you mean to set reuse=None in "
"VarScope?" % name)
if not shape.is_fully_defined() and not initializing_from_value:
raise ValueError("Shape of a new variable (%s) must be fully defined, "
"but instead was %s." % (name, shape))
# Create the tensor to initialize the variable with default value.
if initializer is None:
initializer, initializing_from_value = self._get_default_initializer(
name=name, shape=shape, dtype=dtype)
# Clear control dependencies while creating the initializer.
with ops.control_dependencies(None):
if initializing_from_value:
init_val = initializer
variable_dtype = None
else:
# Instantiate initializer if provided initializer is a type object.
if isinstance(initializer, type(init_ops.Initializer)):
initializer = initializer(dtype=dtype)
init_val = lambda: initializer( # pylint: disable=g-long-lambda
shape.as_list(), dtype=dtype, partition_info=partition_info)
variable_dtype = dtype.base_dtype
# Create the variable.
if use_resource is None:
# Set the default value if unspecified.
use_resource = False
if use_resource:
v = resource_variable_ops.ResourceVariable(
initial_value=init_val,
name=name,
trainable=trainable,
collections=collections,
caching_device=caching_device,
dtype=variable_dtype,
validate_shape=validate_shape)
else:
v = variables.Variable(
initial_value=init_val,
name=name,
trainable=trainable,
collections=collections,
caching_device=caching_device,
dtype=variable_dtype,
validate_shape=validate_shape)
self._vars[name] = v
logging.vlog(1, "Created variable %s with shape %s and init %s", v.name,
format(shape), initializer)
# Run the regularizer if requested and save the resulting loss.
if regularizer:
with ops.colocate_with(v.op):
with ops.name_scope(name + "/Regularizer/"):
loss = regularizer(v)
if loss is not None:
logging.vlog(1, "Applied regularizer to %s and added the result %s "
"to REGULARIZATION_LOSSES.", v.name, loss.name)
ops.add_to_collection(ops.GraphKeys.REGULARIZATION_LOSSES, loss)
return v
# Initialize variable when no initializer provided
def _get_default_initializer(self, name, shape=None, dtype=dtypes.float32):
"""Provide a default initializer and a corresponding value.
Args:
name: see get_variable.
shape: see get_variable.
dtype: see get_variable.
Returns:
initializer and initializing_from_value. See get_variable above.
Raises:
ValueError: When giving unsupported dtype.
"""
# If dtype is DT_FLOAT, provide a uniform unit scaling initializer
if dtype.is_floating:
initializer = init_ops.glorot_uniform_initializer()
initializing_from_value = False
# If dtype is DT_INT/DT_UINT, provide a default value `zero`
# If dtype is DT_BOOL, provide a default value `FALSE`
elif dtype.is_integer or dtype.is_unsigned or dtype.is_bool:
initializer = init_ops.zeros_initializer()(
shape=shape, dtype=dtype.base_dtype)
initializing_from_value = True
# NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX here?
else:
raise ValueError("An initializer for variable %s of %s is required"
% (name, dtype.base_dtype))
return initializer, initializing_from_value
# To stop regularization, use this regularizer
def no_regularizer(_):
"""Use this function to prevent regularization of variables."""
return None
class VariableScope(object):
"""Variable scope object to carry defaults to provide to `get_variable`.
Many of the arguments we need for `get_variable` in a variable store are most
easily handled with a context. This object is used for the defaults.
Attributes:
name: name of the current scope, used as prefix in get_variable.
initializer: default initializer passed to get_variable.
regularizer: default regularizer passed to get_variable.
reuse: Boolean or None, setting the reuse in get_variable.
caching_device: string, callable, or None: the caching device passed to
get_variable.
partitioner: callable or `None`: the partitioner passed to `get_variable`.
custom_getter: default custom getter passed to get_variable.
name_scope: The name passed to `tf.name_scope`.
dtype: default type passed to get_variable (defaults to DT_FLOAT).
use_resource: if False, create a normal Variable; if True create an
experimental ResourceVariable with well-defined semantics. Defaults
to False (will later change to True).
"""
def __init__(self,
reuse,
name="",
initializer=None,
regularizer=None,
caching_device=None,
partitioner=None,
custom_getter=None,
name_scope="",
dtype=dtypes.float32,
use_resource=None):
"""Creates a new VariableScope with the given properties."""
self._name = name
self._initializer = initializer
self._regularizer = regularizer
self._reuse = reuse
self._caching_device = caching_device
self._partitioner = partitioner
self._custom_getter = custom_getter
self._name_scope = name_scope
self._dtype = dtype
self._use_resource = use_resource
@property
def name(self):
return self._name
@property
def original_name_scope(self):
return self._name_scope
@property
def reuse(self):
return self._reuse
@property
def initializer(self):
return self._initializer
@property
def dtype(self):
return self._dtype
@property
def use_resource(self):
return self._use_resource
@property
def regularizer(self):
return self._regularizer
@property
def caching_device(self):
return self._caching_device
@property
def partitioner(self):
return self._partitioner
@property
def custom_getter(self):
return self._custom_getter
def reuse_variables(self):
"""Reuse variables in this scope."""
self._reuse = True
def set_initializer(self, initializer):
"""Set initializer for this scope."""
self._initializer = initializer
def set_dtype(self, dtype):
"""Set data type for this scope."""
self._dtype = dtype
def set_use_resource(self, use_resource):
"""Sets whether to use ResourceVariables for this scope."""
self._use_resource = use_resource
def set_regularizer(self, regularizer):
"""Set regularizer for this scope."""
self._regularizer = regularizer
def set_caching_device(self, caching_device):
"""Set caching_device for this scope."""
self._caching_device = caching_device
def set_partitioner(self, partitioner):
"""Set partitioner for this scope."""
self._partitioner = partitioner
def set_custom_getter(self, custom_getter):
"""Set custom getter for this scope."""
self._custom_getter = custom_getter
def get_collection(self, name):
"""Get this scope's variables."""
scope = self._name + "/" if self._name else ""
return ops.get_collection(name, scope)
def trainable_variables(self):
"""Get this scope's trainable variables."""
return self.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES)
def global_variables(self):
"""Get this scope's global variables."""
return self.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)
def get_variable(self,
var_store,
name,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
reuse=None,
trainable=True,
collections=None,
caching_device=None,
partitioner=None,
validate_shape=True,
use_resource=None,
custom_getter=None,):
"""Gets an existing variable with this name or create a new one."""
if regularizer is None:
regularizer = self._regularizer
if caching_device is None:
caching_device = self._caching_device
if partitioner is None:
partitioner = self._partitioner
if custom_getter is None:
custom_getter = self._custom_getter
if reuse is None:
reuse = self._reuse
full_name = self.name + "/" + name if self.name else name
# Variable names only depend on variable_scope (full_name here),
# not name_scope, so we reset it below for the time of variable creation.
with ops.name_scope(None):
# Check that `initializer` dtype and `dtype` are consistent before
# replacing them with defaults.
if (dtype is not None and initializer is not None and
not callable(initializer)):
init_dtype = ops.convert_to_tensor(initializer).dtype.base_dtype
if init_dtype != dtype:
raise ValueError("Initializer type '%s' and explicit dtype '%s' "
"don't match." % (init_dtype, dtype))
if initializer is None:
initializer = self._initializer
if dtype is None:
dtype = self._dtype
if use_resource is None:
use_resource = self._use_resource
return var_store.get_variable(
full_name, shape=shape, dtype=dtype, initializer=initializer,
regularizer=regularizer, reuse=reuse, trainable=trainable,
collections=collections, caching_device=caching_device,
partitioner=partitioner, validate_shape=validate_shape,
use_resource=use_resource, custom_getter=custom_getter)
def _get_partitioned_variable(self,
var_store,
name,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=True,
collections=None,
caching_device=None,
partitioner=None,
validate_shape=True,
use_resource=None):
"""Gets an existing variable with this name or create a new one."""
if initializer is None:
initializer = self._initializer
if regularizer is None:
regularizer = self._regularizer
if caching_device is None:
caching_device = self._caching_device
if partitioner is None:
partitioner = self._partitioner
if dtype is None:
dtype = self._dtype
if use_resource is None:
use_resource = self._use_resource
if self._custom_getter is not None:
raise ValueError(
"Private access to _get_partitioned_variable is not allowed when "
"a custom getter is set. Current custom getter: %s. "
"It is likely that you're using create_partitioned_variables. "
"If so, consider instead using get_variable with a non-empty "
"partitioner parameter instead." % self._custom_getter)
if partitioner is None:
raise ValueError("No partitioner was specified")
# This allows the variable scope name to be used as the variable name if
# this function is invoked with an empty name arg, for backward
# compatibility with create_partitioned_variables().
full_name_list = []
if self.name:
full_name_list.append(self.name)
if name:
full_name_list.append(name)
full_name = "/".join(full_name_list)
# Variable names only depend on variable_scope (full_name here),
# not name_scope, so we reset it below for the time of variable creation.
with ops.name_scope(None):
# pylint: disable=protected-access
return var_store._get_partitioned_variable(
full_name, shape=shape, dtype=dtype, initializer=initializer,
regularizer=regularizer, reuse=self.reuse, trainable=trainable,
collections=collections, caching_device=caching_device,
partitioner=partitioner, validate_shape=validate_shape,
use_resource=use_resource)
# pylint: enable=protected-access
_VARSTORE_KEY = ("__variable_store",)
_VARSCOPE_KEY = ("__varscope",)
def get_variable_scope():
"""Returns the current variable scope."""
scope = ops.get_collection(_VARSCOPE_KEY)
if scope: # This collection has at most 1 element, the default scope at [0].
return scope[0]
scope = VariableScope(False)
ops.add_to_collection(_VARSCOPE_KEY, scope)
return scope
def _get_default_variable_store():
store = ops.get_collection(_VARSTORE_KEY)
if store:
return store[0]
store = _VariableStore()
ops.add_to_collection(_VARSTORE_KEY, store)
return store
def get_variable(name,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=True,
collections=None,
caching_device=None,
partitioner=None,
validate_shape=True,
use_resource=None,
custom_getter=None):
return get_variable_scope().get_variable(
_get_default_variable_store(), name, shape=shape, dtype=dtype,
initializer=initializer, regularizer=regularizer, trainable=trainable,
collections=collections, caching_device=caching_device,
partitioner=partitioner, validate_shape=validate_shape,
use_resource=use_resource, custom_getter=custom_getter)
get_variable_or_local_docstring = (
"""%s
%sThis function prefixes the name with the current variable scope
and performs reuse checks. See the
@{$variable_scope$Variable Scope How To}
for an extensive description of how reusing works. Here is a basic example:
```python
with tf.variable_scope("foo"):
v = tf.get_variable("v", [1]) # v.name == "foo/v:0"
w = tf.get_variable("w", [1]) # w.name == "foo/w:0"
with tf.variable_scope("foo", reuse=True):
v1 = tf.get_variable("v") # The same as v above.
```
If initializer is `None` (the default), the default initializer passed in
the variable scope will be used. If that one is `None` too, a
`glorot_uniform_initializer` will be used. The initializer can also be
a Tensor, in which case the variable is initialized to this value and shape.
Similarly, if the regularizer is `None` (the default), the default regularizer
passed in the variable scope will be used (if that is `None` too,
then by default no regularization is performed).
If a partitioner is provided, a `PartitionedVariable` is returned.
Accessing this object as a `Tensor` returns the shards concatenated along
the partition axis.
Some useful partitioners are available. See, e.g.,
`variable_axis_size_partitioner` and `min_max_variable_partitioner`.
Args:
name: The name of the new or existing variable.
shape: Shape of the new or existing variable.
dtype: Type of the new or existing variable (defaults to `DT_FLOAT`).
initializer: Initializer for the variable if one is created.
regularizer: A (Tensor -> Tensor or None) function; the result of
applying it on a newly created variable will be added to the collection
@{tf.GraphKeys.REGULARIZATION_LOSSES} and can be used for regularization.
%scollections: List of graph collections keys to add the Variable to.
Defaults to `[%s]` (see `tf.Variable`).
caching_device: Optional device string or function describing where the
Variable should be cached for reading. Defaults to the Variable's
device. If not `None`, caches on another device. Typical use is to
cache on the device where the Ops using the Variable reside, to
deduplicate copying through `Switch` and other conditional statements.
partitioner: Optional callable that accepts a fully defined `TensorShape`
and `dtype` of the Variable to be created, and returns a list of
partitions for each axis (currently only one axis can be partitioned).
validate_shape: If False, allows the variable to be initialized with a
value of unknown shape. If True, the default, the shape of initial_value
must be known.
use_resource: If False, creates a regular Variable. If true, creates an
experimental ResourceVariable instead with well-defined semantics.
Defaults to False (will later change to True).
custom_getter: Callable that takes as a first argument the true getter, and
allows overwriting the internal get_variable method.
The signature of `custom_getter` should match that of this method,
but the most future-proof version will allow for changes:
`def custom_getter(getter, *args, **kwargs)`. Direct access to
all `get_variable` parameters is also allowed:
`def custom_getter(getter, name, *args, **kwargs)`. A simple identity
custom getter that simply creates variables with modified names is:
```python
def custom_getter(getter, name, *args, **kwargs):
return getter(name + '_suffix', *args, **kwargs)
```
Returns:
The created or existing `Variable` (or `PartitionedVariable`, if a
partitioner was used).
Raises:
ValueError: when creating a new variable and shape is not declared,
when violating reuse during variable creation, or when `initializer` dtype
and `dtype` don't match. Reuse is set inside `variable_scope`.
""")
get_variable.__doc__ = get_variable_or_local_docstring % (
"Gets an existing variable with these parameters or create a new one.",
"",
"trainable: If `True` also add the variable to the graph collection\n"
" `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).\n ",
"GraphKeys.GLOBAL_VARIABLES")
@functools.wraps(get_variable)
def get_local_variable(*args, **kwargs):
kwargs["trainable"] = False
if "collections" in kwargs:
kwargs["collections"] += [ops.GraphKeys.LOCAL_VARIABLES]
else:
kwargs["collections"] = [ops.GraphKeys.LOCAL_VARIABLES]
return get_variable(*args, **kwargs)
get_local_variable.__doc__ = get_variable_or_local_docstring % (
"Gets an existing *local* variable or creates a new one.",
"Behavior is the same as in `get_variable`, except that variables are\n"
"added to the `LOCAL_VARIABLES` collection and `trainable` is set to\n"
"`False`.\n",
"",
"GraphKeys.LOCAL_VARIABLES")
def _get_partitioned_variable(name,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=True,
collections=None,
caching_device=None,
partitioner=None,
validate_shape=True,
use_resource=None):
"""Gets or creates a sharded variable list with these parameters.
The `partitioner` must be a callable that accepts a fully defined
`TensorShape` and returns a sequence of integers (the `partitions`).
These integers describe how to partition the given sharded `Variable`
along the given dimension. That is, `partitions[1] = 3` means split
the `Variable` into 3 shards along dimension 1. Currently, sharding along
only one axis is supported.
If the list of variables with the given name (prefix) is already stored,
we return the stored variables. Otherwise, we create a new one.
Set `reuse` to `True` when you only want to reuse existing Variables.
Set `reuse` to `False` when you only want to create new Variables.
If `reuse` is `None` (the default), both new and existing variables are
returned.
If initializer is `None` (the default), the default initializer passed in
the constructor is used. If that one is `None` too, we use a new
`glorot_uniform_initializer`. If initializer is a Tensor, we use
it as a value and derive the shape from the initializer.
If the initializer is a callable, then it will be called for each
shard. Otherwise the initializer should match the shape of the entire
sharded Variable, and it will be sliced accordingly for each shard.
Some useful partitioners are available. See, e.g.,
`variable_axis_size_partitioner` and `min_max_variable_partitioner`.
Args:
name: The name of the new or existing variable.
shape: Shape of the new or existing variable.
dtype: Type of the new or existing variable (defaults to `DT_FLOAT`).
initializer: Initializer for the variable if one is created.
regularizer: A (Tensor -> Tensor or None) function; the result of
applying it on a newly created variable will be added to the collection
GraphKeys.REGULARIZATION_LOSSES and can be used for regularization.
trainable: If `True` also add the variable to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).
collections: List of graph collections keys to add the Variable to.
Defaults to `[GraphKeys.GLOBAL_VARIABLES]` (see `tf.Variable`).
caching_device: Optional device string or function describing where the
Variable should be cached for reading. Defaults to the Variable's
device. If not `None`, caches on another device. Typical use is to
cache on the device where the Ops using the Variable reside, to
deduplicate copying through `Switch` and other conditional statements.
partitioner: Optional callable that accepts a fully defined `TensorShape`
and `dtype` of the Variable to be created, and returns a list of
partitions for each axis (currently only one axis can be partitioned).
validate_shape: If False, allows the variable to be initialized with a
value of unknown shape. If True, the default, the shape of initial_value
must be known.
use_resource: If False, creates a regular Variable. If True, creates an
experimental ResourceVariable instead which has well-defined semantics.
Defaults to False (will later change to True).
Returns:
A tuple `(shards, partitions)` where `shards` is the list of `Variable`
shards and `partitions` is the output of the partitioner on the input
shape.
Raises:
ValueError: when creating a new variable and shape is not declared,
or when violating reuse during variable creation. Reuse is set inside
`variable_scope`.
"""
# pylint: disable=protected-access
scope = get_variable_scope()
if scope.custom_getter is not None:
raise ValueError(
"Private access to _get_partitioned_variable is not allowed when "
"a custom getter is set. Current custom getter: %s. "
"It is likely that you're using create_partitioned_variables. "
"If so, consider instead using get_variable with a non-empty "
"partitioner parameter instead." % scope.custom_getter)
return scope._get_partitioned_variable(
_get_default_variable_store(), name, shape=shape, dtype=dtype,
initializer=initializer, regularizer=regularizer, trainable=trainable,
collections=collections, caching_device=caching_device,
partitioner=partitioner, validate_shape=validate_shape,
use_resource=use_resource)
# pylint: enable=protected-access
@tf_contextlib.contextmanager
def _pure_variable_scope(name_or_scope,
reuse=None,
initializer=None,
regularizer=None,
caching_device=None,
partitioner=None,
custom_getter=None,
old_name_scope=None,
dtype=dtypes.float32,
use_resource=None):
"""Creates a context for the variable_scope, see `variable_scope` for docs.
Note: this does not create a name scope.
Args:
name_or_scope: `string` or `VariableScope`: the scope to open.
reuse: `True` or `None`; if `True`, we go into reuse mode for this scope as
well as all sub-scopes; if `None`, we just inherit the parent scope reuse.
initializer: default initializer for variables within this scope.
regularizer: default regularizer for variables within this scope.
caching_device: default caching device for variables within this scope.
partitioner: default partitioner for variables within this scope.
custom_getter: default custom getter for variables within this scope.
old_name_scope: the original name scope when re-entering a variable scope.
dtype: type of the variables within this scope (defaults to `DT_FLOAT`).
use_resource: If False, variables in this scope will be regular Variables.
If True, experimental ResourceVariables will be creates instead, with
well-defined semantics. Defaults to False (will later change to True).
Yields:
A scope that can be captured and reused.
Raises:
ValueError: when trying to reuse within a create scope, or create within
a reuse scope, or if reuse is not `None` or `True`.
TypeError: when the types of some arguments are not appropriate.
"""
get_variable_scope() # Ensure that a default exists, then get a pointer.
# Get the reference to the collection as we want to modify it in place.
default_varscope = ops.get_collection_ref(_VARSCOPE_KEY)
old = default_varscope[0]
var_store = _get_default_variable_store()
if isinstance(name_or_scope, VariableScope):
new_name = name_or_scope.name
else:
new_name = old.name + "/" + name_or_scope if old.name else name_or_scope
try:
var_store.open_variable_scope(new_name)
if isinstance(name_or_scope, VariableScope):
old_subscopes = copy.copy(var_store.variable_scopes_count)
name_scope = name_or_scope._name_scope # pylint: disable=protected-access
# Handler for the case when we jump to a shared scope.
# We create a new VariableScope (default_varscope[0]) that contains
# a copy of the provided shared scope, possibly with changed reuse
# and initializer, if the user requested this.
default_varscope[0] = VariableScope(
name_or_scope.reuse if reuse is None else reuse,
name=new_name,
initializer=name_or_scope.initializer,
regularizer=name_or_scope.regularizer,
caching_device=name_or_scope.caching_device,
partitioner=name_or_scope.partitioner,
dtype=name_or_scope.dtype,
custom_getter=name_or_scope.custom_getter,
name_scope=name_scope,
use_resource=name_or_scope.use_resource)
if initializer is not None:
default_varscope[0].set_initializer(initializer)
if regularizer is not None:
default_varscope[0].set_regularizer(regularizer)
if caching_device is not None:
default_varscope[0].set_caching_device(caching_device)
if partitioner is not None:
default_varscope[0].set_partitioner(partitioner)
if custom_getter is not None:
default_varscope[0].set_custom_getter(
_maybe_wrap_custom_getter(
custom_getter, name_or_scope.custom_getter))
if dtype is not None:
default_varscope[0].set_dtype(dtype)
if use_resource is not None:
default_varscope[0].set_use_resource(use_resource)
yield default_varscope[0]
else:
# Handler for the case when we just prolong current variable scope.
# VariableScope with name extended by the provided one, and inherited
# reuse and initializer (except if the user provided values to set).
reuse = reuse or old.reuse # Re-using is inherited by sub-scopes.
default_varscope[0] = VariableScope(
reuse,
name=new_name,
initializer=old.initializer,
regularizer=old.regularizer,
caching_device=old.caching_device,
partitioner=old.partitioner,
dtype=old.dtype,
use_resource=old.use_resource,
custom_getter=old.custom_getter,
name_scope=old_name_scope or name_or_scope)
if initializer is not None:
default_varscope[0].set_initializer(initializer)
if regularizer is not None:
default_varscope[0].set_regularizer(regularizer)
if caching_device is not None:
default_varscope[0].set_caching_device(caching_device)
if partitioner is not None:
default_varscope[0].set_partitioner(partitioner)
if custom_getter is not None:
default_varscope[0].set_custom_getter(
_maybe_wrap_custom_getter(custom_getter, old.custom_getter))
if dtype is not None:
default_varscope[0].set_dtype(dtype)
if use_resource is not None:
default_varscope[0].set_use_resource(use_resource)
yield default_varscope[0]
finally:
var_store.close_variable_subscopes(new_name)
# If jumping out from a non-prolonged scope, restore counts.
if isinstance(name_or_scope, VariableScope):
var_store.variable_scopes_count = old_subscopes
default_varscope[0] = old
def _maybe_wrap_custom_getter(custom_getter, old_getter):
"""Wrap a call to a custom_getter to use the old_getter internally."""
if old_getter is None:
return custom_getter
# The new custom_getter should call the old one
def wrapped_custom_getter(getter, *args, **kwargs):
# Call:
# custom_getter(
# lambda: old_getter(true_getter, ...), *args, **kwargs)
# which means custom_getter will call old_getter, which
# will call the true_getter, perform any intermediate
# processing, and return the results to the current
# getter, which will also perform additional processing.
return custom_getter(
functools.partial(old_getter, getter),
*args, **kwargs)
return wrapped_custom_getter
def _get_unique_variable_scope(prefix):
"""Get a name with the given prefix unique in the current variable scope."""
var_store = _get_default_variable_store()
current_scope = get_variable_scope()
name = current_scope.name + "/" + prefix if current_scope.name else prefix
if var_store.variable_scope_count(name) == 0:
return prefix
idx = 1
while var_store.variable_scope_count(name + ("_%d" % idx)) > 0:
idx += 1
return prefix + ("_%d" % idx)
# pylint: disable=g-doc-return-or-yield
@tf_contextlib.contextmanager
def variable_scope(name_or_scope,
default_name=None,
values=None,
initializer=None,
regularizer=None,
caching_device=None,
partitioner=None,
custom_getter=None,
reuse=None,
dtype=None,
use_resource=None):
"""Returns a context manager for defining ops that creates variables (layers).
This context manager validates that the (optional) `values` are from
the same graph, ensures that graph is the default graph, and pushes a
name scope and a variable scope.
If `name_or_scope` is not None, it is used as is. If `scope` is None, then
`default_name` is used. In that case, if the same name has been previously
used in the same scope, it will made unique be appending `_N` to it.
Variable scope allows to create new variables and to share already created
ones while providing checks to not create or share by accident. For details,
see the @{$variable_scope$Variable Scope How To},
here we present only a few basic examples.
Simple example of how to create a new variable:
```python
with tf.variable_scope("foo"):
with tf.variable_scope("bar"):
v = tf.get_variable("v", [1])
assert v.name == "foo/bar/v:0"
```
Basic example of sharing a variable:
```python
with tf.variable_scope("foo"):
v = tf.get_variable("v", [1])
with tf.variable_scope("foo", reuse=True):
v1 = tf.get_variable("v", [1])
assert v1 == v
```
Sharing a variable by capturing a scope and setting reuse:
```python
with tf.variable_scope("foo") as scope:
v = tf.get_variable("v", [1])
scope.reuse_variables()
v1 = tf.get_variable("v", [1])
assert v1 == v
```
To prevent accidental sharing of variables, we raise an exception when
getting an existing variable in a non-reusing scope.
```python
with tf.variable_scope("foo"):
v = tf.get_variable("v", [1])
v1 = tf.get_variable("v", [1])
# Raises ValueError("... v already exists ...").
```
Similarly, we raise an exception when trying to get a variable that
does not exist in reuse mode.
```python
with tf.variable_scope("foo", reuse=True):
v = tf.get_variable("v", [1])
# Raises ValueError("... v does not exists ...").
```
Note that the `reuse` flag is inherited: if we open a reusing scope,
then all its sub-scopes become reusing as well.
A note about name scoping: Setting `reuse` does not impact the naming of other
ops such as mult. See related discussion on [github#6189](https://github.com/tensorflow/tensorflow/issues/6189)
Args:
name_or_scope: `string` or `VariableScope`: the scope to open.
default_name: The default name to use if the `name_or_scope` argument is
`None`, this name will be uniquified. If name_or_scope is provided it
won't be used and therefore it is not required and can be None.
values: The list of `Tensor` arguments that are passed to the op function.
initializer: default initializer for variables within this scope.
regularizer: default regularizer for variables within this scope.
caching_device: default caching device for variables within this scope.
partitioner: default partitioner for variables within this scope.
custom_getter: default custom getter for variables within this scope.
reuse: `True` or `None`; if `True`, we go into reuse mode for this scope as
well as all sub-scopes; if `None`, we just inherit the parent scope reuse.
dtype: type of variables created in this scope (defaults to the type
in the passed scope, or inherited from parent scope).
use_resource: If False, all variables will be regular Variables. If True,
experimental ResourceVariables with well-defined semantics will be used
instead. Defaults to False (will later change to True).
Returns:
A scope that can be to captured and reused.
Raises:
ValueError: when trying to reuse within a create scope, or create within
a reuse scope.
TypeError: when the types of some arguments are not appropriate.
"""
if default_name is None and name_or_scope is None:
raise TypeError("If default_name is None then name_or_scope is required")
if not (reuse is True or reuse is False or reuse is None):
raise ValueError("The reuse parameter must be True or False or None.")
if reuse is False: # We don't allow non-inheriting scopes, False = None here.
reuse = None
if values is None:
values = []
g = ops._get_graph_from_inputs(values) # pylint: disable=protected-access
with g.as_default():
if name_or_scope is not None:
if not isinstance(name_or_scope, (VariableScope,) + six.string_types):
raise TypeError("VariableScope: name_or_scope must be a string or "
"VariableScope.")
if isinstance(name_or_scope, six.string_types):
name_scope = name_or_scope
else:
name_scope = name_or_scope.name.split("/")[-1]
if name_scope:
with ops.name_scope(name_scope) as cur_name_scope:
if isinstance(name_or_scope, six.string_types):
old_name_scope = cur_name_scope
else:
old_name_scope = name_or_scope.original_name_scope
with _pure_variable_scope(
name_or_scope,
reuse=reuse,
initializer=initializer,
regularizer=regularizer,
caching_device=caching_device,
partitioner=partitioner,
custom_getter=custom_getter,
old_name_scope=old_name_scope,
dtype=dtype,
use_resource=use_resource) as vs:
yield vs
else:
# This can only happen if someone is entering the root variable scope.
with _pure_variable_scope(
name_or_scope,
reuse=reuse,
initializer=initializer,
regularizer=regularizer,
caching_device=caching_device,
partitioner=partitioner,
custom_getter=custom_getter,
dtype=dtype,
use_resource=use_resource) as vs:
yield vs
else: # Here name_or_scope is None. Using default name, but made unique.
if reuse:
raise ValueError("reuse=True cannot be used without a name_or_scope")
with ops.name_scope(default_name) as scope:
unique_default_name = _get_unique_variable_scope(default_name)
with _pure_variable_scope(
unique_default_name,
initializer=initializer,
regularizer=regularizer,
caching_device=caching_device,
partitioner=partitioner,
custom_getter=custom_getter,
old_name_scope=scope,
dtype=dtype,
use_resource=use_resource) as vs:
yield vs
# pylint: disable=g-doc-return-or-yield
@tf_contextlib.contextmanager
def variable_op_scope(values,
name_or_scope,
default_name=None,
initializer=None,
regularizer=None,
caching_device=None,
partitioner=None,
custom_getter=None,
reuse=None,
dtype=None,
use_resource=None):
"""Deprecated: context manager for defining an op that creates variables."""
logging.warn("tf.variable_op_scope(values, name, default_name) is deprecated,"
" use tf.variable_scope(name, default_name, values)")
with variable_scope(name_or_scope,
default_name=default_name,
values=values,
initializer=initializer,
regularizer=regularizer,
caching_device=caching_device,
partitioner=partitioner,
custom_getter=custom_getter,
reuse=reuse,
dtype=dtype,
use_resource=use_resource) as scope:
yield scope
def _compute_slice_dim_and_shape(full_shape, slicing):
"""Computes which dimension is being sliced and the typical slice shape."""
slice_shape = [0] * len(full_shape)
slice_dim = None
for dim, num_slices in enumerate(slicing):
dim_size = full_shape[dim]
if num_slices <= 0 or dim_size < num_slices:
raise ValueError("Cannot create %d slices for size %d. shape: %s, "
"slicing: %s" %
(num_slices, full_shape[dim], full_shape, slicing))
if num_slices == 1:
# Not slicing in this dimension.
slice_shape[dim] = dim_size
elif slice_dim is not None:
# We only support slicing along one of the dimensions.
raise ValueError("Can only slice a variable along one dimension: "
"shape: %s, slicing: %s" % (full_shape, slicing))
else:
# Note: We will add any extras onto the last slice, later.
slice_dim = dim
slice_shape[dim] = dim_size // num_slices
# Degenerate case: If "slicing" was all ones, pretend we are slicing along
# the first dimension.
if slice_dim is None:
slice_dim = 0
return slice_dim, slice_shape
def variable(initial_value=None,
trainable=True,
collections=None,
validate_shape=True,
caching_device=None,
name=None,
dtype=None):
if get_variable_scope().use_resource:
return resource_variable_ops.ResourceVariable(
initial_value=initial_value, trainable=trainable,
collections=collections, validate_shape=validate_shape,
caching_device=caching_device, name=name, dtype=dtype)
else:
return variables.Variable(
initial_value=initial_value, trainable=trainable,
collections=collections, validate_shape=validate_shape,
caching_device=caching_device, name=name, dtype=dtype)
| 42.326567 | 113 | 0.661749 |
acefffb097d2eac2494f563a14577bc9792e1c91 | 3,501 | py | Python | car_sim_gen/plot_tire_model.py | svenlr/car-physics-pacejka | bef64a7c3c813419a76f55c2b0553b5fe82f0808 | [
"BSD-2-Clause"
] | null | null | null | car_sim_gen/plot_tire_model.py | svenlr/car-physics-pacejka | bef64a7c3c813419a76f55c2b0553b5fe82f0808 | [
"BSD-2-Clause"
] | null | null | null | car_sim_gen/plot_tire_model.py | svenlr/car-physics-pacejka | bef64a7c3c813419a76f55c2b0553b5fe82f0808 | [
"BSD-2-Clause"
] | null | null | null | import sys
import casadi
import numpy as np
import matplotlib.pyplot as plt
from car_model import calc_wheel_centric_velocities, create_car_model, calc_sigma_xy, calc_wheel_centric_forces
from car_sim_gen.constants import WheelConstants
if __name__ == '__main__':
model, c, q = create_car_model()
vr = casadi.MX.sym("vr")
v_wx = casadi.MX.sym("v_wx")
v_wy = casadi.MX.sym("v_wy")
v_x = casadi.MX.sym("v_x")
v_y = casadi.MX.sym("v_y")
r = casadi.MX.sym("r")
delta = casadi.MX.sym("delta0")
mu_x = casadi.MX.sym("mu_x", c.n_wheels, 1)
mu_y = casadi.MX.sym("mu_y", c.n_wheels, 1)
Fz = casadi.MX.sym("Fz", c.n_wheels, 1)
x = casadi.vertcat(v_x, v_y, r)
u = casadi.vertcat(delta)
p = casadi.vertcat(Fz, mu_x, mu_y)
cw0: WheelConstants = c.wheel_constants[0]
mu_x_val = 0.5
mu_y_val = 0.4
p_val = [cw0.Fz0] * c.n_wheels + [mu_x_val] * c.n_wheels + [mu_y_val] * c.n_wheels
vx, vy = calc_wheel_centric_velocities(x, u, c, 0)
sigma_x, sigma_y = calc_sigma_xy(vr, v_wx, v_wy)
Fx, Fy = calc_wheel_centric_forces(sigma_x, sigma_y, p, c.wheel_constants[0], 0)
calc_slip = casadi.Function("calc_slip", [x, u], [vx, vy], dict())
calc_forces = casadi.Function("calc_forces", [vr, v_wx, v_wy, p], [Fx, Fy], dict())
print(calc_slip([0, 0, -1], [0]))
print(calc_forces(0, 0, 0, [3] * 4 + [1] * 8))
fig, plots = plt.subplots(2, 2)
vsy_vals = np.linspace(-1.0, 1.0)
Fy_vals = []
Fx_vals = []
for vsy_val in vsy_vals:
Fx_val, Fy_val = calc_forces(1, 1.1, vsy_val, p_val)
Fy_vals.append(Fy_val)
Fx_vals.append(Fx_val)
plots[0,0].plot(vsy_vals, Fy_vals, label="Fy")
plots[0,0].plot(vsy_vals, Fx_vals, label="Fx")
plots[0,0].set_xlabel("Vsy [m/s]")
plots[0,0].set_ylabel("F [N]")
plots[0,0].set_title('Vx=1.1 Vr=1')
plots[0,0].legend()
vr_vals = np.linspace(0.5, 1.5, num=100)
vsy_val = 0.05
Fy_vals = []
Fx_vals = []
for vr_val in vr_vals:
Fx_val, Fy_val = calc_forces(vr_val, 1.0, vsy_val, p_val)
Fy_vals.append(Fy_val)
Fx_vals.append(Fx_val)
plots[1,0].plot(vr_vals, Fy_vals, label="Fy [N]")
plots[1,0].plot(vr_vals, Fx_vals, label="Fx [N]")
plots[1,0].set_xlabel("Vr [m/s]")
plots[1,0].set_ylabel("F [N]")
plots[1,0].set_title('Vx=1.0 Vsy=0.05')
plots[1,0].legend()
Fz_vals = np.linspace(1, 10, num=5)
vr_vals = np.linspace(0.5, 1.5, num=100)
vsy_val = 0.0
for Fz_val in Fz_vals:
Fx_vals = []
for vr_val in vr_vals:
Fx_val, Fy_val = calc_forces(vr_val, 1.0, vsy_val,
[Fz_val] * c.n_wheels + [mu_x_val] * c.n_wheels + [mu_y_val] * c.n_wheels)
Fx_vals.append(Fx_val)
plots[0,1].plot(vr_vals, Fx_vals)
plots[0,1].set_xlabel("Vr [m/s]")
plots[0,1].set_ylabel("Fx [N]")
plots[0,1].set_title('Vx=1.0 Vsy=0.0 (Varying Fz)')
Fz_vals = np.linspace(0, 10, num=100)
vsy_val = -0.1
Fy_vals = []
for Fz_val in Fz_vals:
Fx_val, Fy_val = calc_forces(1.0, 1.0, vsy_val,
[Fz_val] * c.n_wheels + [mu_x_val] * c.n_wheels + [mu_y_val] * c.n_wheels)
Fy_vals.append(Fy_val)
plt.plot(Fz_vals, Fy_vals)
plots[1,1].set_xlabel('Fz [N]')
plots[1,1].set_ylabel('Fy [N]')
plots[1,1].set_title('Vx=Vr=1.0, Vsx=0 Vsy=-0.1')
plt.tight_layout(2.0)
plt.savefig("../doc/tire_model.png")
plt.show() | 36.092784 | 115 | 0.601257 |
acf0001784df8bd97738049b181ed59f45200abc | 68,018 | py | Python | tests/test_ext_napoleon_docstring.py | samdoran/sphinx | 4c91c038b220d07bbdfe0c1680af42fe897f342c | [
"BSD-2-Clause"
] | 4,973 | 2015-01-03T15:44:00.000Z | 2022-03-31T03:11:51.000Z | tests/test_ext_napoleon_docstring.py | samdoran/sphinx | 4c91c038b220d07bbdfe0c1680af42fe897f342c | [
"BSD-2-Clause"
] | 7,850 | 2015-01-02T08:09:25.000Z | 2022-03-31T18:57:40.000Z | tests/test_ext_napoleon_docstring.py | samdoran/sphinx | 4c91c038b220d07bbdfe0c1680af42fe897f342c | [
"BSD-2-Clause"
] | 2,179 | 2015-01-03T15:26:53.000Z | 2022-03-31T12:22:44.000Z | """
test_napoleon_docstring
~~~~~~~~~~~~~~~~~~~~~~~
Tests for :mod:`sphinx.ext.napoleon.docstring` module.
:copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
import sys
from collections import namedtuple
from contextlib import contextmanager
from inspect import cleandoc
from textwrap import dedent
from unittest import TestCase, mock
import pytest
from sphinx.ext.napoleon import Config
from sphinx.ext.napoleon.docstring import (GoogleDocstring, NumpyDocstring,
_convert_numpy_type_spec, _recombine_set_tokens,
_token_type, _tokenize_type_spec)
if sys.version_info >= (3, 6):
from .ext_napoleon_pep526_data_google import PEP526GoogleClass
from .ext_napoleon_pep526_data_numpy import PEP526NumpyClass
class NamedtupleSubclass(namedtuple('NamedtupleSubclass', ('attr1', 'attr2'))):
"""Sample namedtuple subclass
Attributes
----------
attr1 : Arbitrary type
Quick description of attr1
attr2 : Another arbitrary type
Quick description of attr2
attr3 : Type
Adds a newline after the type
"""
# To avoid creating a dict, as a namedtuple doesn't have it:
__slots__ = ()
def __new__(cls, attr1, attr2=None):
return super().__new__(cls, attr1, attr2)
class BaseDocstringTest(TestCase):
pass
class NamedtupleSubclassTest(BaseDocstringTest):
def test_attributes_docstring(self):
config = Config()
actual = str(NumpyDocstring(cleandoc(NamedtupleSubclass.__doc__),
config=config, app=None, what='class',
name='NamedtupleSubclass', obj=NamedtupleSubclass))
expected = """\
Sample namedtuple subclass
.. attribute:: attr1
Quick description of attr1
:type: Arbitrary type
.. attribute:: attr2
Quick description of attr2
:type: Another arbitrary type
.. attribute:: attr3
Adds a newline after the type
:type: Type
"""
self.assertEqual(expected, actual)
class InlineAttributeTest(BaseDocstringTest):
def test_class_data_member(self):
config = Config()
docstring = dedent("""\
data member description:
- a: b
""")
actual = str(GoogleDocstring(docstring, config=config, app=None,
what='attribute', name='some_data', obj=0))
expected = dedent("""\
data member description:
- a: b""")
self.assertEqual(expected, actual)
def test_class_data_member_inline(self):
config = Config()
docstring = """b: data member description with :ref:`reference`"""
actual = str(GoogleDocstring(docstring, config=config, app=None,
what='attribute', name='some_data', obj=0))
expected = dedent("""\
data member description with :ref:`reference`
:type: b""")
self.assertEqual(expected, actual)
def test_class_data_member_inline_no_type(self):
config = Config()
docstring = """data with ``a : in code`` and :ref:`reference` and no type"""
actual = str(GoogleDocstring(docstring, config=config, app=None,
what='attribute', name='some_data', obj=0))
expected = """data with ``a : in code`` and :ref:`reference` and no type"""
self.assertEqual(expected, actual)
def test_class_data_member_inline_ref_in_type(self):
config = Config()
docstring = """:class:`int`: data member description"""
actual = str(GoogleDocstring(docstring, config=config, app=None,
what='attribute', name='some_data', obj=0))
expected = dedent("""\
data member description
:type: :class:`int`""")
self.assertEqual(expected, actual)
class GoogleDocstringTest(BaseDocstringTest):
docstrings = [(
"""Single line summary""",
"""Single line summary"""
), (
"""
Single line summary
Extended description
""",
"""
Single line summary
Extended description
"""
), (
"""
Single line summary
Args:
arg1(str):Extended
description of arg1
""",
"""
Single line summary
:Parameters: **arg1** (*str*) -- Extended
description of arg1
"""
), (
"""
Single line summary
Args:
arg1(str):Extended
description of arg1
arg2 ( int ) : Extended
description of arg2
Keyword Args:
kwarg1(str):Extended
description of kwarg1
kwarg2 ( int ) : Extended
description of kwarg2""",
"""
Single line summary
:Parameters: * **arg1** (*str*) -- Extended
description of arg1
* **arg2** (*int*) -- Extended
description of arg2
:Keyword Arguments: * **kwarg1** (*str*) -- Extended
description of kwarg1
* **kwarg2** (*int*) -- Extended
description of kwarg2
"""
), (
"""
Single line summary
Arguments:
arg1(str):Extended
description of arg1
arg2 ( int ) : Extended
description of arg2
Keyword Arguments:
kwarg1(str):Extended
description of kwarg1
kwarg2 ( int ) : Extended
description of kwarg2""",
"""
Single line summary
:Parameters: * **arg1** (*str*) -- Extended
description of arg1
* **arg2** (*int*) -- Extended
description of arg2
:Keyword Arguments: * **kwarg1** (*str*) -- Extended
description of kwarg1
* **kwarg2** (*int*) -- Extended
description of kwarg2
"""
), (
"""
Single line summary
Return:
str:Extended
description of return value
""",
"""
Single line summary
:returns: *str* -- Extended
description of return value
"""
), (
"""
Single line summary
Returns:
str:Extended
description of return value
""",
"""
Single line summary
:returns: *str* -- Extended
description of return value
"""
), (
"""
Single line summary
Returns:
Extended
description of return value
""",
"""
Single line summary
:returns: Extended
description of return value
"""
), (
"""
Single line summary
Args:
arg1(str):Extended
description of arg1
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
""",
"""
Single line summary
:Parameters: * **arg1** (*str*) -- Extended
description of arg1
* **\\*args** -- Variable length argument list.
* **\\*\\*kwargs** -- Arbitrary keyword arguments.
"""
), (
"""
Single line summary
Args:
arg1 (list(int)): Description
arg2 (list[int]): Description
arg3 (dict(str, int)): Description
arg4 (dict[str, int]): Description
""",
"""
Single line summary
:Parameters: * **arg1** (*list(int)*) -- Description
* **arg2** (*list[int]*) -- Description
* **arg3** (*dict(str, int)*) -- Description
* **arg4** (*dict[str, int]*) -- Description
"""
), (
"""
Single line summary
Receive:
arg1 (list(int)): Description
arg2 (list[int]): Description
""",
"""
Single line summary
:Receives: * **arg1** (*list(int)*) -- Description
* **arg2** (*list[int]*) -- Description
"""
), (
"""
Single line summary
Receives:
arg1 (list(int)): Description
arg2 (list[int]): Description
""",
"""
Single line summary
:Receives: * **arg1** (*list(int)*) -- Description
* **arg2** (*list[int]*) -- Description
"""
), (
"""
Single line summary
Yield:
str:Extended
description of yielded value
""",
"""
Single line summary
:Yields: *str* -- Extended
description of yielded value
"""
), (
"""
Single line summary
Yields:
Extended
description of yielded value
""",
"""
Single line summary
:Yields: Extended
description of yielded value
"""
)]
def test_sphinx_admonitions(self):
admonition_map = {
'Attention': 'attention',
'Caution': 'caution',
'Danger': 'danger',
'Error': 'error',
'Hint': 'hint',
'Important': 'important',
'Note': 'note',
'Tip': 'tip',
'Todo': 'todo',
'Warning': 'warning',
'Warnings': 'warning',
}
config = Config()
for section, admonition in admonition_map.items():
# Multiline
actual = str(GoogleDocstring(("{}:\n"
" this is the first line\n"
"\n"
" and this is the second line\n"
).format(section), config))
expect = (".. {}::\n"
"\n"
" this is the first line\n"
" \n"
" and this is the second line\n"
).format(admonition)
self.assertEqual(expect, actual)
# Single line
actual = str(GoogleDocstring(("{}:\n"
" this is a single line\n"
).format(section), config))
expect = (".. {}:: this is a single line\n"
).format(admonition)
self.assertEqual(expect, actual)
def test_docstrings(self):
config = Config(
napoleon_use_param=False,
napoleon_use_rtype=False,
napoleon_use_keyword=False
)
for docstring, expected in self.docstrings:
actual = str(GoogleDocstring(dedent(docstring), config))
expected = dedent(expected)
self.assertEqual(expected, actual)
def test_parameters_with_class_reference(self):
docstring = """\
Construct a new XBlock.
This class should only be used by runtimes.
Arguments:
runtime (:class:`~typing.Dict`\\[:class:`int`,:class:`str`\\]): Use it to
access the environment. It is available in XBlock code
as ``self.runtime``.
field_data (:class:`FieldData`): Interface used by the XBlock
fields to access their data from wherever it is persisted.
scope_ids (:class:`ScopeIds`): Identifiers needed to resolve scopes.
"""
actual = str(GoogleDocstring(docstring))
expected = """\
Construct a new XBlock.
This class should only be used by runtimes.
:param runtime: Use it to
access the environment. It is available in XBlock code
as ``self.runtime``.
:type runtime: :class:`~typing.Dict`\\[:class:`int`,:class:`str`\\]
:param field_data: Interface used by the XBlock
fields to access their data from wherever it is persisted.
:type field_data: :class:`FieldData`
:param scope_ids: Identifiers needed to resolve scopes.
:type scope_ids: :class:`ScopeIds`
"""
self.assertEqual(expected, actual)
def test_attributes_with_class_reference(self):
docstring = """\
Attributes:
in_attr(:class:`numpy.ndarray`): super-dooper attribute
"""
actual = str(GoogleDocstring(docstring))
expected = """\
.. attribute:: in_attr
super-dooper attribute
:type: :class:`numpy.ndarray`
"""
self.assertEqual(expected, actual)
docstring = """\
Attributes:
in_attr(numpy.ndarray): super-dooper attribute
"""
actual = str(GoogleDocstring(docstring))
expected = """\
.. attribute:: in_attr
super-dooper attribute
:type: numpy.ndarray
"""
self.assertEqual(expected, actual)
def test_code_block_in_returns_section(self):
docstring = """
Returns:
foobar: foo::
codecode
codecode
"""
expected = """
:returns:
foo::
codecode
codecode
:rtype: foobar
"""
actual = str(GoogleDocstring(docstring))
self.assertEqual(expected, actual)
def test_colon_in_return_type(self):
docstring = """Example property.
Returns:
:py:class:`~.module.submodule.SomeClass`: an example instance
if available, None if not available.
"""
expected = """Example property.
:returns: an example instance
if available, None if not available.
:rtype: :py:class:`~.module.submodule.SomeClass`
"""
actual = str(GoogleDocstring(docstring))
self.assertEqual(expected, actual)
def test_xrefs_in_return_type(self):
docstring = """Example Function
Returns:
:class:`numpy.ndarray`: A :math:`n \\times 2` array containing
a bunch of math items
"""
expected = """Example Function
:returns: A :math:`n \\times 2` array containing
a bunch of math items
:rtype: :class:`numpy.ndarray`
"""
actual = str(GoogleDocstring(docstring))
self.assertEqual(expected, actual)
def test_raises_types(self):
docstrings = [("""
Example Function
Raises:
RuntimeError:
A setting wasn't specified, or was invalid.
ValueError:
Something something value error.
:py:class:`AttributeError`
errors for missing attributes.
~InvalidDimensionsError
If the dimensions couldn't be parsed.
`InvalidArgumentsError`
If the arguments are invalid.
:exc:`~ValueError`
If the arguments are wrong.
""", """
Example Function
:raises RuntimeError: A setting wasn't specified, or was invalid.
:raises ValueError: Something something value error.
:raises AttributeError: errors for missing attributes.
:raises ~InvalidDimensionsError: If the dimensions couldn't be parsed.
:raises InvalidArgumentsError: If the arguments are invalid.
:raises ~ValueError: If the arguments are wrong.
"""),
################################
("""
Example Function
Raises:
InvalidDimensionsError
""", """
Example Function
:raises InvalidDimensionsError:
"""),
################################
("""
Example Function
Raises:
Invalid Dimensions Error
""", """
Example Function
:raises Invalid Dimensions Error:
"""),
################################
("""
Example Function
Raises:
Invalid Dimensions Error: With description
""", """
Example Function
:raises Invalid Dimensions Error: With description
"""),
################################
("""
Example Function
Raises:
InvalidDimensionsError: If the dimensions couldn't be parsed.
""", """
Example Function
:raises InvalidDimensionsError: If the dimensions couldn't be parsed.
"""),
################################
("""
Example Function
Raises:
Invalid Dimensions Error: If the dimensions couldn't be parsed.
""", """
Example Function
:raises Invalid Dimensions Error: If the dimensions couldn't be parsed.
"""),
################################
("""
Example Function
Raises:
If the dimensions couldn't be parsed.
""", """
Example Function
:raises If the dimensions couldn't be parsed.:
"""),
################################
("""
Example Function
Raises:
:class:`exc.InvalidDimensionsError`
""", """
Example Function
:raises exc.InvalidDimensionsError:
"""),
################################
("""
Example Function
Raises:
:class:`exc.InvalidDimensionsError`: If the dimensions couldn't be parsed.
""", """
Example Function
:raises exc.InvalidDimensionsError: If the dimensions couldn't be parsed.
"""),
################################
("""
Example Function
Raises:
:class:`exc.InvalidDimensionsError`: If the dimensions couldn't be parsed,
then a :class:`exc.InvalidDimensionsError` will be raised.
""", """
Example Function
:raises exc.InvalidDimensionsError: If the dimensions couldn't be parsed,
then a :class:`exc.InvalidDimensionsError` will be raised.
"""),
################################
("""
Example Function
Raises:
:class:`exc.InvalidDimensionsError`: If the dimensions couldn't be parsed.
:class:`exc.InvalidArgumentsError`: If the arguments are invalid.
""", """
Example Function
:raises exc.InvalidDimensionsError: If the dimensions couldn't be parsed.
:raises exc.InvalidArgumentsError: If the arguments are invalid.
"""),
################################
("""
Example Function
Raises:
:class:`exc.InvalidDimensionsError`
:class:`exc.InvalidArgumentsError`
""", """
Example Function
:raises exc.InvalidDimensionsError:
:raises exc.InvalidArgumentsError:
""")]
for docstring, expected in docstrings:
actual = str(GoogleDocstring(docstring))
self.assertEqual(expected, actual)
def test_kwargs_in_arguments(self):
docstring = """Allows to create attributes binded to this device.
Some other paragraph.
Code sample for usage::
dev.bind(loopback=Loopback)
dev.loopback.configure()
Arguments:
**kwargs: name/class pairs that will create resource-managers
bound as instance attributes to this instance. See code
example above.
"""
expected = """Allows to create attributes binded to this device.
Some other paragraph.
Code sample for usage::
dev.bind(loopback=Loopback)
dev.loopback.configure()
:param \\*\\*kwargs: name/class pairs that will create resource-managers
bound as instance attributes to this instance. See code
example above.
"""
actual = str(GoogleDocstring(docstring))
self.assertEqual(expected, actual)
def test_section_header_formatting(self):
docstrings = [("""
Summary line
Example:
Multiline reStructuredText
literal code block
""", """
Summary line
.. rubric:: Example
Multiline reStructuredText
literal code block
"""),
################################
("""
Summary line
Example::
Multiline reStructuredText
literal code block
""", """
Summary line
Example::
Multiline reStructuredText
literal code block
"""),
################################
("""
Summary line
:Example:
Multiline reStructuredText
literal code block
""", """
Summary line
:Example:
Multiline reStructuredText
literal code block
""")]
for docstring, expected in docstrings:
actual = str(GoogleDocstring(docstring))
self.assertEqual(expected, actual)
def test_list_in_parameter_description(self):
docstring = """One line summary.
Parameters:
no_list (int):
one_bullet_empty (int):
*
one_bullet_single_line (int):
- first line
one_bullet_two_lines (int):
+ first line
continued
two_bullets_single_line (int):
- first line
- second line
two_bullets_two_lines (int):
* first line
continued
* second line
continued
one_enumeration_single_line (int):
1. first line
one_enumeration_two_lines (int):
1) first line
continued
two_enumerations_one_line (int):
(iii) first line
(iv) second line
two_enumerations_two_lines (int):
a. first line
continued
b. second line
continued
one_definition_one_line (int):
item 1
first line
one_definition_two_lines (int):
item 1
first line
continued
two_definitions_one_line (int):
item 1
first line
item 2
second line
two_definitions_two_lines (int):
item 1
first line
continued
item 2
second line
continued
one_definition_blank_line (int):
item 1
first line
extra first line
two_definitions_blank_lines (int):
item 1
first line
extra first line
item 2
second line
extra second line
definition_after_inline_text (int): text line
item 1
first line
definition_after_normal_text (int):
text line
item 1
first line
"""
expected = """One line summary.
:param no_list:
:type no_list: int
:param one_bullet_empty:
*
:type one_bullet_empty: int
:param one_bullet_single_line:
- first line
:type one_bullet_single_line: int
:param one_bullet_two_lines:
+ first line
continued
:type one_bullet_two_lines: int
:param two_bullets_single_line:
- first line
- second line
:type two_bullets_single_line: int
:param two_bullets_two_lines:
* first line
continued
* second line
continued
:type two_bullets_two_lines: int
:param one_enumeration_single_line:
1. first line
:type one_enumeration_single_line: int
:param one_enumeration_two_lines:
1) first line
continued
:type one_enumeration_two_lines: int
:param two_enumerations_one_line:
(iii) first line
(iv) second line
:type two_enumerations_one_line: int
:param two_enumerations_two_lines:
a. first line
continued
b. second line
continued
:type two_enumerations_two_lines: int
:param one_definition_one_line:
item 1
first line
:type one_definition_one_line: int
:param one_definition_two_lines:
item 1
first line
continued
:type one_definition_two_lines: int
:param two_definitions_one_line:
item 1
first line
item 2
second line
:type two_definitions_one_line: int
:param two_definitions_two_lines:
item 1
first line
continued
item 2
second line
continued
:type two_definitions_two_lines: int
:param one_definition_blank_line:
item 1
first line
extra first line
:type one_definition_blank_line: int
:param two_definitions_blank_lines:
item 1
first line
extra first line
item 2
second line
extra second line
:type two_definitions_blank_lines: int
:param definition_after_inline_text: text line
item 1
first line
:type definition_after_inline_text: int
:param definition_after_normal_text: text line
item 1
first line
:type definition_after_normal_text: int
"""
config = Config(napoleon_use_param=True)
actual = str(GoogleDocstring(docstring, config))
self.assertEqual(expected, actual)
expected = """One line summary.
:Parameters: * **no_list** (*int*)
* **one_bullet_empty** (*int*) --
*
* **one_bullet_single_line** (*int*) --
- first line
* **one_bullet_two_lines** (*int*) --
+ first line
continued
* **two_bullets_single_line** (*int*) --
- first line
- second line
* **two_bullets_two_lines** (*int*) --
* first line
continued
* second line
continued
* **one_enumeration_single_line** (*int*) --
1. first line
* **one_enumeration_two_lines** (*int*) --
1) first line
continued
* **two_enumerations_one_line** (*int*) --
(iii) first line
(iv) second line
* **two_enumerations_two_lines** (*int*) --
a. first line
continued
b. second line
continued
* **one_definition_one_line** (*int*) --
item 1
first line
* **one_definition_two_lines** (*int*) --
item 1
first line
continued
* **two_definitions_one_line** (*int*) --
item 1
first line
item 2
second line
* **two_definitions_two_lines** (*int*) --
item 1
first line
continued
item 2
second line
continued
* **one_definition_blank_line** (*int*) --
item 1
first line
extra first line
* **two_definitions_blank_lines** (*int*) --
item 1
first line
extra first line
item 2
second line
extra second line
* **definition_after_inline_text** (*int*) -- text line
item 1
first line
* **definition_after_normal_text** (*int*) -- text line
item 1
first line
"""
config = Config(napoleon_use_param=False)
actual = str(GoogleDocstring(docstring, config))
self.assertEqual(expected, actual)
def test_custom_generic_sections(self):
docstrings = (("""\
Really Important Details:
You should listen to me!
""", """.. rubric:: Really Important Details
You should listen to me!
"""),
("""\
Sooper Warning:
Stop hitting yourself!
""", """:Warns: **Stop hitting yourself!**
"""),
("""\
Params Style:
arg1 (int): Description of arg1
arg2 (str): Description of arg2
""", """\
:Params Style: * **arg1** (*int*) -- Description of arg1
* **arg2** (*str*) -- Description of arg2
"""),
("""\
Returns Style:
description of custom section
""", """:Returns Style: description of custom section
"""))
testConfig = Config(napoleon_custom_sections=['Really Important Details',
('Sooper Warning', 'warns'),
('Params Style', 'params_style'),
('Returns Style', 'returns_style')])
for docstring, expected in docstrings:
actual = str(GoogleDocstring(docstring, testConfig))
self.assertEqual(expected, actual)
def test_noindex(self):
docstring = """
Attributes:
arg
description
Methods:
func(i, j)
description
"""
expected = """
.. attribute:: arg
:noindex:
description
.. method:: func(i, j)
:noindex:
description
""" # NOQA
config = Config()
actual = str(GoogleDocstring(docstring, config=config, app=None, what='module',
options={'noindex': True}))
self.assertEqual(expected, actual)
def test_keywords_with_types(self):
docstring = """\
Do as you please
Keyword Args:
gotham_is_yours (None): shall interfere.
"""
actual = str(GoogleDocstring(docstring))
expected = """\
Do as you please
:keyword gotham_is_yours: shall interfere.
:kwtype gotham_is_yours: None
"""
self.assertEqual(expected, actual)
def test_pep526_annotations(self):
if sys.version_info >= (3, 6):
# Test class attributes annotations
config = Config(
napoleon_attr_annotations=True
)
actual = str(GoogleDocstring(cleandoc(PEP526GoogleClass.__doc__), config, app=None, what="class",
obj=PEP526GoogleClass))
expected = """\
Sample class with PEP 526 annotations and google docstring
.. attribute:: attr1
Attr1 description.
:type: int
.. attribute:: attr2
Attr2 description.
:type: str
"""
self.assertEqual(expected, actual)
def test_preprocess_types(self):
docstring = """\
Do as you please
Yield:
str:Extended
"""
actual = str(GoogleDocstring(docstring))
expected = """\
Do as you please
:Yields: *str* -- Extended
"""
self.assertEqual(expected, actual)
config = Config(napoleon_preprocess_types=True)
actual = str(GoogleDocstring(docstring, config))
expected = """\
Do as you please
:Yields: :class:`str` -- Extended
"""
self.assertEqual(expected, actual)
class NumpyDocstringTest(BaseDocstringTest):
docstrings = [(
"""Single line summary""",
"""Single line summary"""
), (
"""
Single line summary
Extended description
""",
"""
Single line summary
Extended description
"""
), (
"""
Single line summary
Parameters
----------
arg1:str
Extended
description of arg1
""",
"""
Single line summary
:Parameters: **arg1** (:class:`str`) -- Extended
description of arg1
"""
), (
"""
Single line summary
Parameters
----------
arg1:str
Extended
description of arg1
arg2 : int
Extended
description of arg2
Keyword Arguments
-----------------
kwarg1:str
Extended
description of kwarg1
kwarg2 : int
Extended
description of kwarg2
""",
"""
Single line summary
:Parameters: * **arg1** (:class:`str`) -- Extended
description of arg1
* **arg2** (:class:`int`) -- Extended
description of arg2
:Keyword Arguments: * **kwarg1** (:class:`str`) -- Extended
description of kwarg1
* **kwarg2** (:class:`int`) -- Extended
description of kwarg2
"""
), (
"""
Single line summary
Return
------
str
Extended
description of return value
""",
"""
Single line summary
:returns: :class:`str` -- Extended
description of return value
"""
), (
"""
Single line summary
Returns
-------
str
Extended
description of return value
""",
"""
Single line summary
:returns: :class:`str` -- Extended
description of return value
"""
), (
"""
Single line summary
Parameters
----------
arg1:str
Extended description of arg1
*args:
Variable length argument list.
**kwargs:
Arbitrary keyword arguments.
""",
"""
Single line summary
:Parameters: * **arg1** (:class:`str`) -- Extended description of arg1
* **\\*args** -- Variable length argument list.
* **\\*\\*kwargs** -- Arbitrary keyword arguments.
"""
), (
"""
Single line summary
Parameters
----------
arg1:str
Extended description of arg1
*args, **kwargs:
Variable length argument list and arbitrary keyword arguments.
""",
"""
Single line summary
:Parameters: * **arg1** (:class:`str`) -- Extended description of arg1
* **\\*args, \\*\\*kwargs** -- Variable length argument list and arbitrary keyword arguments.
"""
), (
"""
Single line summary
Receive
-------
arg1:str
Extended
description of arg1
arg2 : int
Extended
description of arg2
""",
"""
Single line summary
:Receives: * **arg1** (:class:`str`) -- Extended
description of arg1
* **arg2** (:class:`int`) -- Extended
description of arg2
"""
), (
"""
Single line summary
Receives
--------
arg1:str
Extended
description of arg1
arg2 : int
Extended
description of arg2
""",
"""
Single line summary
:Receives: * **arg1** (:class:`str`) -- Extended
description of arg1
* **arg2** (:class:`int`) -- Extended
description of arg2
"""
), (
"""
Single line summary
Yield
-----
str
Extended
description of yielded value
""",
"""
Single line summary
:Yields: :class:`str` -- Extended
description of yielded value
"""
), (
"""
Single line summary
Yields
------
str
Extended
description of yielded value
""",
"""
Single line summary
:Yields: :class:`str` -- Extended
description of yielded value
"""
)]
def test_sphinx_admonitions(self):
admonition_map = {
'Attention': 'attention',
'Caution': 'caution',
'Danger': 'danger',
'Error': 'error',
'Hint': 'hint',
'Important': 'important',
'Note': 'note',
'Tip': 'tip',
'Todo': 'todo',
'Warning': 'warning',
'Warnings': 'warning',
}
config = Config()
for section, admonition in admonition_map.items():
# Multiline
actual = str(NumpyDocstring(("{}\n"
"{}\n"
" this is the first line\n"
"\n"
" and this is the second line\n"
).format(section, '-' * len(section)), config))
expect = (".. {}::\n"
"\n"
" this is the first line\n"
" \n"
" and this is the second line\n"
).format(admonition)
self.assertEqual(expect, actual)
# Single line
actual = str(NumpyDocstring(("{}\n"
"{}\n"
" this is a single line\n"
).format(section, '-' * len(section)), config))
expect = (".. {}:: this is a single line\n"
).format(admonition)
self.assertEqual(expect, actual)
def test_docstrings(self):
config = Config(
napoleon_use_param=False,
napoleon_use_rtype=False,
napoleon_use_keyword=False,
napoleon_preprocess_types=True)
for docstring, expected in self.docstrings:
actual = str(NumpyDocstring(dedent(docstring), config))
expected = dedent(expected)
self.assertEqual(expected, actual)
def test_type_preprocessor(self):
docstring = dedent("""
Single line summary
Parameters
----------
arg1:str
Extended
description of arg1
""")
config = Config(napoleon_preprocess_types=False, napoleon_use_param=False)
actual = str(NumpyDocstring(docstring, config))
expected = dedent("""
Single line summary
:Parameters: **arg1** (*str*) -- Extended
description of arg1
""")
self.assertEqual(expected, actual)
def test_parameters_with_class_reference(self):
docstring = """\
Parameters
----------
param1 : :class:`MyClass <name.space.MyClass>` instance
Other Parameters
----------------
param2 : :class:`MyClass <name.space.MyClass>` instance
"""
config = Config(napoleon_use_param=False)
actual = str(NumpyDocstring(docstring, config))
expected = """\
:Parameters: **param1** (:class:`MyClass <name.space.MyClass>` instance)
:Other Parameters: **param2** (:class:`MyClass <name.space.MyClass>` instance)
"""
self.assertEqual(expected, actual)
config = Config(napoleon_use_param=True)
actual = str(NumpyDocstring(docstring, config))
expected = """\
:param param1:
:type param1: :class:`MyClass <name.space.MyClass>` instance
:param param2:
:type param2: :class:`MyClass <name.space.MyClass>` instance
"""
self.assertEqual(expected, actual)
def test_multiple_parameters(self):
docstring = """\
Parameters
----------
x1, x2 : array_like
Input arrays, description of ``x1``, ``x2``.
"""
config = Config(napoleon_use_param=False)
actual = str(NumpyDocstring(docstring, config))
expected = """\
:Parameters: **x1, x2** (*array_like*) -- Input arrays, description of ``x1``, ``x2``.
"""
self.assertEqual(expected, actual)
config = Config(napoleon_use_param=True)
actual = str(NumpyDocstring(dedent(docstring), config))
expected = """\
:param x1: Input arrays, description of ``x1``, ``x2``.
:type x1: array_like
:param x2: Input arrays, description of ``x1``, ``x2``.
:type x2: array_like
"""
self.assertEqual(expected, actual)
def test_parameters_without_class_reference(self):
docstring = """\
Parameters
----------
param1 : MyClass instance
"""
config = Config(napoleon_use_param=False)
actual = str(NumpyDocstring(docstring, config))
expected = """\
:Parameters: **param1** (*MyClass instance*)
"""
self.assertEqual(expected, actual)
config = Config(napoleon_use_param=True)
actual = str(NumpyDocstring(dedent(docstring), config))
expected = """\
:param param1:
:type param1: MyClass instance
"""
self.assertEqual(expected, actual)
def test_see_also_refs(self):
docstring = """\
numpy.multivariate_normal(mean, cov, shape=None, spam=None)
See Also
--------
some, other, funcs
otherfunc : relationship
"""
actual = str(NumpyDocstring(docstring))
expected = """\
numpy.multivariate_normal(mean, cov, shape=None, spam=None)
.. seealso::
:obj:`some`, :obj:`other`, :obj:`funcs`
\n\
:obj:`otherfunc`
relationship
"""
self.assertEqual(expected, actual)
docstring = """\
numpy.multivariate_normal(mean, cov, shape=None, spam=None)
See Also
--------
some, other, funcs
otherfunc : relationship
"""
config = Config()
app = mock.Mock()
actual = str(NumpyDocstring(docstring, config, app, "method"))
expected = """\
numpy.multivariate_normal(mean, cov, shape=None, spam=None)
.. seealso::
:obj:`some`, :obj:`other`, :obj:`funcs`
\n\
:obj:`otherfunc`
relationship
"""
self.assertEqual(expected, actual)
docstring = """\
numpy.multivariate_normal(mean, cov, shape=None, spam=None)
See Also
--------
some, other, :func:`funcs`
otherfunc : relationship
"""
translations = {
"other": "MyClass.other",
"otherfunc": ":func:`~my_package.otherfunc`",
}
config = Config(napoleon_type_aliases=translations)
app = mock.Mock()
actual = str(NumpyDocstring(docstring, config, app, "method"))
expected = """\
numpy.multivariate_normal(mean, cov, shape=None, spam=None)
.. seealso::
:obj:`some`, :obj:`MyClass.other`, :func:`funcs`
\n\
:func:`~my_package.otherfunc`
relationship
"""
self.assertEqual(expected, actual)
def test_colon_in_return_type(self):
docstring = """
Summary
Returns
-------
:py:class:`~my_mod.my_class`
an instance of :py:class:`~my_mod.my_class`
"""
expected = """
Summary
:returns: an instance of :py:class:`~my_mod.my_class`
:rtype: :py:class:`~my_mod.my_class`
"""
config = Config()
app = mock.Mock()
actual = str(NumpyDocstring(docstring, config, app, "method"))
self.assertEqual(expected, actual)
def test_underscore_in_attribute(self):
docstring = """
Attributes
----------
arg_ : type
some description
"""
expected = """
:ivar arg_: some description
:vartype arg_: type
"""
config = Config(napoleon_use_ivar=True)
app = mock.Mock()
actual = str(NumpyDocstring(docstring, config, app, "class"))
self.assertEqual(expected, actual)
def test_underscore_in_attribute_strip_signature_backslash(self):
docstring = """
Attributes
----------
arg_ : type
some description
"""
expected = """
:ivar arg\\_: some description
:vartype arg\\_: type
"""
config = Config(napoleon_use_ivar=True)
config.strip_signature_backslash = True
app = mock.Mock()
actual = str(NumpyDocstring(docstring, config, app, "class"))
self.assertEqual(expected, actual)
def test_return_types(self):
docstring = dedent("""
Returns
-------
DataFrame
a dataframe
""")
expected = dedent("""
:returns: a dataframe
:rtype: :class:`~pandas.DataFrame`
""")
translations = {
"DataFrame": "~pandas.DataFrame",
}
config = Config(
napoleon_use_param=True,
napoleon_use_rtype=True,
napoleon_preprocess_types=True,
napoleon_type_aliases=translations,
)
actual = str(NumpyDocstring(docstring, config))
self.assertEqual(expected, actual)
def test_yield_types(self):
docstring = dedent("""
Example Function
Yields
------
scalar or array-like
The result of the computation
""")
expected = dedent("""
Example Function
:Yields: :term:`scalar` or :class:`array-like <numpy.ndarray>` -- The result of the computation
""")
translations = {
"scalar": ":term:`scalar`",
"array-like": ":class:`array-like <numpy.ndarray>`",
}
config = Config(napoleon_type_aliases=translations, napoleon_preprocess_types=True)
app = mock.Mock()
actual = str(NumpyDocstring(docstring, config, app, "method"))
self.assertEqual(expected, actual)
def test_raises_types(self):
docstrings = [("""
Example Function
Raises
------
RuntimeError
A setting wasn't specified, or was invalid.
ValueError
Something something value error.
""", """
Example Function
:raises RuntimeError: A setting wasn't specified, or was invalid.
:raises ValueError: Something something value error.
"""),
################################
("""
Example Function
Raises
------
InvalidDimensionsError
""", """
Example Function
:raises InvalidDimensionsError:
"""),
################################
("""
Example Function
Raises
------
Invalid Dimensions Error
""", """
Example Function
:raises Invalid Dimensions Error:
"""),
################################
("""
Example Function
Raises
------
Invalid Dimensions Error
With description
""", """
Example Function
:raises Invalid Dimensions Error: With description
"""),
################################
("""
Example Function
Raises
------
InvalidDimensionsError
If the dimensions couldn't be parsed.
""", """
Example Function
:raises InvalidDimensionsError: If the dimensions couldn't be parsed.
"""),
################################
("""
Example Function
Raises
------
Invalid Dimensions Error
If the dimensions couldn't be parsed.
""", """
Example Function
:raises Invalid Dimensions Error: If the dimensions couldn't be parsed.
"""),
################################
("""
Example Function
Raises
------
If the dimensions couldn't be parsed.
""", """
Example Function
:raises If the dimensions couldn't be parsed.:
"""),
################################
("""
Example Function
Raises
------
:class:`exc.InvalidDimensionsError`
""", """
Example Function
:raises exc.InvalidDimensionsError:
"""),
################################
("""
Example Function
Raises
------
:class:`exc.InvalidDimensionsError`
If the dimensions couldn't be parsed.
""", """
Example Function
:raises exc.InvalidDimensionsError: If the dimensions couldn't be parsed.
"""),
################################
("""
Example Function
Raises
------
:class:`exc.InvalidDimensionsError`
If the dimensions couldn't be parsed,
then a :class:`exc.InvalidDimensionsError` will be raised.
""", """
Example Function
:raises exc.InvalidDimensionsError: If the dimensions couldn't be parsed,
then a :class:`exc.InvalidDimensionsError` will be raised.
"""),
################################
("""
Example Function
Raises
------
:class:`exc.InvalidDimensionsError`
If the dimensions couldn't be parsed.
:class:`exc.InvalidArgumentsError`
If the arguments are invalid.
""", """
Example Function
:raises exc.InvalidDimensionsError: If the dimensions couldn't be parsed.
:raises exc.InvalidArgumentsError: If the arguments are invalid.
"""),
################################
("""
Example Function
Raises
------
CustomError
If the dimensions couldn't be parsed.
""", """
Example Function
:raises package.CustomError: If the dimensions couldn't be parsed.
"""),
################################
("""
Example Function
Raises
------
AnotherError
If the dimensions couldn't be parsed.
""", """
Example Function
:raises ~package.AnotherError: If the dimensions couldn't be parsed.
"""),
################################
("""
Example Function
Raises
------
:class:`exc.InvalidDimensionsError`
:class:`exc.InvalidArgumentsError`
""", """
Example Function
:raises exc.InvalidDimensionsError:
:raises exc.InvalidArgumentsError:
""")]
for docstring, expected in docstrings:
translations = {
"CustomError": "package.CustomError",
"AnotherError": ":py:exc:`~package.AnotherError`",
}
config = Config(napoleon_type_aliases=translations, napoleon_preprocess_types=True)
app = mock.Mock()
actual = str(NumpyDocstring(docstring, config, app, "method"))
self.assertEqual(expected, actual)
def test_xrefs_in_return_type(self):
docstring = """
Example Function
Returns
-------
:class:`numpy.ndarray`
A :math:`n \\times 2` array containing
a bunch of math items
"""
expected = """
Example Function
:returns: A :math:`n \\times 2` array containing
a bunch of math items
:rtype: :class:`numpy.ndarray`
"""
config = Config()
app = mock.Mock()
actual = str(NumpyDocstring(docstring, config, app, "method"))
self.assertEqual(expected, actual)
def test_section_header_underline_length(self):
docstrings = [("""
Summary line
Example
-
Multiline example
body
""", """
Summary line
Example
-
Multiline example
body
"""),
################################
("""
Summary line
Example
--
Multiline example
body
""", """
Summary line
.. rubric:: Example
Multiline example
body
"""),
################################
("""
Summary line
Example
-------
Multiline example
body
""", """
Summary line
.. rubric:: Example
Multiline example
body
"""),
################################
("""
Summary line
Example
------------
Multiline example
body
""", """
Summary line
.. rubric:: Example
Multiline example
body
""")]
for docstring, expected in docstrings:
actual = str(NumpyDocstring(docstring))
self.assertEqual(expected, actual)
def test_list_in_parameter_description(self):
docstring = """One line summary.
Parameters
----------
no_list : int
one_bullet_empty : int
*
one_bullet_single_line : int
- first line
one_bullet_two_lines : int
+ first line
continued
two_bullets_single_line : int
- first line
- second line
two_bullets_two_lines : int
* first line
continued
* second line
continued
one_enumeration_single_line : int
1. first line
one_enumeration_two_lines : int
1) first line
continued
two_enumerations_one_line : int
(iii) first line
(iv) second line
two_enumerations_two_lines : int
a. first line
continued
b. second line
continued
one_definition_one_line : int
item 1
first line
one_definition_two_lines : int
item 1
first line
continued
two_definitions_one_line : int
item 1
first line
item 2
second line
two_definitions_two_lines : int
item 1
first line
continued
item 2
second line
continued
one_definition_blank_line : int
item 1
first line
extra first line
two_definitions_blank_lines : int
item 1
first line
extra first line
item 2
second line
extra second line
definition_after_normal_text : int
text line
item 1
first line
"""
expected = """One line summary.
:param no_list:
:type no_list: int
:param one_bullet_empty:
*
:type one_bullet_empty: int
:param one_bullet_single_line:
- first line
:type one_bullet_single_line: int
:param one_bullet_two_lines:
+ first line
continued
:type one_bullet_two_lines: int
:param two_bullets_single_line:
- first line
- second line
:type two_bullets_single_line: int
:param two_bullets_two_lines:
* first line
continued
* second line
continued
:type two_bullets_two_lines: int
:param one_enumeration_single_line:
1. first line
:type one_enumeration_single_line: int
:param one_enumeration_two_lines:
1) first line
continued
:type one_enumeration_two_lines: int
:param two_enumerations_one_line:
(iii) first line
(iv) second line
:type two_enumerations_one_line: int
:param two_enumerations_two_lines:
a. first line
continued
b. second line
continued
:type two_enumerations_two_lines: int
:param one_definition_one_line:
item 1
first line
:type one_definition_one_line: int
:param one_definition_two_lines:
item 1
first line
continued
:type one_definition_two_lines: int
:param two_definitions_one_line:
item 1
first line
item 2
second line
:type two_definitions_one_line: int
:param two_definitions_two_lines:
item 1
first line
continued
item 2
second line
continued
:type two_definitions_two_lines: int
:param one_definition_blank_line:
item 1
first line
extra first line
:type one_definition_blank_line: int
:param two_definitions_blank_lines:
item 1
first line
extra first line
item 2
second line
extra second line
:type two_definitions_blank_lines: int
:param definition_after_normal_text: text line
item 1
first line
:type definition_after_normal_text: int
"""
config = Config(napoleon_use_param=True)
actual = str(NumpyDocstring(docstring, config))
self.assertEqual(expected, actual)
expected = """One line summary.
:Parameters: * **no_list** (:class:`int`)
* **one_bullet_empty** (:class:`int`) --
*
* **one_bullet_single_line** (:class:`int`) --
- first line
* **one_bullet_two_lines** (:class:`int`) --
+ first line
continued
* **two_bullets_single_line** (:class:`int`) --
- first line
- second line
* **two_bullets_two_lines** (:class:`int`) --
* first line
continued
* second line
continued
* **one_enumeration_single_line** (:class:`int`) --
1. first line
* **one_enumeration_two_lines** (:class:`int`) --
1) first line
continued
* **two_enumerations_one_line** (:class:`int`) --
(iii) first line
(iv) second line
* **two_enumerations_two_lines** (:class:`int`) --
a. first line
continued
b. second line
continued
* **one_definition_one_line** (:class:`int`) --
item 1
first line
* **one_definition_two_lines** (:class:`int`) --
item 1
first line
continued
* **two_definitions_one_line** (:class:`int`) --
item 1
first line
item 2
second line
* **two_definitions_two_lines** (:class:`int`) --
item 1
first line
continued
item 2
second line
continued
* **one_definition_blank_line** (:class:`int`) --
item 1
first line
extra first line
* **two_definitions_blank_lines** (:class:`int`) --
item 1
first line
extra first line
item 2
second line
extra second line
* **definition_after_normal_text** (:class:`int`) -- text line
item 1
first line
"""
config = Config(napoleon_use_param=False, napoleon_preprocess_types=True)
actual = str(NumpyDocstring(docstring, config))
self.assertEqual(expected, actual)
def test_token_type(self):
tokens = (
("1", "literal"),
("-4.6", "literal"),
("2j", "literal"),
("'string'", "literal"),
('"another_string"', "literal"),
("{1, 2}", "literal"),
("{'va{ue', 'set'}", "literal"),
("optional", "control"),
("default", "control"),
(", ", "delimiter"),
(" of ", "delimiter"),
(" or ", "delimiter"),
(": ", "delimiter"),
("True", "obj"),
("None", "obj"),
("name", "obj"),
(":py:class:`Enum`", "reference"),
)
for token, expected in tokens:
actual = _token_type(token)
self.assertEqual(expected, actual)
def test_tokenize_type_spec(self):
specs = (
"str",
"defaultdict",
"int, float, or complex",
"int or float or None, optional",
'{"F", "C", "N"}',
"{'F', 'C', 'N'}, default: 'F'",
"{'F', 'C', 'N or C'}, default 'F'",
"str, default: 'F or C'",
"int, default: None",
"int, default None",
"int, default :obj:`None`",
'"ma{icious"',
r"'with \'quotes\''",
)
tokens = (
["str"],
["defaultdict"],
["int", ", ", "float", ", or ", "complex"],
["int", " or ", "float", " or ", "None", ", ", "optional"],
["{", '"F"', ", ", '"C"', ", ", '"N"', "}"],
["{", "'F'", ", ", "'C'", ", ", "'N'", "}", ", ", "default", ": ", "'F'"],
["{", "'F'", ", ", "'C'", ", ", "'N or C'", "}", ", ", "default", " ", "'F'"],
["str", ", ", "default", ": ", "'F or C'"],
["int", ", ", "default", ": ", "None"],
["int", ", ", "default", " ", "None"],
["int", ", ", "default", " ", ":obj:`None`"],
['"ma{icious"'],
[r"'with \'quotes\''"],
)
for spec, expected in zip(specs, tokens):
actual = _tokenize_type_spec(spec)
self.assertEqual(expected, actual)
def test_recombine_set_tokens(self):
tokens = (
["{", "1", ", ", "2", "}"],
["{", '"F"', ", ", '"C"', ", ", '"N"', "}", ", ", "optional"],
["{", "'F'", ", ", "'C'", ", ", "'N'", "}", ", ", "default", ": ", "None"],
["{", "'F'", ", ", "'C'", ", ", "'N'", "}", ", ", "default", " ", "None"],
)
combined_tokens = (
["{1, 2}"],
['{"F", "C", "N"}', ", ", "optional"],
["{'F', 'C', 'N'}", ", ", "default", ": ", "None"],
["{'F', 'C', 'N'}", ", ", "default", " ", "None"],
)
for tokens_, expected in zip(tokens, combined_tokens):
actual = _recombine_set_tokens(tokens_)
self.assertEqual(expected, actual)
def test_recombine_set_tokens_invalid(self):
tokens = (
["{", "1", ", ", "2"],
['"F"', ", ", '"C"', ", ", '"N"', "}", ", ", "optional"],
["{", "1", ", ", "2", ", ", "default", ": ", "None"],
)
combined_tokens = (
["{1, 2"],
['"F"', ", ", '"C"', ", ", '"N"', "}", ", ", "optional"],
["{1, 2", ", ", "default", ": ", "None"],
)
for tokens_, expected in zip(tokens, combined_tokens):
actual = _recombine_set_tokens(tokens_)
self.assertEqual(expected, actual)
def test_convert_numpy_type_spec(self):
translations = {
"DataFrame": "pandas.DataFrame",
}
specs = (
"",
"optional",
"str, optional",
"int or float or None, default: None",
"int, default None",
'{"F", "C", "N"}',
"{'F', 'C', 'N'}, default: 'N'",
"{'F', 'C', 'N'}, default 'N'",
"DataFrame, optional",
)
converted = (
"",
"*optional*",
":class:`str`, *optional*",
":class:`int` or :class:`float` or :obj:`None`, *default*: :obj:`None`",
":class:`int`, *default* :obj:`None`",
'``{"F", "C", "N"}``',
"``{'F', 'C', 'N'}``, *default*: ``'N'``",
"``{'F', 'C', 'N'}``, *default* ``'N'``",
":class:`pandas.DataFrame`, *optional*",
)
for spec, expected in zip(specs, converted):
actual = _convert_numpy_type_spec(spec, translations=translations)
self.assertEqual(expected, actual)
def test_parameter_types(self):
docstring = dedent("""\
Parameters
----------
param1 : DataFrame
the data to work on
param2 : int or float or None, optional
a parameter with different types
param3 : dict-like, optional
a optional mapping
param4 : int or float or None, optional
a optional parameter with different types
param5 : {"F", "C", "N"}, optional
a optional parameter with fixed values
param6 : int, default None
different default format
param7 : mapping of hashable to str, optional
a optional mapping
param8 : ... or Ellipsis
ellipsis
""")
expected = dedent("""\
:param param1: the data to work on
:type param1: :class:`DataFrame`
:param param2: a parameter with different types
:type param2: :class:`int` or :class:`float` or :obj:`None`, *optional*
:param param3: a optional mapping
:type param3: :term:`dict-like <mapping>`, *optional*
:param param4: a optional parameter with different types
:type param4: :class:`int` or :class:`float` or :obj:`None`, *optional*
:param param5: a optional parameter with fixed values
:type param5: ``{"F", "C", "N"}``, *optional*
:param param6: different default format
:type param6: :class:`int`, *default* :obj:`None`
:param param7: a optional mapping
:type param7: :term:`mapping` of :term:`hashable` to :class:`str`, *optional*
:param param8: ellipsis
:type param8: :obj:`... <Ellipsis>` or :obj:`Ellipsis`
""")
translations = {
"dict-like": ":term:`dict-like <mapping>`",
"mapping": ":term:`mapping`",
"hashable": ":term:`hashable`",
}
config = Config(
napoleon_use_param=True,
napoleon_use_rtype=True,
napoleon_preprocess_types=True,
napoleon_type_aliases=translations,
)
actual = str(NumpyDocstring(docstring, config))
self.assertEqual(expected, actual)
@contextmanager
def warns(warning, match):
match_re = re.compile(match)
try:
yield warning
finally:
raw_warnings = warning.getvalue()
warnings = [w for w in raw_warnings.split("\n") if w.strip()]
assert len(warnings) == 1 and all(match_re.match(w) for w in warnings)
warning.truncate(0)
class TestNumpyDocstring:
def test_token_type_invalid(self, warning):
tokens = (
"{1, 2",
"}",
"'abc",
"def'",
'"ghi',
'jkl"',
)
errors = (
r".+: invalid value set \(missing closing brace\):",
r".+: invalid value set \(missing opening brace\):",
r".+: malformed string literal \(missing closing quote\):",
r".+: malformed string literal \(missing opening quote\):",
r".+: malformed string literal \(missing closing quote\):",
r".+: malformed string literal \(missing opening quote\):",
)
for token, error in zip(tokens, errors):
with warns(warning, match=error):
_token_type(token)
@pytest.mark.parametrize(
("name", "expected"),
(
("x, y, z", "x, y, z"),
("*args, **kwargs", r"\*args, \*\*kwargs"),
("*x, **y", r"\*x, \*\*y"),
),
)
def test_escape_args_and_kwargs(self, name, expected):
numpy_docstring = NumpyDocstring("")
actual = numpy_docstring._escape_args_and_kwargs(name)
assert actual == expected
def test_pep526_annotations(self):
if sys.version_info >= (3, 6):
# test class attributes annotations
config = Config(
napoleon_attr_annotations=True
)
actual = str(NumpyDocstring(cleandoc(PEP526NumpyClass.__doc__), config, app=None, what="class",
obj=PEP526NumpyClass))
expected = """\
Sample class with PEP 526 annotations and numpy docstring
.. attribute:: attr1
Attr1 description
:type: int
.. attribute:: attr2
Attr2 description
:type: str
"""
print(actual)
assert expected == actual
| 26.353351 | 114 | 0.505454 |
acf000aeb54497e212420fad8607f2cae2f670d9 | 15,469 | py | Python | tests/python/test_ndarray.py | gaoxinge/taichi | 86d403f071b8505858763d4712b37cd71b89db91 | [
"MIT"
] | null | null | null | tests/python/test_ndarray.py | gaoxinge/taichi | 86d403f071b8505858763d4712b37cd71b89db91 | [
"MIT"
] | null | null | null | tests/python/test_ndarray.py | gaoxinge/taichi | 86d403f071b8505858763d4712b37cd71b89db91 | [
"MIT"
] | null | null | null | import copy
import numpy as np
import pytest
from taichi.lang import impl
from taichi.lang.misc import get_host_arch_list
from taichi.lang.util import has_pytorch
import taichi as ti
from tests import test_utils
if has_pytorch():
import torch
# properties
data_types = [ti.i32, ti.f32, ti.i64, ti.f64]
ndarray_shapes = [(), 8, (6, 12)]
vector_dims = [3]
matrix_dims = [(1, 2), (2, 3)]
supported_archs_taichi_ndarray = [ti.cpu, ti.cuda, ti.opengl, ti.vulkan]
def _test_scalar_ndarray(dtype, shape):
x = ti.ndarray(dtype, shape)
if isinstance(shape, tuple):
assert x.shape == shape
else:
assert x.shape == (shape, )
assert x.element_shape == ()
assert x.dtype == dtype
@pytest.mark.parametrize('dtype', data_types)
@pytest.mark.parametrize('shape', ndarray_shapes)
@test_utils.test(arch=get_host_arch_list())
def test_scalar_ndarray(dtype, shape):
_test_scalar_ndarray(dtype, shape)
def _test_vector_ndarray(n, dtype, shape):
x = ti.Vector.ndarray(n, dtype, shape)
if isinstance(shape, tuple):
assert x.shape == shape
else:
assert x.shape == (shape, )
assert x.element_shape == (n, )
assert x.dtype == dtype
assert x.n == n
@pytest.mark.parametrize('n', vector_dims)
@pytest.mark.parametrize('dtype', data_types)
@pytest.mark.parametrize('shape', ndarray_shapes)
@test_utils.test(arch=get_host_arch_list())
def test_vector_ndarray(n, dtype, shape):
_test_vector_ndarray(n, dtype, shape)
def _test_matrix_ndarray(n, m, dtype, shape):
x = ti.Matrix.ndarray(n, m, dtype, shape)
if isinstance(shape, tuple):
assert x.shape == shape
else:
assert x.shape == (shape, )
assert x.element_shape == (n, m)
assert x.dtype == dtype
assert x.n == n
assert x.m == m
@pytest.mark.parametrize('n,m', matrix_dims)
@pytest.mark.parametrize('dtype', data_types)
@pytest.mark.parametrize('shape', ndarray_shapes)
@test_utils.test(arch=get_host_arch_list())
def test_matrix_ndarray(n, m, dtype, shape):
_test_matrix_ndarray(n, m, dtype, shape)
@pytest.mark.parametrize('dtype', [ti.f32, ti.f64])
def test_default_fp_ndarray(dtype):
ti.init(arch=supported_archs_taichi_ndarray, default_fp=dtype)
x = ti.Vector.ndarray(2, float, ())
assert x.dtype == impl.get_runtime().default_fp
@pytest.mark.parametrize('dtype', [ti.i32, ti.i64])
def test_default_ip_ndarray(dtype):
ti.init(arch=supported_archs_taichi_ndarray, default_ip=dtype)
x = ti.Vector.ndarray(2, int, ())
assert x.dtype == impl.get_runtime().default_ip
# access
layouts = [ti.Layout.SOA, ti.Layout.AOS]
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_ndarray_1d():
n = 4
@ti.kernel
def run(x: ti.types.ndarray(), y: ti.types.ndarray()):
for i in range(n):
x[i] += i + y[i]
a = ti.ndarray(ti.i32, shape=(n, ))
for i in range(n):
a[i] = i * i
b = np.ones((n, ), dtype=np.int32)
run(a, b)
for i in range(n):
assert a[i] == i * i + i + 1
run(b, a)
for i in range(n):
assert b[i] == i * i + (i + 1) * 2
def _test_ndarray_2d():
n = 4
m = 7
@ti.kernel
def run(x: ti.types.ndarray(), y: ti.types.ndarray()):
for i in range(n):
for j in range(m):
x[i, j] += i + j + y[i, j]
a = ti.ndarray(ti.i32, shape=(n, m))
for i in range(n):
for j in range(m):
a[i, j] = i * j
b = np.ones((n, m), dtype=np.int32)
run(a, b)
for i in range(n):
for j in range(m):
assert a[i, j] == i * j + i + j + 1
run(b, a)
for i in range(n):
for j in range(m):
assert b[i, j] == i * j + (i + j + 1) * 2
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_ndarray_2d():
_test_ndarray_2d()
def _test_ndarray_copy_from_ndarray():
n = 16
a = ti.ndarray(ti.i32, shape=n)
b = ti.ndarray(ti.i32, shape=n)
a[0] = 1
a[4] = 2
b[0] = 4
b[4] = 5
a.copy_from(b)
assert a[0] == 4
assert a[4] == 5
x = ti.Vector.ndarray(10, ti.i32, 5, layout=ti.Layout.SOA)
y = ti.Vector.ndarray(10, ti.i32, 5, layout=ti.Layout.SOA)
x[1][0] = 1
x[2][4] = 2
y[1][0] = 4
y[2][4] = 5
x.copy_from(y)
assert x[1][0] == 4
assert x[2][4] == 5
x = ti.Matrix.ndarray(2, 2, ti.i32, 5, layout=ti.Layout.AOS)
y = ti.Matrix.ndarray(2, 2, ti.i32, 5, layout=ti.Layout.AOS)
x[0][0, 0] = 1
x[4][1, 0] = 3
y[0][0, 0] = 4
y[4][1, 0] = 6
x.copy_from(y)
assert x[0][0, 0] == 4
assert x[4][1, 0] == 6
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_ndarray_copy_from_ndarray():
_test_ndarray_copy_from_ndarray()
def _test_ndarray_deepcopy():
n = 16
x = ti.ndarray(ti.i32, shape=n)
x[0] = 1
x[4] = 2
y = copy.deepcopy(x)
assert y.shape == x.shape
assert y.dtype == x.dtype
assert y[0] == 1
assert y[4] == 2
x[0] = 4
x[4] = 5
assert y[0] == 1
assert y[4] == 2
x = ti.Vector.ndarray(10, ti.i32, 5, layout=ti.Layout.SOA)
x[1][0] = 4
x[2][4] = 5
y = copy.deepcopy(x)
assert y.shape == x.shape
assert y.dtype == x.dtype
assert y.n == x.n
assert y.layout == x.layout
assert y[1][0] == 4
assert y[2][4] == 5
x[1][0] = 1
x[2][4] = 2
assert y[1][0] == 4
assert y[2][4] == 5
x = ti.Matrix.ndarray(2, 2, ti.i32, 5, layout=ti.Layout.AOS)
x[0][0, 0] = 7
x[4][1, 0] = 9
y = copy.deepcopy(x)
assert y.shape == x.shape
assert y.dtype == x.dtype
assert y.m == x.m
assert y.n == x.n
assert y.layout == x.layout
assert y[0][0, 0] == 7
assert y[4][1, 0] == 9
x[0][0, 0] = 3
x[4][1, 0] = 5
assert y[0][0, 0] == 7
assert y[4][1, 0] == 9
def test_ndarray_cuda_caching_allocator():
ti.init(arch=ti.cuda, ndarray_use_cached_allocator=True)
n = 8
a = ti.ndarray(ti.i32, shape=(n))
a.fill(2)
a = 1
b = ti.ndarray(ti.i32, shape=(n))
b.fill(2)
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_ndarray_fill():
n = 8
a = ti.ndarray(ti.i32, shape=(n))
anp = np.ones((n, ), dtype=np.int32)
a.fill(2)
anp.fill(2)
assert (a.to_numpy() == anp).all()
b = ti.Vector.ndarray(4, ti.f32, shape=(n))
bnp = np.ones(shape=b.arr.shape, dtype=np.float32)
b.fill(2.5)
bnp.fill(2.5)
assert (b.to_numpy() == bnp).all()
c = ti.Matrix.ndarray(4, 4, ti.f32, shape=(n))
cnp = np.ones(shape=c.arr.shape, dtype=np.float32)
c.fill(1.5)
cnp.fill(1.5)
assert (c.to_numpy() == cnp).all()
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_ndarray_rw_cache():
a = ti.Vector.ndarray(3, ti.f32, ())
b = ti.Vector.ndarray(3, ti.f32, 12)
n = 1000
for i in range(n):
c_a = copy.deepcopy(a)
c_b = copy.deepcopy(b)
c_a[None] = c_b[10]
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_ndarray_deepcopy():
_test_ndarray_deepcopy()
def _test_ndarray_numpy_io():
n = 7
m = 4
a = ti.ndarray(ti.i32, shape=(n, m))
a.fill(2)
b = ti.ndarray(ti.i32, shape=(n, m))
b.from_numpy(np.ones((n, m), dtype=np.int32) * 2)
assert (a.to_numpy() == b.to_numpy()).all()
d = 2
p = 4
x = ti.Vector.ndarray(d, ti.f32, p)
x.fill(2)
y = ti.Vector.ndarray(d, ti.f32, p)
y.from_numpy(np.ones((p, d), dtype=np.int32) * 2)
assert (x.to_numpy() == y.to_numpy()).all()
c = 2
d = 2
p = 4
x = ti.Matrix.ndarray(c, d, ti.f32, p)
x.fill(2)
y = ti.Matrix.ndarray(c, d, ti.f32, p)
y.from_numpy(np.ones((p, c, d), dtype=np.int32) * 2)
assert (x.to_numpy() == y.to_numpy()).all()
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_ndarray_numpy_io():
_test_ndarray_numpy_io()
def _test_ndarray_matrix_numpy_io(layout):
n = 5
m = 2
x = ti.Vector.ndarray(n, ti.i32, (m, ), layout)
if layout == ti.Layout.AOS:
x_np = 1 + np.arange(n * m).reshape(m, n).astype(np.int32)
else:
x_np = 1 + np.arange(n * m).reshape(n, m).astype(np.int32)
x.from_numpy(x_np)
assert (x_np.flatten() == x.to_numpy().flatten()).all()
k = 2
x = ti.Matrix.ndarray(m, k, ti.i32, n, layout)
if layout == ti.Layout.AOS:
x_np = 1 + np.arange(m * k * n).reshape(n, m, k).astype(np.int32)
else:
x_np = 1 + np.arange(m * k * n).reshape(m, k, n).astype(np.int32)
x.from_numpy(x_np)
assert (x_np.flatten() == x.to_numpy().flatten()).all()
@pytest.mark.parametrize('layout', layouts)
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_ndarray_matrix_numpy_io(layout):
_test_ndarray_matrix_numpy_io(layout)
def _test_matrix_ndarray_python_scope(layout):
a = ti.Matrix.ndarray(2, 2, ti.i32, 5, layout=layout)
for i in range(5):
for j, k in ti.ndrange(2, 2):
a[i][j, k] = j * j + k * k
assert a[0][0, 0] == 0
assert a[1][0, 1] == 1
assert a[2][1, 0] == 1
assert a[3][1, 1] == 2
assert a[4][0, 1] == 1
@pytest.mark.parametrize('layout', layouts)
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_matrix_ndarray_python_scope(layout):
_test_matrix_ndarray_python_scope(layout)
def _test_matrix_ndarray_taichi_scope(layout):
@ti.kernel
def func(a: ti.types.ndarray()):
for i in range(5):
for j, k in ti.ndrange(2, 2):
a[i][j, k] = j * j + k * k
m = ti.Matrix.ndarray(2, 2, ti.i32, 5, layout=layout)
func(m)
assert m[0][0, 0] == 0
assert m[1][0, 1] == 1
assert m[2][1, 0] == 1
assert m[3][1, 1] == 2
assert m[4][0, 1] == 1
@pytest.mark.parametrize('layout', layouts)
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_matrix_ndarray_taichi_scope(layout):
_test_matrix_ndarray_taichi_scope(layout)
def _test_matrix_ndarray_taichi_scope_struct_for(layout):
@ti.kernel
def func(a: ti.types.ndarray()):
for i in a:
for j, k in ti.ndrange(2, 2):
a[i][j, k] = j * j + k * k
m = ti.Matrix.ndarray(2, 2, ti.i32, 5, layout=layout)
func(m)
assert m[0][0, 0] == 0
assert m[1][0, 1] == 1
assert m[2][1, 0] == 1
assert m[3][1, 1] == 2
assert m[4][0, 1] == 1
@pytest.mark.parametrize('layout', layouts)
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_matrix_ndarray_taichi_scope_struct_for(layout):
_test_matrix_ndarray_taichi_scope_struct_for(layout)
@pytest.mark.parametrize('layout', layouts)
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_vector_ndarray_python_scope(layout):
a = ti.Vector.ndarray(10, ti.i32, 5, layout=layout)
for i in range(5):
for j in range(4):
a[i][j * j] = j * j
assert a[0][9] == 9
assert a[1][0] == 0
assert a[2][1] == 1
assert a[3][4] == 4
assert a[4][9] == 9
@pytest.mark.parametrize('layout', layouts)
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_vector_ndarray_taichi_scope(layout):
@ti.kernel
def func(a: ti.types.ndarray()):
for i in range(5):
for j in range(4):
a[i][j * j] = j * j
v = ti.Vector.ndarray(10, ti.i32, 5, layout=layout)
func(v)
assert v[0][9] == 9
assert v[1][0] == 0
assert v[2][1] == 1
assert v[3][4] == 4
assert v[4][9] == 9
# number of compiled functions
def _test_compiled_functions():
@ti.kernel
def func(a: ti.types.ndarray(element_dim=1)):
for i in range(5):
for j in range(4):
a[i][j * j] = j * j
v = ti.Vector.ndarray(10, ti.i32, 5)
func(v)
assert impl.get_runtime().get_num_compiled_functions() == 1
v = np.zeros((6, 10), dtype=np.int32)
func(v)
assert impl.get_runtime().get_num_compiled_functions() == 1
v = np.zeros((6, 11), dtype=np.int32)
func(v)
assert impl.get_runtime().get_num_compiled_functions() == 2
v = ti.Vector.ndarray(10, ti.i32, 5, layout=ti.Layout.SOA)
func(v)
assert impl.get_runtime().get_num_compiled_functions() == 3
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_compiled_functions():
_test_compiled_functions()
# annotation compatibility
def _test_arg_not_match():
@ti.kernel
def func1(a: ti.types.ndarray(element_dim=1)):
pass
x = ti.Matrix.ndarray(2, 3, ti.i32, shape=(4, 7))
with pytest.raises(
ValueError,
match=
r'Invalid argument into ti\.types\.ndarray\(\) - required element_dim=1, but .* is provided'
):
func1(x)
@ti.kernel
def func2(a: ti.types.ndarray(element_dim=2)):
pass
x = ti.Vector.ndarray(2, ti.i32, shape=(4, 7))
with pytest.raises(
ValueError,
match=
r'Invalid argument into ti\.types\.ndarray\(\) - required element_dim=2, but .* is provided'
):
func2(x)
@ti.kernel
def func3(a: ti.types.ndarray(layout=ti.Layout.AOS)):
pass
x = ti.Matrix.ndarray(2, 3, ti.i32, shape=(4, 7), layout=ti.Layout.SOA)
with pytest.raises(
ValueError,
match=
r'Invalid argument into ti\.types\.ndarray\(\) - required layout=Layout\.AOS, but .* is provided'
):
func3(x)
@ti.kernel
def func4(a: ti.types.ndarray(layout=ti.Layout.SOA)):
pass
x = ti.Vector.ndarray(2, ti.i32, shape=(4, 7))
with pytest.raises(
ValueError,
match=
r'Invalid argument into ti\.types\.ndarray\(\) - required layout=Layout\.SOA, but .* is provided'
):
func4(x)
@ti.kernel
def func5(a: ti.types.ndarray(element_shape=(2, 3))):
pass
x = ti.Vector.ndarray(2, ti.i32, shape=(4, 7))
with pytest.raises(
ValueError,
match=
r'Invalid argument into ti\.types\.ndarray\(\) - required element_dim'
):
func5(x)
with pytest.raises(
ValueError,
match=r'Both element_shape and element_dim are specified'):
@ti.kernel
def func6(a: ti.types.ndarray(element_dim=1, element_shape=(2, 3))):
pass
@ti.kernel
def func7(a: ti.types.ndarray(field_dim=2)):
pass
x = ti.ndarray(ti.i32, shape=(3, ))
with pytest.raises(
ValueError,
match=
r'Invalid argument into ti\.types\.ndarray\(\) - required field_dim'
):
func7(x)
@test_utils.test(arch=get_host_arch_list())
def test_arg_not_match():
_test_arg_not_match()
def _test_size_in_bytes():
a = ti.ndarray(ti.i32, 8)
assert a._get_element_size() == 4
assert a._get_nelement() == 8
b = ti.Vector.ndarray(10, ti.f64, 5)
assert b._get_element_size() == 8
assert b._get_nelement() == 50
@test_utils.test(arch=[ti.cpu, ti.cuda])
def test_size_in_bytes():
_test_size_in_bytes()
@test_utils.test(arch=supported_archs_taichi_ndarray)
def test_different_shape():
n1 = 4
x = ti.ndarray(dtype=ti.f32, shape=(n1, n1))
@ti.kernel
def init(d: ti.i32, arr: ti.types.ndarray()):
for i, j in arr:
arr[i, j] = d
init(2, x)
assert (x.to_numpy() == (np.ones(shape=(n1, n1)) * 2)).all()
n2 = 8
y = ti.ndarray(dtype=ti.f32, shape=(n2, n2))
init(3, y)
assert (y.to_numpy() == (np.ones(shape=(n2, n2)) * 3)).all()
| 25.359016 | 109 | 0.595449 |
acf001b3deb18b30b047cb5f7b63252b08837e26 | 7,837 | py | Python | contrib/bitrpc/bitrpc.py | testbitz/blackbitz | 99287831d68b0d8f59a2a375f54db9fe4531c12d | [
"MIT"
] | null | null | null | contrib/bitrpc/bitrpc.py | testbitz/blackbitz | 99287831d68b0d8f59a2a375f54db9fe4531c12d | [
"MIT"
] | null | null | null | contrib/bitrpc/bitrpc.py | testbitz/blackbitz | 99287831d68b0d8f59a2a375f54db9fe4531c12d | [
"MIT"
] | null | null | null | from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:46942")
else:
access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:46942")
cmd = sys.argv[1].lower()
if cmd == "backupwallet":
try:
path = raw_input("Enter destination path/filename: ")
print access.backupwallet(path)
except:
print "\n---An error occurred---\n"
elif cmd == "getaccount":
try:
addr = raw_input("Enter a Bitcoin address: ")
print access.getaccount(addr)
except:
print "\n---An error occurred---\n"
elif cmd == "getaccountaddress":
try:
acct = raw_input("Enter an account name: ")
print access.getaccountaddress(acct)
except:
print "\n---An error occurred---\n"
elif cmd == "getaddressesbyaccount":
try:
acct = raw_input("Enter an account name: ")
print access.getaddressesbyaccount(acct)
except:
print "\n---An error occurred---\n"
elif cmd == "getbalance":
try:
acct = raw_input("Enter an account (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getbalance(acct, mc)
except:
print access.getbalance()
except:
print "\n---An error occurred---\n"
elif cmd == "getblockbycount":
try:
height = raw_input("Height: ")
print access.getblockbycount(height)
except:
print "\n---An error occurred---\n"
elif cmd == "getblockcount":
try:
print access.getblockcount()
except:
print "\n---An error occurred---\n"
elif cmd == "getblocknumber":
try:
print access.getblocknumber()
except:
print "\n---An error occurred---\n"
elif cmd == "getconnectioncount":
try:
print access.getconnectioncount()
except:
print "\n---An error occurred---\n"
elif cmd == "getdifficulty":
try:
print access.getdifficulty()
except:
print "\n---An error occurred---\n"
elif cmd == "getgenerate":
try:
print access.getgenerate()
except:
print "\n---An error occurred---\n"
elif cmd == "gethashespersec":
try:
print access.gethashespersec()
except:
print "\n---An error occurred---\n"
elif cmd == "getinfo":
try:
print access.getinfo()
except:
print "\n---An error occurred---\n"
elif cmd == "getnewaddress":
try:
acct = raw_input("Enter an account name: ")
try:
print access.getnewaddress(acct)
except:
print access.getnewaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "getreceivedbyaccount":
try:
acct = raw_input("Enter an account (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getreceivedbyaccount(acct, mc)
except:
print access.getreceivedbyaccount()
except:
print "\n---An error occurred---\n"
elif cmd == "getreceivedbyaddress":
try:
addr = raw_input("Enter a Bitcoin address (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getreceivedbyaddress(addr, mc)
except:
print access.getreceivedbyaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "gettransaction":
try:
txid = raw_input("Enter a transaction ID: ")
print access.gettransaction(txid)
except:
print "\n---An error occurred---\n"
elif cmd == "getwork":
try:
data = raw_input("Data (optional): ")
try:
print access.gettransaction(data)
except:
print access.gettransaction()
except:
print "\n---An error occurred---\n"
elif cmd == "help":
try:
cmd = raw_input("Command (optional): ")
try:
print access.help(cmd)
except:
print access.help()
except:
print "\n---An error occurred---\n"
elif cmd == "listaccounts":
try:
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.listaccounts(mc)
except:
print access.listaccounts()
except:
print "\n---An error occurred---\n"
elif cmd == "listreceivedbyaccount":
try:
mc = raw_input("Minimum confirmations (optional): ")
incemp = raw_input("Include empty? (true/false, optional): ")
try:
print access.listreceivedbyaccount(mc, incemp)
except:
print access.listreceivedbyaccount()
except:
print "\n---An error occurred---\n"
elif cmd == "listreceivedbyaddress":
try:
mc = raw_input("Minimum confirmations (optional): ")
incemp = raw_input("Include empty? (true/false, optional): ")
try:
print access.listreceivedbyaddress(mc, incemp)
except:
print access.listreceivedbyaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "listtransactions":
try:
acct = raw_input("Account (optional): ")
count = raw_input("Number of transactions (optional): ")
frm = raw_input("Skip (optional):")
try:
print access.listtransactions(acct, count, frm)
except:
print access.listtransactions()
except:
print "\n---An error occurred---\n"
elif cmd == "move":
try:
frm = raw_input("From: ")
to = raw_input("To: ")
amt = raw_input("Amount:")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
try:
print access.move(frm, to, amt, mc, comment)
except:
print access.move(frm, to, amt)
except:
print "\n---An error occurred---\n"
elif cmd == "sendfrom":
try:
frm = raw_input("From: ")
to = raw_input("To: ")
amt = raw_input("Amount:")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
commentto = raw_input("Comment-to (optional): ")
try:
print access.sendfrom(frm, to, amt, mc, comment, commentto)
except:
print access.sendfrom(frm, to, amt)
except:
print "\n---An error occurred---\n"
elif cmd == "sendmany":
try:
frm = raw_input("From: ")
to = raw_input("To (in format address1:amount1,address2:amount2,...): ")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
try:
print access.sendmany(frm,to,mc,comment)
except:
print access.sendmany(frm,to)
except:
print "\n---An error occurred---\n"
elif cmd == "sendtoaddress":
try:
to = raw_input("To (in format address1:amount1,address2:amount2,...): ")
amt = raw_input("Amount:")
comment = raw_input("Comment (optional): ")
commentto = raw_input("Comment-to (optional): ")
try:
print access.sendtoaddress(to,amt,comment,commentto)
except:
print access.sendtoaddress(to,amt)
except:
print "\n---An error occurred---\n"
elif cmd == "setaccount":
try:
addr = raw_input("Address: ")
acct = raw_input("Account:")
print access.setaccount(addr,acct)
except:
print "\n---An error occurred---\n"
elif cmd == "setgenerate":
try:
gen= raw_input("Generate? (true/false): ")
cpus = raw_input("Max processors/cores (-1 for unlimited, optional):")
try:
print access.setgenerate(gen, cpus)
except:
print access.setgenerate(gen)
except:
print "\n---An error occurred---\n"
elif cmd == "settxfee":
try:
amt = raw_input("Amount:")
print access.settxfee(amt)
except:
print "\n---An error occurred---\n"
elif cmd == "stop":
try:
print access.stop()
except:
print "\n---An error occurred---\n"
elif cmd == "validateaddress":
try:
addr = raw_input("Address: ")
print access.validateaddress(addr)
except:
print "\n---An error occurred---\n"
elif cmd == "walletpassphrase":
try:
pwd = raw_input("Enter wallet passphrase: ")
access.walletpassphrase(pwd, 60)
print "\n---Wallet unlocked---\n"
except:
print "\n---An error occurred---\n"
elif cmd == "walletpassphrasechange":
try:
pwd = raw_input("Enter old wallet passphrase: ")
pwd2 = raw_input("Enter new wallet passphrase: ")
access.walletpassphrasechange(pwd, pwd2)
print
print "\n---Passphrase changed---\n"
except:
print
print "\n---An error occurred---\n"
print
else:
print "Command not found or not supported" | 24.188272 | 79 | 0.668368 |
acf00248d683b86300fa39d098628d1af31189d2 | 10,688 | py | Python | jack/core/model_module.py | mitchelljeff/hack1 | 990d873cbcd40d2978f44560016d18a76800908e | [
"MIT"
] | 1 | 2018-10-23T12:07:31.000Z | 2018-10-23T12:07:31.000Z | jack/core/model_module.py | mitchelljeff/hack1 | 990d873cbcd40d2978f44560016d18a76800908e | [
"MIT"
] | null | null | null | jack/core/model_module.py | mitchelljeff/hack1 | 990d873cbcd40d2978f44560016d18a76800908e | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import logging
import os
from abc import abstractmethod
from typing import Mapping, List, Sequence
import numpy as np
import tensorflow as tf
from jack.core.shared_resources import SharedResources
from jack.core.tensorport import TensorPort
logger = logging.getLogger(__name__)
class ModelModule:
"""A model module defines the actual reader model by processing input tensors and producing output tensors.
A model module encapsulates two computations (possibly overlapping): one which computes all
predictions (to be processed by the output module) and another representing the loss(es) and potenially other
training related outputs. It defines the expected input and output tensor shapes and types via its respective input
and output pairs.
"""
@abstractmethod
def __call__(self, batch: Mapping[TensorPort, np.ndarray],
goal_ports: List[TensorPort] = None) -> Mapping[TensorPort, np.ndarray]:
"""Runs a batch and returns values/outputs for specified goal ports.
Args:
batch: mapping from ports to values
goal_ports: optional output ports, defaults to output_ports of this module will be returned
Returns:
A mapping from goal ports to tensors.
"""
raise NotImplementedError
@property
@abstractmethod
def output_ports(self) -> Sequence[TensorPort]:
"""Returns: Definition of the output ports of this module."""
raise NotImplementedError
@property
@abstractmethod
def input_ports(self) -> Sequence[TensorPort]:
"""Returns: Definition of the input ports."""
raise NotImplementedError
@property
@abstractmethod
def training_input_ports(self) -> Sequence[TensorPort]:
"""Returns: Definition of the input ports necessary to create the training output ports, i.e., they do not have
to be provided during eval and they can include output ports of this module."""
raise NotImplementedError
@property
@abstractmethod
def training_output_ports(self) -> Sequence[TensorPort]:
"""Returns: Definition of the output ports provided during training for this module."""
raise NotImplementedError
@abstractmethod
def setup(self, is_training=True):
"""Sets up the module."""
raise NotImplementedError
@abstractmethod
def store(self, path):
"""Store the state of this module."""
raise NotImplementedError
@abstractmethod
def load(self, path):
"""Load the state of this module."""
raise NotImplementedError
class TFModelModule(ModelModule):
"""This class represents an abstract ModelModule for tensroflow models which requires the implementation of
a small set of methods that produce the TF graphs to create predictions and the training outputs,
and define the ports.
"""
def __init__(self, shared_resources: SharedResources, sess=None):
self.shared_resources = shared_resources
if sess is None:
session_config = tf.ConfigProto(allow_soft_placement=True)
session_config.gpu_options.allow_growth = True
sess = tf.Session(config=session_config)
self.tf_session = sess
# will be set in setup
self._tensors = None
self._placeholders = None
def __call__(self, batch: Mapping[TensorPort, np.ndarray],
goal_ports: List[TensorPort] = None) -> Mapping[TensorPort, np.ndarray]:
"""Runs a batch and returns values/outputs for specified goal ports.
Args:
batch: mapping from ports to values
goal_ports: optional output ports, defaults to output_ports of this module will be returned
Returns:
A mapping from goal ports to tensors.
"""
goal_ports = goal_ports or self.output_ports
feed_dict = self.convert_to_feed_dict(batch)
goal_tensors = [self.tensors[p] for p in goal_ports
if p in self.output_ports or p in self.training_output_ports]
outputs = self.tf_session.run(goal_tensors, feed_dict)
ret = dict(zip(filter(lambda p: p in self.output_ports or p in self.training_output_ports, goal_ports),
outputs))
for p in goal_ports:
if p not in ret and p in batch:
ret[p] = batch[p]
return ret
@abstractmethod
def create_output(self, shared_resources: SharedResources,
*input_tensors: tf.Tensor) -> Sequence[tf.Tensor]:
"""
This function needs to be implemented in order to define how the module produces
output from input tensors corresponding to `input_ports`.
Args:
*input_tensors: a list of input tensors.
Returns:
mapping from defined output ports to their tensors.
"""
raise NotImplementedError
@abstractmethod
def create_training_output(self, shared_resources: SharedResources,
*training_input_tensors: tf.Tensor) -> Sequence[tf.Tensor]:
"""
This function needs to be implemented in order to define how the module produces tensors only used
during training given tensors corresponding to the ones defined by `training_input_ports`, which might include
tensors corresponding to ports defined by `output_ports`. This sub-graph should only be created during training.
Args:
*training_input_tensors: a list of input tensors.
Returns:
mapping from defined training output ports to their tensors.
"""
raise NotImplementedError
def setup(self, is_training=True):
"""Sets up the module.
This usually involves creating the actual tensorflow graph. It is expected to be called after the input module
is set up and shared resources, such as the vocab, config, etc., are prepared already at this point.
"""
old_train_variables = tf.trainable_variables()
old_variables = tf.global_variables()
if "name" in self.shared_resources.config:
with tf.variable_scope(self.shared_resources.config["name"],
initializer=tf.contrib.layers.xavier_initializer()):
self._tensors = {d: d.create_placeholder() for d in self.input_ports}
output_tensors = self.create_output(
self.shared_resources, *[self._tensors[port] for port in self.input_ports])
else: # backward compability
self._tensors = {d: d.create_placeholder() for d in self.input_ports}
output_tensors = self.create_output(
self.shared_resources, *[self._tensors[port] for port in self.input_ports])
self._placeholders = dict(self._tensors)
self._tensors.update(zip(self.output_ports, output_tensors))
if is_training:
if "name" in self.shared_resources.config:
with tf.variable_scope(self.shared_resources.config["name"]):
self._placeholders.update((p, p.create_placeholder()) for p in self.training_input_ports
if p not in self._placeholders and p not in self._tensors)
self._tensors.update(self._placeholders)
input_target_tensors = {p: self._tensors.get(p, None) for p in self.training_input_ports}
training_output_tensors = self.create_training_output(
self.shared_resources, *[input_target_tensors[port] for port in self.training_input_ports])
else: # backward compability
self._placeholders.update((p, p.create_placeholder()) for p in self.training_input_ports
if p not in self._placeholders and p not in self._tensors)
self._tensors.update(self._placeholders)
input_target_tensors = {p: self._tensors.get(p, None) for p in self.training_input_ports}
training_output_tensors = self.create_training_output(
self.shared_resources, *[input_target_tensors[port] for port in self.training_input_ports])
self._tensors.update(zip(self.training_output_ports, training_output_tensors))
self._training_variables = [v for v in tf.trainable_variables() if v not in old_train_variables]
self._saver = tf.train.Saver(self._training_variables, max_to_keep=1)
self._variables = [v for v in tf.global_variables() if v not in old_variables]
self.tf_session.run([v.initializer for v in self.variables])
# Sometimes we want to initialize (partially) with a pre-trained model
init_model = self.shared_resources.config.get('pretrained_model')
if is_training and init_model is not None:
if not init_model.endswith('model_module'):
# path to a reader was provided
init_model = os.path.join(init_model, 'model_module')
# get all variables in the checkpoint file
from tensorflow.python import pywrap_tensorflow
reader = pywrap_tensorflow.NewCheckpointReader(init_model)
init_vars = []
for n in reader.get_variable_to_shape_map().keys():
found = False
for v in self.variables:
if v.op.name == n:
found = True
init_vars.append(v)
break
if not found:
logger.warn("Could not find variable", n, "in computation graph to restore from pretrained model.")
saver = tf.train.Saver(init_vars)
saver.restore(self.tf_session, init_model)
@property
def placeholders(self) -> Mapping[TensorPort, tf.Tensor]:
return self._placeholders
@property
def tensors(self) -> Mapping[TensorPort, tf.Tensor]:
return self._tensors if hasattr(self, "_tensors") else None
def store(self, path):
self._saver.save(self.tf_session, path)
def load(self, path):
self._saver.restore(self.tf_session, path)
@property
def train_variables(self) -> Sequence[tf.Tensor]:
return self._training_variables
@property
def variables(self) -> Sequence[tf.Tensor]:
return self._variables
def convert_to_feed_dict(self, mapping: Mapping[TensorPort, np.ndarray]) -> Mapping[tf.Tensor, np.ndarray]:
result = {ph: mapping[port] for port, ph in self.placeholders.items() if port in mapping}
return result
| 43.983539 | 120 | 0.655595 |
acf0025abd0e8317a13dba3769e0f4eefd79c816 | 2,885 | py | Python | server/views/explorer/sentences.py | Yunicorn228/web-tools | 056d2d8310f3096c8be90638342bb3cc5715a89f | [
"Apache-2.0"
] | 32 | 2017-06-12T15:53:14.000Z | 2020-08-31T15:23:38.000Z | server/views/explorer/sentences.py | Yunicorn228/web-tools | 056d2d8310f3096c8be90638342bb3cc5715a89f | [
"Apache-2.0"
] | 1,316 | 2017-05-04T17:14:15.000Z | 2020-09-28T18:32:00.000Z | server/views/explorer/sentences.py | Yunicorn228/web-tools | 056d2d8310f3096c8be90638342bb3cc5715a89f | [
"Apache-2.0"
] | 20 | 2017-10-10T20:07:07.000Z | 2020-08-30T14:03:06.000Z | import logging
from flask import jsonify, request
import flask_login
from server import app
from server.util.request import api_error_handler
import server.views.explorer.apicache as apicache
from server.platforms.reddit_pushshift import RedditPushshiftProvider, NEWS_SUBREDDITS
from server.views.explorer import parse_query_with_keywords, only_queries_reddit, parse_query_dates
logger = logging.getLogger(__name__)
WORD_CONTEXT_SIZE = 5 # for sentence fragments, this is the amount of words before & after that we return
@app.route('/api/explorer/sentences/list', methods=['POST'])
@flask_login.login_required
@api_error_handler
def api_explorer_sentences_list():
around_word = 'word' in request.form
if only_queries_reddit(request.form):
start_date, end_date = parse_query_dates(request.form)
provider = RedditPushshiftProvider()
results = provider.sample(query=request.args['q'], start_date=start_date, end_date=end_date,
subreddits=NEWS_SUBREDDITS)
results = [{
'sentence': r['title'],
'publish_date': r['publish_date'],
'story': r,
} for r in results]
else:
solr_q, solr_fq = parse_query_with_keywords(request.form)
# so we can support large samples or just a few to show
rows = int(request.form['rows']) if 'rows' in request.form else 10
results = apicache.sentence_list(solr_q, solr_fq, rows=rows, include_stories=(not around_word))
if around_word:
word = request.form['word']
results = [_sentence_fragment_around(word, s['sentence']) for s in results if s['sentence'] is not None]
results = [s for s in results if s is not None]
return jsonify({'results': results})
def _sentence_fragment_around(keyword, sentence):
"""
Turn a sentence into a sentence fragment, including just the 5 words before and after the keyword we are looking at.
We do this to enforce our rule that full sentences (even without metadata) never leave our servers).
Warning: this makes simplistic assumptions about word tokenization
:return: a sentence fragment around keyword, or None if keyword can't be found
"""
try:
words = sentence.split() # super naive, but works ok
keyword_index = None
for index, word in enumerate(words):
if keyword_index is not None:
continue
if word.lower().startswith(keyword.replace("*", "").lower()):
keyword_index = index
if keyword_index is None:
return None
min_word_index = max(0, keyword_index - WORD_CONTEXT_SIZE)
max_word_index = min(len(words), keyword_index + WORD_CONTEXT_SIZE)
fragment_words = words[min_word_index:max_word_index]
return " ".join(fragment_words)
except ValueError:
return None
| 44.384615 | 120 | 0.692201 |
acf002f31651339fdc2b3ff6d45e9243cf51bfa8 | 10,234 | py | Python | pandas/tests/series/test_misc_api.py | betoesquivel/PyData29-DataAnalyticsWithAWSLambda | 318d1f595e4079544159a0f4802277dc5b25cb47 | [
"MIT"
] | 4 | 2016-12-06T20:22:28.000Z | 2018-05-04T09:51:45.000Z | pandas/tests/series/test_misc_api.py | betoesquivel/PyData29-DataAnalyticsWithAWSLambda | 318d1f595e4079544159a0f4802277dc5b25cb47 | [
"MIT"
] | null | null | null | pandas/tests/series/test_misc_api.py | betoesquivel/PyData29-DataAnalyticsWithAWSLambda | 318d1f595e4079544159a0f4802277dc5b25cb47 | [
"MIT"
] | 1 | 2021-11-05T22:17:01.000Z | 2021-11-05T22:17:01.000Z | # coding=utf-8
# pylint: disable-msg=E1101,W0612
import numpy as np
import pandas as pd
from pandas import Index, Series, DataFrame, date_range
from pandas.tseries.index import Timestamp
import pandas.core.common as com
from pandas.compat import range
from pandas import compat
from pandas.util.testing import (assert_series_equal,
ensure_clean)
import pandas.util.testing as tm
from .common import TestData
class SharedWithSparse(object):
def test_scalarop_preserve_name(self):
result = self.ts * 2
self.assertEqual(result.name, self.ts.name)
def test_copy_name(self):
result = self.ts.copy()
self.assertEqual(result.name, self.ts.name)
def test_copy_index_name_checking(self):
# don't want to be able to modify the index stored elsewhere after
# making a copy
self.ts.index.name = None
self.assertIsNone(self.ts.index.name)
self.assertIs(self.ts, self.ts)
cp = self.ts.copy()
cp.index.name = 'foo'
com.pprint_thing(self.ts.index.name)
self.assertIsNone(self.ts.index.name)
def test_append_preserve_name(self):
result = self.ts[:5].append(self.ts[5:])
self.assertEqual(result.name, self.ts.name)
def test_binop_maybe_preserve_name(self):
# names match, preserve
result = self.ts * self.ts
self.assertEqual(result.name, self.ts.name)
result = self.ts.mul(self.ts)
self.assertEqual(result.name, self.ts.name)
result = self.ts * self.ts[:-2]
self.assertEqual(result.name, self.ts.name)
# names don't match, don't preserve
cp = self.ts.copy()
cp.name = 'something else'
result = self.ts + cp
self.assertIsNone(result.name)
result = self.ts.add(cp)
self.assertIsNone(result.name)
ops = ['add', 'sub', 'mul', 'div', 'truediv', 'floordiv', 'mod', 'pow']
ops = ops + ['r' + op for op in ops]
for op in ops:
# names match, preserve
s = self.ts.copy()
result = getattr(s, op)(s)
self.assertEqual(result.name, self.ts.name)
# names don't match, don't preserve
cp = self.ts.copy()
cp.name = 'changed'
result = getattr(s, op)(cp)
self.assertIsNone(result.name)
def test_combine_first_name(self):
result = self.ts.combine_first(self.ts[:5])
self.assertEqual(result.name, self.ts.name)
def test_getitem_preserve_name(self):
result = self.ts[self.ts > 0]
self.assertEqual(result.name, self.ts.name)
result = self.ts[[0, 2, 4]]
self.assertEqual(result.name, self.ts.name)
result = self.ts[5:10]
self.assertEqual(result.name, self.ts.name)
def test_pickle(self):
unp_series = self._pickle_roundtrip(self.series)
unp_ts = self._pickle_roundtrip(self.ts)
assert_series_equal(unp_series, self.series)
assert_series_equal(unp_ts, self.ts)
def _pickle_roundtrip(self, obj):
with ensure_clean() as path:
obj.to_pickle(path)
unpickled = pd.read_pickle(path)
return unpickled
def test_argsort_preserve_name(self):
result = self.ts.argsort()
self.assertEqual(result.name, self.ts.name)
def test_sort_index_name(self):
result = self.ts.sort_index(ascending=False)
self.assertEqual(result.name, self.ts.name)
def test_to_sparse_pass_name(self):
result = self.ts.to_sparse()
self.assertEqual(result.name, self.ts.name)
class TestSeriesMisc(TestData, SharedWithSparse, tm.TestCase):
_multiprocess_can_split_ = True
def test_tab_completion(self):
# GH 9910
s = Series(list('abcd'))
# Series of str values should have .str but not .dt/.cat in __dir__
self.assertTrue('str' in dir(s))
self.assertTrue('dt' not in dir(s))
self.assertTrue('cat' not in dir(s))
# similiarly for .dt
s = Series(date_range('1/1/2015', periods=5))
self.assertTrue('dt' in dir(s))
self.assertTrue('str' not in dir(s))
self.assertTrue('cat' not in dir(s))
# similiarly for .cat, but with the twist that str and dt should be
# there if the categories are of that type first cat and str
s = Series(list('abbcd'), dtype="category")
self.assertTrue('cat' in dir(s))
self.assertTrue('str' in dir(s)) # as it is a string categorical
self.assertTrue('dt' not in dir(s))
# similar to cat and str
s = Series(date_range('1/1/2015', periods=5)).astype("category")
self.assertTrue('cat' in dir(s))
self.assertTrue('str' not in dir(s))
self.assertTrue('dt' in dir(s)) # as it is a datetime categorical
def test_not_hashable(self):
s_empty = Series()
s = Series([1])
self.assertRaises(TypeError, hash, s_empty)
self.assertRaises(TypeError, hash, s)
def test_contains(self):
tm.assert_contains_all(self.ts.index, self.ts)
def test_iter(self):
for i, val in enumerate(self.series):
self.assertEqual(val, self.series[i])
for i, val in enumerate(self.ts):
self.assertEqual(val, self.ts[i])
def test_keys(self):
# HACK: By doing this in two stages, we avoid 2to3 wrapping the call
# to .keys() in a list()
getkeys = self.ts.keys
self.assertIs(getkeys(), self.ts.index)
def test_values(self):
self.assert_numpy_array_equal(self.ts, self.ts.values)
def test_iteritems(self):
for idx, val in compat.iteritems(self.series):
self.assertEqual(val, self.series[idx])
for idx, val in compat.iteritems(self.ts):
self.assertEqual(val, self.ts[idx])
# assert is lazy (genrators don't define reverse, lists do)
self.assertFalse(hasattr(self.series.iteritems(), 'reverse'))
def test_raise_on_info(self):
s = Series(np.random.randn(10))
with tm.assertRaises(AttributeError):
s.info()
def test_copy(self):
for deep in [None, False, True]:
s = Series(np.arange(10), dtype='float64')
# default deep is True
if deep is None:
s2 = s.copy()
else:
s2 = s.copy(deep=deep)
s2[::2] = np.NaN
if deep is None or deep is True:
# Did not modify original Series
self.assertTrue(np.isnan(s2[0]))
self.assertFalse(np.isnan(s[0]))
else:
# we DID modify the original Series
self.assertTrue(np.isnan(s2[0]))
self.assertTrue(np.isnan(s[0]))
# GH 11794
# copy of tz-aware
expected = Series([Timestamp('2012/01/01', tz='UTC')])
expected2 = Series([Timestamp('1999/01/01', tz='UTC')])
for deep in [None, False, True]:
s = Series([Timestamp('2012/01/01', tz='UTC')])
if deep is None:
s2 = s.copy()
else:
s2 = s.copy(deep=deep)
s2[0] = pd.Timestamp('1999/01/01', tz='UTC')
# default deep is True
if deep is None or deep is True:
assert_series_equal(s, expected)
assert_series_equal(s2, expected2)
else:
assert_series_equal(s, expected2)
assert_series_equal(s2, expected2)
def test_axis_alias(self):
s = Series([1, 2, np.nan])
assert_series_equal(s.dropna(axis='rows'), s.dropna(axis='index'))
self.assertEqual(s.dropna().sum('rows'), 3)
self.assertEqual(s._get_axis_number('rows'), 0)
self.assertEqual(s._get_axis_name('rows'), 'index')
def test_numpy_unique(self):
# it works!
np.unique(self.ts)
def test_ndarray_compat(self):
# test numpy compat with Series as sub-class of NDFrame
tsdf = DataFrame(np.random.randn(1000, 3), columns=['A', 'B', 'C'],
index=date_range('1/1/2000', periods=1000))
def f(x):
return x[x.argmax()]
result = tsdf.apply(f)
expected = tsdf.max()
assert_series_equal(result, expected)
# .item()
s = Series([1])
result = s.item()
self.assertEqual(result, 1)
self.assertEqual(s.item(), s.iloc[0])
# using an ndarray like function
s = Series(np.random.randn(10))
result = np.ones_like(s)
expected = Series(1, index=range(10), dtype='float64')
# assert_series_equal(result,expected)
# ravel
s = Series(np.random.randn(10))
tm.assert_almost_equal(s.ravel(order='F'), s.values.ravel(order='F'))
# compress
# GH 6658
s = Series([0, 1., -1], index=list('abc'))
result = np.compress(s > 0, s)
assert_series_equal(result, Series([1.], index=['b']))
result = np.compress(s < -1, s)
# result empty Index(dtype=object) as the same as original
exp = Series([], dtype='float64', index=Index([], dtype='object'))
assert_series_equal(result, exp)
s = Series([0, 1., -1], index=[.1, .2, .3])
result = np.compress(s > 0, s)
assert_series_equal(result, Series([1.], index=[.2]))
result = np.compress(s < -1, s)
# result empty Float64Index as the same as original
exp = Series([], dtype='float64', index=Index([], dtype='float64'))
assert_series_equal(result, exp)
def test_str_attribute(self):
# GH9068
methods = ['strip', 'rstrip', 'lstrip']
s = Series([' jack', 'jill ', ' jesse ', 'frank'])
for method in methods:
expected = Series([getattr(str, method)(x) for x in s.values])
assert_series_equal(getattr(Series.str, method)(s.str), expected)
# str accessor only valid with string values
s = Series(range(5))
with self.assertRaisesRegexp(AttributeError, 'only use .str accessor'):
s.str.repeat(2)
| 33.227273 | 79 | 0.589115 |
acf003beb510ca873859e06cfdc9fbabf43368d9 | 6,841 | py | Python | Ricardo_OS/Python_backend/venv/lib/python3.7/site-packages/simple_websocket/ws.py | roguextech/ICL-Rocketry-Avionics | 0ad88dc176730e3c33f8332f2b69ce4b43bf49ed | [
"MIT"
] | null | null | null | Ricardo_OS/Python_backend/venv/lib/python3.7/site-packages/simple_websocket/ws.py | roguextech/ICL-Rocketry-Avionics | 0ad88dc176730e3c33f8332f2b69ce4b43bf49ed | [
"MIT"
] | null | null | null | Ricardo_OS/Python_backend/venv/lib/python3.7/site-packages/simple_websocket/ws.py | roguextech/ICL-Rocketry-Avionics | 0ad88dc176730e3c33f8332f2b69ce4b43bf49ed | [
"MIT"
] | null | null | null | import socket
import ssl
import threading
from urllib.parse import urlsplit
from wsproto import ConnectionType, WSConnection
from wsproto.events import (
AcceptConnection,
RejectConnection,
CloseConnection,
Message,
Request,
Ping,
TextMessage,
BytesMessage,
)
from wsproto.frame_protocol import CloseReason
from wsproto.utilities import LocalProtocolError
class ConnectionError(RuntimeError):
def __init__(self, status_code):
self.status_code = status_code
super().__init__(f'Connection error {status_code}')
class ConnectionClosed(RuntimeError):
pass
class Base:
def __init__(self, sock=None, connection_type=None, receive_bytes=4096,
thread_class=threading.Thread, event_class=threading.Event):
self.sock = sock
self.receive_bytes = receive_bytes
self.input_buffer = []
self.event = event_class()
self.connected = False
self.is_server = (connection_type == ConnectionType.SERVER)
self.ws = WSConnection(connection_type)
self.handshake()
self.thread = thread_class(target=self._thread)
self.thread.start()
self.event.wait()
self.event.clear()
def handshake(self):
"""To be implemented by subclasses."""
pass
def send(self, data):
if not self.connected:
raise ConnectionClosed()
if isinstance(data, bytes):
out_data = self.ws.send(Message(data=data))
else:
out_data = self.ws.send(TextMessage(data=str(data)))
self.sock.send(out_data)
def receive(self, timeout=None):
while self.connected and not self.input_buffer:
if not self.event.wait(timeout=timeout):
return None
self.event.clear()
if not self.connected:
raise ConnectionClosed()
return self.input_buffer.pop(0)
def close(self, reason=None, message=None):
out_data = self.ws.send(CloseConnection(
reason or CloseReason.NORMAL_CLOSURE, message))
try:
self.sock.send(out_data)
except BrokenPipeError:
pass
def _thread(self):
self.connected = self._handle_events()
self.event.set()
while self.connected:
try:
in_data = self.sock.recv(self.receive_bytes)
except (OSError, ConnectionResetError):
self.connected = False
self.event.set()
break
self.ws.receive_data(in_data)
self.connected = self._handle_events()
def _handle_events(self):
keep_going = True
out_data = b''
for event in self.ws.events():
try:
if isinstance(event, Request):
out_data += self.ws.send(AcceptConnection())
elif isinstance(event, CloseConnection):
if self.is_server:
out_data += self.ws.send(event.response())
self.event.set()
keep_going = False
elif isinstance(event, Ping):
out_data += self.ws.send(event.response())
elif isinstance(event, TextMessage):
self.input_buffer.append(event.data)
self.event.set()
elif isinstance(event, BytesMessage):
self.input_buffer.append(event.data)
self.event.set()
except LocalProtocolError:
out_data = b''
self.event.set()
keep_going = False
if out_data:
self.sock.send(out_data)
return keep_going
class Server(Base):
def __init__(self, environ, receive_bytes=4096,
thread_class=threading.Thread, event_class=threading.Event):
self.environ = environ
if 'werkzeug.socket' in environ:
# extract socket from Werkzeug's WSGI environment
sock = environ.get('werkzeug.socket')
elif 'gunicorn.socket' in environ:
# extract socket from Gunicorn WSGI environment
sock = environ.get('gunicorn.socket')
elif 'eventlet.input' in environ:
# extract socket from Eventlet's WSGI environment
sock = environ.get('eventlet.input').get_socket()
elif environ.get('SERVER_SOFTWARE', '').startswith('gevent'):
# extract socket from Gevent's WSGI environment
sock = environ['wsgi.input'].raw._sock
else:
raise RuntimeError('Cannot obtain socket from WSGI environment.')
super().__init__(sock, connection_type=ConnectionType.SERVER,
receive_bytes=receive_bytes,
thread_class=thread_class, event_class=event_class)
def handshake(self):
in_data = b'GET / HTTP/1.1\r\n'
for key, value in self.environ.items():
if key.startswith('HTTP_'):
header = '-'.join([p.capitalize() for p in key[5:].split('_')])
in_data += f'{header}: {value}\r\n'.encode()
in_data += b'\r\n'
self.ws.receive_data(in_data)
class Client(Base):
def __init__(self, url, receive_bytes=4096, thread_class=threading.Thread,
event_class=threading.Event, ssl_context=None):
parsed_url = urlsplit(url)
is_secure = parsed_url.scheme in ['https', 'wss']
self.host = parsed_url.hostname
self.port = parsed_url.port or (443 if is_secure else 80)
self.path = parsed_url.path
if parsed_url.query:
self.path += '?' + parsed_url.query
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if is_secure:
if ssl_context is None:
ssl_context = ssl.create_default_context(
purpose=ssl.Purpose.SERVER_AUTH)
sock = ssl_context.wrap_socket(sock, server_hostname=self.host)
sock.connect((self.host, self.port))
super().__init__(sock, connection_type=ConnectionType.CLIENT,
receive_bytes=receive_bytes,
thread_class=thread_class, event_class=event_class)
def handshake(self):
out_data = self.ws.send(Request(host=self.host, target=self.path))
self.sock.send(out_data)
in_data = self.sock.recv(self.receive_bytes)
self.ws.receive_data(in_data)
for event in self.ws.events():
if isinstance(event, AcceptConnection):
break
elif isinstance(event, RejectConnection):
raise ConnectionError(event.status_code)
def close(self, reason=None, message=None):
super().close(reason=reason, message=message)
self.sock.close()
| 36.005263 | 79 | 0.599181 |
acf003d00e06fc48cef82c9ae1abab07962265ca | 86 | py | Python | vsoup/websuite.py | vaderyang/Vsoup | 3c4052376c281794133e0d2f49d260677d431873 | [
"MIT"
] | null | null | null | vsoup/websuite.py | vaderyang/Vsoup | 3c4052376c281794133e0d2f49d260677d431873 | [
"MIT"
] | null | null | null | vsoup/websuite.py | vaderyang/Vsoup | 3c4052376c281794133e0d2f49d260677d431873 | [
"MIT"
] | null | null | null | #!-encoding=utf8
import vsoup
from .stateful_browser import StatefulBrowser, AGENTS
| 14.333333 | 53 | 0.813953 |
acf00405aaf85dfda8ad0bbec39e6f62d21c209d | 30,223 | py | Python | test/functional/rpc_rawtransaction.py | newbtcio/nbitcoin | 3f13233f0660b85ecd2972e283124fad3e0bab79 | [
"MIT"
] | null | null | null | test/functional/rpc_rawtransaction.py | newbtcio/nbitcoin | 3f13233f0660b85ecd2972e283124fad3e0bab79 | [
"MIT"
] | null | null | null | test/functional/rpc_rawtransaction.py | newbtcio/nbitcoin | 3f13233f0660b85ecd2972e283124fad3e0bab79 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2014-2019 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 the rawtransaction RPCs.
Test the following RPCs:
- createrawtransaction
- signrawtransactionwithwallet
- sendrawtransaction
- decoderawtransaction
- getrawtransaction
"""
from collections import OrderedDict
from decimal import Decimal
from io import BytesIO
from test_framework.messages import CTransaction, ToHex
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
find_vout_for_address,
hex_str_to_bytes,
)
class multidict(dict):
"""Dictionary that allows duplicate keys.
Constructed with a list of (key, value) tuples. When dumped by the json module,
will output invalid json with repeated keys, eg:
>>> json.dumps(multidict([(1,2),(1,2)])
'{"1": 2, "1": 2}'
Used to test calls to rpc methods with repeated keys in the json object."""
def __init__(self, x):
dict.__init__(self, x)
self.x = x
def items(self):
return self.x
# Create one-input, one-output, no-fee transaction:
class RawTransactionsTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 3
self.extra_args = [
["-txindex"],
["-txindex"],
["-txindex"],
]
self.supports_cli = False
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
def setup_network(self):
super().setup_network()
self.connect_nodes(0, 2)
def run_test(self):
self.log.info('prepare some coins for multiple *rawtransaction commands')
self.nodes[2].generate(1)
self.sync_all()
self.nodes[0].generate(101)
self.sync_all()
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(),1.5)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(),1.0)
self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(),5.0)
self.sync_all()
self.nodes[0].generate(5)
self.sync_all()
self.log.info('Test getrawtransaction on genesis block coinbase returns an error')
block = self.nodes[0].getblock(self.nodes[0].getblockhash(0))
assert_raises_rpc_error(-5, "The genesis block coinbase is not considered an ordinary transaction", self.nodes[0].getrawtransaction, block['merkleroot'])
self.log.info('Check parameter types and required parameters of createrawtransaction')
# Test `createrawtransaction` required parameters
assert_raises_rpc_error(-1, "createrawtransaction", self.nodes[0].createrawtransaction)
assert_raises_rpc_error(-1, "createrawtransaction", self.nodes[0].createrawtransaction, [])
# Test `createrawtransaction` invalid extra parameters
assert_raises_rpc_error(-1, "createrawtransaction", self.nodes[0].createrawtransaction, [], {}, 0, False, 'foo')
# Test `createrawtransaction` invalid `inputs`
txid = '1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000'
assert_raises_rpc_error(-3, "Expected type array", self.nodes[0].createrawtransaction, 'foo', {})
assert_raises_rpc_error(-1, "JSON value is not an object as expected", self.nodes[0].createrawtransaction, ['foo'], {})
assert_raises_rpc_error(-1, "JSON value is not a string as expected", self.nodes[0].createrawtransaction, [{}], {})
assert_raises_rpc_error(-8, "txid must be of length 64 (not 3, for 'foo')", self.nodes[0].createrawtransaction, [{'txid': 'foo'}], {})
assert_raises_rpc_error(-8, "txid must be hexadecimal string (not 'ZZZ7bb8b1697ea987f3b223ba7819250cae33efacb068d23dc24859824a77844')", self.nodes[0].createrawtransaction, [{'txid': 'ZZZ7bb8b1697ea987f3b223ba7819250cae33efacb068d23dc24859824a77844'}], {})
assert_raises_rpc_error(-8, "Invalid parameter, missing vout key", self.nodes[0].createrawtransaction, [{'txid': txid}], {})
assert_raises_rpc_error(-8, "Invalid parameter, missing vout key", self.nodes[0].createrawtransaction, [{'txid': txid, 'vout': 'foo'}], {})
assert_raises_rpc_error(-8, "Invalid parameter, vout cannot be negative", self.nodes[0].createrawtransaction, [{'txid': txid, 'vout': -1}], {})
assert_raises_rpc_error(-8, "Invalid parameter, sequence number is out of range", self.nodes[0].createrawtransaction, [{'txid': txid, 'vout': 0, 'sequence': -1}], {})
# Test `createrawtransaction` invalid `outputs`
address = self.nodes[0].getnewaddress()
address2 = self.nodes[0].getnewaddress()
assert_raises_rpc_error(-1, "JSON value is not an array as expected", self.nodes[0].createrawtransaction, [], 'foo')
self.nodes[0].createrawtransaction(inputs=[], outputs={}) # Should not throw for backwards compatibility
self.nodes[0].createrawtransaction(inputs=[], outputs=[])
assert_raises_rpc_error(-8, "Data must be hexadecimal string", self.nodes[0].createrawtransaction, [], {'data': 'foo'})
assert_raises_rpc_error(-5, "Invalid Bitcoin address", self.nodes[0].createrawtransaction, [], {'foo': 0})
assert_raises_rpc_error(-3, "Invalid amount", self.nodes[0].createrawtransaction, [], {address: 'foo'})
assert_raises_rpc_error(-3, "Amount out of range", self.nodes[0].createrawtransaction, [], {address: -1})
assert_raises_rpc_error(-8, "Invalid parameter, duplicated address: %s" % address, self.nodes[0].createrawtransaction, [], multidict([(address, 1), (address, 1)]))
assert_raises_rpc_error(-8, "Invalid parameter, duplicated address: %s" % address, self.nodes[0].createrawtransaction, [], [{address: 1}, {address: 1}])
assert_raises_rpc_error(-8, "Invalid parameter, duplicate key: data", self.nodes[0].createrawtransaction, [], [{"data": 'aa'}, {"data": "bb"}])
assert_raises_rpc_error(-8, "Invalid parameter, duplicate key: data", self.nodes[0].createrawtransaction, [], multidict([("data", 'aa'), ("data", "bb")]))
assert_raises_rpc_error(-8, "Invalid parameter, key-value pair must contain exactly one key", self.nodes[0].createrawtransaction, [], [{'a': 1, 'b': 2}])
assert_raises_rpc_error(-8, "Invalid parameter, key-value pair not an object as expected", self.nodes[0].createrawtransaction, [], [['key-value pair1'], ['2']])
# Test `createrawtransaction` invalid `locktime`
assert_raises_rpc_error(-3, "Expected type number", self.nodes[0].createrawtransaction, [], {}, 'foo')
assert_raises_rpc_error(-8, "Invalid parameter, locktime out of range", self.nodes[0].createrawtransaction, [], {}, -1)
assert_raises_rpc_error(-8, "Invalid parameter, locktime out of range", self.nodes[0].createrawtransaction, [], {}, 4294967296)
# Test `createrawtransaction` invalid `replaceable`
assert_raises_rpc_error(-3, "Expected type bool", self.nodes[0].createrawtransaction, [], {}, 0, 'foo')
self.log.info('Check that createrawtransaction accepts an array and object as outputs')
tx = CTransaction()
# One output
tx.deserialize(BytesIO(hex_str_to_bytes(self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs={address: 99}))))
assert_equal(len(tx.vout), 1)
assert_equal(
tx.serialize().hex(),
self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{address: 99}]),
)
# Two outputs
tx.deserialize(BytesIO(hex_str_to_bytes(self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=OrderedDict([(address, 99), (address2, 99)])))))
assert_equal(len(tx.vout), 2)
assert_equal(
tx.serialize().hex(),
self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{address: 99}, {address2: 99}]),
)
# Multiple mixed outputs
tx.deserialize(BytesIO(hex_str_to_bytes(self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=multidict([(address, 99), (address2, 99), ('data', '99')])))))
assert_equal(len(tx.vout), 3)
assert_equal(
tx.serialize().hex(),
self.nodes[2].createrawtransaction(inputs=[{'txid': txid, 'vout': 9}], outputs=[{address: 99}, {address2: 99}, {'data': '99'}]),
)
for type in ["bech32", "p2sh-segwit", "legacy"]:
addr = self.nodes[0].getnewaddress("", type)
addrinfo = self.nodes[0].getaddressinfo(addr)
pubkey = addrinfo["scriptPubKey"]
self.log.info('sendrawtransaction with missing prevtx info (%s)' %(type))
# Test `signrawtransactionwithwallet` invalid `prevtxs`
inputs = [ {'txid' : txid, 'vout' : 3, 'sequence' : 1000}]
outputs = { self.nodes[0].getnewaddress() : 1 }
rawtx = self.nodes[0].createrawtransaction(inputs, outputs)
prevtx = dict(txid=txid, scriptPubKey=pubkey, vout=3, amount=1)
succ = self.nodes[0].signrawtransactionwithwallet(rawtx, [prevtx])
assert succ["complete"]
if type == "legacy":
del prevtx["amount"]
succ = self.nodes[0].signrawtransactionwithwallet(rawtx, [prevtx])
assert succ["complete"]
if type != "legacy":
assert_raises_rpc_error(-3, "Missing amount", self.nodes[0].signrawtransactionwithwallet, rawtx, [
{
"txid": txid,
"scriptPubKey": pubkey,
"vout": 3,
}
])
assert_raises_rpc_error(-3, "Missing vout", self.nodes[0].signrawtransactionwithwallet, rawtx, [
{
"txid": txid,
"scriptPubKey": pubkey,
"amount": 1,
}
])
assert_raises_rpc_error(-3, "Missing txid", self.nodes[0].signrawtransactionwithwallet, rawtx, [
{
"scriptPubKey": pubkey,
"vout": 3,
"amount": 1,
}
])
assert_raises_rpc_error(-3, "Missing scriptPubKey", self.nodes[0].signrawtransactionwithwallet, rawtx, [
{
"txid": txid,
"vout": 3,
"amount": 1
}
])
#########################################
# sendrawtransaction with missing input #
#########################################
self.log.info('sendrawtransaction with missing input')
inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1}] #won't exists
outputs = { self.nodes[0].getnewaddress() : 4.998 }
rawtx = self.nodes[2].createrawtransaction(inputs, outputs)
rawtx = self.nodes[2].signrawtransactionwithwallet(rawtx)
# This will raise an exception since there are missing inputs
assert_raises_rpc_error(-25, "bad-txns-inputs-missingorspent", self.nodes[2].sendrawtransaction, rawtx['hex'])
#####################################
# getrawtransaction with block hash #
#####################################
# make a tx by sending then generate 2 blocks; block1 has the tx in it
tx = self.nodes[2].sendtoaddress(self.nodes[1].getnewaddress(), 1)
block1, block2 = self.nodes[2].generate(2)
self.sync_all()
# We should be able to get the raw transaction by providing the correct block
gottx = self.nodes[0].getrawtransaction(tx, True, block1)
assert_equal(gottx['txid'], tx)
assert_equal(gottx['in_active_chain'], True)
# We should not have the 'in_active_chain' flag when we don't provide a block
gottx = self.nodes[0].getrawtransaction(tx, True)
assert_equal(gottx['txid'], tx)
assert 'in_active_chain' not in gottx
# We should not get the tx if we provide an unrelated block
assert_raises_rpc_error(-5, "No such transaction found", self.nodes[0].getrawtransaction, tx, True, block2)
# An invalid block hash should raise the correct errors
assert_raises_rpc_error(-1, "JSON value is not a string as expected", self.nodes[0].getrawtransaction, tx, True, True)
assert_raises_rpc_error(-8, "parameter 3 must be of length 64 (not 6, for 'foobar')", self.nodes[0].getrawtransaction, tx, True, "foobar")
assert_raises_rpc_error(-8, "parameter 3 must be of length 64 (not 8, for 'abcd1234')", self.nodes[0].getrawtransaction, tx, True, "abcd1234")
assert_raises_rpc_error(-8, "parameter 3 must be hexadecimal string (not 'ZZZ0000000000000000000000000000000000000000000000000000000000000')", self.nodes[0].getrawtransaction, tx, True, "ZZZ0000000000000000000000000000000000000000000000000000000000000")
assert_raises_rpc_error(-5, "Block hash not found", self.nodes[0].getrawtransaction, tx, True, "0000000000000000000000000000000000000000000000000000000000000000")
# Undo the blocks and check in_active_chain
self.nodes[0].invalidateblock(block1)
gottx = self.nodes[0].getrawtransaction(txid=tx, verbose=True, blockhash=block1)
assert_equal(gottx['in_active_chain'], False)
self.nodes[0].reconsiderblock(block1)
assert_equal(self.nodes[0].getbestblockhash(), block2)
if not self.options.descriptors:
# The traditional multisig workflow does not work with descriptor wallets so these are legacy only.
# The multisig workflow with descriptor wallets uses PSBTs and is tested elsewhere, no need to do them here.
#########################
# RAW TX MULTISIG TESTS #
#########################
# 2of2 test
addr1 = self.nodes[2].getnewaddress()
addr2 = self.nodes[2].getnewaddress()
addr1Obj = self.nodes[2].getaddressinfo(addr1)
addr2Obj = self.nodes[2].getaddressinfo(addr2)
# Tests for createmultisig and addmultisigaddress
assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, ["01020304"])
self.nodes[0].createmultisig(2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) # createmultisig can only take public keys
assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 2, [addr1Obj['pubkey'], addr1]) # addmultisigaddress can take both pubkeys and addresses so long as they are in the wallet, which is tested here.
mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr1])['address']
#use balance deltas instead of absolute values
bal = self.nodes[2].getbalance()
# send 1.2 BTC to msig adr
txId = self.nodes[0].sendtoaddress(mSigObj, 1.2)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
assert_equal(self.nodes[2].getbalance(), bal+Decimal('1.20000000')) #node2 has both keys of the 2of2 ms addr., tx should affect the balance
# 2of3 test from different nodes
bal = self.nodes[2].getbalance()
addr1 = self.nodes[1].getnewaddress()
addr2 = self.nodes[2].getnewaddress()
addr3 = self.nodes[2].getnewaddress()
addr1Obj = self.nodes[1].getaddressinfo(addr1)
addr2Obj = self.nodes[2].getaddressinfo(addr2)
addr3Obj = self.nodes[2].getaddressinfo(addr3)
mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey']])['address']
txId = self.nodes[0].sendtoaddress(mSigObj, 2.2)
decTx = self.nodes[0].gettransaction(txId)
rawTx = self.nodes[0].decoderawtransaction(decTx['hex'])
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
#THIS IS AN INCOMPLETE FEATURE
#NODE2 HAS TWO OF THREE KEY AND THE FUNDS SHOULD BE SPENDABLE AND COUNT AT BALANCE CALCULATION
assert_equal(self.nodes[2].getbalance(), bal) #for now, assume the funds of a 2of3 multisig tx are not marked as spendable
txDetails = self.nodes[0].gettransaction(txId, True)
rawTx = self.nodes[0].decoderawtransaction(txDetails['hex'])
vout = next(o for o in rawTx['vout'] if o['value'] == Decimal('2.20000000'))
bal = self.nodes[0].getbalance()
inputs = [{ "txid" : txId, "vout" : vout['n'], "scriptPubKey" : vout['scriptPubKey']['hex'], "amount" : vout['value']}]
outputs = { self.nodes[0].getnewaddress() : 2.19 }
rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
rawTxPartialSigned = self.nodes[1].signrawtransactionwithwallet(rawTx, inputs)
assert_equal(rawTxPartialSigned['complete'], False) #node1 only has one key, can't comp. sign the tx
rawTxSigned = self.nodes[2].signrawtransactionwithwallet(rawTx, inputs)
assert_equal(rawTxSigned['complete'], True) #node2 can sign the tx compl., own two of three keys
self.nodes[2].sendrawtransaction(rawTxSigned['hex'])
rawTx = self.nodes[0].decoderawtransaction(rawTxSigned['hex'])
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
assert_equal(self.nodes[0].getbalance(), bal+Decimal('50.00000000')+Decimal('2.19000000')) #block reward + tx
# 2of2 test for combining transactions
bal = self.nodes[2].getbalance()
addr1 = self.nodes[1].getnewaddress()
addr2 = self.nodes[2].getnewaddress()
addr1Obj = self.nodes[1].getaddressinfo(addr1)
addr2Obj = self.nodes[2].getaddressinfo(addr2)
self.nodes[1].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])['address']
mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])['address']
mSigObjValid = self.nodes[2].getaddressinfo(mSigObj)
txId = self.nodes[0].sendtoaddress(mSigObj, 2.2)
decTx = self.nodes[0].gettransaction(txId)
rawTx2 = self.nodes[0].decoderawtransaction(decTx['hex'])
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
assert_equal(self.nodes[2].getbalance(), bal) # the funds of a 2of2 multisig tx should not be marked as spendable
txDetails = self.nodes[0].gettransaction(txId, True)
rawTx2 = self.nodes[0].decoderawtransaction(txDetails['hex'])
vout = next(o for o in rawTx2['vout'] if o['value'] == Decimal('2.20000000'))
bal = self.nodes[0].getbalance()
inputs = [{ "txid" : txId, "vout" : vout['n'], "scriptPubKey" : vout['scriptPubKey']['hex'], "redeemScript" : mSigObjValid['hex'], "amount" : vout['value']}]
outputs = { self.nodes[0].getnewaddress() : 2.19 }
rawTx2 = self.nodes[2].createrawtransaction(inputs, outputs)
rawTxPartialSigned1 = self.nodes[1].signrawtransactionwithwallet(rawTx2, inputs)
self.log.debug(rawTxPartialSigned1)
assert_equal(rawTxPartialSigned1['complete'], False) #node1 only has one key, can't comp. sign the tx
rawTxPartialSigned2 = self.nodes[2].signrawtransactionwithwallet(rawTx2, inputs)
self.log.debug(rawTxPartialSigned2)
assert_equal(rawTxPartialSigned2['complete'], False) #node2 only has one key, can't comp. sign the tx
rawTxComb = self.nodes[2].combinerawtransaction([rawTxPartialSigned1['hex'], rawTxPartialSigned2['hex']])
self.log.debug(rawTxComb)
self.nodes[2].sendrawtransaction(rawTxComb)
rawTx2 = self.nodes[0].decoderawtransaction(rawTxComb)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
assert_equal(self.nodes[0].getbalance(), bal+Decimal('50.00000000')+Decimal('2.19000000')) #block reward + tx
# decoderawtransaction tests
# witness transaction
encrawtx = "010000000001010000000000000072c1a6a246ae63f74f931e8365e15a089c68d61900000000000000000000ffffffff0100e1f50500000000000102616100000000"
decrawtx = self.nodes[0].decoderawtransaction(encrawtx, True) # decode as witness transaction
assert_equal(decrawtx['vout'][0]['value'], Decimal('1.00000000'))
assert_raises_rpc_error(-22, 'TX decode failed', self.nodes[0].decoderawtransaction, encrawtx, False) # force decode as non-witness transaction
# non-witness transaction
encrawtx = "01000000010000000000000072c1a6a246ae63f74f931e8365e15a089c68d61900000000000000000000ffffffff0100e1f505000000000000000000"
decrawtx = self.nodes[0].decoderawtransaction(encrawtx, False) # decode as non-witness transaction
assert_equal(decrawtx['vout'][0]['value'], Decimal('1.00000000'))
# known ambiguous transaction in the chain (see https://github.com/bitcoin/bitcoin/issues/20579)
encrawtx = "020000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff4b03c68708046ff8415c622f4254432e434f4d2ffabe6d6de1965d02c68f928e5b244ab1965115a36f56eb997633c7f690124bbf43644e23080000000ca3d3af6d005a65ff0200fd00000000ffffffff03f4c1fb4b0000000016001497cfc76442fe717f2a3f0cc9c175f7561b6619970000000000000000266a24aa21a9ed957d1036a80343e0d1b659497e1b48a38ebe876a056d45965fac4a85cda84e1900000000000000002952534b424c4f434b3a8e092581ab01986cbadc84f4b43f4fa4bb9e7a2e2a0caf9b7cf64d939028e22c0120000000000000000000000000000000000000000000000000000000000000000000000000"
decrawtx = self.nodes[0].decoderawtransaction(encrawtx)
decrawtx_wit = self.nodes[0].decoderawtransaction(encrawtx, True)
assert_raises_rpc_error(-22, 'TX decode failed', self.nodes[0].decoderawtransaction, encrawtx, False) # fails to decode as non-witness transaction
assert_equal(decrawtx, decrawtx_wit) # the witness interpretation should be chosen
assert_equal(decrawtx['vin'][0]['coinbase'], "03c68708046ff8415c622f4254432e434f4d2ffabe6d6de1965d02c68f928e5b244ab1965115a36f56eb997633c7f690124bbf43644e23080000000ca3d3af6d005a65ff0200fd00000000")
# Basic signrawtransaction test
addr = self.nodes[1].getnewaddress()
txid = self.nodes[0].sendtoaddress(addr, 10)
self.nodes[0].generate(1)
self.sync_all()
vout = find_vout_for_address(self.nodes[1], txid, addr)
rawTx = self.nodes[1].createrawtransaction([{'txid': txid, 'vout': vout}], {self.nodes[1].getnewaddress(): 9.999})
rawTxSigned = self.nodes[1].signrawtransactionwithwallet(rawTx)
txId = self.nodes[1].sendrawtransaction(rawTxSigned['hex'])
self.nodes[0].generate(1)
self.sync_all()
# getrawtransaction tests
# 1. valid parameters - only supply txid
assert_equal(self.nodes[0].getrawtransaction(txId), rawTxSigned['hex'])
# 2. valid parameters - supply txid and 0 for non-verbose
assert_equal(self.nodes[0].getrawtransaction(txId, 0), rawTxSigned['hex'])
# 3. valid parameters - supply txid and False for non-verbose
assert_equal(self.nodes[0].getrawtransaction(txId, False), rawTxSigned['hex'])
# 4. valid parameters - supply txid and 1 for verbose.
# We only check the "hex" field of the output so we don't need to update this test every time the output format changes.
assert_equal(self.nodes[0].getrawtransaction(txId, 1)["hex"], rawTxSigned['hex'])
# 5. valid parameters - supply txid and True for non-verbose
assert_equal(self.nodes[0].getrawtransaction(txId, True)["hex"], rawTxSigned['hex'])
# 6. invalid parameters - supply txid and string "Flase"
assert_raises_rpc_error(-1, "not a boolean", self.nodes[0].getrawtransaction, txId, "Flase")
# 7. invalid parameters - supply txid and empty array
assert_raises_rpc_error(-1, "not a boolean", self.nodes[0].getrawtransaction, txId, [])
# 8. invalid parameters - supply txid and empty dict
assert_raises_rpc_error(-1, "not a boolean", self.nodes[0].getrawtransaction, txId, {})
inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 1000}]
outputs = { self.nodes[0].getnewaddress() : 1 }
rawtx = self.nodes[0].createrawtransaction(inputs, outputs)
decrawtx= self.nodes[0].decoderawtransaction(rawtx)
assert_equal(decrawtx['vin'][0]['sequence'], 1000)
# 9. invalid parameters - sequence number out of range
inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : -1}]
outputs = { self.nodes[0].getnewaddress() : 1 }
assert_raises_rpc_error(-8, 'Invalid parameter, sequence number is out of range', self.nodes[0].createrawtransaction, inputs, outputs)
# 10. invalid parameters - sequence number out of range
inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 4294967296}]
outputs = { self.nodes[0].getnewaddress() : 1 }
assert_raises_rpc_error(-8, 'Invalid parameter, sequence number is out of range', self.nodes[0].createrawtransaction, inputs, outputs)
inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 4294967294}]
outputs = { self.nodes[0].getnewaddress() : 1 }
rawtx = self.nodes[0].createrawtransaction(inputs, outputs)
decrawtx= self.nodes[0].decoderawtransaction(rawtx)
assert_equal(decrawtx['vin'][0]['sequence'], 4294967294)
####################################
# TRANSACTION VERSION NUMBER TESTS #
####################################
# Test the minimum transaction version number that fits in a signed 32-bit integer.
# As transaction version is unsigned, this should convert to its unsigned equivalent.
tx = CTransaction()
tx.nVersion = -0x80000000
rawtx = ToHex(tx)
decrawtx = self.nodes[0].decoderawtransaction(rawtx)
assert_equal(decrawtx['version'], 0x80000000)
# Test the maximum transaction version number that fits in a signed 32-bit integer.
tx = CTransaction()
tx.nVersion = 0x7fffffff
rawtx = ToHex(tx)
decrawtx = self.nodes[0].decoderawtransaction(rawtx)
assert_equal(decrawtx['version'], 0x7fffffff)
self.log.info('sendrawtransaction/testmempoolaccept with maxfeerate')
# Test a transaction with a small fee.
txId = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.0)
rawTx = self.nodes[0].getrawtransaction(txId, True)
vout = next(o for o in rawTx['vout'] if o['value'] == Decimal('1.00000000'))
self.sync_all()
inputs = [{ "txid" : txId, "vout" : vout['n'] }]
# Fee 10,000 satoshis, (1 - (10000 sat * 0.00000001 BPS/sat)) = 0.9999
outputs = { self.nodes[0].getnewaddress() : Decimal("0.99990000") }
rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
rawTxSigned = self.nodes[2].signrawtransactionwithwallet(rawTx)
assert_equal(rawTxSigned['complete'], True)
# Fee 10,000 satoshis, ~100 b transaction, fee rate should land around 100 sat/byte = 0.00100000 BPS/kB
# Thus, testmempoolaccept should reject
testres = self.nodes[2].testmempoolaccept([rawTxSigned['hex']], 0.00001000)[0]
assert_equal(testres['allowed'], False)
assert_equal(testres['reject-reason'], 'max-fee-exceeded')
# and sendrawtransaction should throw
assert_raises_rpc_error(-25, 'Fee exceeds maximum configured by user (e.g. -maxtxfee, maxfeerate)', self.nodes[2].sendrawtransaction, rawTxSigned['hex'], 0.00001000)
# and the following calls should both succeed
testres = self.nodes[2].testmempoolaccept(rawtxs=[rawTxSigned['hex']])[0]
assert_equal(testres['allowed'], True)
self.nodes[2].sendrawtransaction(hexstring=rawTxSigned['hex'])
# Test a transaction with a large fee.
txId = self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 1.0)
rawTx = self.nodes[0].getrawtransaction(txId, True)
vout = next(o for o in rawTx['vout'] if o['value'] == Decimal('1.00000000'))
self.sync_all()
inputs = [{ "txid" : txId, "vout" : vout['n'] }]
# Fee 2,000,000 satoshis, (1 - (2000000 sat * 0.00000001 BPS/sat)) = 0.98
outputs = { self.nodes[0].getnewaddress() : Decimal("0.98000000") }
rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
rawTxSigned = self.nodes[2].signrawtransactionwithwallet(rawTx)
assert_equal(rawTxSigned['complete'], True)
# Fee 2,000,000 satoshis, ~100 b transaction, fee rate should land around 20,000 sat/byte = 0.20000000 BPS/kB
# Thus, testmempoolaccept should reject
testres = self.nodes[2].testmempoolaccept([rawTxSigned['hex']])[0]
assert_equal(testres['allowed'], False)
assert_equal(testres['reject-reason'], 'max-fee-exceeded')
# and sendrawtransaction should throw
assert_raises_rpc_error(-25, 'Fee exceeds maximum configured by user (e.g. -maxtxfee, maxfeerate)', self.nodes[2].sendrawtransaction, rawTxSigned['hex'])
# and the following calls should both succeed
testres = self.nodes[2].testmempoolaccept(rawtxs=[rawTxSigned['hex']], maxfeerate='0.20000000')[0]
assert_equal(testres['allowed'], True)
self.nodes[2].sendrawtransaction(hexstring=rawTxSigned['hex'], maxfeerate='0.20000000')
if __name__ == '__main__':
RawTransactionsTest().main()
| 58.685437 | 601 | 0.654932 |
acf00543c214978d6bc0f0dbf9bf1cd47a1d2888 | 1,415 | py | Python | ext/get_titles.py | iArunava/UVa-Desktop | 8f8efa35cabbb2b08d7a888bb3b636c449906a0d | [
"MIT"
] | null | null | null | ext/get_titles.py | iArunava/UVa-Desktop | 8f8efa35cabbb2b08d7a888bb3b636c449906a0d | [
"MIT"
] | null | null | null | ext/get_titles.py | iArunava/UVa-Desktop | 8f8efa35cabbb2b08d7a888bb3b636c449906a0d | [
"MIT"
] | null | null | null | # Script to get all the names of the programs in UVa
# Created by: Aruanva (@iArunava)
# Created on: 13 August, 2017
# Last Updated on: 16 August, 2017
from bs4 import BeautifulSoup
import urllib2
import re
def get_titles_from(uva_url):
resp = urllib2.urlopen (uva_url);
html = resp.read()
soup = BeautifulSoup (html, "html.parser")
for group in soup.find_all ("tr", class_=re.compile ("sectiontableentry[12]")):
soup_td = BeautifulSoup (str (group), "html.parser")
try:
all_in_title = (soup_td.select ("td > a")[1].string).encode('utf-8').strip()
except:
all_in_title = (soup_td.select ("td > a")[0].string).encode('utf-8').strip()
program_info = re.search ('^(\d+)\xc2\xa0-\xc2\xa0([\s\S]*)$', all_in_title)
programid = program_info.group (1)
title = program_info.group (2)
print (programid + " --> " + title)
def generate ():
base_uva_url = "https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category="
categories = [3, 4, 5, 6, 7, 8, 9, 10, 11, 245, 246, 247, 446, 447, 448, 825, 859, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 78, 117, 226, 229, 242, 243, 244, 278, 279, 441, 602, 823, 861, 862, 866, 871, 878]
for i in categories:
get_titles_from (base_uva_url + str (i))
def main ():
generate ()
if __name__ == "__main__":
main()
| 35.375 | 234 | 0.615548 |
acf005e98d8ec18f5082f7adfbe28404844b69e1 | 3,210 | py | Python | pipscoin/wallet/wallet_sync_store.py | Pipscoin-Network/pipscoin-blockchain | f400d26956881eb319786230506bb441f76f64d9 | [
"Apache-2.0"
] | 8 | 2021-08-29T15:13:45.000Z | 2022-03-30T17:23:04.000Z | pipscoin/wallet/wallet_sync_store.py | Pipscoin-Network/pipscoin-blockchain | f400d26956881eb319786230506bb441f76f64d9 | [
"Apache-2.0"
] | 28 | 2021-08-29T02:08:07.000Z | 2022-03-24T23:32:00.000Z | pipscoin/wallet/wallet_sync_store.py | Pipscoin-Network/pipscoin-blockchain | f400d26956881eb319786230506bb441f76f64d9 | [
"Apache-2.0"
] | 4 | 2021-08-29T12:59:05.000Z | 2022-03-15T08:38:29.000Z | import asyncio
import logging
from typing import Dict, List, Optional, Tuple
from pipscoin.types.blockchain_format.sized_bytes import bytes32
from pipscoin.types.header_block import HeaderBlock
from pipscoin.util.ints import uint32
log = logging.getLogger(__name__)
class WalletSyncStore:
# Whether or not we are syncing
sync_mode: bool
# Whether we are waiting for peaks (at the start of sync) or already syncing
waiting_for_peaks: bool
# Potential new peaks that we have received from others.
potential_peaks: Dict[bytes32, HeaderBlock]
# Blocks received from other peers during sync
potential_blocks: Dict[uint32, HeaderBlock]
# Event to signal when blocks are received at each height
potential_blocks_received: Dict[uint32, asyncio.Event]
# Blocks that we have finalized during sync, queue them up for adding after sync is done
potential_future_blocks: List[HeaderBlock]
# A map from height to header hash of blocks added to the chain
header_hashes_added: Dict[uint32, bytes32]
# map from potential peak to fork point
peak_fork_point: Dict[bytes32, uint32]
@classmethod
async def create(cls) -> "WalletSyncStore":
self = cls()
self.sync_mode = False
self.waiting_for_peaks = True
self.potential_peaks = {}
self.potential_blocks = {}
self.potential_blocks_received = {}
self.potential_future_blocks = []
self.header_hashes_added = {}
self.peak_fork_point = {}
return self
def set_sync_mode(self, sync_mode: bool) -> None:
self.sync_mode = sync_mode
def get_sync_mode(self) -> bool:
return self.sync_mode
async def clear_sync_info(self):
self.potential_peaks.clear()
self.potential_blocks.clear()
self.potential_blocks_received.clear()
self.potential_future_blocks.clear()
self.header_hashes_added.clear()
self.waiting_for_peaks = True
self.peak_fork_point = {}
def get_potential_peaks_tuples(self) -> List[Tuple[bytes32, HeaderBlock]]:
return list(self.potential_peaks.items())
def add_potential_peak(self, block: HeaderBlock) -> None:
self.potential_peaks[block.header_hash] = block
def add_potential_fork_point(self, peak_hash: bytes32, fork_point: uint32):
self.peak_fork_point[peak_hash] = fork_point
def get_potential_fork_point(self, peak_hash) -> Optional[uint32]:
if peak_hash in self.peak_fork_point:
return self.peak_fork_point[peak_hash]
else:
return None
def get_potential_peak(self, header_hash: bytes32) -> Optional[HeaderBlock]:
return self.potential_peaks.get(header_hash, None)
def add_potential_future_block(self, block: HeaderBlock):
self.potential_future_blocks.append(block)
def get_potential_future_blocks(self):
return self.potential_future_blocks
def add_header_hashes_added(self, height: uint32, header_hash: bytes32):
self.header_hashes_added[height] = header_hash
def get_header_hashes_added(self, height: uint32) -> Optional[bytes32]:
return self.header_hashes_added.get(height, None)
| 36.477273 | 92 | 0.715576 |
acf006604e9d4ccc055049cdede1550ce82fab78 | 312 | py | Python | src/trigger.py | Invictify/Jupter-Notebook-REST-API | c19cdda37649413367edbed7729bdbd6b209f818 | [
"MIT"
] | 39 | 2020-03-31T23:43:23.000Z | 2022-02-02T00:46:16.000Z | src/trigger.py | Invictify/Jupter-Notebook-REST-API | c19cdda37649413367edbed7729bdbd6b209f818 | [
"MIT"
] | 3 | 2021-03-31T19:31:40.000Z | 2021-12-13T20:36:42.000Z | src/trigger.py | Invictify/Jupter-Notebook-REST-API | c19cdda37649413367edbed7729bdbd6b209f818 | [
"MIT"
] | 8 | 2020-04-02T16:41:24.000Z | 2022-01-25T17:18:23.000Z | import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
def trigger(notebook_filename='chp-traffic.ipynb'):
with open(notebook_filename) as f:
nb = nbformat.read(f, as_version=4)
ep = ExecutePreprocessor(timeout=600, kernel_name='python3')
r = ep.preprocess(nb)
return r
| 31.2 | 64 | 0.74359 |
acf0074e4533e399932cba28ce3e24e7d6000e52 | 1,337 | py | Python | temporal_difference_policy_evaluation.py | ivnle/search-and-optimization-algorithms | 0175561718169d2e0b3ce040c21a0eb42bea5b9e | [
"MIT"
] | null | null | null | temporal_difference_policy_evaluation.py | ivnle/search-and-optimization-algorithms | 0175561718169d2e0b3ce040c21a0eb42bea5b9e | [
"MIT"
] | null | null | null | temporal_difference_policy_evaluation.py | ivnle/search-and-optimization-algorithms | 0175561718169d2e0b3ce040c21a0eb42bea5b9e | [
"MIT"
] | null | null | null | # %%
import gym
from policy_iteration import policy_iteration, heatmap_value_func
import numpy as np
from collections import defaultdict
def reward_to_go(state, k, episode, gamma):
reward = 0
for i, (s, r) in enumerate(episode[k:]):
reward += (gamma ** i) * r
return reward
def td_policy_eval(policy, env, gamma, alpha):
"""
Goal: Estimate value of a policy without knowing the transition probabilities.
"""
# Value function we are trying to approximate
U = np.zeros(env.nS)
iterations = 100000
ob = env.reset()
for i in range(iterations):
a = policy[ob]
new_ob, reward, done, _ = env.step(a)
U[ob] += alpha * (reward + gamma * U[new_ob] - U[ob])
if done:
ob = env.reset()
else:
ob = new_ob
return U
if __name__ == '__main__':
environment = "FrozenLake-v1"
env = gym.make(environment)
env.seed(0)
gamma = 0.9
tolerance = 1e-3
alpha = 0.2
value_function, policy = policy_iteration(
env.env.P, env.env.nS, env.env.nA, gamma, tolerance)
est_val_func = td_policy_eval(policy, env.env, gamma, alpha)
# print(value_function)
# heatmap_value_func(value_function.reshape(8 , -1))
print(est_val_func)
heatmap_value_func(est_val_func.reshape(4 , -1))
| 24.759259 | 82 | 0.62528 |
acf00759cf7d95af655f6f63a164a634a8e06543 | 1,925 | py | Python | examples/scripts/USD_Deposit_Swap.py | bpmbank/pyql | db1fc886a61ab3e234cebf54723abaa4258138b3 | [
"BSD-3-Clause"
] | 488 | 2015-01-13T11:03:27.000Z | 2022-03-31T07:19:44.000Z | examples/scripts/USD_Deposit_Swap.py | bpmbank/pyql | db1fc886a61ab3e234cebf54723abaa4258138b3 | [
"BSD-3-Clause"
] | 139 | 2015-01-05T18:56:55.000Z | 2022-01-26T18:33:37.000Z | examples/scripts/USD_Deposit_Swap.py | bpmbank/pyql | db1fc886a61ab3e234cebf54723abaa4258138b3 | [
"BSD-3-Clause"
] | 142 | 2015-01-07T14:26:46.000Z | 2022-01-23T14:08:47.000Z | """
Copyright (C) 2013, Enthought Inc
Copyright (C) 2013, Patrick Henaff
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
"""
from __future__ import division
from __future__ import print_function
# USD Deposit and Swap Rates
# ==========================
#
# This script shows how to process a curve of US deposit and swap rates.
# The data comes from the US Federal Reserve Board, and is published daily
# as a data set named 'Table H15'.
# Here, we extract a curve from the data set and construct a simple plot .
import os
import datetime
import pandas as pd
import pylab as pl
if __name__ == '__main__':
# maturities in years
maturities_dic = {'Swap1Y': 1,
'Swap2Y': 2,
'Swap3Y': 3,
'Swap4Y': 4,
'Swap5Y': 5,
'Swap7Y': 7,
'Swap10Y': 10,
'Swap30Y': 30,
'Libor1M': 1.0 / 12,
'Libor3M': 3.0 / 12,
'Libor6M': 6.0 / 12}
dt_obs = datetime.datetime(2011, 12, 20)
# extract a yield curve from data frame
libor_rates = pd.read_pickle(os.path.join('..', 'data', 'df_libor.pkl'))
df_libor = pd.DataFrame({'Rate': libor_rates.loc[dt_obs]})
# add maturity column
df_libor['Maturity'] = [maturities_dic[k] for k in df_libor.index]
# ... and sort by increasing maturity
df_libor = df_libor.sort_values('Maturity')
print(df_libor)
pl.plot(df_libor['Maturity'], df_libor['Rate'])
pl.xlabel('Maturity (Yr)')
pl.ylabel('Deposit/Libor Rate')
pl.title('Libor Deposit and Swap Rates (%s) \n from Table H15 \
at www.federalreserve.gov' % dt_obs.strftime('%d-%b-%Y'))
pl.show()
| 32.627119 | 78 | 0.603636 |
acf007cb3fee4eaa2f1bb5e63d2f5f800ecd9e12 | 32,392 | py | Python | analyzer/windows/analyzer.py | Yuanmessi/Bold-Falcon | 00fcaba0b3d9c462b9d20ecb256ff85db5d119e2 | [
"BSD-3-Clause"
] | 24 | 2021-06-21T07:35:37.000Z | 2022-03-22T03:33:59.000Z | analyzer/windows/analyzer.py | Yuanmessi/Bold-Falcon | 00fcaba0b3d9c462b9d20ecb256ff85db5d119e2 | [
"BSD-3-Clause"
] | 3 | 2021-07-01T08:09:05.000Z | 2022-01-28T03:38:36.000Z | analyzer/windows/analyzer.py | Yuanmessi/Bold-Falcon | 00fcaba0b3d9c462b9d20ecb256ff85db5d119e2 | [
"BSD-3-Clause"
] | 6 | 2021-06-22T05:32:57.000Z | 2022-02-11T02:05:45.000Z | # Copyright (C) 2011-2013 Claudio Guarnieri.
# Copyright (C) 2014-2018 Cuckoo Foundation.
# Copyright (C) 2020-2021 PowerLZY.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
import datetime
import hashlib
import logging
import os
import pkgutil
import socket
import struct
import sys
import threading
import traceback
import urllib
import urllib2
import xmlrpclib
import zipfile
from lib.api.process import Process
from lib.common.abstracts import Package, Auxiliary
from lib.common.constants import SHUTDOWN_MUTEX
from lib.common.decide import dump_memory
from lib.common.defines import KERNEL32
from lib.common.exceptions import CuckooError, CuckooDisableModule
from lib.common.hashing import hash_file
from lib.common.rand import random_string
from lib.common.results import upload_to_host
from lib.core.config import Config
from lib.core.ioctl import zer0m0n
from lib.core.packages import choose_package
from lib.core.pipe import PipeServer, PipeForwarder, PipeDispatcher
from lib.core.pipe import disconnect_pipes
from lib.core.privileges import grant_privilege
from lib.core.startup import init_logging, disconnect_logger, set_clock
from modules import auxiliary
log = logging.getLogger("analyzer")
class Files(object):
PROTECTED_NAMES = ()
def __init__(self):
self.files = {}
self.files_orig = {}
self.dumped = []
def is_protected_filename(self, file_name):
"""
Return whether or not to inject into a process with this name.
"""
return file_name.lower() in self.PROTECTED_NAMES
def add_pid(self, filepath, pid, verbose=True):
"""Track a process identifier for this file."""
if not pid or filepath.lower() not in self.files:
return
if pid not in self.files[filepath.lower()]:
self.files[filepath.lower()].append(pid)
verbose and log.info("Added pid %s for %r", pid, filepath)
def add_file(self, filepath, pid=None):
"""Add filepath to the list of files and track the pid."""
if filepath.lower() not in self.files:
log.info(
"Added new file to list with pid %s and path %s",
pid, filepath.encode("utf8")
)
self.files[filepath.lower()] = []
self.files_orig[filepath.lower()] = filepath
self.add_pid(filepath, pid, verbose=False)
def dump_file(self, filepath):
"""Dump a file to the host."""
if not os.path.isfile(filepath):
log.warning("File at path %r does not exist, skip.", filepath)
return False
# Check whether we've already dumped this file - in that case skip it.
try:
sha256 = hash_file(hashlib.sha256, filepath)
if sha256 in self.dumped:
return
except IOError as e:
log.info("Error dumping file from path \"%s\": %s", filepath, e)
return
filename = "%s_%s" % (sha256[:16], os.path.basename(filepath))
upload_path = os.path.join("files", filename)
try:
upload_to_host(
# If available use the original filepath, the one that is
# not lowercased.
self.files_orig.get(filepath.lower(), filepath),
upload_path, self.files.get(filepath.lower(), [])
)
self.dumped.append(sha256)
except (IOError, socket.error) as e:
log.error(
"Unable to upload dropped file at path \"%s\": %s",
filepath, e
)
def delete_file(self, filepath, pid=None):
"""A file is about to removed and thus should be dumped right away."""
self.add_pid(filepath, pid)
self.dump_file(filepath)
# Remove the filepath from the files list.
self.files.pop(filepath.lower(), None)
self.files_orig.pop(filepath.lower(), None)
def move_file(self, oldfilepath, newfilepath, pid=None):
"""A file will be moved - track this change."""
self.add_pid(oldfilepath, pid)
if oldfilepath.lower() in self.files:
# Replace the entry with the new filepath.
self.files[newfilepath.lower()] = \
self.files.pop(oldfilepath.lower(), [])
def dump_files(self):
"""Dump all pending files."""
while self.files:
self.delete_file(self.files.keys()[0])
class ProcessList(object):
def __init__(self):
self.pids = []
self.pids_notrack = []
def add_pid(self, pid, track=True):
"""
Add a process identifier to the process list.
Track determines whether the analyzer should be monitoring this
process, i.e., whether Cuckoo should wait for this process to finish.
"""
if int(pid) not in self.pids and int(pid) not in self.pids_notrack:
if track:
self.pids.append(int(pid))
else:
self.pids_notrack.append(int(pid))
def add_pids(self, pids):
"""Add one or more process identifiers to the process list."""
if isinstance(pids, (tuple, list)):
for pid in pids:
self.add_pid(pid)
else:
self.add_pid(pids)
def has_pid(self, pid, notrack=True):
"""Return whether or not this process identifier being tracked."""
if int(pid) in self.pids:
return True
if notrack and int(pid) in self.pids_notrack:
return True
return False
def remove_pid(self, pid):
"""Remove a process identifier from being tracked."""
if pid in self.pids:
self.pids.remove(pid)
if pid in self.pids_notrack:
self.pids_notrack.remove(pid)
class CommandPipeHandler(object):
"""Pipe Handler.
This class handles the notifications received through the Pipe Server and
decides what to do with them.
"""
ignore_list = dict(pid=[])
def __init__(self, analyzer):
self.analyzer = analyzer
self.tracked = {}
def _handle_debug(self, data):
"""Debug message from the monitor."""
log.debug(data)
def _handle_info(self, data):
"""Regular message from the monitor."""
log.info(data)
def _handle_warning(self, data):
"""Warning message from the monitor."""
log.warning(data)
def _handle_critical(self, data):
"""Critical message from the monitor."""
log.critical(data)
def _handle_loaded(self, data):
"""The monitor has loaded into a particular process."""
if not data or data.count(",") != 1:
log.warning("Received loaded command with incorrect parameters, "
"skipping it.")
return
pid, track = data.split(",")
if not pid.isdigit() or not track.isdigit():
log.warning("Received loaded command with incorrect parameters, "
"skipping it.")
return
self.analyzer.process_lock.acquire()
self.analyzer.process_list.add_pid(int(pid), track=int(track))
self.analyzer.process_lock.release()
log.debug("Loaded monitor into process with pid %s", pid)
def _handle_getpids(self, data):
"""Return the process identifiers of the agent and its parent process."""
return struct.pack("II", self.analyzer.pid, self.analyzer.ppid)
def _inject_process(self, process_id, thread_id, mode):
"""Helper function for injecting the monitor into a process."""
# We acquire the process lock in order to prevent the analyzer to
# terminate the analysis while we are operating on the new process.
self.analyzer.process_lock.acquire()
# Set the current DLL to the default one provided at submission.
dll = self.analyzer.default_dll
if process_id in (self.analyzer.pid, self.analyzer.ppid):
if process_id not in self.ignore_list["pid"]:
log.warning("Received request to inject Cuckoo processes, "
"skipping it.")
self.ignore_list["pid"].append(process_id)
self.analyzer.process_lock.release()
return
# We inject the process only if it's not being monitored already,
# otherwise we would generated polluted logs (if it wouldn't crash
# horribly to start with).
if self.analyzer.process_list.has_pid(process_id):
# This pid is already on the notrack list, move it to the
# list of tracked pids.
if not self.analyzer.process_list.has_pid(process_id, notrack=False):
log.debug("Received request to inject pid=%d. It was already "
"on our notrack list, moving it to the track list.")
self.analyzer.process_list.remove_pid(process_id)
self.analyzer.process_list.add_pid(process_id)
self.ignore_list["pid"].append(process_id)
# Spit out an error once and just ignore it further on.
elif process_id not in self.ignore_list["pid"]:
self.ignore_list["pid"].append(process_id)
# We're done operating on the processes list, release the lock.
self.analyzer.process_lock.release()
return
# Open the process and inject the DLL. Hope it enjoys it.
proc = Process(pid=process_id, tid=thread_id)
filename = os.path.basename(proc.get_filepath())
if not self.analyzer.files.is_protected_filename(filename):
# Add the new process ID to the list of monitored processes.
self.analyzer.process_list.add_pid(process_id)
# We're done operating on the processes list,
# release the lock. Let the injection do its thing.
self.analyzer.process_lock.release()
# If we have both pid and tid, then we can use APC to inject.
if process_id and thread_id:
proc.inject(dll, apc=True, mode="%s" % mode)
else:
proc.inject(dll, apc=False, mode="%s" % mode)
log.info("Injected into process with pid %s and name %r",
proc.pid, filename)
def _handle_process(self, data):
"""Request for injection into a process."""
# Parse the process identifier.
if not data or not data.isdigit():
log.warning("Received PROCESS command from monitor with an "
"incorrect argument.")
return
return self._inject_process(int(data), None, 0)
def _handle_process2(self, data):
"""Request for injection into a process using APC."""
# Parse the process and thread identifier.
if not data or data.count(",") != 2:
log.warning("Received PROCESS2 command from monitor with an "
"incorrect argument.")
return
pid, tid, mode = data.split(",")
if not pid.isdigit() or not tid.isdigit() or not mode.isdigit():
log.warning("Received PROCESS2 command from monitor with an "
"incorrect argument.")
return
return self._inject_process(int(pid), int(tid), int(mode))
def _handle_file_new(self, data):
"""Notification of a new dropped file."""
self.analyzer.files.add_file(data.decode("utf8"), self.pid)
def _handle_file_del(self, data):
"""Notification of a file being removed (if it exists) - we have to
dump it before it's being removed."""
filepath = data.decode("utf8")
if os.path.exists(filepath):
self.analyzer.files.delete_file(filepath, self.pid)
def _handle_file_move(self, data):
"""A file is being moved - track these changes."""
if "::" not in data:
log.warning("Received FILE_MOVE command from monitor with an "
"incorrect argument.")
return
old_filepath, new_filepath = data.split("::", 1)
self.analyzer.files.move_file(
old_filepath.decode("utf8"), new_filepath.decode("utf8"), self.pid
)
def _handle_kill(self, data):
"""A process is being killed."""
if not data.isdigit():
log.warning("Received KILL command with an incorrect argument.")
return
if self.analyzer.config.options.get("procmemdump"):
dump_memory(int(data))
def _handle_dumpmem(self, data):
"""Dump the memory of a process as it is right now."""
if not data.isdigit():
log.warning("Received DUMPMEM command with an incorrect argument.")
return
dump_memory(int(data))
def _handle_dumpreqs(self, data):
if not data.isdigit():
log.warning("Received DUMPREQS command with an incorrect argument %r.", data)
return
pid = int(data)
if pid not in self.tracked:
log.warning("Received DUMPREQS command but there are no reqs for pid %d.", pid)
return
dumpreqs = self.tracked[pid].get("dumpreq", [])
for addr, length in dumpreqs:
log.debug("tracked dump req (%r, %r, %r)", pid, addr, length)
if not addr or not length:
continue
Process(pid=pid).dump_memory_block(int(addr), int(length))
def _handle_track(self, data):
if not data.count(":") == 2:
log.warning("Received TRACK command with an incorrect argument %r.", data)
return
pid, scope, params = data.split(":", 2)
pid = int(pid)
paramtuple = params.split(",")
if pid not in self.tracked:
self.tracked[pid] = {}
if scope not in self.tracked[pid]:
self.tracked[pid][scope] = []
self.tracked[pid][scope].append(paramtuple)
def dispatch(self, data):
response = "NOPE"
if not data or ":" not in data:
log.critical("Unknown command received from the monitor: %r",
data.strip())
else:
# Backwards compatibility (old syntax is, e.g., "FILE_NEW:" vs the
# new syntax, e.g., "1234:FILE_NEW:").
if data[0].isupper():
command, arguments = data.strip().split(":", 1)
self.pid = None
else:
self.pid, command, arguments = data.strip().split(":", 2)
fn = getattr(self, "_handle_%s" % command.lower(), None)
if not fn:
log.critical("Unknown command received from the monitor: %r",
data.strip())
else:
try:
response = fn(arguments)
except:
log.exception(
"Pipe command handler exception occurred (command "
"%s args %r).", command, arguments
)
return response
class Analyzer(object):
"""
Cuckoo Windows Analyzer.
:Note: This class handles the initialization and execution of the analysis
procedure, including handling of the pipe server, the auxiliary modules and
the analysis packages.
"""
def __init__(self):
self.config = None
self.target = None
self.do_run = True
self.time_counter = 0
self.process_lock = threading.Lock()
self.default_dll = None
self.pid = os.getpid()
self.ppid = Process(pid=self.pid).get_parent_pid()
self.files = Files()
self.process_list = ProcessList()
self.package = None
self.reboot = []
def get_pipe_path(self, name):
"""
get the pipe path
:return: \\\\.\\PIPE on Windows XP and \\??\\PIPE elsewhere.
"""
version = sys.getwindowsversion()
if version.major == 5 and version.minor == 1:
return "\\\\.\\PIPE\\%s" % name
return "\\??\\PIPE\\%s" % name
def prepare(self):
"""
Prepare env for analysis.
"""
# Get SeDebugPrivilege for the Python process. It will be needed in
# order to perform the injections.
grant_privilege("SeDebugPrivilege")
grant_privilege("SeLoadDriverPrivilege")
# Initialize logging.
init_logging()
# Parse the analysis configuration file generated by the agent.
self.config = Config(cfg="analysis.conf")
# Pass the configuration through to the Process class.
Process.set_config(self.config)
# Set virtual machine clock.
set_clock(datetime.datetime.strptime(
self.config.clock, "%Y%m%dT%H:%M:%S"
))
# Set the default DLL to be used for this analysis.
self.default_dll = self.config.options.get("dll")
# If a pipe name has not set, then generate a random one.
self.config.pipe = self.get_pipe_path(
self.config.options.get("pipe", random_string(16, 32))
)
# Generate a random name for the logging pipe server.
self.config.logpipe = self.get_pipe_path(random_string(16, 32))
# Initialize and start the Command Handler pipe server. This is going
# to be used for communicating with the monitored processes.
self.command_pipe = PipeServer(
PipeDispatcher, self.config.pipe, message=True,
dispatcher=CommandPipeHandler(self)
)
self.command_pipe.daemon = True
self.command_pipe.start()
# Initialize and start the Log Pipe Server - the log pipe server will
# open up a pipe that monitored processes will use to send logs to
# before they head off to the host machine.
destination = self.config.ip, self.config.port
self.log_pipe_server = PipeServer(
PipeForwarder, self.config.logpipe, destination=destination
)
self.log_pipe_server.daemon = True
self.log_pipe_server.start()
# We update the target according to its category. If it's a file, then
# we store the target path.
if self.config.category == "file":
self.target = os.path.join(
os.environ["TEMP"], self.config.file_name
)
elif self.config.category == "archive":
zip_path = os.path.join(os.environ["TEMP"], self.config.file_name)
zipfile.ZipFile(zip_path).extractall(os.environ["TEMP"])
self.target = os.path.join(
os.environ["TEMP"], self.config.options["filename"]
)
# If it's a URL, well.. we store the URL.
else:
self.target = self.config.target
def stop(self):
"""
Allow an auxiliary module to stop the analysis.
"""
self.do_run = False
def complete(self):
"""
End analysis.
"""
# Stop the Pipe Servers.
self.command_pipe.stop()
self.log_pipe_server.stop()
# Cleanly close remaining connections
disconnect_pipes()
disconnect_logger()
def run(self):
"""
Run analysis.
:return: operation status.
"""
self.prepare()
self.path = os.getcwd()
log.debug("Starting analyzer from: %s", self.path)
log.debug("Pipe server name: %s", self.config.pipe)
log.debug("Log pipe server name: %s", self.config.logpipe)
# If no analysis package was specified at submission, we try to select
# one automatically.
if not self.config.package:
log.debug(
"No analysis package specified, trying to detect "
"it automagically."
)
# If the analysis target is a file, we choose the package according
# to the file format.
if self.config.category == "file":
package = choose_package(
self.config.file_type, self.config.file_name,
self.config.pe_exports.split(",")
)
# If it's an URL, we'll just use the default Internet Explorer
# package.
else:
package = "ie"
# If we weren't able to automatically determine the proper package,
# we need to abort the analysis.
if not package:
raise CuckooError("No valid package available for file "
"type: {0}".format(self.config.file_type))
log.info("Automatically selected analysis package \"%s\"", package)
# Otherwise just select the specified package.
else:
package = self.config.package
# Generate the package path.
package_name = "modules.packages.%s" % package
# Try to import the analysis package.
try:
__import__(package_name, globals(), locals(), ["dummy"], -1)
# If it fails, we need to abort the analysis.
except ImportError:
raise CuckooError("Unable to import package \"{0}\", does "
"not exist.".format(package_name))
# Initialize the package parent abstract.
Package()
# Enumerate the abstract subclasses.
try:
package_class = Package.__subclasses__()[0]
except IndexError as e:
raise CuckooError("Unable to select package class "
"(package={0}): {1}".format(package_name, e))
# Initialize the analysis package.
self.package = package_class(self.config.options, analyzer=self)
# Move the sample to the current working directory as provided by the
# task - one is able to override the starting path of the sample.
# E.g., for some samples it might be useful to run from %APPDATA%
# instead of %TEMP%.
if self.config.category == "file":
self.target = self.package.move_curdir(self.target)
# Initialize Auxiliary modules
Auxiliary()
prefix = auxiliary.__name__ + "."
for loader, name, ispkg in pkgutil.iter_modules(auxiliary.__path__, prefix):
if ispkg:
continue
# Import the auxiliary module.
try:
__import__(name, globals(), locals(), ["dummy"], -1)
except ImportError as e:
log.warning("Unable to import the auxiliary module "
"\"%s\": %s", name, e)
# Walk through the available auxiliary modules.
aux_enabled, aux_avail = [], []
for module in Auxiliary.__subclasses__():
# Try to start the auxiliary module.
try:
aux = module(options=self.config.options, analyzer=self)
aux_avail.append(aux)
aux.init()
aux.start()
except (NotImplementedError, AttributeError):
log.exception(
"Auxiliary module %s was not implemented", module.__name__
)
except CuckooDisableModule:
continue
except Exception as e:
log.exception(
"Cannot execute auxiliary module %s: %s",
module.__name__, e
)
else:
log.debug("Started auxiliary module %s",
module.__name__)
aux_enabled.append(aux)
# Inform zer0m0n of the ResultServer address.
zer0m0n.resultserver(self.config.ip, self.config.port)
# Forward the command pipe and logpipe names on to zer0m0n.
zer0m0n.cmdpipe(self.config.pipe)
zer0m0n.channel(self.config.logpipe)
# Hide the Cuckoo Analyzer & Cuckoo Agent.
zer0m0n.hidepid(self.pid)
zer0m0n.hidepid(self.ppid)
# Initialize zer0m0n with our compiled Yara rules.
zer0m0n.yarald("bin/rules.yarac")
# Propagate the requested dump interval, if set.
zer0m0n.dumpint(int(self.config.options.get("dumpint", "0")))
# Start analysis package. If for any reason, the execution of the
# analysis package fails, we have to abort the analysis.
pids = self.package.start(self.target)
# If the analysis package returned a list of process identifiers, we
# add them to the list of monitored processes and enable the process monitor.
if pids:
self.process_list.add_pids(pids)
pid_check = True
# If the package didn't return any process ID (for example in the case
# where the package isn't enabling any behavioral analysis), we don't
# enable the process monitor.
else:
log.info("No process IDs returned by the package, running "
"for the full timeout.")
pid_check = False
# Check in the options if the user toggled the timeout enforce. If so,
# we need to override pid_check and disable process monitor.
if self.config.enforce_timeout:
log.info("Enabled timeout enforce, running for the full timeout.")
pid_check = False
while self.do_run:
self.time_counter += 1
if self.time_counter == int(self.config.timeout):
log.info("Analysis timeout hit, terminating analysis.")
break
# If the process lock is locked, it means that something is
# operating on the list of monitored processes. Therefore we
# cannot proceed with the checks until the lock is released.
if self.process_lock.locked():
KERNEL32.Sleep(1000)
continue
try:
# If the process monitor is enabled we start checking whether
# the monitored processes are still alive.
if pid_check:
# We also track the PIDs provided by zer0m0n.
self.process_list.add_pids(zer0m0n.getpids())
for pid in self.process_list.pids:
if not Process(pid=pid).is_alive():
log.info("Process with pid %s has terminated", pid)
self.process_list.remove_pid(pid)
# If none of the monitored processes are still alive, we
# can terminate the analysis.
if not self.process_list.pids:
log.info("Process list is empty, "
"terminating analysis.")
break
# Update the list of monitored processes available to the
# analysis package. It could be used for internal
# operations within the module.
self.package.set_pids(self.process_list.pids)
try:
# The analysis packages are provided with a function that
# is executed at every loop's iteration. If such function
# returns False, it means that it requested the analysis
# to be terminate.
if not self.package.check():
log.info("The analysis package requested the "
"termination of the analysis.")
break
# If the check() function of the package raised some exception
# we don't care, we can still proceed with the analysis but we
# throw a warning.
except Exception as e:
log.warning("The package \"%s\" check function raised "
"an exception: %s", package_name, e)
finally:
# Zzz.
KERNEL32.Sleep(1000)
if not self.do_run:
log.debug("The analyzer has been stopped on request by an "
"auxiliary module.")
# Create the shutdown mutex.
KERNEL32.CreateMutexA(None, False, SHUTDOWN_MUTEX)
try:
# Before shutting down the analysis, the package can perform some
# final operations through the finish() function.
self.package.finish()
except Exception as e:
log.warning("The package \"%s\" finish function raised an "
"exception: %s", package_name, e)
try:
# Upload files the package created to package_files in the
# results folder.
for path, name in self.package.package_files() or []:
upload_to_host(path, os.path.join("package_files", name))
except Exception as e:
log.warning("The package \"%s\" package_files function raised an "
"exception: %s", package_name, e)
# Terminate the Auxiliary modules.
for aux in aux_enabled:
try:
aux.stop()
except (NotImplementedError, AttributeError):
continue
except Exception as e:
log.warning("Cannot terminate auxiliary module %s: %s",
aux.__class__.__name__, e)
if self.config.terminate_processes:
# Try to terminate remaining active processes.
log.info("Terminating remaining processes before shutdown.")
for pid in self.process_list.pids:
proc = Process(pid=pid)
if proc.is_alive():
try:
proc.terminate()
except:
continue
# Run the finish callback of every available Auxiliary module.
for aux in aux_avail:
try:
aux.finish()
except (NotImplementedError, AttributeError):
continue
except Exception as e:
log.warning("Exception running finish callback of auxiliary "
"module %s: %s", aux.__class__.__name__, e)
# Dump all the notified files.
self.files.dump_files()
# Hell yeah.
log.info("Analysis completed.")
return True
if __name__ == "__main__":
success = False
error = ""
try:
# Initialize the main analyzer class.
analyzer = Analyzer()
# Run it and wait for the response.
success = analyzer.run()
data = {
"status": "complete",
"description": success,
}
# This is not likely to happen.
except KeyboardInterrupt:
error = "Keyboard Interrupt"
# If the analysis process encountered a critical error, it will raise a
# CuckooError exception, which will force the termination of the analysis.
# Notify the agent of the failure. Also catch unexpected exceptions.
except Exception as e:
# Store the error.
error_exc = traceback.format_exc()
error = "%s\n%s" % (e, error_exc)
# Just to be paranoid.
if len(log.handlers):
log.exception(error_exc)
else:
sys.stderr.write("{0}\n".format(error_exc))
data = {
"status": "exception",
"description": error_exc,
}
finally:
try:
# Let's invoke the completion procedure.
analyzer.complete()
except Exception as e:
complete_excp = traceback.format_exc()
data["status"] = "exception"
if "description" in data:
data["description"] += "%s\n%s" % (
data["description"], complete_excp
)
else:
data["description"] = complete_excp
# Report that we're finished. First try with the XML RPC thing and
# if that fails, attempt the new Agent.
try:
server = xmlrpclib.Server("http://127.0.0.1:8000")
server.complete(success, error, "unused_path")
except Exception as e:
urllib2.urlopen("http://127.0.0.1:8000/status",
urllib.urlencode(data)).read()
| 37.019429 | 91 | 0.578167 |
acf008af29cdf617582e790e5118a503d05d1248 | 2,003 | py | Python | api/migrations/0134_generaldocument.py | IFRCGo/go-api | 6acd84df479f0cf46553029ababa1e7753f86550 | [
"MIT"
] | 11 | 2018-06-11T06:05:12.000Z | 2022-03-25T09:31:44.000Z | api/migrations/0134_generaldocument.py | IFRCGo/go-api | 6acd84df479f0cf46553029ababa1e7753f86550 | [
"MIT"
] | 498 | 2017-11-07T21:20:13.000Z | 2022-03-31T14:37:18.000Z | api/migrations/0134_generaldocument.py | IFRCGo/go-api | 6acd84df479f0cf46553029ababa1e7753f86550 | [
"MIT"
] | 6 | 2018-04-11T13:29:50.000Z | 2020-07-16T16:52:11.000Z | # Generated by Django 2.2.24 on 2021-11-04 14:33
import api.models
import django.core.files.storage
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0133_auto_20210922_1327'),
]
operations = [
migrations.CreateModel(
name='GeneralDocument',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(verbose_name='created at')),
('name', models.CharField(max_length=100, verbose_name='name')),
# Instead of django.core.files.storage.FileSystemStorage(location='media')
('document', models.FileField(blank=True, null=True, storage=api.storage.AzureStorage(),
upload_to=api.models.general_document_path, verbose_name='document')),
('document_url', models.URLField(blank=True, verbose_name='document url')),
],
options={
'verbose_name': 'general document',
'verbose_name_plural': 'general documents',
},
),
migrations.AddField(
model_name='GeneralDocument',
name='name_ar',
field=models.CharField(max_length=200, null=True, verbose_name='name'),
),
migrations.AddField(
model_name='GeneralDocument',
name='name_en',
field=models.CharField(max_length=200, null=True, verbose_name='name'),
),
migrations.AddField(
model_name='GeneralDocument',
name='name_es',
field=models.CharField(max_length=200, null=True, verbose_name='name'),
),
migrations.AddField(
model_name='GeneralDocument',
name='name_fr',
field=models.CharField(max_length=200, null=True, verbose_name='name'),
),
]
| 38.519231 | 116 | 0.585622 |
acf009ce1a05477c41d009e2a3c65fbba59959d6 | 362 | py | Python | Class2_Inher.py | kranthir/seleniumpython-code | 9e3ba44dda9269b2b85b5418dea2bfed1f93416c | [
"MIT"
] | null | null | null | Class2_Inher.py | kranthir/seleniumpython-code | 9e3ba44dda9269b2b85b5418dea2bfed1f93416c | [
"MIT"
] | null | null | null | Class2_Inher.py | kranthir/seleniumpython-code | 9e3ba44dda9269b2b85b5418dea2bfed1f93416c | [
"MIT"
] | null | null | null | class Parent: # define parent class
def myMethod(self):
print 'Calling parent method'
class Child(Parent): # define child class
def myMethod(self):
print 'Calling child method'
def cha(self):
c=Parent()
print 'cha',c.myMethod()
c = Child() # instance of child
c.myMethod()
b= Parent()
b.myMethod()
c.cha()
| 18.1 | 42 | 0.610497 |
acf00bc4beb387bd2e2266974ce8ab8b706700c3 | 393 | py | Python | XDonline/wsgi.py | zws910/XDonline | 491004d0c79f2cc0614d999711ffe9a56a833fb3 | [
"MIT"
] | null | null | null | XDonline/wsgi.py | zws910/XDonline | 491004d0c79f2cc0614d999711ffe9a56a833fb3 | [
"MIT"
] | null | null | null | XDonline/wsgi.py | zws910/XDonline | 491004d0c79f2cc0614d999711ffe9a56a833fb3 | [
"MIT"
] | null | null | null | """
WSGI config for XDonline project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "XDonline.settings")
application = get_wsgi_application()
| 23.117647 | 78 | 0.78626 |
acf00cc65a7ce9b6ee7ef6a840e088a9d5ba997a | 1,118 | py | Python | vex/test/run.py | AdvancedVEXLibrary/Advanced-VEX-Library | 514f92f10c1f4b2c8ba72369116b25e05db9e979 | [
"Apache-2.0"
] | 8 | 2019-05-23T08:50:14.000Z | 2020-02-21T15:13:00.000Z | vex/test/run.py | AdvancedVEXLibrary/Advanced-VEX-Library | 514f92f10c1f4b2c8ba72369116b25e05db9e979 | [
"Apache-2.0"
] | 40 | 2018-10-01T04:57:08.000Z | 2019-04-08T19:56:08.000Z | vex/test/run.py | anvdev/Advanced-VEX-Library | 514f92f10c1f4b2c8ba72369116b25e05db9e979 | [
"Apache-2.0"
] | 2 | 2019-05-23T08:50:19.000Z | 2020-02-13T15:20:06.000Z | from __future__ import print_function
import os
import sys
from subprocess import check_output
def root():
return os.path.dirname(__file__).replace('\\', '/')
def run_test(bin_folder, test_file=None):
avl_test_file = test_file or os.path.join(root(), 'avl_test.vfl').replace('\\', '/')
avl_vex_test_file = avl_test_file[:-3] + 'vex'
print(avl_test_file)
if not os.path.exists(avl_test_file): return
os.environ['HOUDINI_VEX_ASSERT'] = '1'
print(check_output(bin_folder + '/vcc.exe {0} -o {1} -V -I {2}'.format(avl_test_file,
avl_vex_test_file,
os.path.dirname(avl_test_file).replace('\\', '/') + '/../include/'),
shell=False).decode('utf-8'))
print(check_output(bin_folder + '/vexexec.exe ' + avl_vex_test_file, shell=False).decode('utf-8'))
if __name__ == '__main__':
if len(sys.argv) > 1:
run_test(sys.argv[1])
else:
print('Path to Houdini bin folder not found.')
input('Press enter to exit...')
exit()
| 38.551724 | 129 | 0.581395 |
acf00cdddc54c71566a05ae5e20d0aca52475ede | 4,456 | py | Python | tests/components/flexure/test_flexure.py | amanaster2/landlab | ea17f8314eb12e3fc76df66c9b6ff32078caa75c | [
"MIT"
] | 257 | 2015-01-13T16:01:21.000Z | 2022-03-29T22:37:43.000Z | tests/components/flexure/test_flexure.py | amanaster2/landlab | ea17f8314eb12e3fc76df66c9b6ff32078caa75c | [
"MIT"
] | 1,222 | 2015-02-05T21:36:53.000Z | 2022-03-31T17:53:49.000Z | tests/components/flexure/test_flexure.py | amanaster2/landlab | ea17f8314eb12e3fc76df66c9b6ff32078caa75c | [
"MIT"
] | 274 | 2015-02-11T19:56:08.000Z | 2022-03-28T23:31:07.000Z | #! /usr/bin/env python
"""
Unit tests for landlab.components.flexure.flexure
"""
import numpy as np
import pytest
from landlab import RasterModelGrid
from landlab.components import Flexure
(_SHAPE, _SPACING, _ORIGIN) = ((20, 20), (10e3, 10e3), (0.0, 0.0))
def test_method_names():
grid = RasterModelGrid((20, 20), xy_spacing=10e3)
grid.add_zeros("lithosphere__overlying_pressure_increment", at="node")
assert Flexure(grid, method="airy").method == "airy"
assert Flexure(grid, method="flexure").method == "flexure"
with pytest.raises(ValueError):
Flexure(grid, method="bad-name")
def test_eet_attribute():
grid = RasterModelGrid((20, 20), xy_spacing=10e3)
grid.add_zeros("lithosphere__overlying_pressure_increment", at="node")
for val in (10e3, 1e3):
assert Flexure(grid, eet=val).eet == pytest.approx(val)
with pytest.raises(ValueError):
assert Flexure(grid, eet=-10e3)
def test_youngs_attribute():
grid = RasterModelGrid((20, 20), xy_spacing=10e3)
grid.add_zeros("lithosphere__overlying_pressure_increment", at="node")
for val in (10e3, 1e3):
assert Flexure(grid, youngs=val).youngs == pytest.approx(val)
def test_gravity_attribute():
grid = RasterModelGrid((20, 20), xy_spacing=10e3)
grid.add_zeros("lithosphere__overlying_pressure_increment", at="node")
for val in (10e3, 1e3):
assert Flexure(grid, gravity=val).gravity == pytest.approx(val)
def test_rho_mantle_attribute():
grid = RasterModelGrid((20, 20), xy_spacing=10e3)
grid.add_zeros("lithosphere__overlying_pressure_increment", at="node")
for val in (10e3, 1e3):
assert Flexure(grid, rho_mantle=val).rho_mantle == pytest.approx(val)
def test_name(flex):
assert flex.name == "Flexure"
def test_input_var_names(flex):
assert flex.input_var_names == ("lithosphere__overlying_pressure_increment",)
def test_output_var_names(flex):
assert flex.output_var_names == ("lithosphere_surface__elevation_increment",)
def test_var_units(flex):
assert set(flex.input_var_names) | set(flex.output_var_names) == set(
dict(flex.units).keys()
)
assert flex.var_units("lithosphere_surface__elevation_increment") == "m"
assert flex.var_units("lithosphere__overlying_pressure_increment") == "Pa"
def test_grid_shape(flex):
assert flex.grid.number_of_node_rows == _SHAPE[0]
assert flex.grid.number_of_node_columns == _SHAPE[1]
def test_grid_x_extent(flex):
assert flex.grid.extent[1] == (_SHAPE[1] - 1) * _SPACING[1]
def test_grid_y_extent(flex):
assert flex.grid.extent[0] == (_SHAPE[0] - 1) * _SPACING[0]
def test_field_getters(flex):
for name in flex.grid["node"]:
field = flex.grid["node"][name]
assert isinstance(field, np.ndarray)
assert field.shape == (
flex.grid.number_of_node_rows * flex.grid.number_of_node_columns,
)
with pytest.raises(KeyError):
flex.grid["not_a_var_name"]
def test_field_initialized_to_zero(flex):
for name in flex.grid["node"]:
field = flex.grid["node"][name]
assert np.all(field == 0.0)
def test_update():
n = 11
n_mid = (n - 1) // 2
i_mid = np.ravel_multi_index((n_mid, n_mid), (n, n))
load_0 = 1e9
grid = RasterModelGrid((n, n), xy_spacing=1e3)
grid.add_zeros("lithosphere__overlying_pressure_increment", at="node")
flex = Flexure(grid, method="flexure")
load = grid.at_node["lithosphere__overlying_pressure_increment"]
load[i_mid] = load_0
flex.update()
dz = flex.grid.at_node["lithosphere_surface__elevation_increment"].reshape((n, n))
assert np.argmax(dz) == i_mid
assert dz[n_mid, n_mid] > 0.0
assert np.all(dz[:, n_mid::-1] == dz[:, n_mid:])
assert np.all(dz[n_mid::-1, :] == dz[n_mid:, :])
def test_subside_loads():
n, load_0 = 11, 1e9
grid = RasterModelGrid((n, n), xy_spacing=1e3)
grid.add_zeros("lithosphere__overlying_pressure_increment", at="node")
flex = Flexure(grid, method="flexure")
grid.at_node["lithosphere__overlying_pressure_increment"][0] = load_0
flex.update()
dz_expected = flex.grid.at_node["lithosphere_surface__elevation_increment"]
load = np.zeros((n, n))
load[0, 0] = load_0
dz = flex.subside_loads(load)
assert np.all(dz.flatten() == pytest.approx(dz_expected))
out = np.zeros((n, n))
dz = flex.subside_loads(load, out=out)
assert dz is out
| 30.312925 | 86 | 0.689408 |
acf00d2494373db4b5cbeb8d42bab9def2009b42 | 789 | py | Python | chpt4/coinFlipStreaks.py | maxmacdon/Automate | 2f405604ddfde55848798ebb2ad273f089bce466 | [
"MIT"
] | null | null | null | chpt4/coinFlipStreaks.py | maxmacdon/Automate | 2f405604ddfde55848798ebb2ad273f089bce466 | [
"MIT"
] | null | null | null | chpt4/coinFlipStreaks.py | maxmacdon/Automate | 2f405604ddfde55848798ebb2ad273f089bce466 | [
"MIT"
] | null | null | null | #! python3
import random
numberOfStreaks = 0
for experimentNumber in range(10000):
# Code that creates a list of 100 'heads' or 'tails' values.
randomList = []
for listEntry in range(100):
if random.randint(0,1) == 1:
randomList.append('H')
else:
randomList.append('T')
# Code that checks if there is a streak of 6 heads or tails in a row.
counterH, counterT = 0, 0
for flip in range(100):
if randomList[flip] == 'H':
counterH += 1
counterT = 0
else:
counterT += 1
counterH = 0
if counterH == 6 or counterT == 6:
numberOfStreaks +=1
counterH, counterT = 0, 0
print('Chance of streak: %s%%' % (numberOfStreaks/100)) | 29.222222 | 73 | 0.550063 |
acf00d4f4bc295566691790882f4b91429e05379 | 12,734 | py | Python | ckine/FCimports.py | meyer-lab/type-I-ckine-model | fb2db21f1c476d79467e2bf22e1fdc2cdd6c47a3 | [
"MIT"
] | null | null | null | ckine/FCimports.py | meyer-lab/type-I-ckine-model | fb2db21f1c476d79467e2bf22e1fdc2cdd6c47a3 | [
"MIT"
] | 6 | 2021-02-01T23:47:16.000Z | 2021-04-28T19:56:17.000Z | ckine/FCimports.py | meyer-lab/gc-valent | bc0451610655633483a98ab450d20ef631479d2b | [
"MIT"
] | null | null | null | """
This file includes various methods for flow cytometry analysis of fixed cells.
"""
import os
from os.path import dirname, join
from pathlib import Path
import pandas as pd
import numpy as np
from FlowCytometryTools import FCMeasurement, PolyGate
path_here = dirname(dirname(__file__))
def combineWells(samples):
"""Accepts sample array returned from importF, and array of channels, returns combined well data"""
combinedSamples = samples[0]
for sample in samples[1:]:
combinedSamples.data = combinedSamples.data.append(sample.data, ignore_index=True)
return combinedSamples
def importF(date, plate, wellRow, panel, receptorType, wellNum, comp=True):
"""
Import FCS files. Variable input: date in format mm-dd, plate #, panel #, and well letter. Output is a list of Data File Names in FCT Format
Title/file names are returned in the array file --> later referenced in other functions as title/titles input argument
"""
path_ = os.path.abspath("")
pathname = path_ + "/ckine/data/flow/" + date + " Live PBMC Receptor Data/Plate " + plate + "/Plate " + plate + " - Panel " + str(panel) + " " + receptorType + "/"
isotypePathname = pathname + "/Isotypes/"
# Declare arrays and int
file = []
sample = []
isotypes = []
z = 0
# Read in user input for file path and assign to array file
pathlist = Path(r"" + str(pathname)).glob("**/*.fcs")
iso_pathlist = Path(r"" + str(isotypePathname)).glob("**/*.fcs")
for iso in iso_pathlist:
name = iso.name.split("_")[0]
isoSample = FCMeasurement(ID=name, datafile=str(iso))
compedIsoSample = applyMatrix(isoSample, compMatrix(date, plate, wellRow))
isotypes.append(compedIsoSample)
unstainedWell = None
for path in pathlist:
if path.name.split("_")[2] == "Isotype.fcs":
continue
wellID = path.name.split("_")[1]
if wellID[0] == wellRow:
file.append(str(path))
else:
unstainedWell = FCMeasurement(ID="Unstained Sample", datafile=str(path)) # Stores data from unstainedWell separately
file.sort()
assert file != []
# Go through each file and assign the file contents to entry in the array sample
for entry in file:
sample.append(FCMeasurement(ID="Test Sample" + str(z), datafile=entry))
z += 1
# The array sample contains data of each file in folder (one file per entry in array)
if wellNum is None:
if comp is False:
combinedSamples = combineWells(sample)
return combinedSamples, unstainedWell, isotypes
combinedSamples = combineWells(sample) # Combines all files from samples
compSample = applyMatrix(combinedSamples, compMatrix(date, plate, wellRow)) # Applies compensation matrix
return compSample, unstainedWell, isotypes
if comp is False:
return sample[wellNum - 1], unstainedWell, isotypes
compSample = applyMatrix(sample[wellNum - 1], compMatrix(date, plate, wellRow))
return compSample, unstainedWell, isotypes
def subtract_unstained_signal(sample, channels, receptors, unstainedWell, isotypes):
""" Subtract larger of mean isotype signal and mean unstained signal from all input channels for a given sample. """
for _, channel in enumerate(channels):
fileFound = False
if _ < len(isotypes):
for i, iso in enumerate(isotypes):
if iso.ID == receptors[_]:
assert(isotypes[i].ID == receptors[_])
fileFound = True
meanBackground = compareSignals(isotypes[i], unstainedWell, channel) # Returns larger of two background signals
break
if not fileFound:
print("Isotype File Not Found")
meanBackground = np.mean(unstainedWell.data[channel])
sample[channel] = np.maximum(sample[channel] - meanBackground, 0.0)
return sample
def compareSignals(isotype, unstained, channel):
""" Compares a mean isotype and mean unstained signal and returns greater of the two"""
meanIsotype = np.mean(isotype.data[channel])
meanUnstained = np.mean(unstained.data[channel])
if meanIsotype > meanUnstained:
return meanIsotype
else:
return meanUnstained
def compMatrix(date, plate, panel, invert=True):
"""Creates compensation matrix given parameters date in mm-dd, plate number and panel A, B, or C."""
path = path_here + "/ckine/data/compensation/0" + date + "/Plate " + plate + "/Plate " + plate + " - " + panel + ".csv"
# imports csv file with comp values as a dataframe
header_names = ['Channel1', 'Channel2', 'Comp']
df_comp = pd.read_csv(path, header=None, skiprows=1, names=header_names)
# Add diangonal values of 100 to compensation values
addedChannels = []
for i in df_comp.index:
channelName = df_comp.iloc[i]['Channel1']
if channelName not in addedChannels: # Ensures a diagonal value is only added once for each channel
addedChannels.append(channelName)
df2 = pd.DataFrame([[channelName, channelName, 100]], columns=['Channel1', 'Channel2', 'Comp']) # Creates new row for dataframe
df_comp = df_comp.append(df2, ignore_index=True) # Adds row
# Create square matrix from compensation values
df_matrix = pd.DataFrame(index=addedChannels, columns=addedChannels) # df_matrix is now a square and has exactly one row and one column for each channel
for i in df_matrix.index:
for c in df_matrix.columns:
df_matrix.at[i, c] = df_comp.loc[(df_comp['Channel1'] == c) & (df_comp['Channel2'] == i), 'Comp'].iloc[0] # Fills in square matrix by finding corresponding comp value from csv
# df_matrix now has all values in square matrix form
df_matrix = df_matrix.div(100)
if invert: # true by default, inverts matrix before returning it
a = np.matrix(df_matrix.values, dtype=float) # Convert to np to allow for linalg usage
df_matrix = pd.DataFrame(np.linalg.inv(a), df_matrix.columns, df_matrix.index) # Calculate inverse and put pack as dataframe
return df_matrix
def applyMatrix(sample, matrix):
"""Multiples two matrices together in the order sample dot matrix"""
holder = pd.DataFrame() # Will hold columns not being compensated
for c in sample.data.columns:
if c not in matrix: # If sample channel column is not found in matrix
holder = holder.join(sample.data[[c]], how='right') # Store for after calculation
sample.data = sample.data.drop([c], axis=1) # Removed column to allow for matrix multiplication
cols = sample.data.columns
matrix = matrix[cols]
matrix = matrix.reindex(cols)
sample.data = sample.data.dot(matrix) # Use matrix multiplication to compensate the relevant data
sample.data = sample.data.join(holder) # Restore uncompensated channels to sample
return sample
def import_gates():
""" Imports dataframe with gates for all cell types and replicates. """
data = pd.read_csv(join(path_here, "ckine/data/fc_gates.csv"))
data.dropna(axis=0, how='any', thresh=None, subset=None, inplace=True)
return data
def apply_gates(date, plate, gates_df, subpopulations=False, correlation=None):
""" Constructs dataframe with channels relevant to receptor quantification. """
if date == "5-16":
receptors = ['CD127']
channels = ['BL1-H']
else:
receptors = ['CD25', 'CD122', 'CD132']
channels = ["VL1-H", "BL5-H", "RL1-H"]
for i, r in enumerate(receptors):
cellTypes = ['T-helper', 'T-reg', 'NK', 'CD8+']
for j, cellType in enumerate(cellTypes):
if i == 0 and j == 0:
df, unstainedWell, isotypes = samp_Gate(date, plate, gates_df, cellType, r, correlation, subPop=subpopulations)
df = subtract_unstained_signal(df, channels, receptors, unstainedWell, isotypes)
else:
df2, unstainedWell2, isotypes2 = samp_Gate(date, plate, gates_df, cellType, r, correlation, subPop=subpopulations)
df2 = subtract_unstained_signal(df2, channels, receptors, unstainedWell2, isotypes2)
df = df.append(df2)
return df
def samp_Gate(date, plate, gates_df, cellType, receptor, correlation, subPop=False):
""" Returns gated sample for a given date and plate. """
# import data and create transformed df for gating
# correlation argument only implemented for Tcell CD25/CD122 and CD25/CD132, to be used when getting CD25 data
if correlation == 'CD122':
Dict = {'CD127': 1, 'CD25': 3, 'CD122': 3, 'CD132': 5}
elif correlation == 'CD132':
Dict = {'CD127': 1, 'CD25': 5, 'CD122': 3, 'CD132': 5}
else:
Dict = {'CD127': 1, 'CD25': 1, 'CD122': 3, 'CD132': 5}
wellNum = Dict[receptor]
if receptor == 'CD127':
rType = 'IL7R'
else:
rType = 'IL2R'
tchannels, subPopName, row, panelNum = cellGateDat(cellType)
if date == '5-16' and (row == 'C' or row == 'B'):
row = 'A'
panelNum = 1
panel, unstainedWell, isotypes = importF(date, plate, row, panelNum, rType, wellNum)
panel_t = panel.transform("tlog", channels=tchannels) # Creates copy of panel to transform and gate
df = pd.DataFrame(columns=["Cell Type", "Date", "Plate", "VL1-H", "BL5-H", "RL1-H", "BL1-H"])
# Implement gating, revert tlog, and add to dataframe
if cellType in ('T-reg', 'T-helper'):
samplecd3cd4 = panel_t.gate(eval(gates_df.loc[(gates_df["Name"] == 'CD3CD4') &
(gates_df["Date"] == date) & (gates_df["Plate"] == float(plate))]["Gate"].values[0]))
sample = samplecd3cd4.gate(eval(gates_df.loc[(gates_df["Name"] == cellType) &
(gates_df["Date"] == date) & (gates_df["Plate"] == float(plate))]["Gate"].values[0]))
else:
sample = panel_t.gate(eval(gates_df.loc[(gates_df["Name"] == cellType) &
(gates_df["Date"] == date) & (gates_df["Plate"] == float(plate))]["Gate"].values[0]))
# Gated signals based on gating values from csv
gated_idx = np.array(sample.data.index)
panel.set_data(panel.data.loc[gated_idx]) # Selects only the corresponding data points from panel1(untransformed) based on gated points from panel1_t
df_add = pd.DataFrame({"Cell Type": np.tile(cellType, sample.counts), "Date": np.tile(date, sample.counts), "Plate": np.tile(plate, sample.counts),
"VL1-H": panel.data[["VL1-H"]].values.reshape((sample.counts,)), "BL5-H": panel.data[["BL5-H"]].values.reshape((sample.counts,)),
"RL1-H": panel.data[["RL1-H"]].values.reshape((sample.counts,)), "BL1-H": panel.data[["BL1-H"]].values.reshape((sample.counts,))})
df = df.append(df_add)
df['Receptor'] = str(receptor)
# Separates memory and naive populations and adds to dataframe
if subPop:
for subpopulation in subPopName:
sampleSub = sample.gate(eval(gates_df.loc[(gates_df["Name"] == subpopulation) &
(gates_df["Date"] == date) & (gates_df["Plate"] == float(plate))]["Gate"].values[0]))
gated_idx = np.array(sampleSub.data.index)
panel_S = panel.data.loc[gated_idx]
df_add = pd.DataFrame({"Cell Type": np.tile(subpopulation, sampleSub.counts), "Date": np.tile(date, sampleSub.counts), "Plate": np.tile(plate, sampleSub.counts),
"VL1-H": panel_S.data[["VL1-H"]].values.reshape((sampleSub.counts,)), "BL5-H": panel_S.data[["BL5-H"]].values.reshape((sampleSub.counts,)),
"RL1-H": panel_S.data[["RL1-H"]].values.reshape((sampleSub.counts,))})
df = df.append(df_add)
return df, unstainedWell, isotypes
def cellGateDat(cellType):
"Returns pertinent gating information for a given cell type"
if cellType in ('T-reg', 'T-helper'):
tchannels = ['VL6-H', 'VL4-H', 'BL1-H', 'VL1-H', 'BL3-H']
row = 'A'
panel = 1
if cellType == "T-reg":
subPopName = ["Mem Treg", "Naive Treg"]
else:
subPopName = ['Naive Th', 'Mem Th']
elif cellType == "CD8+":
tchannels = ['VL4-H', 'VL6-H', 'BL3-H']
row = 'C'
panel = 3
subPopName = ['Naive CD8+', 'Mem CD8+']
elif cellType == "NK":
tchannels = ['VL4-H', 'BL3-H']
row = 'B'
panel = 2
subPopName = ['NKT']
assert tchannels != []
return tchannels, subPopName, row, panel
| 48.05283 | 188 | 0.632009 |
acf00d96d7ff29c92eefeefda7555eff7f356058 | 405 | py | Python | departmentsApp/migrations/0006_remove_department_prequel.py | i3dprogrammer/Django-GraduationProject | 2445b9f773638a344be8625f0d9ef6c149e68015 | [
"MIT"
] | null | null | null | departmentsApp/migrations/0006_remove_department_prequel.py | i3dprogrammer/Django-GraduationProject | 2445b9f773638a344be8625f0d9ef6c149e68015 | [
"MIT"
] | null | null | null | departmentsApp/migrations/0006_remove_department_prequel.py | i3dprogrammer/Django-GraduationProject | 2445b9f773638a344be8625f0d9ef6c149e68015 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-18 13:50
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('departmentsApp', '0005_auto_20171118_1550'),
]
operations = [
migrations.RemoveField(
model_name='department',
name='prequel',
),
]
| 20.25 | 54 | 0.624691 |
acf00da3cd0aa2c5ff443e573a157f89b3e8aa53 | 206 | py | Python | homepage/views.py | nandiniigarg/offline | 02650899ffffe68d8ab71df35e9fbb9b133e34fc | [
"MIT"
] | null | null | null | homepage/views.py | nandiniigarg/offline | 02650899ffffe68d8ab71df35e9fbb9b133e34fc | [
"MIT"
] | null | null | null | homepage/views.py | nandiniigarg/offline | 02650899ffffe68d8ab71df35e9fbb9b133e34fc | [
"MIT"
] | 1 | 2021-11-07T18:11:00.000Z | 2021-11-07T18:11:00.000Z | from django.http.response import HttpResponse
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return render(request, 'index.html')
| 25.75 | 45 | 0.796117 |
acf00debd212ff6bf45e220d69c5881cadc42667 | 4,391 | py | Python | src/scenic/simulators/lgsvl/actions.py | gaffordb/Scenic | 959450488098871eac8a120bf3de3350855f777f | [
"BSD-3-Clause"
] | null | null | null | src/scenic/simulators/lgsvl/actions.py | gaffordb/Scenic | 959450488098871eac8a120bf3de3350855f777f | [
"BSD-3-Clause"
] | null | null | null | src/scenic/simulators/lgsvl/actions.py | gaffordb/Scenic | 959450488098871eac8a120bf3de3350855f777f | [
"BSD-3-Clause"
] | null | null | null | """Actions for agents in the LGSVL model."""
import math
import lgsvl
import numpy as np
from scipy import linalg
from scenic.domains.driving.actions import * # Most actions imported here
import scenic.simulators.lgsvl.utils as utils
from scenic.core.type_support import toVector
import scenic.syntax.veneer as veneer
class FollowWaypointsAction(Action):
def __init__(self, waypoints):
self.waypoints = tuple(waypoints)
if not isinstance(self.waypoints[0], lgsvl.DriveWaypoint):
pts = []
for wp in self.waypoints:
elev = veneer.simulation().groundElevationAt(wp.position)
pos = utils.scenicToLGSVLPosition(wp.position, y=elev)
rot = utils.scenicToLGSVLRotation(wp.heading)
pt = lgsvl.DriveWaypoint(pos, wp.speed, rot)
pts.append(pt)
self.waypoints = tuple(pts)
self.lastTime = -2
def canBeTakenBy(self, agent):
return agent.lgsvlAgentType in (lgsvl.AgentType.NPC, lgsvl.AgentType.PEDESTRIAN)
def applyTo(self, obj, sim):
if sim.currentTime is not self.lastTime + 1:
obj.lgsvlObject.follow(self.waypoints)
self.lastTime = sim.currentTime
class CancelWaypointsAction(Action):
def canBeTakenBy(self, agent):
return agent.lgsvlAgentType in (lgsvl.AgentType.NPC, lgsvl.AgentType.PEDESTRIAN)
def applyTo(self, obj, sim):
obj.lgsvlObject.walk_randomly(False)
class SetDestinationAction(Action):
def __init__(self, dest):
self.dest = toVector(dest)
self.timer = 0
def canBeTakenBy(self, agent):
return bool(getattr(agent, 'dreamview', False))
def applyTo(self, obj, sim):
if self.timer == 0:
z = sim.groundElevationAt(self.dest)
obj.dreamview.set_destination(self.dest.x, self.dest.y, z,
coord_type=lgsvl.dreamview.CoordType.Unity)
# push vehicle for 1 second to start
oneSec = int(1.0/sim.timestep)
if self.timer < oneSec:
obj.control.throttle = 0.5
elif self.timer == oneSec:
obj.control.throttle = 0.5
obj._stickyControl = False
self.timer = self.timer + 1
class TrackWaypointsAction(Action):
def __init__(self, waypoints, cruising_speed = 10):
self.waypoints = np.array(waypoints)
self.curr_index = 1
self.cruising_speed = cruising_speed
def canBeTakenBy(self, agent):
return agent.lgsvlAgentType is lgsvl.AgentType.EGO
def LQR(v_target, wheelbase, Q, R):
A = np.matrix([[0, v_target*(5./18.)], [0, 0]])
B = np.matrix([[0], [(v_target/wheelbase)*(5./18.)]])
V = np.matrix(linalg.solve_continuous_are(A, B, Q, R))
K = np.matrix(linalg.inv(R)*(B.T*V))
return K
def applyTo(self, obj, sim):
lgsvlObject = obj.lgsvlObject
state = lgsvlObject.state
pos = state.transform.position
rot = state.transform.rotation
velocity = state.velocity
th, x, y, v = rot.y/180.0*np.pi, pos.x, pos.z, (velocity.x**2 + velocity.z**2)**0.5
#print('state:', th, x, y, v)
PREDICTIVE_LENGTH = 3
MIN_SPEED = 1
WHEEL_BASE = 3
v = max(MIN_SPEED, v)
x = x + PREDICTIVE_LENGTH * np.cos(-th+np.pi/2)
y = y + PREDICTIVE_LENGTH * np.sin(-th+np.pi/2)
#print('car front:', x, y)
dists = np.linalg.norm(self.waypoints - np.array([x, y]), axis=1)
dist_pos = np.argpartition(dists,1)
index = dist_pos[0]
if index > self.curr_index and index < len(self.waypoints)-1:
self.curr_index = index
p1, p2, p3 = self.waypoints[self.curr_index-1], self.waypoints[self.curr_index], self.waypoints[self.curr_index+1]
p1_a = np.linalg.norm(p1 - np.array([x, y]))
p3_a = np.linalg.norm(p3 - np.array([x, y]))
p1_p2= np.linalg.norm(p1 - p2)
p3_p2= np.linalg.norm(p3 - p2)
if p1_a - p1_p2 > p3_a - p3_p2:
p1 = p2
p2 = p3
#print('points:',p1, p2)
x1, y1, x2, y2 = p1[0], p1[1], p2[0], p2[1]
th_n = -math.atan2(y2-y1,x2-x1)+np.pi/2
d_th = (th - th_n + 3*np.pi) % (2*np.pi) - np.pi
d_x = (x2-x1)*y - (y2-y1)*x + y2*x1 - y1*x2
d_x /= np.linalg.norm(np.array([x1, y1]) - np.array([x2, y2]))
#print('d_th, d_x:',d_th, d_x)
K = TrackWaypoints.LQR(v, WHEEL_BASE, np.array([[1, 0], [0, 3]]), np.array([[10]]))
u = -K * np.matrix([[-d_x], [d_th]])
u = np.double(u)
u_steering = min(max(u, -1), 1)
K = 1
u = -K*(v - self.cruising_speed)
u_thrust = min(max(u, -1), 1)
#print('u:', u_thrust, u_steering)
cntrl = lgsvl.VehicleControl()
cntrl.steering = u_steering
if u_thrust > 0:
cntrl.throttle = u_thrust
elif u_thrust < 0.1:
cntrl.braking = -u_thrust
lgsvlObject.apply_control(cntrl, True)
| 30.922535 | 116 | 0.677067 |
acf00f2b701cb75c213b167d225ad32f241f70fc | 319 | py | Python | torch_models/models/__init__.py | Ryou0634/pytorch_models | cd48f9b3797839df5dbf4e51bed81de44e7b962e | [
"BSD-3-Clause"
] | null | null | null | torch_models/models/__init__.py | Ryou0634/pytorch_models | cd48f9b3797839df5dbf4e51bed81de44e7b962e | [
"BSD-3-Clause"
] | null | null | null | torch_models/models/__init__.py | Ryou0634/pytorch_models | cd48f9b3797839df5dbf4e51bed81de44e7b962e | [
"BSD-3-Clause"
] | null | null | null | from .attentions import *
from .grad_reverse_mlp import *
from .classifiers import *
from .functions import *
from .generators import *
from .infersent import *
from .mlp import *
from .multi_classifier import *
from .seq_encoders import *
from .beam_searcher import *
from .seq2seq import *
from .transformer import *
| 24.538462 | 31 | 0.774295 |
acf010100ec387a866bc3cf9e2120ef3ba997af8 | 8,874 | py | Python | bot/extensions/reminders.py | Axelancerr/Life | 1e214af2a46439a756c442967be4bfa8b05fd99c | [
"MIT"
] | 27 | 2020-10-18T04:35:00.000Z | 2021-08-03T13:21:27.000Z | bot/extensions/reminders.py | Axelancerr/Life | 1e214af2a46439a756c442967be4bfa8b05fd99c | [
"MIT"
] | 19 | 2020-12-04T23:03:51.000Z | 2021-08-14T20:21:53.000Z | bot/extensions/reminders.py | Axelancerr/Life | 1e214af2a46439a756c442967be4bfa8b05fd99c | [
"MIT"
] | 7 | 2020-10-26T18:51:17.000Z | 2021-07-07T05:39:01.000Z | # Future
from __future__ import annotations
# Packages
import discord
import pendulum
from discord.ext import commands
# My stuff
from core import colours, emojis
from core.bot import Life
from utilities import custom, enums, exceptions, objects, utils
def setup(bot: Life) -> None:
bot.add_cog(Reminders(bot=bot))
class Reminders(commands.Cog):
def __init__(self, bot: Life) -> None:
self.bot = bot
@commands.command(name="remind", aliases=["remindme"])
async def remind(self, ctx: custom.Context, *, when: objects.FuturePhrasedDatetimeSearch) -> None:
"""
Creates a reminder.
**when**: The subject you want to be reminded about, should include some form of time such as **tomorrow**, **10am**, or **3 hours**.
**Usage:**
`l-remind in 3 hours do that thing you talked about doing.`
"""
entries = {index: (phrase, datetime) for index, (phrase, datetime) in enumerate(when.datetimes.items())}
choice = await ctx.choice(
entries=[f"**{index + 1}:** **{phrase}**\n`{utils.format_datetime(datetime)}`" for index, (phrase, datetime) in entries.items()],
per_page=5,
splitter="\n\n",
title="Multiple dates/times where detected in your reminder:",
header="Choose the option that best matches your intended reminder time.\n\n",
)
_, datetime = entries[choice]
if datetime < pendulum.now(tz="UTC"):
raise exceptions.EmbedError(
colour=colours.RED,
emoji=emojis.CROSS,
description="The date/time detected was in the past."
)
user_config = await self.bot.user_manager.get_config(ctx.author.id)
reminder = await user_config.create_reminder(
channel_id=ctx.channel.id,
datetime=datetime,
content=await utils.safe_content(self.bot.mystbin, when.phrase, max_characters=1500),
jump_url=ctx.message.jump_url,
)
await ctx.reply(
embed=discord.Embed(
colour=colours.GREEN,
description=f"Reminder with id **{reminder.id}** created for **{utils.format_datetime(reminder.datetime)}**, "
f"which is in **{utils.format_difference(reminder.datetime)}**.",
)
)
@commands.group(name="reminders", aliases=["reminder"], invoke_without_command=True)
async def _reminders(self, ctx: custom.Context) -> None:
"""
Base reminder command, displays a list of active reminders.
"""
user_config = await self.bot.user_manager.get_config(ctx.author.id)
if not (reminders := [reminder for reminder in user_config.reminders.values() if not reminder.done]):
raise exceptions.EmbedError(
colour=colours.RED,
emoji=emojis.CROSS,
description="You do not have any active reminders."
)
entries = [
f"**{reminder.id}:** [__**In {utils.format_difference(reminder.datetime)}**__]({reminder.jump_url})\n"
f"**When:** {utils.format_datetime(reminder.datetime, seconds=True)}\n"
f"**Repeat:** {reminder.repeat_type.name.replace('_', ' ').lower().title()}\n"
f"**Content:** {await utils.safe_content(self.bot.mystbin, reminder.content, max_characters=80)}\n"
for reminder in sorted(reminders, key=lambda reminder: reminder.datetime)
]
await ctx.paginate_embed(
entries=entries,
per_page=5,
title=f"Active reminders for **{ctx.author}**:"
)
@_reminders.command(name="list", aliases=["l"])
async def _reminders_list(self, ctx: custom.Context) -> None:
"""
Alias of the base reminder command.
"""
await ctx.invoke(self._reminders)
@_reminders.command(name="all", aliases=["a"])
async def _reminders_all(self, ctx: custom.Context) -> None:
"""
Displays a list of all your reminders.
"""
user_config = await self.bot.user_manager.get_config(ctx.author.id)
if not user_config.reminders:
raise exceptions.EmbedError(
colour=colours.RED,
emoji=emojis.CROSS,
description="You do not have any reminders."
)
entries = [
f"**{reminder.id}:** [__**{'In ' if not reminder.done else ''}{utils.format_difference(reminder.datetime)}"
f"{' ago' if reminder.done else ''}**__]({reminder.jump_url})\n"
f"**When:** {utils.format_datetime(reminder.datetime, seconds=True)}\n"
f"**Repeat:** {reminder.repeat_type.name.replace('_', ' ').lower().title()}\n"
f"**Content:** {await utils.safe_content(self.bot.mystbin, reminder.content, max_characters=80)}\n"
for reminder in sorted(user_config.reminders.values(), key=lambda reminder: reminder.datetime)
]
await ctx.paginate_embed(
entries=entries,
per_page=5,
title=f"Reminders for **{ctx.author}**:"
)
@_reminders.command(name="edit")
async def _reminders_edit(self, ctx: custom.Context, reminder: objects.Reminder, *, content: str) -> None:
"""
Edits a reminders content.
`reminder`: The id of the reminder to edit.
`content`: The content to edit the reminder with.
"""
content = await utils.safe_content(self.bot.mystbin, content, max_characters=1500)
await reminder.change_content(content, jump_url=ctx.message.jump_url)
await ctx.reply(
embed=utils.embed(
colour=colours.GREEN,
emoji=emojis.TICK,
description=f"Edited content of reminder with id **{reminder.id}**."
)
)
#
@_reminders.command(name="delete")
async def _reminders_delete(self, ctx: custom.Context, reminders: commands.Greedy[objects.Reminder]) -> None:
"""
Deletes reminders with the given id's.
**reminders**: A list of reminders id's to delete, separated by spaces.
"""
if not reminders:
raise exceptions.EmbedError(
colour=colours.RED,
emoji=emojis.CROSS,
description="One or more of the reminder id's provided were invalid."
)
for reminder in reminders:
await reminder.delete()
s = "s" if len(reminders) > 1 else ""
embed = utils.embed(
colour=colours.GREEN,
emoji=emojis.TICK,
description=f"Deleted **{len(reminders)}** reminder{s} with id{s} {', '.join(f'**{reminder.id}**' for reminder in reminders)}.",
)
await ctx.reply(embed=embed)
@_reminders.command(name="repeat")
async def _reminders_repeat(self, ctx: custom.Context, reminder: objects.Reminder, *, repeat_type: enums.ReminderRepeatType) -> None:
"""
Edits a reminders repeat type.
**reminder**: The id of the reminder to edit.
**repeat_type**: The repeat type to set for the reminder.
"""
if reminder.done:
raise exceptions.EmbedError(
colour=colours.RED,
emoji=emojis.CROSS,
description="That reminder is already done."
)
await reminder.change_repeat_type(repeat_type)
await ctx.reply(
embed=utils.embed(
colour=colours.GREEN,
emoji=emojis.TICK,
description=f"Edited repeat type of reminder with id **{reminder.id}**."
)
)
@_reminders.command(name="info")
async def _reminders_info(self, ctx: custom.Context, reminder: objects.Reminder) -> None:
"""
Displays information about a reminder.
"""
embed = discord.Embed(
colour=colours.MAIN,
title=f"Information for reminder **{reminder.id}:**",
description=f"[__**{'In ' if not reminder.done else ''}{utils.format_difference(reminder.datetime)}"
f"{' ago' if reminder.done else ''}:**__]({reminder.jump_url})\n"
f"**Created:** {utils.format_datetime(reminder.created_at, seconds=True)}\n"
f"**When:** {utils.format_datetime(reminder.datetime, seconds=True)}\n"
f"**Repeat:** {reminder.repeat_type.name.replace('_', ' ').lower().title()}\n"
f"**Done:** {str(reminder.done).replace('False', 'No').replace('True', 'Yes')}\n"
f"**Content:**\n\n"
f"{await utils.safe_content(self.bot.mystbin, reminder.content, max_characters=1000)}",
)
await ctx.reply(embed=embed)
| 38.415584 | 141 | 0.587221 |
acf01068f2bb82380e02e85bcc9de64e8546a9e4 | 1,084 | py | Python | memeify.py | brandonp2412/memeify | 0224aa62287c70ceeb8f352b08625d9a9d1d603f | [
"MIT"
] | null | null | null | memeify.py | brandonp2412/memeify | 0224aa62287c70ceeb8f352b08625d9a9d1d603f | [
"MIT"
] | null | null | null | memeify.py | brandonp2412/memeify | 0224aa62287c70ceeb8f352b08625d9a9d1d603f | [
"MIT"
] | null | null | null | import discord
import random
token = input("Enter your bot token: ")
RANDOM_EMOJIS = [':ok_hand:', ':100:', ':banana:', ':monkey_face:', ':sunglasses:', ':thinking:', ':yum:', ':weary:', ':poop:', ':smiling_imp:', ':scream_cat:']
client = discord.Client()
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!memeify'):
params = message.content.split()
memes = [random.choice(RANDOM_EMOJIS) for param in params[1:]]
meme_text = []
for meme, param in zip(memes, params[1:]):
meme_text.append(meme)
meme_text.append(param)
meme_text = ' '.join(meme_text)
log(message, meme_text)
await client.send_message(message.channel, meme_text)
@client.event
async def on_ready():
print(f'[INFO] -- Logged in as: {client.user.name}')
def log(message, meme_text):
print(f"[INFO] -- User: {message.author} inputted: {message.content}")
print(f"[INFO] -- User: {message.author} got output: {meme_text}")
client.run(token)
| 32.848485 | 160 | 0.635609 |
acf0111000d8dd960b661f613b7706f3f80f2500 | 5,794 | py | Python | third_party/blink/tools/blinkpy/web_tests/models/test_failures_unittest.py | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | third_party/blink/tools/blinkpy/web_tests/models/test_failures_unittest.py | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | third_party/blink/tools/blinkpy/web_tests/models/test_failures_unittest.py | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
from blinkpy.common.system.system_host_mock import MockSystemHost
from blinkpy.web_tests.models.typ_types import ResultType, Artifacts
from blinkpy.web_tests.port.base import Port
from blinkpy.web_tests.port.driver import DriverOutput
from blinkpy.web_tests.models.test_failures import (ALL_FAILURE_CLASSES,
PassWithStderr,
FailureCrash,
FailureTimeout,
TestFailure)
class TestFailuresTest(unittest.TestCase):
def setUp(self):
self._actual_output = DriverOutput(
text=None, image=None, image_hash=None, audio=None)
self._expected_output = DriverOutput(
text=None, image=None, image_hash=None, audio=None)
def assert_loads(self, cls):
failure_obj = cls(self._actual_output, self._expected_output)
s = failure_obj.dumps()
new_failure_obj = TestFailure.loads(s)
self.assertIsInstance(new_failure_obj, cls)
self.assertEqual(failure_obj, new_failure_obj)
# Also test that != is implemented.
self.assertFalse(failure_obj != new_failure_obj)
def test_message_is_virtual(self):
failure_obj = TestFailure(self._actual_output, self._expected_output)
with self.assertRaises(NotImplementedError):
failure_obj.message()
def test_loads(self):
for c in ALL_FAILURE_CLASSES:
self.assert_loads(c)
def test_equals(self):
self.assertEqual(FailureCrash(self._actual_output),
FailureCrash(self._actual_output))
self.assertNotEqual(FailureCrash(self._actual_output),
FailureTimeout(self._actual_output))
crash_set = set([
FailureCrash(self._actual_output),
FailureCrash(self._actual_output)
])
self.assertEqual(len(crash_set), 1)
# The hash happens to be the name of the class, but sets still work:
crash_set = set([FailureCrash(self._actual_output), 'FailureCrash'])
self.assertEqual(len(crash_set), 2)
def test_crashes(self):
self.assertEqual(
FailureCrash(self._actual_output).message(),
'content_shell crashed')
self.assertEqual(
FailureCrash(
self._actual_output,
process_name='foo',
pid=1234).message(), 'foo crashed [pid=1234]')
def test_repeated_test_artifacts(self):
host = MockSystemHost()
port = Port(host, 'baseport')
artifacts = Artifacts('/dir', host.filesystem, repeat_tests=True)
def init_test_failure(test_failure):
test_failure.port = port
test_failure.filesystem = host.filesystem
test_failure.test_name = 'foo.html'
test_failure.result_directory = '/dir'
pass_with_stderr = PassWithStderr(
DriverOutput(None, None, None, None, error=b'pass with stderr'))
init_test_failure(pass_with_stderr)
crash = FailureCrash(
DriverOutput(None,
None,
None,
None,
crash=True,
error=b'crash stderr'))
init_test_failure(crash)
timeout = FailureTimeout(
DriverOutput(None, None, None, None, error=b'timeout with stderr'))
init_test_failure(timeout)
pass_with_stderr.create_artifacts(artifacts)
self.assertEqual('pass with stderr',
host.filesystem.read_text_file('/dir/foo-stderr.txt'))
crash.create_artifacts(artifacts)
self.assertEqual('crash stderr',
host.filesystem.read_text_file('/dir/foo-stderr.txt'))
timeout.create_artifacts(artifacts)
self.assertEqual('timeout with stderr',
host.filesystem.read_text_file('/dir/foo-stderr.txt'))
pass_with_stderr.create_artifacts(artifacts)
self.assertEqual('timeout with stderr',
host.filesystem.read_text_file('/dir/foo-stderr.txt'))
| 43.238806 | 79 | 0.654125 |
acf011131049cdb2c5c40ca479c28ce8e9dc5e9e | 1,081 | py | Python | Examples/interactive.py | vkopey/py2nb | cfec80c172808648d6695fa8e7a868d795be8b1e | [
"MIT"
] | null | null | null | Examples/interactive.py | vkopey/py2nb | cfec80c172808648d6695fa8e7a868d795be8b1e | [
"MIT"
] | null | null | null | Examples/interactive.py | vkopey/py2nb | cfec80c172808648d6695fa8e7a868d795be8b1e | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
# Заголовок
Markdown текст: *курсив* **жирний** `програмний код` [Посилання](https://jupyter.org)

>>> a=2 # програмний код
>>> a**2
LaTeX формула: $a^{i\pi}_{k} + 1 = \frac{\sqrt{x+1}}{\sin x}$
|A |B |C |
|--|--|--|
|1 |2 |3 |
"""
# розкоментуйте наступний рядок для інтерактивності
#%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import *
x = np.linspace(1, 9); line, = plt.plot(x, np.sin(x)/x)
def update(A=(0,2,0.1), B="1.0", C=[0,1,2], D=False):
line.set_ydata((-1 if D else 1)*A*np.sin(float(B)*x+C)/x)
plt.show()
interact(update);
##
print "неформатований текст"
from IPython.display import display, HTML, Markdown, SVG
# візуалізація коду мовами HTML, Markdown, SVG
display(HTML(u"HTML <b>жирний</b> текст"))
display(Markdown(u"Markdown **жирний** текст"))
display(SVG("""<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40">
<circle r="10" cx="50%" cy="50%" fill="green"/></svg>"""))
| 30.885714 | 86 | 0.619796 |
acf0116cfb056638f9e15438a1114cfe32172e7f | 43,394 | py | Python | lib/spack/spack/test/spec_semantics.py | padamson/spack | d3f67a48552691b4846ccc4a10f76740b154090c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 2 | 2018-11-16T02:42:57.000Z | 2019-06-06T19:18:50.000Z | lib/spack/spack/test/spec_semantics.py | padamson/spack | d3f67a48552691b4846ccc4a10f76740b154090c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 32 | 2020-12-15T17:29:20.000Z | 2022-03-21T15:08:31.000Z | lib/spack/spack/test/spec_semantics.py | padamson/spack | d3f67a48552691b4846ccc4a10f76740b154090c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 2 | 2021-07-19T20:31:27.000Z | 2021-07-19T21:14:14.000Z | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import sys
import pytest
import spack.architecture
import spack.directives
import spack.error
from spack.error import SpecError, UnsatisfiableSpecError
from spack.spec import (
Spec,
SpecFormatSigilError,
SpecFormatStringError,
UnconstrainableDependencySpecError,
)
from spack.variant import (
InvalidVariantValueError,
MultipleValuesInExclusiveVariantError,
UnknownVariantError,
substitute_abstract_variants,
)
def make_spec(spec_like, concrete):
if isinstance(spec_like, Spec):
return spec_like
spec = Spec(spec_like)
if concrete:
spec._mark_concrete()
substitute_abstract_variants(spec)
return spec
def _specify(spec_like):
if isinstance(spec_like, Spec):
return spec_like
return Spec(spec_like)
def check_satisfies(target_spec, constraint_spec, target_concrete=False):
target = make_spec(target_spec, target_concrete)
constraint = _specify(constraint_spec)
# Satisfies is one-directional.
assert target.satisfies(constraint)
# If target satisfies constraint, then we should be able to constrain
# constraint by target. Reverse is not always true.
constraint.copy().constrain(target)
def check_unsatisfiable(target_spec, constraint_spec, target_concrete=False):
target = make_spec(target_spec, target_concrete)
constraint = _specify(constraint_spec)
assert not target.satisfies(constraint)
with pytest.raises(UnsatisfiableSpecError):
constraint.copy().constrain(target)
def check_constrain(expected, spec, constraint):
exp = Spec(expected)
spec = Spec(spec)
constraint = Spec(constraint)
spec.constrain(constraint)
assert exp == spec
def check_constrain_changed(spec, constraint):
spec = Spec(spec)
assert spec.constrain(constraint)
def check_constrain_not_changed(spec, constraint):
spec = Spec(spec)
assert not spec.constrain(constraint)
def check_invalid_constraint(spec, constraint):
spec = Spec(spec)
constraint = Spec(constraint)
with pytest.raises((UnsatisfiableSpecError,
UnconstrainableDependencySpecError)):
spec.constrain(constraint)
@pytest.mark.usefixtures('config', 'mock_packages')
class TestSpecSematics(object):
"""This tests satisfies(), constrain() and other semantic operations
on specs.
"""
def test_satisfies(self):
check_satisfies('libelf@0.8.13', '@0:1')
check_satisfies('libdwarf^libelf@0.8.13', '^libelf@0:1')
def test_empty_satisfies(self):
# Basic satisfaction
check_satisfies('libelf', Spec())
check_satisfies('libdwarf', Spec())
check_satisfies('%intel', Spec())
check_satisfies('^mpi', Spec())
check_satisfies('+debug', Spec())
check_satisfies('@3:', Spec())
# Concrete (strict) satisfaction
check_satisfies('libelf', Spec(), True)
check_satisfies('libdwarf', Spec(), True)
check_satisfies('%intel', Spec(), True)
check_satisfies('^mpi', Spec(), True)
# TODO: Variants can't be called concrete while anonymous
# check_satisfies('+debug', Spec(), True)
check_satisfies('@3:', Spec(), True)
# Reverse (non-strict) satisfaction
check_satisfies(Spec(), 'libelf')
check_satisfies(Spec(), 'libdwarf')
check_satisfies(Spec(), '%intel')
check_satisfies(Spec(), '^mpi')
# TODO: Variant matching is auto-strict
# we should rethink this
# check_satisfies(Spec(), '+debug')
check_satisfies(Spec(), '@3:')
def test_satisfies_namespace(self):
check_satisfies('builtin.mpich', 'mpich')
check_satisfies('builtin.mock.mpich', 'mpich')
# TODO: only works for deps now, but shouldn't we allow for root spec?
# check_satisfies('builtin.mock.mpich', 'mpi')
check_satisfies('builtin.mock.mpich', 'builtin.mock.mpich')
check_unsatisfiable('builtin.mock.mpich', 'builtin.mpich')
def test_satisfies_namespaced_dep(self):
"""Ensure spec from same or unspecified namespace satisfies namespace
constraint."""
check_satisfies('mpileaks ^builtin.mock.mpich', '^mpich')
check_satisfies('mpileaks ^builtin.mock.mpich', '^mpi')
check_satisfies(
'mpileaks ^builtin.mock.mpich', '^builtin.mock.mpich')
check_unsatisfiable(
'mpileaks ^builtin.mock.mpich', '^builtin.mpich')
def test_satisfies_compiler(self):
check_satisfies('foo%gcc', '%gcc')
check_satisfies('foo%intel', '%intel')
check_unsatisfiable('foo%intel', '%gcc')
check_unsatisfiable('foo%intel', '%pgi')
def test_satisfies_compiler_version(self):
check_satisfies('foo%gcc', '%gcc@4.7.2')
check_satisfies('foo%intel', '%intel@4.7.2')
check_satisfies('foo%pgi@4.5', '%pgi@4.4:4.6')
check_satisfies('foo@2.0%pgi@4.5', '@1:3%pgi@4.4:4.6')
check_unsatisfiable('foo%pgi@4.3', '%pgi@4.4:4.6')
check_unsatisfiable('foo@4.0%pgi', '@1:3%pgi')
check_unsatisfiable('foo@4.0%pgi@4.5', '@1:3%pgi@4.4:4.6')
check_satisfies('foo %gcc@4.7.3', '%gcc@4.7')
check_unsatisfiable('foo %gcc@4.7', '%gcc@4.7.3')
def test_satisfies_architecture(self):
check_satisfies(
'foo platform=test',
'platform=test')
check_satisfies(
'foo platform=linux',
'platform=linux')
check_satisfies(
'foo platform=test',
'platform=test target=frontend')
check_satisfies(
'foo platform=test',
'platform=test os=frontend target=frontend')
check_satisfies(
'foo platform=test os=frontend target=frontend',
'platform=test')
check_unsatisfiable(
'foo platform=linux',
'platform=test os=redhat6 target=x86')
check_unsatisfiable(
'foo os=redhat6',
'platform=test os=debian6 target=x86_64')
check_unsatisfiable(
'foo target=x86_64',
'platform=test os=redhat6 target=x86')
check_satisfies(
'foo arch=test-None-None',
'platform=test')
check_satisfies(
'foo arch=test-None-frontend',
'platform=test target=frontend')
check_satisfies(
'foo arch=test-frontend-frontend',
'platform=test os=frontend target=frontend')
check_satisfies(
'foo arch=test-frontend-frontend',
'platform=test')
check_unsatisfiable(
'foo arch=test-frontend-frontend',
'platform=test os=frontend target=backend')
check_satisfies(
'foo platform=test target=frontend os=frontend',
'platform=test target=frontend os=frontend')
check_satisfies(
'foo platform=test target=backend os=backend',
'platform=test target=backend os=backend')
check_satisfies(
'foo platform=test target=default_target os=default_os',
'platform=test os=default_os')
check_unsatisfiable(
'foo platform=test target=x86 os=redhat6',
'platform=linux target=x86 os=redhat6')
def test_satisfies_dependencies(self):
check_satisfies('mpileaks^mpich', '^mpich')
check_satisfies('mpileaks^zmpi', '^zmpi')
check_unsatisfiable('mpileaks^mpich', '^zmpi')
check_unsatisfiable('mpileaks^zmpi', '^mpich')
def test_satisfies_dependency_versions(self):
check_satisfies('mpileaks^mpich@2.0', '^mpich@1:3')
check_unsatisfiable('mpileaks^mpich@1.2', '^mpich@2.0')
check_satisfies(
'mpileaks^mpich@2.0^callpath@1.5', '^mpich@1:3^callpath@1.4:1.6')
check_unsatisfiable(
'mpileaks^mpich@4.0^callpath@1.5', '^mpich@1:3^callpath@1.4:1.6')
check_unsatisfiable(
'mpileaks^mpich@2.0^callpath@1.7', '^mpich@1:3^callpath@1.4:1.6')
check_unsatisfiable(
'mpileaks^mpich@4.0^callpath@1.7', '^mpich@1:3^callpath@1.4:1.6')
def test_satisfies_virtual_dependencies(self):
check_satisfies('mpileaks^mpi', '^mpi')
check_satisfies('mpileaks^mpi', '^mpich')
check_satisfies('mpileaks^mpi', '^zmpi')
check_unsatisfiable('mpileaks^mpich', '^zmpi')
def test_satisfies_virtual_dependency_versions(self):
check_satisfies('mpileaks^mpi@1.5', '^mpi@1.2:1.6')
check_unsatisfiable('mpileaks^mpi@3', '^mpi@1.2:1.6')
check_satisfies('mpileaks^mpi@2:', '^mpich')
check_satisfies('mpileaks^mpi@2:', '^mpich@3.0.4')
check_satisfies('mpileaks^mpi@2:', '^mpich2@1.4')
check_satisfies('mpileaks^mpi@1:', '^mpich2')
check_satisfies('mpileaks^mpi@2:', '^mpich2')
check_unsatisfiable('mpileaks^mpi@3:', '^mpich2@1.4')
check_unsatisfiable('mpileaks^mpi@3:', '^mpich2')
check_unsatisfiable('mpileaks^mpi@3:', '^mpich@1.0')
def test_satisfies_matching_variant(self):
check_satisfies('mpich+foo', 'mpich+foo')
check_satisfies('mpich~foo', 'mpich~foo')
check_satisfies('mpich foo=1', 'mpich foo=1')
# confirm that synonymous syntax works correctly
check_satisfies('mpich+foo', 'mpich foo=True')
check_satisfies('mpich foo=true', 'mpich+foo')
check_satisfies('mpich~foo', 'mpich foo=FALSE')
check_satisfies('mpich foo=False', 'mpich~foo')
check_satisfies('mpich foo=*', 'mpich~foo')
check_satisfies('mpich +foo', 'mpich foo=*')
def test_satisfies_multi_value_variant(self):
# Check quoting
check_satisfies('multivalue-variant foo="bar,baz"',
'multivalue-variant foo="bar,baz"')
check_satisfies('multivalue-variant foo=bar,baz',
'multivalue-variant foo=bar,baz')
check_satisfies('multivalue-variant foo="bar,baz"',
'multivalue-variant foo=bar,baz')
# A more constrained spec satisfies a less constrained one
check_satisfies('multivalue-variant foo="bar,baz"',
'multivalue-variant foo=*')
check_satisfies('multivalue-variant foo=*',
'multivalue-variant foo="bar,baz"')
check_satisfies('multivalue-variant foo="bar,baz"',
'multivalue-variant foo="bar"')
check_satisfies('multivalue-variant foo="bar,baz"',
'multivalue-variant foo="baz"')
check_satisfies('multivalue-variant foo="bar,baz,barbaz"',
'multivalue-variant foo="bar,baz"')
check_satisfies('multivalue-variant foo="bar,baz"',
'foo="bar,baz"')
check_satisfies('multivalue-variant foo="bar,baz"',
'foo="bar"')
def test_satisfies_single_valued_variant(self):
"""Tests that the case reported in
https://github.com/spack/spack/pull/2386#issuecomment-282147639
is handled correctly.
"""
a = Spec('a foobar=bar')
a.concretize()
assert a.satisfies('foobar=bar')
assert a.satisfies('foobar=*')
# Assert that an autospec generated from a literal
# gives the right result for a single valued variant
assert 'foobar=bar' in a
assert 'foobar=baz' not in a
assert 'foobar=fee' not in a
# ... and for a multi valued variant
assert 'foo=bar' in a
# Check that conditional dependencies are treated correctly
assert '^b' in a
def test_unsatisfied_single_valued_variant(self):
a = Spec('a foobar=baz')
a.concretize()
assert '^b' not in a
mv = Spec('multivalue-variant')
mv.concretize()
assert 'a@1.0' not in mv
def test_indirect_unsatisfied_single_valued_variant(self):
spec = Spec('singlevalue-variant-dependent')
spec.concretize()
assert 'a@1.0' not in spec
def test_unsatisfiable_multi_value_variant(self):
# Semantics for a multi-valued variant is different
# Depending on whether the spec is concrete or not
a = make_spec(
'multivalue-variant foo="bar"', concrete=True
)
spec_str = 'multivalue-variant foo="bar,baz"'
b = Spec(spec_str)
assert not a.satisfies(b)
assert not a.satisfies(spec_str)
# A concrete spec cannot be constrained further
with pytest.raises(UnsatisfiableSpecError):
a.constrain(b)
a = Spec('multivalue-variant foo="bar"')
spec_str = 'multivalue-variant foo="bar,baz"'
b = Spec(spec_str)
# The specs are abstract and they **could** be constrained
assert a.satisfies(b)
assert a.satisfies(spec_str)
# An abstract spec can instead be constrained
assert a.constrain(b)
a = make_spec(
'multivalue-variant foo="bar,baz"', concrete=True
)
spec_str = 'multivalue-variant foo="bar,baz,quux"'
b = Spec(spec_str)
assert not a.satisfies(b)
assert not a.satisfies(spec_str)
# A concrete spec cannot be constrained further
with pytest.raises(UnsatisfiableSpecError):
a.constrain(b)
a = Spec('multivalue-variant foo="bar,baz"')
spec_str = 'multivalue-variant foo="bar,baz,quux"'
b = Spec(spec_str)
# The specs are abstract and they **could** be constrained
assert a.satisfies(b)
assert a.satisfies(spec_str)
# An abstract spec can instead be constrained
assert a.constrain(b)
# ...but will fail during concretization if there are
# values in the variant that are not allowed
with pytest.raises(InvalidVariantValueError):
a.concretize()
# This time we'll try to set a single-valued variant
a = Spec('multivalue-variant fee="bar"')
spec_str = 'multivalue-variant fee="baz"'
b = Spec(spec_str)
# The specs are abstract and they **could** be constrained,
# as before concretization I don't know which type of variant
# I have (if it is not a BV)
assert a.satisfies(b)
assert a.satisfies(spec_str)
# A variant cannot be parsed as single-valued until we try to
# concretize. This means that we can constrain the variant above
assert a.constrain(b)
# ...but will fail during concretization if there are
# multiple values set
with pytest.raises(MultipleValuesInExclusiveVariantError):
a.concretize()
def test_unsatisfiable_variant_types(self):
# These should fail due to incompatible types
# FIXME: these needs to be checked as the new relaxed
# FIXME: semantic makes them fail (constrain does not raise)
# check_unsatisfiable('multivalue-variant +foo',
# 'multivalue-variant foo="bar"')
# check_unsatisfiable('multivalue-variant ~foo',
# 'multivalue-variant foo="bar"')
check_unsatisfiable(
target_spec='multivalue-variant foo="bar"',
constraint_spec='multivalue-variant +foo',
target_concrete=True
)
check_unsatisfiable(
target_spec='multivalue-variant foo="bar"',
constraint_spec='multivalue-variant ~foo',
target_concrete=True
)
def test_satisfies_unconstrained_variant(self):
# only asked for mpich, no constraints. Either will do.
check_satisfies('mpich+foo', 'mpich')
check_satisfies('mpich~foo', 'mpich')
check_satisfies('mpich foo=1', 'mpich')
def test_unsatisfiable_variants(self):
# This case is different depending on whether the specs are concrete.
# 'mpich' is not concrete:
check_satisfies('mpich', 'mpich+foo', False)
check_satisfies('mpich', 'mpich~foo', False)
check_satisfies('mpich', 'mpich foo=1', False)
# 'mpich' is concrete:
check_unsatisfiable('mpich', 'mpich+foo', True)
check_unsatisfiable('mpich', 'mpich~foo', True)
check_unsatisfiable('mpich', 'mpich foo=1', True)
def test_unsatisfiable_variant_mismatch(self):
# No matchi in specs
check_unsatisfiable('mpich~foo', 'mpich+foo')
check_unsatisfiable('mpich+foo', 'mpich~foo')
check_unsatisfiable('mpich foo=True', 'mpich foo=False')
def test_satisfies_matching_compiler_flag(self):
check_satisfies('mpich cppflags="-O3"', 'mpich cppflags="-O3"')
check_satisfies(
'mpich cppflags="-O3 -Wall"', 'mpich cppflags="-O3 -Wall"'
)
def test_satisfies_unconstrained_compiler_flag(self):
# only asked for mpich, no constraints. Any will do.
check_satisfies('mpich cppflags="-O3"', 'mpich')
def test_unsatisfiable_compiler_flag(self):
# This case is different depending on whether the specs are concrete.
# 'mpich' is not concrete:
check_satisfies('mpich', 'mpich cppflags="-O3"', False)
# 'mpich' is concrete:
check_unsatisfiable('mpich', 'mpich cppflags="-O3"', True)
def test_copy_satisfies_transitive(self):
spec = Spec('dttop')
spec.concretize()
copy = spec.copy()
for s in spec.traverse():
assert s.satisfies(copy[s.name])
assert copy[s.name].satisfies(s)
def test_unsatisfiable_compiler_flag_mismatch(self):
# No matchi in specs
check_unsatisfiable(
'mpich cppflags="-O3"', 'mpich cppflags="-O2"')
def test_satisfies_virtual(self):
# Don't use check_satisfies: it checks constrain() too, and
# you can't constrain a non-virtual by a virtual.
assert Spec('mpich').satisfies(Spec('mpi'))
assert Spec('mpich2').satisfies(Spec('mpi'))
assert Spec('zmpi').satisfies(Spec('mpi'))
def test_satisfies_virtual_dep_with_virtual_constraint(self):
"""Ensure we can satisfy virtual constraints when there are multiple
vdep providers in the specs."""
assert Spec('netlib-lapack ^openblas').satisfies(
'netlib-lapack ^openblas'
)
assert not Spec('netlib-lapack ^netlib-blas').satisfies(
'netlib-lapack ^openblas'
)
assert not Spec('netlib-lapack ^openblas').satisfies(
'netlib-lapack ^netlib-blas'
)
assert Spec('netlib-lapack ^netlib-blas').satisfies(
'netlib-lapack ^netlib-blas'
)
def test_satisfies_same_spec_with_different_hash(self):
"""Ensure that concrete specs are matched *exactly* by hash."""
s1 = Spec('mpileaks').concretized()
s2 = s1.copy()
assert s1.satisfies(s2)
assert s2.satisfies(s1)
# Simulate specs that were installed before and after a change to
# Spack's hashing algorithm. This just reverses s2's hash.
s2._hash = s1.dag_hash()[-1::-1]
assert not s1.satisfies(s2)
assert not s2.satisfies(s1)
# ========================================================================
# Indexing specs
# ========================================================================
def test_self_index(self):
s = Spec('callpath')
assert s['callpath'] == s
def test_dep_index(self):
s = Spec('callpath')
s.normalize()
assert s['callpath'] == s
assert type(s['dyninst']) == Spec
assert type(s['libdwarf']) == Spec
assert type(s['libelf']) == Spec
assert type(s['mpi']) == Spec
assert s['dyninst'].name == 'dyninst'
assert s['libdwarf'].name == 'libdwarf'
assert s['libelf'].name == 'libelf'
assert s['mpi'].name == 'mpi'
def test_spec_contains_deps(self):
s = Spec('callpath')
s.normalize()
assert 'dyninst' in s
assert 'libdwarf' in s
assert 'libelf' in s
assert 'mpi' in s
@pytest.mark.usefixtures('config')
def test_virtual_index(self):
s = Spec('callpath')
s.concretize()
s_mpich = Spec('callpath ^mpich')
s_mpich.concretize()
s_mpich2 = Spec('callpath ^mpich2')
s_mpich2.concretize()
s_zmpi = Spec('callpath ^zmpi')
s_zmpi.concretize()
assert s['mpi'].name != 'mpi'
assert s_mpich['mpi'].name == 'mpich'
assert s_mpich2['mpi'].name == 'mpich2'
assert s_zmpi['zmpi'].name == 'zmpi'
for spec in [s, s_mpich, s_mpich2, s_zmpi]:
assert 'mpi' in spec
# ========================================================================
# Constraints
# ========================================================================
def test_constrain_variants(self):
check_constrain('libelf@2.1:2.5', 'libelf@0:2.5', 'libelf@2.1:3')
check_constrain(
'libelf@2.1:2.5%gcc@4.5:4.6',
'libelf@0:2.5%gcc@2:4.6',
'libelf@2.1:3%gcc@4.5:4.7'
)
check_constrain('libelf+debug+foo', 'libelf+debug', 'libelf+foo')
check_constrain(
'libelf+debug+foo', 'libelf+debug', 'libelf+debug+foo'
)
check_constrain(
'libelf debug=2 foo=1', 'libelf debug=2', 'libelf foo=1'
)
check_constrain(
'libelf debug=2 foo=1', 'libelf debug=2', 'libelf debug=2 foo=1'
)
check_constrain('libelf+debug~foo', 'libelf+debug', 'libelf~foo')
check_constrain(
'libelf+debug~foo', 'libelf+debug', 'libelf+debug~foo'
)
def test_constrain_multi_value_variant(self):
check_constrain(
'multivalue-variant foo="bar,baz"',
'multivalue-variant foo="bar"',
'multivalue-variant foo="baz"'
)
check_constrain(
'multivalue-variant foo="bar,baz,barbaz"',
'multivalue-variant foo="bar,barbaz"',
'multivalue-variant foo="baz"'
)
check_constrain(
'libelf foo=bar,baz', 'libelf foo=bar,baz', 'libelf foo=*')
check_constrain(
'libelf foo=bar,baz', 'libelf foo=*', 'libelf foo=bar,baz')
def test_constrain_compiler_flags(self):
check_constrain(
'libelf cflags="-O3" cppflags="-Wall"',
'libelf cflags="-O3"',
'libelf cppflags="-Wall"'
)
check_constrain(
'libelf cflags="-O3" cppflags="-Wall"',
'libelf cflags="-O3"',
'libelf cflags="-O3" cppflags="-Wall"'
)
def test_constrain_architecture(self):
check_constrain(
'libelf target=default_target os=default_os',
'libelf target=default_target os=default_os',
'libelf target=default_target os=default_os'
)
check_constrain(
'libelf target=default_target os=default_os',
'libelf',
'libelf target=default_target os=default_os'
)
def test_constrain_compiler(self):
check_constrain(
'libelf %gcc@4.4.7', 'libelf %gcc@4.4.7', 'libelf %gcc@4.4.7'
)
check_constrain(
'libelf %gcc@4.4.7', 'libelf', 'libelf %gcc@4.4.7'
)
def test_invalid_constraint(self):
check_invalid_constraint('libelf@0:2.0', 'libelf@2.1:3')
check_invalid_constraint(
'libelf@0:2.5%gcc@4.8:4.9', 'libelf@2.1:3%gcc@4.5:4.7')
check_invalid_constraint('libelf+debug', 'libelf~debug')
check_invalid_constraint('libelf+debug~foo', 'libelf+debug+foo')
check_invalid_constraint('libelf debug=True', 'libelf debug=False')
check_invalid_constraint(
'libelf cppflags="-O3"', 'libelf cppflags="-O2"')
check_invalid_constraint(
'libelf platform=test target=be os=be', 'libelf target=fe os=fe'
)
check_invalid_constraint('libdwarf', '^%gcc')
def test_constrain_changed(self):
check_constrain_changed('libelf', '@1.0')
check_constrain_changed('libelf', '@1.0:5.0')
check_constrain_changed('libelf', '%gcc')
check_constrain_changed('libelf%gcc', '%gcc@4.5')
check_constrain_changed('libelf', '+debug')
check_constrain_changed('libelf', 'debug=*')
check_constrain_changed('libelf', '~debug')
check_constrain_changed('libelf', 'debug=2')
check_constrain_changed('libelf', 'cppflags="-O3"')
platform = spack.architecture.platform()
check_constrain_changed(
'libelf', 'target=' + platform.target('default_target').name)
check_constrain_changed(
'libelf', 'os=' + platform.operating_system('default_os').name)
def test_constrain_not_changed(self):
check_constrain_not_changed('libelf', 'libelf')
check_constrain_not_changed('libelf@1.0', '@1.0')
check_constrain_not_changed('libelf@1.0:5.0', '@1.0:5.0')
check_constrain_not_changed('libelf%gcc', '%gcc')
check_constrain_not_changed('libelf%gcc@4.5', '%gcc@4.5')
check_constrain_not_changed('libelf+debug', '+debug')
check_constrain_not_changed('libelf~debug', '~debug')
check_constrain_not_changed('libelf debug=2', 'debug=2')
check_constrain_not_changed('libelf debug=2', 'debug=*')
check_constrain_not_changed(
'libelf cppflags="-O3"', 'cppflags="-O3"')
platform = spack.architecture.platform()
default_target = platform.target('default_target').name
check_constrain_not_changed(
'libelf target=' + default_target, 'target=' + default_target)
def test_constrain_dependency_changed(self):
check_constrain_changed('libelf^foo', 'libelf^foo@1.0')
check_constrain_changed('libelf^foo', 'libelf^foo@1.0:5.0')
check_constrain_changed('libelf^foo', 'libelf^foo%gcc')
check_constrain_changed('libelf^foo%gcc', 'libelf^foo%gcc@4.5')
check_constrain_changed('libelf^foo', 'libelf^foo+debug')
check_constrain_changed('libelf^foo', 'libelf^foo~debug')
check_constrain_changed('libelf', '^foo')
platform = spack.architecture.platform()
default_target = platform.target('default_target').name
check_constrain_changed(
'libelf^foo', 'libelf^foo target=' + default_target)
def test_constrain_dependency_not_changed(self):
check_constrain_not_changed('libelf^foo@1.0', 'libelf^foo@1.0')
check_constrain_not_changed(
'libelf^foo@1.0:5.0', 'libelf^foo@1.0:5.0')
check_constrain_not_changed('libelf^foo%gcc', 'libelf^foo%gcc')
check_constrain_not_changed(
'libelf^foo%gcc@4.5', 'libelf^foo%gcc@4.5')
check_constrain_not_changed(
'libelf^foo+debug', 'libelf^foo+debug')
check_constrain_not_changed(
'libelf^foo~debug', 'libelf^foo~debug')
check_constrain_not_changed(
'libelf^foo cppflags="-O3"', 'libelf^foo cppflags="-O3"')
platform = spack.architecture.platform()
default_target = platform.target('default_target').name
check_constrain_not_changed(
'libelf^foo target=' + default_target,
'libelf^foo target=' + default_target)
def test_exceptional_paths_for_constructor(self):
with pytest.raises(TypeError):
Spec((1, 2))
with pytest.raises(ValueError):
Spec('')
with pytest.raises(ValueError):
Spec('libelf foo')
def test_spec_formatting(self):
spec = Spec("multivalue-variant cflags=-O2")
spec.concretize()
# Since the default is the full spec see if the string rep of
# spec is the same as the output of spec.format()
# ignoring whitespace (though should we?) and ignoring dependencies
spec_string = str(spec)
idx = spec_string.index(' ^')
assert spec_string[:idx] == spec.format().strip()
# Testing named strings ie {string} and whether we get
# the correct component
# Mixed case intentional to test both
package_segments = [("{NAME}", "name"),
("{VERSION}", "versions"),
("{compiler}", "compiler"),
("{compiler_flags}", "compiler_flags"),
("{variants}", "variants"),
("{architecture}", "architecture")]
sigil_package_segments = [("{@VERSIONS}", '@' + str(spec.version)),
("{%compiler}", '%' + str(spec.compiler)),
("{arch=architecture}",
'arch=' + str(spec.architecture))]
compiler_segments = [("{compiler.name}", "name"),
("{compiler.version}", "versions")]
sigil_compiler_segments = [("{%compiler.name}",
'%' + spec.compiler.name),
("{@compiler.version}",
'@' + str(spec.compiler.version))]
architecture_segments = [("{architecture.platform}", "platform"),
("{architecture.os}", "os"),
("{architecture.target}", "target")]
other_segments = [('{spack_root}', spack.paths.spack_root),
('{spack_install}', spack.store.layout.root),
('{hash:7}', spec.dag_hash(7)),
('{/hash}', '/' + spec.dag_hash())]
for named_str, prop in package_segments:
expected = getattr(spec, prop, "")
actual = spec.format(named_str)
assert str(expected).strip() == actual
for named_str, expected in sigil_package_segments:
actual = spec.format(named_str)
assert expected == actual
compiler = spec.compiler
for named_str, prop in compiler_segments:
expected = getattr(compiler, prop, "")
actual = spec.format(named_str)
assert str(expected) == actual
for named_str, expected in sigil_compiler_segments:
actual = spec.format(named_str)
assert expected == actual
arch = spec.architecture
for named_str, prop in architecture_segments:
expected = getattr(arch, prop, "")
actual = spec.format(named_str)
assert str(expected) == actual
for named_str, expected in other_segments:
actual = spec.format(named_str)
assert expected == actual
def test_spec_formatting_escapes(self):
spec = Spec('multivalue-variant cflags=-O2')
spec.concretize()
sigil_mismatches = [
'{@name}',
'{@version.concrete}',
'{%compiler.version}',
'{/hashd}',
'{arch=architecture.os}'
]
for fmt_str in sigil_mismatches:
with pytest.raises(SpecFormatSigilError):
spec.format(fmt_str)
bad_formats = [
r'{}',
r'name}',
r'\{name}',
r'{name',
r'{name\}',
r'{_concrete}',
r'{dag_hash}',
r'{foo}',
r'{+variants.debug}'
]
for fmt_str in bad_formats:
with pytest.raises(SpecFormatStringError):
spec.format(fmt_str)
def test_spec_deprecated_formatting(self):
spec = Spec("libelf cflags=-O2")
spec.concretize()
# Since the default is the full spec see if the string rep of
# spec is the same as the output of spec.format()
# ignoring whitespace (though should we?)
assert str(spec) == spec.format('$_$@$%@+$+$=').strip()
# Testing named strings ie {string} and whether we get
# the correct component
# Mixed case intentional for testing both
package_segments = [("${PACKAGE}", "name"),
("${VERSION}", "versions"),
("${compiler}", "compiler"),
("${compilerflags}", "compiler_flags"),
("${options}", "variants"),
("${architecture}", "architecture")]
compiler_segments = [("${compilername}", "name"),
("${compilerver}", "versions")]
architecture_segments = [("${PLATFORM}", "platform"),
("${OS}", "os"),
("${TARGET}", "target")]
for named_str, prop in package_segments:
expected = getattr(spec, prop, "")
actual = spec.format(named_str)
assert str(expected) == actual
compiler = spec.compiler
for named_str, prop in compiler_segments:
expected = getattr(compiler, prop, "")
actual = spec.format(named_str)
assert str(expected) == actual
arch = spec.architecture
for named_str, prop in architecture_segments:
expected = getattr(arch, prop, "")
actual = spec.format(named_str)
assert str(expected) == actual
@pytest.mark.regression('9908')
def test_spec_flags_maintain_order(self):
# Spack was assembling flags in a manner that could result in
# different orderings for repeated concretizations of the same
# spec and config
spec_str = 'libelf %gcc@4.7.2 os=redhat6'
for _ in range(25):
s = Spec(spec_str).concretized()
assert all(
s.compiler_flags[x] == ['-O0', '-g']
for x in ('cflags', 'cxxflags', 'fflags')
)
def test_combination_of_wildcard_or_none(self):
# Test that using 'none' and another value raises
with pytest.raises(spack.variant.InvalidVariantValueCombinationError):
Spec('multivalue-variant foo=none,bar')
# Test that using wildcard and another value raises
with pytest.raises(spack.variant.InvalidVariantValueCombinationError):
Spec('multivalue-variant foo=*,bar')
@pytest.mark.skipif(
sys.version_info[0] == 2, reason='__wrapped__ requires python 3'
)
def test_errors_in_variant_directive(self):
variant = spack.directives.variant.__wrapped__
class Pkg(object):
name = 'PKG'
# We can't use names that are reserved by Spack
fn = variant('patches')
with pytest.raises(spack.directives.DirectiveError) as exc_info:
fn(Pkg())
assert "The name 'patches' is reserved" in str(exc_info.value)
# We can't have conflicting definitions for arguments
fn = variant(
'foo', values=spack.variant.any_combination_of('fee', 'foom'),
default='bar'
)
with pytest.raises(spack.directives.DirectiveError) as exc_info:
fn(Pkg())
assert " it is handled by an attribute of the 'values' " \
"argument" in str(exc_info.value)
# We can't leave None as a default value
fn = variant('foo', default=None)
with pytest.raises(spack.directives.DirectiveError) as exc_info:
fn(Pkg())
assert "either a default was not explicitly set, or 'None' was used"\
in str(exc_info.value)
# We can't use an empty string as a default value
fn = variant('foo', default='')
with pytest.raises(spack.directives.DirectiveError) as exc_info:
fn(Pkg())
assert "the default cannot be an empty string" in str(exc_info.value)
def test_abstract_spec_prefix_error(self):
spec = Spec('libelf')
with pytest.raises(SpecError):
spec.prefix
def test_forwarding_of_architecture_attributes(self):
spec = Spec('libelf target=x86_64').concretized()
# Check that we can still access each member through
# the architecture attribute
assert 'test' in spec.architecture
assert 'debian' in spec.architecture
assert 'x86_64' in spec.architecture
# Check that we forward the platform and os attribute correctly
assert spec.platform == 'test'
assert spec.os == 'debian6'
# Check that the target is also forwarded correctly and supports
# all the operators we expect
assert spec.target == 'x86_64'
assert spec.target.family == 'x86_64'
assert 'avx512' not in spec.target
assert spec.target < 'broadwell'
@pytest.mark.parametrize('transitive', [True, False])
def test_splice(self, transitive):
# Tests the new splice function in Spec using a somewhat simple case
# with a variant with a conditional dependency.
# TODO: Test being able to splice in different provider for a virtual.
# Example: mvapich for mpich.
spec = Spec('splice-t')
dep = Spec('splice-h+foo')
spec.concretize()
dep.concretize()
# Sanity checking that these are not the same thing.
assert dep.dag_hash() != spec['splice-h'].dag_hash()
assert dep.build_hash() != spec['splice-h'].build_hash()
# Do the splice.
out = spec.splice(dep, transitive)
# Returned spec should still be concrete.
assert out.concrete
# Traverse the spec and assert that all dependencies are accounted for.
for node in spec.traverse():
assert node.name in out
# If the splice worked, then the full hash of the spliced dep should
# now match the full hash of the build spec of the dependency from the
# returned spec.
out_h_build = out['splice-h'].build_spec
assert out_h_build.full_hash() == dep.full_hash()
# Transitivity should determine whether the transitive dependency was
# changed.
expected_z = dep['splice-z'] if transitive else spec['splice-z']
assert out['splice-z'].full_hash() == expected_z.full_hash()
# Sanity check build spec of out should be the original spec.
assert (out['splice-t'].build_spec.full_hash() ==
spec['splice-t'].full_hash())
# Finally, the spec should know it's been spliced:
assert out.spliced
@pytest.mark.parametrize('transitive', [True, False])
def test_splice_with_cached_hashes(self, transitive):
spec = Spec('splice-t')
dep = Spec('splice-h+foo')
spec.concretize()
dep.concretize()
# monkeypatch hashes so we can test that they are cached
spec._full_hash = 'aaaaaa'
spec._build_hash = 'aaaaaa'
dep._full_hash = 'bbbbbb'
dep._build_hash = 'bbbbbb'
spec['splice-h']._full_hash = 'cccccc'
spec['splice-h']._build_hash = 'cccccc'
spec['splice-z']._full_hash = 'dddddd'
spec['splice-z']._build_hash = 'dddddd'
dep['splice-z']._full_hash = 'eeeeee'
dep['splice-z']._build_hash = 'eeeeee'
out = spec.splice(dep, transitive=transitive)
out_z_expected = (dep if transitive else spec)['splice-z']
assert out.full_hash() != spec.full_hash()
assert (out['splice-h'].full_hash() == dep.full_hash()) == transitive
assert out['splice-z'].full_hash() == out_z_expected.full_hash()
assert out.build_hash() != spec.build_hash()
assert (out['splice-h'].build_hash() == dep.build_hash()) == transitive
assert out['splice-z'].build_hash() == out_z_expected.build_hash()
@pytest.mark.parametrize('transitive', [True, False])
def test_splice_input_unchanged(self, transitive):
spec = Spec('splice-t').concretized()
dep = Spec('splice-h+foo').concretized()
orig_spec_hash = spec.full_hash()
orig_dep_hash = dep.full_hash()
spec.splice(dep, transitive)
# Post-splice, dag hash should still be different; no changes should be
# made to these specs.
assert spec.full_hash() == orig_spec_hash
assert dep.full_hash() == orig_dep_hash
@pytest.mark.parametrize('transitive', [True, False])
def test_splice_subsequent(self, transitive):
spec = Spec('splice-t')
dep = Spec('splice-h+foo')
spec.concretize()
dep.concretize()
out = spec.splice(dep, transitive)
# Now we attempt a second splice.
dep = Spec('splice-z+bar')
dep.concretize()
# Transitivity shouldn't matter since Splice Z has no dependencies.
out2 = out.splice(dep, transitive)
assert out2.concrete
assert out2['splice-z'].build_hash() != spec['splice-z'].build_hash()
assert out2['splice-z'].build_hash() != out['splice-z'].build_hash()
assert out2['splice-z'].full_hash() != spec['splice-z'].full_hash()
assert out2['splice-z'].full_hash() != out['splice-z'].full_hash()
assert (out2['splice-t'].build_spec.full_hash() ==
spec['splice-t'].full_hash())
assert out2.spliced
@pytest.mark.parametrize('spec,constraint,expected_result', [
('libelf target=haswell', 'target=broadwell', False),
('libelf target=haswell', 'target=haswell', True),
('libelf target=haswell', 'target=x86_64:', True),
('libelf target=haswell', 'target=:haswell', True),
('libelf target=haswell', 'target=icelake,:nocona', False),
('libelf target=haswell', 'target=haswell,:nocona', True),
# Check that a single target is not treated as the start
# or the end of an open range
('libelf target=haswell', 'target=x86_64', False),
('libelf target=x86_64', 'target=haswell', False),
])
@pytest.mark.regression('13111')
def test_target_constraints(self, spec, constraint, expected_result):
s = Spec(spec)
assert s.satisfies(constraint) is expected_result
@pytest.mark.regression('13124')
def test_error_message_unknown_variant(self):
s = Spec('mpileaks +unknown')
with pytest.raises(UnknownVariantError, match=r'package has no such'):
s.concretize()
@pytest.mark.regression('18527')
def test_satisfies_dependencies_ordered(self):
d = Spec('zmpi ^fake')
s = Spec('mpileaks')
s._add_dependency(d, ())
assert s.satisfies('mpileaks ^zmpi ^fake', strict=True)
@pytest.mark.regression('3887')
@pytest.mark.parametrize('spec_str', [
'git', 'hdf5', 'py-flake8'
])
def test_is_extension_after_round_trip_to_dict(config, spec_str):
# x is constructed directly from string, y from a
# round-trip to dict representation
x = Spec(spec_str)
x.concretize()
y = Spec.from_dict(x.to_dict())
# Using 'y' since the round-trip make us lose build dependencies
for d in y.traverse():
assert x[d.name].package.is_extension == y[d.name].package.is_extension
| 38.13181 | 79 | 0.603102 |
acf01178557985a7055cc5bbbecee409242ec09c | 3,449 | py | Python | readthedocs/rtd_tests/mocks/mock_api.py | dbdaryl/readthedocs.org | 09a14c7ffaf571fd136037c0f343926e275f6ce7 | [
"MIT"
] | 1 | 2019-04-26T17:18:19.000Z | 2019-04-26T17:18:19.000Z | readthedocs/rtd_tests/mocks/mock_api.py | dbdaryl/readthedocs.org | 09a14c7ffaf571fd136037c0f343926e275f6ce7 | [
"MIT"
] | null | null | null | readthedocs/rtd_tests/mocks/mock_api.py | dbdaryl/readthedocs.org | 09a14c7ffaf571fd136037c0f343926e275f6ce7 | [
"MIT"
] | null | null | null | """Mock versions of many API-related classes."""
from __future__ import absolute_import
from builtins import object
from contextlib import contextmanager
import json
import mock
# Mock tastypi API.
class ProjectData(object):
def get(self):
return dict()
def put(self, x=None):
return x
def mock_version(repo):
"""Construct and return a class implementing the Version interface."""
class MockVersion(object):
def __init__(self, x=None):
pass
def put(self, x=None):
return x
def get(self, **kwargs):
"""Returns mock data to emulate real Version objects."""
# SCIENTIST DOG
version = json.loads("""
{
"active": false,
"built": false,
"id": "12095",
"identifier": "remotes/origin/zip_importing",
"resource_uri": "/api/v1/version/12095/",
"slug": "zip_importing",
"uploaded": false,
"verbose_name": "zip_importing"
}""")
project = json.loads("""
{
"absolute_url": "/projects/docs/",
"analytics_code": "",
"copyright": "",
"default_branch": "",
"default_version": "latest",
"description": "Make docs.readthedocs.org work :D",
"django_packages_url": "",
"documentation_type": "sphinx",
"id": "2599",
"modified_date": "2012-03-12T19:59:09.130773",
"name": "docs",
"project_url": "",
"pub_date": "2012-02-19T18:10:56.582780",
"repo": "git://github.com/rtfd/readthedocs.org",
"repo_type": "git",
"requirements_file": "",
"resource_uri": "/api/v1/project/2599/",
"slug": "docs",
"suffix": ".rst",
"theme": "default",
"install_project": false,
"users": [
"/api/v1/user/1/"
],
"version": ""
}""")
version['project'] = project
project['repo'] = repo
if 'slug' in kwargs:
return {'objects': [version], 'project': project}
return version
return MockVersion
class MockApi(object):
def __init__(self, repo):
self.version = mock_version(repo)
def project(self, _):
return ProjectData()
def build(self, _):
return mock.Mock(**{'get.return_value': {'id': 123, 'state': 'triggered'}})
def command(self, _):
return mock.Mock(**{'get.return_value': {}})
@contextmanager
def mock_api(repo):
api_mock = MockApi(repo)
with mock.patch('readthedocs.restapi.client.api', api_mock), \
mock.patch('readthedocs.api.client.api', api_mock), \
mock.patch('readthedocs.projects.tasks.api_v2', api_mock), \
mock.patch('readthedocs.projects.tasks.api_v1', api_mock), \
mock.patch('readthedocs.doc_builder.environments.api_v1', api_mock), \
mock.patch('readthedocs.doc_builder.environments.api_v2', api_mock):
yield api_mock
| 33.485437 | 83 | 0.493766 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.